-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheppo-client.ts
1504 lines (1376 loc) · 52.9 KB
/
eppo-client.ts
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { v4 as randomUUID } from 'uuid';
import ApiEndpoints from '../api-endpoints';
import { logger, loggerPrefix } from '../application-logger';
import { IAssignmentEvent, IAssignmentLogger } from '../assignment-logger';
import {
ensureActionsWithContextualAttributes,
ensureContextualSubjectAttributes,
ensureNonContextualSubjectAttributes,
} from '../attributes';
import { BanditEvaluation, BanditEvaluator } from '../bandit-evaluator';
import { IBanditEvent, IBanditLogger } from '../bandit-logger';
import { AssignmentCache } from '../cache/abstract-assignment-cache';
import { LRUInMemoryAssignmentCache } from '../cache/lru-in-memory-assignment-cache';
import { NonExpiringInMemoryAssignmentCache } from '../cache/non-expiring-in-memory-cache-assignment';
import { TLRUInMemoryAssignmentCache } from '../cache/tlru-in-memory-assignment-cache';
import ConfigurationRequestor from '../configuration-requestor';
import { ConfigurationManager } from '../configuration-store/configuration-manager';
import { IConfigurationStore, ISyncStore } from '../configuration-store/configuration-store';
import {
ConfigurationStoreBundle,
IConfigurationManager,
} from '../configuration-store/i-configuration-manager';
import { MemoryOnlyConfigurationStore } from '../configuration-store/memory.store';
import {
ConfigurationWireV1,
IConfigurationWire,
IPrecomputedConfiguration,
PrecomputedConfiguration,
} from '../configuration-wire/configuration-wire-types';
import { inflateJsonObject } from '../configuration-wire/json-util';
import {
DEFAULT_INITIAL_CONFIG_REQUEST_RETRIES,
DEFAULT_POLL_CONFIG_REQUEST_RETRIES,
DEFAULT_POLL_INTERVAL_MS,
DEFAULT_REQUEST_TIMEOUT_MS,
} from '../constants';
import { decodeFlag } from '../decoding';
import { EppoValue } from '../eppo_value';
import { Evaluator, FlagEvaluation, noneResult, overrideResult } from '../evaluator';
import { BoundedEventQueue } from '../events/bounded-event-queue';
import EventDispatcher from '../events/event-dispatcher';
import NoOpEventDispatcher from '../events/no-op-event-dispatcher';
import {
FlagEvaluationDetailsBuilder,
IFlagEvaluationDetails,
} from '../flag-evaluation-details-builder';
import { FlagEvaluationError } from '../flag-evaluation-error';
import FetchHttpClient, {
IBanditParametersResponse,
IUniversalFlagConfigResponse,
} from '../http-client';
import { IConfiguration } from '../i-configuration';
import {
BanditModelData,
BanditParameters,
BanditVariation,
Flag,
IPrecomputedBandit,
ObfuscatedFlag,
PrecomputedFlag,
Variation,
VariationType,
} from '../interfaces';
import { getMD5Hash } from '../obfuscation';
import { OverridePayload, OverrideValidator } from '../override-validator';
import initPoller, { IPoller } from '../poller';
import {
Attributes,
AttributeType,
BanditActions,
BanditSubjectAttributes,
ContextAttributes,
FlagKey,
ValueType,
} from '../types';
import { shallowClone } from '../util';
import { validateNotBlank } from '../validation';
import { LIB_VERSION } from '../version';
export interface IAssignmentDetails<T extends Variation['value'] | object> {
variation: T;
action: string | null;
evaluationDetails: IFlagEvaluationDetails;
}
export type FlagConfigurationRequestParameters = {
apiKey: string;
sdkVersion: string;
sdkName: string;
baseUrl?: string;
requestTimeoutMs?: number;
pollingIntervalMs?: number;
numInitialRequestRetries?: number;
numPollRequestRetries?: number;
pollAfterSuccessfulInitialization?: boolean;
pollAfterFailedInitialization?: boolean;
throwOnFailedInitialization?: boolean;
skipInitialPoll?: boolean;
};
export interface IContainerExperiment<T> {
flagKey: string;
controlVariationEntry: T;
treatmentVariationEntries: Array<T>;
}
export type EppoClientParameters = {
// Dispatcher for arbitrary, application-level events (not to be confused with Eppo specific assignment
// or bandit events). These events are application-specific and captures by EppoClient#track API.
eventDispatcher?: EventDispatcher;
flagConfigurationStore: IConfigurationStore<Flag | ObfuscatedFlag>;
banditVariationConfigurationStore?: IConfigurationStore<BanditVariation[]>;
banditModelConfigurationStore?: IConfigurationStore<BanditParameters>;
configurationRequestParameters?: FlagConfigurationRequestParameters;
/**
* Setting this value will have no side effects other than triggering a warning when the actual
* configuration's obfuscated does not match the value set here.
*
* @deprecated obfuscation is determined by inspecting the `format` field of the UFC response.
*/
isObfuscated?: boolean;
};
export default class EppoClient {
private eventDispatcher: EventDispatcher;
private readonly assignmentEventsQueue: BoundedEventQueue<IAssignmentEvent> =
new BoundedEventQueue<IAssignmentEvent>('assignments');
private readonly banditEventsQueue: BoundedEventQueue<IBanditEvent> =
new BoundedEventQueue<IBanditEvent>('bandit');
private readonly banditEvaluator = new BanditEvaluator();
private banditLogger?: IBanditLogger;
private banditAssignmentCache?: AssignmentCache;
private configurationRequestParameters?: FlagConfigurationRequestParameters;
private banditModelConfigurationStore?: IConfigurationStore<BanditParameters>;
private banditVariationConfigurationStore?: IConfigurationStore<BanditVariation[]>;
private overrideStore?: ISyncStore<Variation>;
private flagConfigurationStore: IConfigurationStore<Flag | ObfuscatedFlag>;
private assignmentLogger?: IAssignmentLogger;
private assignmentCache?: AssignmentCache;
// whether to suppress any errors and return default values instead
private isGracefulFailureMode = true;
private expectObfuscated: boolean;
private obfuscationMismatchWarningIssued = false;
private configObfuscatedCache?: boolean;
private requestPoller?: IPoller;
private readonly evaluator = new Evaluator();
private configurationRequestor?: ConfigurationRequestor;
private readonly overrideValidator = new OverrideValidator();
private configurationManager: IConfigurationManager;
constructor({
eventDispatcher = new NoOpEventDispatcher(),
isObfuscated = false,
flagConfigurationStore,
banditVariationConfigurationStore,
banditModelConfigurationStore,
overrideStore,
configurationRequestParameters,
}: {
// Dispatcher for arbitrary, application-level events (not to be confused with Eppo specific assignment
// or bandit events). These events are application-specific and captures by EppoClient#track API.
eventDispatcher?: EventDispatcher;
flagConfigurationStore: IConfigurationStore<Flag | ObfuscatedFlag>;
banditVariationConfigurationStore?: IConfigurationStore<BanditVariation[]>;
banditModelConfigurationStore?: IConfigurationStore<BanditParameters>;
overrideStore?: ISyncStore<Variation>;
configurationRequestParameters?: FlagConfigurationRequestParameters;
isObfuscated?: boolean;
}) {
this.eventDispatcher = eventDispatcher;
this.flagConfigurationStore = flagConfigurationStore;
this.banditVariationConfigurationStore = banditVariationConfigurationStore;
this.banditModelConfigurationStore = banditModelConfigurationStore;
this.overrideStore = overrideStore;
this.configurationRequestParameters = configurationRequestParameters;
this.expectObfuscated = isObfuscated;
// Initialize the configuration manager
this.configurationManager = new ConfigurationManager(
this.flagConfigurationStore,
this.banditVariationConfigurationStore,
this.banditModelConfigurationStore,
);
}
private getConfiguration(): IConfiguration {
return this.configurationManager.getConfiguration();
}
private maybeWarnAboutObfuscationMismatch(configObfuscated: boolean) {
// Don't warn again if we did on the last check.
if (configObfuscated !== this.expectObfuscated && !this.obfuscationMismatchWarningIssued) {
this.obfuscationMismatchWarningIssued = true;
logger.warn(
`[Eppo SDK] configuration obfuscation [${configObfuscated}] does not match expected [${this.expectObfuscated}]`,
);
} else if (configObfuscated === this.expectObfuscated) {
// Reset the warning to false in case the client configuration (re-)enters a mismatched state.
this.obfuscationMismatchWarningIssued = false;
}
}
/**
* This method delegates to the configuration to determine whether it is obfuscated, then caches the actual
* obfuscation state and issues a warning if it hasn't already.
* This method can be removed with the next major update when the @deprecated setIsObfuscated is removed
*/
private isObfuscated(config: IConfiguration) {
if (this.configObfuscatedCache === undefined) {
this.configObfuscatedCache = config.isObfuscated();
}
this.maybeWarnAboutObfuscationMismatch(this.configObfuscatedCache);
return this.configObfuscatedCache;
}
/**
* Validates and parses x-eppo-overrides header sent by Eppo's Chrome extension
*/
async parseOverrides(
overridePayload: string | undefined,
): Promise<Record<FlagKey, Variation> | undefined> {
if (!overridePayload) {
return undefined;
}
const payload: OverridePayload = this.overrideValidator.parseOverridePayload(overridePayload);
await this.overrideValidator.validateKey(payload.browserExtensionKey);
return payload.overrides;
}
/**
* Creates an EppoClient instance that has the specified overrides applied
* to it without affecting the original EppoClient singleton. Useful for
* applying overrides in a shared Node instance, such as a web server.
*/
withOverrides(overrides: Record<FlagKey, Variation> | undefined): EppoClient {
if (overrides && Object.keys(overrides).length) {
const copy = shallowClone(this);
copy.overrideStore = new MemoryOnlyConfigurationStore<Variation>();
copy.overrideStore.setEntries(overrides);
return copy;
}
return this;
}
setConfigurationRequestParameters(
configurationRequestParameters: FlagConfigurationRequestParameters,
) {
this.configurationRequestParameters = configurationRequestParameters;
}
public setConfigurationStores(configStores: ConfigurationStoreBundle) {
// Update the configuration manager
this.configurationManager.setConfigurationStores(configStores);
}
// noinspection JSUnusedGlobalSymbols
/**
* @deprecated use `setConfigurationStores` instead
*/
setFlagConfigurationStore(flagConfigurationStore: IConfigurationStore<Flag | ObfuscatedFlag>) {
this.flagConfigurationStore = flagConfigurationStore;
this.configObfuscatedCache = undefined;
// Update the configuration manager
this.innerSetConfigurationStores();
}
// noinspection JSUnusedGlobalSymbols
/**
* @deprecated use `setConfigurationStores` instead
*/
setBanditVariationConfigurationStore(
banditVariationConfigurationStore: IConfigurationStore<BanditVariation[]>,
) {
this.banditVariationConfigurationStore = banditVariationConfigurationStore;
// Update the configuration manager
this.innerSetConfigurationStores();
}
// noinspection JSUnusedGlobalSymbols
/**
* @deprecated use `setConfigurationStores` instead
*/
setBanditModelConfigurationStore(
banditModelConfigurationStore: IConfigurationStore<BanditParameters>,
) {
this.banditModelConfigurationStore = banditModelConfigurationStore;
// Update the configuration manager
this.innerSetConfigurationStores();
}
private innerSetConfigurationStores() {
// Set the set of configuration stores to those owned by the `this`.
this.setConfigurationStores({
flagConfigurationStore: this.flagConfigurationStore,
banditReferenceConfigurationStore: this.banditVariationConfigurationStore,
banditConfigurationStore: this.banditModelConfigurationStore,
});
}
/** Sets the EventDispatcher instance to use when tracking events with {@link track}. */
setEventDispatcher(eventDispatcher: EventDispatcher) {
this.eventDispatcher = eventDispatcher;
}
/**
* Attaches a context to be included with all events dispatched by the EventDispatcher.
* The context is delivered as a top-level object in the ingestion request payload.
* An existing key can be removed by providing a `null` value.
* Calling this method with same key multiple times causes only the last value to be used for the
* given key.
*
* @param key - The context entry key.
* @param value - The context entry value, must be a string, number, boolean, or null. If value is
* an object or an array, will throw an ArgumentError.
*/
setContext(key: string, value: string | number | boolean | null) {
this.eventDispatcher?.attachContext(key, value);
}
setOverrideStore(store: ISyncStore<Variation>): void {
this.overrideStore = store;
}
unsetOverrideStore(): void {
this.overrideStore = undefined;
}
// Returns a mapping of flag key to variation key for all active overrides
getOverrideVariationKeys(): Record<string, string> {
return Object.fromEntries(
Object.entries(this.overrideStore?.entries() ?? {}).map(([flagKey, value]) => [
flagKey,
value.key,
]),
);
}
/**
* Initializes the `EppoClient` from the provided configuration. This method is async only to
* accommodate writing to a persistent store. For fastest initialization, (at the cost of persisting configuration),
* use `bootstrap` in conjunction with `MemoryOnlyConfigurationStore` instances which won't do an async write.
*/
async bootstrap(configuration: IConfigurationWire): Promise<void> {
if (!configuration.config) {
throw new Error('Flag configuration not provided');
}
const flagConfigResponse: IUniversalFlagConfigResponse = inflateJsonObject(
configuration.config.response,
);
const banditParamResponse: IBanditParametersResponse | undefined = configuration.bandits
? inflateJsonObject(configuration.bandits.response)
: undefined;
// We need to run this method sync, but, because the configuration stores potentially have an async write at the end
// of updating the configuration, the method to do so it also async. Use an IIFE to wrap the async call.
await this.configurationManager.hydrateConfigurationStoresFromUfc(
flagConfigResponse,
banditParamResponse,
);
}
async fetchFlagConfigurations() {
if (!this.configurationRequestParameters) {
throw new Error(
'Eppo SDK unable to fetch flag configurations without configuration request parameters',
);
}
// if fetchFlagConfigurations() was previously called, stop any polling process from that call
this.requestPoller?.stop();
const {
apiKey,
sdkName,
sdkVersion,
baseUrl,
requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT_MS,
numInitialRequestRetries = DEFAULT_INITIAL_CONFIG_REQUEST_RETRIES,
numPollRequestRetries = DEFAULT_POLL_CONFIG_REQUEST_RETRIES,
pollAfterSuccessfulInitialization = false,
pollAfterFailedInitialization = false,
throwOnFailedInitialization = false,
skipInitialPoll = false,
} = this.configurationRequestParameters;
let { pollingIntervalMs = DEFAULT_POLL_INTERVAL_MS } = this.configurationRequestParameters;
if (pollingIntervalMs <= 0) {
logger.error('pollingIntervalMs must be greater than 0. Using default');
pollingIntervalMs = DEFAULT_POLL_INTERVAL_MS;
}
const apiEndpoints = new ApiEndpoints({
baseUrl,
queryParams: { apiKey, sdkName, sdkVersion },
});
const httpClient = new FetchHttpClient(apiEndpoints, requestTimeoutMs);
// Use the configuration manager when creating the requestor
const configurationRequestor = new ConfigurationRequestor(
httpClient,
this.configurationManager,
!!this.banditModelConfigurationStore && !!this.banditVariationConfigurationStore,
);
this.configurationRequestor = configurationRequestor;
const pollingCallback = async () => {
if (await this.flagConfigurationStore.isExpired()) {
this.configObfuscatedCache = undefined;
return configurationRequestor.fetchAndStoreConfigurations();
}
};
this.requestPoller = initPoller(pollingIntervalMs, pollingCallback, {
maxStartRetries: numInitialRequestRetries,
maxPollRetries: numPollRequestRetries,
pollAfterSuccessfulStart: pollAfterSuccessfulInitialization,
pollAfterFailedStart: pollAfterFailedInitialization,
errorOnFailedStart: throwOnFailedInitialization,
skipInitialPoll: skipInitialPoll,
});
await this.requestPoller.start();
}
// noinspection JSUnusedGlobalSymbols
stopPolling() {
if (this.requestPoller) {
this.requestPoller.stop();
}
}
/**
* Maps a subject to a string variation for a given experiment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* The subject attributes are used for evaluating any targeting rules tied to the experiment.
* @returns a variation value if the subject is part of the experiment sample, otherwise the default value
* @public
*/
getStringAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: string,
): string {
return this.getStringAssignmentDetails(flagKey, subjectKey, subjectAttributes, defaultValue)
.variation;
}
/**
* Maps a subject to a string variation for a given experiment and provides additional details about the
* variation assigned and the reason for the assignment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* The subject attributes are used for evaluating any targeting rules tied to the experiment.
* @returns an object that includes the variation value along with additional metadata about the assignment
* @public
*/
getStringAssignmentDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: Record<string, AttributeType>,
defaultValue: string,
): IAssignmentDetails<string> {
const { eppoValue, flagEvaluationDetails } = this.getAssignmentVariation(
flagKey,
subjectKey,
subjectAttributes,
EppoValue.String(defaultValue),
VariationType.STRING,
);
return {
variation: eppoValue.stringValue ?? defaultValue,
action: null,
evaluationDetails: flagEvaluationDetails,
};
}
/**
* @deprecated use getBooleanAssignment instead.
*/
getBoolAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: boolean,
): boolean {
return this.getBooleanAssignment(flagKey, subjectKey, subjectAttributes, defaultValue);
}
/**
* Maps a subject to a boolean variation for a given experiment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* @returns a boolean variation value if the subject is part of the experiment sample, otherwise the default value
*/
getBooleanAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: boolean,
): boolean {
return this.getBooleanAssignmentDetails(flagKey, subjectKey, subjectAttributes, defaultValue)
.variation;
}
/**
* Maps a subject to a boolean variation for a given experiment and provides additional details about the
* variation assigned and the reason for the assignment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* The subject attributes are used for evaluating any targeting rules tied to the experiment.
* @returns an object that includes the variation value along with additional metadata about the assignment
* @public
*/
getBooleanAssignmentDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: Record<string, AttributeType>,
defaultValue: boolean,
): IAssignmentDetails<boolean> {
const { eppoValue, flagEvaluationDetails } = this.getAssignmentVariation(
flagKey,
subjectKey,
subjectAttributes,
EppoValue.Bool(defaultValue),
VariationType.BOOLEAN,
);
return {
variation: eppoValue.boolValue ?? defaultValue,
action: null,
evaluationDetails: flagEvaluationDetails,
};
}
/**
* Maps a subject to an Integer variation for a given experiment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* @returns an integer variation value if the subject is part of the experiment sample, otherwise the default value
*/
getIntegerAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: number,
): number {
return this.getIntegerAssignmentDetails(flagKey, subjectKey, subjectAttributes, defaultValue)
.variation;
}
/**
* Maps a subject to an Integer variation for a given experiment and provides additional details about the
* variation assigned and the reason for the assignment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* The subject attributes are used for evaluating any targeting rules tied to the experiment.
* @returns an object that includes the variation value along with additional metadata about the assignment
* @public
*/
getIntegerAssignmentDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: Record<string, AttributeType>,
defaultValue: number,
): IAssignmentDetails<number> {
const { eppoValue, flagEvaluationDetails } = this.getAssignmentVariation(
flagKey,
subjectKey,
subjectAttributes,
EppoValue.Numeric(defaultValue),
VariationType.INTEGER,
);
return {
variation: eppoValue.numericValue ?? defaultValue,
action: null,
evaluationDetails: flagEvaluationDetails,
};
}
/**
* Maps a subject to a numeric variation for a given experiment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* @returns a number variation value if the subject is part of the experiment sample, otherwise the default value
*/
getNumericAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: number,
): number {
return this.getNumericAssignmentDetails(flagKey, subjectKey, subjectAttributes, defaultValue)
.variation;
}
/**
* Maps a subject to a numeric variation for a given experiment and provides additional details about the
* variation assigned and the reason for the assignment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* The subject attributes are used for evaluating any targeting rules tied to the experiment.
* @returns an object that includes the variation value along with additional metadata about the assignment
* @public
*/
getNumericAssignmentDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: Record<string, AttributeType>,
defaultValue: number,
): IAssignmentDetails<number> {
const { eppoValue, flagEvaluationDetails } = this.getAssignmentVariation(
flagKey,
subjectKey,
subjectAttributes,
EppoValue.Numeric(defaultValue),
VariationType.NUMERIC,
);
return {
variation: eppoValue.numericValue ?? defaultValue,
action: null,
evaluationDetails: flagEvaluationDetails,
};
}
/**
* Maps a subject to a JSON variation for a given experiment.
*
* @param flagKey feature flag identifier
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @param defaultValue default value to return if the subject is not part of the experiment sample
* @returns a JSON object variation value if the subject is part of the experiment sample, otherwise the default value
*/
getJSONAssignment(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: object,
): object {
return this.getJSONAssignmentDetails(flagKey, subjectKey, subjectAttributes, defaultValue)
.variation;
}
getJSONAssignmentDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: Record<string, AttributeType>,
defaultValue: object,
): IAssignmentDetails<object> {
const { eppoValue, flagEvaluationDetails } = this.getAssignmentVariation(
flagKey,
subjectKey,
subjectAttributes,
EppoValue.JSON(defaultValue),
VariationType.JSON,
);
return {
variation: eppoValue.objectValue ?? defaultValue,
action: null,
evaluationDetails: flagEvaluationDetails,
};
}
getBanditAction(
flagKey: string,
subjectKey: string,
subjectAttributes: BanditSubjectAttributes,
actions: BanditActions,
defaultValue: string,
): Omit<IAssignmentDetails<string>, 'evaluationDetails'> {
const { variation, action } = this.getBanditActionDetails(
flagKey,
subjectKey,
subjectAttributes,
actions,
defaultValue,
);
return { variation, action };
}
/**
* Evaluates the supplied actions using the first bandit associated with `flagKey` and returns the best ranked action.
*
* This method should be considered **preview** and is subject to change as requirements mature.
*
* NOTE: This method does not do any logging or assignment computation and so calling this method will have
* NO IMPACT on bandit and experiment training.
*
* Only use this method under certain circumstances (i.e. where the impact of the choice of bandit cannot be measured,
* but you want to put the "best foot forward", for example, when being web-crawled).
*
*/
getBestAction(
flagKey: string,
subjectAttributes: BanditSubjectAttributes,
actions: BanditActions,
defaultAction: string,
): string {
const config = this.getConfiguration();
let result: string | null = null;
const flagBanditVariations = config.getFlagBanditVariations(flagKey);
const banditKey = flagBanditVariations?.at(0)?.key;
if (banditKey) {
const banditParameters = config.getBandit(banditKey);
if (banditParameters) {
const contextualSubjectAttributes = ensureContextualSubjectAttributes(subjectAttributes);
const actionsWithContextualAttributes = ensureActionsWithContextualAttributes(actions);
result = this.banditEvaluator.evaluateBestBanditAction(
contextualSubjectAttributes,
actionsWithContextualAttributes,
banditParameters.modelData,
);
}
}
return result ?? defaultAction;
}
getBanditActionDetails(
flagKey: string,
subjectKey: string,
subjectAttributes: BanditSubjectAttributes,
actions: BanditActions,
defaultValue: string,
): IAssignmentDetails<string> {
const config = this.getConfiguration();
let variation = defaultValue;
let action: string | null = null;
// Initialize with a generic evaluation details. This will mutate as the function progresses.
let evaluationDetails: IFlagEvaluationDetails = this.newFlagEvaluationDetailsBuilder(
config,
flagKey,
).buildForNoneResult(
'ASSIGNMENT_ERROR',
'Unexpected error getting assigned variation for bandit action',
);
try {
// Get the assigned variation for the flag with a possible bandit
// Note for getting assignments, we don't care about context
const nonContextualSubjectAttributes =
ensureNonContextualSubjectAttributes(subjectAttributes);
const { variation: assignedVariation, evaluationDetails: assignmentEvaluationDetails } =
this.getStringAssignmentDetails(
flagKey,
subjectKey,
nonContextualSubjectAttributes,
defaultValue,
);
variation = assignedVariation;
evaluationDetails = assignmentEvaluationDetails;
// Check if the assigned variation is an active bandit
// Note: the reason for non-bandit assignments include the subject being bucketed into a non-bandit variation or
// a rollout having been done.
const bandit = config.getFlagVariationBandit(flagKey, variation);
if (!bandit) {
return { variation, action: null, evaluationDetails };
}
evaluationDetails.banditKey = bandit.banditKey;
const banditEvaluation = this.evaluateBanditAction(
flagKey,
subjectKey,
subjectAttributes,
actions,
bandit.modelData,
);
if (banditEvaluation?.actionKey) {
action = banditEvaluation.actionKey;
const banditEvent: IBanditEvent = {
timestamp: new Date().toISOString(),
featureFlag: flagKey,
bandit: bandit.banditKey,
subject: subjectKey,
action,
actionProbability: banditEvaluation.actionWeight,
optimalityGap: banditEvaluation.optimalityGap,
modelVersion: bandit.modelVersion,
subjectNumericAttributes: banditEvaluation.subjectAttributes.numericAttributes,
subjectCategoricalAttributes: banditEvaluation.subjectAttributes.categoricalAttributes,
actionNumericAttributes: banditEvaluation.actionAttributes.numericAttributes,
actionCategoricalAttributes: banditEvaluation.actionAttributes.categoricalAttributes,
metaData: this.buildLoggerMetadata(),
evaluationDetails,
};
try {
this.logBanditAction(banditEvent);
} catch (err: any) {
logger.error('Error logging bandit event', err);
}
evaluationDetails.banditAction = action;
}
} catch (err: any) {
logger.error('Error determining bandit action', err);
if (!this.isGracefulFailureMode) {
throw err;
}
if (variation) {
// If we have a variation, the assignment succeeded and the error was with the bandit part.
// Update the flag evaluation code to indicate that
evaluationDetails.flagEvaluationCode = 'BANDIT_ERROR';
}
evaluationDetails.flagEvaluationDescription = `Error evaluating bandit action: ${err.message}`;
}
return { variation, action, evaluationDetails };
}
/**
* For use with 3rd party CMS tooling, such as the Contentful Eppo plugin.
*
* CMS plugins that integrate with Eppo will follow a common format for
* creating a feature flag. The flag created by the CMS plugin will have
* variations with values 'control', 'treatment-1', 'treatment-2', etc.
* This function allows users to easily return the CMS container entry
* for the assigned variation.
*
* @param flagExperiment the flag key, control container entry and treatment container entries.
* @param subjectKey an identifier of the experiment subject, for example a user ID.
* @param subjectAttributes optional attributes associated with the subject, for example name and email.
* @returns The container entry associated with the experiment.
*/
getExperimentContainerEntry<T>(
flagExperiment: IContainerExperiment<T>,
subjectKey: string,
subjectAttributes: Attributes,
): T {
const { flagKey, controlVariationEntry, treatmentVariationEntries } = flagExperiment;
const assignment = this.getStringAssignment(flagKey, subjectKey, subjectAttributes, 'control');
if (assignment === 'control') {
return controlVariationEntry;
}
if (!assignment.startsWith('treatment-')) {
logger.warn(
`Variation '${assignment}' cannot be mapped to a container. Defaulting to control variation.`,
);
return controlVariationEntry;
}
const treatmentVariationIndex = Number.parseInt(assignment.split('-')[1]) - 1;
if (isNaN(treatmentVariationIndex)) {
logger.warn(
`Variation '${assignment}' cannot be mapped to a container. Defaulting to control variation.`,
);
return controlVariationEntry;
}
if (treatmentVariationIndex >= treatmentVariationEntries.length) {
logger.warn(
`Selected treatment variation (${treatmentVariationIndex}) index is out of bounds. Defaulting to control variation.`,
);
return controlVariationEntry;
}
return treatmentVariationEntries[treatmentVariationIndex];
}
private evaluateBanditAction(
flagKey: string,
subjectKey: string,
subjectAttributes: BanditSubjectAttributes,
actions: BanditActions,
banditModelData: BanditModelData,
): BanditEvaluation | null {
// If no actions, there is nothing to do
if (!Object.keys(actions).length) {
return null;
}
const contextualSubjectAttributes = ensureContextualSubjectAttributes(subjectAttributes);
const actionsWithContextualAttributes = ensureActionsWithContextualAttributes(actions);
return this.banditEvaluator.evaluateBandit(
flagKey,
subjectKey,
contextualSubjectAttributes,
actionsWithContextualAttributes,
banditModelData,
);
}
private logBanditAction(banditEvent: IBanditEvent): void {
// First we check if this bandit action has been logged before
const subjectKey = banditEvent.subject;
const flagKey = banditEvent.featureFlag;
const banditKey = banditEvent.bandit;
const actionKey = banditEvent.action ?? '__eppo_no_action';
const banditAssignmentCacheProperties = {
flagKey,
subjectKey,
banditKey,
actionKey,
};
if (this.banditAssignmentCache?.has(banditAssignmentCacheProperties)) {
// Ignore repeat assignment
return;
}
// If here, we have a logger and a new assignment to be logged
try {
if (this.banditLogger) {
this.banditLogger.logBanditAction(banditEvent);
} else {
// If no logger defined, queue up the events (up to a max) to flush if a logger is later defined
this.banditEventsQueue.push(banditEvent);
}
// Record in the assignment cache, if active, to deduplicate subsequent repeat assignments
this.banditAssignmentCache?.set(banditAssignmentCacheProperties);
} catch (err) {
logger.warn('Error encountered logging bandit action', err);
}
}
private getAssignmentVariation(
flagKey: string,
subjectKey: string,
subjectAttributes: Attributes,
defaultValue: EppoValue,
expectedVariationType: VariationType,
): { eppoValue: EppoValue; flagEvaluationDetails: IFlagEvaluationDetails } {
try {
const result = this.getAssignmentDetail(
flagKey,
subjectKey,
subjectAttributes,
expectedVariationType,
);
return this.parseVariationWithDetails(result, defaultValue, expectedVariationType);
} catch (error: any) {
const eppoValue = this.rethrowIfNotGraceful(error, defaultValue);
if (error instanceof FlagEvaluationError && error.flagEvaluationDetails) {
return {
eppoValue,
flagEvaluationDetails: error.flagEvaluationDetails,
};
} else {
const flagEvaluationDetails = new FlagEvaluationDetailsBuilder(
'',
[],
'',
'',
).buildForNoneResult('ASSIGNMENT_ERROR', `Assignment Error: ${error.message}`);
return {
eppoValue,
flagEvaluationDetails,
};
}
}
}
private parseVariationWithDetails(
{ flagEvaluationDetails, variation }: FlagEvaluation,
defaultValue: EppoValue,
expectedVariationType: VariationType,
): { eppoValue: EppoValue; flagEvaluationDetails: IFlagEvaluationDetails } {
try {
if (!variation || flagEvaluationDetails.flagEvaluationCode !== 'MATCH') {
return { eppoValue: defaultValue, flagEvaluationDetails };
}
const eppoValue = EppoValue.valueOf(variation.value, expectedVariationType);
return { eppoValue, flagEvaluationDetails };
} catch (error: any) {
const eppoValue = this.rethrowIfNotGraceful(error, defaultValue);
return { eppoValue, flagEvaluationDetails };
}