@mark1russell7/otel-ts 0.8.4 → 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 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.
@@ -320,6 +342,28 @@ A shorter interval sends more samples. Each series then costs more in Mimir and
320
342
 
321
343
  By default, the exporter requests cumulative temporality. In its default configuration, Mimir rejects delta sums and delta histograms. Keep `metricsTemporality` at `"cumulative"` for Mimir and Prometheus.
322
344
 
345
+ ## Read metrics when you ask
346
+
347
+ The entry `/pull` reads the metrics of a process at the times that the program chooses. A lab run, for example, reads them after the start and after each pass. The entry starts no SDK and sends nothing.
348
+
349
+ ```ts
350
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
351
+ import { collectReadings, PullMetricReader } from "@mark1russell7/otel-ts/pull";
352
+
353
+ const reader = new PullMetricReader();
354
+ const provider = new MeterProvider({ readers: [reader] });
355
+ provider.getMeter("app").createCounter("requests").add(1, { route: "/a" });
356
+
357
+ const { readings, errors } = await collectReadings(reader, Date.now());
358
+ // readings: [{ series: 'requests{route="/a"}', at: "2026-11-24T12:00:00.000Z", value: 1 }]
359
+ ```
360
+
361
+ - `PullMetricReader` has no timer and no export. Give it to a `MeterProvider`, or to the SDK as a metric reader.
362
+ - The option `temporality` is `"cumulative"` (the default) or `"delta"`. With `"delta"`, counters and histograms give the change after the last collection.
363
+ - Each set of attributes is a series. With `{ attributes: "sum" }`, each metric is one series, the sum over its attributes.
364
+ - A histogram gives the series `<name>.count` and `<name>.sum`.
365
+ - `errors` is the count of the callbacks that failed in the collection.
366
+
323
367
  ## Page lifecycle
324
368
 
325
369
  The library follows the state of the page with [`page-lifecycle-tracker`](https://github.com/mark1russell7/page-lifecycle-tracker). It uses the tracker that the page shares (`getPageLifecycle()`), and it subscribes in the `export` phase:
@@ -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,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,gCAAgC;AAChC,MAAM,WAAW,cAAc;IAC7B,sEAAsE;IACtE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED,uEAAuE;AACvE,MAAM,WAAW,WAAW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AAC,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,EAAiC,MAAM,oBAAoB,CAAC;AAC7I,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAE7C,uFAAuF;AACvF,MAAM,CAAC,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AAErD,0GAA0G;AAC1G,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAElC,mDAAmD;AACnD,MAAM,CAAC,MAAM,gBAAgB,GAAG,IA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AAM,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IACzC,GAAG,CAAC,cAAc,EAAE,MAAM,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;IACnD,GAAG,CAAC,OAAO,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC;IAC7B,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IAC3B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC;QAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IAC3E,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,UAAU,KAAK,CAAC,GAAG,IAAI,OAAO,GAAG,EAAE,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC;IACtH,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IAChD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
package/dist/pull.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { MetricReader, type ResourceMetrics } from "@opentelemetry/sdk-metrics";
11
+ /**
12
+ * The temporality of a pull reader. With `"cumulative"`, each collection gives the totals from the start. With
13
+ * `"delta"`, the counters and the histograms give the change after the last collection, and the up-down counters
14
+ * and the gauges stay cumulative, as with the OTLP delta preference.
15
+ */
16
+ export type PullTemporality = "cumulative" | "delta";
17
+ /** The options of a {@link PullMetricReader}. */
18
+ export interface PullMetricReaderOptions {
19
+ /** The temporality of each collection. The default is `"cumulative"`. */
20
+ readonly temporality?: PullTemporality;
21
+ }
22
+ /**
23
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
24
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
25
+ *
26
+ * ```ts no-run
27
+ * const reader = new PullMetricReader();
28
+ * const provider = new MeterProvider({ readers: [reader] });
29
+ * const { readings } = await collectReadings(reader, Date.now());
30
+ * ```
31
+ */
32
+ export declare class PullMetricReader extends MetricReader {
33
+ constructor(options?: PullMetricReaderOptions);
34
+ protected onForceFlush(): Promise<void>;
35
+ protected onShutdown(): Promise<void>;
36
+ }
37
+ /** One reading of a series: its key, the UTC time of the collection and its value. */
38
+ export interface MetricReading {
39
+ /**
40
+ * The key of the series. It is the name of the metric, then its attributes in the order of their keys, for example
41
+ * `http.requests{method="GET",status=200}`. With `attributes: "sum"`, it is the name only. A histogram gives the
42
+ * series `<name>.count` and `<name>.sum`.
43
+ */
44
+ readonly series: string;
45
+ /** The UTC time of the collection, in the ISO 8601 form. */
46
+ readonly at: string;
47
+ readonly value: number;
48
+ }
49
+ /** The options of {@link metricReadings}. */
50
+ export interface MetricReadingsOptions {
51
+ /**
52
+ * The series of a metric. With `"series"` (the default), each set of attributes is a series. With `"sum"`, the
53
+ * metric is one series: the sum of its data points over all attributes.
54
+ */
55
+ readonly attributes?: "series" | "sum";
56
+ }
57
+ /**
58
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
59
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
60
+ * their series.
61
+ */
62
+ export declare function metricReadings(metrics: ResourceMetrics, at: number, options?: MetricReadingsOptions): MetricReading[];
63
+ /** The result of one collection: the readings, and the count of the errors of the callbacks. */
64
+ export interface ReadingsCollection {
65
+ readonly readings: readonly MetricReading[];
66
+ readonly errors: number;
67
+ }
68
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
69
+ export declare function collectReadings(reader: MetricReader, at: number, options?: MetricReadingsOptions): Promise<ReadingsCollection>;
70
+ //# sourceMappingURL=pull.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAIL,YAAY,EAEZ,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AAEpC;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,OAAO,CAAC;AAErD,iDAAiD;AACjD,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,QAAQ,CAAC,WAAW,CAAC,EAAE,eAAe,CAAC;CACxC;AASD;;;;;;;;;GASG;AACH,qBAAa,gBAAiB,SAAQ,YAAY;gBACpC,OAAO,GAAE,uBAA4B;cAQ9B,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAI7B,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/C;AAED,sFAAsF;AACtF,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,6CAA6C;AAC7C,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAC;CACxC;AA2BD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,aAAa,EAAE,CAiBzH;AAED,gGAAgG;AAChG,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,0HAA0H;AAC1H,wBAAsB,eAAe,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAGxI"}
package/dist/pull.js ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { AggregationTemporality, DataPointType, InstrumentType, MetricReader, } from "@opentelemetry/sdk-metrics";
11
+ /** The instruments that the delta preference reads as a change. The others stay cumulative. */
12
+ const DELTA_INSTRUMENTS = new Set([
13
+ InstrumentType.COUNTER,
14
+ InstrumentType.OBSERVABLE_COUNTER,
15
+ InstrumentType.HISTOGRAM,
16
+ ]);
17
+ /**
18
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
19
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
20
+ *
21
+ * ```ts no-run
22
+ * const reader = new PullMetricReader();
23
+ * const provider = new MeterProvider({ readers: [reader] });
24
+ * const { readings } = await collectReadings(reader, Date.now());
25
+ * ```
26
+ */
27
+ export class PullMetricReader extends MetricReader {
28
+ constructor(options = {}) {
29
+ const delta = options.temporality === "delta";
30
+ super({
31
+ aggregationTemporalitySelector: (type) => delta && DELTA_INSTRUMENTS.has(type) ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE,
32
+ });
33
+ }
34
+ onForceFlush() {
35
+ return Promise.resolve();
36
+ }
37
+ onShutdown() {
38
+ return Promise.resolve();
39
+ }
40
+ }
41
+ /** This function gives the key of a series: the name, then the attributes in the order of their keys. */
42
+ const seriesKey = (name, attributes) => {
43
+ const keys = Object.keys(attributes)
44
+ .filter((key) => attributes[key] !== undefined)
45
+ .sort();
46
+ if (keys.length === 0)
47
+ return name;
48
+ return `${name}{${keys.map((key) => `${key}=${JSON.stringify(attributes[key])}`).join(",")}}`;
49
+ };
50
+ /** This function gives the named values of each data point of a metric, with the attributes of the point. */
51
+ const pointValues = (metric) => {
52
+ const name = metric.descriptor.name;
53
+ switch (metric.dataPointType) {
54
+ case DataPointType.SUM:
55
+ case DataPointType.GAUGE:
56
+ return metric.dataPoints.map((point) => ({ attributes: point.attributes, values: [[name, point.value]] }));
57
+ case DataPointType.HISTOGRAM:
58
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
59
+ return metric.dataPoints.map((point) => ({
60
+ attributes: point.attributes,
61
+ values: [[`${name}.count`, point.value.count], ...(point.value.sum === undefined ? [] : [[`${name}.sum`, point.value.sum]])],
62
+ }));
63
+ }
64
+ };
65
+ /**
66
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
67
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
68
+ * their series.
69
+ */
70
+ export function metricReadings(metrics, at, options = {}) {
71
+ const time = new Date(at).toISOString();
72
+ const sum = options.attributes === "sum";
73
+ const values = new Map();
74
+ for (const scope of metrics.scopeMetrics) {
75
+ for (const metric of scope.metrics) {
76
+ for (const point of pointValues(metric)) {
77
+ for (const [name, value] of point.values) {
78
+ const series = sum ? name : seriesKey(name, point.attributes);
79
+ values.set(series, (values.get(series) ?? 0) + value);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return [...values.keys()]
85
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
86
+ .map((series) => ({ series, at: time, value: values.get(series) ?? 0 }));
87
+ }
88
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
89
+ export async function collectReadings(reader, at, options = {}) {
90
+ const result = await reader.collect();
91
+ return { readings: metricReadings(result.resourceMetrics, at, options), errors: result.errors.length };
92
+ }
93
+ //# sourceMappingURL=pull.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.js","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,YAAY,GAGb,MAAM,4BAA4B,CAAC;AAepC,+FAA+F;AAC/F,MAAM,iBAAiB,GAAgC,IAAI,GAAG,CAAC;IAC7D,cAAc,CAAC,OAAO;IACtB,cAAc,CAAC,kBAAkB;IACjC,cAAc,CAAC,SAAS;CACzB,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,MAAM,OAAO,gBAAiB,SAAQ,YAAY;IAChD,YAAY,UAAmC,EAAE;QAC/C,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,KAAK,OAAO,CAAC;QAC9C,KAAK,CAAC;YACJ,8BAA8B,EAAE,CAAC,IAAI,EAAE,EAAE,CACvC,KAAK,IAAI,iBAAiB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,sBAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,sBAAsB,CAAC,UAAU;SAC1G,CAAC,CAAC;IACL,CAAC;IAEkB,YAAY;QAC7B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAEkB,UAAU;QAC3B,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;CACF;AAwBD,yGAAyG;AACzG,MAAM,SAAS,GAAG,CAAC,IAAY,EAAE,UAA6C,EAAU,EAAE;IACxF,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC;SACjC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,SAAS,CAAC;SAC9C,IAAI,EAAE,CAAC;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AAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC7E,CAAC;AAQD,0HAA0H;AAC1H,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAoB,EAAE,EAAU,EAAE,UAAiC,EAAE;IACzG,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACtC,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;AACzG,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/otel-ts",
4
- "version": "0.8.4",
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)",
@@ -51,6 +51,14 @@
51
51
  "./lag": {
52
52
  "types": "./dist/lag.d.ts",
53
53
  "import": "./dist/lag.js"
54
+ },
55
+ "./pull": {
56
+ "types": "./dist/pull.d.ts",
57
+ "import": "./dist/pull.js"
58
+ },
59
+ "./error": {
60
+ "types": "./dist/error-record.d.ts",
61
+ "import": "./dist/error-record.js"
54
62
  }
55
63
  },
56
64
  "files": [
@@ -60,6 +68,7 @@
60
68
  ],
61
69
  "sideEffects": false,
62
70
  "dependencies": {
71
+ "@mark1russell7/text": "^0.0.18",
63
72
  "@grafana/faro-web-sdk": "^2.13.0",
64
73
  "@opentelemetry/api": "^1.10.0",
65
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
+ }
package/src/pull.ts ADDED
@@ -0,0 +1,148 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import {
11
+ AggregationTemporality,
12
+ DataPointType,
13
+ InstrumentType,
14
+ MetricReader,
15
+ type MetricData,
16
+ type ResourceMetrics,
17
+ } from "@opentelemetry/sdk-metrics";
18
+
19
+ /**
20
+ * The temporality of a pull reader. With `"cumulative"`, each collection gives the totals from the start. With
21
+ * `"delta"`, the counters and the histograms give the change after the last collection, and the up-down counters
22
+ * and the gauges stay cumulative, as with the OTLP delta preference.
23
+ */
24
+ export type PullTemporality = "cumulative" | "delta";
25
+
26
+ /** The options of a {@link PullMetricReader}. */
27
+ export interface PullMetricReaderOptions {
28
+ /** The temporality of each collection. The default is `"cumulative"`. */
29
+ readonly temporality?: PullTemporality;
30
+ }
31
+
32
+ /** The instruments that the delta preference reads as a change. The others stay cumulative. */
33
+ const DELTA_INSTRUMENTS: ReadonlySet<InstrumentType> = new Set([
34
+ InstrumentType.COUNTER,
35
+ InstrumentType.OBSERVABLE_COUNTER,
36
+ InstrumentType.HISTOGRAM,
37
+ ]);
38
+
39
+ /**
40
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
41
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
42
+ *
43
+ * ```ts no-run
44
+ * const reader = new PullMetricReader();
45
+ * const provider = new MeterProvider({ readers: [reader] });
46
+ * const { readings } = await collectReadings(reader, Date.now());
47
+ * ```
48
+ */
49
+ export class PullMetricReader extends MetricReader {
50
+ constructor(options: PullMetricReaderOptions = {}) {
51
+ const delta = options.temporality === "delta";
52
+ super({
53
+ aggregationTemporalitySelector: (type) =>
54
+ delta && DELTA_INSTRUMENTS.has(type) ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE,
55
+ });
56
+ }
57
+
58
+ protected override onForceFlush(): Promise<void> {
59
+ return Promise.resolve();
60
+ }
61
+
62
+ protected override onShutdown(): Promise<void> {
63
+ return Promise.resolve();
64
+ }
65
+ }
66
+
67
+ /** One reading of a series: its key, the UTC time of the collection and its value. */
68
+ export interface MetricReading {
69
+ /**
70
+ * The key of the series. It is the name of the metric, then its attributes in the order of their keys, for example
71
+ * `http.requests{method="GET",status=200}`. With `attributes: "sum"`, it is the name only. A histogram gives the
72
+ * series `<name>.count` and `<name>.sum`.
73
+ */
74
+ readonly series: string;
75
+ /** The UTC time of the collection, in the ISO 8601 form. */
76
+ readonly at: string;
77
+ readonly value: number;
78
+ }
79
+
80
+ /** The options of {@link metricReadings}. */
81
+ export interface MetricReadingsOptions {
82
+ /**
83
+ * The series of a metric. With `"series"` (the default), each set of attributes is a series. With `"sum"`, the
84
+ * metric is one series: the sum of its data points over all attributes.
85
+ */
86
+ readonly attributes?: "series" | "sum";
87
+ }
88
+
89
+ /** This function gives the key of a series: the name, then the attributes in the order of their keys. */
90
+ const seriesKey = (name: string, attributes: Readonly<Record<string, unknown>>): string => {
91
+ const keys = Object.keys(attributes)
92
+ .filter((key) => attributes[key] !== undefined)
93
+ .sort();
94
+ if (keys.length === 0) return name;
95
+ return `${name}{${keys.map((key) => `${key}=${JSON.stringify(attributes[key])}`).join(",")}}`;
96
+ };
97
+
98
+ /** This function gives the named values of each data point of a metric, with the attributes of the point. */
99
+ const pointValues = (metric: MetricData): { attributes: Readonly<Record<string, unknown>>; values: [string, number][] }[] => {
100
+ const name = metric.descriptor.name;
101
+ switch (metric.dataPointType) {
102
+ case DataPointType.SUM:
103
+ case DataPointType.GAUGE:
104
+ return metric.dataPoints.map((point) => ({ attributes: point.attributes, values: [[name, point.value]] }));
105
+ case DataPointType.HISTOGRAM:
106
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
107
+ return metric.dataPoints.map((point) => ({
108
+ attributes: point.attributes,
109
+ values: [[`${name}.count`, point.value.count], ...(point.value.sum === undefined ? [] : ([[`${name}.sum`, point.value.sum]] as [string, number][]))],
110
+ }));
111
+ }
112
+ };
113
+
114
+ /**
115
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
116
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
117
+ * their series.
118
+ */
119
+ export function metricReadings(metrics: ResourceMetrics, at: number, options: MetricReadingsOptions = {}): MetricReading[] {
120
+ const time = new Date(at).toISOString();
121
+ const sum = options.attributes === "sum";
122
+ const values = new Map<string, number>();
123
+ for (const scope of metrics.scopeMetrics) {
124
+ for (const metric of scope.metrics) {
125
+ for (const point of pointValues(metric)) {
126
+ for (const [name, value] of point.values) {
127
+ const series = sum ? name : seriesKey(name, point.attributes);
128
+ values.set(series, (values.get(series) ?? 0) + value);
129
+ }
130
+ }
131
+ }
132
+ }
133
+ return [...values.keys()]
134
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
135
+ .map((series) => ({ series, at: time, value: values.get(series) ?? 0 }));
136
+ }
137
+
138
+ /** The result of one collection: the readings, and the count of the errors of the callbacks. */
139
+ export interface ReadingsCollection {
140
+ readonly readings: readonly MetricReading[];
141
+ readonly errors: number;
142
+ }
143
+
144
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
145
+ export async function collectReadings(reader: MetricReader, at: number, options: MetricReadingsOptions = {}): Promise<ReadingsCollection> {
146
+ const result = await reader.collect();
147
+ return { readings: metricReadings(result.resourceMetrics, at, options), errors: result.errors.length };
148
+ }