-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathProviderRepository.cs
292 lines (263 loc) · 11.1 KB
/
ProviderRepository.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using OpenFeature.Constant;
using OpenFeature.Model;
namespace OpenFeature
{
/// <summary>
/// This class manages the collection of providers, both default and named, contained by the API.
/// </summary>
internal sealed partial class ProviderRepository : IAsyncDisposable
{
private ILogger _logger = NullLogger<EventExecutor>.Instance;
private FeatureProvider _defaultProvider = new NoOpFeatureProvider();
private readonly ConcurrentDictionary<string, FeatureProvider> _featureProviders =
new ConcurrentDictionary<string, FeatureProvider>();
/// The reader/writer locks is not disposed because the singleton instance should never be disposed.
///
/// Mutations of the _defaultProvider or _featureProviders are done within this lock even though
/// _featureProvider is a concurrent collection. This is for a couple of reasons, the first is that
/// a provider should only be shutdown if it is not in use, and it could be in use as either a named or
/// default provider.
///
/// The second is that a concurrent collection doesn't provide any ordering, so we could check a provider
/// as it was being added or removed such as two concurrent calls to SetProvider replacing multiple instances
/// of that provider under different names.
private readonly ReaderWriterLockSlim _providersLock = new ReaderWriterLockSlim();
public async ValueTask DisposeAsync()
{
using (this._providersLock)
{
await this.ShutdownAsync().ConfigureAwait(false);
}
}
internal void SetLogger(ILogger logger) => this._logger = logger;
/// <summary>
/// Set the default provider
/// </summary>
/// <param name="featureProvider">the provider to set as the default, passing null has no effect</param>
/// <param name="context">the context to initialize the provider with</param>
/// <param name="afterInitSuccess">
/// called after the provider has initialized successfully, only called if the provider needed initialization
/// </param>
/// <param name="afterInitError">
/// called if an error happens during the initialization of the provider, only called if the provider needed
/// initialization
/// </param>
public async Task SetProviderAsync(
FeatureProvider? featureProvider,
EvaluationContext context,
Func<FeatureProvider, Task>? afterInitSuccess = null,
Func<FeatureProvider, Exception, Task>? afterInitError = null)
{
// Cannot unset the feature provider.
if (featureProvider == null)
{
return;
}
this._providersLock.EnterWriteLock();
// Default provider is swapped synchronously, initialization and shutdown may happen asynchronously.
try
{
// Setting the provider to the same provider should not have an effect.
if (ReferenceEquals(featureProvider, this._defaultProvider))
{
return;
}
var oldProvider = this._defaultProvider;
this._defaultProvider = featureProvider;
// We want to allow shutdown to happen concurrently with initialization, and the caller to not
// wait for it.
_ = this.ShutdownIfUnusedAsync(oldProvider);
}
finally
{
this._providersLock.ExitWriteLock();
}
await InitProviderAsync(this._defaultProvider, context, afterInitSuccess, afterInitError)
.ConfigureAwait(false);
}
private static async Task InitProviderAsync(
FeatureProvider? newProvider,
EvaluationContext context,
Func<FeatureProvider, Task>? afterInitialization,
Func<FeatureProvider, Exception, Task>? afterError)
{
if (newProvider == null)
{
return;
}
if (newProvider.Status == ProviderStatus.NotReady)
{
try
{
await newProvider.InitializeAsync(context).ConfigureAwait(false);
if (afterInitialization != null)
{
await afterInitialization.Invoke(newProvider).ConfigureAwait(false);
}
}
catch (Exception ex)
{
if (afterError != null)
{
await afterError.Invoke(newProvider, ex).ConfigureAwait(false);
}
}
}
}
/// <summary>
/// Set a named provider
/// </summary>
/// <param name="domain">an identifier which logically binds clients with providers</param>
/// <param name="featureProvider">the provider to set as the default, passing null has no effect</param>
/// <param name="context">the context to initialize the provider with</param>
/// <param name="afterInitSuccess">
/// called after the provider has initialized successfully, only called if the provider needed initialization
/// </param>
/// <param name="afterInitError">
/// called if an error happens during the initialization of the provider, only called if the provider needed
/// initialization
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to cancel any async side effects.</param>
public async Task SetProviderAsync(string? domain,
FeatureProvider? featureProvider,
EvaluationContext context,
Func<FeatureProvider, Task>? afterInitSuccess = null,
Func<FeatureProvider, Exception, Task>? afterInitError = null,
CancellationToken cancellationToken = default)
{
// Cannot set a provider for a null domain.
if (domain == null)
{
return;
}
this._providersLock.EnterWriteLock();
try
{
this._featureProviders.TryGetValue(domain, out var oldProvider);
if (featureProvider != null)
{
this._featureProviders.AddOrUpdate(domain, featureProvider,
(key, current) => featureProvider);
}
else
{
// If names of clients are programmatic, then setting the provider to null could result
// in unbounded growth of the collection.
this._featureProviders.TryRemove(domain, out _);
}
// We want to allow shutdown to happen concurrently with initialization, and the caller to not
// wait for it.
_ = this.ShutdownIfUnusedAsync(oldProvider);
}
finally
{
this._providersLock.ExitWriteLock();
}
await InitProviderAsync(featureProvider, context, afterInitSuccess, afterInitError).ConfigureAwait(false);
}
/// <remarks>
/// Shutdown the feature provider if it is unused. This must be called within a write lock of the _providersLock.
/// </remarks>
private async Task ShutdownIfUnusedAsync(
FeatureProvider? targetProvider)
{
if (ReferenceEquals(this._defaultProvider, targetProvider))
{
return;
}
if (targetProvider != null && this._featureProviders.Values.Contains(targetProvider))
{
return;
}
await this.SafeShutdownProviderAsync(targetProvider).ConfigureAwait(false);
}
/// <remarks>
/// <para>
/// Shut down the provider and capture any exceptions thrown.
/// </para>
/// <para>
/// The provider is set either to a name or default before the old provider it shut down, so
/// it would not be meaningful to emit an error.
/// </para>
/// </remarks>
private async Task SafeShutdownProviderAsync(FeatureProvider? targetProvider)
{
if (targetProvider == null)
{
return;
}
try
{
await targetProvider.ShutdownAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
this.ErrorShuttingDownProvider(targetProvider.GetMetadata()?.Name, ex);
}
}
public FeatureProvider GetProvider()
{
this._providersLock.EnterReadLock();
try
{
return this._defaultProvider;
}
finally
{
this._providersLock.ExitReadLock();
}
}
public FeatureProvider GetProvider(string? domain)
{
#if NET6_0_OR_GREATER
if (string.IsNullOrEmpty(domain))
{
return this.GetProvider();
}
#else
// This is a workaround for the issue in .NET Framework where string.IsNullOrEmpty is not nullable compatible.
if (domain == null || string.IsNullOrEmpty(domain))
{
return this.GetProvider();
}
#endif
return this._featureProviders.TryGetValue(domain, out var featureProvider)
? featureProvider
: this.GetProvider();
}
public async Task ShutdownAsync(Action<FeatureProvider, Exception>? afterError = null, CancellationToken cancellationToken = default)
{
var providers = new HashSet<FeatureProvider>();
this._providersLock.EnterWriteLock();
try
{
providers.Add(this._defaultProvider);
foreach (var featureProvidersValue in this._featureProviders.Values)
{
providers.Add(featureProvidersValue);
}
// Set a default provider so the Api is ready to be used again.
this._defaultProvider = new NoOpFeatureProvider();
this._featureProviders.Clear();
}
finally
{
this._providersLock.ExitWriteLock();
}
foreach (var targetProvider in providers)
{
// We don't need to take any actions after shutdown.
await this.SafeShutdownProviderAsync(targetProvider).ConfigureAwait(false);
}
}
[LoggerMessage(EventId = 105, Level = LogLevel.Error, Message = "Error shutting down provider: {TargetProviderName}`")]
partial void ErrorShuttingDownProvider(string? targetProviderName, Exception exception);
}
}