-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathmetrics.ts
419 lines (359 loc) · 10.2 KB
/
metrics.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
import { EventEmitter } from 'events';
import { post } from './request';
import { CustomHeaders, CustomHeadersFunction } from './headers';
import { sdkVersion } from './details.json';
import { HttpOptions } from './http-options';
import { suffixSlash, resolveUrl } from './url-utils';
import { UnleashEvents } from './events';
import { getAppliedJitter } from './helpers';
import { SUPPORTED_SPEC_VERSION } from './repository';
export interface MetricsOptions {
appName: string;
instanceId: string;
connectionId: string;
strategies: string[];
metricsInterval: number;
metricsJitter?: number;
disableMetrics?: boolean;
url: string;
headers?: CustomHeaders;
customHeadersFunction?: CustomHeadersFunction;
timeout?: number;
httpOptions?: HttpOptions;
}
interface VariantBucket {
[s: string]: number;
}
interface Bucket {
start: Date;
stop?: Date;
toggles: { [s: string]: { yes: number; no: number; variants: VariantBucket } };
}
declare var Bun:
| {
version: string;
}
| undefined;
declare var Deno:
| {
version: {
deno: string;
};
}
| undefined;
type PlatformName = 'bun' | 'deno' | 'node' | 'unknown';
type PlatformData = {
name: PlatformName;
version: string;
};
interface BaseMetricsData {
appName: string;
instanceId: string;
connectionId: string;
platformName: PlatformName;
platformVersion: string;
yggdrasilVersion: null;
specVersion: string;
}
interface MetricsData extends BaseMetricsData {
bucket: Bucket;
}
interface RegistrationData extends BaseMetricsData {
sdkVersion: string;
strategies: string[];
started: Date;
interval: number;
}
export default class Metrics extends EventEmitter {
private bucket: Bucket;
private appName: string;
private instanceId: string;
private connectionId: string;
private sdkVersion: string;
private strategies: string[];
private metricsInterval: number;
private metricsJitter: number;
private failures: number = 0;
private disabled: boolean;
private url: string;
private timer: NodeJS.Timeout | undefined;
private started: Date;
private headers?: CustomHeaders;
private customHeadersFunction?: CustomHeadersFunction;
private timeout?: number;
private httpOptions?: HttpOptions;
private platformData: PlatformData;
constructor({
appName,
instanceId,
connectionId,
strategies,
metricsInterval = 0,
metricsJitter = 0,
disableMetrics = false,
url,
headers,
customHeadersFunction,
timeout,
httpOptions,
}: MetricsOptions) {
super();
this.disabled = disableMetrics;
this.metricsInterval = metricsInterval;
this.metricsJitter = metricsJitter;
this.appName = appName;
this.instanceId = instanceId;
this.connectionId = connectionId;
this.sdkVersion = sdkVersion;
this.strategies = strategies;
this.url = url;
this.headers = headers;
this.customHeadersFunction = customHeadersFunction;
this.started = new Date();
this.timeout = timeout;
this.bucket = this.createBucket();
this.httpOptions = httpOptions;
this.platformData = this.getPlatformData();
}
private getAppliedJitter(): number {
return getAppliedJitter(this.metricsJitter);
}
getFailures(): number {
return this.failures;
}
getInterval(): number {
if (this.metricsInterval === 0) {
return 0;
} else {
return this.metricsInterval + this.failures * this.metricsInterval + this.getAppliedJitter();
}
}
private startTimer(): void {
if (this.disabled || this.getInterval() === 0) {
return;
}
this.timer = setTimeout(() => {
this.sendMetrics();
}, this.getInterval());
if (process.env.NODE_ENV !== 'test' && typeof this.timer.unref === 'function') {
this.timer.unref();
}
}
start(): void {
if (this.metricsInterval > 0) {
this.startTimer();
this.registerInstance();
}
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
delete this.timer;
}
this.disabled = true;
}
async registerInstance(): Promise<boolean> {
if (this.disabled) {
return false;
}
const url = resolveUrl(suffixSlash(this.url), './client/register');
const payload = this.getClientData();
const headers = this.customHeadersFunction ? await this.customHeadersFunction() : this.headers;
try {
const res = await post({
url,
json: payload,
appName: this.appName,
instanceId: this.instanceId,
connectionId: this.connectionId,
headers,
timeout: this.timeout,
httpOptions: this.httpOptions,
});
if (!res.ok) {
// status code outside 200 range
this.emit(UnleashEvents.Warn, `${url} returning ${res.status}`, await res.text());
} else {
this.emit(UnleashEvents.Registered, payload);
}
} catch (err) {
this.emit(UnleashEvents.Warn, err);
}
return true;
}
configurationError(url: string, statusCode: number) {
this.emit(UnleashEvents.Warn, `${url} returning ${statusCode}, stopping metrics`);
this.metricsInterval = 0;
this.stop();
}
backoff(url: string, statusCode: number): void {
this.failures = Math.min(10, this.failures + 1);
// eslint-disable-next-line max-len
this.emit(
UnleashEvents.Warn,
`${url} returning ${statusCode}. Backing off to ${this.failures} times normal interval`,
);
this.startTimer();
}
async sendMetrics(): Promise<void> {
if (this.disabled) {
return;
}
if (this.bucketIsEmpty()) {
this.resetBucket();
this.startTimer();
return;
}
const url = resolveUrl(suffixSlash(this.url), './client/metrics');
const payload = this.createMetricsData();
const headers = this.customHeadersFunction ? await this.customHeadersFunction() : this.headers;
try {
const res = await post({
url,
json: payload,
appName: this.appName,
instanceId: this.instanceId,
connectionId: this.connectionId,
interval: this.metricsInterval,
headers,
timeout: this.timeout,
httpOptions: this.httpOptions,
});
if (!res.ok) {
if (res.status === 403 || res.status == 401) {
this.configurationError(url, res.status);
} else if (
res.status === 404 ||
res.status === 429 ||
res.status === 500 ||
res.status === 502 ||
res.status === 503 ||
res.status === 504
) {
this.backoff(url, res.status);
}
this.restoreBucket(payload.bucket);
} else {
this.emit(UnleashEvents.Sent, payload);
this.reduceBackoff();
}
} catch (err) {
this.restoreBucket(payload.bucket);
this.emit(UnleashEvents.Warn, err);
this.startTimer();
}
}
reduceBackoff(): void {
this.failures = Math.max(0, this.failures - 1);
this.startTimer();
}
assertBucket(name: string): void {
if (this.disabled) {
return;
}
if (!this.bucket.toggles[name]) {
this.bucket.toggles[name] = {
yes: 0,
no: 0,
variants: {},
};
}
}
count(name: string, enabled: boolean): void {
if (this.disabled) {
return;
}
this.increaseCounter(name, enabled, 1);
this.emit(UnleashEvents.Count, name, enabled);
}
countVariant(name: string, variantName: string): void {
if (this.disabled) {
return;
}
this.increaseVariantCounter(name, variantName, 1);
this.emit(UnleashEvents.CountVariant, name, variantName);
}
private increaseCounter(name: string, enabled: boolean, inc = 1): void {
if (inc === 0) {
return;
}
this.assertBucket(name);
this.bucket.toggles[name][enabled ? 'yes' : 'no'] += inc;
}
private increaseVariantCounter(name: string, variantName: string, inc = 1): void {
this.assertBucket(name);
if (this.bucket.toggles[name].variants[variantName]) {
this.bucket.toggles[name].variants[variantName] += inc;
} else {
this.bucket.toggles[name].variants[variantName] = inc;
}
}
private bucketIsEmpty(): boolean {
return Object.keys(this.bucket.toggles).length === 0;
}
private createBucket(): Bucket {
return {
start: new Date(),
stop: undefined,
toggles: {},
};
}
private resetBucket(): void {
this.bucket = this.createBucket();
}
createMetricsData(): MetricsData {
const bucket = { ...this.bucket, stop: new Date() };
this.resetBucket();
return {
appName: this.appName,
instanceId: this.instanceId,
connectionId: this.connectionId,
bucket,
platformName: this.platformData.name,
platformVersion: this.platformData.version,
yggdrasilVersion: null,
specVersion: SUPPORTED_SPEC_VERSION,
};
}
private restoreBucket(bucket: Bucket): void {
if (this.disabled) {
return;
}
this.bucket.start = bucket.start;
const { toggles } = bucket;
Object.keys(toggles).forEach((toggleName) => {
const toggle = toggles[toggleName];
this.increaseCounter(toggleName, true, toggle.yes);
this.increaseCounter(toggleName, false, toggle.no);
Object.keys(toggle.variants).forEach((variant) => {
this.increaseVariantCounter(toggleName, variant, toggle.variants[variant]);
});
});
}
getClientData(): RegistrationData {
return {
appName: this.appName,
instanceId: this.instanceId,
sdkVersion: this.sdkVersion,
strategies: this.strategies,
started: this.started,
interval: this.metricsInterval,
connectionId: this.connectionId,
platformName: this.platformData.name,
platformVersion: this.platformData.version,
yggdrasilVersion: null,
specVersion: SUPPORTED_SPEC_VERSION,
};
}
private getPlatformData(): PlatformData {
if (typeof Bun !== 'undefined') {
return { name: 'bun', version: Bun.version };
} else if (typeof Deno !== 'undefined') {
return { name: 'deno', version: Deno.version.deno };
} else if (typeof process !== 'undefined' && process.versions && process.versions.node) {
return { name: 'node', version: process.versions.node };
} else {
return { name: 'unknown', version: 'unknown' };
}
}
}