Skip to content

Commit a289db9

Browse files
committed
[FEATURE] Implement Tracking in .NET open-feature#309
Signed-off-by: christian.lutnik <[email protected]>
1 parent c444e52 commit a289db9

8 files changed

+505
-1
lines changed

README.md

+14-1
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,19 @@ await Api.Instance.SetProviderAsync(myClient.GetMetadata().Name, provider);
212212
myClient.AddHandler(ProviderEventTypes.ProviderReady, callback);
213213
```
214214

215+
### Tracking
216+
217+
The tracking API allows you to use OpenFeature abstractions and objects to associate user actions with feature flag evaluations.
218+
This is essential for robust experimentation powered by feature flags.
219+
For example, a flag enhancing the appearance of a UI component might drive user engagement to a new feature; to test this hypothesis, telemetry collected by a hook(#hooks) or provider(#providers) can be associated with telemetry reported in the client's `track` function.
220+
221+
```csharp
222+
var client = Api.Instance.GetClient();
223+
client.Track("visited-promo-page", trackingEventDetails: new TrackingEventDetailsBuilder().SetValue(99.77).Set("currency", "USD").Build());
224+
```
225+
226+
Note that some providers may not support tracking; check the documentation for your provider for more information.
227+
215228
### Shutdown
216229

217230
The OpenFeature API provides a close function to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.
@@ -320,7 +333,7 @@ builder.Services.AddOpenFeature(featureBuilder => {
320333
featureBuilder
321334
.AddHostedFeatureLifecycle() // From Hosting package
322335
.AddContext((contextBuilder, serviceProvider) => { /* Custom context configuration */ })
323-
.AddInMemoryProvider();
336+
.AddInMemoryProvider();
324337
});
325338
```
326339
**Domain-Scoped Provider Configuration:**

src/OpenFeature/FeatureProvider.cs

+12
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using OpenFeature.Model;
88

99
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // required to allow NSubstitute mocking of internal methods
10+
1011
namespace OpenFeature
1112
{
1213
/// <summary>
@@ -140,5 +141,16 @@ public virtual Task ShutdownAsync(CancellationToken cancellationToken = default)
140141
/// </summary>
141142
/// <returns>The event channel of the provider</returns>
142143
public virtual Channel<object> GetEventChannel() => this.EventChannel;
144+
145+
/// <summary>
146+
/// Use this method to track user interactions and the application state. The implementation of this method is optional.
147+
/// </summary>
148+
/// <param name="trackingEventName">The name associated with this tracking event</param>
149+
/// <param name="evaluationContext">The evaluation context used in the evaluation of the flag (optional)</param>
150+
/// <param name="trackingEventDetails">Data pertinent to the tracking event (Optional)</param>
151+
public virtual void Track(string trackingEventName, EvaluationContext? evaluationContext = default, TrackingEventDetails? trackingEventDetails = default)
152+
{
153+
// Intentionally left blank.
154+
}
143155
}
144156
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Collections.Immutable;
4+
5+
namespace OpenFeature.Model;
6+
7+
/// <summary>
8+
/// The `tracking event details` structure defines optional data pertinent to a particular `tracking event`.
9+
/// </summary>
10+
/// <seealso href="https://github.com/open-feature/spec/blob/main/specification/sections/06-tracking.md#62-tracking-event-details"/>
11+
public sealed class TrackingEventDetails
12+
{
13+
/// <summary>
14+
/// The index for the "targeting key" property when the EvaluationContext is serialized or expressed as a dictionary.
15+
/// </summary>
16+
internal const string TargetingKeyIndex = "targetingKey";
17+
18+
/// <summary>
19+
///A predefined value field for the tracking details.
20+
/// </summary>
21+
public readonly double? Value;
22+
23+
private readonly Structure _structure;
24+
25+
/// <summary>
26+
/// Internal constructor used by the builder.
27+
/// </summary>
28+
/// <param name="content"></param>
29+
/// <param name="value"></param>
30+
internal TrackingEventDetails(Structure content, double? value)
31+
{
32+
this.Value = value;
33+
this._structure = content;
34+
}
35+
36+
37+
/// <summary>
38+
/// Private constructor for making an empty <see cref="TrackingEventDetails"/>.
39+
/// </summary>
40+
private TrackingEventDetails()
41+
{
42+
this._structure = Structure.Empty;
43+
this.Value = null;
44+
}
45+
46+
/// <summary>
47+
/// Empty tracking event details.
48+
/// </summary>
49+
public static TrackingEventDetails Empty { get; } = new();
50+
51+
52+
/// <summary>
53+
/// Gets the Value at the specified key
54+
/// </summary>
55+
/// <param name="key">The key of the value to be retrieved</param>
56+
/// <returns>The <see cref="Model.Value"/> associated with the key</returns>
57+
/// <exception cref="KeyNotFoundException">
58+
/// Thrown when the context does not contain the specified key
59+
/// </exception>
60+
/// <exception cref="ArgumentNullException">
61+
/// Thrown when the key is <see langword="null" />
62+
/// </exception>
63+
public Value GetValue(string key) => this._structure.GetValue(key);
64+
65+
/// <summary>
66+
/// Bool indicating if the specified key exists in the evaluation context
67+
/// </summary>
68+
/// <param name="key">The key of the value to be checked</param>
69+
/// <returns><see cref="bool" />indicating the presence of the key</returns>
70+
/// <exception cref="ArgumentNullException">
71+
/// Thrown when the key is <see langword="null" />
72+
/// </exception>
73+
public bool ContainsKey(string key) => this._structure.ContainsKey(key);
74+
75+
/// <summary>
76+
/// Gets the value associated with the specified key
77+
/// </summary>
78+
/// <param name="value">The <see cref="Model.Value"/> or <see langword="null" /> if the key was not present</param>
79+
/// <param name="key">The key of the value to be retrieved</param>
80+
/// <returns><see cref="bool" />indicating the presence of the key</returns>
81+
/// <exception cref="ArgumentNullException">
82+
/// Thrown when the key is <see langword="null" />
83+
/// </exception>
84+
public bool TryGetValue(string key, out Value? value) => this._structure.TryGetValue(key, out value);
85+
86+
/// <summary>
87+
/// Gets all values as a Dictionary
88+
/// </summary>
89+
/// <returns>New <see cref="IDictionary{TKey,TValue}"/> representation of this Structure</returns>
90+
public IImmutableDictionary<string, Value> AsDictionary()
91+
{
92+
return this._structure.AsDictionary();
93+
}
94+
95+
/// <summary>
96+
/// Return a count of all values
97+
/// </summary>
98+
public int Count => this._structure.Count;
99+
100+
/// <summary>
101+
/// Returns the targeting key for the context.
102+
/// </summary>
103+
public string? TargetingKey
104+
{
105+
get
106+
{
107+
this._structure.TryGetValue(TargetingKeyIndex, out Value? targetingKey);
108+
return targetingKey?.AsString;
109+
}
110+
}
111+
112+
/// <summary>
113+
/// Return an enumerator for all values
114+
/// </summary>
115+
/// <returns>An enumerator for all values</returns>
116+
public IEnumerator<KeyValuePair<string, Value>> GetEnumerator()
117+
{
118+
return this._structure.GetEnumerator();
119+
}
120+
121+
/// <summary>
122+
/// Get a builder which can build an <see cref="EvaluationContext"/>.
123+
/// </summary>
124+
/// <returns>The builder</returns>
125+
public static TrackingEventDetailsBuilder Builder()
126+
{
127+
return new TrackingEventDetailsBuilder();
128+
}
129+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
using System;
2+
3+
namespace OpenFeature.Model
4+
{
5+
/// <summary>
6+
/// A builder which allows the specification of attributes for an <see cref="TrackingEventDetails"/>.
7+
/// <para>
8+
/// A <see cref="TrackingEventDetailsBuilder"/> object is intended for use by a single thread and should not be used
9+
/// from multiple threads. Once an <see cref="TrackingEventDetails"/> has been created it is immutable and safe for use
10+
/// from multiple threads.
11+
/// </para>
12+
/// </summary>
13+
public sealed class TrackingEventDetailsBuilder
14+
{
15+
private readonly StructureBuilder _attributes = Structure.Builder();
16+
private double? _value;
17+
18+
/// <summary>
19+
/// Internal to only allow direct creation by <see cref="TrackingEventDetails.Builder()"/>.
20+
/// </summary>
21+
internal TrackingEventDetailsBuilder() { }
22+
23+
/// <summary>
24+
/// Set the predefined value field for the tracking details.
25+
/// </summary>
26+
/// <param name="value"></param>
27+
/// <returns></returns>
28+
public TrackingEventDetailsBuilder SetValue(double? value)
29+
{
30+
this._value = value;
31+
return this;
32+
}
33+
34+
/// <summary>
35+
/// Set the targeting key for the tracking details.
36+
/// </summary>
37+
/// <param name="targetingKey">The targeting key</param>
38+
/// <returns>This builder</returns>
39+
public TrackingEventDetailsBuilder SetTargetingKey(string targetingKey)
40+
{
41+
this._attributes.Set(TrackingEventDetails.TargetingKeyIndex, targetingKey);
42+
return this;
43+
}
44+
45+
/// <summary>
46+
/// Set the key to the given <see cref="Value"/>.
47+
/// </summary>
48+
/// <param name="key">The key for the value</param>
49+
/// <param name="value">The value to set</param>
50+
/// <returns>This builder</returns>
51+
public TrackingEventDetailsBuilder Set(string key, Value value)
52+
{
53+
this._attributes.Set(key, value);
54+
return this;
55+
}
56+
57+
/// <summary>
58+
/// Set the key to the given string.
59+
/// </summary>
60+
/// <param name="key">The key for the value</param>
61+
/// <param name="value">The value to set</param>
62+
/// <returns>This builder</returns>
63+
public TrackingEventDetailsBuilder Set(string key, string value)
64+
{
65+
this._attributes.Set(key, value);
66+
return this;
67+
}
68+
69+
/// <summary>
70+
/// Set the key to the given int.
71+
/// </summary>
72+
/// <param name="key">The key for the value</param>
73+
/// <param name="value">The value to set</param>
74+
/// <returns>This builder</returns>
75+
public TrackingEventDetailsBuilder Set(string key, int value)
76+
{
77+
this._attributes.Set(key, value);
78+
return this;
79+
}
80+
81+
/// <summary>
82+
/// Set the key to the given double.
83+
/// </summary>
84+
/// <param name="key">The key for the value</param>
85+
/// <param name="value">The value to set</param>
86+
/// <returns>This builder</returns>
87+
public TrackingEventDetailsBuilder Set(string key, double value)
88+
{
89+
this._attributes.Set(key, value);
90+
return this;
91+
}
92+
93+
/// <summary>
94+
/// Set the key to the given long.
95+
/// </summary>
96+
/// <param name="key">The key for the value</param>
97+
/// <param name="value">The value to set</param>
98+
/// <returns>This builder</returns>
99+
public TrackingEventDetailsBuilder Set(string key, long value)
100+
{
101+
this._attributes.Set(key, value);
102+
return this;
103+
}
104+
105+
/// <summary>
106+
/// Set the key to the given bool.
107+
/// </summary>
108+
/// <param name="key">The key for the value</param>
109+
/// <param name="value">The value to set</param>
110+
/// <returns>This builder</returns>
111+
public TrackingEventDetailsBuilder Set(string key, bool value)
112+
{
113+
this._attributes.Set(key, value);
114+
return this;
115+
}
116+
117+
/// <summary>
118+
/// Set the key to the given <see cref="Structure"/>.
119+
/// </summary>
120+
/// <param name="key">The key for the value</param>
121+
/// <param name="value">The value to set</param>
122+
/// <returns>This builder</returns>
123+
public TrackingEventDetailsBuilder Set(string key, Structure value)
124+
{
125+
this._attributes.Set(key, value);
126+
return this;
127+
}
128+
129+
/// <summary>
130+
/// Set the key to the given DateTime.
131+
/// </summary>
132+
/// <param name="key">The key for the value</param>
133+
/// <param name="value">The value to set</param>
134+
/// <returns>This builder</returns>
135+
public TrackingEventDetailsBuilder Set(string key, DateTime value)
136+
{
137+
this._attributes.Set(key, value);
138+
return this;
139+
}
140+
141+
/// <summary>
142+
/// Incorporate existing tracking details into the builder.
143+
/// <para>
144+
/// Any existing keys in the builder will be replaced by keys in the tracking details.
145+
/// </para>
146+
/// </summary>
147+
/// <param name="trackingDetails">The tracking details to add merge</param>
148+
/// <returns>This builder</returns>
149+
public TrackingEventDetailsBuilder Merge(TrackingEventDetails trackingDetails)
150+
{
151+
foreach (var kvp in trackingDetails)
152+
{
153+
this.Set(kvp.Key, kvp.Value);
154+
}
155+
156+
return this;
157+
}
158+
159+
/// <summary>
160+
/// Build an immutable <see cref="TrackingEventDetails"/>.
161+
/// </summary>
162+
/// <returns>An immutable <see cref="TrackingEventDetails"/></returns>
163+
public TrackingEventDetails Build()
164+
{
165+
return new TrackingEventDetails(this._attributes.Build(), this._value);
166+
}
167+
}
168+
}

src/OpenFeature/OpenFeatureClient.cs

+25
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,31 @@ private async Task TriggerFinallyHooksAsync<T>(IReadOnlyList<Hook> hooks, HookCo
367367
}
368368
}
369369

370+
/// <summary>
371+
/// Use this method to track user interactions and the application state.
372+
/// </summary>
373+
/// <param name="trackingEventName">The name associated with this tracking event</param>
374+
/// <param name="evaluationContext">The evaluation context used in the evaluation of the flag (optional)</param>
375+
/// <param name="trackingEventDetails">Data pertinent to the tracking event (Optional)</param>
376+
/// <exception cref="ArgumentException">When trackingEventName is null or empty</exception>
377+
public void Track(string trackingEventName, EvaluationContext? evaluationContext = default, TrackingEventDetails? trackingEventDetails = default)
378+
{
379+
if (string.IsNullOrEmpty(trackingEventName))
380+
{
381+
throw new ArgumentException(nameof(trackingEventName) + " cannot be null or empty.");
382+
}
383+
384+
var globalContext = Api.Instance.GetContext();
385+
var clientContext = this.GetContext();
386+
387+
var evaluationContextBuilder = EvaluationContext.Builder()
388+
.Merge(globalContext)
389+
.Merge(clientContext);
390+
if (evaluationContext != null) evaluationContextBuilder.Merge(evaluationContext);
391+
392+
this._providerAccessor.Invoke().Track(trackingEventName, evaluationContextBuilder.Build(), trackingEventDetails);
393+
}
394+
370395
[LoggerMessage(100, LogLevel.Debug, "Hook {HookName} returned null, nothing to merge back into context")]
371396
partial void HookReturnedNull(string hookName);
372397

0 commit comments

Comments
 (0)