@mark1russell7/otel-ts 0.8.5 → 0.8.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,306 @@
1
+ /**
2
+ * The error record: an error as data, with the ids of its context.
3
+ *
4
+ * An error that a page or a service shows as bare text loses its context: the
5
+ * trace, the session, the request and the procedure. `errorRecord()` reads them
6
+ * from the active context of the context manager, at the place of the error.
7
+ * A view, a copy, a report and a log line then use the same record.
8
+ *
9
+ * This module depends on `@opentelemetry/api` and `@mark1russell7/text` only.
10
+ * Without an SDK, a record has no trace id, and `reportError()` emits its log
11
+ * record to the no-op logger of the API.
12
+ *
13
+ * The record holds no secret: each text goes through the redaction of
14
+ * `@mark1russell7/text/redact` (the token shapes of known services, and the
15
+ * values of parameters with the name of a secret).
16
+ */
17
+ import { context, isSpanContextValid, logs, SeverityNumber, SpanStatusCode, trace, type Attributes, type Context } from "@opentelemetry/api";
18
+ import { errorMessage } from "@mark1russell7/text";
19
+ import { CONTEXT_SHAPES, redactSecretShapes, SECRET_SHAPES } from "@mark1russell7/text/redact";
20
+ import { contextValues } from "./context.js";
21
+
22
+ /** The format of an error record. A change that breaks a reader gives a new number. */
23
+ export const ERROR_RECORD_FORMAT = "otel-ts.error/1";
24
+
25
+ /** The most causes in a record. A longer chain, or a loop, ends with a cause of the name `CauseLimit`. */
26
+ export const MAX_ERROR_CAUSES = 8;
27
+
28
+ /** The most characters of one stack in a record */
29
+ export const MAX_STACK_LENGTH = 4000;
30
+
31
+ /** One error of the cause chain */
32
+ export interface ErrorCause {
33
+ /** The name, for example `TypeError`. A thrown value that is not an error gives its type, for example `string`. */
34
+ readonly name: string;
35
+ /** The message, with no secret */
36
+ readonly message: string;
37
+ /** The `code` of the error, when it has a code of type string or number (for example `ECONNRESET`) */
38
+ readonly code?: string;
39
+ /** The stack, with no secret, when the options ask for it */
40
+ readonly stack?: string;
41
+ /** Where this cause comes from in its parent: `cause`, or `errors[1]` of an `AggregateError` */
42
+ readonly via?: string;
43
+ }
44
+
45
+ /** The procedure that failed */
46
+ export interface ErrorProcedure {
47
+ /** The name, for example `fleet.inbox.create` or `GET /api/status` */
48
+ readonly name: string;
49
+ /**
50
+ * The digest of the input, for example the SHA-256 of its canonical JSON (`@mark1russell7/rigor-generators`).
51
+ * It tells two calls with the same input apart from two calls with different inputs. The record never holds the input.
52
+ */
53
+ readonly inputDigest?: string;
54
+ }
55
+
56
+ /** An error as data, with the ids of its context. It is plain JSON. */
57
+ export interface ErrorRecord {
58
+ /** Always `ERROR_RECORD_FORMAT` */
59
+ readonly format: typeof ERROR_RECORD_FORMAT;
60
+ /** A random id of this record. A report and the log line give the same id. */
61
+ readonly id: string;
62
+ /** The time of the record, as an ISO 8601 text in UTC */
63
+ readonly at: string;
64
+ /** The name of the error, as in `causes[0]` */
65
+ readonly name: string;
66
+ /** The message of the error, as in `causes[0]` */
67
+ readonly message: string;
68
+ /** The code of the error, as in `causes[0]` */
69
+ readonly code?: string;
70
+ /** The error, then each cause, then each error of an `AggregateError`, depth first */
71
+ readonly causes: readonly ErrorCause[];
72
+ /** The trace id of the active span, when the span context is valid */
73
+ readonly traceId?: string;
74
+ /** The span id of the active span, when the span context is valid */
75
+ readonly spanId?: string;
76
+ /** True when the trace is sampled, thus when a sink can have it */
77
+ readonly sampled?: boolean;
78
+ /** The values of the context keys (`defineContextKeys`) in the context, for example `session.id` and `page` */
79
+ readonly context: Readonly<Record<string, string>>;
80
+ /** The procedure that failed */
81
+ readonly procedure?: ErrorProcedure;
82
+ /** Other facts of the place, for example the URL path of a page or the name of a service, with no secret */
83
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
84
+ }
85
+
86
+ /** The options of `errorRecord()` */
87
+ export interface ErrorRecordOptions {
88
+ /** The procedure that failed */
89
+ readonly procedure?: ErrorProcedure;
90
+ /** Other facts of the place. A text value goes through the redaction. */
91
+ readonly attributes?: Readonly<Record<string, string | number | boolean>>;
92
+ /** The context. Default: the active context. */
93
+ readonly from?: Context;
94
+ /** The time. Default: now. */
95
+ readonly at?: Date;
96
+ /** Keep the stack of each cause. Default: false, because a stack can tell the paths of a computer. */
97
+ readonly stacks?: boolean;
98
+ /** The id of the record. Default: a random id. */
99
+ readonly id?: string;
100
+ }
101
+
102
+ const redact = (text: string): string => redactSecretShapes(text, { shapes: [...SECRET_SHAPES, ...CONTEXT_SHAPES] });
103
+
104
+ const isError = (value: unknown): value is Error =>
105
+ value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
106
+
107
+ /** The fields of one value of the chain. Each read is guarded, because a getter of the value can throw. */
108
+ function causeOf(value: unknown, via: string | undefined, stacks: boolean): ErrorCause {
109
+ const read = (key: string): unknown => {
110
+ try {
111
+ return (value as Record<string, unknown>)[key];
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ };
116
+ const error = isError(value);
117
+ const rawName = error ? read("name") : undefined;
118
+ const name = error ? (typeof rawName === "string" && rawName !== "" ? rawName : "Error") : value === null ? "null" : typeof value;
119
+ const code = error ? read("code") : undefined;
120
+ const stack = error && stacks ? read("stack") : undefined;
121
+ return {
122
+ name: redact(name),
123
+ message: redact(errorMessage(value)),
124
+ ...(typeof code === "string" || typeof code === "number" ? { code: redact(String(code)) } : {}),
125
+ ...(typeof stack === "string" ? { stack: redact(stack.slice(0, MAX_STACK_LENGTH)) } : {}),
126
+ ...(via === undefined ? {} : { via }),
127
+ };
128
+ }
129
+
130
+ /** The chain of `error`: the error, its `cause`, then the `errors` of an `AggregateError`, depth first, with no loop */
131
+ function causesOf(error: unknown, stacks: boolean): ErrorCause[] {
132
+ const causes: ErrorCause[] = [];
133
+ const seen = new Set<unknown>();
134
+ const visit = (value: unknown, via: string | undefined): void => {
135
+ if (causes.length >= MAX_ERROR_CAUSES) return;
136
+ if (typeof value === "object" && value !== null) {
137
+ if (seen.has(value)) return;
138
+ seen.add(value);
139
+ }
140
+ causes.push(causeOf(value, via, stacks));
141
+ if (!isError(value)) return;
142
+ let cause: unknown;
143
+ let errors: unknown;
144
+ try {
145
+ cause = (value as { cause?: unknown }).cause;
146
+ errors = (value as { errors?: unknown }).errors;
147
+ } catch {
148
+ return;
149
+ }
150
+ if (cause !== undefined) visit(cause, "cause");
151
+ if (Array.isArray(errors)) errors.forEach((each, index) => visit(each, `errors[${index}]`));
152
+ };
153
+ visit(error, undefined);
154
+ if (causes.length >= MAX_ERROR_CAUSES) causes[MAX_ERROR_CAUSES - 1] = { name: "CauseLimit", message: `The chain has ${MAX_ERROR_CAUSES - 1} causes or more. The record ends here.` };
155
+ return causes;
156
+ }
157
+
158
+ /** A random id of 16 bytes as hex, from the Web Crypto API of the platform, else from `Math.random` */
159
+ function recordId(): string {
160
+ const bytes = new Uint8Array(16);
161
+ const crypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } }).crypto;
162
+ if (crypto?.getRandomValues) crypto.getRandomValues(bytes);
163
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
164
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
165
+ }
166
+
167
+ /**
168
+ * The record of `error`, with the ids of the context: the trace and span id of the active span, the context keys,
169
+ * the procedure and the cause chain. The function never throws, also for a thrown value that is not an error.
170
+ */
171
+ export function errorRecord(error: unknown, options: ErrorRecordOptions = {}): ErrorRecord {
172
+ const from = options.from ?? context.active();
173
+ const causes = causesOf(error, options.stacks ?? false);
174
+ const first = causes[0] ?? { name: "unknown", message: "" };
175
+ const span = trace.getSpanContext(from);
176
+ const valid = span !== undefined && isSpanContextValid(span);
177
+ const attributes = options.attributes
178
+ ? Object.fromEntries(Object.entries(options.attributes).map(([key, value]) => [key, typeof value === "string" ? redact(value) : value]))
179
+ : undefined;
180
+ return {
181
+ format: ERROR_RECORD_FORMAT,
182
+ id: options.id ?? recordId(),
183
+ at: (options.at ?? new Date()).toISOString(),
184
+ name: first.name,
185
+ message: first.message,
186
+ ...(first.code === undefined ? {} : { code: first.code }),
187
+ causes,
188
+ ...(valid ? { traceId: span.traceId, spanId: span.spanId, sampled: (span.traceFlags & 1) === 1 } : {}),
189
+ context: Object.fromEntries(Object.entries(contextValues(from)).map(([key, value]) => [key, redact(value)])),
190
+ ...(options.procedure
191
+ ? { procedure: { name: redact(options.procedure.name), ...(options.procedure.inputDigest === undefined ? {} : { inputDigest: options.procedure.inputDigest }) } }
192
+ : {}),
193
+ ...(attributes ? { attributes } : {}),
194
+ };
195
+ }
196
+
197
+ /**
198
+ * The attributes of the log record of an error record, in the names of the semantic conventions
199
+ * (`exception.type`, `exception.message`), with `error.record.id` and the procedure. The trace and span id come with
200
+ * the context of the log record, and the context processors of otel-ts add the context keys.
201
+ */
202
+ export function errorLogAttributes(record: ErrorRecord): Attributes {
203
+ return {
204
+ "exception.type": record.name,
205
+ "exception.message": record.message,
206
+ "error.record.id": record.id,
207
+ ...(record.code === undefined ? {} : { "error.code": record.code }),
208
+ ...(record.causes.length > 1 ? { "error.causes": record.causes.slice(1).map((cause) => `${cause.name}: ${cause.message}`) } : {}),
209
+ ...(record.procedure ? { "error.procedure": record.procedure.name } : {}),
210
+ ...(record.procedure?.inputDigest === undefined ? {} : { "error.input_digest": record.procedure.inputDigest }),
211
+ ...(record.attributes ?? {}),
212
+ };
213
+ }
214
+
215
+ /** The options of `reportError()` */
216
+ export interface ReportErrorOptions extends ErrorRecordOptions {
217
+ /** The scope of the logger. Default: `otel-ts`. */
218
+ readonly logger?: string;
219
+ /** Mark the active span as failed, with the exception. Default: true. */
220
+ readonly markSpan?: boolean;
221
+ }
222
+
223
+ /**
224
+ * Make the record of `error`, emit it as one log record of severity ERROR in the same context, and mark the active
225
+ * span as failed. The view, the log line and the span thus give the same ids. Without an SDK, the log record and the
226
+ * span go to the no-op of the API, and the record stays.
227
+ */
228
+ export function reportError(error: unknown, options: ReportErrorOptions = {}): ErrorRecord {
229
+ const from = options.from ?? context.active();
230
+ const record = errorRecord(error, { ...options, from });
231
+ logs.getLogger(options.logger ?? "otel-ts").emit({
232
+ severityNumber: SeverityNumber.ERROR,
233
+ severityText: "ERROR",
234
+ body: record.procedure ? `${record.procedure.name}: ${record.message}` : record.message,
235
+ attributes: errorLogAttributes(record),
236
+ context: from,
237
+ });
238
+ if (options.markSpan ?? true) {
239
+ const span = trace.getSpan(from);
240
+ if (span?.isRecording()) {
241
+ span.recordException({ name: record.name, message: record.message });
242
+ span.setStatus({ code: SpanStatusCode.ERROR, message: record.message });
243
+ }
244
+ }
245
+ return record;
246
+ }
247
+
248
+ /**
249
+ * A copy of `record` with each text through the redaction. `errorRecord()` already redacts. Use this function for a
250
+ * record from another place, for example the JSON of a server, before a view shows it or a person copies it.
251
+ * It is idempotent: a second pass changes nothing.
252
+ */
253
+ export function redactErrorRecord(record: ErrorRecord): ErrorRecord {
254
+ const text = (value: unknown): string => redact(String(value ?? ""));
255
+ const strings = (values: Readonly<Record<string, unknown>> | undefined): Record<string, string> =>
256
+ Object.fromEntries(Object.entries(values ?? {}).map(([key, value]) => [text(key), text(value)]));
257
+ const causes = Array.isArray(record.causes) ? record.causes : [];
258
+ return {
259
+ format: ERROR_RECORD_FORMAT,
260
+ id: text(record.id),
261
+ at: text(record.at),
262
+ name: text(record.name),
263
+ message: text(record.message),
264
+ ...(record.code === undefined ? {} : { code: text(record.code) }),
265
+ causes: causes.slice(0, MAX_ERROR_CAUSES).map((cause) => ({
266
+ name: text(cause.name),
267
+ message: text(cause.message),
268
+ ...(cause.code === undefined ? {} : { code: text(cause.code) }),
269
+ ...(cause.stack === undefined ? {} : { stack: text(cause.stack).slice(0, MAX_STACK_LENGTH) }),
270
+ ...(cause.via === undefined ? {} : { via: text(cause.via) }),
271
+ })),
272
+ ...(record.traceId === undefined ? {} : { traceId: text(record.traceId) }),
273
+ ...(record.spanId === undefined ? {} : { spanId: text(record.spanId) }),
274
+ ...(record.sampled === undefined ? {} : { sampled: record.sampled === true }),
275
+ context: strings(record.context),
276
+ ...(record.procedure
277
+ ? { procedure: { name: text(record.procedure.name), ...(record.procedure.inputDigest === undefined ? {} : { inputDigest: text(record.procedure.inputDigest) }) } }
278
+ : {}),
279
+ ...(record.attributes
280
+ ? { attributes: Object.fromEntries(Object.entries(record.attributes).map(([key, value]) => [text(key), typeof value === "string" ? text(value) : typeof value === "number" || typeof value === "boolean" ? value : text(value)])) }
281
+ : {}),
282
+ };
283
+ }
284
+
285
+ /**
286
+ * The record as a text to copy or to paste in a report: the message, then each id, then the cause chain, then the
287
+ * record as JSON. A reader with no tool reads the top, and a tool reads the JSON. The record goes through
288
+ * `redactErrorRecord()` first, so a record from another place gives no secret either.
289
+ */
290
+ export function errorRecordText(input: ErrorRecord): string {
291
+ const record = redactErrorRecord(input);
292
+ const lines = [`${record.name}: ${record.message}`, ""];
293
+ const row = (label: string, value: string | undefined): void => {
294
+ if (value !== undefined && value !== "") lines.push(`${label}: ${value}`);
295
+ };
296
+ row("Time", record.at);
297
+ row("Record", record.id);
298
+ row("Procedure", record.procedure?.name);
299
+ row("Input digest", record.procedure?.inputDigest);
300
+ row("Trace", record.traceId);
301
+ row("Span", record.spanId);
302
+ for (const [key, value] of Object.entries(record.context)) row(key, value);
303
+ for (const cause of record.causes.slice(1)) row(`Cause (${cause.via ?? "cause"})`, `${cause.name}: ${cause.message}`);
304
+ lines.push("", JSON.stringify(record, null, 2));
305
+ return lines.join("\n");
306
+ }