@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,1068 @@
1
+ // Spec: 0001-telemetry FR-014
2
+ /**
3
+ * OpenTelemetry on the host (commons 0001-telemetry FR-014 to FR-019): the OTLP/HTTP JSON exporter over `fetch` (headers, timeout, retries on
4
+ * 429, 502, 503 and 504 after `Retry-After` or a growing wait, partial success counted, never throwing, a failure said once), the probe of
5
+ * `http://localhost:4318` where no endpoint is configured, the journal (every export request also one line of OTLP JSON in a rotated
6
+ * file), the current span carried across `await` by `AsyncLocalStorage` and the parent read from `TRACEPARENT` and `TRACESTATE`, the
7
+ * pipeline a process installs (`startTelemetry`), the runtime's own signals (`process`, `http.client`, `http.server`) that `proc`, the HTTP
8
+ * client and `serve` make through the hooks below (no-ops while nothing is installed), and an OTLP/HTTP JSON receiver over `serve`.
9
+ *
10
+ * This module imports only `node:` builtins and the kernel, so that `proc.ts`, `http-client.ts` and `serve.ts` can import its hooks.
11
+ *
12
+ * @example
13
+ * ```ts
14
+ * import { defineSignals } from "../signals.ts";
15
+ * import { ok } from "@intellectual-frontiers/core";
16
+ * import { startTelemetry } from "./otel.ts";
17
+ * const registry = defineSignals({ "build.step": { signal: "span", role: "step", attributes: { target: "string" } } });
18
+ * const run = startTelemetry({ registry, service: "build" }); // OTEL_* from the environment; installed for proc, the client and serve
19
+ * await run.telemetry.span("build.step", { target: "site" }, async () => ok(undefined));
20
+ * await run.pipeline.shutdown(); // at most one second
21
+ * const warning = run.pipeline.warning(); // what to say, once and dimmed, at the end of the run (FR-024)
22
+ * ```
23
+ *
24
+ * @module
25
+ */
26
+ import { AsyncLocalStorage } from "node:async_hooks";
27
+ import * as nfs from "node:fs";
28
+ import { dirname } from "node:path";
29
+ import process from "node:process";
30
+ import { absurd, formatDecodeError, err, ok, type Result } from "@intellectual-frontiers/core";
31
+ import { retryAfterMs } from "@intellectual-frontiers/formats/http";
32
+ import {
33
+ type AttributeValue,
34
+ commandShape,
35
+ DEFAULT_OTLP_ENDPOINT,
36
+ extractContext,
37
+ type Limits,
38
+ type OtelConfig,
39
+ redactText,
40
+ redactUrl,
41
+ type Resource,
42
+ resolveConfig,
43
+ type Sampler,
44
+ type Scope,
45
+ SEVERITY,
46
+ type SignalName,
47
+ signalEndpoint,
48
+ type LogRecord,
49
+ type SpanContext,
50
+ type SpanData,
51
+ } from "../otel.ts";
52
+ import {
53
+ decodeLogs,
54
+ decodeMetrics,
55
+ decodeResponse,
56
+ decodeTraces,
57
+ encodeLogs,
58
+ encodeMetrics,
59
+ encodeResponse,
60
+ encodeTraces,
61
+ type ExportResponse,
62
+ type LogBatch,
63
+ type MetricBatch,
64
+ type TraceBatch,
65
+ } from "../otlp.ts";
66
+ import {
67
+ batchProcessor,
68
+ type BatchOptions,
69
+ type ContextManager,
70
+ createTelemetry,
71
+ type Declarations,
72
+ defineSignals,
73
+ type ExportingProcessor,
74
+ type Exporter,
75
+ type ExportResult,
76
+ type FlushResult,
77
+ type Processor,
78
+ type ProcessorStats,
79
+ type Registry,
80
+ type SignalStats,
81
+ type Source,
82
+ type Telemetry,
83
+ } from "../signals.ts";
84
+ import { setProcessTracer } from "@intellectual-frontiers/system/proc";
85
+
86
+ /** The longest a probe of the default endpoint waits for an answer (FR-015). */
87
+ export const PROBE_TIMEOUT_MS = 150;
88
+
89
+ /** The longest the runtime waits at exit for what is left to be sent (FR-015). */
90
+ export const EXIT_WAIT_MS = 1000;
91
+
92
+ /** The statuses an export is retried on (FR-014). */
93
+ export const RETRYABLE_STATUSES: ReadonlySet<number> = new Set([429, 502, 503, 504]);
94
+
95
+ // ---------------------------------------------------------------------------------------------------------------------------------
96
+ // Time, randomness, context (FR-011, FR-017)
97
+ // ---------------------------------------------------------------------------------------------------------------------------------
98
+
99
+ /** A clock of nanoseconds since the Unix epoch, from `performance.timeOrigin` and `performance.now()`: monotonic within the process. */
100
+ export function systemClock(): () => bigint {
101
+ const origin = BigInt(Math.round(performance.timeOrigin * 1000)) * 1000n;
102
+ return () => origin + BigInt(Math.round(performance.now() * 1e6));
103
+ }
104
+
105
+ /** `n` random bytes from Web Crypto. */
106
+ export function systemRandom(n: number): Uint8Array {
107
+ return globalThis.crypto.getRandomValues(new Uint8Array(n));
108
+ }
109
+
110
+ /** A context manager on `AsyncLocalStorage` (FR-017): the current span is carried across `await`, timers and callbacks. */
111
+ export function asyncContextManager(): ContextManager {
112
+ const storage = new AsyncLocalStorage<SpanContext | undefined>();
113
+ return {
114
+ active: () => storage.getStore(),
115
+ with<T>(context: SpanContext | undefined, fn: () => T): T {
116
+ return storage.run(context, fn);
117
+ },
118
+ };
119
+ }
120
+
121
+ /** The parent a process takes from its environment's `TRACEPARENT` and `TRACESTATE` (FR-017); undefined where there is no valid one. */
122
+ export function environmentParent(env: Readonly<Record<string, string | undefined>> = process.env): SpanContext | undefined {
123
+ return extractContext(env["TRACEPARENT"], env["TRACESTATE"]);
124
+ }
125
+
126
+ function runtimeName(): string {
127
+ const v: Readonly<Record<string, string | undefined>> = process.versions;
128
+ return v["bun"] !== undefined ? "bun" : "node";
129
+ }
130
+
131
+ const OS_TYPES: Readonly<Record<string, string>> = { win32: "windows", sunos: "solaris" };
132
+ const HOST_ARCHES: Readonly<Record<string, string>> = { x64: "amd64", ia32: "x86", arm: "arm32", ppc64: "ppc64", s390x: "s390x" };
133
+
134
+ /**
135
+ * The attributes of the process that describe where it runs, by the semantic conventions: `process.runtime.name` and `.version`,
136
+ * `os.type` and `host.arch`. Never a host's or a person's name.
137
+ */
138
+ export function processAttributes(): Readonly<Record<string, AttributeValue>> {
139
+ const name = runtimeName();
140
+ const v: Readonly<Record<string, string | undefined>> = process.versions;
141
+ return {
142
+ "process.runtime.name": name,
143
+ "process.runtime.version": v[name] ?? process.version.replace(/^v/, ""),
144
+ "os.type": OS_TYPES[process.platform] ?? process.platform,
145
+ "host.arch": HOST_ARCHES[process.arch] ?? process.arch,
146
+ };
147
+ }
148
+
149
+ // ---------------------------------------------------------------------------------------------------------------------------------
150
+ // The OTLP/HTTP JSON exporter (FR-014, FR-015)
151
+ // ---------------------------------------------------------------------------------------------------------------------------------
152
+
153
+ /** How the OTLP exporter sends. Everything here is for a test or a special host; the defaults are the specification's. */
154
+ export type OtlpExporterOptions = {
155
+ /** The `fetch` to use (the platform's by default). */
156
+ readonly fetch?: typeof fetch;
157
+ /** Told once, the first time an export fails or no collector answers (FR-014, FR-024). */
158
+ readonly onWarning?: (message: string) => void;
159
+ /** The base endpoint probed where a signal has none configured (`http://localhost:4318`). */
160
+ readonly defaultEndpoint?: string;
161
+ /** How long the probe waits (150 ms). */
162
+ readonly probeTimeoutMs?: number;
163
+ /** The first wait before a retry with no `Retry-After`; each next one doubles (100 ms). */
164
+ readonly retryBaseMs?: number;
165
+ /** How a wait is spent (a timer by default); it rejects when `signal` aborts. */
166
+ readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
167
+ };
168
+
169
+ /** The OTLP exporter: an `Exporter`, and the warning it gave, if any. */
170
+ export type OtlpExporter = Exporter & {
171
+ /** The warning said, once, if an export failed or no collector answered. */
172
+ readonly warning: () => string | undefined;
173
+ };
174
+
175
+ function abortableSleep(ms: number, signal: AbortSignal): Promise<void> {
176
+ return new Promise((resolve, reject) => {
177
+ if (signal.aborted) {
178
+ reject(new Error("the exporter is shut down"));
179
+ return;
180
+ }
181
+ const onAbort = (): void => {
182
+ clearTimeout(t);
183
+ reject(new Error("the exporter is shut down"));
184
+ };
185
+ const t = setTimeout(() => {
186
+ signal.removeEventListener("abort", onAbort);
187
+ resolve();
188
+ }, ms);
189
+ signal.addEventListener("abort", onAbort, { once: true });
190
+ });
191
+ }
192
+
193
+ function describeThrown(e: unknown): string {
194
+ if (!(e instanceof Error)) return String(e);
195
+ const cause = e.cause instanceof Error ? `: ${e.cause.message}` : "";
196
+ return redactText(`${e.message}${cause}`);
197
+ }
198
+
199
+ /**
200
+ * The OTLP/HTTP JSON exporter over `fetch` (FR-014): each export is a `POST` of the request as JSON to the signal's endpoint, with
201
+ * `content-type: application/json` and the configured headers, within the signal's timeout; 429, 502, 503 and 504 are retried after the
202
+ * server's `Retry-After` or a doubling wait, as long as the wait ends within the timeout; a partial success is read and returned. An
203
+ * export never throws. Where a signal has no endpoint configured, the default is probed for at most 150 ms before the first export, and
204
+ * nothing is sent where nothing answers (FR-015). The first failure is told to `onWarning`, once. `shutdown` waits for the exports in
205
+ * flight within its time, then aborts them, so nothing keeps the process alive.
206
+ */
207
+ export function otlpExporter(exporters: OtelConfig["exporters"], options: OtlpExporterOptions = {}): OtlpExporter {
208
+ const fetcher = options.fetch ?? fetch;
209
+ const base = options.defaultEndpoint ?? DEFAULT_OTLP_ENDPOINT;
210
+ const probeTimeout = options.probeTimeoutMs ?? PROBE_TIMEOUT_MS;
211
+ const retryBase = options.retryBaseMs ?? 100;
212
+ const sleep = options.sleep ?? abortableSleep;
213
+ const stop = new AbortController();
214
+ const inflight = new Set<Promise<ExportResult>>();
215
+ let warned: string | undefined;
216
+ let probed: Promise<boolean> | undefined;
217
+
218
+ const warn = (message: string): void => {
219
+ if (warned !== undefined) return;
220
+ warned = message;
221
+ try {
222
+ options.onWarning?.(message);
223
+ } catch {
224
+ /* a listener never breaks an export */
225
+ }
226
+ };
227
+ const failure = (message: string): ExportResult => {
228
+ warn(`OpenTelemetry signals were not exported: ${message}`);
229
+ return { kind: "failure", message };
230
+ };
231
+
232
+ // Any HTTP answer counts: an OTLP receiver answers an empty export request with 200, anything else with some status.
233
+ const probe = (): Promise<boolean> => {
234
+ probed ??= (async () => {
235
+ try {
236
+ const res = await fetcher(signalEndpoint(base, "traces"), {
237
+ method: "POST",
238
+ headers: { "content-type": "application/json" },
239
+ body: "{}",
240
+ signal: AbortSignal.any([AbortSignal.timeout(probeTimeout), stop.signal]),
241
+ });
242
+ await res.body?.cancel().catch(() => undefined);
243
+ return true;
244
+ } catch {
245
+ return false;
246
+ }
247
+ })();
248
+ return probed;
249
+ };
250
+
251
+ const endpointOf = async (signal: SignalName): Promise<Result<string, string>> => {
252
+ const configured = exporters[signal].endpoint;
253
+ if (configured !== undefined) return ok(configured);
254
+ if (await probe()) return ok(signalEndpoint(base, signal));
255
+ return err(`no OpenTelemetry collector answered at ${redactUrl(base)} within ${probeTimeout} ms`);
256
+ };
257
+
258
+ const post = async (signal: SignalName, body: string): Promise<ExportResult> => {
259
+ const config = exporters[signal];
260
+ if (!config.enabled) return { kind: "success" };
261
+ if (stop.signal.aborted) return failure("the exporter is shut down");
262
+ const endpoint = await endpointOf(signal);
263
+ if (endpoint.kind === "err") {
264
+ warn(`${endpoint.error}; signals were not exported`);
265
+ return { kind: "failure", message: endpoint.error };
266
+ }
267
+ const url = endpoint.value;
268
+ const shown = redactUrl(url);
269
+ const deadline = Date.now() + config.timeoutMs;
270
+ for (let attempt = 0; ; attempt++) {
271
+ const left = deadline - Date.now();
272
+ if (left <= 0) return failure(`${shown} did not answer within ${config.timeoutMs} ms`);
273
+ let res: Response;
274
+ try {
275
+ res = await fetcher(url, {
276
+ method: "POST",
277
+ headers: { ...config.headers, "content-type": "application/json" },
278
+ body,
279
+ signal: AbortSignal.any([AbortSignal.timeout(left), stop.signal]),
280
+ });
281
+ } catch (e) {
282
+ if (stop.signal.aborted) return failure(`the export to ${shown} was given up at exit`);
283
+ return failure(`${shown}: ${describeThrown(e)}`);
284
+ }
285
+ if (res.ok) {
286
+ const text = await res.text().catch(() => "");
287
+ if (text.trim() === "") return { kind: "success" };
288
+ let parsed: unknown;
289
+ try {
290
+ parsed = JSON.parse(text);
291
+ } catch {
292
+ return { kind: "success" };
293
+ }
294
+ const decoded = decodeResponse(signal, parsed);
295
+ if (decoded.kind === "err" || decoded.value.rejected === 0) return { kind: "success" };
296
+ return { kind: "partial", rejected: decoded.value.rejected, message: decoded.value.errorMessage };
297
+ }
298
+ await res.body?.cancel().catch(() => undefined);
299
+ if (!RETRYABLE_STATUSES.has(res.status)) return failure(`${shown}: HTTP ${res.status}`);
300
+ const wait = retryAfterMs(res.headers.get("retry-after"), Date.now()) ?? retryBase * 2 ** attempt;
301
+ if (Date.now() + wait >= deadline) return failure(`${shown}: HTTP ${res.status}, and no time is left to retry`);
302
+ try {
303
+ await sleep(wait, stop.signal);
304
+ } catch {
305
+ return failure(`the export to ${shown} was given up at exit`);
306
+ }
307
+ }
308
+ };
309
+
310
+ const send = (signal: SignalName, body: () => string): Promise<ExportResult> => {
311
+ const p = (async (): Promise<ExportResult> => {
312
+ try {
313
+ return await post(signal, body());
314
+ } catch (e) {
315
+ return failure(describeThrown(e));
316
+ }
317
+ })();
318
+ inflight.add(p);
319
+ void p.finally(() => inflight.delete(p));
320
+ return p;
321
+ };
322
+
323
+ return {
324
+ exportTraces: (batches: readonly TraceBatch[]) => send("traces", () => JSON.stringify(encodeTraces(batches))),
325
+ exportLogs: (batches: readonly LogBatch[]) => send("logs", () => JSON.stringify(encodeLogs(batches))),
326
+ exportMetrics: (batches: readonly MetricBatch[]) => send("metrics", () => JSON.stringify(encodeMetrics(batches))),
327
+ async shutdown(timeoutMs: number): Promise<void> {
328
+ if (inflight.size > 0) {
329
+ let handle: ReturnType<typeof setTimeout> | undefined;
330
+ await Promise.race([
331
+ Promise.allSettled([...inflight]),
332
+ new Promise<void>((resolve) => {
333
+ handle = setTimeout(resolve, Math.max(0, timeoutMs));
334
+ }),
335
+ ]);
336
+ clearTimeout(handle);
337
+ }
338
+ stop.abort();
339
+ },
340
+ warning: () => warned,
341
+ };
342
+ }
343
+
344
+ // ---------------------------------------------------------------------------------------------------------------------------------
345
+ // The journal (FR-016)
346
+ // ---------------------------------------------------------------------------------------------------------------------------------
347
+
348
+ /** Where and how a journal is kept. */
349
+ export type JournalOptions = {
350
+ /** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
351
+ readonly path: string;
352
+ /** The size past which the file is rotated before the next line (10 MiB by default). */
353
+ readonly maxBytes?: number;
354
+ /** How many older files are kept (3 by default; 0 keeps none). */
355
+ readonly keep?: number;
356
+ /** Where given, a journal file last written more than this many days ago is removed when the journal starts and at each rotation. */
357
+ readonly maxAgeDays?: number;
358
+ /** The clock that ages files, in milliseconds since the epoch (`Date.now` by default; a test gives its own). */
359
+ readonly now?: () => number;
360
+ };
361
+
362
+ function sizeOf(path: string): number {
363
+ try {
364
+ return nfs.statSync(path).size;
365
+ } catch {
366
+ return 0;
367
+ }
368
+ }
369
+
370
+ const DAY_MS = 24 * 60 * 60 * 1000;
371
+
372
+ /** Each journal file (the current one and `<path>.1` to `<path>.<keep>`) last written before `oldest` removed. */
373
+ function removeAged(path: string, keep: number, oldest: number): void {
374
+ for (const file of [path, ...Array.from({ length: keep }, (_, i) => `${path}.${i + 1}`)]) {
375
+ try {
376
+ if (nfs.statSync(file).mtimeMs < oldest) nfs.rmSync(file, { force: true });
377
+ } catch {
378
+ // not there: nothing to remove
379
+ }
380
+ }
381
+ }
382
+
383
+ function rotate(path: string, keep: number): void {
384
+ if (keep <= 0) {
385
+ nfs.rmSync(path, { force: true });
386
+ return;
387
+ }
388
+ nfs.rmSync(`${path}.${keep}`, { force: true });
389
+ for (let i = keep - 1; i >= 1; i--) if (nfs.existsSync(`${path}.${i}`)) nfs.renameSync(`${path}.${i}`, `${path}.${i + 1}`);
390
+ nfs.renameSync(path, `${path}.1`);
391
+ }
392
+
393
+ /**
394
+ * An exporter that writes each export request as one line of OTLP JSON to a file (FR-016), appended synchronously so that what a run made
395
+ * is kept even where it ends abruptly. Before a line is written to a file that already holds `maxBytes` or more, the file is rotated:
396
+ * `<path>.<keep>` removed, each `<path>.<i>` renamed `<path>.<i+1>`, and the file renamed `<path>.1`. Where `maxAgeDays` is given, a
397
+ * journal file last written longer ago than that is removed before the first line and after each rotation. A write that fails is a
398
+ * failure result, never a throw.
399
+ */
400
+ export function journalExporter(options: JournalOptions): Exporter {
401
+ const maxBytes = options.maxBytes ?? 10 * 1024 * 1024;
402
+ const keep = Math.max(0, Math.floor(options.keep ?? 3));
403
+ let stopped = false;
404
+ let ready = false;
405
+ const write = (line: () => string): Promise<ExportResult> => {
406
+ if (stopped) return Promise.resolve({ kind: "failure", message: "the journal is closed" });
407
+ try {
408
+ const age = (): void => {
409
+ if (options.maxAgeDays !== undefined) removeAged(options.path, keep, (options.now ?? Date.now)() - options.maxAgeDays * DAY_MS);
410
+ };
411
+ if (!ready) {
412
+ nfs.mkdirSync(dirname(options.path), { recursive: true });
413
+ age();
414
+ ready = true;
415
+ }
416
+ if (sizeOf(options.path) >= maxBytes) {
417
+ rotate(options.path, keep);
418
+ age();
419
+ }
420
+ nfs.appendFileSync(options.path, `${line()}\n`);
421
+ return Promise.resolve({ kind: "success" });
422
+ } catch (e) {
423
+ return Promise.resolve({ kind: "failure", message: `the journal ${options.path} could not be written: ${describeThrown(e)}` });
424
+ }
425
+ };
426
+ return {
427
+ exportTraces: (batches) => write(() => JSON.stringify(encodeTraces(batches))),
428
+ exportLogs: (batches) => write(() => JSON.stringify(encodeLogs(batches))),
429
+ exportMetrics: (batches) => write(() => JSON.stringify(encodeMetrics(batches))),
430
+ shutdown: () => {
431
+ stopped = true;
432
+ return Promise.resolve();
433
+ },
434
+ };
435
+ }
436
+
437
+ /** A batch processor that keeps a journal (FR-016): spans and log records batched as `options` says, metric collections as they come. */
438
+ export function journalProcessor(options: JournalOptions & BatchOptions): ExportingProcessor {
439
+ return batchProcessor(journalExporter(options), options);
440
+ }
441
+
442
+ /** A processor that hands on only the signals named: the others never reach `processor`. */
443
+ export function onlySignals(processor: ExportingProcessor, signals: Iterable<SignalName>): ExportingProcessor {
444
+ const s = new Set(signals);
445
+ return {
446
+ ...(s.has("traces") ? { onEnd: (span, source) => processor.onEnd?.(span, source) } : {}),
447
+ ...(s.has("logs") ? { onLog: (record, source) => processor.onLog?.(record, source) } : {}),
448
+ ...(s.has("metrics") ? { onMetrics: (metrics, source) => processor.onMetrics?.(metrics, source) } : {}),
449
+ forceFlush: (timeoutMs) => processor.forceFlush(timeoutMs),
450
+ shutdown: (timeoutMs) => processor.shutdown(timeoutMs),
451
+ stats: () => processor.stats(),
452
+ } satisfies ExportingProcessor;
453
+ }
454
+
455
+ /**
456
+ * An exporter shared by `users` processors: its `shutdown` stops the exporter only when the last of them shuts it down, so that one
457
+ * processor's shutdown never aborts another's exports in flight.
458
+ */
459
+ export function shareExporter(exporter: Exporter, users: number): Exporter {
460
+ let left = Math.max(1, users);
461
+ return {
462
+ exportTraces: (batches) => exporter.exportTraces(batches),
463
+ exportLogs: (batches) => exporter.exportLogs(batches),
464
+ exportMetrics: (batches) => exporter.exportMetrics(batches),
465
+ shutdown: (timeoutMs) => (--left <= 0 ? exporter.shutdown(timeoutMs) : Promise.resolve()),
466
+ };
467
+ }
468
+
469
+ // ---------------------------------------------------------------------------------------------------------------------------------
470
+ // The pipeline a process installs
471
+ // ---------------------------------------------------------------------------------------------------------------------------------
472
+
473
+ /** The signals the runtime itself makes (FR-018), and the warning that signals were not sent (FR-014). */
474
+ export const RUNTIME_SIGNALS = defineSignals({
475
+ process: {
476
+ signal: "span",
477
+ spanKind: "client",
478
+ role: "detail",
479
+ description: "A program run by proc: its name and option names alone (FR-006), and its exit status.",
480
+ attributes: { "process.executable.name": "string", "process.command_args": "string[]", "process.exit.code?": "int" },
481
+ },
482
+ "http.client": {
483
+ signal: "span",
484
+ spanKind: "client",
485
+ role: "detail",
486
+ description: "A request made by the HTTP client; the URL redacted (FR-006).",
487
+ attributes: {
488
+ "http.request.method": "string",
489
+ "url.full": "string",
490
+ "server.address": "string",
491
+ "server.port?": "int",
492
+ "http.response.status_code?": "int",
493
+ "error.type?": "string",
494
+ },
495
+ },
496
+ "http.server": {
497
+ signal: "span",
498
+ spanKind: "server",
499
+ role: "detail",
500
+ description: "A request answered by serve; its parent is the request's traceparent.",
501
+ attributes: {
502
+ "http.request.method": "string",
503
+ "url.path": "string",
504
+ "url.scheme": "string",
505
+ "server.address?": "string",
506
+ "server.port?": "int",
507
+ "http.response.status_code?": "int",
508
+ },
509
+ },
510
+ "otel.warning": {
511
+ signal: "log",
512
+ severity: SEVERITY.WARN,
513
+ // The console says this once, at the end of the run (FR-024), from `Pipeline.warning()`, not as it happens.
514
+ role: "none",
515
+ description: "Signals were not sent: an export failed, no collector answered, or the wait at exit ran out.",
516
+ attributes: {},
517
+ },
518
+ });
519
+
520
+ /** The kinds of the runtime's own registry. */
521
+ export type RuntimeKinds = (typeof RUNTIME_SIGNALS)["kinds"];
522
+
523
+ /** The scope of the runtime's own signals. */
524
+ export const RUNTIME_SCOPE: Scope = { name: "ifc-ts/runtime" };
525
+
526
+ /** What a pipeline is made from. Everything but the resource has a default for a real process. */
527
+ export type PipelineOptions = {
528
+ readonly resource: Resource;
529
+ /** The processors every signal goes to; more may be added with `addProcessor`. */
530
+ readonly processors?: readonly Processor[];
531
+ /** `AsyncLocalStorage` by default (FR-017). */
532
+ readonly context?: ContextManager;
533
+ /** The parent of a span started with no current one (`environmentParent()` in `startTelemetry`). */
534
+ readonly parent?: SpanContext;
535
+ readonly clock?: () => bigint;
536
+ readonly random?: (n: number) => Uint8Array;
537
+ readonly sampler?: Sampler;
538
+ readonly limits?: Limits;
539
+ /** How often the metrics are collected and handed on (never where 0 or absent). */
540
+ readonly metricIntervalMs?: number;
541
+ /** Told once, with the first warning. */
542
+ readonly onWarning?: (message: string) => void;
543
+ /** What a processor threw. */
544
+ readonly onError?: (error: unknown) => void;
545
+ };
546
+
547
+ /** A finished span or a log record handed to a pipeline whole. */
548
+ export type PipelineItem = { readonly kind: "span"; readonly span: SpanData } | { readonly kind: "log"; readonly record: LogRecord };
549
+
550
+ /** The signals of a process: one resource, one context, the processors, and the telemetries made on them. */
551
+ export interface Pipeline {
552
+ /** The resource every signal carries. */
553
+ readonly resource: Resource;
554
+ /** The context manager every telemetry of the pipeline shares. */
555
+ readonly context: ContextManager;
556
+ /** The parent of a span started with no current one. */
557
+ readonly parent: SpanContext | undefined;
558
+ /** A telemetry of a registry and scope on this pipeline: its signals go to every processor of the pipeline. */
559
+ telemetry<const R extends Declarations>(registry: Registry<R>, scope: Scope): Telemetry<R>;
560
+ /** Adds a processor (a console's renderer, a memory processor); returns what removes it. */
561
+ addProcessor(processor: Processor): () => void;
562
+ /**
563
+ * Hands a span or a log record made elsewhere, with its own ids and times (a test's, commons 0008-test-evidence FR-004), to every
564
+ * processor as a telemetry hands its own (`onEnd`, `onLog`), with the resource and scope it came from; nothing once shut down.
565
+ */
566
+ emit(item: PipelineItem, source: Source): void;
567
+ /** Says a warning; only the first of a run is kept, told to the listeners and recorded as an `otel.warning` log record. */
568
+ warn(message: string): void;
569
+ /** The warning of the run, if any: what the console says once, dimmed, at the end (FR-024). */
570
+ warning(): string | undefined;
571
+ /** Calls `listener` with the warning when it is said (at once, if it already has been); returns what removes it. */
572
+ onWarning(listener: (message: string) => void): () => void;
573
+ /** What the exporting processors did, by signal, summed. */
574
+ stats(): ProcessorStats;
575
+ /** Collects the metrics and flushes every processor, within `timeoutMs`. */
576
+ forceFlush(timeoutMs?: number): Promise<FlushResult>;
577
+ /**
578
+ * Ends what is open, collects the metrics, and shuts every processor down within `timeoutMs` (at most one second by default, FR-015);
579
+ * where that time runs out, gives up and says so as the run's warning. Uninstalls the pipeline where it is installed.
580
+ */
581
+ shutdown(timeoutMs?: number): Promise<FlushResult>;
582
+ }
583
+
584
+ type Stoppable = { forceFlush(timeoutMs: number): Promise<FlushResult>; shutdown(timeoutMs: number): Promise<FlushResult> };
585
+
586
+ async function within<T>(promise: Promise<T>, ms: number): Promise<{ readonly value: T } | undefined> {
587
+ let handle: ReturnType<typeof setTimeout> | undefined;
588
+ try {
589
+ return await Promise.race([
590
+ promise.then((value) => ({ value })),
591
+ new Promise<undefined>((resolve) => {
592
+ handle = setTimeout(() => resolve(undefined), Math.max(0, ms));
593
+ }),
594
+ ]);
595
+ } finally {
596
+ clearTimeout(handle);
597
+ }
598
+ }
599
+
600
+ function hasStats(p: Processor): p is ExportingProcessor {
601
+ return "stats" in p && typeof p.stats === "function";
602
+ }
603
+
604
+ function sumStats(all: readonly ProcessorStats[]): ProcessorStats {
605
+ const sum = (s: SignalName): SignalStats => {
606
+ let exported = 0;
607
+ let failed = 0;
608
+ let rejected = 0;
609
+ let dropped = 0;
610
+ let lastError: string | undefined;
611
+ for (const p of all) {
612
+ exported += p[s].exported;
613
+ failed += p[s].failed;
614
+ rejected += p[s].rejected;
615
+ dropped += p[s].dropped;
616
+ lastError = p[s].lastError ?? lastError;
617
+ }
618
+ return { exported, failed, rejected, dropped, ...(lastError === undefined ? {} : { lastError }) };
619
+ };
620
+ return { traces: sum("traces"), logs: sum("logs"), metrics: sum("metrics") };
621
+ }
622
+
623
+ /** The pipeline installed for this process, and the runtime's telemetry on it. */
624
+ let current: { readonly pipeline: Pipeline; readonly runtime: Telemetry<RuntimeKinds> } | undefined;
625
+
626
+ /**
627
+ * A pipeline (FR-012, FR-017): the processors every signal goes to, one `AsyncLocalStorage` context, one clock and source of random
628
+ * bytes, and the telemetries made on it. It is not installed; `install` makes it the process's.
629
+ */
630
+ export function createPipeline(options: PipelineOptions): Pipeline {
631
+ const processors: Processor[] = [...(options.processors ?? [])];
632
+ const context = options.context ?? asyncContextManager();
633
+ const clock = options.clock ?? systemClock();
634
+ const random = options.random ?? systemRandom;
635
+ const telemetries: Stoppable[] = [];
636
+ const listeners = new Set<(message: string) => void>();
637
+ let warned: string | undefined;
638
+ let runtime: Telemetry<RuntimeKinds> | undefined;
639
+ let stopped = false;
640
+
641
+ // Every telemetry hands its signals to this one processor, which hands them to the pipeline's processors as they are now; flushing
642
+ // and shutting down are the pipeline's, once for every telemetry.
643
+ const fanout: Processor = {
644
+ onStart: (span, source) => processors.forEach((p) => p.onStart?.(span, source)),
645
+ onEvent: (span, event, source) => processors.forEach((p) => p.onEvent?.(span, event, source)),
646
+ onEnd: (span, source) => processors.forEach((p) => p.onEnd?.(span, source)),
647
+ onLog: (record, source) => processors.forEach((p) => p.onLog?.(record, source)),
648
+ onMetrics: (metrics, source) => processors.forEach((p) => p.onMetrics?.(metrics, source)),
649
+ forceFlush: () => Promise.resolve({ kind: "done" }),
650
+ shutdown: () => Promise.resolve({ kind: "done" }),
651
+ };
652
+
653
+ const interval =
654
+ options.metricIntervalMs !== undefined && options.metricIntervalMs > 0
655
+ ? setInterval(() => {
656
+ for (const t of telemetries) void t.forceFlush(0);
657
+ }, options.metricIntervalMs)
658
+ : undefined;
659
+ if (interval !== undefined && typeof interval === "object" && "unref" in interval) interval.unref();
660
+
661
+ const settle = async (run: (p: Processor) => Promise<FlushResult>, timeoutMs: number): Promise<FlushResult> => {
662
+ const settled = processors.map((p) =>
663
+ run(p).catch((e: unknown): FlushResult => {
664
+ options.onError?.(e);
665
+ return { kind: "done" };
666
+ }),
667
+ );
668
+ const r = await within(Promise.all(settled), timeoutMs);
669
+ return r !== undefined && r.value.every((x) => x.kind === "done") ? { kind: "done" } : { kind: "timeout" };
670
+ };
671
+
672
+ const pipeline: Pipeline = {
673
+ resource: options.resource,
674
+ context,
675
+ parent: options.parent,
676
+ telemetry<const R extends Declarations>(registry: Registry<R>, scope: Scope): Telemetry<R> {
677
+ const t = createTelemetry({
678
+ registry,
679
+ resource: options.resource,
680
+ scope,
681
+ clock,
682
+ random,
683
+ processors: [fanout],
684
+ context,
685
+ ...(options.parent === undefined ? {} : { parent: options.parent }),
686
+ ...(options.sampler === undefined ? {} : { sampler: options.sampler }),
687
+ ...(options.limits === undefined ? {} : { limits: options.limits }),
688
+ ...(options.onError === undefined ? {} : { onError: options.onError }),
689
+ });
690
+ telemetries.push(t);
691
+ return t;
692
+ },
693
+ addProcessor(processor) {
694
+ processors.push(processor);
695
+ return () => {
696
+ const i = processors.indexOf(processor);
697
+ if (i >= 0) processors.splice(i, 1);
698
+ };
699
+ },
700
+ emit(item, source) {
701
+ if (stopped) return;
702
+ for (const p of [...processors]) {
703
+ try {
704
+ switch (item.kind) {
705
+ case "span":
706
+ p.onEnd?.(item.span, source);
707
+ break;
708
+ case "log":
709
+ p.onLog?.(item.record, source);
710
+ break;
711
+ default:
712
+ absurd(item);
713
+ }
714
+ } catch (e) {
715
+ options.onError?.(e);
716
+ }
717
+ }
718
+ },
719
+ warn(message) {
720
+ if (warned !== undefined) return;
721
+ warned = message;
722
+ for (const l of [...listeners, ...(options.onWarning === undefined ? [] : [options.onWarning])]) {
723
+ try {
724
+ l(message);
725
+ } catch (e) {
726
+ options.onError?.(e);
727
+ }
728
+ }
729
+ if (!stopped) {
730
+ runtime ??= pipeline.telemetry(RUNTIME_SIGNALS, RUNTIME_SCOPE);
731
+ runtime.log("otel.warning", {}, message);
732
+ }
733
+ },
734
+ warning: () => warned,
735
+ onWarning(listener) {
736
+ if (warned !== undefined) listener(warned);
737
+ else listeners.add(listener);
738
+ return () => void listeners.delete(listener);
739
+ },
740
+ stats: () => sumStats(processors.filter(hasStats).map((p) => p.stats())),
741
+ async forceFlush(timeoutMs = EXIT_WAIT_MS) {
742
+ const started = Date.now();
743
+ await Promise.all(telemetries.map((t) => t.forceFlush(0)));
744
+ return settle((p) => p.forceFlush(Math.max(0, timeoutMs - (Date.now() - started))), Math.max(0, timeoutMs - (Date.now() - started)));
745
+ },
746
+ async shutdown(timeoutMs = EXIT_WAIT_MS) {
747
+ if (current?.pipeline === pipeline) current = undefined;
748
+ if (interval !== undefined) clearInterval(interval);
749
+ const started = Date.now();
750
+ // Every telemetry ends its open spans and hands on its last metrics; its processor is the fan-out, which settles at once.
751
+ await Promise.all(telemetries.map((t) => t.shutdown(0)));
752
+ stopped = true;
753
+ const left = (): number => Math.max(0, timeoutMs - (Date.now() - started));
754
+ const r = await settle((p) => p.shutdown(left()), left());
755
+ if (r.kind === "timeout") pipeline.warn(`not every signal was sent within ${timeoutMs} ms at exit; the rest were given up`);
756
+ return r;
757
+ },
758
+ };
759
+ return pipeline;
760
+ }
761
+
762
+ /** Makes `pipeline` the process's: the runtime's own signals (FR-018) go to it from now on. It replaces any installed before. */
763
+ export function install(pipeline: Pipeline): void {
764
+ current = { pipeline, runtime: pipeline.telemetry(RUNTIME_SIGNALS, RUNTIME_SCOPE) };
765
+ }
766
+
767
+ /** Uninstalls the process's pipeline, if any; the runtime's hooks are no-ops again. */
768
+ export function uninstall(): void {
769
+ current = undefined;
770
+ }
771
+
772
+ /** The pipeline installed for this process, if any. */
773
+ export function installed(): Pipeline | undefined {
774
+ return current?.pipeline;
775
+ }
776
+
777
+ /** How `startTelemetry` starts. */
778
+ export type StartOptions<R extends Declarations> = {
779
+ /** The harness's own signals. */
780
+ readonly registry: Registry<R>;
781
+ /** The harness's name: `service.name` where `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` do not say it, and the scope's name. */
782
+ readonly service?: string;
783
+ /** The harness's version, for its scope. */
784
+ readonly version?: string;
785
+ /** The `OTEL_*` variables and `TRACEPARENT` (the process's environment by default). */
786
+ readonly env?: Readonly<Record<string, string | undefined>>;
787
+ /** Keep a journal (FR-016). */
788
+ readonly journal?: JournalOptions;
789
+ /** More processors (the console's renderer, a memory processor). */
790
+ readonly processors?: readonly Processor[];
791
+ /** Install the pipeline as the process's (the default). */
792
+ readonly install?: boolean;
793
+ /** Told once, with the run's warning. */
794
+ readonly onWarning?: (message: string) => void;
795
+ /** For a test: the exporter's `fetch`, default endpoint, retry and sleep (see `OtlpExporterOptions`). */
796
+ readonly exporter?: Omit<OtlpExporterOptions, "onWarning">;
797
+ readonly clock?: () => bigint;
798
+ readonly random?: (n: number) => Uint8Array;
799
+ };
800
+
801
+ /** A started telemetry: the pipeline, the harness's telemetry on it, and the configuration and its warnings. */
802
+ export type Started<R extends Declarations> = {
803
+ readonly pipeline: Pipeline;
804
+ readonly telemetry: Telemetry<R>;
805
+ readonly config: OtelConfig;
806
+ /** The `OTEL_*` values that were not valid, each with the default used (FR-005). */
807
+ readonly configWarnings: readonly string[];
808
+ };
809
+
810
+ /**
811
+ * The telemetry of a process, from its environment (FR-005, FR-014 to FR-017): the configuration resolved from the `OTEL_*` variables, a
812
+ * resource (`service.name`, `process.runtime.*`, `os.type`, `host.arch`; never a host's or a person's name), `AsyncLocalStorage` for the
813
+ * current span with the parent from `TRACEPARENT` and `TRACESTATE`, a batch processor exporting spans and one exporting log records and
814
+ * metrics over OTLP/HTTP JSON (none where the SDK is disabled or no signal is exported), a journal where asked, the processors given, and
815
+ * the metrics collected every `OTEL_METRIC_EXPORT_INTERVAL`. Installed as the process's pipeline unless `install` is false.
816
+ */
817
+ export function startTelemetry<const R extends Declarations>(options: StartOptions<R>): Started<R> {
818
+ const env = options.env ?? process.env;
819
+ const { config, warnings } = resolveConfig(env);
820
+ const resource: Resource = {
821
+ attributes: {
822
+ "service.name": options.service ?? `unknown_service:${runtimeName()}`,
823
+ "telemetry.sdk.name": "ifc-ts",
824
+ ...processAttributes(),
825
+ ...config.resource,
826
+ },
827
+ };
828
+ const signals = (["traces", "logs", "metrics"] as const).filter((s) => config.exporters[s].enabled);
829
+ const parent = environmentParent(env);
830
+ const pipeline = createPipeline({
831
+ resource,
832
+ processors: options.processors ?? [],
833
+ ...(parent === undefined ? {} : { parent }),
834
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
835
+ ...(options.random === undefined ? {} : { random: options.random }),
836
+ sampler: config.sampler,
837
+ limits: config.limits,
838
+ // Metrics are collected on a schedule only where something exports them; otherwise at a flush and at exit.
839
+ ...(signals.includes("metrics") || options.journal !== undefined ? { metricIntervalMs: config.metricExportIntervalMs } : {}),
840
+ ...(options.onWarning === undefined ? {} : { onWarning: options.onWarning }),
841
+ });
842
+ if (signals.length > 0) {
843
+ const rest = signals.filter((s) => s !== "traces");
844
+ const users = (signals.includes("traces") ? 1 : 0) + (rest.length > 0 ? 1 : 0);
845
+ const exporter = shareExporter(otlpExporter(config.exporters, { ...options.exporter, onWarning: (m) => pipeline.warn(m) }), users);
846
+ if (signals.includes("traces")) pipeline.addProcessor(onlySignals(batchProcessor(exporter, config.spanBatch), ["traces"]));
847
+ if (rest.length > 0) pipeline.addProcessor(onlySignals(batchProcessor(exporter, config.logBatch), rest));
848
+ }
849
+ if (options.journal !== undefined) pipeline.addProcessor(journalProcessor({ ...options.journal, ...config.logBatch }));
850
+ const telemetry = pipeline.telemetry(options.registry, {
851
+ name: options.service ?? "ifc-ts",
852
+ ...(options.version === undefined ? {} : { version: options.version }),
853
+ });
854
+ if (options.install !== false) install(pipeline);
855
+ return { pipeline, telemetry, config, configWarnings: warnings };
856
+ }
857
+
858
+ // ---------------------------------------------------------------------------------------------------------------------------------
859
+ // The runtime's hooks (FR-018): no-ops while no pipeline is installed
860
+ // ---------------------------------------------------------------------------------------------------------------------------------
861
+
862
+ type Carried<T> = Result<T, { readonly value: T; readonly message: string }>;
863
+
864
+ function carried<T>(r: Carried<T>): T {
865
+ return r.kind === "ok" ? r.value : r.error.value;
866
+ }
867
+
868
+ /**
869
+ * Runs a program in a `process` client span (FR-018): `process.executable.name` and `process.command_args` as `commandShape` gives them
870
+ * (the program and its option names, never a value, FR-006), `process.exit.code`, `error` where it is not 0. `run` is given the
871
+ * `TRACEPARENT` and `TRACESTATE` to add to the program's environment. With no pipeline installed, `run({})` and nothing else.
872
+ */
873
+ export function traceProcess<T extends { readonly code: number }>(
874
+ argv: readonly string[],
875
+ run: (env: Readonly<Record<string, string>>) => Promise<T>,
876
+ ): Promise<T> {
877
+ const c = current;
878
+ if (c === undefined) return run({});
879
+ const shape = commandShape(argv);
880
+ return c.runtime
881
+ .span("process", { "process.executable.name": shape[0] ?? "", "process.command_args": shape }, async (span): Promise<Carried<T>> => {
882
+ const env: Record<string, string> = { TRACEPARENT: span.traceparent };
883
+ if (span.tracestate !== "") env["TRACESTATE"] = span.tracestate;
884
+ const r = await run(env);
885
+ span.set({ "process.exit.code": r.code });
886
+ return r.code === 0 ? ok(r) : err({ value: r, message: `${shape[0] ?? "the program"} exited with ${r.code}` });
887
+ })
888
+ .then(carried);
889
+ }
890
+
891
+ // The system's process runner traces its programs through this module's pipeline once the module is loaded (commons 0032-lifting-libraries: the system does not import the telemetry).
892
+ setProcessTracer(traceProcess);
893
+
894
+ function portOf(url: URL): number | undefined {
895
+ if (url.port !== "") return Number(url.port);
896
+ return url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : undefined;
897
+ }
898
+
899
+ /**
900
+ * Sends a request in an `http.client` span (FR-018): `http.request.method`, `url.full` redacted (FR-006), `server.address`, `server.port`,
901
+ * `http.response.status_code` (`status` of what `send` gives; undefined where no answer came), `error` from 400 up or with no answer.
902
+ * `send` is given the `traceparent` (and `tracestate`) headers to add. With no pipeline installed, `send({})` and nothing else.
903
+ */
904
+ export function traceHttpClient<T>(
905
+ method: string,
906
+ url: string,
907
+ send: (headers: Readonly<Record<string, string>>) => Promise<T>,
908
+ status: (value: T) => number | undefined,
909
+ ): Promise<T> {
910
+ const c = current;
911
+ if (c === undefined) return send({});
912
+ let parsed: URL | undefined;
913
+ try {
914
+ parsed = new URL(url);
915
+ } catch {
916
+ parsed = undefined;
917
+ }
918
+ const port = parsed === undefined ? undefined : portOf(parsed);
919
+ return c.runtime
920
+ .span(
921
+ "http.client",
922
+ {
923
+ "http.request.method": method,
924
+ "url.full": redactUrl(url),
925
+ "server.address": parsed?.hostname ?? "",
926
+ ...(port === undefined ? {} : { "server.port": port }),
927
+ },
928
+ async (span): Promise<Carried<T>> => {
929
+ const headers: Record<string, string> = { traceparent: span.traceparent };
930
+ if (span.tracestate !== "") headers["tracestate"] = span.tracestate;
931
+ const value = await send(headers);
932
+ const code = status(value);
933
+ if (code === undefined) {
934
+ span.set({ "error.type": "network" });
935
+ return err({ value, message: "no answer" });
936
+ }
937
+ span.set({ "http.response.status_code": code, ...(code >= 400 ? { "error.type": String(code) } : {}) });
938
+ return code >= 400 ? err({ value, message: `HTTP ${code}` }) : ok(value);
939
+ },
940
+ )
941
+ .then(carried);
942
+ }
943
+
944
+ const UNTRACED = new WeakSet<object>();
945
+
946
+ /** A serve handler (or any function) marked so that `traceServer` makes no span for it: the OTLP receiver, so it never traces itself. */
947
+ export function untraced<F extends object>(handler: F): F {
948
+ UNTRACED.add(handler);
949
+ return handler;
950
+ }
951
+
952
+ /**
953
+ * Answers a request in an `http.server` span (FR-018) whose parent is the request's `traceparent` and `tracestate` (the process's own
954
+ * parent where it has none): `http.request.method`, `url.path`, `url.scheme`, `server.address`, `server.port`,
955
+ * `http.response.status_code`, `error` from 500 up. With no pipeline installed, or a handler marked `untraced`, `handle()` and nothing else.
956
+ */
957
+ export function traceServer(request: Request, handle: () => Response | Promise<Response>, handler?: object): Response | Promise<Response> {
958
+ const c = current;
959
+ if (c === undefined || (handler !== undefined && UNTRACED.has(handler))) return handle();
960
+ const url = new URL(request.url);
961
+ const port = portOf(url);
962
+ const remote = extractContext(request.headers.get("traceparent") ?? undefined, request.headers.get("tracestate") ?? undefined);
963
+ const parent = remote ?? c.pipeline.parent;
964
+ return c.runtime
965
+ .span(
966
+ "http.server",
967
+ {
968
+ "http.request.method": request.method,
969
+ "url.path": url.pathname,
970
+ "url.scheme": url.protocol.replace(/:$/, ""),
971
+ "server.address": url.hostname,
972
+ ...(port === undefined ? {} : { "server.port": port }),
973
+ },
974
+ async (span): Promise<Carried<Response>> => {
975
+ const response = await handle();
976
+ span.set({ "http.response.status_code": response.status });
977
+ return response.status >= 500 ? err({ value: response, message: `HTTP ${response.status}` }) : ok(response);
978
+ },
979
+ { parent: parent ?? null },
980
+ )
981
+ .then(carried);
982
+ }
983
+
984
+ // ---------------------------------------------------------------------------------------------------------------------------------
985
+ // The OTLP/HTTP JSON receiver (FR-019)
986
+ // ---------------------------------------------------------------------------------------------------------------------------------
987
+
988
+ /** What a receiver hands decoded requests to; a sink may answer with a partial success (signals it rejected, and why). */
989
+ export type ReceiverSinks = {
990
+ readonly onTraces?: (batches: readonly TraceBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
991
+ readonly onLogs?: (batches: readonly LogBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
992
+ readonly onMetrics?: (batches: readonly MetricBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
993
+ };
994
+
995
+ const RECEIVER_PATHS: Readonly<Record<string, SignalName>> = { "/v1/traces": "traces", "/v1/logs": "logs", "/v1/metrics": "metrics" };
996
+
997
+ function statusResponse(status: number, code: number, message: string): Response {
998
+ return new Response(JSON.stringify({ code, message }), { status, headers: { "content-type": "application/json" } });
999
+ }
1000
+
1001
+ async function bodyText(request: Request): Promise<Result<string, Response>> {
1002
+ const encoding = (request.headers.get("content-encoding") ?? "identity").trim().toLowerCase();
1003
+ if (encoding === "identity" || encoding === "") return ok(await request.text());
1004
+ if (encoding !== "gzip") return err(statusResponse(415, 3, `the content encoding ${encoding} is not supported (gzip is)`));
1005
+ if (request.body === null) return ok("");
1006
+ try {
1007
+ return ok(await new Response(request.body.pipeThrough(new DecompressionStream("gzip"))).text());
1008
+ } catch {
1009
+ return err(statusResponse(400, 3, "the body is not valid gzip"));
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * An OTLP/HTTP JSON receiver, as a handler for `serve` (FR-019): `POST /v1/traces`, `/v1/logs` and `/v1/metrics` with a JSON body
1015
+ * (gzip-encoded or not) decoded by the kernel (FR-004) and handed to the sink; 415 for any content type but `application/json` (protobuf
1016
+ * among them), 400 with the path where the body does not decode, 404 for another path, 405 for another method, and OTLP's success body
1017
+ * (`{}`, or `partialSuccess` where the sink rejected some) otherwise. Errors are `google.rpc.Status` JSON. The handler is `untraced`.
1018
+ */
1019
+ export function otlpReceiver(sinks: ReceiverSinks): (request: Request) => Promise<Response> {
1020
+ return untraced(async (request: Request): Promise<Response> => {
1021
+ const path = new URL(request.url).pathname;
1022
+ const signal = Object.hasOwn(RECEIVER_PATHS, path) ? RECEIVER_PATHS[path] : undefined;
1023
+ if (signal === undefined) return statusResponse(404, 5, `${path} is not an OTLP path (/v1/traces, /v1/logs, /v1/metrics)`);
1024
+ if (request.method !== "POST") return statusResponse(405, 12, `${request.method} is not allowed; OTLP/HTTP is POST`);
1025
+ const type = (request.headers.get("content-type") ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
1026
+ if (type !== "application/json") {
1027
+ await request.body?.cancel().catch(() => undefined);
1028
+ return statusResponse(415, 3, `the content type ${type === "" ? "(none)" : type} is not supported; send application/json`);
1029
+ }
1030
+ const text = await bodyText(request);
1031
+ if (text.kind === "err") return text.error;
1032
+ let parsed: unknown;
1033
+ try {
1034
+ parsed = JSON.parse(text.value);
1035
+ } catch (e) {
1036
+ return statusResponse(400, 3, `the body is not JSON: ${e instanceof Error ? e.message : String(e)}`);
1037
+ }
1038
+ let answer: void | ExportResponse;
1039
+ try {
1040
+ switch (signal) {
1041
+ case "traces": {
1042
+ const d = decodeTraces(parsed);
1043
+ if (d.kind === "err") return statusResponse(400, 3, formatDecodeError(d.error));
1044
+ answer = await sinks.onTraces?.(d.value);
1045
+ break;
1046
+ }
1047
+ case "logs": {
1048
+ const d = decodeLogs(parsed);
1049
+ if (d.kind === "err") return statusResponse(400, 3, formatDecodeError(d.error));
1050
+ answer = await sinks.onLogs?.(d.value);
1051
+ break;
1052
+ }
1053
+ case "metrics": {
1054
+ const d = decodeMetrics(parsed);
1055
+ if (d.kind === "err") return statusResponse(400, 3, formatDecodeError(d.error));
1056
+ answer = await sinks.onMetrics?.(d.value);
1057
+ break;
1058
+ }
1059
+ default:
1060
+ absurd(signal);
1061
+ }
1062
+ } catch (e) {
1063
+ return statusResponse(500, 13, `the receiver failed: ${describeThrown(e)}`);
1064
+ }
1065
+ const body = encodeResponse(signal, answer ?? { rejected: 0, errorMessage: "" });
1066
+ return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } });
1067
+ });
1068
+ }