@mark1russell7/otel-ts 0.8.5 → 0.8.6
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/README.md +22 -0
- package/dist/error-record.d.ts +120 -0
- package/dist/error-record.d.ts.map +1 -0
- package/dist/error-record.js +190 -0
- package/dist/error-record.js.map +1 -0
- package/package.json +6 -1
- package/src/error-record.ts +267 -0
package/README.md
CHANGED
|
@@ -244,6 +244,28 @@ In the browser, `init()` registers the context when `tracing` is on (the default
|
|
|
244
244
|
|
|
245
245
|
Only one part of a program registers the context. A second `init()` before the `shutdown()` of the first is an error. `shutdown()` removes the registration. With `tracing: false`, `init()` registers no context manager and no propagator.
|
|
246
246
|
|
|
247
|
+
## Error records
|
|
248
|
+
|
|
249
|
+
The entry `@mark1russell7/otel-ts/error` makes a record of an error with the ids of its context. A view, a copy, a report and a log line then use the same record. It depends on `@opentelemetry/api` and `@mark1russell7/text` only, and it needs no SDK.
|
|
250
|
+
|
|
251
|
+
```ts
|
|
252
|
+
import { reportError, errorRecordText } from "@mark1russell7/otel-ts/error";
|
|
253
|
+
|
|
254
|
+
try {
|
|
255
|
+
await save(item);
|
|
256
|
+
} catch (error) {
|
|
257
|
+
// One ERROR log record in this context, the span marked as failed, and the record
|
|
258
|
+
const record = reportError(error, { procedure: { name: "items.save", inputDigest } });
|
|
259
|
+
show(record); // the message, the trace id, the context keys and the causes
|
|
260
|
+
await navigator.clipboard.writeText(errorRecordText(record));
|
|
261
|
+
}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
- `errorRecord(error, options)` gives the record only. It reads the active context, or the context in `options.from`.
|
|
265
|
+
- The record holds the trace and span id of the active span, the values of the context keys, the procedure, the cause chain and the time. It never holds the input: give the digest of the input, for example the SHA-256 of its canonical JSON.
|
|
266
|
+
- Each text goes through the redaction of `@mark1russell7/text/redact`. A stack stays out, unless you give `stacks: true`.
|
|
267
|
+
- Without an SDK, the record has no trace id, and the log record goes to the no-op logger of the API.
|
|
268
|
+
|
|
247
269
|
## Writer identity
|
|
248
270
|
|
|
249
271
|
Prometheus and Mimir make the `instance` label from the `service.instance.id` resource attribute. Each SDK instance writes its own metric series. Two SDK instances with the same identity write to the same series. Then Mimir rejects samples, and `rate()` gives incorrect values.
|
|
@@ -0,0 +1,120 @@
|
|
|
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 { type Attributes, type Context } from "@opentelemetry/api";
|
|
18
|
+
/** The format of an error record. A change that breaks a reader gives a new number. */
|
|
19
|
+
export declare const ERROR_RECORD_FORMAT = "otel-ts.error/1";
|
|
20
|
+
/** The most causes in a record. A longer chain, or a loop, ends with a cause of the name `CauseLimit`. */
|
|
21
|
+
export declare const MAX_ERROR_CAUSES = 8;
|
|
22
|
+
/** The most characters of one stack in a record */
|
|
23
|
+
export declare const MAX_STACK_LENGTH = 4000;
|
|
24
|
+
/** One error of the cause chain */
|
|
25
|
+
export interface ErrorCause {
|
|
26
|
+
/** The name, for example `TypeError`. A thrown value that is not an error gives its type, for example `string`. */
|
|
27
|
+
readonly name: string;
|
|
28
|
+
/** The message, with no secret */
|
|
29
|
+
readonly message: string;
|
|
30
|
+
/** The `code` of the error, when it has a code of type string or number (for example `ECONNRESET`) */
|
|
31
|
+
readonly code?: string;
|
|
32
|
+
/** The stack, with no secret, when the options ask for it */
|
|
33
|
+
readonly stack?: string;
|
|
34
|
+
/** Where this cause comes from in its parent: `cause`, or `errors[1]` of an `AggregateError` */
|
|
35
|
+
readonly via?: string;
|
|
36
|
+
}
|
|
37
|
+
/** The procedure that failed */
|
|
38
|
+
export interface ErrorProcedure {
|
|
39
|
+
/** The name, for example `fleet.inbox.create` or `GET /api/status` */
|
|
40
|
+
readonly name: string;
|
|
41
|
+
/**
|
|
42
|
+
* The digest of the input, for example the SHA-256 of its canonical JSON (`@mark1russell7/rigor-generators`).
|
|
43
|
+
* It tells two calls with the same input apart from two calls with different inputs. The record never holds the input.
|
|
44
|
+
*/
|
|
45
|
+
readonly inputDigest?: string;
|
|
46
|
+
}
|
|
47
|
+
/** An error as data, with the ids of its context. It is plain JSON. */
|
|
48
|
+
export interface ErrorRecord {
|
|
49
|
+
/** Always `ERROR_RECORD_FORMAT` */
|
|
50
|
+
readonly format: typeof ERROR_RECORD_FORMAT;
|
|
51
|
+
/** A random id of this record. A report and the log line give the same id. */
|
|
52
|
+
readonly id: string;
|
|
53
|
+
/** The time of the record, as an ISO 8601 text in UTC */
|
|
54
|
+
readonly at: string;
|
|
55
|
+
/** The name of the error, as in `causes[0]` */
|
|
56
|
+
readonly name: string;
|
|
57
|
+
/** The message of the error, as in `causes[0]` */
|
|
58
|
+
readonly message: string;
|
|
59
|
+
/** The code of the error, as in `causes[0]` */
|
|
60
|
+
readonly code?: string;
|
|
61
|
+
/** The error, then each cause, then each error of an `AggregateError`, depth first */
|
|
62
|
+
readonly causes: readonly ErrorCause[];
|
|
63
|
+
/** The trace id of the active span, when the span context is valid */
|
|
64
|
+
readonly traceId?: string;
|
|
65
|
+
/** The span id of the active span, when the span context is valid */
|
|
66
|
+
readonly spanId?: string;
|
|
67
|
+
/** True when the trace is sampled, thus when a sink can have it */
|
|
68
|
+
readonly sampled?: boolean;
|
|
69
|
+
/** The values of the context keys (`defineContextKeys`) in the context, for example `session.id` and `page` */
|
|
70
|
+
readonly context: Readonly<Record<string, string>>;
|
|
71
|
+
/** The procedure that failed */
|
|
72
|
+
readonly procedure?: ErrorProcedure;
|
|
73
|
+
/** Other facts of the place, for example the URL path of a page or the name of a service, with no secret */
|
|
74
|
+
readonly attributes?: Readonly<Record<string, string | number | boolean>>;
|
|
75
|
+
}
|
|
76
|
+
/** The options of `errorRecord()` */
|
|
77
|
+
export interface ErrorRecordOptions {
|
|
78
|
+
/** The procedure that failed */
|
|
79
|
+
readonly procedure?: ErrorProcedure;
|
|
80
|
+
/** Other facts of the place. A text value goes through the redaction. */
|
|
81
|
+
readonly attributes?: Readonly<Record<string, string | number | boolean>>;
|
|
82
|
+
/** The context. Default: the active context. */
|
|
83
|
+
readonly from?: Context;
|
|
84
|
+
/** The time. Default: now. */
|
|
85
|
+
readonly at?: Date;
|
|
86
|
+
/** Keep the stack of each cause. Default: false, because a stack can tell the paths of a computer. */
|
|
87
|
+
readonly stacks?: boolean;
|
|
88
|
+
/** The id of the record. Default: a random id. */
|
|
89
|
+
readonly id?: string;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The record of `error`, with the ids of the context: the trace and span id of the active span, the context keys,
|
|
93
|
+
* the procedure and the cause chain. The function never throws, also for a thrown value that is not an error.
|
|
94
|
+
*/
|
|
95
|
+
export declare function errorRecord(error: unknown, options?: ErrorRecordOptions): ErrorRecord;
|
|
96
|
+
/**
|
|
97
|
+
* The attributes of the log record of an error record, in the names of the semantic conventions
|
|
98
|
+
* (`exception.type`, `exception.message`), with `error.record.id` and the procedure. The trace and span id come with
|
|
99
|
+
* the context of the log record, and the context processors of otel-ts add the context keys.
|
|
100
|
+
*/
|
|
101
|
+
export declare function errorLogAttributes(record: ErrorRecord): Attributes;
|
|
102
|
+
/** The options of `reportError()` */
|
|
103
|
+
export interface ReportErrorOptions extends ErrorRecordOptions {
|
|
104
|
+
/** The scope of the logger. Default: `otel-ts`. */
|
|
105
|
+
readonly logger?: string;
|
|
106
|
+
/** Mark the active span as failed, with the exception. Default: true. */
|
|
107
|
+
readonly markSpan?: boolean;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Make the record of `error`, emit it as one log record of severity ERROR in the same context, and mark the active
|
|
111
|
+
* span as failed. The view, the log line and the span thus give the same ids. Without an SDK, the log record and the
|
|
112
|
+
* span go to the no-op of the API, and the record stays.
|
|
113
|
+
*/
|
|
114
|
+
export declare function reportError(error: unknown, options?: ReportErrorOptions): ErrorRecord;
|
|
115
|
+
/**
|
|
116
|
+
* The record as a text to copy or to paste in a report: the message, then each id, then the cause chain, then the
|
|
117
|
+
* record as JSON. A reader with no tool reads the top, and a tool reads the JSON.
|
|
118
|
+
*/
|
|
119
|
+
export declare function errorRecordText(record: ErrorRecord): string;
|
|
120
|
+
//# sourceMappingURL=error-record.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-record.d.ts","sourceRoot":"","sources":["../src/error-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAA4E,KAAK,UAAU,EAAE,KAAK,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAK7I,uFAAuF;AACvF,eAAO,MAAM,mBAAmB,oBAAoB,CAAC;AAErD,0GAA0G;AAC1G,eAAO,MAAM,gBAAgB,IAAI,CAAC;AAElC,mDAAmD;AACnD,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC,mCAAmC;AACnC,MAAM,WAAW,UAAU;IACzB,mHAAmH;IACnH,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,kCAAkC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,sGAAsG;IACtG,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IACvB,6DAA6D;IAC7D,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,gGAAgG;IAChG,QAAQ,C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IACjC,gCAAgC;IAChC,QAAQ,CAAC,SAAS,CAAC,EAAE,cAAc,CAAC;IACpC,yEAAyE;IACzE,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC;IAC1E,gDAAgD;IAChD,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB,8BAA8B;IAC9B,QAAQ,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC;IACnB,sGAAsG;IACtG,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,kDAAkD;IAClD,QAAQ,CAAC,EAAE,CAAC,EAAE,MAAM,CAAC;CACtB;AAmED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAwBzF;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,WAAW,GAAG,UAAU,CAWlE;AAED,qCAAqC;AACrC,MAAM,WAAW,kBAAmB,SAAQ,kBAAkB;IAC5D,mDAAmD;IACnD,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IACzB,yEAAyE;IACzE,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAkBzF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,WAAW,GAAG,MAAM,CAe3D"}
|
|
@@ -0,0 +1,190 @@
|
|
|
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 } 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
|
+
/** The format of an error record. A change that breaks a reader gives a new number. */
|
|
22
|
+
export const ERROR_RECORD_FORMAT = "otel-ts.error/1";
|
|
23
|
+
/** The most causes in a record. A longer chain, or a loop, ends with a cause of the name `CauseLimit`. */
|
|
24
|
+
export const MAX_ERROR_CAUSES = 8;
|
|
25
|
+
/** The most characters of one stack in a record */
|
|
26
|
+
export const MAX_STACK_LENGTH = 4000;
|
|
27
|
+
const redact = (text) => redactSecretShapes(text, { shapes: [...SECRET_SHAPES, ...CONTEXT_SHAPES] });
|
|
28
|
+
const isError = (value) => value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
|
|
29
|
+
/** The fields of one value of the chain. Each read is guarded, because a getter of the value can throw. */
|
|
30
|
+
function causeOf(value, via, stacks) {
|
|
31
|
+
const read = (key) => {
|
|
32
|
+
try {
|
|
33
|
+
return value[key];
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return undefined;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const error = isError(value);
|
|
40
|
+
const rawName = error ? read("name") : undefined;
|
|
41
|
+
const name = error ? (typeof rawName === "string" && rawName !== "" ? rawName : "Error") : value === null ? "null" : typeof value;
|
|
42
|
+
const code = error ? read("code") : undefined;
|
|
43
|
+
const stack = error && stacks ? read("stack") : undefined;
|
|
44
|
+
return {
|
|
45
|
+
name: redact(name),
|
|
46
|
+
message: redact(errorMessage(value)),
|
|
47
|
+
...(typeof code === "string" || typeof code === "number" ? { code: redact(String(code)) } : {}),
|
|
48
|
+
...(typeof stack === "string" ? { stack: redact(stack.slice(0, MAX_STACK_LENGTH)) } : {}),
|
|
49
|
+
...(via === undefined ? {} : { via }),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
/** The chain of `error`: the error, its `cause`, then the `errors` of an `AggregateError`, depth first, with no loop */
|
|
53
|
+
function causesOf(error, stacks) {
|
|
54
|
+
const causes = [];
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
const visit = (value, via) => {
|
|
57
|
+
if (causes.length >= MAX_ERROR_CAUSES)
|
|
58
|
+
return;
|
|
59
|
+
if (typeof value === "object" && value !== null) {
|
|
60
|
+
if (seen.has(value))
|
|
61
|
+
return;
|
|
62
|
+
seen.add(value);
|
|
63
|
+
}
|
|
64
|
+
causes.push(causeOf(value, via, stacks));
|
|
65
|
+
if (!isError(value))
|
|
66
|
+
return;
|
|
67
|
+
let cause;
|
|
68
|
+
let errors;
|
|
69
|
+
try {
|
|
70
|
+
cause = value.cause;
|
|
71
|
+
errors = value.errors;
|
|
72
|
+
}
|
|
73
|
+
catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (cause !== undefined)
|
|
77
|
+
visit(cause, "cause");
|
|
78
|
+
if (Array.isArray(errors))
|
|
79
|
+
errors.forEach((each, index) => visit(each, `errors[${index}]`));
|
|
80
|
+
};
|
|
81
|
+
visit(error, undefined);
|
|
82
|
+
if (causes.length >= MAX_ERROR_CAUSES)
|
|
83
|
+
causes[MAX_ERROR_CAUSES - 1] = { name: "CauseLimit", message: `The chain has ${MAX_ERROR_CAUSES - 1} causes or more. The record ends here.` };
|
|
84
|
+
return causes;
|
|
85
|
+
}
|
|
86
|
+
/** A random id of 16 bytes as hex, from the Web Crypto API of the platform, else from `Math.random` */
|
|
87
|
+
function recordId() {
|
|
88
|
+
const bytes = new Uint8Array(16);
|
|
89
|
+
const crypto = globalThis.crypto;
|
|
90
|
+
if (crypto?.getRandomValues)
|
|
91
|
+
crypto.getRandomValues(bytes);
|
|
92
|
+
else
|
|
93
|
+
for (let i = 0; i < bytes.length; i++)
|
|
94
|
+
bytes[i] = Math.floor(Math.random() * 256);
|
|
95
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* The record of `error`, with the ids of the context: the trace and span id of the active span, the context keys,
|
|
99
|
+
* the procedure and the cause chain. The function never throws, also for a thrown value that is not an error.
|
|
100
|
+
*/
|
|
101
|
+
export function errorRecord(error, options = {}) {
|
|
102
|
+
const from = options.from ?? context.active();
|
|
103
|
+
const causes = causesOf(error, options.stacks ?? false);
|
|
104
|
+
const first = causes[0] ?? { name: "unknown", message: "" };
|
|
105
|
+
const span = trace.getSpanContext(from);
|
|
106
|
+
const valid = span !== undefined && isSpanContextValid(span);
|
|
107
|
+
const attributes = options.attributes
|
|
108
|
+
? Object.fromEntries(Object.entries(options.attributes).map(([key, value]) => [key, typeof value === "string" ? redact(value) : value]))
|
|
109
|
+
: undefined;
|
|
110
|
+
return {
|
|
111
|
+
format: ERROR_RECORD_FORMAT,
|
|
112
|
+
id: options.id ?? recordId(),
|
|
113
|
+
at: (options.at ?? new Date()).toISOString(),
|
|
114
|
+
name: first.name,
|
|
115
|
+
message: first.message,
|
|
116
|
+
...(first.code === undefined ? {} : { code: first.code }),
|
|
117
|
+
causes,
|
|
118
|
+
...(valid ? { traceId: span.traceId, spanId: span.spanId, sampled: (span.traceFlags & 1) === 1 } : {}),
|
|
119
|
+
context: Object.fromEntries(Object.entries(contextValues(from)).map(([key, value]) => [key, redact(value)])),
|
|
120
|
+
...(options.procedure
|
|
121
|
+
? { procedure: { name: redact(options.procedure.name), ...(options.procedure.inputDigest === undefined ? {} : { inputDigest: options.procedure.inputDigest }) } }
|
|
122
|
+
: {}),
|
|
123
|
+
...(attributes ? { attributes } : {}),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The attributes of the log record of an error record, in the names of the semantic conventions
|
|
128
|
+
* (`exception.type`, `exception.message`), with `error.record.id` and the procedure. The trace and span id come with
|
|
129
|
+
* the context of the log record, and the context processors of otel-ts add the context keys.
|
|
130
|
+
*/
|
|
131
|
+
export function errorLogAttributes(record) {
|
|
132
|
+
return {
|
|
133
|
+
"exception.type": record.name,
|
|
134
|
+
"exception.message": record.message,
|
|
135
|
+
"error.record.id": record.id,
|
|
136
|
+
...(record.code === undefined ? {} : { "error.code": record.code }),
|
|
137
|
+
...(record.causes.length > 1 ? { "error.causes": record.causes.slice(1).map((cause) => `${cause.name}: ${cause.message}`) } : {}),
|
|
138
|
+
...(record.procedure ? { "error.procedure": record.procedure.name } : {}),
|
|
139
|
+
...(record.procedure?.inputDigest === undefined ? {} : { "error.input_digest": record.procedure.inputDigest }),
|
|
140
|
+
...(record.attributes ?? {}),
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Make the record of `error`, emit it as one log record of severity ERROR in the same context, and mark the active
|
|
145
|
+
* span as failed. The view, the log line and the span thus give the same ids. Without an SDK, the log record and the
|
|
146
|
+
* span go to the no-op of the API, and the record stays.
|
|
147
|
+
*/
|
|
148
|
+
export function reportError(error, options = {}) {
|
|
149
|
+
const from = options.from ?? context.active();
|
|
150
|
+
const record = errorRecord(error, { ...options, from });
|
|
151
|
+
logs.getLogger(options.logger ?? "otel-ts").emit({
|
|
152
|
+
severityNumber: SeverityNumber.ERROR,
|
|
153
|
+
severityText: "ERROR",
|
|
154
|
+
body: record.procedure ? `${record.procedure.name}: ${record.message}` : record.message,
|
|
155
|
+
attributes: errorLogAttributes(record),
|
|
156
|
+
context: from,
|
|
157
|
+
});
|
|
158
|
+
if (options.markSpan ?? true) {
|
|
159
|
+
const span = trace.getSpan(from);
|
|
160
|
+
if (span?.isRecording()) {
|
|
161
|
+
span.recordException({ name: record.name, message: record.message });
|
|
162
|
+
span.setStatus({ code: SpanStatusCode.ERROR, message: record.message });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return record;
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* The record as a text to copy or to paste in a report: the message, then each id, then the cause chain, then the
|
|
169
|
+
* record as JSON. A reader with no tool reads the top, and a tool reads the JSON.
|
|
170
|
+
*/
|
|
171
|
+
export function errorRecordText(record) {
|
|
172
|
+
const lines = [`${record.name}: ${record.message}`, ""];
|
|
173
|
+
const row = (label, value) => {
|
|
174
|
+
if (value !== undefined && value !== "")
|
|
175
|
+
lines.push(`${label}: ${value}`);
|
|
176
|
+
};
|
|
177
|
+
row("Time", record.at);
|
|
178
|
+
row("Record", record.id);
|
|
179
|
+
row("Procedure", record.procedure?.name);
|
|
180
|
+
row("Input digest", record.procedure?.inputDigest);
|
|
181
|
+
row("Trace", record.traceId);
|
|
182
|
+
row("Span", record.spanId);
|
|
183
|
+
for (const [key, value] of Object.entries(record.context))
|
|
184
|
+
row(key, value);
|
|
185
|
+
for (const cause of record.causes.slice(1))
|
|
186
|
+
row(`Cause (${cause.via ?? "cause"})`, `${cause.name}: ${cause.message}`);
|
|
187
|
+
lines.push("", JSON.stringify(record, null, 2));
|
|
188
|
+
return lines.join("\n");
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=error-record.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-record.js","sourceRoot":"","sources":["../src/error-record.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,EAAE,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,cAAc,EAAE,cAAc,EAAE,KAAK,EA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
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/otel-ts",
|
|
4
|
-
"version": "0.8.
|
|
4
|
+
"version": "0.8.6",
|
|
5
5
|
"description": "Frontend observability in one init() call — OpenTelemetry + Grafana Faro for any TypeScript web app",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
@@ -55,6 +55,10 @@
|
|
|
55
55
|
"./pull": {
|
|
56
56
|
"types": "./dist/pull.d.ts",
|
|
57
57
|
"import": "./dist/pull.js"
|
|
58
|
+
},
|
|
59
|
+
"./error": {
|
|
60
|
+
"types": "./dist/error-record.d.ts",
|
|
61
|
+
"import": "./dist/error-record.js"
|
|
58
62
|
}
|
|
59
63
|
},
|
|
60
64
|
"files": [
|
|
@@ -64,6 +68,7 @@
|
|
|
64
68
|
],
|
|
65
69
|
"sideEffects": false,
|
|
66
70
|
"dependencies": {
|
|
71
|
+
"@mark1russell7/text": "^0.0.18",
|
|
67
72
|
"@grafana/faro-web-sdk": "^2.13.0",
|
|
68
73
|
"@opentelemetry/api": "^1.10.0",
|
|
69
74
|
"@opentelemetry/auto-instrumentations-web": "^0.70.1",
|
|
@@ -0,0 +1,267 @@
|
|
|
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
|
+
* The record as a text to copy or to paste in a report: the message, then each id, then the cause chain, then the
|
|
250
|
+
* record as JSON. A reader with no tool reads the top, and a tool reads the JSON.
|
|
251
|
+
*/
|
|
252
|
+
export function errorRecordText(record: ErrorRecord): string {
|
|
253
|
+
const lines = [`${record.name}: ${record.message}`, ""];
|
|
254
|
+
const row = (label: string, value: string | undefined): void => {
|
|
255
|
+
if (value !== undefined && value !== "") lines.push(`${label}: ${value}`);
|
|
256
|
+
};
|
|
257
|
+
row("Time", record.at);
|
|
258
|
+
row("Record", record.id);
|
|
259
|
+
row("Procedure", record.procedure?.name);
|
|
260
|
+
row("Input digest", record.procedure?.inputDigest);
|
|
261
|
+
row("Trace", record.traceId);
|
|
262
|
+
row("Span", record.spanId);
|
|
263
|
+
for (const [key, value] of Object.entries(record.context)) row(key, value);
|
|
264
|
+
for (const cause of record.causes.slice(1)) row(`Cause (${cause.via ?? "cause"})`, `${cause.name}: ${cause.message}`);
|
|
265
|
+
lines.push("", JSON.stringify(record, null, 2));
|
|
266
|
+
return lines.join("\n");
|
|
267
|
+
}
|