-
Notifications
You must be signed in to change notification settings - Fork 1
/
telemetry.ts
57 lines (49 loc) · 1.63 KB
/
telemetry.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
export type InstrumentBaggage = Record<string, unknown>;
export interface Instrumentable {
readonly mark: () => PerformanceMark;
readonly measure: () => Instrument;
readonly baggage?: InstrumentBaggage;
}
export interface Instrument extends Instrumentable {
readonly performanceMeasure: PerformanceMeasure;
}
export type InstrumentIdentity = string;
export interface InstrumentationOptions {
readonly identity?: InstrumentIdentity;
readonly baggage?: InstrumentBaggage;
}
export interface Instrumentation {
readonly instruments: Instrument[];
readonly prepareInstrument: (
options?: InstrumentationOptions,
) => Instrumentable;
}
export class Telemetry implements Instrumentation {
readonly instruments: Instrument[] = [];
constructor(readonly prefix?: InstrumentIdentity) {
}
prepareInstrument(options?: InstrumentationOptions): Instrumentable {
const identity = options?.identity ||
`instrument_${this.instruments.length}`;
const name = this.prefix ? `${this.prefix}${identity}` : identity;
const mark = performance.mark(identity, { detail: options?.baggage });
const result: Instrumentable = {
mark: () => mark,
measure: () => {
const performanceMeasure = performance.measure(name, {
detail: options?.baggage,
start: mark.startTime,
});
const instrument = {
...result,
performanceMeasure,
};
this.instruments.push(instrument);
return instrument;
},
baggage: options?.baggage,
};
result.mark();
return result; // it's the responsibility of the caller to later call result.measure()
}
}