@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/host/console.d.ts +80 -0
- package/dist/host/console.js +188 -0
- package/dist/host/mod.d.ts +15 -0
- package/dist/host/mod.js +16 -0
- package/dist/host/otel.d.ts +280 -0
- package/dist/host/otel.js +848 -0
- package/dist/mod.d.ts +17 -0
- package/dist/mod.js +18 -0
- package/dist/otel.d.ts +365 -0
- package/dist/otel.js +686 -0
- package/dist/otlp.d.ts +83 -0
- package/dist/otlp.js +634 -0
- package/dist/render.d.ts +111 -0
- package/dist/render.js +368 -0
- package/dist/signals.d.ts +371 -0
- package/dist/signals.js +800 -0
- package/package.json +76 -4
- package/src/host/console.ts +253 -0
- package/src/host/mod.ts +16 -0
- package/src/host/otel.ts +1068 -0
- package/src/mod.ts +18 -0
- package/src/otel.ts +919 -0
- package/src/otlp.ts +721 -0
- package/src/render.ts +489 -0
- package/src/signals.ts +1175 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Intellectual Frontiers
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,9 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @intellectual-frontiers/telemetry
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
OpenTelemetry-native signals for TypeScript, written from the specification itself with no OpenTelemetry package: the data model, W3C Trace Context, OTLP/HTTP JSON, typed signals, a pure renderer of the console, and a host that exports, journals and shows them; the same code on Bun and Node 26.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
bun add @intellectual-frontiers/telemetry # or: npm install @intellectual-frontiers/telemetry
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/telemetry
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import type { AnyValue, Attributes } from "../otel.js";
|
|
2
|
+
import { type Mode } from "../render.js";
|
|
3
|
+
import { type Declarations, type FlushResult, type Processor, type ProcessorStats, type Registry } from "../signals.js";
|
|
4
|
+
import { type Look } from "@intellectual-frontiers/system/tty";
|
|
5
|
+
/** A processor whose exports the console watches, to say at the end where signals were not sent (an `ExportingProcessor`). */
|
|
6
|
+
export type Watched = {
|
|
7
|
+
stats(): ProcessorStats;
|
|
8
|
+
forceFlush(timeoutMs: number): Promise<FlushResult>;
|
|
9
|
+
};
|
|
10
|
+
/** How a console is made; everything but the registry has a default. */
|
|
11
|
+
export type ConsoleOptions = {
|
|
12
|
+
/** The registry that gives each kind its presentation role. */
|
|
13
|
+
readonly registry: Registry<Declarations>;
|
|
14
|
+
/** The mode; by default the one `IFC_CONSOLE` names, else `attended` at a terminal and `plain` elsewhere. */
|
|
15
|
+
readonly mode?: Mode;
|
|
16
|
+
/** The stream written to: standard error by default, standard output in `json` mode. */
|
|
17
|
+
readonly stream?: "stdout" | "stderr";
|
|
18
|
+
/** What the terminal shows; by default `currentLook` of the stream. */
|
|
19
|
+
readonly look?: Look;
|
|
20
|
+
/** The environment the mode is read from; this process's by default. */
|
|
21
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
22
|
+
/** The exporting processors to ask, at shutdown, whether everything was sent. */
|
|
23
|
+
readonly exporters?: readonly Watched[];
|
|
24
|
+
/** How often the live region is redrawn, in milliseconds (200 by default). */
|
|
25
|
+
readonly tickMs?: number;
|
|
26
|
+
/** The time now, in nanoseconds since the Unix epoch, for elapsed times; the system's clock by default. */
|
|
27
|
+
readonly now?: () => bigint;
|
|
28
|
+
/** A signal's text from its kind and attributes (`render.ts`'s `defaultText` by default). */
|
|
29
|
+
readonly text?: (name: string, attributes: Attributes) => string;
|
|
30
|
+
};
|
|
31
|
+
/** The console: a processor, with its mode, and a way to add an export warning said at the end. */
|
|
32
|
+
export type ConsoleProcessor = Processor & {
|
|
33
|
+
/** The mode it writes in. */
|
|
34
|
+
readonly mode: Mode;
|
|
35
|
+
/** Keeps a warning about an export, said once, dimmed, at the end of the run (FR-024). */
|
|
36
|
+
warn(message: string): void;
|
|
37
|
+
};
|
|
38
|
+
/** A console processor: renders every signal it is handed and writes the frames for a person (FR-026). */
|
|
39
|
+
export declare function consoleProcessor(options: ConsoleOptions): ConsoleProcessor;
|
|
40
|
+
/** The kind of log record an uncaught exception or an unhandled rejection becomes, to spread into a registry. */
|
|
41
|
+
export declare const uncaughtSignals: {
|
|
42
|
+
readonly exception: {
|
|
43
|
+
readonly signal: "log";
|
|
44
|
+
readonly role: "error";
|
|
45
|
+
readonly severity: 21;
|
|
46
|
+
readonly description: "An uncaught exception or an unhandled rejection, after which the process exits with status 1.";
|
|
47
|
+
readonly attributes: {
|
|
48
|
+
readonly "exception.type": "string";
|
|
49
|
+
readonly "exception.message": "string";
|
|
50
|
+
readonly "exception.stacktrace?": "string";
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/** The attributes of an `exception` log record. */
|
|
55
|
+
export type ExceptionAttributes = {
|
|
56
|
+
readonly "exception.type": string;
|
|
57
|
+
readonly "exception.message": string;
|
|
58
|
+
readonly "exception.stacktrace"?: string;
|
|
59
|
+
};
|
|
60
|
+
/** What `installUncaught` needs of a telemetry: a `Telemetry` whose registry declares `uncaughtSignals` is one. */
|
|
61
|
+
export type UncaughtTarget = {
|
|
62
|
+
log(kind: "exception", attributes: ExceptionAttributes, body?: AnyValue): void;
|
|
63
|
+
shutdown(timeoutMs: number): Promise<FlushResult>;
|
|
64
|
+
};
|
|
65
|
+
/** How `installUncaught` ends the process: the most time the telemetry has to shut down, and the exit (`proc.exit` by default). */
|
|
66
|
+
export type UncaughtOptions = {
|
|
67
|
+
readonly timeoutMs?: number;
|
|
68
|
+
readonly exit?: (code: number) => void;
|
|
69
|
+
};
|
|
70
|
+
/** The attributes and the text of the error log record for a thrown value. */
|
|
71
|
+
export declare function exceptionOf(thrown: unknown): {
|
|
72
|
+
readonly attributes: ExceptionAttributes;
|
|
73
|
+
readonly text: string;
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* On an uncaught exception or an unhandled rejection: an `exception` log record through the telemetry (so the console renders it), the
|
|
77
|
+
* telemetry shut down within `timeoutMs` (1000 by default), and exit status 1 (FR-026). A second one while this happens exits at once.
|
|
78
|
+
* Returns what removes the handlers.
|
|
79
|
+
*/
|
|
80
|
+
export declare function installUncaught(telemetry: UncaughtTarget, options?: UncaughtOptions): () => void;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// Spec: 0001-telemetry FR-024
|
|
2
|
+
/**
|
|
3
|
+
* The console: the one code of IFC TypeScript that writes for a person to standard output or standard error (commons 0001-telemetry FR-024).
|
|
4
|
+
* It is a processor of the signal pipeline (`src/signals.ts`'s `Processor`): every span that starts, records progress or ends and every
|
|
5
|
+
* log record goes through the kernel's pure renderer (`src/render.ts`), and the frames it returns are written. The mode is the one asked
|
|
6
|
+
* for (the option, else `IFC_CONSOLE=attended|plain|quiet|silent|json`), else `attended` at a terminal and `plain` elsewhere
|
|
7
|
+
* (`system/tty`'s look decides what a terminal is, and whether colour and emoji may be used). In `attended` mode a timer, which never
|
|
8
|
+
* keeps the process alive, redraws the live region so elapsed times move. At shutdown it asks the exporting processors it watches to
|
|
9
|
+
* flush, says once, dimmed, where signals were not sent (FR-024), ends the live region and waits, a bounded time, for the writes to drain.
|
|
10
|
+
*
|
|
11
|
+
* `installUncaught` makes an uncaught exception or an unhandled rejection an error log record (`exception.type`, `exception.message`,
|
|
12
|
+
* `exception.stacktrace`) emitted through the telemetry, so it is rendered and exported like any other signal; the telemetry is then shut
|
|
13
|
+
* down (bounded) and the process exits with status 1. Its kind, `exception`, is declared in `uncaughtSignals`, to spread into a registry.
|
|
14
|
+
*
|
|
15
|
+
* It depends only on the kernel's interfaces, so it plugs into any telemetry.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { createTelemetry, defineSignals } from "../signals.ts";
|
|
20
|
+
* import { consoleProcessor, installUncaught, uncaughtSignals } from "./console.ts";
|
|
21
|
+
* const registry = defineSignals({ ...uncaughtSignals, "build.step": { signal: "span", role: "step", attributes: { target: "string" } } });
|
|
22
|
+
* const telemetry = createTelemetry({ registry, processors: [consoleProcessor({ registry })], ...rest });
|
|
23
|
+
* installUncaught(telemetry);
|
|
24
|
+
* ```
|
|
25
|
+
*
|
|
26
|
+
* @module
|
|
27
|
+
*/
|
|
28
|
+
import process from "node:process";
|
|
29
|
+
import { clearInterval, clearTimeout, setInterval, setTimeout } from "node:timers";
|
|
30
|
+
import { SEVERITY } from "../otel.js";
|
|
31
|
+
import { chooseMode, initial, parseMode, render } from "../render.js";
|
|
32
|
+
import { describeError } from "../signals.js";
|
|
33
|
+
import { env, exit } from "@intellectual-frontiers/system/proc";
|
|
34
|
+
import { currentLook } from "@intellectual-frontiers/system/tty";
|
|
35
|
+
const systemNow = () => BigInt(Date.now()) * 1000000n;
|
|
36
|
+
/** A promise that settles with `promise`, or with `fallback` once `ms` have passed; the timer never keeps the process alive. */
|
|
37
|
+
function within(promise, ms, fallback) {
|
|
38
|
+
return new Promise((resolve) => {
|
|
39
|
+
const timer = setTimeout(() => resolve(fallback), Math.max(0, ms));
|
|
40
|
+
timer.unref();
|
|
41
|
+
void promise.then((v) => {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
resolve(v);
|
|
44
|
+
}, () => {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
resolve(fallback);
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
function unsent(stats) {
|
|
51
|
+
let count = 0;
|
|
52
|
+
let lastError;
|
|
53
|
+
for (const s of [stats.traces, stats.logs, stats.metrics]) {
|
|
54
|
+
count += s.failed + s.dropped + s.rejected;
|
|
55
|
+
lastError = s.lastError ?? lastError;
|
|
56
|
+
}
|
|
57
|
+
return { count, lastError };
|
|
58
|
+
}
|
|
59
|
+
/** A console processor: renders every signal it is handed and writes the frames for a person (FR-026). */
|
|
60
|
+
export function consoleProcessor(options) {
|
|
61
|
+
const vars = options.env ?? env.toObject();
|
|
62
|
+
const requested = options.mode ?? vars["IFC_CONSOLE"];
|
|
63
|
+
const asked = requested === undefined ? undefined : parseMode(requested);
|
|
64
|
+
const streamName = options.stream ?? (asked === "json" ? "stdout" : "stderr");
|
|
65
|
+
const look = options.look ?? currentLook(streamName);
|
|
66
|
+
const mode = options.mode ?? chooseMode({ requested, tty: look.tty });
|
|
67
|
+
const stream = streamName === "stdout" ? process.stdout : process.stderr;
|
|
68
|
+
const now = options.now ?? systemNow;
|
|
69
|
+
let state = initial({
|
|
70
|
+
mode,
|
|
71
|
+
look,
|
|
72
|
+
registry: options.registry,
|
|
73
|
+
...(options.text === undefined ? {} : { text: options.text }),
|
|
74
|
+
});
|
|
75
|
+
let timer;
|
|
76
|
+
const write = (frames) => {
|
|
77
|
+
if (frames === "")
|
|
78
|
+
return;
|
|
79
|
+
try {
|
|
80
|
+
stream.write(frames);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// A closed stream: nothing more can be shown, and the program goes on.
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const feed = (input) => {
|
|
87
|
+
const step = render(state, input, now());
|
|
88
|
+
state = step.state;
|
|
89
|
+
write(step.frames);
|
|
90
|
+
if (mode === "attended" && timer === undefined && state.live.length > 0 && !state.finished) {
|
|
91
|
+
timer = setInterval(() => feed({ kind: "tick" }), Math.max(20, options.tickMs ?? 200));
|
|
92
|
+
timer.unref();
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
const stopTimer = () => {
|
|
96
|
+
if (timer !== undefined)
|
|
97
|
+
clearInterval(timer);
|
|
98
|
+
timer = undefined;
|
|
99
|
+
};
|
|
100
|
+
const drained = () => new Promise((resolve) => {
|
|
101
|
+
try {
|
|
102
|
+
stream.write("", () => resolve());
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
resolve();
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
return {
|
|
109
|
+
mode,
|
|
110
|
+
warn: (message) => feed({ kind: "export-warning", message }),
|
|
111
|
+
onStart: (span, source) => feed({ kind: "span-start", span, source }),
|
|
112
|
+
onEvent: (span, event, source) => feed({ kind: "span-event", span, event, source }),
|
|
113
|
+
onEnd: (span, source) => feed({ kind: "span-end", span, source }),
|
|
114
|
+
onLog: (record, source) => feed({ kind: "log", record, source }),
|
|
115
|
+
forceFlush: async (timeoutMs) => {
|
|
116
|
+
await within(drained(), timeoutMs, undefined);
|
|
117
|
+
return { kind: "done" };
|
|
118
|
+
},
|
|
119
|
+
shutdown: async (timeoutMs) => {
|
|
120
|
+
const started = Date.now();
|
|
121
|
+
const watched = options.exporters ?? [];
|
|
122
|
+
if (watched.length > 0) {
|
|
123
|
+
const flushed = await within(Promise.all(watched.map((w) => w.forceFlush(timeoutMs))), timeoutMs, watched.map(() => ({ kind: "timeout" })));
|
|
124
|
+
if (flushed.some((f) => f.kind === "timeout"))
|
|
125
|
+
feed({ kind: "export-warning", message: "the signals were not all sent: no collector answered in time" });
|
|
126
|
+
for (const w of watched) {
|
|
127
|
+
const u = unsent(w.stats());
|
|
128
|
+
if (u.count > 0) {
|
|
129
|
+
feed({
|
|
130
|
+
kind: "export-warning",
|
|
131
|
+
message: `${u.count} signals were not sent${u.lastError === undefined ? "" : `: ${u.lastError}`}`,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
stopTimer();
|
|
137
|
+
feed({ kind: "finish" });
|
|
138
|
+
await within(drained(), Math.max(0, timeoutMs - (Date.now() - started)), undefined);
|
|
139
|
+
return { kind: "done" };
|
|
140
|
+
},
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/** The kind of log record an uncaught exception or an unhandled rejection becomes, to spread into a registry. */
|
|
144
|
+
export const uncaughtSignals = {
|
|
145
|
+
exception: {
|
|
146
|
+
signal: "log",
|
|
147
|
+
role: "error",
|
|
148
|
+
severity: SEVERITY.FATAL,
|
|
149
|
+
description: "An uncaught exception or an unhandled rejection, after which the process exits with status 1.",
|
|
150
|
+
attributes: { "exception.type": "string", "exception.message": "string", "exception.stacktrace?": "string" },
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
/** The attributes and the text of the error log record for a thrown value. */
|
|
154
|
+
export function exceptionOf(thrown) {
|
|
155
|
+
const type = thrown instanceof Error ? thrown.name : typeof thrown;
|
|
156
|
+
const message = describeError(thrown);
|
|
157
|
+
const stack = thrown instanceof Error && thrown.stack !== undefined ? { "exception.stacktrace": thrown.stack } : {};
|
|
158
|
+
return { attributes: { "exception.type": type, "exception.message": message, ...stack }, text: `${type}: ${message}` };
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* On an uncaught exception or an unhandled rejection: an `exception` log record through the telemetry (so the console renders it), the
|
|
162
|
+
* telemetry shut down within `timeoutMs` (1000 by default), and exit status 1 (FR-026). A second one while this happens exits at once.
|
|
163
|
+
* Returns what removes the handlers.
|
|
164
|
+
*/
|
|
165
|
+
export function installUncaught(telemetry, options = {}) {
|
|
166
|
+
const timeoutMs = options.timeoutMs ?? 1000;
|
|
167
|
+
const end = options.exit ?? ((code) => exit(code));
|
|
168
|
+
let handling = false;
|
|
169
|
+
const handle = (thrown) => {
|
|
170
|
+
if (handling)
|
|
171
|
+
return end(1);
|
|
172
|
+
handling = true;
|
|
173
|
+
const e = exceptionOf(thrown);
|
|
174
|
+
try {
|
|
175
|
+
telemetry.log("exception", e.attributes, e.text);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
// A telemetry already shut down: the exit status still says it.
|
|
179
|
+
}
|
|
180
|
+
void within(telemetry.shutdown(timeoutMs).then(() => undefined), timeoutMs + 100, undefined).then(() => end(1));
|
|
181
|
+
};
|
|
182
|
+
process.on("uncaughtException", handle);
|
|
183
|
+
process.on("unhandledRejection", handle);
|
|
184
|
+
return () => {
|
|
185
|
+
process.off("uncaughtException", handle);
|
|
186
|
+
process.off("unhandledRejection", handle);
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host of Telemetry (its specification 0001-telemetry): the exporter over OTLP/HTTP JSON with its journal, its probe and the pipeline a process installs (as `otel`, with `startTelemetry`), and the console that
|
|
3
|
+
* renders signals for a person and is the one writer to standard output and standard error for that (as `console`). It names `node:` builtins and no vendor's global, and depends on the library `system` for
|
|
4
|
+
* the process, the terminal and the files.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* ```ts
|
|
8
|
+
* import { otel } from "@intellectual-frontiers/telemetry/host";
|
|
9
|
+
* const run = otel.startTelemetry({ registry, service: "build" });
|
|
10
|
+
* ```
|
|
11
|
+
*
|
|
12
|
+
* @module
|
|
13
|
+
*/
|
|
14
|
+
export * as console from "./console.js";
|
|
15
|
+
export * as otel from "./otel.js";
|
package/dist/host/mod.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Spec: 0001-telemetry FR-026
|
|
2
|
+
/**
|
|
3
|
+
* The host of Telemetry (its specification 0001-telemetry): the exporter over OTLP/HTTP JSON with its journal, its probe and the pipeline a process installs (as `otel`, with `startTelemetry`), and the console that
|
|
4
|
+
* renders signals for a person and is the one writer to standard output and standard error for that (as `console`). It names `node:` builtins and no vendor's global, and depends on the library `system` for
|
|
5
|
+
* the process, the terminal and the files.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { otel } from "@intellectual-frontiers/telemetry/host";
|
|
10
|
+
* const run = otel.startTelemetry({ registry, service: "build" });
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @module
|
|
14
|
+
*/
|
|
15
|
+
export * as console from "./console.js";
|
|
16
|
+
export * as otel from "./otel.js";
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { type AttributeValue, type Limits, type OtelConfig, type Resource, type Sampler, type Scope, type SignalName, type LogRecord, type SpanContext, type SpanData } from "../otel.js";
|
|
2
|
+
import { type ExportResponse, type LogBatch, type MetricBatch, type TraceBatch } from "../otlp.js";
|
|
3
|
+
import { type BatchOptions, type ContextManager, type Declarations, type ExportingProcessor, type Exporter, type FlushResult, type Processor, type ProcessorStats, type Registry, type Source, type Telemetry } from "../signals.js";
|
|
4
|
+
/** The longest a probe of the default endpoint waits for an answer (FR-015). */
|
|
5
|
+
export declare const PROBE_TIMEOUT_MS = 150;
|
|
6
|
+
/** The longest the runtime waits at exit for what is left to be sent (FR-015). */
|
|
7
|
+
export declare const EXIT_WAIT_MS = 1000;
|
|
8
|
+
/** The statuses an export is retried on (FR-014). */
|
|
9
|
+
export declare const RETRYABLE_STATUSES: ReadonlySet<number>;
|
|
10
|
+
/** A clock of nanoseconds since the Unix epoch, from `performance.timeOrigin` and `performance.now()`: monotonic within the process. */
|
|
11
|
+
export declare function systemClock(): () => bigint;
|
|
12
|
+
/** `n` random bytes from Web Crypto. */
|
|
13
|
+
export declare function systemRandom(n: number): Uint8Array;
|
|
14
|
+
/** A context manager on `AsyncLocalStorage` (FR-017): the current span is carried across `await`, timers and callbacks. */
|
|
15
|
+
export declare function asyncContextManager(): ContextManager;
|
|
16
|
+
/** The parent a process takes from its environment's `TRACEPARENT` and `TRACESTATE` (FR-017); undefined where there is no valid one. */
|
|
17
|
+
export declare function environmentParent(env?: Readonly<Record<string, string | undefined>>): SpanContext | undefined;
|
|
18
|
+
/**
|
|
19
|
+
* The attributes of the process that describe where it runs, by the semantic conventions: `process.runtime.name` and `.version`,
|
|
20
|
+
* `os.type` and `host.arch`. Never a host's or a person's name.
|
|
21
|
+
*/
|
|
22
|
+
export declare function processAttributes(): Readonly<Record<string, AttributeValue>>;
|
|
23
|
+
/** How the OTLP exporter sends. Everything here is for a test or a special host; the defaults are the specification's. */
|
|
24
|
+
export type OtlpExporterOptions = {
|
|
25
|
+
/** The `fetch` to use (the platform's by default). */
|
|
26
|
+
readonly fetch?: typeof fetch;
|
|
27
|
+
/** Told once, the first time an export fails or no collector answers (FR-014, FR-024). */
|
|
28
|
+
readonly onWarning?: (message: string) => void;
|
|
29
|
+
/** The base endpoint probed where a signal has none configured (`http://localhost:4318`). */
|
|
30
|
+
readonly defaultEndpoint?: string;
|
|
31
|
+
/** How long the probe waits (150 ms). */
|
|
32
|
+
readonly probeTimeoutMs?: number;
|
|
33
|
+
/** The first wait before a retry with no `Retry-After`; each next one doubles (100 ms). */
|
|
34
|
+
readonly retryBaseMs?: number;
|
|
35
|
+
/** How a wait is spent (a timer by default); it rejects when `signal` aborts. */
|
|
36
|
+
readonly sleep?: (ms: number, signal: AbortSignal) => Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
/** The OTLP exporter: an `Exporter`, and the warning it gave, if any. */
|
|
39
|
+
export type OtlpExporter = Exporter & {
|
|
40
|
+
/** The warning said, once, if an export failed or no collector answered. */
|
|
41
|
+
readonly warning: () => string | undefined;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* 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
|
|
45
|
+
* `content-type: application/json` and the configured headers, within the signal's timeout; 429, 502, 503 and 504 are retried after the
|
|
46
|
+
* 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
|
|
47
|
+
* export never throws. Where a signal has no endpoint configured, the default is probed for at most 150 ms before the first export, and
|
|
48
|
+
* nothing is sent where nothing answers (FR-015). The first failure is told to `onWarning`, once. `shutdown` waits for the exports in
|
|
49
|
+
* flight within its time, then aborts them, so nothing keeps the process alive.
|
|
50
|
+
*/
|
|
51
|
+
export declare function otlpExporter(exporters: OtelConfig["exporters"], options?: OtlpExporterOptions): OtlpExporter;
|
|
52
|
+
/** Where and how a journal is kept. */
|
|
53
|
+
export type JournalOptions = {
|
|
54
|
+
/** The file; the older ones are `<path>.1` (the newest) to `<path>.<keep>`. */
|
|
55
|
+
readonly path: string;
|
|
56
|
+
/** The size past which the file is rotated before the next line (10 MiB by default). */
|
|
57
|
+
readonly maxBytes?: number;
|
|
58
|
+
/** How many older files are kept (3 by default; 0 keeps none). */
|
|
59
|
+
readonly keep?: number;
|
|
60
|
+
/** Where given, a journal file last written more than this many days ago is removed when the journal starts and at each rotation. */
|
|
61
|
+
readonly maxAgeDays?: number;
|
|
62
|
+
/** The clock that ages files, in milliseconds since the epoch (`Date.now` by default; a test gives its own). */
|
|
63
|
+
readonly now?: () => number;
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* 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
|
|
67
|
+
* 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:
|
|
68
|
+
* `<path>.<keep>` removed, each `<path>.<i>` renamed `<path>.<i+1>`, and the file renamed `<path>.1`. Where `maxAgeDays` is given, a
|
|
69
|
+
* journal file last written longer ago than that is removed before the first line and after each rotation. A write that fails is a
|
|
70
|
+
* failure result, never a throw.
|
|
71
|
+
*/
|
|
72
|
+
export declare function journalExporter(options: JournalOptions): Exporter;
|
|
73
|
+
/** A batch processor that keeps a journal (FR-016): spans and log records batched as `options` says, metric collections as they come. */
|
|
74
|
+
export declare function journalProcessor(options: JournalOptions & BatchOptions): ExportingProcessor;
|
|
75
|
+
/** A processor that hands on only the signals named: the others never reach `processor`. */
|
|
76
|
+
export declare function onlySignals(processor: ExportingProcessor, signals: Iterable<SignalName>): ExportingProcessor;
|
|
77
|
+
/**
|
|
78
|
+
* An exporter shared by `users` processors: its `shutdown` stops the exporter only when the last of them shuts it down, so that one
|
|
79
|
+
* processor's shutdown never aborts another's exports in flight.
|
|
80
|
+
*/
|
|
81
|
+
export declare function shareExporter(exporter: Exporter, users: number): Exporter;
|
|
82
|
+
/** The signals the runtime itself makes (FR-018), and the warning that signals were not sent (FR-014). */
|
|
83
|
+
export declare const RUNTIME_SIGNALS: Registry<{
|
|
84
|
+
readonly process: {
|
|
85
|
+
readonly signal: "span";
|
|
86
|
+
readonly spanKind: "client";
|
|
87
|
+
readonly role: "detail";
|
|
88
|
+
readonly description: "A program run by proc: its name and option names alone (FR-006), and its exit status.";
|
|
89
|
+
readonly attributes: {
|
|
90
|
+
readonly "process.executable.name": "string";
|
|
91
|
+
readonly "process.command_args": "string[]";
|
|
92
|
+
readonly "process.exit.code?": "int";
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
readonly "http.client": {
|
|
96
|
+
readonly signal: "span";
|
|
97
|
+
readonly spanKind: "client";
|
|
98
|
+
readonly role: "detail";
|
|
99
|
+
readonly description: "A request made by the HTTP client; the URL redacted (FR-006).";
|
|
100
|
+
readonly attributes: {
|
|
101
|
+
readonly "http.request.method": "string";
|
|
102
|
+
readonly "url.full": "string";
|
|
103
|
+
readonly "server.address": "string";
|
|
104
|
+
readonly "server.port?": "int";
|
|
105
|
+
readonly "http.response.status_code?": "int";
|
|
106
|
+
readonly "error.type?": "string";
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
readonly "http.server": {
|
|
110
|
+
readonly signal: "span";
|
|
111
|
+
readonly spanKind: "server";
|
|
112
|
+
readonly role: "detail";
|
|
113
|
+
readonly description: "A request answered by serve; its parent is the request's traceparent.";
|
|
114
|
+
readonly attributes: {
|
|
115
|
+
readonly "http.request.method": "string";
|
|
116
|
+
readonly "url.path": "string";
|
|
117
|
+
readonly "url.scheme": "string";
|
|
118
|
+
readonly "server.address?": "string";
|
|
119
|
+
readonly "server.port?": "int";
|
|
120
|
+
readonly "http.response.status_code?": "int";
|
|
121
|
+
};
|
|
122
|
+
};
|
|
123
|
+
readonly "otel.warning": {
|
|
124
|
+
readonly signal: "log";
|
|
125
|
+
readonly severity: 13;
|
|
126
|
+
readonly role: "none";
|
|
127
|
+
readonly description: "Signals were not sent: an export failed, no collector answered, or the wait at exit ran out.";
|
|
128
|
+
readonly attributes: {};
|
|
129
|
+
};
|
|
130
|
+
}>;
|
|
131
|
+
/** The kinds of the runtime's own registry. */
|
|
132
|
+
export type RuntimeKinds = (typeof RUNTIME_SIGNALS)["kinds"];
|
|
133
|
+
/** The scope of the runtime's own signals. */
|
|
134
|
+
export declare const RUNTIME_SCOPE: Scope;
|
|
135
|
+
/** What a pipeline is made from. Everything but the resource has a default for a real process. */
|
|
136
|
+
export type PipelineOptions = {
|
|
137
|
+
readonly resource: Resource;
|
|
138
|
+
/** The processors every signal goes to; more may be added with `addProcessor`. */
|
|
139
|
+
readonly processors?: readonly Processor[];
|
|
140
|
+
/** `AsyncLocalStorage` by default (FR-017). */
|
|
141
|
+
readonly context?: ContextManager;
|
|
142
|
+
/** The parent of a span started with no current one (`environmentParent()` in `startTelemetry`). */
|
|
143
|
+
readonly parent?: SpanContext;
|
|
144
|
+
readonly clock?: () => bigint;
|
|
145
|
+
readonly random?: (n: number) => Uint8Array;
|
|
146
|
+
readonly sampler?: Sampler;
|
|
147
|
+
readonly limits?: Limits;
|
|
148
|
+
/** How often the metrics are collected and handed on (never where 0 or absent). */
|
|
149
|
+
readonly metricIntervalMs?: number;
|
|
150
|
+
/** Told once, with the first warning. */
|
|
151
|
+
readonly onWarning?: (message: string) => void;
|
|
152
|
+
/** What a processor threw. */
|
|
153
|
+
readonly onError?: (error: unknown) => void;
|
|
154
|
+
};
|
|
155
|
+
/** A finished span or a log record handed to a pipeline whole. */
|
|
156
|
+
export type PipelineItem = {
|
|
157
|
+
readonly kind: "span";
|
|
158
|
+
readonly span: SpanData;
|
|
159
|
+
} | {
|
|
160
|
+
readonly kind: "log";
|
|
161
|
+
readonly record: LogRecord;
|
|
162
|
+
};
|
|
163
|
+
/** The signals of a process: one resource, one context, the processors, and the telemetries made on them. */
|
|
164
|
+
export interface Pipeline {
|
|
165
|
+
/** The resource every signal carries. */
|
|
166
|
+
readonly resource: Resource;
|
|
167
|
+
/** The context manager every telemetry of the pipeline shares. */
|
|
168
|
+
readonly context: ContextManager;
|
|
169
|
+
/** The parent of a span started with no current one. */
|
|
170
|
+
readonly parent: SpanContext | undefined;
|
|
171
|
+
/** A telemetry of a registry and scope on this pipeline: its signals go to every processor of the pipeline. */
|
|
172
|
+
telemetry<const R extends Declarations>(registry: Registry<R>, scope: Scope): Telemetry<R>;
|
|
173
|
+
/** Adds a processor (a console's renderer, a memory processor); returns what removes it. */
|
|
174
|
+
addProcessor(processor: Processor): () => void;
|
|
175
|
+
/**
|
|
176
|
+
* 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
|
|
177
|
+
* processor as a telemetry hands its own (`onEnd`, `onLog`), with the resource and scope it came from; nothing once shut down.
|
|
178
|
+
*/
|
|
179
|
+
emit(item: PipelineItem, source: Source): void;
|
|
180
|
+
/** Says a warning; only the first of a run is kept, told to the listeners and recorded as an `otel.warning` log record. */
|
|
181
|
+
warn(message: string): void;
|
|
182
|
+
/** The warning of the run, if any: what the console says once, dimmed, at the end (FR-024). */
|
|
183
|
+
warning(): string | undefined;
|
|
184
|
+
/** Calls `listener` with the warning when it is said (at once, if it already has been); returns what removes it. */
|
|
185
|
+
onWarning(listener: (message: string) => void): () => void;
|
|
186
|
+
/** What the exporting processors did, by signal, summed. */
|
|
187
|
+
stats(): ProcessorStats;
|
|
188
|
+
/** Collects the metrics and flushes every processor, within `timeoutMs`. */
|
|
189
|
+
forceFlush(timeoutMs?: number): Promise<FlushResult>;
|
|
190
|
+
/**
|
|
191
|
+
* Ends what is open, collects the metrics, and shuts every processor down within `timeoutMs` (at most one second by default, FR-015);
|
|
192
|
+
* where that time runs out, gives up and says so as the run's warning. Uninstalls the pipeline where it is installed.
|
|
193
|
+
*/
|
|
194
|
+
shutdown(timeoutMs?: number): Promise<FlushResult>;
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* A pipeline (FR-012, FR-017): the processors every signal goes to, one `AsyncLocalStorage` context, one clock and source of random
|
|
198
|
+
* bytes, and the telemetries made on it. It is not installed; `install` makes it the process's.
|
|
199
|
+
*/
|
|
200
|
+
export declare function createPipeline(options: PipelineOptions): Pipeline;
|
|
201
|
+
/** Makes `pipeline` the process's: the runtime's own signals (FR-018) go to it from now on. It replaces any installed before. */
|
|
202
|
+
export declare function install(pipeline: Pipeline): void;
|
|
203
|
+
/** Uninstalls the process's pipeline, if any; the runtime's hooks are no-ops again. */
|
|
204
|
+
export declare function uninstall(): void;
|
|
205
|
+
/** The pipeline installed for this process, if any. */
|
|
206
|
+
export declare function installed(): Pipeline | undefined;
|
|
207
|
+
/** How `startTelemetry` starts. */
|
|
208
|
+
export type StartOptions<R extends Declarations> = {
|
|
209
|
+
/** The harness's own signals. */
|
|
210
|
+
readonly registry: Registry<R>;
|
|
211
|
+
/** The harness's name: `service.name` where `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES` do not say it, and the scope's name. */
|
|
212
|
+
readonly service?: string;
|
|
213
|
+
/** The harness's version, for its scope. */
|
|
214
|
+
readonly version?: string;
|
|
215
|
+
/** The `OTEL_*` variables and `TRACEPARENT` (the process's environment by default). */
|
|
216
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
217
|
+
/** Keep a journal (FR-016). */
|
|
218
|
+
readonly journal?: JournalOptions;
|
|
219
|
+
/** More processors (the console's renderer, a memory processor). */
|
|
220
|
+
readonly processors?: readonly Processor[];
|
|
221
|
+
/** Install the pipeline as the process's (the default). */
|
|
222
|
+
readonly install?: boolean;
|
|
223
|
+
/** Told once, with the run's warning. */
|
|
224
|
+
readonly onWarning?: (message: string) => void;
|
|
225
|
+
/** For a test: the exporter's `fetch`, default endpoint, retry and sleep (see `OtlpExporterOptions`). */
|
|
226
|
+
readonly exporter?: Omit<OtlpExporterOptions, "onWarning">;
|
|
227
|
+
readonly clock?: () => bigint;
|
|
228
|
+
readonly random?: (n: number) => Uint8Array;
|
|
229
|
+
};
|
|
230
|
+
/** A started telemetry: the pipeline, the harness's telemetry on it, and the configuration and its warnings. */
|
|
231
|
+
export type Started<R extends Declarations> = {
|
|
232
|
+
readonly pipeline: Pipeline;
|
|
233
|
+
readonly telemetry: Telemetry<R>;
|
|
234
|
+
readonly config: OtelConfig;
|
|
235
|
+
/** The `OTEL_*` values that were not valid, each with the default used (FR-005). */
|
|
236
|
+
readonly configWarnings: readonly string[];
|
|
237
|
+
};
|
|
238
|
+
/**
|
|
239
|
+
* The telemetry of a process, from its environment (FR-005, FR-014 to FR-017): the configuration resolved from the `OTEL_*` variables, a
|
|
240
|
+
* resource (`service.name`, `process.runtime.*`, `os.type`, `host.arch`; never a host's or a person's name), `AsyncLocalStorage` for the
|
|
241
|
+
* current span with the parent from `TRACEPARENT` and `TRACESTATE`, a batch processor exporting spans and one exporting log records and
|
|
242
|
+
* metrics over OTLP/HTTP JSON (none where the SDK is disabled or no signal is exported), a journal where asked, the processors given, and
|
|
243
|
+
* the metrics collected every `OTEL_METRIC_EXPORT_INTERVAL`. Installed as the process's pipeline unless `install` is false.
|
|
244
|
+
*/
|
|
245
|
+
export declare function startTelemetry<const R extends Declarations>(options: StartOptions<R>): Started<R>;
|
|
246
|
+
/**
|
|
247
|
+
* Runs a program in a `process` client span (FR-018): `process.executable.name` and `process.command_args` as `commandShape` gives them
|
|
248
|
+
* (the program and its option names, never a value, FR-006), `process.exit.code`, `error` where it is not 0. `run` is given the
|
|
249
|
+
* `TRACEPARENT` and `TRACESTATE` to add to the program's environment. With no pipeline installed, `run({})` and nothing else.
|
|
250
|
+
*/
|
|
251
|
+
export declare function traceProcess<T extends {
|
|
252
|
+
readonly code: number;
|
|
253
|
+
}>(argv: readonly string[], run: (env: Readonly<Record<string, string>>) => Promise<T>): Promise<T>;
|
|
254
|
+
/**
|
|
255
|
+
* Sends a request in an `http.client` span (FR-018): `http.request.method`, `url.full` redacted (FR-006), `server.address`, `server.port`,
|
|
256
|
+
* `http.response.status_code` (`status` of what `send` gives; undefined where no answer came), `error` from 400 up or with no answer.
|
|
257
|
+
* `send` is given the `traceparent` (and `tracestate`) headers to add. With no pipeline installed, `send({})` and nothing else.
|
|
258
|
+
*/
|
|
259
|
+
export declare function traceHttpClient<T>(method: string, url: string, send: (headers: Readonly<Record<string, string>>) => Promise<T>, status: (value: T) => number | undefined): Promise<T>;
|
|
260
|
+
/** A serve handler (or any function) marked so that `traceServer` makes no span for it: the OTLP receiver, so it never traces itself. */
|
|
261
|
+
export declare function untraced<F extends object>(handler: F): F;
|
|
262
|
+
/**
|
|
263
|
+
* Answers a request in an `http.server` span (FR-018) whose parent is the request's `traceparent` and `tracestate` (the process's own
|
|
264
|
+
* parent where it has none): `http.request.method`, `url.path`, `url.scheme`, `server.address`, `server.port`,
|
|
265
|
+
* `http.response.status_code`, `error` from 500 up. With no pipeline installed, or a handler marked `untraced`, `handle()` and nothing else.
|
|
266
|
+
*/
|
|
267
|
+
export declare function traceServer(request: Request, handle: () => Response | Promise<Response>, handler?: object): Response | Promise<Response>;
|
|
268
|
+
/** What a receiver hands decoded requests to; a sink may answer with a partial success (signals it rejected, and why). */
|
|
269
|
+
export type ReceiverSinks = {
|
|
270
|
+
readonly onTraces?: (batches: readonly TraceBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
|
|
271
|
+
readonly onLogs?: (batches: readonly LogBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
|
|
272
|
+
readonly onMetrics?: (batches: readonly MetricBatch[]) => void | ExportResponse | Promise<void | ExportResponse>;
|
|
273
|
+
};
|
|
274
|
+
/**
|
|
275
|
+
* An OTLP/HTTP JSON receiver, as a handler for `serve` (FR-019): `POST /v1/traces`, `/v1/logs` and `/v1/metrics` with a JSON body
|
|
276
|
+
* (gzip-encoded or not) decoded by the kernel (FR-004) and handed to the sink; 415 for any content type but `application/json` (protobuf
|
|
277
|
+
* 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
|
|
278
|
+
* (`{}`, or `partialSuccess` where the sink rejected some) otherwise. Errors are `google.rpc.Status` JSON. The handler is `untraced`.
|
|
279
|
+
*/
|
|
280
|
+
export declare function otlpReceiver(sinks: ReceiverSinks): (request: Request) => Promise<Response>;
|