@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/host/console.d.ts +80 -0
- package/dist/host/console.js +188 -0
- package/dist/host/mod.d.ts +15 -0
- package/dist/host/mod.js +16 -0
- package/dist/host/otel.d.ts +280 -0
- package/dist/host/otel.js +848 -0
- package/dist/mod.d.ts +17 -0
- package/dist/mod.js +18 -0
- package/dist/otel.d.ts +365 -0
- package/dist/otel.js +686 -0
- package/dist/otlp.d.ts +83 -0
- package/dist/otlp.js +634 -0
- package/dist/render.d.ts +111 -0
- package/dist/render.js +368 -0
- package/dist/signals.d.ts +371 -0
- package/dist/signals.js +800 -0
- package/package.json +76 -4
- package/src/host/console.ts +253 -0
- package/src/host/mod.ts +16 -0
- package/src/host/otel.ts +1068 -0
- package/src/mod.ts +18 -0
- package/src/otel.ts +919 -0
- package/src/otlp.ts +721 -0
- package/src/render.ts +489 -0
- package/src/signals.ts +1175 -0
package/src/signals.ts
ADDED
|
@@ -0,0 +1,1175 @@
|
|
|
1
|
+
// Spec: 0001-telemetry FR-009
|
|
2
|
+
/**
|
|
3
|
+
* Typed signals and the pipeline they go through (commons 0001-telemetry FR-009 to FR-013). `defineSignals` declares each kind of signal
|
|
4
|
+
* once (a span, a log event, or a counter, up-down counter, gauge or histogram), with its attributes and their types, a log event's
|
|
5
|
+
* severity, a metric's unit and bounds, the attributes that are secret, and its presentation role; emitting a kind that is not declared,
|
|
6
|
+
* an attribute of the wrong type or a missing required attribute does not compile. `createTelemetry` makes the tracer, logger and meter of
|
|
7
|
+
* one resource and scope from what the caller gives (a clock, a source of random bytes, a context manager, a parent), so a span tree is
|
|
8
|
+
* the same every run; it redacts (FR-006), applies the limits (FR-007) and samples (FR-008), and hands every signal, in the order it was
|
|
9
|
+
* made, to its processors: the in-memory one, the simple one and the batch one, whose `forceFlush` and `shutdown` resolve within their
|
|
10
|
+
* time whatever an exporter does.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import { createTelemetry, defineSignals, memoryProcessor } from "./signals.ts";
|
|
15
|
+
* import { ok } from "@intellectual-frontiers/core";
|
|
16
|
+
* const registry = defineSignals({
|
|
17
|
+
* "build.step": { signal: "span", role: "step", attributes: { target: "string", "jobs?": "int" } },
|
|
18
|
+
* "build.files": { signal: "counter", role: "none", unit: "{file}", attributes: { target: "string" } },
|
|
19
|
+
* });
|
|
20
|
+
* const memory = memoryProcessor();
|
|
21
|
+
* let t = 0n;
|
|
22
|
+
* const telemetry = createTelemetry({
|
|
23
|
+
* registry, resource: { attributes: { "service.name": "build" } }, scope: { name: "build" },
|
|
24
|
+
* clock: () => t++, random: (n) => new Uint8Array(n).fill(7), processors: [memory],
|
|
25
|
+
* });
|
|
26
|
+
* telemetry.span("build.step", { target: "site" }, () => {
|
|
27
|
+
* telemetry.add("build.files", 3, { target: "site" });
|
|
28
|
+
* return ok("built");
|
|
29
|
+
* });
|
|
30
|
+
* memory.spans[0]?.status; // { kind: "ok" }
|
|
31
|
+
* ```
|
|
32
|
+
*
|
|
33
|
+
* @module
|
|
34
|
+
*/
|
|
35
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
36
|
+
import { toBase64 } from "@intellectual-frontiers/formats/base64";
|
|
37
|
+
import {
|
|
38
|
+
type AnyValue,
|
|
39
|
+
type Attributes,
|
|
40
|
+
type AttributeValue,
|
|
41
|
+
DEFAULT_HISTOGRAM_BOUNDS,
|
|
42
|
+
DEFAULT_LIMITS,
|
|
43
|
+
DEFAULT_SAMPLER,
|
|
44
|
+
formatTraceparent,
|
|
45
|
+
formatTracestate,
|
|
46
|
+
type HistogramPoint,
|
|
47
|
+
type Limits,
|
|
48
|
+
limitAttributes,
|
|
49
|
+
type LogRecord,
|
|
50
|
+
mergeAttributes,
|
|
51
|
+
type Metric,
|
|
52
|
+
type NumberPoint,
|
|
53
|
+
redactAnyValue,
|
|
54
|
+
redactAttributes,
|
|
55
|
+
type Resource,
|
|
56
|
+
SAMPLED,
|
|
57
|
+
type Sampler,
|
|
58
|
+
type Scope,
|
|
59
|
+
type SeverityNumber,
|
|
60
|
+
severityText,
|
|
61
|
+
shouldSample,
|
|
62
|
+
type SignalName,
|
|
63
|
+
type SpanContext,
|
|
64
|
+
type SpanData,
|
|
65
|
+
type SpanEvent,
|
|
66
|
+
type SpanId,
|
|
67
|
+
spanIdFrom,
|
|
68
|
+
type SpanKind,
|
|
69
|
+
type SpanLink,
|
|
70
|
+
type SpanStatus,
|
|
71
|
+
type TraceId,
|
|
72
|
+
traceIdFrom,
|
|
73
|
+
type TraceState,
|
|
74
|
+
} from "./otel.ts";
|
|
75
|
+
import { countSignals, type LogBatch, type MetricBatch, type TraceBatch } from "./otlp.ts";
|
|
76
|
+
|
|
77
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
78
|
+
// The registry (FR-009)
|
|
79
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
80
|
+
|
|
81
|
+
/** The type of a declared attribute. `int` takes a `number` (cut to an integer) or a `bigint`, and is written as an OTLP integer. */
|
|
82
|
+
export type AttributeType = "string" | "boolean" | "int" | "double" | "bytes" | "string[]" | "boolean[]" | "int[]" | "double[]";
|
|
83
|
+
|
|
84
|
+
/** The attributes a kind declares: a name (ending in `?` where it is optional) to its type. */
|
|
85
|
+
export type AttributeSchema = Readonly<Record<string, AttributeType>>;
|
|
86
|
+
|
|
87
|
+
/** The value an attribute of a type takes. */
|
|
88
|
+
export type AttributeValueOf = {
|
|
89
|
+
readonly string: string;
|
|
90
|
+
readonly boolean: boolean;
|
|
91
|
+
readonly int: number | bigint;
|
|
92
|
+
readonly double: number;
|
|
93
|
+
readonly bytes: Uint8Array;
|
|
94
|
+
readonly "string[]": readonly string[];
|
|
95
|
+
readonly "boolean[]": readonly boolean[];
|
|
96
|
+
readonly "int[]": readonly (number | bigint)[];
|
|
97
|
+
readonly "double[]": readonly number[];
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
type Simplify<T> = { [K in keyof T]: T[K] } & {};
|
|
101
|
+
|
|
102
|
+
/** The attributes object a schema asks for: its required names, and its optional ones (declared with `?`) without the `?`. */
|
|
103
|
+
export type AttributesFor<S extends AttributeSchema> = Simplify<
|
|
104
|
+
{ readonly [K in keyof S & string as K extends `${string}?` ? never : K]: AttributeValueOf[S[K]] } & {
|
|
105
|
+
readonly [K in keyof S & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[S[K]];
|
|
106
|
+
}
|
|
107
|
+
>;
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* How a kind is presented to a person: the renderer shows every role but `none`. `pending` (⏳, not set up yet) and `action` (⚡, a step
|
|
111
|
+
* that is the person's to take) are neither warnings nor errors (FR-027).
|
|
112
|
+
*/
|
|
113
|
+
export type Role = "step" | "detail" | "progress" | "result" | "hint" | "warning" | "error" | "pending" | "action" | "none";
|
|
114
|
+
|
|
115
|
+
type Common = {
|
|
116
|
+
/** The kind's attributes and their types. */
|
|
117
|
+
readonly attributes: AttributeSchema;
|
|
118
|
+
/** How a renderer presents it. */
|
|
119
|
+
readonly role: Role;
|
|
120
|
+
/** What the kind is, for a reader of the registry. */
|
|
121
|
+
readonly description?: string;
|
|
122
|
+
/** Attributes that are secret: never written anywhere (FR-006). */
|
|
123
|
+
readonly secret?: readonly string[];
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** A kind of span; its span kind is `internal` unless said. */
|
|
127
|
+
export type SpanDeclaration = Common & { readonly signal: "span"; readonly spanKind?: SpanKind };
|
|
128
|
+
|
|
129
|
+
/** A kind of log event, with its severity. */
|
|
130
|
+
export type LogDeclaration = Common & { readonly signal: "log"; readonly severity: SeverityNumber };
|
|
131
|
+
|
|
132
|
+
/** A kind of counter (monotonic), up-down counter or gauge, with its unit (UCUM, as `ms`, `By`, `{file}`). */
|
|
133
|
+
export type InstrumentDeclaration = Common & { readonly signal: "counter" | "updown" | "gauge"; readonly unit: string };
|
|
134
|
+
|
|
135
|
+
/** A kind of histogram, with its unit and, optionally, its explicit bucket bounds (OpenTelemetry's defaults otherwise). */
|
|
136
|
+
export type HistogramDeclaration = Common & { readonly signal: "histogram"; readonly unit: string; readonly bounds?: readonly number[] };
|
|
137
|
+
|
|
138
|
+
/** The declaration of one kind of signal. */
|
|
139
|
+
export type SignalDeclaration = SpanDeclaration | LogDeclaration | InstrumentDeclaration | HistogramDeclaration;
|
|
140
|
+
|
|
141
|
+
/** What a declaration declares: `span`, `log`, `counter`, `updown`, `gauge` or `histogram`. */
|
|
142
|
+
export type SignalType = SignalDeclaration["signal"];
|
|
143
|
+
|
|
144
|
+
/** The declarations of a registry, by kind name. */
|
|
145
|
+
export type Declarations = Readonly<Record<string, SignalDeclaration>>;
|
|
146
|
+
|
|
147
|
+
/** A registry of signal kinds, made by `defineSignals`. */
|
|
148
|
+
export type Registry<R extends Declarations> = { readonly kinds: R };
|
|
149
|
+
|
|
150
|
+
/** The names of the kinds of a registry's declarations that declare one of the signal types `S`. */
|
|
151
|
+
export type KindOf<R extends Declarations, S extends SignalType> = {
|
|
152
|
+
[K in keyof R & string]: R[K]["signal"] extends S ? K : never;
|
|
153
|
+
}[keyof R & string];
|
|
154
|
+
|
|
155
|
+
/** The attributes object a kind asks for. */
|
|
156
|
+
export type AttributesOf<R extends Declarations, K extends keyof R> = AttributesFor<R[K]["attributes"]>;
|
|
157
|
+
|
|
158
|
+
const ATTRIBUTE_TYPES: ReadonlySet<string> = new Set([
|
|
159
|
+
"string",
|
|
160
|
+
"boolean",
|
|
161
|
+
"int",
|
|
162
|
+
"double",
|
|
163
|
+
"bytes",
|
|
164
|
+
"string[]",
|
|
165
|
+
"boolean[]",
|
|
166
|
+
"int[]",
|
|
167
|
+
"double[]",
|
|
168
|
+
]);
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* A registry of signal kinds (FR-009). The declarations are checked once here, and a mistake in them is a programming error that throws:
|
|
172
|
+
* an attribute type that does not exist, a secret attribute that is not declared, histogram bounds that do not increase.
|
|
173
|
+
*/
|
|
174
|
+
export function defineSignals<const R extends Declarations>(kinds: R): Registry<R> {
|
|
175
|
+
for (const [name, d] of Object.entries(kinds)) {
|
|
176
|
+
const declared = new Set(Object.keys(d.attributes).map((k) => k.replace(/\?$/, "")));
|
|
177
|
+
for (const [k, t] of Object.entries(d.attributes)) {
|
|
178
|
+
if (!ATTRIBUTE_TYPES.has(t)) throw new Error(`${name}: the attribute ${k} has the type ${t}, which does not exist`);
|
|
179
|
+
}
|
|
180
|
+
for (const s of d.secret ?? []) if (!declared.has(s)) throw new Error(`${name}: the secret attribute ${s} is not declared`);
|
|
181
|
+
if (d.signal === "histogram" && d.bounds !== undefined) {
|
|
182
|
+
const b = d.bounds;
|
|
183
|
+
if (b.some((x, i) => !Number.isFinite(x) || (i > 0 && x <= (b[i - 1] ?? -Infinity)))) {
|
|
184
|
+
throw new Error(`${name}: the histogram bounds do not increase`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return { kinds };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The presentation role of a kind, by its name (a span's name, a log record's `eventName`, a metric's name); undefined where not declared. */
|
|
192
|
+
export function roleOf(registry: Registry<Declarations>, name: string): Role | undefined {
|
|
193
|
+
return Object.hasOwn(registry.kinds, name) ? registry.kinds[name]?.role : undefined;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** The declaration of a kind, by its name; undefined where not declared. */
|
|
197
|
+
export function declarationOf(registry: Registry<Declarations>, name: string): SignalDeclaration | undefined {
|
|
198
|
+
return Object.hasOwn(registry.kinds, name) ? registry.kinds[name] : undefined;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
202
|
+
// Context (FR-010, FR-011)
|
|
203
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
/** Where the current span's context is kept: a synchronous stack here, `AsyncLocalStorage` in the runtime. */
|
|
206
|
+
export interface ContextManager {
|
|
207
|
+
/** The current context, if any. */
|
|
208
|
+
active(): SpanContext | undefined;
|
|
209
|
+
/** Runs `fn` with `context` current, and restores the previous one after it returns or throws. */
|
|
210
|
+
with<T>(context: SpanContext | undefined, fn: () => T): T;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* A context manager on a synchronous stack: correct for synchronous code and up to the first `await` of an asynchronous function. Past it,
|
|
215
|
+
* use the span handle's own `span` and `log`, which name their parent, or the runtime's `AsyncLocalStorage` manager.
|
|
216
|
+
*/
|
|
217
|
+
export function stackContextManager(): ContextManager {
|
|
218
|
+
let current: SpanContext | undefined;
|
|
219
|
+
return {
|
|
220
|
+
active: () => current,
|
|
221
|
+
with<T>(context: SpanContext | undefined, fn: () => T): T {
|
|
222
|
+
const previous = current;
|
|
223
|
+
current = context;
|
|
224
|
+
try {
|
|
225
|
+
return fn();
|
|
226
|
+
} finally {
|
|
227
|
+
current = previous;
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
234
|
+
// Processors and exporters (FR-012)
|
|
235
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
236
|
+
|
|
237
|
+
/** The resource and scope a signal came from; one object per telemetry, so a processor may group by it. */
|
|
238
|
+
export type Source = { readonly resource: Resource; readonly scope: Scope };
|
|
239
|
+
|
|
240
|
+
/** A span as it starts: what a renderer needs to show it in progress. */
|
|
241
|
+
export type SpanStart = {
|
|
242
|
+
readonly name: string;
|
|
243
|
+
readonly context: SpanContext;
|
|
244
|
+
readonly parentSpanId?: SpanId;
|
|
245
|
+
readonly kind: SpanKind;
|
|
246
|
+
readonly startTime: bigint;
|
|
247
|
+
readonly attributes: Attributes;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
/** How a flush or a shutdown ended: everything handed on, or the time given ran out. */
|
|
251
|
+
export type FlushResult = { readonly kind: "done" } | { readonly kind: "timeout" };
|
|
252
|
+
|
|
253
|
+
/** What a pipeline hands its signals to, in the order they were made. */
|
|
254
|
+
export interface Processor {
|
|
255
|
+
/** A span started. */
|
|
256
|
+
onStart?(span: SpanStart, source: Source): void;
|
|
257
|
+
/** A span in progress recorded an event (`progress` among them). */
|
|
258
|
+
onEvent?(span: SpanStart, event: SpanEvent, source: Source): void;
|
|
259
|
+
/** A span ended. */
|
|
260
|
+
onEnd?(span: SpanData, source: Source): void;
|
|
261
|
+
/** A log record was emitted. */
|
|
262
|
+
onLog?(record: LogRecord, source: Source): void;
|
|
263
|
+
/** Metrics were collected. */
|
|
264
|
+
onMetrics?(metrics: readonly Metric[], source: Source): void;
|
|
265
|
+
/** Hands on everything held, within `timeoutMs`. */
|
|
266
|
+
forceFlush(timeoutMs: number): Promise<FlushResult>;
|
|
267
|
+
/** Hands on everything held and stops, within `timeoutMs`. */
|
|
268
|
+
shutdown(timeoutMs: number): Promise<FlushResult>;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** How an export went. `partial`: the receiver rejected some signals. */
|
|
272
|
+
export type ExportResult =
|
|
273
|
+
| { readonly kind: "success" }
|
|
274
|
+
| { readonly kind: "partial"; readonly rejected: number; readonly message: string }
|
|
275
|
+
| { readonly kind: "failure"; readonly message: string };
|
|
276
|
+
|
|
277
|
+
/** What sends batches somewhere (the runtime's OTLP/HTTP exporter, a test's fake). It may be slow, fail or never answer. */
|
|
278
|
+
export interface Exporter {
|
|
279
|
+
/** Sends trace batches. */
|
|
280
|
+
exportTraces(batches: readonly TraceBatch[]): Promise<ExportResult>;
|
|
281
|
+
/** Sends log batches. */
|
|
282
|
+
exportLogs(batches: readonly LogBatch[]): Promise<ExportResult>;
|
|
283
|
+
/** Sends metric batches. */
|
|
284
|
+
exportMetrics(batches: readonly MetricBatch[]): Promise<ExportResult>;
|
|
285
|
+
/** Stops, within `timeoutMs`. */
|
|
286
|
+
shutdown(timeoutMs: number): Promise<void>;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** What a processor did with one signal: spans, log records or metric data points exported, failed, rejected by a partial success, or dropped. */
|
|
290
|
+
export type SignalStats = {
|
|
291
|
+
readonly exported: number;
|
|
292
|
+
readonly failed: number;
|
|
293
|
+
readonly rejected: number;
|
|
294
|
+
readonly dropped: number;
|
|
295
|
+
readonly lastError?: string;
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
/** What an exporting processor did, by signal. */
|
|
299
|
+
export type ProcessorStats = { readonly [S in SignalName]: SignalStats };
|
|
300
|
+
|
|
301
|
+
/** A processor that exports, and says what it did. */
|
|
302
|
+
export type ExportingProcessor = Processor & { stats(): ProcessorStats };
|
|
303
|
+
|
|
304
|
+
/** A recorded signal, in the order the memory processor received it. */
|
|
305
|
+
export type MemoryEntry =
|
|
306
|
+
| { readonly kind: "start"; readonly span: SpanStart; readonly source: Source }
|
|
307
|
+
| { readonly kind: "event"; readonly span: SpanStart; readonly event: SpanEvent; readonly source: Source }
|
|
308
|
+
| { readonly kind: "end"; readonly span: SpanData; readonly source: Source }
|
|
309
|
+
| { readonly kind: "log"; readonly record: LogRecord; readonly source: Source }
|
|
310
|
+
| { readonly kind: "metrics"; readonly metrics: readonly Metric[]; readonly source: Source };
|
|
311
|
+
|
|
312
|
+
/** A processor that keeps everything, for tests and the renderer. */
|
|
313
|
+
export type MemoryProcessor = Processor & {
|
|
314
|
+
/** Every signal, in order. */
|
|
315
|
+
readonly entries: readonly MemoryEntry[];
|
|
316
|
+
/** The finished spans, in the order they ended. */
|
|
317
|
+
readonly spans: readonly SpanData[];
|
|
318
|
+
/** The log records, in order. */
|
|
319
|
+
readonly logs: readonly LogRecord[];
|
|
320
|
+
/** The metric collections, in order. */
|
|
321
|
+
readonly metrics: readonly (readonly Metric[])[];
|
|
322
|
+
/** Forgets everything kept. */
|
|
323
|
+
clear(): void;
|
|
324
|
+
};
|
|
325
|
+
|
|
326
|
+
/** A processor that keeps every signal it receives (FR-012). */
|
|
327
|
+
export function memoryProcessor(): MemoryProcessor {
|
|
328
|
+
const entries: MemoryEntry[] = [];
|
|
329
|
+
const done = (): Promise<FlushResult> => Promise.resolve({ kind: "done" });
|
|
330
|
+
return {
|
|
331
|
+
onStart: (span, source) => void entries.push({ kind: "start", span, source }),
|
|
332
|
+
onEvent: (span, event, source) => void entries.push({ kind: "event", span, event, source }),
|
|
333
|
+
onEnd: (span, source) => void entries.push({ kind: "end", span, source }),
|
|
334
|
+
onLog: (record, source) => void entries.push({ kind: "log", record, source }),
|
|
335
|
+
onMetrics: (metrics, source) => void entries.push({ kind: "metrics", metrics, source }),
|
|
336
|
+
forceFlush: done,
|
|
337
|
+
shutdown: done,
|
|
338
|
+
get entries() {
|
|
339
|
+
return entries;
|
|
340
|
+
},
|
|
341
|
+
get spans() {
|
|
342
|
+
return entries.flatMap((e) => (e.kind === "end" ? [e.span] : []));
|
|
343
|
+
},
|
|
344
|
+
get logs() {
|
|
345
|
+
return entries.flatMap((e) => (e.kind === "log" ? [e.record] : []));
|
|
346
|
+
},
|
|
347
|
+
get metrics() {
|
|
348
|
+
return entries.flatMap((e) => (e.kind === "metrics" ? [e.metrics] : []));
|
|
349
|
+
},
|
|
350
|
+
clear: () => void entries.splice(0),
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** A timer, so that a batch processor's schedule can be driven by a test. */
|
|
355
|
+
export type Timer = { readonly set: (fn: () => void, ms: number) => unknown; readonly clear: (handle: unknown) => void };
|
|
356
|
+
|
|
357
|
+
/** The host's timer; a scheduled export never keeps a process alive (`unref` where the host has it). */
|
|
358
|
+
export const systemTimer: Timer = {
|
|
359
|
+
set: (fn, ms) => {
|
|
360
|
+
const handle: unknown = setTimeout(fn, ms);
|
|
361
|
+
const unref: unknown = typeof handle === "object" && handle !== null ? Reflect.get(handle, "unref") : undefined;
|
|
362
|
+
if (typeof unref === "function") Reflect.apply(unref, handle, []);
|
|
363
|
+
return handle;
|
|
364
|
+
},
|
|
365
|
+
// The handle is what `setTimeout` gave; its type differs between the DOM and Node.
|
|
366
|
+
clear: (handle) => clearTimeout(handle as Parameters<typeof clearTimeout>[0]),
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
/** A promise's value, or `undefined` once `ms` have passed, whichever comes first; the timer is cleared either way. */
|
|
370
|
+
async function within<T>(promise: Promise<T>, ms: number): Promise<{ readonly value: T } | undefined> {
|
|
371
|
+
let handle: ReturnType<typeof setTimeout> | undefined;
|
|
372
|
+
const timeout = new Promise<undefined>((resolve) => {
|
|
373
|
+
handle = setTimeout(() => resolve(undefined), Math.max(0, ms));
|
|
374
|
+
});
|
|
375
|
+
try {
|
|
376
|
+
return await Promise.race([promise.then((value) => ({ value })), timeout]);
|
|
377
|
+
} finally {
|
|
378
|
+
clearTimeout(handle);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function describeThrown(e: unknown): string {
|
|
383
|
+
return e instanceof Error ? e.message : String(e);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
type MutableStats = { exported: number; failed: number; rejected: number; dropped: number; lastError?: string };
|
|
387
|
+
|
|
388
|
+
function newStats(): { [S in SignalName]: MutableStats } {
|
|
389
|
+
const one = (): MutableStats => ({ exported: 0, failed: 0, rejected: 0, dropped: 0 });
|
|
390
|
+
return { traces: one(), logs: one(), metrics: one() };
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
function snapshot(stats: { [S in SignalName]: MutableStats }): ProcessorStats {
|
|
394
|
+
return { traces: { ...stats.traces }, logs: { ...stats.logs }, metrics: { ...stats.metrics } };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** The exports of a processor: one at a time, in order, each within its timeout, never throwing, counted. */
|
|
398
|
+
function exportQueue(exportTimeoutMs: number) {
|
|
399
|
+
const stats = newStats();
|
|
400
|
+
let tail: Promise<void> = Promise.resolve();
|
|
401
|
+
const send = async (signal: SignalName, count: number, run: () => Promise<ExportResult>): Promise<void> => {
|
|
402
|
+
const s = stats[signal];
|
|
403
|
+
let result: ExportResult;
|
|
404
|
+
try {
|
|
405
|
+
const r = await within(run(), exportTimeoutMs);
|
|
406
|
+
result = r === undefined ? { kind: "failure", message: `the export took more than ${exportTimeoutMs} ms` } : r.value;
|
|
407
|
+
} catch (e) {
|
|
408
|
+
result = { kind: "failure", message: describeThrown(e) };
|
|
409
|
+
}
|
|
410
|
+
switch (result.kind) {
|
|
411
|
+
case "success":
|
|
412
|
+
s.exported += count;
|
|
413
|
+
return;
|
|
414
|
+
case "partial":
|
|
415
|
+
s.exported += count - result.rejected;
|
|
416
|
+
s.rejected += result.rejected;
|
|
417
|
+
s.lastError = result.message;
|
|
418
|
+
return;
|
|
419
|
+
case "failure":
|
|
420
|
+
s.failed += count;
|
|
421
|
+
s.lastError = result.message;
|
|
422
|
+
return;
|
|
423
|
+
default:
|
|
424
|
+
absurd(result);
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
return {
|
|
428
|
+
stats,
|
|
429
|
+
/** Sends one export now. */
|
|
430
|
+
send,
|
|
431
|
+
/** Queues an export after those already queued. */
|
|
432
|
+
push(signal: SignalName, count: number, run: () => Promise<ExportResult>): void {
|
|
433
|
+
tail = tail.then(() => send(signal, count, run));
|
|
434
|
+
},
|
|
435
|
+
/** Settles when every export queued so far has. */
|
|
436
|
+
idle: (): Promise<void> => tail,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function byTraceBatch(items: readonly { readonly span: SpanData; readonly source: Source }[]): TraceBatch[] {
|
|
441
|
+
const out = new Map<Source, SpanData[]>();
|
|
442
|
+
for (const i of items) out.set(i.source, [...(out.get(i.source) ?? []), i.span]);
|
|
443
|
+
return [...out].map(([source, spans]) => ({ resource: source.resource, scope: source.scope, spans }));
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function byLogBatch(items: readonly { readonly record: LogRecord; readonly source: Source }[]): LogBatch[] {
|
|
447
|
+
const out = new Map<Source, LogRecord[]>();
|
|
448
|
+
for (const i of items) out.set(i.source, [...(out.get(i.source) ?? []), i.record]);
|
|
449
|
+
return [...out].map(([source, records]) => ({ resource: source.resource, scope: source.scope, records }));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function shutdownWithin(flushed: Promise<FlushResult>, exporter: Exporter, timeoutMs: number): Promise<FlushResult> {
|
|
453
|
+
const started = Date.now();
|
|
454
|
+
const first = await flushed;
|
|
455
|
+
const left = Math.max(0, timeoutMs - (Date.now() - started));
|
|
456
|
+
const stopped = await within(
|
|
457
|
+
exporter.shutdown(left).catch(() => undefined),
|
|
458
|
+
left,
|
|
459
|
+
);
|
|
460
|
+
return first.kind === "done" && stopped !== undefined ? first : { kind: "timeout" };
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** A processor that exports each signal as it comes, one export at a time (FR-012). */
|
|
464
|
+
export function simpleProcessor(exporter: Exporter, options: { readonly exportTimeoutMs?: number } = {}): ExportingProcessor {
|
|
465
|
+
const queue = exportQueue(options.exportTimeoutMs ?? 30000);
|
|
466
|
+
let stopped = false;
|
|
467
|
+
const flush = async (timeoutMs: number): Promise<FlushResult> =>
|
|
468
|
+
(await within(queue.idle(), timeoutMs)) === undefined ? { kind: "timeout" } : { kind: "done" };
|
|
469
|
+
return {
|
|
470
|
+
onEnd: (span, source) => {
|
|
471
|
+
if (stopped) return void queue.stats.traces.dropped++;
|
|
472
|
+
queue.push("traces", 1, () => exporter.exportTraces([{ resource: source.resource, scope: source.scope, spans: [span] }]));
|
|
473
|
+
},
|
|
474
|
+
onLog: (record, source) => {
|
|
475
|
+
if (stopped) return void queue.stats.logs.dropped++;
|
|
476
|
+
queue.push("logs", 1, () => exporter.exportLogs([{ resource: source.resource, scope: source.scope, records: [record] }]));
|
|
477
|
+
},
|
|
478
|
+
onMetrics: (metrics, source) => {
|
|
479
|
+
const batches: MetricBatch[] = [{ resource: source.resource, scope: source.scope, metrics }];
|
|
480
|
+
if (stopped) return void (queue.stats.metrics.dropped += countSignals(batches));
|
|
481
|
+
queue.push("metrics", countSignals(batches), () => exporter.exportMetrics(batches));
|
|
482
|
+
},
|
|
483
|
+
forceFlush: flush,
|
|
484
|
+
shutdown: (timeoutMs) => {
|
|
485
|
+
stopped = true;
|
|
486
|
+
return shutdownWithin(flush(timeoutMs), exporter, timeoutMs);
|
|
487
|
+
},
|
|
488
|
+
stats: () => snapshot(queue.stats),
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** The settings of a batch processor, as `OTEL_BSP_*` and `OTEL_BLRP_*` give them (`BatchConfig` of `./otel.ts`), and its timer. */
|
|
493
|
+
export type BatchOptions = {
|
|
494
|
+
readonly maxQueueSize?: number;
|
|
495
|
+
readonly maxExportBatchSize?: number;
|
|
496
|
+
readonly scheduleDelayMs?: number;
|
|
497
|
+
readonly exportTimeoutMs?: number;
|
|
498
|
+
readonly timer?: Timer;
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* A processor that queues spans and log records (each at most `maxQueueSize`; what does not fit is dropped and counted, never blocking
|
|
503
|
+
* the caller) and exports them in batches of at most `maxExportBatchSize`: as soon as a full batch is waiting, else `scheduleDelayMs` after
|
|
504
|
+
* the first one queued. Metric collections are exported as they come. Exports run one at a time, each within `exportTimeoutMs`, and a
|
|
505
|
+
* batch leaves its queue only when it is sent (FR-012).
|
|
506
|
+
*/
|
|
507
|
+
export function batchProcessor(exporter: Exporter, options: BatchOptions = {}): ExportingProcessor {
|
|
508
|
+
const maxQueueSize = Math.max(1, options.maxQueueSize ?? 2048);
|
|
509
|
+
const maxBatch = Math.max(1, Math.min(options.maxExportBatchSize ?? 512, maxQueueSize));
|
|
510
|
+
const delay = options.scheduleDelayMs ?? 5000;
|
|
511
|
+
const timer = options.timer ?? systemTimer;
|
|
512
|
+
const queue = exportQueue(options.exportTimeoutMs ?? 30000);
|
|
513
|
+
const spans: { readonly span: SpanData; readonly source: Source }[] = [];
|
|
514
|
+
const logs: { readonly record: LogRecord; readonly source: Source }[] = [];
|
|
515
|
+
const metrics: MetricBatch[][] = [];
|
|
516
|
+
let scheduled: { readonly handle: unknown } | undefined;
|
|
517
|
+
let pumping: Promise<void> | undefined;
|
|
518
|
+
let all = false;
|
|
519
|
+
let stopped = false;
|
|
520
|
+
|
|
521
|
+
// The one worker: it takes a batch from a queue only when it is about to send it, so that a slow exporter fills the queues (and what
|
|
522
|
+
// does not fit is dropped) rather than memory.
|
|
523
|
+
const work = async (): Promise<void> => {
|
|
524
|
+
// First let `pump` keep this promise, so that the end below, which runs with no pause after the last check, clears it.
|
|
525
|
+
await Promise.resolve();
|
|
526
|
+
for (;;) {
|
|
527
|
+
if (spans.length > 0 && (all || spans.length >= maxBatch)) {
|
|
528
|
+
const items = spans.splice(0, maxBatch);
|
|
529
|
+
await queue.send("traces", items.length, () => exporter.exportTraces(byTraceBatch(items)));
|
|
530
|
+
} else if (logs.length > 0 && (all || logs.length >= maxBatch)) {
|
|
531
|
+
const items = logs.splice(0, maxBatch);
|
|
532
|
+
await queue.send("logs", items.length, () => exporter.exportLogs(byLogBatch(items)));
|
|
533
|
+
} else {
|
|
534
|
+
const batches = metrics.shift();
|
|
535
|
+
if (batches === undefined) break;
|
|
536
|
+
await queue.send("metrics", countSignals(batches), () => exporter.exportMetrics(batches));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
all = false;
|
|
540
|
+
pumping = undefined;
|
|
541
|
+
if (spans.length > 0 || logs.length > 0) arm();
|
|
542
|
+
};
|
|
543
|
+
const pump = (): Promise<void> => {
|
|
544
|
+
pumping ??= work();
|
|
545
|
+
return pumping;
|
|
546
|
+
};
|
|
547
|
+
const arm = (): void => {
|
|
548
|
+
if (scheduled !== undefined || stopped) return;
|
|
549
|
+
scheduled = {
|
|
550
|
+
handle: timer.set(() => {
|
|
551
|
+
scheduled = undefined;
|
|
552
|
+
all = true;
|
|
553
|
+
void pump();
|
|
554
|
+
}, delay),
|
|
555
|
+
};
|
|
556
|
+
};
|
|
557
|
+
const disarm = (): void => {
|
|
558
|
+
if (scheduled !== undefined) timer.clear(scheduled.handle);
|
|
559
|
+
scheduled = undefined;
|
|
560
|
+
};
|
|
561
|
+
const enqueue = <T>(items: T[], item: T, stats: MutableStats): void => {
|
|
562
|
+
if (stopped || items.length >= maxQueueSize) {
|
|
563
|
+
stats.dropped++;
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
items.push(item);
|
|
567
|
+
if (items.length >= maxBatch) void pump();
|
|
568
|
+
else arm();
|
|
569
|
+
};
|
|
570
|
+
const flush = async (timeoutMs: number): Promise<FlushResult> => {
|
|
571
|
+
disarm();
|
|
572
|
+
all = true;
|
|
573
|
+
const r = await within(pump(), timeoutMs);
|
|
574
|
+
return r === undefined ? { kind: "timeout" } : { kind: "done" };
|
|
575
|
+
};
|
|
576
|
+
return {
|
|
577
|
+
onEnd: (span, source) => enqueue(spans, { span, source }, queue.stats.traces),
|
|
578
|
+
onLog: (record, source) => enqueue(logs, { record, source }, queue.stats.logs),
|
|
579
|
+
onMetrics: (collected, source) => {
|
|
580
|
+
const batches: MetricBatch[] = [{ resource: source.resource, scope: source.scope, metrics: collected }];
|
|
581
|
+
if (stopped || metrics.length >= maxQueueSize) return void (queue.stats.metrics.dropped += countSignals(batches));
|
|
582
|
+
metrics.push(batches);
|
|
583
|
+
void pump();
|
|
584
|
+
},
|
|
585
|
+
forceFlush: flush,
|
|
586
|
+
shutdown: (timeoutMs) => {
|
|
587
|
+
const flushed = flush(timeoutMs);
|
|
588
|
+
stopped = true;
|
|
589
|
+
disarm();
|
|
590
|
+
return shutdownWithin(flushed, exporter, timeoutMs);
|
|
591
|
+
},
|
|
592
|
+
stats: () => snapshot(queue.stats),
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
597
|
+
// Telemetry (FR-010, FR-011, FR-013)
|
|
598
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
599
|
+
|
|
600
|
+
/** A link a new span makes to another span's context. */
|
|
601
|
+
export type LinkInput = {
|
|
602
|
+
readonly traceId: TraceId;
|
|
603
|
+
readonly spanId: SpanId;
|
|
604
|
+
readonly traceFlags: number;
|
|
605
|
+
readonly traceState: TraceState;
|
|
606
|
+
readonly attributes?: Attributes;
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
/** How a span starts: its parent (`null` for a new trace; the current context by default) and its links. */
|
|
610
|
+
export type SpanOptions = { readonly parent?: SpanContext | null; readonly links?: readonly LinkInput[] };
|
|
611
|
+
|
|
612
|
+
/** How one log record is emitted: a severity of its own instead of its kind's (a finding's, say, where one kind has many severities). */
|
|
613
|
+
export type LogOptions = { readonly severity?: SeverityNumber };
|
|
614
|
+
|
|
615
|
+
/** A span in progress, as the function it runs sees it. */
|
|
616
|
+
export interface SpanHandle<R extends Declarations, K extends keyof R> {
|
|
617
|
+
/** The span's context. */
|
|
618
|
+
readonly context: SpanContext;
|
|
619
|
+
/** Whether the span is recorded (sampled, and the telemetry not shut down). */
|
|
620
|
+
readonly recording: boolean;
|
|
621
|
+
/** The W3C `traceparent` to give what this span calls (a child process, an HTTP request). */
|
|
622
|
+
readonly traceparent: string;
|
|
623
|
+
/** The W3C `tracestate` to give with it. */
|
|
624
|
+
readonly tracestate: string;
|
|
625
|
+
/** Sets declared attributes of the span. */
|
|
626
|
+
set(attributes: Partial<AttributesOf<R, K>>): void;
|
|
627
|
+
/** Records an event. */
|
|
628
|
+
event(name: string, attributes?: Attributes): void;
|
|
629
|
+
/** Records how far the work has come, as a `progress` event (`progress.done`, `progress.total`). */
|
|
630
|
+
progress(done: number, total?: number): void;
|
|
631
|
+
/** Runs a child span of this one. */
|
|
632
|
+
span<C extends KindOf<R, "span">, T>(
|
|
633
|
+
kind: C,
|
|
634
|
+
attributes: AttributesOf<R, C>,
|
|
635
|
+
fn: (span: SpanHandle<R, C>) => T,
|
|
636
|
+
options?: SpanOptions,
|
|
637
|
+
): T;
|
|
638
|
+
/** Emits a log record in this span; its severity is the kind's unless `options.severity` gives another. */
|
|
639
|
+
log<L extends KindOf<R, "log">>(kind: L, attributes: AttributesOf<R, L>, body?: AnyValue, options?: LogOptions): void;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** The tracer, logger and meter of one resource and scope, typed by a registry. */
|
|
643
|
+
export interface Telemetry<R extends Declarations> {
|
|
644
|
+
/** The registry the kinds come from. */
|
|
645
|
+
readonly registry: Registry<R>;
|
|
646
|
+
/** The resource and scope every signal carries. */
|
|
647
|
+
readonly source: Source;
|
|
648
|
+
/** The current span's context, or the initial parent, if any. */
|
|
649
|
+
active(): SpanContext | undefined;
|
|
650
|
+
/**
|
|
651
|
+
* Runs `fn` in a new span, the child of the current one (FR-010), and returns what it returns. The span ends once: `ok` for an `Ok`
|
|
652
|
+
* result, `error` with the error's description for an `Err`, unset for any other value (a promise is waited for); a function that
|
|
653
|
+
* throws ends it with an `exception` event and `error`, and the exception is thrown on.
|
|
654
|
+
*/
|
|
655
|
+
span<K extends KindOf<R, "span">, T>(
|
|
656
|
+
kind: K,
|
|
657
|
+
attributes: AttributesOf<R, K>,
|
|
658
|
+
fn: (span: SpanHandle<R, K>) => T,
|
|
659
|
+
options?: SpanOptions,
|
|
660
|
+
): T;
|
|
661
|
+
/** Emits a log record of a kind, in the current span; its `eventName` is the kind, its severity the kind's unless `options.severity` gives another. */
|
|
662
|
+
log<K extends KindOf<R, "log">>(kind: K, attributes: AttributesOf<R, K>, body?: AnyValue, options?: LogOptions): void;
|
|
663
|
+
/** Adds to a counter (a negative or non-finite increment is refused) or an up-down counter. */
|
|
664
|
+
add<K extends KindOf<R, "counter" | "updown">>(kind: K, value: number, attributes: AttributesOf<R, K>): Result<void, string>;
|
|
665
|
+
/** Sets a gauge. */
|
|
666
|
+
set<K extends KindOf<R, "gauge">>(kind: K, value: number, attributes: AttributesOf<R, K>): Result<void, string>;
|
|
667
|
+
/** Records a value in a histogram. */
|
|
668
|
+
record<K extends KindOf<R, "histogram">>(kind: K, value: number, attributes: AttributesOf<R, K>): Result<void, string>;
|
|
669
|
+
/** The metrics as they stand, cumulative since each series began (FR-013), also handed to every processor. */
|
|
670
|
+
collect(): readonly Metric[];
|
|
671
|
+
/** Collects the metrics and flushes every processor, within `timeoutMs`. */
|
|
672
|
+
forceFlush(timeoutMs: number): Promise<FlushResult>;
|
|
673
|
+
/** Ends every open span as `error`, collects the metrics and shuts every processor down, within `timeoutMs`; nothing is recorded after. */
|
|
674
|
+
shutdown(timeoutMs: number): Promise<FlushResult>;
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** What a telemetry is made from (FR-011): everything that varies is the caller's. */
|
|
678
|
+
export type TelemetryOptions<R extends Declarations> = {
|
|
679
|
+
readonly registry: Registry<R>;
|
|
680
|
+
readonly resource: Resource;
|
|
681
|
+
readonly scope: Scope;
|
|
682
|
+
/** Nanoseconds since the Unix epoch. */
|
|
683
|
+
readonly clock: () => bigint;
|
|
684
|
+
/** `n` random bytes. */
|
|
685
|
+
readonly random: (n: number) => Uint8Array;
|
|
686
|
+
readonly processors: readonly Processor[];
|
|
687
|
+
/** A stack by default; the runtime gives `AsyncLocalStorage`. */
|
|
688
|
+
readonly context?: ContextManager;
|
|
689
|
+
/** The parent of a span started with no current span (from `TRACEPARENT`, say). */
|
|
690
|
+
readonly parent?: SpanContext;
|
|
691
|
+
readonly sampler?: Sampler;
|
|
692
|
+
readonly limits?: Limits;
|
|
693
|
+
/** What a processor threw; processors never break the program. */
|
|
694
|
+
readonly onError?: (error: unknown) => void;
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
/** The description of an error for a span's status: a string as it is, an `Error`'s message, an object's `message`, else its JSON. */
|
|
698
|
+
export function describeError(error: unknown): string {
|
|
699
|
+
if (typeof error === "string") return error;
|
|
700
|
+
if (error instanceof Error) return error.message;
|
|
701
|
+
if (typeof error === "object" && error !== null) {
|
|
702
|
+
if ("message" in error && typeof error.message === "string") return error.message;
|
|
703
|
+
try {
|
|
704
|
+
return JSON.stringify(error, (_k, v: unknown) => (typeof v === "bigint" ? v.toString() : v));
|
|
705
|
+
} catch {
|
|
706
|
+
return "an object that cannot be written as JSON";
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return String(error);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function isThenable(value: unknown): value is PromiseLike<unknown> {
|
|
713
|
+
return (
|
|
714
|
+
(typeof value === "object" || typeof value === "function") && value !== null && "then" in value && typeof value.then === "function"
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
function statusOf(value: unknown): SpanStatus {
|
|
719
|
+
if (typeof value !== "object" || value === null || !("kind" in value)) return { kind: "unset" };
|
|
720
|
+
if (value.kind === "ok" && "value" in value) return { kind: "ok" };
|
|
721
|
+
if (value.kind === "err" && "error" in value) return { kind: "error", message: describeError(value.error) };
|
|
722
|
+
return { kind: "unset" };
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
function toInt(v: number | bigint): bigint | undefined {
|
|
726
|
+
if (typeof v === "bigint") return v;
|
|
727
|
+
return Number.isFinite(v) ? BigInt(Math.trunc(v)) : undefined;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/** Typed attributes as OpenTelemetry attributes, by the schema: an `int` as a `bigint`; an undeclared or absent attribute left out. */
|
|
731
|
+
export function toAttributes(schema: AttributeSchema, attributes: object): Attributes {
|
|
732
|
+
const out: Record<string, AttributeValue> = {};
|
|
733
|
+
const given: Readonly<Record<string, unknown>> = { ...attributes };
|
|
734
|
+
for (const [declared, type] of Object.entries(schema)) {
|
|
735
|
+
const name = declared.replace(/\?$/, "");
|
|
736
|
+
const v = given[name];
|
|
737
|
+
if (v === undefined) continue;
|
|
738
|
+
if (type === "int" && (typeof v === "number" || typeof v === "bigint")) {
|
|
739
|
+
const i = toInt(v);
|
|
740
|
+
if (i !== undefined) out[name] = i;
|
|
741
|
+
} else if (type === "int[]" && Array.isArray(v)) {
|
|
742
|
+
out[name] = v.flatMap((e: unknown) => {
|
|
743
|
+
const i = typeof e === "number" || typeof e === "bigint" ? toInt(e) : undefined;
|
|
744
|
+
return i === undefined ? [] : [i];
|
|
745
|
+
});
|
|
746
|
+
} else if (isAttributeValue(v)) out[name] = v;
|
|
747
|
+
}
|
|
748
|
+
return out;
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
function isAttributeValue(v: unknown): v is AttributeValue {
|
|
752
|
+
if (typeof v === "string" || typeof v === "boolean" || typeof v === "bigint" || typeof v === "number" || v instanceof Uint8Array)
|
|
753
|
+
return true;
|
|
754
|
+
if (!Array.isArray(v)) return false;
|
|
755
|
+
const values: readonly unknown[] = v;
|
|
756
|
+
const first = values[0];
|
|
757
|
+
return values.every((e) => typeof e === typeof first && ["string", "boolean", "bigint", "number"].includes(typeof e));
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** A canonical key of attributes, the same for equal sets in any order: one metric series for each (FR-013). */
|
|
761
|
+
export function attributesKey(attributes: Attributes): string {
|
|
762
|
+
const enc = (v: AttributeValue): unknown => {
|
|
763
|
+
if (typeof v === "bigint") return `${v}n`;
|
|
764
|
+
if (v instanceof Uint8Array) return `b64:${toBase64(v)}`;
|
|
765
|
+
if (Array.isArray(v)) return (v as readonly (string | boolean | bigint | number)[]).map((e) => (typeof e === "bigint" ? `${e}n` : e));
|
|
766
|
+
return typeof v === "string" ? `s:${v}` : v;
|
|
767
|
+
};
|
|
768
|
+
return JSON.stringify(
|
|
769
|
+
Object.keys(attributes)
|
|
770
|
+
.sort()
|
|
771
|
+
.map((k) => [k, enc(attributes[k] ?? "")]),
|
|
772
|
+
);
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
type Series = {
|
|
776
|
+
readonly attributes: Attributes;
|
|
777
|
+
readonly startTime: bigint;
|
|
778
|
+
time: bigint;
|
|
779
|
+
value: number;
|
|
780
|
+
count: number;
|
|
781
|
+
sum: number;
|
|
782
|
+
min: number;
|
|
783
|
+
max: number;
|
|
784
|
+
buckets: number[];
|
|
785
|
+
};
|
|
786
|
+
|
|
787
|
+
type Open = {
|
|
788
|
+
readonly start: SpanStart;
|
|
789
|
+
readonly recording: boolean;
|
|
790
|
+
readonly links: readonly SpanLink[];
|
|
791
|
+
readonly droppedLinks: number;
|
|
792
|
+
readonly secret: readonly string[];
|
|
793
|
+
attributes: Attributes;
|
|
794
|
+
droppedAttributes: number;
|
|
795
|
+
readonly events: SpanEvent[];
|
|
796
|
+
droppedEvents: number;
|
|
797
|
+
ended: boolean;
|
|
798
|
+
};
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* The tracer, logger and meter of one resource and scope (FR-010 to FR-013). Every signal is redacted (the kind's secret attributes left
|
|
802
|
+
* out, credentials replaced), limited and handed to each processor in the order it was made. Ids come from `random`, times from `clock`.
|
|
803
|
+
*/
|
|
804
|
+
export function createTelemetry<const R extends Declarations>(options: TelemetryOptions<R>): Telemetry<R> {
|
|
805
|
+
const { registry, clock, random, processors } = options;
|
|
806
|
+
const source: Source = { resource: options.resource, scope: options.scope };
|
|
807
|
+
const context = options.context ?? stackContextManager();
|
|
808
|
+
const sampler = options.sampler ?? DEFAULT_SAMPLER;
|
|
809
|
+
const limits = options.limits ?? DEFAULT_LIMITS;
|
|
810
|
+
const open = new Set<Open>();
|
|
811
|
+
const series = new Map<string, Map<string, Series>>();
|
|
812
|
+
let stopped = false;
|
|
813
|
+
|
|
814
|
+
const each = (f: (p: Processor) => void): void => {
|
|
815
|
+
for (const p of processors) {
|
|
816
|
+
try {
|
|
817
|
+
f(p);
|
|
818
|
+
} catch (e) {
|
|
819
|
+
options.onError?.(e);
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
const declaration = (kind: string): SignalDeclaration => {
|
|
824
|
+
const d = declarationOf(registry, kind);
|
|
825
|
+
if (d === undefined) throw new Error(`the signal kind ${kind} is not declared`);
|
|
826
|
+
return d;
|
|
827
|
+
};
|
|
828
|
+
const newTraceId = (): TraceId => {
|
|
829
|
+
const bytes = random(16);
|
|
830
|
+
const r = traceIdFrom(bytes);
|
|
831
|
+
if (r.kind === "ok") return r.value;
|
|
832
|
+
const fixed = Uint8Array.from({ length: 16 }, (_, i) => bytes[i] ?? 0);
|
|
833
|
+
fixed[15] = 1;
|
|
834
|
+
const again = traceIdFrom(fixed);
|
|
835
|
+
if (again.kind === "err") throw new Error(again.error);
|
|
836
|
+
return again.value;
|
|
837
|
+
};
|
|
838
|
+
const newSpanId = (): SpanId => {
|
|
839
|
+
const bytes = random(8);
|
|
840
|
+
const r = spanIdFrom(bytes);
|
|
841
|
+
if (r.kind === "ok") return r.value;
|
|
842
|
+
const fixed = Uint8Array.from({ length: 8 }, (_, i) => bytes[i] ?? 0);
|
|
843
|
+
fixed[7] = 1;
|
|
844
|
+
const again = spanIdFrom(fixed);
|
|
845
|
+
if (again.kind === "err") throw new Error(again.error);
|
|
846
|
+
return again.value;
|
|
847
|
+
};
|
|
848
|
+
const clean = (attributes: Attributes, secret: readonly string[]): { readonly attributes: Attributes; readonly dropped: number } =>
|
|
849
|
+
limitAttributes(redactAttributes(attributes, secret), limits);
|
|
850
|
+
|
|
851
|
+
const addEvent = (o: Open, name: string, attributes: Attributes): void => {
|
|
852
|
+
if (o.ended || !o.recording) return;
|
|
853
|
+
if (o.events.length >= limits.eventCount) {
|
|
854
|
+
o.droppedEvents++;
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
const a = clean(attributes, []);
|
|
858
|
+
const event: SpanEvent = { name, time: clock(), attributes: a.attributes, droppedAttributesCount: a.dropped };
|
|
859
|
+
o.events.push(event);
|
|
860
|
+
each((p) => p.onEvent?.(o.start, event, source));
|
|
861
|
+
};
|
|
862
|
+
|
|
863
|
+
const end = (o: Open, status: SpanStatus): void => {
|
|
864
|
+
if (o.ended) return;
|
|
865
|
+
o.ended = true;
|
|
866
|
+
open.delete(o);
|
|
867
|
+
if (!o.recording) return;
|
|
868
|
+
const s = o.start;
|
|
869
|
+
const data: SpanData = {
|
|
870
|
+
name: s.name,
|
|
871
|
+
context: s.context,
|
|
872
|
+
...(s.parentSpanId === undefined ? {} : { parentSpanId: s.parentSpanId }),
|
|
873
|
+
kind: s.kind,
|
|
874
|
+
startTime: s.startTime,
|
|
875
|
+
endTime: clock(),
|
|
876
|
+
attributes: o.attributes,
|
|
877
|
+
events: [...o.events],
|
|
878
|
+
links: o.links,
|
|
879
|
+
status,
|
|
880
|
+
droppedAttributesCount: o.droppedAttributes,
|
|
881
|
+
droppedEventsCount: o.droppedEvents,
|
|
882
|
+
droppedLinksCount: o.droppedLinks,
|
|
883
|
+
};
|
|
884
|
+
each((p) => p.onEnd?.(data, source));
|
|
885
|
+
};
|
|
886
|
+
|
|
887
|
+
const fail = (o: Open, thrown: unknown): void => {
|
|
888
|
+
const message = describeError(thrown);
|
|
889
|
+
const type = thrown instanceof Error ? thrown.name : typeof thrown;
|
|
890
|
+
const stack = thrown instanceof Error && thrown.stack !== undefined ? { "exception.stacktrace": thrown.stack } : {};
|
|
891
|
+
addEvent(o, "exception", { "exception.type": type, "exception.message": message, ...stack });
|
|
892
|
+
end(o, { kind: "error", message });
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
const startSpan = (
|
|
896
|
+
kind: string,
|
|
897
|
+
attributes: object,
|
|
898
|
+
explicitParent: SpanContext | null | undefined,
|
|
899
|
+
links: readonly LinkInput[],
|
|
900
|
+
): Open => {
|
|
901
|
+
const d = declaration(kind);
|
|
902
|
+
if (d.signal !== "span") throw new Error(`the signal kind ${kind} is not a span`);
|
|
903
|
+
const parent = explicitParent === null ? undefined : (explicitParent ?? context.active() ?? options.parent);
|
|
904
|
+
const traceId = parent?.traceId ?? newTraceId();
|
|
905
|
+
const sampled = !stopped && shouldSample(sampler, traceId, parent);
|
|
906
|
+
const flags = ((parent?.traceFlags ?? 0) & ~SAMPLED) | (sampled ? SAMPLED : 0);
|
|
907
|
+
const spanContext: SpanContext = {
|
|
908
|
+
traceId,
|
|
909
|
+
spanId: newSpanId(),
|
|
910
|
+
traceFlags: flags,
|
|
911
|
+
traceState: parent?.traceState ?? [],
|
|
912
|
+
isRemote: false,
|
|
913
|
+
};
|
|
914
|
+
const secret = d.secret ?? [];
|
|
915
|
+
const a = clean(toAttributes(d.attributes, attributes), secret);
|
|
916
|
+
const kept = links.slice(0, limits.linkCount).map((l): SpanLink => {
|
|
917
|
+
const la = clean(l.attributes ?? {}, []);
|
|
918
|
+
return { ...l, attributes: la.attributes, droppedAttributesCount: la.dropped };
|
|
919
|
+
});
|
|
920
|
+
const start: SpanStart = {
|
|
921
|
+
name: kind,
|
|
922
|
+
context: spanContext,
|
|
923
|
+
...(parent === undefined ? {} : { parentSpanId: parent.spanId }),
|
|
924
|
+
kind: d.spanKind ?? "internal",
|
|
925
|
+
startTime: clock(),
|
|
926
|
+
attributes: a.attributes,
|
|
927
|
+
};
|
|
928
|
+
const o: Open = {
|
|
929
|
+
start,
|
|
930
|
+
recording: sampled,
|
|
931
|
+
links: kept,
|
|
932
|
+
droppedLinks: Math.max(0, links.length - limits.linkCount),
|
|
933
|
+
secret,
|
|
934
|
+
attributes: a.attributes,
|
|
935
|
+
droppedAttributes: a.dropped,
|
|
936
|
+
events: [],
|
|
937
|
+
droppedEvents: 0,
|
|
938
|
+
ended: false,
|
|
939
|
+
};
|
|
940
|
+
open.add(o);
|
|
941
|
+
if (sampled) each((p) => p.onStart?.(start, source));
|
|
942
|
+
return o;
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
const runSpan = <T>(
|
|
946
|
+
kind: string,
|
|
947
|
+
attributes: object,
|
|
948
|
+
fn: (handle: SpanHandle<R, keyof R>) => T,
|
|
949
|
+
spanOptions: SpanOptions | undefined,
|
|
950
|
+
parent: SpanContext | undefined,
|
|
951
|
+
): T => {
|
|
952
|
+
const o = startSpan(kind, attributes, spanOptions?.parent === undefined ? parent : spanOptions.parent, spanOptions?.links ?? []);
|
|
953
|
+
const handle = makeHandle(o);
|
|
954
|
+
let out: T;
|
|
955
|
+
try {
|
|
956
|
+
out = context.with(o.start.context, () => fn(handle));
|
|
957
|
+
} catch (e) {
|
|
958
|
+
fail(o, e);
|
|
959
|
+
throw e;
|
|
960
|
+
}
|
|
961
|
+
if (isThenable(out)) {
|
|
962
|
+
const pending = out;
|
|
963
|
+
const settled = (async (): Promise<unknown> => {
|
|
964
|
+
try {
|
|
965
|
+
const value = await pending;
|
|
966
|
+
end(o, statusOf(value));
|
|
967
|
+
return value;
|
|
968
|
+
} catch (e) {
|
|
969
|
+
fail(o, e);
|
|
970
|
+
throw e;
|
|
971
|
+
}
|
|
972
|
+
})();
|
|
973
|
+
// `out` is a promise of T's value, and `settled` settles to that same value: it is the same type.
|
|
974
|
+
return settled as T;
|
|
975
|
+
}
|
|
976
|
+
end(o, statusOf(out));
|
|
977
|
+
return out;
|
|
978
|
+
};
|
|
979
|
+
|
|
980
|
+
const emitLog = (
|
|
981
|
+
kind: string,
|
|
982
|
+
attributes: object,
|
|
983
|
+
body: AnyValue | undefined,
|
|
984
|
+
active: SpanContext | undefined,
|
|
985
|
+
logOptions: LogOptions | undefined,
|
|
986
|
+
): void => {
|
|
987
|
+
const d = declaration(kind);
|
|
988
|
+
if (d.signal !== "log") throw new Error(`the signal kind ${kind} is not a log event`);
|
|
989
|
+
if (stopped) return;
|
|
990
|
+
const a = clean(toAttributes(d.attributes, attributes), d.secret ?? []);
|
|
991
|
+
const severity = logOptions?.severity ?? d.severity;
|
|
992
|
+
const time = clock();
|
|
993
|
+
const record: LogRecord = {
|
|
994
|
+
time,
|
|
995
|
+
observedTime: time,
|
|
996
|
+
severityNumber: severity,
|
|
997
|
+
severityText: severityText(severity),
|
|
998
|
+
...(body === undefined ? {} : { body: redactAnyValue(body) }),
|
|
999
|
+
attributes: a.attributes,
|
|
1000
|
+
droppedAttributesCount: a.dropped,
|
|
1001
|
+
eventName: kind,
|
|
1002
|
+
...(active === undefined ? {} : { traceId: active.traceId, spanId: active.spanId, traceFlags: active.traceFlags }),
|
|
1003
|
+
};
|
|
1004
|
+
each((p) => p.onLog?.(record, source));
|
|
1005
|
+
};
|
|
1006
|
+
|
|
1007
|
+
const makeHandle = (o: Open): SpanHandle<R, keyof R> => {
|
|
1008
|
+
const d = declaration(o.start.name);
|
|
1009
|
+
return {
|
|
1010
|
+
context: o.start.context,
|
|
1011
|
+
recording: o.recording,
|
|
1012
|
+
traceparent: formatTraceparent(o.start.context),
|
|
1013
|
+
tracestate: formatTracestate(o.start.context.traceState),
|
|
1014
|
+
set: (attributes) => {
|
|
1015
|
+
if (o.ended || !o.recording) return;
|
|
1016
|
+
const added = redactAttributes(toAttributes(d.attributes, attributes), o.secret);
|
|
1017
|
+
const merged = mergeAttributes(o.attributes, added, limits);
|
|
1018
|
+
o.attributes = merged.attributes;
|
|
1019
|
+
o.droppedAttributes += merged.dropped;
|
|
1020
|
+
},
|
|
1021
|
+
event: (name, attributes = {}) => addEvent(o, name, attributes),
|
|
1022
|
+
progress: (done, total) =>
|
|
1023
|
+
addEvent(o, "progress", total === undefined ? { "progress.done": done } : { "progress.done": done, "progress.total": total }),
|
|
1024
|
+
span: (kind, attributes, fn, spanOptions) => runSpan(kind, attributes, fn, spanOptions, o.start.context),
|
|
1025
|
+
log: (kind, attributes, body, logOptions) => emitLog(kind, attributes, body, o.start.context, logOptions),
|
|
1026
|
+
};
|
|
1027
|
+
};
|
|
1028
|
+
|
|
1029
|
+
const measure = (
|
|
1030
|
+
kind: string,
|
|
1031
|
+
allowed: readonly SignalDeclaration["signal"][],
|
|
1032
|
+
value: number,
|
|
1033
|
+
attributes: object,
|
|
1034
|
+
): Result<void, string> => {
|
|
1035
|
+
const d = declaration(kind);
|
|
1036
|
+
if (!allowed.includes(d.signal)) return err(`the signal kind ${kind} is a ${d.signal}`);
|
|
1037
|
+
if (!Number.isFinite(value)) return err(`${kind}: ${value} is not a finite number`);
|
|
1038
|
+
if (d.signal === "counter" && value < 0) return err(`${kind}: a counter does not take a negative increment (${value})`);
|
|
1039
|
+
if (stopped) return ok(undefined);
|
|
1040
|
+
const a = clean(toAttributes(d.attributes, attributes), d.secret ?? []).attributes;
|
|
1041
|
+
const key = attributesKey(a);
|
|
1042
|
+
let byKey = series.get(kind);
|
|
1043
|
+
if (byKey === undefined) {
|
|
1044
|
+
byKey = new Map();
|
|
1045
|
+
series.set(kind, byKey);
|
|
1046
|
+
}
|
|
1047
|
+
const time = clock();
|
|
1048
|
+
let s = byKey.get(key);
|
|
1049
|
+
if (s === undefined) {
|
|
1050
|
+
const bounds = d.signal === "histogram" ? (d.bounds ?? DEFAULT_HISTOGRAM_BOUNDS) : [];
|
|
1051
|
+
s = {
|
|
1052
|
+
attributes: a,
|
|
1053
|
+
startTime: time,
|
|
1054
|
+
time,
|
|
1055
|
+
value: 0,
|
|
1056
|
+
count: 0,
|
|
1057
|
+
sum: 0,
|
|
1058
|
+
min: Infinity,
|
|
1059
|
+
max: -Infinity,
|
|
1060
|
+
buckets: bounds.map(() => 0).concat(0),
|
|
1061
|
+
};
|
|
1062
|
+
byKey.set(key, s);
|
|
1063
|
+
}
|
|
1064
|
+
s.time = time;
|
|
1065
|
+
switch (d.signal) {
|
|
1066
|
+
case "counter":
|
|
1067
|
+
case "updown":
|
|
1068
|
+
s.value += value;
|
|
1069
|
+
break;
|
|
1070
|
+
case "gauge":
|
|
1071
|
+
s.value = value;
|
|
1072
|
+
break;
|
|
1073
|
+
case "histogram": {
|
|
1074
|
+
const bounds = d.bounds ?? DEFAULT_HISTOGRAM_BOUNDS;
|
|
1075
|
+
const i = bounds.findIndex((b) => value <= b);
|
|
1076
|
+
const at = i < 0 ? bounds.length : i;
|
|
1077
|
+
s.buckets[at] = (s.buckets[at] ?? 0) + 1;
|
|
1078
|
+
s.count++;
|
|
1079
|
+
s.sum += value;
|
|
1080
|
+
s.min = Math.min(s.min, value);
|
|
1081
|
+
s.max = Math.max(s.max, value);
|
|
1082
|
+
break;
|
|
1083
|
+
}
|
|
1084
|
+
case "span":
|
|
1085
|
+
case "log":
|
|
1086
|
+
break;
|
|
1087
|
+
default:
|
|
1088
|
+
absurd(d);
|
|
1089
|
+
}
|
|
1090
|
+
return ok(undefined);
|
|
1091
|
+
};
|
|
1092
|
+
|
|
1093
|
+
const collect = (): readonly Metric[] => {
|
|
1094
|
+
const time = clock();
|
|
1095
|
+
const metrics: Metric[] = [];
|
|
1096
|
+
for (const [kind, byKey] of series) {
|
|
1097
|
+
const d = declaration(kind);
|
|
1098
|
+
const all = [...byKey.values()];
|
|
1099
|
+
const description = d.description ?? "";
|
|
1100
|
+
const numberPoints = (): NumberPoint[] =>
|
|
1101
|
+
all.map((s) => ({ attributes: s.attributes, startTime: s.startTime, time, value: s.value }));
|
|
1102
|
+
switch (d.signal) {
|
|
1103
|
+
case "counter":
|
|
1104
|
+
case "updown":
|
|
1105
|
+
metrics.push({
|
|
1106
|
+
name: kind,
|
|
1107
|
+
description,
|
|
1108
|
+
unit: d.unit,
|
|
1109
|
+
data: { kind: "sum", temporality: "cumulative", monotonic: d.signal === "counter", points: numberPoints() },
|
|
1110
|
+
});
|
|
1111
|
+
break;
|
|
1112
|
+
case "gauge":
|
|
1113
|
+
metrics.push({ name: kind, description, unit: d.unit, data: { kind: "gauge", points: numberPoints() } });
|
|
1114
|
+
break;
|
|
1115
|
+
case "histogram": {
|
|
1116
|
+
const bounds = d.bounds ?? DEFAULT_HISTOGRAM_BOUNDS;
|
|
1117
|
+
const points = all.map((s): HistogramPoint => ({
|
|
1118
|
+
attributes: s.attributes,
|
|
1119
|
+
startTime: s.startTime,
|
|
1120
|
+
time,
|
|
1121
|
+
count: s.count,
|
|
1122
|
+
sum: s.sum,
|
|
1123
|
+
...(s.count > 0 ? { min: s.min, max: s.max } : {}),
|
|
1124
|
+
bounds,
|
|
1125
|
+
bucketCounts: [...s.buckets],
|
|
1126
|
+
}));
|
|
1127
|
+
metrics.push({ name: kind, description, unit: d.unit, data: { kind: "histogram", temporality: "cumulative", points } });
|
|
1128
|
+
break;
|
|
1129
|
+
}
|
|
1130
|
+
case "span":
|
|
1131
|
+
case "log":
|
|
1132
|
+
break;
|
|
1133
|
+
default:
|
|
1134
|
+
absurd(d);
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
if (metrics.length > 0) each((p) => p.onMetrics?.(metrics, source));
|
|
1138
|
+
return metrics;
|
|
1139
|
+
};
|
|
1140
|
+
|
|
1141
|
+
const all = async (run: (p: Processor) => Promise<FlushResult>, timeoutMs: number): Promise<FlushResult> => {
|
|
1142
|
+
const settled = processors.map((p) =>
|
|
1143
|
+
run(p).catch((e: unknown): FlushResult => {
|
|
1144
|
+
options.onError?.(e);
|
|
1145
|
+
return { kind: "done" };
|
|
1146
|
+
}),
|
|
1147
|
+
);
|
|
1148
|
+
const r = await within(Promise.all(settled), timeoutMs);
|
|
1149
|
+
return r !== undefined && r.value.every((x) => x.kind === "done") ? { kind: "done" } : { kind: "timeout" };
|
|
1150
|
+
};
|
|
1151
|
+
|
|
1152
|
+
return {
|
|
1153
|
+
registry,
|
|
1154
|
+
source,
|
|
1155
|
+
active: () => context.active() ?? options.parent,
|
|
1156
|
+
span: (kind, attributes, fn, spanOptions) => runSpan(kind, attributes, fn, spanOptions, undefined),
|
|
1157
|
+
log: (kind, attributes, body, logOptions) => emitLog(kind, attributes, body, context.active() ?? options.parent, logOptions),
|
|
1158
|
+
add: (kind, value, attributes) => measure(kind, ["counter", "updown"], value, attributes),
|
|
1159
|
+
set: (kind, value, attributes) => measure(kind, ["gauge"], value, attributes),
|
|
1160
|
+
record: (kind, value, attributes) => measure(kind, ["histogram"], value, attributes),
|
|
1161
|
+
collect,
|
|
1162
|
+
forceFlush: (timeoutMs) => {
|
|
1163
|
+
if (!stopped) collect();
|
|
1164
|
+
return all((p) => p.forceFlush(timeoutMs), timeoutMs);
|
|
1165
|
+
},
|
|
1166
|
+
shutdown: (timeoutMs) => {
|
|
1167
|
+
if (!stopped) {
|
|
1168
|
+
for (const o of [...open]) end(o, { kind: "error", message: "the span was still open at shutdown" });
|
|
1169
|
+
collect();
|
|
1170
|
+
stopped = true;
|
|
1171
|
+
}
|
|
1172
|
+
return all((p) => p.shutdown(timeoutMs), timeoutMs);
|
|
1173
|
+
},
|
|
1174
|
+
};
|
|
1175
|
+
}
|