-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreforge.ts
More file actions
484 lines (389 loc) · 12.5 KB
/
reforge.ts
File metadata and controls
484 lines (389 loc) · 12.5 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
/* eslint-disable max-classes-per-file */
import { Config, EvaluationPayload, RawConfigWithoutTypes } from "./config";
import type {
Duration,
TypedFrontEndConfigurationRaw,
FrontEndConfigurationRaw,
Contexts,
} from "./types";
import Context from "./context";
import { EvaluationSummaryAggregator } from "./evaluationSummaryAggregator";
import Loader, { CollectContextModeType } from "./loader";
import {
PREFIX as loggerPrefix,
shouldLog,
ShouldLogParams,
LogLevel,
shouldLogAtLevel,
} from "./logger";
import TelemetryUploader from "./telemetryUploader";
import { LoggerAggregator } from "./loggerAggregator";
/* eslint-disable no-underscore-dangle */
declare const __SDK_VERSION__: string;
const version = __SDK_VERSION__;
/* eslint-enable no-underscore-dangle */
function uuid() {
if (typeof crypto !== "undefined") {
return crypto.randomUUID();
}
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
type EvaluationCallback = <K extends keyof TypedFrontEndConfigurationRaw>(
key: K,
value: TypedFrontEndConfigurationRaw[K],
context: Context | undefined
) => void;
export interface ReforgeBootstrap {
evaluations: EvaluationPayload;
context: Contexts;
}
export type ReforgeInitParams = {
sdkKey: string;
context: Context;
endpoints?: string[] | undefined;
apiEndpoint?: string;
timeout?: number;
afterEvaluationCallback?: EvaluationCallback;
collectEvaluationSummaries?: boolean;
collectLoggerNames?: boolean;
collectContextMode?: CollectContextModeType;
clientNameString?: string;
clientVersionString?: string;
loggerKey?: string;
};
type PollStatus =
| { status: "not-started" }
| { status: "pending" }
| { status: "stopped" }
| { status: "running"; frequencyInMs: number };
type PublicShouldLogParams = Omit<ShouldLogParams, "get">;
// Forward declaration for ReforgeLogger
// eslint-disable-next-line @typescript-eslint/no-use-before-define
class ReforgeLogger {
// eslint-disable-next-line no-use-before-define
private reforge: Reforge;
// eslint-disable-next-line no-use-before-define
constructor(reforge: Reforge) {
this.reforge = reforge;
}
private log(message: string, level: LogLevel): void {
const configuredLevel = this.reforge.getLogLevel("");
if (shouldLogAtLevel(configuredLevel, level)) {
switch (level) {
case LogLevel.TRACE:
case LogLevel.DEBUG:
// eslint-disable-next-line no-console
console.debug(message);
break;
case LogLevel.INFO:
// eslint-disable-next-line no-console
console.info(message);
break;
case LogLevel.WARN:
// eslint-disable-next-line no-console
console.warn(message);
break;
case LogLevel.ERROR:
case LogLevel.FATAL:
// eslint-disable-next-line no-console
console.error(message);
break;
default:
// eslint-disable-next-line no-console
console.error(message);
}
}
}
trace(message: string): void {
this.log(message, LogLevel.TRACE);
}
debug(message: string): void {
this.log(message, LogLevel.DEBUG);
}
info(message: string): void {
this.log(message, LogLevel.INFO);
}
warn(message: string): void {
this.log(message, LogLevel.WARN);
}
error(message: string): void {
this.log(message, LogLevel.ERROR);
}
fatal(message: string): void {
this.log(message, LogLevel.FATAL);
}
}
export class Reforge {
private _configs: { [key: string]: Config } = {};
private _telemetryUploader: TelemetryUploader | undefined;
private _pollCount = 0;
private _pollStatus: PollStatus = { status: "not-started" };
private _pollTimeoutId = undefined as ReturnType<typeof setTimeout> | undefined;
private _instanceHash: string = uuid();
private collectEvaluationSummaries = true;
private collectLoggerNames = false;
private evalutionSummaryAggregator: EvaluationSummaryAggregator | undefined;
private loggerAggregator: LoggerAggregator | undefined;
public clientNameString = "sdk-javascript";
public loaded = false;
public loader: Loader | undefined;
public afterEvaluationCallback = (() => {}) as EvaluationCallback;
private _context: Context = new Context({});
private _loggerKey = "log-levels.default";
public logger: ReforgeLogger;
constructor() {
this.logger = new ReforgeLogger(this);
}
async init({
sdkKey,
context: providedContext,
endpoints = undefined,
apiEndpoint,
timeout = undefined,
afterEvaluationCallback = () => {},
collectEvaluationSummaries = true,
collectLoggerNames = false,
collectContextMode = "PERIODIC_EXAMPLE",
clientNameString = "sdk-javascript",
clientVersionString = version,
loggerKey = "log-levels.default",
}: ReforgeInitParams) {
const context = providedContext ?? this.context;
if (!context) {
throw new Error("Context must be provided");
}
this._context = context;
this._loggerKey = loggerKey;
this.clientNameString = clientNameString;
const clientNameAndVersionString = `${clientNameString}-${clientVersionString}`;
this.loader = new Loader({
sdkKey,
context,
endpoints,
timeout,
collectContextMode,
clientVersion: clientNameAndVersionString,
});
this._telemetryUploader = new TelemetryUploader({
sdkKey,
apiEndpoint,
timeout,
clientVersion: clientNameAndVersionString,
});
this.collectEvaluationSummaries = collectEvaluationSummaries;
if (collectEvaluationSummaries) {
this.evalutionSummaryAggregator = new EvaluationSummaryAggregator(this, 100000);
}
this.collectLoggerNames = collectLoggerNames;
if (collectLoggerNames) {
this.loggerAggregator = new LoggerAggregator(this, 100000);
}
if (
(collectEvaluationSummaries || collectLoggerNames) &&
typeof window !== "undefined" &&
typeof window.addEventListener === "function"
) {
window.addEventListener("beforeunload", () => {
this.evalutionSummaryAggregator?.sync();
this.loggerAggregator?.sync();
});
}
this.afterEvaluationCallback = afterEvaluationCallback;
return this.load();
}
public extract(): Record<string, Config["value"]> {
return Object.entries(this._configs).reduce(
(agg, [key, value]) => ({
...agg,
[key]: value.value,
}),
{} as Record<string, Config["value"]>
);
}
public hydrate(rawValues: RawConfigWithoutTypes | EvaluationPayload): void {
this.setConfigPrivate(rawValues);
}
get context(): Context {
return this._context;
}
get instanceHash(): string {
return this._instanceHash;
}
get pollTimeoutId() {
return this._pollTimeoutId;
}
get pollCount() {
return this._pollCount;
}
get pollStatus() {
return this._pollStatus;
}
get telemetryUploader(): TelemetryUploader | undefined {
return this._telemetryUploader;
}
private async load() {
if (!this.loader || !this.context) {
throw new Error("Reforge not initialized. Call init() first.");
}
/* eslint-disable no-underscore-dangle */
if (globalThis && (globalThis as any)._reforgeBootstrap) {
/* eslint-disable no-underscore-dangle */
const reforgeBootstrap = (globalThis as any)._reforgeBootstrap as ReforgeBootstrap;
const bootstrapContext = new Context(reforgeBootstrap.context);
if (this.context.equals(bootstrapContext)) {
this.setConfigPrivate({ evaluations: reforgeBootstrap.evaluations });
return Promise.resolve();
}
}
// make sure we have the freshest context
this.loader.context = this.context;
return this.loader
.load()
.then((rawValues: any) => {
this.setConfigPrivate(rawValues as EvaluationPayload);
})
.finally(() => {
if (this.pollStatus.status === "running") {
this._pollCount += 1;
}
});
}
async updateContext(context: Context, skipLoad = false) {
if (!this.loader) {
throw new Error("Reforge not initialized. Call init() first.");
}
this._context = context;
if (skipLoad) {
return Promise.resolve();
}
return this.load();
}
async poll({ frequencyInMs }: { frequencyInMs: number }) {
if (!this.loader) {
throw new Error("Reforge not initialized. Call init() first.");
}
this.stopPolling();
this._pollStatus = { status: "pending" };
return this.loader.load().finally(() => {
this.doPolling({ frequencyInMs });
});
}
private doPolling({ frequencyInMs }: { frequencyInMs: number }) {
this._pollTimeoutId = setTimeout(() => {
this.load().finally(() => {
if (this.pollStatus.status === "running") {
this.doPolling({ frequencyInMs });
}
});
}, frequencyInMs);
this._pollStatus = {
status: "running",
frequencyInMs,
};
}
stopPolling() {
if (this.pollTimeoutId) {
clearTimeout(this.pollTimeoutId);
this._pollTimeoutId = undefined;
}
this._pollStatus = { status: "stopped" };
}
stopTelemetry() {
if (this.telemetryUploader) {
this.evalutionSummaryAggregator?.stop();
this.loggerAggregator?.stop();
}
}
private setConfigPrivate(rawValues: RawConfigWithoutTypes | EvaluationPayload) {
this._configs = Config.digest(rawValues);
this.loaded = true;
}
isEnabled<
// We need to calcuate these live and not store in a type to ensure dynamic evaluation
// in upstream libraries that override the FrontEndConfigurationRaw interface
K extends keyof FrontEndConfigurationRaw extends never
? string
: {
[IK in keyof TypedFrontEndConfigurationRaw]: TypedFrontEndConfigurationRaw[IK] extends boolean
? IK
: never;
}[keyof TypedFrontEndConfigurationRaw],
>(key: K): boolean {
return this.get(key) === true;
}
get<K extends keyof TypedFrontEndConfigurationRaw>(key: K): TypedFrontEndConfigurationRaw[K] {
if (!this.loaded) {
if (!key.startsWith(loggerPrefix)) {
// eslint-disable-next-line no-console
console.warn(
`Reforge warning: The client has not finished loading data yet. Unable to look up actual value for key "${key}".`
);
}
return undefined;
}
const config = this._configs[key];
const value = config?.value;
if (!key.startsWith(loggerPrefix)) {
if (this.collectEvaluationSummaries) {
setTimeout(() => this.evalutionSummaryAggregator?.record(config));
}
setTimeout(() => this.afterEvaluationCallback(key, value, this.context));
}
return value;
}
getDuration<
// We need to calcuate these live and not store in a type to ensure dynamic evaluation
// in upstream libraries that override the FrontEndConfigurationRaw interface
K extends keyof FrontEndConfigurationRaw extends never
? string
: {
[IK in keyof TypedFrontEndConfigurationRaw]: TypedFrontEndConfigurationRaw[IK] extends Duration
? IK
: never;
}[keyof TypedFrontEndConfigurationRaw],
>(key: K): Duration | undefined {
const value = this.get(key);
if (!value) {
return undefined;
}
if (
!Object.prototype.hasOwnProperty.call(value, "seconds") ||
!Object.prototype.hasOwnProperty.call(value, "ms")
) {
throw new Error(`Value for key "${key}" is not a duration`);
}
return value as Duration;
}
shouldLog(args: PublicShouldLogParams, async = true): boolean {
if (this.collectLoggerNames) {
const record = () => this.loggerAggregator?.record(args.loggerName, args.desiredLevel);
if (async) {
setTimeout(record);
} else {
record();
}
}
return shouldLog({ ...args, get: this.get.bind(this) });
}
getLogLevel(_loggerName: string): LogLevel {
const value = this.get(this._loggerKey);
if (value && typeof value === "string") {
const upperValue = value.toUpperCase();
if (upperValue in LogLevel) {
return LogLevel[upperValue as keyof typeof LogLevel];
}
}
// Default to DEBUG if no config found or invalid value
return LogLevel.DEBUG;
}
isCollectingEvaluationSummaries(): boolean {
return this.collectEvaluationSummaries;
}
isCollectingLoggerNames(): boolean {
return this.collectLoggerNames;
}
}
export const reforge = new Reforge();
// Re-export prefetchReforgeConfig for backwards compatibility
export { prefetchReforgeConfig } from "./prefetch";
export type { PrefetchParams } from "./prefetch";