-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSplitClient.cs
More file actions
637 lines (517 loc) · 29.6 KB
/
Copy pathSplitClient.cs
File metadata and controls
637 lines (517 loc) · 29.6 KB
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
using Splitio.Constants;
using Splitio.Domain;
using Splitio.Enums.Extensions;
using Splitio.Services.Cache.Filter;
using Splitio.Services.Cache.Interfaces;
using Splitio.Services.Client.Interfaces;
using Splitio.Services.Common;
using Splitio.Services.Evaluator;
using Splitio.Services.Events.Interfaces;
using Splitio.Services.Filters;
using Splitio.Services.Impressions.Classes;
using Splitio.Services.Impressions.Interfaces;
using Splitio.Services.InputValidation.Classes;
using Splitio.Services.InputValidation.Interfaces;
using Splitio.Services.Logger;
using Splitio.Services.Parsing.Interfaces;
using Splitio.Services.Shared.Classes;
using Splitio.Services.Shared.Interfaces;
using Splitio.Services.Tasks;
using Splitio.Telemetry.Storages;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace Splitio.Services.Client.Classes
{
public abstract class SplitClient : ISplitClient
{
protected readonly ISplitLogger _log = WrapperAdapter.Instance().GetLogger(typeof(SplitClient));
protected readonly IKeyValidator _keyValidator;
protected readonly ISplitNameValidator _splitNameValidator;
protected readonly IEventTypeValidator _eventTypeValidator;
protected readonly IPropertiesValidator _propertiesValidator;
protected readonly IWrapperAdapter _wrapperAdapter;
protected readonly IConfigService _configService;
protected readonly IFlagSetsValidator _flagSetsValidator;
protected readonly string ApiKey;
protected ISplitManager _manager;
protected IEventsLog _eventsLog;
protected ITrafficTypeValidator _trafficTypeValidator;
protected IBlockUntilReadyService _blockUntilReadyService;
protected IFactoryInstantiationsService _factoryInstantiationsService;
protected IParser<Split, ParsedSplit> _splitParser;
protected IParser<RuleBasedSegmentDto, RuleBasedSegment> _rbsParser;
protected IEvaluator _evaluator;
protected ITelemetryEvaluationProducer _telemetryEvaluationProducer;
protected ITelemetryInitProducer _telemetryInitProducer;
protected ITasksManager _tasksManager;
protected IStatusManager _statusManager;
protected ISyncManager _syncManager;
protected IImpressionsLog _impressionsLog;
protected IUniqueKeysTracker _uniqueKeysTracker;
protected IImpressionListener _customerImpressionListener;
protected IImpressionsManager _impressionsManager;
protected IImpressionsSenderAdapter _impressionsSenderAdapter;
protected IImpressionsCounter _impressionsCounter;
protected IImpressionsObserver _impressionsObserver;
protected IClientExtensionService _clientExtensionService;
protected IFlagSetsFilter _flagSetsFilter;
protected IFallbackTreatmentCalculator _fallbackTreatmentCalculator;
protected IEventsManager<SdkEvent, SdkInternalEvent, EventMetadata> _eventsManager;
protected IInternalEventsTask _internalEventsTask;
private EventHandler<EventMetadata> SdkReadyEvent;
public event EventHandler<EventMetadata> SdkReady
{
add
{
SdkReadyEvent = (EventHandler<EventMetadata>)Delegate.Combine(SdkReadyEvent, value);
if (_eventsManager.EventAlreadyTriggered(SdkEvent.SdkReady))
{
SdkReadyEvent.Invoke(this, null);
}
}
remove
{
SdkReadyEvent = (EventHandler<EventMetadata>)Delegate.Remove(SdkReadyEvent, value);
}
}
public event EventHandler<EventMetadata> SdkUpdate;
protected SplitClient(string apikey)
{
ApiKey = apikey;
_wrapperAdapter = WrapperAdapter.Instance();
_keyValidator = new KeyValidator();
_splitNameValidator = new SplitNameValidator();
_eventTypeValidator = new EventTypeValidator();
_propertiesValidator = new PropertiesValidator();
_factoryInstantiationsService = FactoryInstantiationsService.Instance();
_flagSetsValidator = new FlagSetsValidator();
_configService = new ConfigService(_wrapperAdapter, _flagSetsValidator, new SdkMetadataValidator());
}
#region GetTreatment
public async Task<string> GetTreatmentAsync(Key key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var evaluationResult = await GetTreatmentsAsync(Enums.API.GetTreatmentAsync, key, new List<string> { feature }, attributes, evaluationOptions);
return TreatmentWithConfig(evaluationResult).Treatment;
}
public async Task<string> GetTreatmentAsync(string key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentAsync(new Key(key, null), feature, attributes, evaluationOptions);
}
public virtual string GetTreatment(Key key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var evaluationResult = GetTreatmentsSync(Enums.API.GetTreatment, key, new List<string> { feature }, attributes, evaluationOptions);
return TreatmentWithConfig(evaluationResult).Treatment;
}
public virtual string GetTreatment(string key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatment(new Key(key, null), feature, attributes, evaluationOptions);
}
#endregion
#region GetTreatments
public async Task<Dictionary<string, string>> GetTreatmentsAsync(Key key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsAsync(Enums.API.GetTreatmentsAsync, key, features, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
public async Task<Dictionary<string, string>> GetTreatmentsAsync(string key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsAsync(new Key(key, null), features, attributes, evaluationOptions);
}
public Dictionary<string, string> GetTreatments(Key key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsSync(Enums.API.GetTreatments, key, features, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
public Dictionary<string, string> GetTreatments(string key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatments(new Key(key, null), features, attributes, evaluationOptions);
}
#endregion
#region GetTreatmentWithConfig
public async Task<SplitResult> GetTreatmentWithConfigAsync(Key key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var evaluationResult = await GetTreatmentsAsync(Enums.API.GetTreatmentWithConfigAsync, key, new List<string> { feature }, attributes, evaluationOptions);
return TreatmentWithConfig(evaluationResult);
}
public async Task<SplitResult> GetTreatmentWithConfigAsync(string key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentWithConfigAsync(new Key(key, null), feature, attributes, evaluationOptions);
}
public SplitResult GetTreatmentWithConfig(Key key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var evaluationResult = GetTreatmentsSync(Enums.API.GetTreatmentWithConfig, key, new List<string> { feature }, attributes, evaluationOptions);
return TreatmentWithConfig(evaluationResult);
}
public SplitResult GetTreatmentWithConfig(string key, string feature, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentWithConfig(new Key(key, null), feature, attributes, evaluationOptions);
}
#endregion
#region GetTreatmentsWithConfig
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigAsync(Key key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsAsync(Enums.API.GetTreatmentsWithConfigAsync, key, features, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigAsync(string key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsWithConfigAsync(new Key(key, null), features, attributes, evaluationOptions);
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfig(Key key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsSync(Enums.API.GetTreatmentsWithConfig, key, features, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfig(string key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentsWithConfig(new Key(key, null), features, attributes, evaluationOptions);
}
#endregion
#region GetTreatmentsWithConfigByFlagSets
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigByFlagSetsAsync(string key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsWithConfigByFlagSetsAsync(new Key(key, null), flagSets, attributes, evaluationOptions);
}
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigByFlagSetsAsync(Key key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsByFlagSetsAsync(Enums.API.GetTreatmentsWithConfigByFlagSetsAsync, key, flagSets, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfigByFlagSets(string key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentsWithConfigByFlagSets(new Key(key, null), flagSets, attributes, evaluationOptions);
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfigByFlagSets(Key key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsByFlagSets(Enums.API.GetTreatmentsWithConfigByFlagSets, key, flagSets, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
#endregion
#region GetTreatmentsByFlagSets
public async Task<Dictionary<string, string>> GetTreatmentsByFlagSetsAsync(string key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsByFlagSetsAsync(new Key(key, null), flagSets, attributes, evaluationOptions);
}
public async Task<Dictionary<string, string>> GetTreatmentsByFlagSetsAsync(Key key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsByFlagSetsAsync(Enums.API.GetTreatmentsByFlagSetsAsync, key, flagSets, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
public Dictionary<string, string> GetTreatmentsByFlagSets(string key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentsByFlagSets(new Key(key, null), flagSets, attributes, evaluationOptions);
}
public Dictionary<string, string> GetTreatmentsByFlagSets(Key key, List<string> flagSets, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsByFlagSets(Enums.API.GetTreatmentsByFlagSets, key, flagSets, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
#endregion
#region GetTreatmentsWithConfigByFlagSet
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigByFlagSetAsync(string key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsWithConfigByFlagSetAsync(new Key(key, null), flagSet, attributes, evaluationOptions);
}
public async Task<Dictionary<string, SplitResult>> GetTreatmentsWithConfigByFlagSetAsync(Key key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsByFlagSetsAsync(Enums.API.GetTreatmentsWithConfigByFlagSetAsync, key, new List<string> { flagSet }, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfigByFlagSet(string key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentsWithConfigByFlagSet(new Key(key, null), flagSet, attributes, evaluationOptions);
}
public Dictionary<string, SplitResult> GetTreatmentsWithConfigByFlagSet(Key key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsByFlagSets(Enums.API.GetTreatmentsWithConfigByFlagSet, key, new List<string> { flagSet }, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => new SplitResult(r.Treatment, r.Config));
}
#endregion
#region GetTreatmentsByFlagSet
public async Task<Dictionary<string, string>> GetTreatmentsByFlagSetAsync(string key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return await GetTreatmentsByFlagSetAsync(new Key(key, null), flagSet, attributes, evaluationOptions);
}
public async Task<Dictionary<string, string>> GetTreatmentsByFlagSetAsync(Key key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = await GetTreatmentsByFlagSetsAsync(Enums.API.GetTreatmentsByFlagSetAsync, key, new List<string> { flagSet }, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
public Dictionary<string, string> GetTreatmentsByFlagSet(string key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
return GetTreatmentsByFlagSet(new Key(key, null), flagSet, attributes, evaluationOptions);
}
public Dictionary<string, string> GetTreatmentsByFlagSet(Key key, string flagSet, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
var results = GetTreatmentsByFlagSets(Enums.API.GetTreatmentsByFlagSet, key, new List<string> { flagSet }, attributes, evaluationOptions);
return results.ToDictionary(r => r.FeatureFlagName, r => r.Treatment);
}
#endregion
#region Destroy
public virtual async Task DestroyAsync()
{
if (_statusManager.IsDestroyed()) return;
_log.Info(Messages.InitDestroy);
_factoryInstantiationsService.Decrease(ApiKey);
_statusManager.SetDestroy();
await _syncManager.ShutdownAsync();
if (_eventsManager != null)
{
_internalEventsTask.Stop();
UnregisterEvents();
}
_log.Info(Messages.Destroyed);
}
public virtual void Destroy()
{
if (_statusManager.IsDestroyed()) return;
_log.Info(Messages.InitDestroy);
_factoryInstantiationsService.Decrease(ApiKey);
_statusManager.SetDestroy();
_syncManager.Shutdown();
if (_eventsManager != null)
{
_internalEventsTask.Stop();
UnregisterEvents();
}
_log.Info(Messages.Destroyed);
}
#endregion
#region Track
public virtual bool Track(string key, string trafficType, string eventType, double? value = null, Dictionary<string, object> properties = null)
{
if (_statusManager.IsDestroyed()) return false;
var clock = new Stopwatch();
clock.Start();
try
{
if (!_clientExtensionService.TrackValidations(key, trafficType, eventType, value, properties, out var wrappedEvent)) return false;
_eventsLog.Log(wrappedEvent);
_clientExtensionService.RecordLatency(Enums.API.Track, clock.ElapsedMilliseconds);
return true;
}
catch (Exception e)
{
_log.Error("Exception caught trying to track an event", e);
_clientExtensionService.RecordException(Enums.API.Track);
return false;
}
finally { clock.Stop(); }
}
public virtual async Task<bool> TrackAsync(string key, string trafficType, string eventType, double? value = null, Dictionary<string, object> properties = null)
{
if (_statusManager.IsDestroyed()) return false;
var clock = new Stopwatch();
clock.Start();
try
{
if (!_clientExtensionService.TrackValidations(key, trafficType, eventType, value, properties, out var wrappedEvent)) return false;
await _eventsLog.LogAsync(wrappedEvent);
await _clientExtensionService.RecordLatencyAsync(Enums.API.Track, clock.ElapsedMilliseconds);
return true;
}
catch (Exception e)
{
_log.Error("Exception caught trying to track an event", e);
await _clientExtensionService.RecordExceptionAsync(Enums.API.Track);
return false;
}
finally { clock.Stop(); }
}
#endregion
#region Public Methods
public bool IsDestroyed()
{
return _statusManager.IsDestroyed();
}
public void BlockUntilReady(int blockMilisecondsUntilReady)
{
_blockUntilReadyService.BlockUntilReady(blockMilisecondsUntilReady);
}
public ISplitManager GetSplitManager()
{
return _manager;
}
#endregion
#region Protected Methods
protected void BuildStatusAndTaskManager()
{
_statusManager = new InMemoryReadinessGatesCache(_internalEventsTask);
_tasksManager = new TasksManager(_statusManager);
}
protected void BuildUniqueKeysTracker(BaseConfig config)
{
var bloomFilter = new BloomFilter(config.BfExpectedElements, config.BfErrorRate);
var filterAdapter = new FilterAdapter(bloomFilter);
var trackerCache = new ConcurrentDictionary<string, HashSet<string>>();
var trackerConfig = new ComponentConfig(config.UniqueKeysCacheMaxSize, config.UniqueKeysBulkSize);
var mtksTask = _tasksManager.NewPeriodicTask(Enums.Task.MTKsSender, config.UniqueKeysRefreshRate * 1000);
var cacheLongTermCleaningTask = _tasksManager.NewPeriodicTask(Enums.Task.CacheLongTermCleaning, Constants.Gral.IntervalToClearLongTermCache);
var sendBulkDataTask = _tasksManager.NewOnTimeTask(Enums.Task.MtkSendBulkData);
_uniqueKeysTracker = new UniqueKeysTracker(trackerConfig, filterAdapter, trackerCache, _impressionsSenderAdapter, mtksTask, cacheLongTermCleaningTask, sendBulkDataTask);
}
protected void BuildImpressionsCounter(BaseConfig config)
{
var trackerConfig = new ComponentConfig(config.ImpressionsCounterCacheMaxSize, config.ImpressionsCountBulkSize);
var task = _tasksManager.NewPeriodicTask(Enums.Task.ImpressionsCountSender, config.ImpressionsCounterRefreshRate * 1000);
var sendBulkDataTask = _tasksManager.NewOnTimeTask(Enums.Task.ImpressionCounterSendBulkData);
_impressionsCounter = new ImpressionsCounter(trackerConfig, _impressionsSenderAdapter, task, sendBulkDataTask);
}
protected void BuildClientExtension()
{
_clientExtensionService = new ClientExtensionService(_blockUntilReadyService, _statusManager, _keyValidator, _splitNameValidator, _telemetryEvaluationProducer, _eventTypeValidator, _propertiesValidator, _trafficTypeValidator, _flagSetsValidator, _flagSetsFilter, _fallbackTreatmentCalculator);
}
protected void BuildFlagSetsFilter(HashSet<string> sets)
{
_flagSetsFilter = new FlagSetsFilter(sets);
}
protected void BuildFallbackCalculator(FallbackTreatmentsConfiguration fallbackTreatmentsConfiguration)
{
_fallbackTreatmentCalculator = new FallbackTreatmentCalculator(fallbackTreatmentsConfiguration);
}
protected void BuildEventsManager()
{
_eventsManager = new EventsManager<SdkEvent, SdkInternalEvent, EventMetadata>(new EventsManagerConfig(), new EventDelivery<SdkEvent, EventMetadata>());
_internalEventsTask = new InternalEventsTask(_eventsManager, new SplitQueue<EventSource.Workers.SdkEventNotification>());
_internalEventsTask.Start();
RegisterEvents();
}
#endregion
#region Private Async Methods
private async Task<List<TreatmentResult>> GetTreatmentsAsync(Enums.API method, Key key, List<string> features, Dictionary<string, object> attributes, EvaluationOptions evaluationOptions)
{
try
{
features = _clientExtensionService.TreatmentsValidations(method, key, features, _log, out List<TreatmentResult> controlTreatments);
if (controlTreatments != null) return controlTreatments;
var treatments = await _evaluator.EvaluateFeaturesAsync(method, key, features, attributes);
await TrackImpressionsAsync(treatments, key, evaluationOptions);
return treatments;
}
catch (Exception ex)
{
_telemetryEvaluationProducer.RecordException(method.ConvertToMethodEnum());
_log.Warn("Something went wrong evaluating features.", ex);
return _clientExtensionService.ReturnControl(features);
}
}
private async Task<List<TreatmentResult>> GetTreatmentsByFlagSetsAsync(Enums.API method, Key key, List<string> flagSets, Dictionary<string, object> attributes, EvaluationOptions evaluationOptions)
{
try
{
flagSets = _clientExtensionService.FlagSetsValidations(method, key, flagSets, _log);
var treatments = await _evaluator.EvaluateFeaturesByFlagSetsAsync(method, key, flagSets, attributes);
await TrackImpressionsAsync(treatments, key, evaluationOptions);
return treatments;
}
catch (Exception ex)
{
_telemetryEvaluationProducer.RecordException(method.ConvertToMethodEnum());
_log.Warn("Something went wrong evaluating features.", ex);
return new List<TreatmentResult>();
}
}
private async Task TrackImpressionsAsync(List<TreatmentResult> evaluatorResults, Key key, EvaluationOptions evaluationOptions)
{
if (evaluationOptions == null)
{
evaluationOptions = new EvaluationOptions();
}
var impressions = BuildAndGetImpressions(evaluatorResults, key, evaluationOptions.Properties);
if (impressions.Any())
await _impressionsManager.TrackAsync(impressions);
}
#endregion
#region Private Methods
private void RegisterEvents()
{
_eventsManager.Register(SdkEvent.SdkReady, TriggerSdkReady);
_eventsManager.Register(SdkEvent.SdkUpdate, TriggerSdkUpdate);
}
private void UnregisterEvents()
{
_eventsManager.Unregister(SdkEvent.SdkReady);
_eventsManager.Unregister(SdkEvent.SdkUpdate);
}
private List<TreatmentResult> GetTreatmentsSync(Enums.API method, Key key, List<string> features, Dictionary<string, object> attributes = null, EvaluationOptions evaluationOptions = null)
{
try
{
features = _clientExtensionService.TreatmentsValidations(method, key, features, _log, out List<TreatmentResult> controlTreatments);
if (controlTreatments != null) return controlTreatments;
var treatments = _evaluator.EvaluateFeatures(method, key, features, attributes);
TrackImpressions(treatments, key, evaluationOptions);
return treatments;
}
catch (Exception ex)
{
_telemetryEvaluationProducer.RecordException(method.ConvertToMethodEnum());
_log.Warn("Something went wrong evaluating features.", ex);
return _clientExtensionService.ReturnControl(features);
}
}
private List<TreatmentResult> GetTreatmentsByFlagSets(Enums.API method, Key key, List<string> flagSets, Dictionary<string, object> attributes, EvaluationOptions evaluationOptions = null)
{
try
{
flagSets = _clientExtensionService.FlagSetsValidations(method, key, flagSets, _log);
var treatments = _evaluator.EvaluateFeaturesByFlagSets(method, key, flagSets, attributes);
TrackImpressions(treatments, key, evaluationOptions);
return treatments;
}
catch (Exception ex)
{
_telemetryEvaluationProducer.RecordException(method.ConvertToMethodEnum());
_log.Warn("Something went wrong evaluating features.", ex);
return new List<TreatmentResult>();
}
}
private List<KeyImpression> BuildAndGetImpressions(List<TreatmentResult> treatments, Key key, Dictionary<string, object> properties = null)
{
var impressions = new List<KeyImpression>();
foreach (var treatment in treatments)
{
var impression = _impressionsManager.Build(treatment, key, properties);
if (impression != null) impressions.Add(impression);
}
return impressions;
}
private void TrackImpressions(List<TreatmentResult> treatments, Key key, EvaluationOptions evaluationOptions)
{
try
{
if (evaluationOptions == null)
{
evaluationOptions = new EvaluationOptions();
}
var impressions = BuildAndGetImpressions(treatments, key, evaluationOptions.Properties);
if (impressions.Any())
_impressionsManager.Track(impressions);
}
catch (Exception ex)
{
_log.Warn("Something went wrong tracking impressions.", ex);
}
}
private static SplitResult TreatmentWithConfig(List<TreatmentResult> results)
{
if (!results.Any()) return new SplitResult(Gral.Control, null);
var result = results.FirstOrDefault();
if (result == null) return new SplitResult(Gral.Control, null);
return new SplitResult(result.Treatment, result.Config);
}
private void TriggerSdkReady(EventMetadata metaData)
{
SdkReadyEvent?.Invoke(this, metaData);
}
private void TriggerSdkUpdate(EventMetadata metaData)
{
SdkUpdate?.Invoke(this, metaData);
}
#endregion
}
}