@intellectual-frontiers/telemetry 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +8 -2
- package/dist/host/console.d.ts +80 -0
- package/dist/host/console.js +188 -0
- package/dist/host/mod.d.ts +15 -0
- package/dist/host/mod.js +16 -0
- package/dist/host/otel.d.ts +280 -0
- package/dist/host/otel.js +848 -0
- package/dist/mod.d.ts +17 -0
- package/dist/mod.js +18 -0
- package/dist/otel.d.ts +365 -0
- package/dist/otel.js +686 -0
- package/dist/otlp.d.ts +83 -0
- package/dist/otlp.js +634 -0
- package/dist/render.d.ts +111 -0
- package/dist/render.js +368 -0
- package/dist/signals.d.ts +371 -0
- package/dist/signals.js +800 -0
- package/package.json +76 -4
- package/src/host/console.ts +253 -0
- package/src/host/mod.ts +16 -0
- package/src/host/otel.ts +1068 -0
- package/src/mod.ts +18 -0
- package/src/otel.ts +919 -0
- package/src/otlp.ts +721 -0
- package/src/render.ts +489 -0
- package/src/signals.ts +1175 -0
package/src/otel.ts
ADDED
|
@@ -0,0 +1,919 @@
|
|
|
1
|
+
// Spec: 0001-telemetry FR-001
|
|
2
|
+
/**
|
|
3
|
+
* The OpenTelemetry data model, written from the OpenTelemetry specification itself (commons 0001-telemetry FR-001 to FR-008): attribute
|
|
4
|
+
* values and log bodies, trace and span ids as brands made only from bytes the caller gives (the kernel has no randomness of its own), W3C
|
|
5
|
+
* Trace Context Level 2 `traceparent` and `tracestate`, resources, scopes, finished spans, log records and metric points, the
|
|
6
|
+
* configuration read from the `OTEL_*` environment variables (given as a record: the kernel reads no environment), redaction of what must
|
|
7
|
+
* never leave a process, the attribute, event and link limits, and the samplers OpenTelemetry names.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* import { formatTraceparent, parseTraceparent, redactUrl, resolveConfig } from "./otel.ts";
|
|
12
|
+
* const parent = parseTraceparent("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01");
|
|
13
|
+
* if (parent.kind === "ok") formatTraceparent(parent.value); // the same header back
|
|
14
|
+
* redactUrl("https://user:pw@host/x?token=abc&page=2"); // "https://REDACTED:REDACTED@host/x?token=REDACTED&page=2"
|
|
15
|
+
* resolveConfig({ OTEL_SERVICE_NAME: "build" }).config.resource; // { "service.name": "build" }
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* @module
|
|
19
|
+
*/
|
|
20
|
+
import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
|
|
21
|
+
import type { Brand } from "@intellectual-frontiers/core";
|
|
22
|
+
import { fromBase64 } from "@intellectual-frontiers/formats/base64";
|
|
23
|
+
import { toHex } from "@intellectual-frontiers/formats/hex";
|
|
24
|
+
|
|
25
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
26
|
+
// Values (FR-001)
|
|
27
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* An attribute's value: a string, a boolean, an integer (`bigint`, OTLP's int64), a double (`number`), bytes, or a homogeneous array of
|
|
31
|
+
* one of the primitive types. Nothing else is representable (FR-001).
|
|
32
|
+
*/
|
|
33
|
+
export type AttributeValue =
|
|
34
|
+
string | boolean | bigint | number | Uint8Array | readonly string[] | readonly boolean[] | readonly bigint[] | readonly number[];
|
|
35
|
+
|
|
36
|
+
/** A set of attributes: names to values. */
|
|
37
|
+
export type Attributes = Readonly<Record<string, AttributeValue>>;
|
|
38
|
+
|
|
39
|
+
/** A log body, as OTLP's `AnyValue`: what an attribute may be, and also a map or an array of mixed values (FR-001). */
|
|
40
|
+
export type AnyValue = AttributeValue | readonly AnyValue[] | AnyMap;
|
|
41
|
+
|
|
42
|
+
/** A map of `AnyValue`s, as OTLP's `KeyValueList`. */
|
|
43
|
+
export type AnyMap = { readonly [key: string]: AnyValue };
|
|
44
|
+
|
|
45
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
46
|
+
// Ids (FR-002)
|
|
47
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
48
|
+
|
|
49
|
+
/** A trace id: 32 lower-case hexadecimal digits, not all zeros (FR-002). */
|
|
50
|
+
export type TraceId = Brand<string, "TraceId">;
|
|
51
|
+
|
|
52
|
+
/** A span id: 16 lower-case hexadecimal digits, not all zeros (FR-002). */
|
|
53
|
+
export type SpanId = Brand<string, "SpanId">;
|
|
54
|
+
|
|
55
|
+
const TRACE_ID = /^[0-9a-f]{32}$/;
|
|
56
|
+
const SPAN_ID = /^[0-9a-f]{16}$/;
|
|
57
|
+
const ZEROS = /^0+$/;
|
|
58
|
+
|
|
59
|
+
/** A trace id from 16 bytes a caller gives (`traceIdFrom(random(16))`); other lengths and all zeros are refused (FR-002). */
|
|
60
|
+
export function traceIdFrom(bytes: Uint8Array): Result<TraceId, string> {
|
|
61
|
+
if (bytes.length !== 16) return err(`a trace id is 16 bytes, not ${bytes.length}`);
|
|
62
|
+
return parseTraceId(toHex(bytes));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A span id from 8 bytes a caller gives (`spanIdFrom(random(8))`); other lengths and all zeros are refused (FR-002). */
|
|
66
|
+
export function spanIdFrom(bytes: Uint8Array): Result<SpanId, string> {
|
|
67
|
+
if (bytes.length !== 8) return err(`a span id is 8 bytes, not ${bytes.length}`);
|
|
68
|
+
return parseSpanId(toHex(bytes));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A trace id from its text: 32 lower-case hexadecimal digits, not all zeros. */
|
|
72
|
+
export function parseTraceId(text: string): Result<TraceId, string> {
|
|
73
|
+
if (!TRACE_ID.test(text)) return err("a trace id is 32 lower-case hexadecimal digits");
|
|
74
|
+
if (ZEROS.test(text)) return err("a trace id of all zeros is not valid");
|
|
75
|
+
// The one place a TraceId is made, after its validation.
|
|
76
|
+
return ok(text as TraceId);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A span id from its text: 16 lower-case hexadecimal digits, not all zeros. */
|
|
80
|
+
export function parseSpanId(text: string): Result<SpanId, string> {
|
|
81
|
+
if (!SPAN_ID.test(text)) return err("a span id is 16 lower-case hexadecimal digits");
|
|
82
|
+
if (ZEROS.test(text)) return err("a span id of all zeros is not valid");
|
|
83
|
+
// The one place a SpanId is made, after its validation.
|
|
84
|
+
return ok(text as SpanId);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
88
|
+
// W3C Trace Context Level 2 (FR-003)
|
|
89
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
90
|
+
|
|
91
|
+
/** One `tracestate` member. */
|
|
92
|
+
export type TraceStateMember = { readonly key: string; readonly value: string };
|
|
93
|
+
|
|
94
|
+
/** A `tracestate`: its members, newest first, at most 32, each key once. */
|
|
95
|
+
export type TraceState = readonly TraceStateMember[];
|
|
96
|
+
|
|
97
|
+
/** The `sampled` trace flag. */
|
|
98
|
+
export const SAMPLED = 0x01;
|
|
99
|
+
|
|
100
|
+
/** The `random` trace flag of Level 2: the trace id's right-most 7 bytes are random. */
|
|
101
|
+
export const RANDOM = 0x02;
|
|
102
|
+
|
|
103
|
+
/** The trace flags this version of Trace Context defines; the others are written as zero. */
|
|
104
|
+
const KNOWN_FLAGS = SAMPLED | RANDOM;
|
|
105
|
+
|
|
106
|
+
/** The most members a `tracestate` keeps. */
|
|
107
|
+
export const TRACESTATE_MAX_MEMBERS = 32;
|
|
108
|
+
|
|
109
|
+
/** What propagates: the ids, the flags, the trace state, and whether it came from another process. */
|
|
110
|
+
export type SpanContext = {
|
|
111
|
+
readonly traceId: TraceId;
|
|
112
|
+
readonly spanId: SpanId;
|
|
113
|
+
readonly traceFlags: number;
|
|
114
|
+
readonly traceState: TraceState;
|
|
115
|
+
readonly isRemote: boolean;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** Whether a context's `sampled` flag is set. */
|
|
119
|
+
export function isSampled(context: { readonly traceFlags: number }): boolean {
|
|
120
|
+
return (context.traceFlags & SAMPLED) === SAMPLED;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const HEX2 = /^[0-9a-f]{2}$/;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* A `traceparent` header read (FR-003): version `00` exactly as written (55 characters, lower-case hexadecimal, ids not all zeros),
|
|
127
|
+
* version `ff` refused, a later version read by its first four fields. The context is remote and its trace state empty; the flags this
|
|
128
|
+
* version does not define are dropped.
|
|
129
|
+
*/
|
|
130
|
+
export function parseTraceparent(header: string): Result<SpanContext, string> {
|
|
131
|
+
const h = header.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
132
|
+
const version = h.slice(0, 2);
|
|
133
|
+
if (!HEX2.test(version) || h[2] !== "-") return err("the version is not two lower-case hexadecimal digits and a dash");
|
|
134
|
+
if (version === "ff") return err("the version ff is not valid");
|
|
135
|
+
if (version === "00" ? h.length !== 55 : h.length < 55 || (h.length > 55 && h[55] !== "-")) {
|
|
136
|
+
return err("the header does not have the length of its version");
|
|
137
|
+
}
|
|
138
|
+
if (h[35] !== "-" || h[52] !== "-") return err("the fields are not separated by dashes");
|
|
139
|
+
const traceId = parseTraceId(h.slice(3, 35));
|
|
140
|
+
if (traceId.kind === "err") return traceId;
|
|
141
|
+
const spanId = parseSpanId(h.slice(36, 52));
|
|
142
|
+
if (spanId.kind === "err") return spanId;
|
|
143
|
+
const flags = h.slice(53, 55);
|
|
144
|
+
if (!HEX2.test(flags)) return err("the trace flags are not two lower-case hexadecimal digits");
|
|
145
|
+
return ok({
|
|
146
|
+
traceId: traceId.value,
|
|
147
|
+
spanId: spanId.value,
|
|
148
|
+
traceFlags: Number.parseInt(flags, 16) & KNOWN_FLAGS,
|
|
149
|
+
traceState: [],
|
|
150
|
+
isRemote: true,
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** A `traceparent` header (version `00`) for a context. */
|
|
155
|
+
export function formatTraceparent(context: { readonly traceId: TraceId; readonly spanId: SpanId; readonly traceFlags: number }): string {
|
|
156
|
+
const flags = (context.traceFlags & KNOWN_FLAGS).toString(16).padStart(2, "0");
|
|
157
|
+
return `00-${context.traceId}-${context.spanId}-${flags}`;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const KEY_CHAR = "[a-z0-9_\\-*/]";
|
|
161
|
+
const TRACESTATE_KEY = new RegExp(`^(?:[a-z]${KEY_CHAR}{0,255}|[a-z0-9]${KEY_CHAR}{0,240}@[a-z]${KEY_CHAR}{0,13})$`);
|
|
162
|
+
const TRACESTATE_VALUE = /^[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]$/;
|
|
163
|
+
|
|
164
|
+
/** Whether a key is a `tracestate` key of the grammar. */
|
|
165
|
+
export function isTraceStateKey(key: string): boolean {
|
|
166
|
+
return TRACESTATE_KEY.test(key);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Whether a value is a `tracestate` value of the grammar. */
|
|
170
|
+
export function isTraceStateValue(value: string): boolean {
|
|
171
|
+
return TRACESTATE_VALUE.test(value);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* A `tracestate` header read (FR-003): members split on commas with optional white space, a member that breaks the grammar or repeats a
|
|
176
|
+
* key dropped (never the header), at most 32 members kept. Several header fields are read joined with commas.
|
|
177
|
+
*/
|
|
178
|
+
export function parseTracestate(header: string): TraceState {
|
|
179
|
+
const out: TraceStateMember[] = [];
|
|
180
|
+
const seen = new Set<string>();
|
|
181
|
+
for (const raw of header.split(",")) {
|
|
182
|
+
if (out.length >= TRACESTATE_MAX_MEMBERS) break;
|
|
183
|
+
const member = raw.replace(/^[ \t]+|[ \t]+$/g, "");
|
|
184
|
+
if (member === "") continue;
|
|
185
|
+
const eq = member.indexOf("=");
|
|
186
|
+
if (eq < 0) continue;
|
|
187
|
+
const key = member.slice(0, eq);
|
|
188
|
+
const value = member.slice(eq + 1);
|
|
189
|
+
if (!isTraceStateKey(key) || !isTraceStateValue(value) || seen.has(key)) continue;
|
|
190
|
+
seen.add(key);
|
|
191
|
+
out.push({ key, value });
|
|
192
|
+
}
|
|
193
|
+
return out;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** A `tracestate` header: the members newest first, as they are held. */
|
|
197
|
+
export function formatTracestate(state: TraceState): string {
|
|
198
|
+
return state
|
|
199
|
+
.slice(0, TRACESTATE_MAX_MEMBERS)
|
|
200
|
+
.map((m) => `${m.key}=${m.value}`)
|
|
201
|
+
.join(",");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** The value of a key in a trace state. */
|
|
205
|
+
export function traceStateGet(state: TraceState, key: string): string | undefined {
|
|
206
|
+
return state.find((m) => m.key === key)?.value;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** A trace state with a key set: the member moved to the front (newest), the oldest dropped beyond 32; a key or value of no grammar refused. */
|
|
210
|
+
export function traceStateSet(state: TraceState, key: string, value: string): Result<TraceState, string> {
|
|
211
|
+
if (!isTraceStateKey(key)) return err(`${JSON.stringify(key)} is not a tracestate key`);
|
|
212
|
+
if (!isTraceStateValue(value)) return err(`${JSON.stringify(value)} is not a tracestate value`);
|
|
213
|
+
return ok([{ key, value }, ...state.filter((m) => m.key !== key)].slice(0, TRACESTATE_MAX_MEMBERS));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A trace state without a key. */
|
|
217
|
+
export function traceStateDelete(state: TraceState, key: string): TraceState {
|
|
218
|
+
return state.filter((m) => m.key !== key);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* The context carried by a `traceparent` and a `tracestate` (an HTTP request's headers, or the `TRACEPARENT` and `TRACESTATE` of the
|
|
223
|
+
* environment): undefined when there is no valid `traceparent`, whose `tracestate` is then ignored too.
|
|
224
|
+
*/
|
|
225
|
+
export function extractContext(traceparent: string | undefined, tracestate: string | undefined): SpanContext | undefined {
|
|
226
|
+
if (traceparent === undefined) return undefined;
|
|
227
|
+
const parent = parseTraceparent(traceparent);
|
|
228
|
+
if (parent.kind === "err") return undefined;
|
|
229
|
+
return { ...parent.value, traceState: tracestate === undefined ? [] : parseTracestate(tracestate) };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
233
|
+
// Resources, scopes, spans, logs, metrics (FR-001)
|
|
234
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
/** The entity that makes the signals: `service.name` and the others. */
|
|
237
|
+
export type Resource = { readonly attributes: Attributes };
|
|
238
|
+
|
|
239
|
+
/** The instrumentation scope: the library or harness that makes the signals. */
|
|
240
|
+
export type Scope = { readonly name: string; readonly version?: string; readonly attributes?: Attributes };
|
|
241
|
+
|
|
242
|
+
/** A span's kind. */
|
|
243
|
+
export type SpanKind = "internal" | "server" | "client" | "producer" | "consumer";
|
|
244
|
+
|
|
245
|
+
/** A span's status: unset, ok, or an error with its description. */
|
|
246
|
+
export type SpanStatus = { readonly kind: "unset" } | { readonly kind: "ok" } | { readonly kind: "error"; readonly message: string };
|
|
247
|
+
|
|
248
|
+
/** Something that happened at a time during a span. */
|
|
249
|
+
export type SpanEvent = {
|
|
250
|
+
readonly name: string;
|
|
251
|
+
readonly time: bigint;
|
|
252
|
+
readonly attributes: Attributes;
|
|
253
|
+
readonly droppedAttributesCount: number;
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
/** A span's link to another span's context. */
|
|
257
|
+
export type SpanLink = {
|
|
258
|
+
readonly traceId: TraceId;
|
|
259
|
+
readonly spanId: SpanId;
|
|
260
|
+
readonly traceState: TraceState;
|
|
261
|
+
readonly traceFlags: number;
|
|
262
|
+
readonly attributes: Attributes;
|
|
263
|
+
readonly droppedAttributesCount: number;
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
/** A finished span. Times are nanoseconds since the Unix epoch. */
|
|
267
|
+
export type SpanData = {
|
|
268
|
+
readonly name: string;
|
|
269
|
+
readonly context: SpanContext;
|
|
270
|
+
readonly parentSpanId?: SpanId;
|
|
271
|
+
readonly kind: SpanKind;
|
|
272
|
+
readonly startTime: bigint;
|
|
273
|
+
readonly endTime: bigint;
|
|
274
|
+
readonly attributes: Attributes;
|
|
275
|
+
readonly events: readonly SpanEvent[];
|
|
276
|
+
readonly links: readonly SpanLink[];
|
|
277
|
+
readonly status: SpanStatus;
|
|
278
|
+
readonly droppedAttributesCount: number;
|
|
279
|
+
readonly droppedEventsCount: number;
|
|
280
|
+
readonly droppedLinksCount: number;
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
/** A severity number of the log data model, 1 (TRACE) to 24 (FATAL4). */
|
|
284
|
+
export type SeverityNumber = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24;
|
|
285
|
+
|
|
286
|
+
/** The first severity number of each range of the log data model. */
|
|
287
|
+
export const SEVERITY = { TRACE: 1, DEBUG: 5, INFO: 9, WARN: 13, ERROR: 17, FATAL: 21 } as const satisfies Readonly<
|
|
288
|
+
Record<string, SeverityNumber>
|
|
289
|
+
>;
|
|
290
|
+
|
|
291
|
+
/** Whether a number is a severity number (an integer from 1 to 24). */
|
|
292
|
+
export function isSeverityNumber(n: number): n is SeverityNumber {
|
|
293
|
+
return Number.isInteger(n) && n >= 1 && n <= 24;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** The short name the log data model gives a severity number: `INFO`, `INFO2`, ... `FATAL4`. */
|
|
297
|
+
export function severityText(n: SeverityNumber): string {
|
|
298
|
+
const names = ["TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"] as const;
|
|
299
|
+
const range = names[Math.floor((n - 1) / 4)] ?? "FATAL";
|
|
300
|
+
const step = (n - 1) % 4;
|
|
301
|
+
return step === 0 ? range : `${range}${step + 1}`;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** A log record. Times are nanoseconds since the Unix epoch. */
|
|
305
|
+
export type LogRecord = {
|
|
306
|
+
readonly time: bigint;
|
|
307
|
+
readonly observedTime: bigint;
|
|
308
|
+
readonly severityNumber: SeverityNumber;
|
|
309
|
+
readonly severityText: string;
|
|
310
|
+
readonly body?: AnyValue;
|
|
311
|
+
readonly attributes: Attributes;
|
|
312
|
+
readonly droppedAttributesCount: number;
|
|
313
|
+
readonly eventName?: string;
|
|
314
|
+
readonly traceId?: TraceId;
|
|
315
|
+
readonly spanId?: SpanId;
|
|
316
|
+
readonly traceFlags?: number;
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
/** How a sum or a histogram accumulates: since the last collection, or since the series began. */
|
|
320
|
+
export type Temporality = "delta" | "cumulative";
|
|
321
|
+
|
|
322
|
+
/** A point of a sum or a gauge: an integer (`bigint`) or a double. */
|
|
323
|
+
export type NumberPoint = {
|
|
324
|
+
readonly attributes: Attributes;
|
|
325
|
+
readonly startTime: bigint;
|
|
326
|
+
readonly time: bigint;
|
|
327
|
+
readonly value: bigint | number;
|
|
328
|
+
};
|
|
329
|
+
|
|
330
|
+
/** A point of an explicit-bucket histogram: `bucketCounts` has one more element than `bounds`, bucket `i` holding (bounds[i-1], bounds[i]]. */
|
|
331
|
+
export type HistogramPoint = {
|
|
332
|
+
readonly attributes: Attributes;
|
|
333
|
+
readonly startTime: bigint;
|
|
334
|
+
readonly time: bigint;
|
|
335
|
+
readonly count: number;
|
|
336
|
+
readonly sum?: number;
|
|
337
|
+
readonly min?: number;
|
|
338
|
+
readonly max?: number;
|
|
339
|
+
readonly bounds: readonly number[];
|
|
340
|
+
readonly bucketCounts: readonly number[];
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
/** The data of a metric: a sum (monotonic or not), a gauge, or a histogram. */
|
|
344
|
+
export type MetricData =
|
|
345
|
+
| { readonly kind: "sum"; readonly temporality: Temporality; readonly monotonic: boolean; readonly points: readonly NumberPoint[] }
|
|
346
|
+
| { readonly kind: "gauge"; readonly points: readonly NumberPoint[] }
|
|
347
|
+
| { readonly kind: "histogram"; readonly temporality: Temporality; readonly points: readonly HistogramPoint[] };
|
|
348
|
+
|
|
349
|
+
/** A metric: its name, description, unit and data. */
|
|
350
|
+
export type Metric = { readonly name: string; readonly description: string; readonly unit: string; readonly data: MetricData };
|
|
351
|
+
|
|
352
|
+
/** OpenTelemetry's default explicit bucket bounds for a histogram (FR-013). */
|
|
353
|
+
export const DEFAULT_HISTOGRAM_BOUNDS: readonly number[] = [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000];
|
|
354
|
+
|
|
355
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
356
|
+
// Limits (FR-007)
|
|
357
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
358
|
+
|
|
359
|
+
/** The limits of FR-005, applied by FR-007. `attributeValueLength` is `Infinity` where there is none. */
|
|
360
|
+
export type Limits = {
|
|
361
|
+
readonly attributeValueLength: number;
|
|
362
|
+
readonly attributeCount: number;
|
|
363
|
+
readonly eventCount: number;
|
|
364
|
+
readonly linkCount: number;
|
|
365
|
+
};
|
|
366
|
+
|
|
367
|
+
/** OpenTelemetry's default limits: no value length limit, 128 attributes, events and links. */
|
|
368
|
+
export const DEFAULT_LIMITS: Limits = { attributeValueLength: Infinity, attributeCount: 128, eventCount: 128, linkCount: 128 };
|
|
369
|
+
|
|
370
|
+
function cut(s: string, length: number): string {
|
|
371
|
+
if (s.length <= length) return s;
|
|
372
|
+
// Cut by code points, so that a surrogate pair is never split.
|
|
373
|
+
return Array.from(s).slice(0, length).join("");
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** A value cut to the value length limit: a string, or each string of an array of strings; other values unchanged. */
|
|
377
|
+
export function truncateValue(value: AttributeValue, length: number): AttributeValue {
|
|
378
|
+
if (!Number.isFinite(length)) return value;
|
|
379
|
+
if (typeof value === "string") return cut(value, length);
|
|
380
|
+
if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) return value.map((v) => cut(v, length));
|
|
381
|
+
return value;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Attributes added to others under the limits (FR-007): a value cut to the length limit, an existing key replaced, a new key beyond the
|
|
386
|
+
* count dropped and counted.
|
|
387
|
+
*/
|
|
388
|
+
export function mergeAttributes(
|
|
389
|
+
current: Attributes,
|
|
390
|
+
added: Attributes,
|
|
391
|
+
limits: Pick<Limits, "attributeValueLength" | "attributeCount">,
|
|
392
|
+
): { readonly attributes: Attributes; readonly dropped: number } {
|
|
393
|
+
const out: Record<string, AttributeValue> = { ...current };
|
|
394
|
+
let count = Object.keys(out).length;
|
|
395
|
+
let dropped = 0;
|
|
396
|
+
for (const [key, value] of Object.entries(added)) {
|
|
397
|
+
if (!Object.hasOwn(out, key)) {
|
|
398
|
+
if (count >= limits.attributeCount) {
|
|
399
|
+
dropped++;
|
|
400
|
+
continue;
|
|
401
|
+
}
|
|
402
|
+
count++;
|
|
403
|
+
}
|
|
404
|
+
out[key] = truncateValue(value, limits.attributeValueLength);
|
|
405
|
+
}
|
|
406
|
+
return { attributes: out, dropped };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Attributes under the limits: what `mergeAttributes` gives from none. */
|
|
410
|
+
export function limitAttributes(
|
|
411
|
+
attributes: Attributes,
|
|
412
|
+
limits: Pick<Limits, "attributeValueLength" | "attributeCount">,
|
|
413
|
+
): { readonly attributes: Attributes; readonly dropped: number } {
|
|
414
|
+
return mergeAttributes({}, attributes, limits);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
418
|
+
// Samplers (FR-008)
|
|
419
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
420
|
+
|
|
421
|
+
/** A sampler for a span with no parent. */
|
|
422
|
+
export type RootSampler =
|
|
423
|
+
{ readonly kind: "always_on" } | { readonly kind: "always_off" } | { readonly kind: "traceidratio"; readonly ratio: number };
|
|
424
|
+
|
|
425
|
+
/** A sampler: a root sampler, or `parentbased` (the parent's `sampled` flag where there is a parent, `root` where there is none). */
|
|
426
|
+
export type Sampler = RootSampler | { readonly kind: "parentbased"; readonly root: RootSampler };
|
|
427
|
+
|
|
428
|
+
/** OpenTelemetry's default sampler: `parentbased_always_on`. */
|
|
429
|
+
export const DEFAULT_SAMPLER: Sampler = { kind: "parentbased", root: { kind: "always_on" } };
|
|
430
|
+
|
|
431
|
+
const TWO_56 = 2 ** 56;
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* The rejection threshold of `TraceIdRatioBased` for a ratio: a trace is sampled where its trace id's right-most 56 bits, read as an
|
|
435
|
+
* unsigned integer, are at least the threshold (`(1 - ratio) * 2^56`). Every process of a trace decides alike from the id alone.
|
|
436
|
+
*/
|
|
437
|
+
export function ratioThreshold(ratio: number): bigint {
|
|
438
|
+
const r = Number.isFinite(ratio) ? Math.min(1, Math.max(0, ratio)) : 1;
|
|
439
|
+
return BigInt(Math.round((1 - r) * TWO_56));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Whether a sampler samples a new span of a trace, given its parent (FR-008). */
|
|
443
|
+
export function shouldSample(sampler: Sampler, traceId: TraceId, parent: SpanContext | undefined): boolean {
|
|
444
|
+
switch (sampler.kind) {
|
|
445
|
+
case "always_on":
|
|
446
|
+
return true;
|
|
447
|
+
case "always_off":
|
|
448
|
+
return false;
|
|
449
|
+
case "traceidratio":
|
|
450
|
+
return BigInt(`0x${traceId.slice(18)}`) >= ratioThreshold(sampler.ratio);
|
|
451
|
+
case "parentbased":
|
|
452
|
+
return parent === undefined ? shouldSample(sampler.root, traceId, undefined) : isSampled(parent);
|
|
453
|
+
default:
|
|
454
|
+
return absurd(sampler);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
459
|
+
// Redaction (FR-006)
|
|
460
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
461
|
+
|
|
462
|
+
/** What a redacted secret is written as. */
|
|
463
|
+
export const REDACTED = "REDACTED";
|
|
464
|
+
|
|
465
|
+
const CREDENTIAL_PARTS = [
|
|
466
|
+
"token",
|
|
467
|
+
"secret",
|
|
468
|
+
"password",
|
|
469
|
+
"passwd",
|
|
470
|
+
"passphrase",
|
|
471
|
+
"signature",
|
|
472
|
+
"credential",
|
|
473
|
+
"apikey",
|
|
474
|
+
"auth",
|
|
475
|
+
"cookie",
|
|
476
|
+
"jwt",
|
|
477
|
+
];
|
|
478
|
+
const CREDENTIAL_WORDS = new Set(["key", "code", "sig", "pwd", "pass", "session", "sid", "otp", "awsaccesskeyid", "sas", "se", "sp", "sv"]);
|
|
479
|
+
|
|
480
|
+
/** Whether a query parameter's or a field's name says it holds a credential (`token`, `key`, `secret`, `password`, `signature`, `code`, ...). */
|
|
481
|
+
export function isCredentialName(name: string): boolean {
|
|
482
|
+
const n = name.toLowerCase();
|
|
483
|
+
if (CREDENTIAL_PARTS.some((p) => n.includes(p))) return true;
|
|
484
|
+
return n.split(/[^a-z0-9]+/).some((w) => CREDENTIAL_WORDS.has(w) || (w.length > 3 && w.endsWith("key")));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function decodedName(name: string): string {
|
|
488
|
+
try {
|
|
489
|
+
return decodeURIComponent(name.replaceAll("+", " "));
|
|
490
|
+
} catch {
|
|
491
|
+
return name;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const URL_HEAD = /^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)([^/?#]*)/;
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* A URL with its secrets replaced (FR-006): the user and password of its authority, and the value of each query parameter whose name says
|
|
499
|
+
* it is a credential, become `REDACTED`. The rest of the text is kept as written.
|
|
500
|
+
*/
|
|
501
|
+
export function redactUrl(url: string): string {
|
|
502
|
+
let out = url;
|
|
503
|
+
const head = URL_HEAD.exec(out);
|
|
504
|
+
if (head !== null) {
|
|
505
|
+
const scheme = head[1] ?? "";
|
|
506
|
+
const authority = head[2] ?? "";
|
|
507
|
+
const at = authority.lastIndexOf("@");
|
|
508
|
+
if (at >= 0) {
|
|
509
|
+
const userinfo = authority.slice(0, at);
|
|
510
|
+
const replaced = userinfo.includes(":") ? `${REDACTED}:${REDACTED}` : REDACTED;
|
|
511
|
+
out = `${scheme}${replaced}@${authority.slice(at + 1)}${out.slice(head[0].length)}`;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
const q = out.indexOf("?");
|
|
515
|
+
if (q < 0) return out;
|
|
516
|
+
const hash = out.indexOf("#", q);
|
|
517
|
+
const end = hash < 0 ? out.length : hash;
|
|
518
|
+
const query = out
|
|
519
|
+
.slice(q + 1, end)
|
|
520
|
+
.split("&")
|
|
521
|
+
.map((pair) => {
|
|
522
|
+
const eq = pair.indexOf("=");
|
|
523
|
+
if (eq < 0) return pair;
|
|
524
|
+
return isCredentialName(decodedName(pair.slice(0, eq))) ? `${pair.slice(0, eq)}=${REDACTED}` : pair;
|
|
525
|
+
})
|
|
526
|
+
.join("&");
|
|
527
|
+
return `${out.slice(0, q + 1)}${query}${out.slice(end)}`;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
const URL_IN_TEXT = /[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^\s"'<>`]+/g;
|
|
531
|
+
const PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g;
|
|
532
|
+
const BEARER = /\b(Bearer)[ \t]+[A-Za-z0-9._~+/-]{8,}=*/gi;
|
|
533
|
+
const BASIC = /\b(Basic)[ \t]+([A-Za-z0-9+/]{4,}={0,2})/gi;
|
|
534
|
+
// `Authorization: <scheme> <credential>` (or `=`), quoted or not: the scheme kept, the credential replaced up to a space, quote, `,` or `;`.
|
|
535
|
+
const AUTHORIZATION = /\b((?:proxy-)?authorization["']?[ \t]*[:=][ \t]*["']?)(?:([A-Za-z][A-Za-z0-9-]*)[ \t]+)?([^\s"',;]+)/gi;
|
|
536
|
+
// `name=value`, `name: value`, `"name": "value"`: the name an identifier (with `-` and `.`), the value quoted or up to a delimiter.
|
|
537
|
+
const PAIR = /(["']?)\b([A-Za-z_][A-Za-z0-9_.-]*)\1([ \t]*[:=][ \t]*)("[^"\n]*"|'[^'\n]*'|[^\s"',;&)}\]]+)/g;
|
|
538
|
+
const SECRET_NAME_ENDINGS = [
|
|
539
|
+
"token",
|
|
540
|
+
"secret",
|
|
541
|
+
"password",
|
|
542
|
+
"passwd",
|
|
543
|
+
"passphrase",
|
|
544
|
+
"apikey",
|
|
545
|
+
"accesskey",
|
|
546
|
+
"secretkey",
|
|
547
|
+
"privatekey",
|
|
548
|
+
"credential",
|
|
549
|
+
"signature",
|
|
550
|
+
] as const;
|
|
551
|
+
const KNOWN_TOKENS = [
|
|
552
|
+
/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, // GitHub
|
|
553
|
+
/\bgithub_pat_[A-Za-z0-9_]{30,}\b/g,
|
|
554
|
+
/\bglpat-[A-Za-z0-9_-]{20,}/g, // GitLab
|
|
555
|
+
/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, // Slack
|
|
556
|
+
/\bxapp-[0-9]-[A-Za-z0-9-]{10,}/g,
|
|
557
|
+
/\bya29\.[A-Za-z0-9._-]{20,}/g, // Google access, refresh and client secret, API key
|
|
558
|
+
/(?<![A-Za-z0-9])1\/\/[A-Za-z0-9_-]{30,}/g,
|
|
559
|
+
/\bGOCSPX-[A-Za-z0-9_-]{20,}/g,
|
|
560
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/g,
|
|
561
|
+
/\bcf[au]t_[A-Za-z0-9_-]{20,}/g, // Cloudflare account and user API tokens
|
|
562
|
+
/\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g, // Anthropic, OpenAI
|
|
563
|
+
/\b[rs]k_(?:live|test)_[A-Za-z0-9]{16,}/g, // Stripe
|
|
564
|
+
/\bnpm_[A-Za-z0-9]{36}\b/g, // npm
|
|
565
|
+
/\bdo[opr]_v1_[a-f0-9]{64}\b/g, // DigitalOcean
|
|
566
|
+
/\bdckr_pat_[A-Za-z0-9_-]{20,}/g, // Docker
|
|
567
|
+
/\bhf_[A-Za-z]{30,}\b/g, // Hugging Face
|
|
568
|
+
/\blin_(?:api|oauth)_[A-Za-z0-9]{30,}\b/g, // Linear
|
|
569
|
+
/\bAT(?:ATT|BB)[A-Za-z0-9_=-]{20,}/g, // Atlassian, Bitbucket
|
|
570
|
+
/\beyJ[A-Za-z0-9_-]{4,}\.eyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]+/g, // JSON Web Token
|
|
571
|
+
/\$(?:6|5|y|gy|2[aby])\$[^\s:"']{8,}/g, // crypt password hashes
|
|
572
|
+
];
|
|
573
|
+
|
|
574
|
+
function isBasicCredential(token: string): boolean {
|
|
575
|
+
const bytes = fromBase64(token);
|
|
576
|
+
if (bytes.kind === "err") return false;
|
|
577
|
+
return new TextDecoder().decode(bytes.value).includes(":");
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Whether a field's name in text says its value is a secret (FR-006): it ends in `token`, `secret`, `password`, `passwd`, `passphrase`,
|
|
582
|
+
* `apikey`, `accesskey`, `secretkey`, `privatekey`, `credential` or `signature`, with case, `-`, `_` and `.` ignored (`api_token`,
|
|
583
|
+
* `AWS_SECRET_ACCESS_KEY`, `X-Amz-Signature`, `clientSecret`), but not `max_tokens` or `token_type`. Narrower than
|
|
584
|
+
* {@link isCredentialName}, which judges a URL's query parameters, because prose is full of `code=` and `key:`.
|
|
585
|
+
*/
|
|
586
|
+
export function isSecretFieldName(name: string): boolean {
|
|
587
|
+
const n = name.toLowerCase().replace(/[-_.]/g, "");
|
|
588
|
+
return SECRET_NAME_ENDINGS.some((e) => n.endsWith(e));
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* Text with its secrets replaced (FR-006), the one redaction for signals and for what a harness mails: each exact secret named in
|
|
593
|
+
* `secrets` (four characters or more; a shorter one would garble the text and hide nothing), a private key block, each URL as
|
|
594
|
+
* `redactUrl` writes it, a bearer token, a basic credential (base64 of `user:pass`), the credential of an `Authorization` header with any
|
|
595
|
+
* scheme, the value of a `name=value` or `name: value` pair whose name {@link isSecretFieldName} judges secret (quoted or bare, in prose,
|
|
596
|
+
* JSON, YAML or an environment file), and the token formats that announce themselves (GitHub, GitLab, Slack, Google, Cloudflare,
|
|
597
|
+
* Anthropic, OpenAI, Stripe, npm, DigitalOcean, Docker, Hugging Face, Linear, Atlassian, JSON Web Tokens) and crypt password hashes
|
|
598
|
+
* become `REDACTED`.
|
|
599
|
+
*/
|
|
600
|
+
export function redactText(text: string, secrets: Iterable<string> = []): string {
|
|
601
|
+
let out = text;
|
|
602
|
+
const exact = [...new Set(secrets)].filter((s) => s.length >= 4).sort((a, b) => b.length - a.length);
|
|
603
|
+
for (const s of exact) out = out.split(s).join(REDACTED);
|
|
604
|
+
out = out.replace(PRIVATE_KEY, REDACTED);
|
|
605
|
+
out = out.replace(URL_IN_TEXT, (u) => redactUrl(u));
|
|
606
|
+
out = out.replace(
|
|
607
|
+
AUTHORIZATION,
|
|
608
|
+
(_m, head: string, scheme: string | undefined) => `${head}${scheme === undefined ? "" : `${scheme} `}${REDACTED}`,
|
|
609
|
+
);
|
|
610
|
+
out = out.replace(BEARER, (_m, word: string) => `${word} ${REDACTED}`);
|
|
611
|
+
out = out.replace(BASIC, (m, word: string, token: string) => (isBasicCredential(token) ? `${word} ${REDACTED}` : m));
|
|
612
|
+
out = out.replace(PAIR, (m, quote: string, name: string, sep: string, value: string) => {
|
|
613
|
+
if (!isSecretFieldName(name)) return m;
|
|
614
|
+
const q = value.startsWith('"') || value.startsWith("'") ? value.charAt(0) : "";
|
|
615
|
+
return `${quote}${name}${quote}${sep}${q}${REDACTED}${q}`;
|
|
616
|
+
});
|
|
617
|
+
for (const re of KNOWN_TOKENS) out = out.replace(re, REDACTED);
|
|
618
|
+
return out;
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** An attribute value with its secrets replaced: `redactText` on a string and on each string of an array. */
|
|
622
|
+
export function redactValue(value: AttributeValue): AttributeValue {
|
|
623
|
+
if (typeof value === "string") return redactText(value);
|
|
624
|
+
if (Array.isArray(value) && value.every((v): v is string => typeof v === "string")) return value.map((v) => redactText(v));
|
|
625
|
+
return value;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/** A log body with its secrets replaced, at every depth. */
|
|
629
|
+
export function redactAnyValue(value: AnyValue): AnyValue {
|
|
630
|
+
if (typeof value === "string") return redactText(value);
|
|
631
|
+
if (value instanceof Uint8Array || typeof value !== "object") return value;
|
|
632
|
+
if (Array.isArray(value)) return value.map((v: AnyValue) => redactAnyValue(v));
|
|
633
|
+
const out: Record<string, AnyValue> = {};
|
|
634
|
+
for (const [k, v] of Object.entries(value)) {
|
|
635
|
+
Object.defineProperty(out, k, { value: redactAnyValue(v), enumerable: true, writable: true, configurable: true });
|
|
636
|
+
}
|
|
637
|
+
return out;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Attributes with the secret ones left out (never written, FR-006) and every other string redacted by `redactText`. */
|
|
641
|
+
export function redactAttributes(attributes: Attributes, secretKeys: Iterable<string> = []): Attributes {
|
|
642
|
+
const secret = new Set(secretKeys);
|
|
643
|
+
const out: Record<string, AttributeValue> = {};
|
|
644
|
+
for (const [key, value] of Object.entries(attributes)) if (!secret.has(key)) out[key] = redactValue(value);
|
|
645
|
+
return out;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* A command line as it may be recorded (FR-006): the program's name (its last path segment) and the names of its options alone, never a
|
|
650
|
+
* value, an operand or a subcommand. `--opt=value` is kept as `--opt`, a short option as its first letter (`-pSECRET` as `-p`), and
|
|
651
|
+
* nothing after `--`.
|
|
652
|
+
*/
|
|
653
|
+
export function commandShape(argv: readonly string[]): readonly string[] {
|
|
654
|
+
const [program, ...rest] = argv;
|
|
655
|
+
if (program === undefined) return [];
|
|
656
|
+
const out = [program.split(/[/\\]/).pop() ?? program];
|
|
657
|
+
for (const arg of rest) {
|
|
658
|
+
if (arg === "--") break;
|
|
659
|
+
if (arg.startsWith("--")) out.push(arg.split("=")[0] ?? arg);
|
|
660
|
+
else if (arg.startsWith("-") && arg.length > 1 && !/^-[0-9.]/.test(arg)) out.push(arg.slice(0, 2));
|
|
661
|
+
}
|
|
662
|
+
return out;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
666
|
+
// Configuration (FR-005)
|
|
667
|
+
// ---------------------------------------------------------------------------------------------------------------------------------
|
|
668
|
+
|
|
669
|
+
/** The three signals. */
|
|
670
|
+
export type SignalName = "traces" | "logs" | "metrics";
|
|
671
|
+
|
|
672
|
+
/** Where and how one signal is exported. `endpoint` is undefined where none is configured (the runtime then probes the default). */
|
|
673
|
+
export type ExporterConfig = {
|
|
674
|
+
readonly enabled: boolean;
|
|
675
|
+
readonly endpoint: string | undefined;
|
|
676
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
677
|
+
readonly timeoutMs: number;
|
|
678
|
+
};
|
|
679
|
+
|
|
680
|
+
/** The settings of a batch processor (`OTEL_BSP_*`, `OTEL_BLRP_*`). */
|
|
681
|
+
export type BatchConfig = {
|
|
682
|
+
readonly scheduleDelayMs: number;
|
|
683
|
+
readonly exportTimeoutMs: number;
|
|
684
|
+
readonly maxQueueSize: number;
|
|
685
|
+
readonly maxExportBatchSize: number;
|
|
686
|
+
};
|
|
687
|
+
|
|
688
|
+
/** The SDK's own log level (`OTEL_LOG_LEVEL`). */
|
|
689
|
+
export type LogLevel = "none" | "error" | "warn" | "info" | "debug" | "verbose" | "all";
|
|
690
|
+
|
|
691
|
+
/** The configuration the `OTEL_*` variables give. */
|
|
692
|
+
export type OtelConfig = {
|
|
693
|
+
readonly disabled: boolean;
|
|
694
|
+
readonly resource: Attributes;
|
|
695
|
+
readonly exporters: { readonly [S in SignalName]: ExporterConfig };
|
|
696
|
+
readonly sampler: Sampler;
|
|
697
|
+
readonly spanBatch: BatchConfig;
|
|
698
|
+
readonly logBatch: BatchConfig;
|
|
699
|
+
readonly metricExportIntervalMs: number;
|
|
700
|
+
readonly metricExportTimeoutMs: number;
|
|
701
|
+
readonly limits: Limits;
|
|
702
|
+
readonly logLevel: LogLevel;
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
/** The endpoint an OTLP/HTTP exporter uses where none is configured. */
|
|
706
|
+
export const DEFAULT_OTLP_ENDPOINT = "http://localhost:4318";
|
|
707
|
+
|
|
708
|
+
/** The path of each signal under a base endpoint. */
|
|
709
|
+
export const SIGNAL_PATHS: { readonly [S in SignalName]: string } = { traces: "v1/traces", logs: "v1/logs", metrics: "v1/metrics" };
|
|
710
|
+
|
|
711
|
+
const SIGNAL_VARIABLE: { readonly [S in SignalName]: string } = { traces: "TRACES", logs: "LOGS", metrics: "METRICS" };
|
|
712
|
+
|
|
713
|
+
const LOG_LEVELS: readonly LogLevel[] = ["none", "error", "warn", "info", "debug", "verbose", "all"];
|
|
714
|
+
|
|
715
|
+
function isUrl(text: string): boolean {
|
|
716
|
+
try {
|
|
717
|
+
const u = new URL(text);
|
|
718
|
+
return u.protocol === "http:" || u.protocol === "https:";
|
|
719
|
+
} catch {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** A base endpoint with a signal's path appended, with one `/` between them. */
|
|
725
|
+
export function signalEndpoint(base: string, signal: SignalName): string {
|
|
726
|
+
return `${base.endsWith("/") ? base : `${base}/`}${SIGNAL_PATHS[signal]}`;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/** `key=value` pairs separated by commas, values percent-decoded; undefined where one pair is not valid. */
|
|
730
|
+
function keyValues(text: string): Record<string, string> | undefined {
|
|
731
|
+
const out: Record<string, string> = {};
|
|
732
|
+
for (const raw of text.split(",")) {
|
|
733
|
+
const pair = raw.trim();
|
|
734
|
+
if (pair === "") continue;
|
|
735
|
+
const eq = pair.indexOf("=");
|
|
736
|
+
if (eq <= 0) return undefined;
|
|
737
|
+
const key = pair.slice(0, eq).trim();
|
|
738
|
+
if (key === "") return undefined;
|
|
739
|
+
try {
|
|
740
|
+
out[decodeURIComponent(key)] = decodeURIComponent(pair.slice(eq + 1).trim());
|
|
741
|
+
} catch {
|
|
742
|
+
return undefined;
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
return out;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/**
|
|
749
|
+
* The configuration of the OpenTelemetry environment variables, from a record of them (FR-005): the kernel reads no environment. A value
|
|
750
|
+
* that is not valid is a warning and its default is used; an empty value counts as unset; no vendor's variable is read. A protocol other
|
|
751
|
+
* than `http/json` is a warning and disables the export of that signal.
|
|
752
|
+
*/
|
|
753
|
+
export function resolveConfig(env: Readonly<Record<string, string | undefined>>): {
|
|
754
|
+
readonly config: OtelConfig;
|
|
755
|
+
readonly warnings: readonly string[];
|
|
756
|
+
} {
|
|
757
|
+
const warnings: string[] = [];
|
|
758
|
+
const get = (name: string): string | undefined => {
|
|
759
|
+
const v = env[name]?.trim();
|
|
760
|
+
return v === undefined || v === "" ? undefined : v;
|
|
761
|
+
};
|
|
762
|
+
const bool = (name: string): boolean => {
|
|
763
|
+
const v = get(name);
|
|
764
|
+
if (v === undefined) return false;
|
|
765
|
+
if (v.toLowerCase() === "true") return true;
|
|
766
|
+
if (v.toLowerCase() !== "false") warnings.push(`${name}=${v} is not true or false; false is used`);
|
|
767
|
+
return false;
|
|
768
|
+
};
|
|
769
|
+
const int = (name: string, fallback: number, min = 0): number => {
|
|
770
|
+
const v = get(name);
|
|
771
|
+
if (v === undefined) return fallback;
|
|
772
|
+
if (!/^[0-9]+$/.test(v) || Number(v) < min || !Number.isSafeInteger(Number(v))) {
|
|
773
|
+
warnings.push(`${name}=${v} is not an integer of at least ${min}; ${fallback} is used`);
|
|
774
|
+
return fallback;
|
|
775
|
+
}
|
|
776
|
+
return Number(v);
|
|
777
|
+
};
|
|
778
|
+
|
|
779
|
+
const disabled = bool("OTEL_SDK_DISABLED");
|
|
780
|
+
|
|
781
|
+
const resource: Record<string, AttributeValue> = {};
|
|
782
|
+
const attrs = get("OTEL_RESOURCE_ATTRIBUTES");
|
|
783
|
+
if (attrs !== undefined) {
|
|
784
|
+
const parsed = keyValues(attrs);
|
|
785
|
+
if (parsed === undefined) warnings.push("OTEL_RESOURCE_ATTRIBUTES is not a list of key=value pairs; it is ignored");
|
|
786
|
+
else Object.assign(resource, parsed);
|
|
787
|
+
}
|
|
788
|
+
const serviceName = get("OTEL_SERVICE_NAME");
|
|
789
|
+
if (serviceName !== undefined) resource["service.name"] = serviceName;
|
|
790
|
+
|
|
791
|
+
const genericHeaders = (() => {
|
|
792
|
+
const v = get("OTEL_EXPORTER_OTLP_HEADERS");
|
|
793
|
+
if (v === undefined) return {};
|
|
794
|
+
const parsed = keyValues(v);
|
|
795
|
+
if (parsed === undefined) warnings.push("OTEL_EXPORTER_OTLP_HEADERS is not a list of key=value pairs; it is ignored");
|
|
796
|
+
return parsed ?? {};
|
|
797
|
+
})();
|
|
798
|
+
const genericEndpoint = (() => {
|
|
799
|
+
const v = get("OTEL_EXPORTER_OTLP_ENDPOINT");
|
|
800
|
+
if (v === undefined || isUrl(v)) return v;
|
|
801
|
+
warnings.push(`OTEL_EXPORTER_OTLP_ENDPOINT=${redactUrl(v)} is not an http or https URL; it is ignored`);
|
|
802
|
+
return undefined;
|
|
803
|
+
})();
|
|
804
|
+
const genericTimeout = int("OTEL_EXPORTER_OTLP_TIMEOUT", 10000);
|
|
805
|
+
const genericProtocol = get("OTEL_EXPORTER_OTLP_PROTOCOL");
|
|
806
|
+
|
|
807
|
+
const exporter = (signal: SignalName): ExporterConfig => {
|
|
808
|
+
const S = SIGNAL_VARIABLE[signal];
|
|
809
|
+
let enabled = true;
|
|
810
|
+
const protocolName =
|
|
811
|
+
get(`OTEL_EXPORTER_OTLP_${S}_PROTOCOL`) === undefined ? "OTEL_EXPORTER_OTLP_PROTOCOL" : `OTEL_EXPORTER_OTLP_${S}_PROTOCOL`;
|
|
812
|
+
const protocol = get(`OTEL_EXPORTER_OTLP_${S}_PROTOCOL`) ?? genericProtocol ?? "http/json";
|
|
813
|
+
if (protocol !== "http/json") {
|
|
814
|
+
warnings.push(`${protocolName}=${protocol} is not supported (only http/json is); ${signal} are not exported`);
|
|
815
|
+
enabled = false;
|
|
816
|
+
}
|
|
817
|
+
const exporterName = get(`OTEL_${S}_EXPORTER`) ?? "otlp";
|
|
818
|
+
const names = exporterName.split(",").map((n) => n.trim());
|
|
819
|
+
if (names.includes("none")) enabled = false;
|
|
820
|
+
else if (!names.includes("otlp")) {
|
|
821
|
+
warnings.push(`OTEL_${S}_EXPORTER=${exporterName} is not supported (only otlp and none are); ${signal} are not exported`);
|
|
822
|
+
enabled = false;
|
|
823
|
+
}
|
|
824
|
+
let endpoint = genericEndpoint === undefined ? undefined : signalEndpoint(genericEndpoint, signal);
|
|
825
|
+
const own = get(`OTEL_EXPORTER_OTLP_${S}_ENDPOINT`);
|
|
826
|
+
if (own !== undefined) {
|
|
827
|
+
if (isUrl(own)) endpoint = own;
|
|
828
|
+
else warnings.push(`OTEL_EXPORTER_OTLP_${S}_ENDPOINT=${redactUrl(own)} is not an http or https URL; it is ignored`);
|
|
829
|
+
}
|
|
830
|
+
let headers = genericHeaders;
|
|
831
|
+
const ownHeaders = get(`OTEL_EXPORTER_OTLP_${S}_HEADERS`);
|
|
832
|
+
if (ownHeaders !== undefined) {
|
|
833
|
+
const parsed = keyValues(ownHeaders);
|
|
834
|
+
if (parsed === undefined) warnings.push(`OTEL_EXPORTER_OTLP_${S}_HEADERS is not a list of key=value pairs; it is ignored`);
|
|
835
|
+
else headers = parsed;
|
|
836
|
+
}
|
|
837
|
+
const timeoutMs = int(`OTEL_EXPORTER_OTLP_${S}_TIMEOUT`, genericTimeout);
|
|
838
|
+
return { enabled: enabled && !disabled, endpoint, headers, timeoutMs };
|
|
839
|
+
};
|
|
840
|
+
|
|
841
|
+
const ratio = (() => {
|
|
842
|
+
const v = get("OTEL_TRACES_SAMPLER_ARG");
|
|
843
|
+
if (v === undefined) return 1;
|
|
844
|
+
const n = Number(v);
|
|
845
|
+
if (!/^[0-9.eE+-]+$/.test(v) || !Number.isFinite(n) || n < 0 || n > 1) {
|
|
846
|
+
warnings.push(`OTEL_TRACES_SAMPLER_ARG=${v} is not a ratio from 0 to 1; 1 is used`);
|
|
847
|
+
return 1;
|
|
848
|
+
}
|
|
849
|
+
return n;
|
|
850
|
+
})();
|
|
851
|
+
const sampler = ((): Sampler => {
|
|
852
|
+
const v = get("OTEL_TRACES_SAMPLER");
|
|
853
|
+
switch (v) {
|
|
854
|
+
case undefined:
|
|
855
|
+
return DEFAULT_SAMPLER;
|
|
856
|
+
case "always_on":
|
|
857
|
+
return { kind: "always_on" };
|
|
858
|
+
case "always_off":
|
|
859
|
+
return { kind: "always_off" };
|
|
860
|
+
case "traceidratio":
|
|
861
|
+
return { kind: "traceidratio", ratio };
|
|
862
|
+
case "parentbased_always_on":
|
|
863
|
+
return { kind: "parentbased", root: { kind: "always_on" } };
|
|
864
|
+
case "parentbased_always_off":
|
|
865
|
+
return { kind: "parentbased", root: { kind: "always_off" } };
|
|
866
|
+
case "parentbased_traceidratio":
|
|
867
|
+
return { kind: "parentbased", root: { kind: "traceidratio", ratio } };
|
|
868
|
+
default:
|
|
869
|
+
warnings.push(`OTEL_TRACES_SAMPLER=${v} is not supported; parentbased_always_on is used`);
|
|
870
|
+
return DEFAULT_SAMPLER;
|
|
871
|
+
}
|
|
872
|
+
})();
|
|
873
|
+
|
|
874
|
+
const batch = (prefix: "OTEL_BSP" | "OTEL_BLRP", scheduleDelay: number): BatchConfig => {
|
|
875
|
+
const maxQueueSize = int(`${prefix}_MAX_QUEUE_SIZE`, 2048, 1);
|
|
876
|
+
let maxExportBatchSize = int(`${prefix}_MAX_EXPORT_BATCH_SIZE`, Math.min(512, maxQueueSize), 1);
|
|
877
|
+
if (maxExportBatchSize > maxQueueSize) {
|
|
878
|
+
warnings.push(`${prefix}_MAX_EXPORT_BATCH_SIZE is more than ${prefix}_MAX_QUEUE_SIZE; ${maxQueueSize} is used`);
|
|
879
|
+
maxExportBatchSize = maxQueueSize;
|
|
880
|
+
}
|
|
881
|
+
return {
|
|
882
|
+
scheduleDelayMs: int(`${prefix}_SCHEDULE_DELAY`, scheduleDelay),
|
|
883
|
+
exportTimeoutMs: int(`${prefix}_EXPORT_TIMEOUT`, 30000),
|
|
884
|
+
maxQueueSize,
|
|
885
|
+
maxExportBatchSize,
|
|
886
|
+
};
|
|
887
|
+
};
|
|
888
|
+
|
|
889
|
+
const valueLength =
|
|
890
|
+
get("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT") === undefined ? Infinity : int("OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT", Infinity);
|
|
891
|
+
const limits: Limits = {
|
|
892
|
+
attributeValueLength: valueLength,
|
|
893
|
+
attributeCount: int("OTEL_ATTRIBUTE_COUNT_LIMIT", 128),
|
|
894
|
+
eventCount: int("OTEL_SPAN_EVENT_COUNT_LIMIT", 128),
|
|
895
|
+
linkCount: int("OTEL_SPAN_LINK_COUNT_LIMIT", 128),
|
|
896
|
+
};
|
|
897
|
+
|
|
898
|
+
const logLevel = ((): LogLevel => {
|
|
899
|
+
const v = get("OTEL_LOG_LEVEL")?.toLowerCase();
|
|
900
|
+
if (v === undefined) return "info";
|
|
901
|
+
const found = LOG_LEVELS.find((l) => l === v);
|
|
902
|
+
if (found === undefined) warnings.push(`OTEL_LOG_LEVEL=${v} is not one of ${LOG_LEVELS.join(", ")}; info is used`);
|
|
903
|
+
return found ?? "info";
|
|
904
|
+
})();
|
|
905
|
+
|
|
906
|
+
const config: OtelConfig = {
|
|
907
|
+
disabled,
|
|
908
|
+
resource,
|
|
909
|
+
exporters: { traces: exporter("traces"), logs: exporter("logs"), metrics: exporter("metrics") },
|
|
910
|
+
sampler,
|
|
911
|
+
spanBatch: batch("OTEL_BSP", 5000),
|
|
912
|
+
logBatch: batch("OTEL_BLRP", 1000),
|
|
913
|
+
metricExportIntervalMs: int("OTEL_METRIC_EXPORT_INTERVAL", 60000),
|
|
914
|
+
metricExportTimeoutMs: int("OTEL_METRIC_EXPORT_TIMEOUT", 30000),
|
|
915
|
+
limits,
|
|
916
|
+
logLevel,
|
|
917
|
+
};
|
|
918
|
+
return { config, warnings };
|
|
919
|
+
}
|