IF Commons GitHub

signals

Written to: 1 requirement: 1 proved, 0 partly, 0 failing, 0 with no test recorded. 0001-telemetry FR-009

Typed signals and the pipeline they go through (commons 0001-telemetry FR-009 to FR-013). defineSignals declares each kind of signal 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 severity, a metric's unit and bounds, the attributes that are secret, and its presentation role; emitting a kind that is not declared, an attribute of the wrong type or a missing required attribute does not compile. createTelemetry makes the tracer, logger and meter of 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 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 made, to its processors: the in-memory one, the simple one and the batch one, whose forceFlush and shutdown resolve within their time whatever an exporter does.

import { createTelemetry, defineSignals, memoryProcessor } from "./signals.ts";
import { ok } from "@intellectual-frontiers/core";
const registry = defineSignals({
  "build.step": { signal: "span", role: "step", attributes: { target: "string", "jobs?": "int" } },
  "build.files": { signal: "counter", role: "none", unit: "{file}", attributes: { target: "string" } },
});
const memory = memoryProcessor();
let t = 0n;
const telemetry = createTelemetry({
  registry, resource: { attributes: { "service.name": "build" } }, scope: { name: "build" },
  clock: () => t++, random: (n) => new Uint8Array(n).fill(7), processors: [memory],
});
telemetry.span("build.step", { target: "site" }, () => {
  telemetry.add("build.files", 3, { target: "site" });
  return ok("built");
});
memory.spans[0]?.status; // { kind: "ok" }

Source: commons/telemetry/src/signals.ts

18 of 94 exports are imported by a test of the run. A test that imports an export may not call it or check what it returns.

signalsnamespace
namespace signals
signals.AttributeTypetypeno test imports it
type AttributeType = "string" | "boolean" | "int" | "double" | "bytes" | "string[]" | "boolean[]" | "int[]" | "double[]";

The type of a declared attribute. int takes a number (cut to an integer) or a bigint, and is written as an OTLP integer.

signals.AttributeSchematypeno test imports it
type AttributeSchema = Readonly<Record<string, AttributeType>>;

The attributes a kind declares: a name (ending in ? where it is optional) to its type.

signals.AttributeValueOftypeno test imports it
type AttributeValueOf = {
  readonly string: string;
  readonly boolean: boolean;
  readonly int: number | bigint;
  readonly double: number;
  readonly bytes: Uint8Array;
  readonly "string[]": readonly string[];
  readonly "boolean[]": readonly boolean[];
  readonly "int[]": readonly (number | bigint)[];
  readonly "double[]": readonly number[];
};

The value an attribute of a type takes.

signals.AttributesFortypeno test imports it
type AttributesFor<S extends AttributeSchema> = Simplify<
  { readonly [K in keyof S & string as K extends `${string}?` ? never : K]: AttributeValueOf[S[K]] } & {
    readonly [K in keyof S & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[S[K]];
  }
>;

The attributes object a schema asks for: its required names, and its optional ones (declared with ?) without the ?.

signals.Roletypeno test imports it
type Role = "step" | "detail" | "progress" | "result" | "hint" | "warning" | "error" | "pending" | "action" | "none";

How a kind is presented to a person: the renderer shows every role but none. pending (⏳, not set up yet) and action (⚡, a step that is the person's to take) are neither warnings nor errors (FR-027).

signals.SpanDeclarationtypeno test imports it
type SpanDeclaration = Common & { readonly signal: "span"; readonly spanKind?: SpanKind };

A kind of span; its span kind is internal unless said.

signals.LogDeclarationtypeno test imports it
type LogDeclaration = Common & { readonly signal: "log"; readonly severity: SeverityNumber };

A kind of log event, with its severity.

signals.InstrumentDeclarationtypeno test imports it
type InstrumentDeclaration = Common & { readonly signal: "counter" | "updown" | "gauge"; readonly unit: string };

A kind of counter (monotonic), up-down counter or gauge, with its unit (UCUM, as ms, By, {file}).

signals.HistogramDeclarationtypeno test imports it
type HistogramDeclaration = Common & { readonly signal: "histogram"; readonly unit: string; readonly bounds?: readonly number[] };

A kind of histogram, with its unit and, optionally, its explicit bucket bounds (OpenTelemetry's defaults otherwise).

signals.SignalDeclarationtypeno test imports it
type SignalDeclaration = SpanDeclaration | LogDeclaration | InstrumentDeclaration | HistogramDeclaration;

The declaration of one kind of signal.

signals.SignalTypetypeno test imports it
type SignalType = SignalDeclaration["signal"];

What a declaration declares: span, log, counter, updown, gauge or histogram.

signals.Declarationstypeno test imports it
type Declarations = Readonly<Record<string, SignalDeclaration>>;

The declarations of a registry, by kind name.

signals.Registrytypeno test imports it
type Registry<R extends Declarations> = { readonly kinds: R };

A registry of signal kinds, made by defineSignals.

signals.KindOftypeno test imports it
type KindOf<R extends Declarations, S extends SignalType> = {
  [K in keyof R & string]: R[K]["signal"] extends S ? K : never;
}[keyof R & string];

The names of the kinds of a registry's declarations that declare one of the signal types S.

signals.AttributesOftypeno test imports it
type AttributesOf<R extends Declarations, K extends keyof R> = AttributesFor<R[K]["attributes"]>;

The attributes object a kind asks for.

signals.defineSignalsfunctionno test imports it
function defineSignals<const R extends Declarations>(kinds: R): Registry<R>

A registry of signal kinds (FR-009). The declarations are checked once here, and a mistake in them is a programming error that throws: an attribute type that does not exist, a secret attribute that is not declared, histogram bounds that do not increase.

signals.roleOffunctionno test imports it
function roleOf(registry: Registry<Readonly<Record<string, SignalDeclaration>>>, name: string): Role | undefined

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.

signals.declarationOffunctionno test imports it
function declarationOf(registry: Registry<Readonly<Record<string, SignalDeclaration>>>, name: string): SignalDeclaration | undefined

The declaration of a kind, by its name; undefined where not declared.

signals.ContextManagerinterfaceno test imports it
interface ContextManager

Where the current span's context is kept: a synchronous stack here, AsyncLocalStorage in the runtime.

MemberTypeWhat it is
active() => SpanContext | undefinedThe current context, if any.
with<T>(context: SpanContext | undefined, fn: () => T) => TRuns fn with context current, and restores the previous one after it returns or throws.
signals.stackContextManagerfunctionno test imports it
function stackContextManager(): ContextManager

A context manager on a synchronous stack: correct for synchronous code and up to the first await of an asynchronous function. Past it, use the span handle's own span and log, which name their parent, or the runtime's AsyncLocalStorage manager.

signals.Sourcetypeno test imports it
type Source = { readonly resource: Resource; readonly scope: Scope };

The resource and scope a signal came from; one object per telemetry, so a processor may group by it.

signals.SpanStarttypeno test imports it
type SpanStart = {
  readonly name: string;
  readonly context: SpanContext;
  readonly parentSpanId?: SpanId;
  readonly kind: SpanKind;
  readonly startTime: bigint;
  readonly attributes: Attributes;
};

A span as it starts: what a renderer needs to show it in progress.

signals.FlushResulttypeno test imports it
type FlushResult = { readonly kind: "done" } | { readonly kind: "timeout" };

How a flush or a shutdown ended: everything handed on, or the time given ran out.

signals.Processorinterfaceno test imports it
interface Processor

What a pipeline hands its signals to, in the order they were made.

MemberTypeWhat it is
onStart?((span: SpanStart, source: Source) => void)A span started.
onEvent?((span: SpanStart, event: SpanEvent, source: Source) => void)A span in progress recorded an event (progress among them).
onEnd?((span: SpanData, source: Source) => void)A span ended.
onLog?((record: LogRecord, source: Source) => void)A log record was emitted.
onMetrics?((metrics: readonly Metric[], source: Source) => void)Metrics were collected.
forceFlush(timeoutMs: number) => Promise<FlushResult>Hands on everything held, within timeoutMs.
shutdown(timeoutMs: number) => Promise<FlushResult>Hands on everything held and stops, within timeoutMs.
signals.ExportResulttypeno test imports it
type ExportResult =
  | { readonly kind: "success" }
  | { readonly kind: "partial"; readonly rejected: number; readonly message: string }
  | { readonly kind: "failure"; readonly message: string };

How an export went. partial: the receiver rejected some signals.

signals.Exporterinterfaceno test imports it
interface Exporter

What sends batches somewhere (the runtime's OTLP/HTTP exporter, a test's fake). It may be slow, fail or never answer.

MemberTypeWhat it is
exportTraces(batches: readonly TraceBatch[]) => Promise<ExportResult>Sends trace batches.
exportLogs(batches: readonly LogBatch[]) => Promise<ExportResult>Sends log batches.
exportMetrics(batches: readonly MetricBatch[]) => Promise<ExportResult>Sends metric batches.
shutdown(timeoutMs: number) => Promise<void>Stops, within timeoutMs.
signals.SignalStatstypeno test imports it
type SignalStats = {
  readonly exported: number;
  readonly failed: number;
  readonly rejected: number;
  readonly dropped: number;
  readonly lastError?: string;
};

What a processor did with one signal: spans, log records or metric data points exported, failed, rejected by a partial success, or dropped.

signals.ProcessorStatstypeno test imports it
type ProcessorStats = { readonly [S in SignalName]: SignalStats };

What an exporting processor did, by signal.

signals.ExportingProcessortypeno test imports it
type ExportingProcessor = Processor & { stats(): ProcessorStats };

A processor that exports, and says what it did.

signals.MemoryEntrytypeno test imports it
type MemoryEntry = | { readonly kind: "start"; readonly span: SpanStart; readonly source: Source } | { readonly kind… (466 characters)
type MemoryEntry =
  | { readonly kind: "start"; readonly span: SpanStart; readonly source: Source }
  | { readonly kind: "event"; readonly span: SpanStart; readonly event: SpanEvent; readonly source: Source }
  | { readonly kind: "end"; readonly span: SpanData; readonly source: Source }
  | { readonly kind: "log"; readonly record: LogRecord; readonly source: Source }
  | { readonly kind: "metrics"; readonly metrics: readonly Metric[]; readonly source: Source };

A recorded signal, in the order the memory processor received it.

signals.MemoryProcessortypeno test imports it
type MemoryProcessor = Processor & { /** Every signal, in order. */ readonly entries: readonly MemoryEntry[]; /** … (430 characters)
type MemoryProcessor = Processor & {
  /** Every signal, in order. */
  readonly entries: readonly MemoryEntry[];
  /** The finished spans, in the order they ended. */
  readonly spans: readonly SpanData[];
  /** The log records, in order. */
  readonly logs: readonly LogRecord[];
  /** The metric collections, in order. */
  readonly metrics: readonly (readonly Metric[])[];
  /** Forgets everything kept. */
  clear(): void;
};

A processor that keeps everything, for tests and the renderer.

signals.memoryProcessorfunctionno test imports it
function memoryProcessor(): MemoryProcessor

A processor that keeps every signal it receives (FR-012).

signals.Timertypeno test imports it
type Timer = { readonly set: (fn: () => void, ms: number) => unknown; readonly clear: (handle: unknown) => void };

A timer, so that a batch processor's schedule can be driven by a test.

signals.systemTimerconstno test imports it
const systemTimer: Timer

The host's timer; a scheduled export never keeps a process alive (unref where the host has it).

signals.simpleProcessorfunctionno test imports it
function simpleProcessor(exporter: Exporter, options?: { readonly exportTimeoutMs?: number | undefined; }): ExportingProcessor

A processor that exports each signal as it comes, one export at a time (FR-012).

signals.BatchOptionstypeno test imports it
type BatchOptions = {
  readonly maxQueueSize?: number;
  readonly maxExportBatchSize?: number;
  readonly scheduleDelayMs?: number;
  readonly exportTimeoutMs?: number;
  readonly timer?: Timer;
};

The settings of a batch processor, as OTEL_BSP_* and OTEL_BLRP_* give them (BatchConfig of ./otel.ts), and its timer.

signals.batchProcessorfunctionno test imports it
function batchProcessor(exporter: Exporter, options?: BatchOptions): ExportingProcessor

A processor that queues spans and log records (each at most maxQueueSize; what does not fit is dropped and counted, never blocking the caller) and exports them in batches of at most maxExportBatchSize: as soon as a full batch is waiting, else scheduleDelayMs after the first one queued. Metric collections are exported as they come. Exports run one at a time, each within exportTimeoutMs, and a batch leaves its queue only when it is sent (FR-012).

signals.LinkInputtypeno test imports it
type LinkInput = {
  readonly traceId: TraceId;
  readonly spanId: SpanId;
  readonly traceFlags: number;
  readonly traceState: TraceState;
  readonly attributes?: Attributes;
};

A link a new span makes to another span's context.

signals.SpanOptionstypeno test imports it
type SpanOptions = { readonly parent?: SpanContext | null; readonly links?: readonly LinkInput[] };

How a span starts: its parent (null for a new trace; the current context by default) and its links.

signals.LogOptionstypeno test imports it
type LogOptions = { readonly severity?: SeverityNumber };

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).

signals.SpanHandleinterfaceno test imports it
interface SpanHandle<R extends Declarations, K extends keyof R>

A span in progress, as the function it runs sees it.

MemberTypeWhat it is
contextSpanContextThe span's context.
recordingbooleanWhether the span is recorded (sampled, and the telemetry not shut down).
traceparentstringThe W3C traceparent to give what this span calls (a child process, an HTTP request).
tracestatestringThe W3C tracestate to give with it.
set(attributes: Partial<{ [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }>) => voidSets declared attributes of the span.
event(name: string, attributes?: Readonly<Record<string, AttributeValue>> | undefined) => voidRecords an event.
progress(done: number, total?: number | undefined) => voidRecords how far the work has come, as a progress event (progress.done, progress.total).
span<C extends KindOf<R, "span">, T>(kind: C, attributes: { [K in keyof ({ readonly [K in keyof R[C]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[C]["attributes"][K]]; } & { readonly [K in keyof R[C]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[C]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[C]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[C]["attributes"][K]]; } & { readonly [K in keyof R[C]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[C]["attributes"][K]] | undefined; })[K]; }, fn: (span: SpanHandle<R, C>) => T, options?: SpanOptions | undefined) => TRuns a child span of this one.
log<L extends KindOf<R, "log">>(kind: L, attributes: { [K in keyof ({ readonly [K in keyof R[L]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[L]["attributes"][K]]; } & { readonly [K in keyof R[L]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[L]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[L]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[L]["attributes"][K]]; } & { readonly [K in keyof R[L]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[L]["attributes"][K]] | undefined; })[K]; }, body?: AnyValue | undefined, options?: LogOptions | undefined) => voidEmits a log record in this span; its severity is the kind's unless options.severity gives another.
signals.Telemetryinterfaceno test imports it
interface Telemetry<R extends Declarations>

The tracer, logger and meter of one resource and scope, typed by a registry.

MemberTypeWhat it is
registryRegistry<R>The registry the kinds come from.
sourceSourceThe resource and scope every signal carries.
active() => SpanContext | undefinedThe current span's context, or the initial parent, if any.
span<K extends KindOf<R, "span">, T>(kind: K, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }, fn: (span: SpanHandle<R, K>) => T, options?: SpanOptions | undefined) => TRuns 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 result, error with the error's description for an Err, unset for any other value (a promise is waited for); a function that throws ends it with an exception event and error, and the exception is thrown on.
log<K extends KindOf<R, "log">>(kind: K, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }, body?: AnyValue | undefined, options?: LogOptions | undefined) => voidEmits 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.
add<K extends KindOf<R, "counter" | "updown">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Adds to a counter (a negative or non-finite increment is refused) or an up-down counter.
set<K extends KindOf<R, "gauge">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Sets a gauge.
record<K extends KindOf<R, "histogram">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Records a value in a histogram.
collect() => readonly Metric[]The metrics as they stand, cumulative since each series began (FR-013), also handed to every processor.
forceFlush(timeoutMs: number) => Promise<FlushResult>Collects the metrics and flushes every processor, within timeoutMs.
shutdown(timeoutMs: number) => Promise<FlushResult>Ends every open span as error, collects the metrics and shuts every processor down, within timeoutMs; nothing is recorded after.
signals.TelemetryOptionstypeno test imports it
type TelemetryOptions<R extends Declarations> = { readonly registry: Registry<R>; readonly resource: Resource; rea… (733 characters)
type TelemetryOptions<R extends Declarations> = {
  readonly registry: Registry<R>;
  readonly resource: Resource;
  readonly scope: Scope;
  /** Nanoseconds since the Unix epoch. */
  readonly clock: () => bigint;
  /** `n` random bytes. */
  readonly random: (n: number) => Uint8Array;
  readonly processors: readonly Processor[];
  /** A stack by default; the runtime gives `AsyncLocalStorage`. */
  readonly context?: ContextManager;
  /** The parent of a span started with no current span (from `TRACEPARENT`, say). */
  readonly parent?: SpanContext;
  readonly sampler?: Sampler;
  readonly limits?: Limits;
  /** What a processor threw; processors never break the program. */
  readonly onError?: (error: unknown) => void;
};

What a telemetry is made from (FR-011): everything that varies is the caller's.

signals.describeErrorfunctionno test imports it
function describeError(error: unknown): string

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.

signals.toAttributesfunctionno test imports it
function toAttributes(schema: Readonly<Record<string, AttributeType>>, attributes: object): Readonly<Record<string, AttributeValue>>

Typed attributes as OpenTelemetry attributes, by the schema: an int as a bigint; an undeclared or absent attribute left out.

signals.attributesKeyfunctionno test imports it
function attributesKey(attributes: Readonly<Record<string, AttributeValue>>): string

A canonical key of attributes, the same for equal sets in any order: one metric series for each (FR-013).

signals.createTelemetryfunctionno test imports it
function createTelemetry<const R extends Declarations>(options: TelemetryOptions<R>): Telemetry<R>

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 out, credentials replaced), limited and handed to each processor in the order it was made. Ids come from random, times from clock.

AttributeTypetypeno test imports it
type AttributeType = "string" | "boolean" | "int" | "double" | "bytes" | "string[]" | "boolean[]" | "int[]" | "double[]";

The type of a declared attribute. int takes a number (cut to an integer) or a bigint, and is written as an OTLP integer.

AttributeSchematypeno test imports it
type AttributeSchema = Readonly<Record<string, AttributeType>>;

The attributes a kind declares: a name (ending in ? where it is optional) to its type.

AttributeValueOftypeno test imports it
type AttributeValueOf = {
  readonly string: string;
  readonly boolean: boolean;
  readonly int: number | bigint;
  readonly double: number;
  readonly bytes: Uint8Array;
  readonly "string[]": readonly string[];
  readonly "boolean[]": readonly boolean[];
  readonly "int[]": readonly (number | bigint)[];
  readonly "double[]": readonly number[];
};

The value an attribute of a type takes.

AttributesFortypeno test imports it
type AttributesFor<S extends AttributeSchema> = Simplify<
  { readonly [K in keyof S & string as K extends `${string}?` ? never : K]: AttributeValueOf[S[K]] } & {
    readonly [K in keyof S & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[S[K]];
  }
>;

The attributes object a schema asks for: its required names, and its optional ones (declared with ?) without the ?.

Roletypeno test imports it
type Role = "step" | "detail" | "progress" | "result" | "hint" | "warning" | "error" | "pending" | "action" | "none";

How a kind is presented to a person: the renderer shows every role but none. pending (⏳, not set up yet) and action (⚡, a step that is the person's to take) are neither warnings nor errors (FR-027).

SpanDeclarationtypeno test imports it
type SpanDeclaration = Common & { readonly signal: "span"; readonly spanKind?: SpanKind };

A kind of span; its span kind is internal unless said.

LogDeclarationtypeno test imports it
type LogDeclaration = Common & { readonly signal: "log"; readonly severity: SeverityNumber };

A kind of log event, with its severity.

InstrumentDeclarationtypeno test imports it
type InstrumentDeclaration = Common & { readonly signal: "counter" | "updown" | "gauge"; readonly unit: string };

A kind of counter (monotonic), up-down counter or gauge, with its unit (UCUM, as ms, By, {file}).

HistogramDeclarationtypeno test imports it
type HistogramDeclaration = Common & { readonly signal: "histogram"; readonly unit: string; readonly bounds?: readonly number[] };

A kind of histogram, with its unit and, optionally, its explicit bucket bounds (OpenTelemetry's defaults otherwise).

SignalDeclarationtypeno test imports it
type SignalDeclaration = SpanDeclaration | LogDeclaration | InstrumentDeclaration | HistogramDeclaration;

The declaration of one kind of signal.

SignalTypetypeno test imports it
type SignalType = SignalDeclaration["signal"];

What a declaration declares: span, log, counter, updown, gauge or histogram.

Declarationstypeno test imports it
type Declarations = Readonly<Record<string, SignalDeclaration>>;

The declarations of a registry, by kind name.

Registrytypeno test imports it
type Registry<R extends Declarations> = { readonly kinds: R };

A registry of signal kinds, made by defineSignals.

KindOftype
type KindOf<R extends Declarations, S extends SignalType> = {
  [K in keyof R & string]: R[K]["signal"] extends S ? K : never;
}[keyof R & string];

The names of the kinds of a registry's declarations that declare one of the signal types S.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

AttributesOftype
type AttributesOf<R extends Declarations, K extends keyof R> = AttributesFor<R[K]["attributes"]>;

The attributes object a kind asks for.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

defineSignalsfunction
function defineSignals<const R extends Declarations>(kinds: R): Registry<R>

A registry of signal kinds (FR-009). The declarations are checked once here, and a mistake in them is a programming error that throws: an attribute type that does not exist, a secret attribute that is not declared, histogram bounds that do not increase.

Imported by 53 tests of the run (52 passed, 0 failed): the library's results

roleOffunction
function roleOf(registry: Registry<Readonly<Record<string, SignalDeclaration>>>, name: string): Role | undefined

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.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

declarationOffunction
function declarationOf(registry: Registry<Readonly<Record<string, SignalDeclaration>>>, name: string): SignalDeclaration | undefined

The declaration of a kind, by its name; undefined where not declared.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

ContextManagerinterfaceno test imports it
interface ContextManager

Where the current span's context is kept: a synchronous stack here, AsyncLocalStorage in the runtime.

MemberTypeWhat it is
active() => SpanContext | undefinedThe current context, if any.
with<T>(context: SpanContext | undefined, fn: () => T) => TRuns fn with context current, and restores the previous one after it returns or throws.
stackContextManagerfunctionno test imports it
function stackContextManager(): ContextManager

A context manager on a synchronous stack: correct for synchronous code and up to the first await of an asynchronous function. Past it, use the span handle's own span and log, which name their parent, or the runtime's AsyncLocalStorage manager.

Sourcetype
type Source = { readonly resource: Resource; readonly scope: Scope };

The resource and scope a signal came from; one object per telemetry, so a processor may group by it.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

SpanStarttypeno test imports it
type SpanStart = {
  readonly name: string;
  readonly context: SpanContext;
  readonly parentSpanId?: SpanId;
  readonly kind: SpanKind;
  readonly startTime: bigint;
  readonly attributes: Attributes;
};

A span as it starts: what a renderer needs to show it in progress.

FlushResulttype
type FlushResult = { readonly kind: "done" } | { readonly kind: "timeout" };

How a flush or a shutdown ended: everything handed on, or the time given ran out.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

Processorinterface
interface Processor

What a pipeline hands its signals to, in the order they were made.

MemberTypeWhat it is
onStart?((span: SpanStart, source: Source) => void)A span started.
onEvent?((span: SpanStart, event: SpanEvent, source: Source) => void)A span in progress recorded an event (progress among them).
onEnd?((span: SpanData, source: Source) => void)A span ended.
onLog?((record: LogRecord, source: Source) => void)A log record was emitted.
onMetrics?((metrics: readonly Metric[], source: Source) => void)Metrics were collected.
forceFlush(timeoutMs: number) => Promise<FlushResult>Hands on everything held, within timeoutMs.
shutdown(timeoutMs: number) => Promise<FlushResult>Hands on everything held and stops, within timeoutMs.

Imported by 24 tests of the run (24 passed, 0 failed): the library's results

ExportResulttype
type ExportResult =
  | { readonly kind: "success" }
  | { readonly kind: "partial"; readonly rejected: number; readonly message: string }
  | { readonly kind: "failure"; readonly message: string };

How an export went. partial: the receiver rejected some signals.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

Exporterinterface
interface Exporter

What sends batches somewhere (the runtime's OTLP/HTTP exporter, a test's fake). It may be slow, fail or never answer.

MemberTypeWhat it is
exportTraces(batches: readonly TraceBatch[]) => Promise<ExportResult>Sends trace batches.
exportLogs(batches: readonly LogBatch[]) => Promise<ExportResult>Sends log batches.
exportMetrics(batches: readonly MetricBatch[]) => Promise<ExportResult>Sends metric batches.
shutdown(timeoutMs: number) => Promise<void>Stops, within timeoutMs.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

SignalStatstypeno test imports it
type SignalStats = {
  readonly exported: number;
  readonly failed: number;
  readonly rejected: number;
  readonly dropped: number;
  readonly lastError?: string;
};

What a processor did with one signal: spans, log records or metric data points exported, failed, rejected by a partial success, or dropped.

ProcessorStatstypeno test imports it
type ProcessorStats = { readonly [S in SignalName]: SignalStats };

What an exporting processor did, by signal.

ExportingProcessortypeno test imports it
type ExportingProcessor = Processor & { stats(): ProcessorStats };

A processor that exports, and says what it did.

MemoryEntrytypeno test imports it
type MemoryEntry = | { readonly kind: "start"; readonly span: SpanStart; readonly source: Source } | { readonly kind… (466 characters)
type MemoryEntry =
  | { readonly kind: "start"; readonly span: SpanStart; readonly source: Source }
  | { readonly kind: "event"; readonly span: SpanStart; readonly event: SpanEvent; readonly source: Source }
  | { readonly kind: "end"; readonly span: SpanData; readonly source: Source }
  | { readonly kind: "log"; readonly record: LogRecord; readonly source: Source }
  | { readonly kind: "metrics"; readonly metrics: readonly Metric[]; readonly source: Source };

A recorded signal, in the order the memory processor received it.

MemoryProcessortypeno test imports it
type MemoryProcessor = Processor & { /** Every signal, in order. */ readonly entries: readonly MemoryEntry[]; /** … (430 characters)
type MemoryProcessor = Processor & {
  /** Every signal, in order. */
  readonly entries: readonly MemoryEntry[];
  /** The finished spans, in the order they ended. */
  readonly spans: readonly SpanData[];
  /** The log records, in order. */
  readonly logs: readonly LogRecord[];
  /** The metric collections, in order. */
  readonly metrics: readonly (readonly Metric[])[];
  /** Forgets everything kept. */
  clear(): void;
};

A processor that keeps everything, for tests and the renderer.

memoryProcessorfunction
function memoryProcessor(): MemoryProcessor

A processor that keeps every signal it receives (FR-012).

Imported by 36 tests of the run (35 passed, 0 failed): the library's results

Timertype
type Timer = { readonly set: (fn: () => void, ms: number) => unknown; readonly clear: (handle: unknown) => void };

A timer, so that a batch processor's schedule can be driven by a test.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

systemTimerconstno test imports it
const systemTimer: Timer

The host's timer; a scheduled export never keeps a process alive (unref where the host has it).

simpleProcessorfunction
function simpleProcessor(exporter: Exporter, options?: { readonly exportTimeoutMs?: number | undefined; }): ExportingProcessor

A processor that exports each signal as it comes, one export at a time (FR-012).

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

BatchOptionstypeno test imports it
type BatchOptions = {
  readonly maxQueueSize?: number;
  readonly maxExportBatchSize?: number;
  readonly scheduleDelayMs?: number;
  readonly exportTimeoutMs?: number;
  readonly timer?: Timer;
};

The settings of a batch processor, as OTEL_BSP_* and OTEL_BLRP_* give them (BatchConfig of ./otel.ts), and its timer.

batchProcessorfunction
function batchProcessor(exporter: Exporter, options?: BatchOptions): ExportingProcessor

A processor that queues spans and log records (each at most maxQueueSize; what does not fit is dropped and counted, never blocking the caller) and exports them in batches of at most maxExportBatchSize: as soon as a full batch is waiting, else scheduleDelayMs after the first one queued. Metric collections are exported as they come. Exports run one at a time, each within exportTimeoutMs, and a batch leaves its queue only when it is sent (FR-012).

Imported by 31 tests of the run (31 passed, 0 failed): the library's results

LinkInputtypeno test imports it
type LinkInput = {
  readonly traceId: TraceId;
  readonly spanId: SpanId;
  readonly traceFlags: number;
  readonly traceState: TraceState;
  readonly attributes?: Attributes;
};

A link a new span makes to another span's context.

SpanOptionstypeno test imports it
type SpanOptions = { readonly parent?: SpanContext | null; readonly links?: readonly LinkInput[] };

How a span starts: its parent (null for a new trace; the current context by default) and its links.

LogOptionstypeno test imports it
type LogOptions = { readonly severity?: SeverityNumber };

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).

SpanHandleinterfaceno test imports it
interface SpanHandle<R extends Declarations, K extends keyof R>

A span in progress, as the function it runs sees it.

MemberTypeWhat it is
contextSpanContextThe span's context.
recordingbooleanWhether the span is recorded (sampled, and the telemetry not shut down).
traceparentstringThe W3C traceparent to give what this span calls (a child process, an HTTP request).
tracestatestringThe W3C tracestate to give with it.
set(attributes: Partial<{ [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }>) => voidSets declared attributes of the span.
event(name: string, attributes?: Readonly<Record<string, AttributeValue>> | undefined) => voidRecords an event.
progress(done: number, total?: number | undefined) => voidRecords how far the work has come, as a progress event (progress.done, progress.total).
span<C extends KindOf<R, "span">, T>(kind: C, attributes: { [K in keyof ({ readonly [K in keyof R[C]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[C]["attributes"][K]]; } & { readonly [K in keyof R[C]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[C]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[C]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[C]["attributes"][K]]; } & { readonly [K in keyof R[C]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[C]["attributes"][K]] | undefined; })[K]; }, fn: (span: SpanHandle<R, C>) => T, options?: SpanOptions | undefined) => TRuns a child span of this one.
log<L extends KindOf<R, "log">>(kind: L, attributes: { [K in keyof ({ readonly [K in keyof R[L]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[L]["attributes"][K]]; } & { readonly [K in keyof R[L]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[L]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[L]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[L]["attributes"][K]]; } & { readonly [K in keyof R[L]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[L]["attributes"][K]] | undefined; })[K]; }, body?: AnyValue | undefined, options?: LogOptions | undefined) => voidEmits a log record in this span; its severity is the kind's unless options.severity gives another.
Telemetryinterface
interface Telemetry<R extends Declarations>

The tracer, logger and meter of one resource and scope, typed by a registry.

MemberTypeWhat it is
registryRegistry<R>The registry the kinds come from.
sourceSourceThe resource and scope every signal carries.
active() => SpanContext | undefinedThe current span's context, or the initial parent, if any.
span<K extends KindOf<R, "span">, T>(kind: K, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }, fn: (span: SpanHandle<R, K>) => T, options?: SpanOptions | undefined) => TRuns 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 result, error with the error's description for an Err, unset for any other value (a promise is waited for); a function that throws ends it with an exception event and error, and the exception is thrown on.
log<K extends KindOf<R, "log">>(kind: K, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }, body?: AnyValue | undefined, options?: LogOptions | undefined) => voidEmits 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.
add<K extends KindOf<R, "counter" | "updown">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Adds to a counter (a negative or non-finite increment is refused) or an up-down counter.
set<K extends KindOf<R, "gauge">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Sets a gauge.
record<K extends KindOf<R, "histogram">>(kind: K, value: number, attributes: { [K in keyof ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })]: ({ readonly [K in keyof R[K]["attributes"] & string as K extends `${string}?` ? never : K]: AttributeValueOf[R[K]["attributes"][K]]; } & { readonly [K in keyof R[K]["attributes"] & string as K extends `${infer N}?` ? N : never]?: AttributeValueOf[R[K]["attributes"][K]] | undefined; })[K]; }) => Result<void, string>Records a value in a histogram.
collect() => readonly Metric[]The metrics as they stand, cumulative since each series began (FR-013), also handed to every processor.
forceFlush(timeoutMs: number) => Promise<FlushResult>Collects the metrics and flushes every processor, within timeoutMs.
shutdown(timeoutMs: number) => Promise<FlushResult>Ends every open span as error, collects the metrics and shuts every processor down, within timeoutMs; nothing is recorded after.

Imported by 5 tests of the run (5 passed, 0 failed): the library's results

TelemetryOptionstype
type TelemetryOptions<R extends Declarations> = { readonly registry: Registry<R>; readonly resource: Resource; rea… (733 characters)
type TelemetryOptions<R extends Declarations> = {
  readonly registry: Registry<R>;
  readonly resource: Resource;
  readonly scope: Scope;
  /** Nanoseconds since the Unix epoch. */
  readonly clock: () => bigint;
  /** `n` random bytes. */
  readonly random: (n: number) => Uint8Array;
  readonly processors: readonly Processor[];
  /** A stack by default; the runtime gives `AsyncLocalStorage`. */
  readonly context?: ContextManager;
  /** The parent of a span started with no current span (from `TRACEPARENT`, say). */
  readonly parent?: SpanContext;
  readonly sampler?: Sampler;
  readonly limits?: Limits;
  /** What a processor threw; processors never break the program. */
  readonly onError?: (error: unknown) => void;
};

What a telemetry is made from (FR-011): everything that varies is the caller's.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

describeErrorfunction
function describeError(error: unknown): string

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.

Imported by 12 tests of the run (12 passed, 0 failed): the library's results

toAttributesfunctionno test imports it
function toAttributes(schema: Readonly<Record<string, AttributeType>>, attributes: object): Readonly<Record<string, AttributeValue>>

Typed attributes as OpenTelemetry attributes, by the schema: an int as a bigint; an undeclared or absent attribute left out.

attributesKeyfunctionno test imports it
function attributesKey(attributes: Readonly<Record<string, AttributeValue>>): string

A canonical key of attributes, the same for equal sets in any order: one metric series for each (FR-013).

createTelemetryfunction
function createTelemetry<const R extends Declarations>(options: TelemetryOptions<R>): Telemetry<R>

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 out, credentials replaced), limited and handed to each processor in the order it was made. Ids come from random, times from clock.

Imported by 33 tests of the run (32 passed, 0 failed): the library's results

Titles, headings, exports, tables, columns and requirements. Esc closes.