otel.PROBE_TIMEOUT_MSconstno test imports itconst PROBE_TIMEOUT_MS: 150The longest a probe of the default endpoint waits for an answer (FR-015).
OpenTelemetry on the host (commons 0001-telemetry FR-014 to FR-019): the OTLP/HTTP JSON exporter over fetch (headers, timeout, retries on 429, 502, 503 and 504 after Retry-After or a growing wait, partial success counted, never throwing, a failure said once), the probe of http://localhost:4318 where no endpoint is configured, the journal (every export request also one line of OTLP JSON in a rotated file), the current span carried across await by AsyncLocalStorage and the parent read from TRACEPARENT and TRACESTATE, the pipeline a process installs (startTelemetry), the runtime's own signals (process, http.client, http.server) that proc, the HTTP client and serve make through the hooks below (no-ops while nothing is installed), and an OTLP/HTTP JSON receiver over serve.
This module imports only node: builtins and the kernel, so that proc.ts, http-client.ts and serve.ts can import its hooks.
import { defineSignals } from "../signals.ts";
import { ok } from "@intellectual-frontiers/core";
import { startTelemetry } from "./otel.ts";
const registry = defineSignals({ "build.step": { signal: "span", role: "step", attributes: { target: "string" } } });
const run = startTelemetry({ registry, service: "build" }); // OTEL_* from the environment; installed for proc, the client and serve
await run.telemetry.span("build.step", { target: "site" }, async () => ok(undefined));
await run.pipeline.shutdown(); // at most one second
const warning = run.pipeline.warning(); // what to say, once and dimmed, at the end of the run (FR-024)otel.PROBE_TIMEOUT_MSconstno test imports itconst PROBE_TIMEOUT_MS: 150The longest a probe of the default endpoint waits for an answer (FR-015).
otel.EXIT_WAIT_MSconstno test imports itconst EXIT_WAIT_MS: 1000The longest the runtime waits at exit for what is left to be sent (FR-015).
otel.RETRYABLE_STATUSESconstno test imports itconst RETRYABLE_STATUSES: ReadonlySet<number>The statuses an export is retried on (FR-014).
otel.systemClockfunctionno test imports itfunction systemClock(): () => bigintA clock of nanoseconds since the Unix epoch, from performance.timeOrigin and performance.now(): monotonic within the process.
otel.systemRandomfunctionno test imports itfunction systemRandom(n: number): Uint8Array<ArrayBufferLike>n random bytes from Web Crypto.
otel.asyncContextManagerfunctionno test imports itfunction asyncContextManager(): ContextManagerA context manager on AsyncLocalStorage (FR-017): the current span is carried across await, timers and callbacks.
otel.environmentParentfunctionno test imports itfunction environmentParent(env?: Readonly<Record<string, string | undefined>>): SpanContext | undefinedThe parent a process takes from its environment's TRACEPARENT and TRACESTATE (FR-017); undefined where there is no valid one.
otel.processAttributesfunctionno test imports itfunction processAttributes(): Readonly<Record<string, AttributeValue>>The attributes of the process that describe where it runs, by the semantic conventions: process.runtime.name and .version, os.type and host.arch. Never a host's or a person's name.
otel.OtlpExporterOptionstypeno test imports ittype OtlpExporterOptions = {
/** The `fetch` to use (the platform's by default). */
readonly fetch?: typeof fetch;
… (759 characters)type OtlpExporterOptions = {
/** The `fetch` to use (the platform's by default). */
readonly fetch?: typeof fetch;
/** Told once, the first time an export fails or no collector answers (FR-014, FR-024). */
readonly onWarning?: (message: string) => void;
/** The base endpoint probed where a signal has none configured (`http://localhost:4318`). */
readonly defaultEndpoint?: string;
/** How long the probe waits (150 ms). */
readonly probeTimeoutMs?: number;
/** The first wait before a retry with no `Retry-After`; each next one doubles (100 ms). */
readonly retryBaseMs?: number;
/** How a wait is spent (a timer by default); it rejects when `signal` aborts. */
readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
};How the OTLP exporter sends. Everything here is for a test or a special host; the defaults are the specification's.
otel.OtlpExportertypeno test imports ittype OtlpExporter = Exporter & {
/** The warning said, once, if an export failed or no collector answered. */
readonly warning: () => string | undefined;
};The OTLP exporter: an Exporter, and the warning it gave, if any.
otel.otlpExporterfunctionno test imports itfunction otlpExporter(exporters: { readonly logs: ExporterConfig; readonly metrics: ExporterConfig; readonly traces: ExporterConfig; }, options?: OtlpExporterOptions): OtlpExporterThe OTLP/HTTP JSON exporter over fetch (FR-014): each export is a POST of the request as JSON to the signal's endpoint, with content-type: application/json and the configured headers, within the signal's timeout; 429, 502, 503 and 504 are retried after the 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 export never throws. Where a signal has no endpoint configured, the default is probed for at most 150 ms before the first export, and nothing is sent where nothing answers (FR-015). The first failure is told to onWarning, once. shutdown waits for the exports in flight within its time, then aborts them, so nothing keeps the process alive.
otel.JournalOptionstypeno test imports ittype JournalOptions = {
/** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
readonly pat… (663 characters)type JournalOptions = {
/** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
readonly path: string;
/** The size past which the file is rotated before the next line (10 MiB by default). */
readonly maxBytes?: number;
/** How many older files are kept (3 by default; 0 keeps none). */
readonly keep?: number;
/** Where given, a journal file last written more than this many days ago is removed when the journal starts and at each rotation. */
readonly maxAgeDays?: number;
/** The clock that ages files, in milliseconds since the epoch (`Date.now` by default; a test gives its own). */
readonly now?: () => number;
};Where and how a journal is kept.
otel.journalExporterfunctionno test imports itfunction journalExporter(options: JournalOptions): ExporterAn 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 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: <path>.<keep> removed, each <path>.<i> renamed <path>.<i+1>, and the file renamed <path>.1. Where maxAgeDays is given, a journal file last written longer ago than that is removed before the first line and after each rotation. A write that fails is a failure result, never a throw.
otel.journalProcessorfunctionno test imports itfunction journalProcessor(options: JournalOptions & BatchOptions): ExportingProcessorA batch processor that keeps a journal (FR-016): spans and log records batched as options says, metric collections as they come.
otel.onlySignalsfunctionno test imports itfunction onlySignals(processor: ExportingProcessor, signals: Iterable<SignalName>): ExportingProcessorA processor that hands on only the signals named: the others never reach processor.
otel.RUNTIME_SIGNALSconstno test imports itconst RUNTIME_SIGNALS: Registry<{ readonly process: { readonly signal: "span"; readonly spanKind: "client"; readonly rol… (1541 characters)const RUNTIME_SIGNALS: Registry<{ readonly process: { readonly signal: "span"; readonly spanKind: "client"; readonly role: "detail"; readonly description: "A program run by proc: its name and option names alone (FR-006), and its exit status."; readonly attributes: { readonly "process.executable.name": "string"; readonly "process.command_args": "string[]"; readonly "process.exit.code?": "int"; }; }; readonly "http.client": { readonly signal: "span"; readonly spanKind: "client"; readonly role: "detail"; readonly description: "A request made by the HTTP client; the URL redacted (FR-006)."; readonly attributes: { readonly "http.request.method": "string"; readonly "url.full": "string"; readonly "server.address": "string"; readonly "server.port?": "int"; readonly "http.response.status_code?": "int"; readonly "error.type?": "string"; }; }; readonly "http.server": { readonly signal: "span"; readonly spanKind: "server"; readonly role: "detail"; readonly description: "A request answered by serve; its parent is the request's traceparent."; readonly attributes: { readonly "http.request.method": "string"; readonly "url.path": "string"; readonly "url.scheme": "string"; readonly "server.address?": "string"; readonly "server.port?": "int"; readonly "http.response.status_code?": "int"; }; }; readonly "otel.warning": { readonly signal: "log"; readonly severity: 13; readonly role: "none"; readonly description: "Signals were not sent: an export failed, no collector answered, or the wait at exit ran out."; readonly attributes: {}; }; }>The signals the runtime itself makes (FR-018), and the warning that signals were not sent (FR-014).
otel.RuntimeKindstypeno test imports ittype RuntimeKinds = (typeof RUNTIME_SIGNALS)["kinds"];The kinds of the runtime's own registry.
otel.RUNTIME_SCOPEconstno test imports itconst RUNTIME_SCOPE: ScopeThe scope of the runtime's own signals.
otel.PipelineOptionstypeno test imports ittype PipelineOptions = {
readonly resource: Resource;
/** The processors every signal goes to; more may be added wit… (848 characters)type PipelineOptions = {
readonly resource: Resource;
/** The processors every signal goes to; more may be added with `addProcessor`. */
readonly processors?: readonly Processor[];
/** `AsyncLocalStorage` by default (FR-017). */
readonly context?: ContextManager;
/** The parent of a span started with no current one (`environmentParent()` in `startTelemetry`). */
readonly parent?: SpanContext;
readonly clock?: () => bigint;
readonly random?: (n: number) => Uint8Array;
readonly sampler?: Sampler;
readonly limits?: Limits;
/** How often the metrics are collected and handed on (never where 0 or absent). */
readonly metricIntervalMs?: number;
/** Told once, with the first warning. */
readonly onWarning?: (message: string) => void;
/** What a processor threw. */
readonly onError?: (error: unknown) => void;
};What a pipeline is made from. Everything but the resource has a default for a real process.
otel.PipelineItemtypeno test imports ittype PipelineItem = { readonly kind: "span"; readonly span: SpanData } | { readonly kind: "log"; readonly record: LogRecord };A finished span or a log record handed to a pipeline whole.
otel.Pipelineinterfaceno test imports itinterface PipelineThe signals of a process: one resource, one context, the processors, and the telemetries made on them.
| Member | Type | What it is |
|---|---|---|
resource | Resource | The resource every signal carries. |
context | ContextManager | The context manager every telemetry of the pipeline shares. |
parent | SpanContext | undefined | The parent of a span started with no current one. |
telemetry | <const R extends Declarations>(registry: Registry<R>, scope: Scope) => Telemetry<R> | A telemetry of a registry and scope on this pipeline: its signals go to every processor of the pipeline. |
addProcessor | (processor: Processor) => () => void | Adds a processor (a console's renderer, a memory processor); returns what removes it. |
emit | (item: PipelineItem, source: Source) => void | 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 processor as a telemetry hands its own (onEnd, onLog), with the resource and scope it came from; nothing once shut down. |
warn | (message: string) => void | Says a warning; only the first of a run is kept, told to the listeners and recorded as an otel.warning log record. |
warning | () => string | undefined | The warning of the run, if any: what the console says once, dimmed, at the end (FR-024). |
onWarning | (listener: (message: string) => void) => () => void | Calls listener with the warning when it is said (at once, if it already has been); returns what removes it. |
stats | () => ProcessorStats | What the exporting processors did, by signal, summed. |
forceFlush | (timeoutMs?: number | undefined) => Promise<FlushResult> | Collects the metrics and flushes every processor, within timeoutMs. |
shutdown | (timeoutMs?: number | undefined) => Promise<FlushResult> | Ends what is open, collects the metrics, and shuts every processor down within timeoutMs (at most one second by default, FR-015); where that time runs out, gives up and says so as the run's warning. Uninstalls the pipeline where it is installed. |
otel.createPipelinefunctionno test imports itfunction createPipeline(options: PipelineOptions): PipelineA pipeline (FR-012, FR-017): the processors every signal goes to, one AsyncLocalStorage context, one clock and source of random bytes, and the telemetries made on it. It is not installed; install makes it the process's.
otel.installfunctionno test imports itfunction install(pipeline: Pipeline): voidMakes pipeline the process's: the runtime's own signals (FR-018) go to it from now on. It replaces any installed before.
otel.uninstallfunctionno test imports itfunction uninstall(): voidUninstalls the process's pipeline, if any; the runtime's hooks are no-ops again.
otel.installedfunctionno test imports itfunction installed(): Pipeline | undefinedThe pipeline installed for this process, if any.
otel.StartOptionstypeno test imports ittype StartOptions<R extends Declarations> = {
/** The harness's own signals. */
readonly registry: Registry<R>;
/*… (1138 characters)type StartOptions<R extends Declarations> = {
/** The harness's own signals. */
readonly registry: Registry<R>;
/** The harness's name: `service.name` where `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` do not say it, and the scope's name. */
readonly service?: string;
/** The harness's version, for its scope. */
readonly version?: string;
/** The `OTEL_*` variables and `TRACEPARENT` (the process's environment by default). */
readonly env?: Readonly<Record<string, string | undefined>>;
/** Keep a journal (FR-016). */
readonly journal?: JournalOptions;
/** More processors (the console's renderer, a memory processor). */
readonly processors?: readonly Processor[];
/** Install the pipeline as the process's (the default). */
readonly install?: boolean;
/** Told once, with the run's warning. */
readonly onWarning?: (message: string) => void;
/** For a test: the exporter's `fetch`, default endpoint, retry and sleep (see `OtlpExporterOptions`). */
readonly exporter?: Omit<OtlpExporterOptions, "onWarning">;
readonly clock?: () => bigint;
readonly random?: (n: number) => Uint8Array;
};How startTelemetry starts.
otel.Startedtypeno test imports ittype Started<R extends Declarations> = {
readonly pipeline: Pipeline;
readonly telemetry: Telemetry<R>;
readonly config: OtelConfig;
/** The `OTEL_*` values that were not valid, each with the default used (FR-005). */
readonly configWarnings: readonly string[];
};A started telemetry: the pipeline, the harness's telemetry on it, and the configuration and its warnings.
otel.startTelemetryfunctionno test imports itfunction startTelemetry<const R extends Declarations>(options: StartOptions<R>): Started<R>The telemetry of a process, from its environment (FR-005, FR-014 to FR-017): the configuration resolved from the OTEL_* variables, a resource (service.name, process.runtime.*, os.type, host.arch; never a host's or a person's name), AsyncLocalStorage for the current span with the parent from TRACEPARENT and TRACESTATE, a batch processor exporting spans and one exporting log records and metrics over OTLP/HTTP JSON (none where the SDK is disabled or no signal is exported), a journal where asked, the processors given, and the metrics collected every OTEL_METRIC_EXPORT_INTERVAL. Installed as the process's pipeline unless install is false.
otel.traceProcessfunctionno test imports itfunction traceProcess<T extends { readonly code: number; }>(argv: readonly string[], run: (env: Readonly<Record<string, string>>) => Promise<T>): Promise<T>Runs a program in a process client span (FR-018): process.executable.name and process.command_args as commandShape gives them (the program and its option names, never a value, FR-006), process.exit.code, error where it is not 0. run is given the TRACEPARENT and TRACESTATE to add to the program's environment. With no pipeline installed, run({}) and nothing else.
otel.traceHttpClientfunctionno test imports itfunction traceHttpClient<T>(method: string, url: string, send: (headers: Readonly<Record<string, string>>) => Promise<T>, status: (value: T) => number | undefined): Promise<T>Sends a request in an http.client span (FR-018): http.request.method, url.full redacted (FR-006), server.address, server.port, http.response.status_code (status of what send gives; undefined where no answer came), error from 400 up or with no answer. send is given the traceparent (and tracestate) headers to add. With no pipeline installed, send({}) and nothing else.
otel.untracedfunctionno test imports itfunction untraced<F extends object>(handler: F): FA serve handler (or any function) marked so that traceServer makes no span for it: the OTLP receiver, so it never traces itself.
otel.traceServerfunctionno test imports itfunction traceServer(request: Request, handle: () => Promise<Response> | Response, handler?: object | undefined): Promise<Response> | ResponseAnswers a request in an http.server span (FR-018) whose parent is the request's traceparent and tracestate (the process's own parent where it has none): http.request.method, url.path, url.scheme, server.address, server.port, http.response.status_code, error from 500 up. With no pipeline installed, or a handler marked untraced, handle() and nothing else.
otel.ReceiverSinkstypeno test imports ittype ReceiverSinks = {
readonly onTraces?: (batches: readonly TraceBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
readonly onLogs?: (batches: readonly LogBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
readonly onMetrics?: (batches: readonly MetricBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
};What a receiver hands decoded requests to; a sink may answer with a partial success (signals it rejected, and why).
otel.otlpReceiverfunctionno test imports itfunction otlpReceiver(sinks: ReceiverSinks): (request: Request) => Promise<Response>An OTLP/HTTP JSON receiver, as a handler for serve (FR-019): POST /v1/traces, /v1/logs and /v1/metrics with a JSON body (gzip-encoded or not) decoded by the kernel (FR-004) and handed to the sink; 415 for any content type but application/json (protobuf 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 ({}, or partialSuccess where the sink rejected some) otherwise. Errors are google.rpc.Status JSON. The handler is untraced.
PROBE_TIMEOUT_MSconstconst PROBE_TIMEOUT_MS: 150The longest a probe of the default endpoint waits for an answer (FR-015).
EXIT_WAIT_MSconstconst EXIT_WAIT_MS: 1000The longest the runtime waits at exit for what is left to be sent (FR-015).
RETRYABLE_STATUSESconstno test imports itconst RETRYABLE_STATUSES: ReadonlySet<number>The statuses an export is retried on (FR-014).
systemClockfunctionfunction systemClock(): () => bigintA clock of nanoseconds since the Unix epoch, from performance.timeOrigin and performance.now(): monotonic within the process.
systemRandomfunctionfunction systemRandom(n: number): Uint8Array<ArrayBufferLike>n random bytes from Web Crypto.
asyncContextManagerfunctionfunction asyncContextManager(): ContextManagerA context manager on AsyncLocalStorage (FR-017): the current span is carried across await, timers and callbacks.
environmentParentfunctionfunction environmentParent(env?: Readonly<Record<string, string | undefined>>): SpanContext | undefinedThe parent a process takes from its environment's TRACEPARENT and TRACESTATE (FR-017); undefined where there is no valid one.
processAttributesfunctionno test imports itfunction processAttributes(): Readonly<Record<string, AttributeValue>>The attributes of the process that describe where it runs, by the semantic conventions: process.runtime.name and .version, os.type and host.arch. Never a host's or a person's name.
OtlpExporterOptionstypeno test imports ittype OtlpExporterOptions = {
/** The `fetch` to use (the platform's by default). */
readonly fetch?: typeof fetch;
… (759 characters)type OtlpExporterOptions = {
/** The `fetch` to use (the platform's by default). */
readonly fetch?: typeof fetch;
/** Told once, the first time an export fails or no collector answers (FR-014, FR-024). */
readonly onWarning?: (message: string) => void;
/** The base endpoint probed where a signal has none configured (`http://localhost:4318`). */
readonly defaultEndpoint?: string;
/** How long the probe waits (150 ms). */
readonly probeTimeoutMs?: number;
/** The first wait before a retry with no `Retry-After`; each next one doubles (100 ms). */
readonly retryBaseMs?: number;
/** How a wait is spent (a timer by default); it rejects when `signal` aborts. */
readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
};How the OTLP exporter sends. Everything here is for a test or a special host; the defaults are the specification's.
OtlpExportertypeno test imports ittype OtlpExporter = Exporter & {
/** The warning said, once, if an export failed or no collector answered. */
readonly warning: () => string | undefined;
};The OTLP exporter: an Exporter, and the warning it gave, if any.
otlpExporterfunctionfunction otlpExporter(exporters: { readonly logs: ExporterConfig; readonly metrics: ExporterConfig; readonly traces: ExporterConfig; }, options?: OtlpExporterOptions): OtlpExporterThe OTLP/HTTP JSON exporter over fetch (FR-014): each export is a POST of the request as JSON to the signal's endpoint, with content-type: application/json and the configured headers, within the signal's timeout; 429, 502, 503 and 504 are retried after the 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 export never throws. Where a signal has no endpoint configured, the default is probed for at most 150 ms before the first export, and nothing is sent where nothing answers (FR-015). The first failure is told to onWarning, once. shutdown waits for the exports in flight within its time, then aborts them, so nothing keeps the process alive.
JournalOptionstypeno test imports ittype JournalOptions = {
/** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
readonly pat… (663 characters)type JournalOptions = {
/** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
readonly path: string;
/** The size past which the file is rotated before the next line (10 MiB by default). */
readonly maxBytes?: number;
/** How many older files are kept (3 by default; 0 keeps none). */
readonly keep?: number;
/** Where given, a journal file last written more than this many days ago is removed when the journal starts and at each rotation. */
readonly maxAgeDays?: number;
/** The clock that ages files, in milliseconds since the epoch (`Date.now` by default; a test gives its own). */
readonly now?: () => number;
};Where and how a journal is kept.
journalExporterfunctionfunction journalExporter(options: JournalOptions): ExporterAn 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 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: <path>.<keep> removed, each <path>.<i> renamed <path>.<i+1>, and the file renamed <path>.1. Where maxAgeDays is given, a journal file last written longer ago than that is removed before the first line and after each rotation. A write that fails is a failure result, never a throw.
journalProcessorfunctionno test imports itfunction journalProcessor(options: JournalOptions & BatchOptions): ExportingProcessorA batch processor that keeps a journal (FR-016): spans and log records batched as options says, metric collections as they come.
onlySignalsfunctionno test imports itfunction onlySignals(processor: ExportingProcessor, signals: Iterable<SignalName>): ExportingProcessorA processor that hands on only the signals named: the others never reach processor.
RUNTIME_SIGNALSconstno test imports itconst RUNTIME_SIGNALS: Registry<{ readonly process: { readonly signal: "span"; readonly spanKind: "client"; readonly rol… (1541 characters)const RUNTIME_SIGNALS: Registry<{ readonly process: { readonly signal: "span"; readonly spanKind: "client"; readonly role: "detail"; readonly description: "A program run by proc: its name and option names alone (FR-006), and its exit status."; readonly attributes: { readonly "process.executable.name": "string"; readonly "process.command_args": "string[]"; readonly "process.exit.code?": "int"; }; }; readonly "http.client": { readonly signal: "span"; readonly spanKind: "client"; readonly role: "detail"; readonly description: "A request made by the HTTP client; the URL redacted (FR-006)."; readonly attributes: { readonly "http.request.method": "string"; readonly "url.full": "string"; readonly "server.address": "string"; readonly "server.port?": "int"; readonly "http.response.status_code?": "int"; readonly "error.type?": "string"; }; }; readonly "http.server": { readonly signal: "span"; readonly spanKind: "server"; readonly role: "detail"; readonly description: "A request answered by serve; its parent is the request's traceparent."; readonly attributes: { readonly "http.request.method": "string"; readonly "url.path": "string"; readonly "url.scheme": "string"; readonly "server.address?": "string"; readonly "server.port?": "int"; readonly "http.response.status_code?": "int"; }; }; readonly "otel.warning": { readonly signal: "log"; readonly severity: 13; readonly role: "none"; readonly description: "Signals were not sent: an export failed, no collector answered, or the wait at exit ran out."; readonly attributes: {}; }; }>The signals the runtime itself makes (FR-018), and the warning that signals were not sent (FR-014).
RuntimeKindstypeno test imports ittype RuntimeKinds = (typeof RUNTIME_SIGNALS)["kinds"];The kinds of the runtime's own registry.
RUNTIME_SCOPEconstno test imports itconst RUNTIME_SCOPE: ScopeThe scope of the runtime's own signals.
PipelineOptionstypeno test imports ittype PipelineOptions = {
readonly resource: Resource;
/** The processors every signal goes to; more may be added wit… (848 characters)type PipelineOptions = {
readonly resource: Resource;
/** The processors every signal goes to; more may be added with `addProcessor`. */
readonly processors?: readonly Processor[];
/** `AsyncLocalStorage` by default (FR-017). */
readonly context?: ContextManager;
/** The parent of a span started with no current one (`environmentParent()` in `startTelemetry`). */
readonly parent?: SpanContext;
readonly clock?: () => bigint;
readonly random?: (n: number) => Uint8Array;
readonly sampler?: Sampler;
readonly limits?: Limits;
/** How often the metrics are collected and handed on (never where 0 or absent). */
readonly metricIntervalMs?: number;
/** Told once, with the first warning. */
readonly onWarning?: (message: string) => void;
/** What a processor threw. */
readonly onError?: (error: unknown) => void;
};What a pipeline is made from. Everything but the resource has a default for a real process.
PipelineItemtypeno test imports ittype PipelineItem = { readonly kind: "span"; readonly span: SpanData } | { readonly kind: "log"; readonly record: LogRecord };A finished span or a log record handed to a pipeline whole.
Pipelineinterfaceno test imports itinterface PipelineThe signals of a process: one resource, one context, the processors, and the telemetries made on them.
| Member | Type | What it is |
|---|---|---|
resource | Resource | The resource every signal carries. |
context | ContextManager | The context manager every telemetry of the pipeline shares. |
parent | SpanContext | undefined | The parent of a span started with no current one. |
telemetry | <const R extends Declarations>(registry: Registry<R>, scope: Scope) => Telemetry<R> | A telemetry of a registry and scope on this pipeline: its signals go to every processor of the pipeline. |
addProcessor | (processor: Processor) => () => void | Adds a processor (a console's renderer, a memory processor); returns what removes it. |
emit | (item: PipelineItem, source: Source) => void | 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 processor as a telemetry hands its own (onEnd, onLog), with the resource and scope it came from; nothing once shut down. |
warn | (message: string) => void | Says a warning; only the first of a run is kept, told to the listeners and recorded as an otel.warning log record. |
warning | () => string | undefined | The warning of the run, if any: what the console says once, dimmed, at the end (FR-024). |
onWarning | (listener: (message: string) => void) => () => void | Calls listener with the warning when it is said (at once, if it already has been); returns what removes it. |
stats | () => ProcessorStats | What the exporting processors did, by signal, summed. |
forceFlush | (timeoutMs?: number | undefined) => Promise<FlushResult> | Collects the metrics and flushes every processor, within timeoutMs. |
shutdown | (timeoutMs?: number | undefined) => Promise<FlushResult> | Ends what is open, collects the metrics, and shuts every processor down within timeoutMs (at most one second by default, FR-015); where that time runs out, gives up and says so as the run's warning. Uninstalls the pipeline where it is installed. |
createPipelinefunctionfunction createPipeline(options: PipelineOptions): PipelineA pipeline (FR-012, FR-017): the processors every signal goes to, one AsyncLocalStorage context, one clock and source of random bytes, and the telemetries made on it. It is not installed; install makes it the process's.
installfunctionno test imports itfunction install(pipeline: Pipeline): voidMakes pipeline the process's: the runtime's own signals (FR-018) go to it from now on. It replaces any installed before.
uninstallfunctionno test imports itfunction uninstall(): voidUninstalls the process's pipeline, if any; the runtime's hooks are no-ops again.
installedfunctionfunction installed(): Pipeline | undefinedThe pipeline installed for this process, if any.
StartOptionstypeno test imports ittype StartOptions<R extends Declarations> = {
/** The harness's own signals. */
readonly registry: Registry<R>;
/*… (1138 characters)type StartOptions<R extends Declarations> = {
/** The harness's own signals. */
readonly registry: Registry<R>;
/** The harness's name: `service.name` where `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` do not say it, and the scope's name. */
readonly service?: string;
/** The harness's version, for its scope. */
readonly version?: string;
/** The `OTEL_*` variables and `TRACEPARENT` (the process's environment by default). */
readonly env?: Readonly<Record<string, string | undefined>>;
/** Keep a journal (FR-016). */
readonly journal?: JournalOptions;
/** More processors (the console's renderer, a memory processor). */
readonly processors?: readonly Processor[];
/** Install the pipeline as the process's (the default). */
readonly install?: boolean;
/** Told once, with the run's warning. */
readonly onWarning?: (message: string) => void;
/** For a test: the exporter's `fetch`, default endpoint, retry and sleep (see `OtlpExporterOptions`). */
readonly exporter?: Omit<OtlpExporterOptions, "onWarning">;
readonly clock?: () => bigint;
readonly random?: (n: number) => Uint8Array;
};How startTelemetry starts.
Startedtypetype Started<R extends Declarations> = {
readonly pipeline: Pipeline;
readonly telemetry: Telemetry<R>;
readonly config: OtelConfig;
/** The `OTEL_*` values that were not valid, each with the default used (FR-005). */
readonly configWarnings: readonly string[];
};A started telemetry: the pipeline, the harness's telemetry on it, and the configuration and its warnings.
startTelemetryfunctionfunction startTelemetry<const R extends Declarations>(options: StartOptions<R>): Started<R>The telemetry of a process, from its environment (FR-005, FR-014 to FR-017): the configuration resolved from the OTEL_* variables, a resource (service.name, process.runtime.*, os.type, host.arch; never a host's or a person's name), AsyncLocalStorage for the current span with the parent from TRACEPARENT and TRACESTATE, a batch processor exporting spans and one exporting log records and metrics over OTLP/HTTP JSON (none where the SDK is disabled or no signal is exported), a journal where asked, the processors given, and the metrics collected every OTEL_METRIC_EXPORT_INTERVAL. Installed as the process's pipeline unless install is false.
traceProcessfunctionno test imports itfunction traceProcess<T extends { readonly code: number; }>(argv: readonly string[], run: (env: Readonly<Record<string, string>>) => Promise<T>): Promise<T>Runs a program in a process client span (FR-018): process.executable.name and process.command_args as commandShape gives them (the program and its option names, never a value, FR-006), process.exit.code, error where it is not 0. run is given the TRACEPARENT and TRACESTATE to add to the program's environment. With no pipeline installed, run({}) and nothing else.
traceHttpClientfunctionno test imports itfunction traceHttpClient<T>(method: string, url: string, send: (headers: Readonly<Record<string, string>>) => Promise<T>, status: (value: T) => number | undefined): Promise<T>Sends a request in an http.client span (FR-018): http.request.method, url.full redacted (FR-006), server.address, server.port, http.response.status_code (status of what send gives; undefined where no answer came), error from 400 up or with no answer. send is given the traceparent (and tracestate) headers to add. With no pipeline installed, send({}) and nothing else.
untracedfunctionfunction untraced<F extends object>(handler: F): FA serve handler (or any function) marked so that traceServer makes no span for it: the OTLP receiver, so it never traces itself.
traceServerfunctionno test imports itfunction traceServer(request: Request, handle: () => Promise<Response> | Response, handler?: object | undefined): Promise<Response> | ResponseAnswers a request in an http.server span (FR-018) whose parent is the request's traceparent and tracestate (the process's own parent where it has none): http.request.method, url.path, url.scheme, server.address, server.port, http.response.status_code, error from 500 up. With no pipeline installed, or a handler marked untraced, handle() and nothing else.
ReceiverSinkstypeno test imports ittype ReceiverSinks = {
readonly onTraces?: (batches: readonly TraceBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
readonly onLogs?: (batches: readonly LogBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
readonly onMetrics?: (batches: readonly MetricBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
};What a receiver hands decoded requests to; a sink may answer with a partial success (signals it rejected, and why).
otlpReceiverfunctionfunction otlpReceiver(sinks: ReceiverSinks): (request: Request) => Promise<Response>An OTLP/HTTP JSON receiver, as a handler for serve (FR-019): POST /v1/traces, /v1/logs and /v1/metrics with a JSON body (gzip-encoded or not) decoded by the kernel (FR-004) and handed to the sink; 415 for any content type but application/json (protobuf 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 ({}, or partialSuccess where the sink rejected some) otherwise. Errors are google.rpc.Status JSON. The handler is untraced.