@mark1russell7/otel-ts 0.10.1 → 0.10.2

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
@@ -267,6 +267,25 @@ try {
267
267
  - Each text goes through the redaction of `@mark1russell7/text/redact`. A stack stays out, unless you give `stacks: true`.
268
268
  - Without an SDK, the record has no trace id, and the log record goes to the no-op logger of the API.
269
269
 
270
+ ### The trace of a call with no SDK
271
+
272
+ The entry `@mark1russell7/otel-ts/call-trace` gives one outgoing call a trace context. It depends on `@opentelemetry/api` only, and it needs no SDK and no context manager.
273
+
274
+ ```ts
275
+ import { callTrace } from "@mark1russell7/otel-ts/call-trace";
276
+ import { reportError } from "@mark1russell7/otel-ts/error";
277
+
278
+ const call = callTrace();
279
+ const response = await fetch("/map", { headers: call.headers });
280
+ // The record has the trace id that the server got
281
+ if (!response.ok) reportError(new Error(`HTTP ${response.status}`), { from: call.context, procedure: { name: "GET /map" } });
282
+ ```
283
+
284
+ - With a valid span in the active context (or in `options.from`), the call is in the trace of that span.
285
+ - Else the call starts a new trace with random ids, in a span that does not record. The trace is sampled, so a server with a parent-based sampler records its span. Give `sampled: false` to clear the flag.
286
+ - `headers` holds only `traceparent`. The call sends no baggage.
287
+ - Give `call.context` as `from` to the record. Without a context manager, the active context does not change.
288
+
270
289
  ### The view of an error
271
290
 
272
291
  The entry `@mark1russell7/otel-ts/error-view` shows an error record. It is a custom element with no framework, so each front end can use it.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The trace context of one outgoing call, also on a page with no SDK.
3
+ *
4
+ * A page with no SDK has no active span. So a call of the page sends no `traceparent`, and the record of a failed call
5
+ * has no trace id. `callTrace()` gives the call a trace context: the active span when the SDK operates, else new
6
+ * random ids in a span that does not record. The caller sends `headers` with the request, so the server joins the same
7
+ * trace. On a failure, the caller gives `context` to `errorRecord()` or `reportError()` of `@mark1russell7/otel-ts/error`.
8
+ * The record then has the trace id that the server got.
9
+ *
10
+ * A context manager is not necessary: the caller passes `context` explicitly. This module depends on
11
+ * `@opentelemetry/api` only.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import { type Context } from "@opentelemetry/api";
16
+ /** The trace context of one outgoing call */
17
+ export interface CallTrace {
18
+ /** The context of the call: give it as `from` to `errorRecord()` or `reportError()`. */
19
+ readonly context: Context;
20
+ /** The trace id, 32 hex digits */
21
+ readonly traceId: string;
22
+ /** The span id that the server gets as its parent, 16 hex digits */
23
+ readonly spanId: string;
24
+ /** True when the trace is sampled. A server with a parent-based sampler then records its span. */
25
+ readonly sampled: boolean;
26
+ /** The W3C `traceparent` of the call, in the form of version `00` */
27
+ readonly traceparent: string;
28
+ /** The headers to add to the request: only `traceparent`. The call sends no baggage. */
29
+ readonly headers: Readonly<{
30
+ traceparent: string;
31
+ }>;
32
+ }
33
+ /** The options of `callTrace()` */
34
+ export interface CallTraceOptions {
35
+ /** The context of the call. Default: the active context. A valid span in it gives the trace of the call. */
36
+ readonly from?: Context;
37
+ /**
38
+ * The sampled flag of a new trace. Default: true, so that the server records the trace of a call that fails. It
39
+ * has no effect when `from` has a valid span: the call then keeps the flags of that span.
40
+ */
41
+ readonly sampled?: boolean;
42
+ }
43
+ /**
44
+ * The trace context of one outgoing call. With a valid span in `from` (the SDK operates), the call is in the trace of
45
+ * that span. Else the call starts a new trace with random ids, in a span that does not record. The context keys and
46
+ * the baggage of `from` stay in `context`.
47
+ *
48
+ * ```ts
49
+ * const call = callTrace();
50
+ * const response = await fetch("/map", { headers: call.headers });
51
+ * if (!response.ok) reportError(new Error(`HTTP ${response.status}`), { from: call.context });
52
+ * ```
53
+ */
54
+ export declare function callTrace(options?: CallTraceOptions): CallTrace;
55
+ //# sourceMappingURL=call-trace.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"call-trace.d.ts","sourceRoot":"","sources":["../src/call-trace.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAyD,KAAK,OAAO,EAAoB,MAAM,oBAAoB,CAAC;AAE3H,6CAA6C;AAC7C,MAAM,WAAW,SAAS;IACxB,wFAAwF;IACxF,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,kCAAkC;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,oEAAoE;IACpE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,kGAAkG;IAClG,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,qEAAqE;IACrE,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,wFAAwF;IACxF,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACrD;AAED,mCAAmC;AACnC,MAAM,WAAW,gBAAgB;IAC/B,4GAA4G;IAC5G,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC5B;AA2BD;;;;;;;;;;GAUG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,GAAG,SAAS,CAUnE"}
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The trace context of one outgoing call, also on a page with no SDK.
3
+ *
4
+ * A page with no SDK has no active span. So a call of the page sends no `traceparent`, and the record of a failed call
5
+ * has no trace id. `callTrace()` gives the call a trace context: the active span when the SDK operates, else new
6
+ * random ids in a span that does not record. The caller sends `headers` with the request, so the server joins the same
7
+ * trace. On a failure, the caller gives `context` to `errorRecord()` or `reportError()` of `@mark1russell7/otel-ts/error`.
8
+ * The record then has the trace id that the server got.
9
+ *
10
+ * A context manager is not necessary: the caller passes `context` explicitly. This module depends on
11
+ * `@opentelemetry/api` only.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import { context as api, isSpanContextValid, trace, TraceFlags } from "@opentelemetry/api";
16
+ /** `length` random bytes as hex, from the Web Crypto API of the platform, else from `Math.random` */
17
+ function randomHex(length) {
18
+ const bytes = new Uint8Array(length);
19
+ const crypto = globalThis.crypto;
20
+ if (crypto?.getRandomValues)
21
+ crypto.getRandomValues(bytes);
22
+ else
23
+ for (let i = 0; i < bytes.length; i++)
24
+ bytes[i] = Math.floor(Math.random() * 256);
25
+ // An id of only zeros is not valid (W3C trace context). The chance is 2^-64 or less, but the id must stay valid.
26
+ if (bytes.every((byte) => byte === 0))
27
+ bytes[length - 1] = 1;
28
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
29
+ }
30
+ /** The trace of a call in `context`, with the ids of `span` */
31
+ function traceOf(context, span) {
32
+ const flags = (span.traceFlags & 0xff).toString(16).padStart(2, "0");
33
+ const traceparent = `00-${span.traceId}-${span.spanId}-${flags}`;
34
+ return {
35
+ context,
36
+ traceId: span.traceId,
37
+ spanId: span.spanId,
38
+ sampled: (span.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED,
39
+ traceparent,
40
+ headers: { traceparent },
41
+ };
42
+ }
43
+ /**
44
+ * The trace context of one outgoing call. With a valid span in `from` (the SDK operates), the call is in the trace of
45
+ * that span. Else the call starts a new trace with random ids, in a span that does not record. The context keys and
46
+ * the baggage of `from` stay in `context`.
47
+ *
48
+ * ```ts
49
+ * const call = callTrace();
50
+ * const response = await fetch("/map", { headers: call.headers });
51
+ * if (!response.ok) reportError(new Error(`HTTP ${response.status}`), { from: call.context });
52
+ * ```
53
+ */
54
+ export function callTrace(options = {}) {
55
+ const from = options.from ?? api.active();
56
+ const active = trace.getSpanContext(from);
57
+ if (active !== undefined && isSpanContextValid(active))
58
+ return traceOf(from, active);
59
+ const span = {
60
+ traceId: randomHex(16),
61
+ spanId: randomHex(8),
62
+ traceFlags: (options.sampled ?? true) ? TraceFlags.SAMPLED : TraceFlags.NONE,
63
+ };
64
+ return traceOf(trace.setSpanContext(from, span), span);
65
+ }
66
+ //# sourceMappingURL=call-trace.js.map
@@ -0,0 +1 @@
1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W,GAAG,MAAM,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;IACjE,OAAO;QACL,OAAO;QACP,OAAO,EAAE,IAAI,CAAC,OAAO;QACrB,MAAM,EAAE,IAAI,CAAC,MAAM;QACnB,OAAO,EAAE,CAAC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC,OAAO,CAAC,KAAK,UAAU,CAAC,OAAO;QACtE,WAAW;QACX,OAAO,EAAE,EAAE,WAAW,EAAE;KACzB,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,SAAS,CAAC,UAA4B,EAAE;IACtD,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,GAAG,CAAC,MAAM,EAAE,CAAC;IAC1C,MAAM,MAAM,GAAG,KAAK,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;IAC1C,IAAI,MAAM,KAAK,SAAS,IAAI,kBAAkB,CAAC,MAAM,CAAC;QAAE,OAAO,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;IACrF,MAAM,IAAI,GAAgB;QACxB,OAAO,EAAE,SAAS,CAAC,EAAE,CAAC;QACtB,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;QACpB,UAAU,EAAE,CAAC,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI;KAC7E,CAAC;IACF,OAAO,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,CAAC;AACzD,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.10.1",
4
+ "version": "0.10.2",
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)",
@@ -67,6 +67,10 @@
67
67
  "./error-view": {
68
68
  "types": "./dist/error-view.d.ts",
69
69
  "import": "./dist/error-view.js"
70
+ },
71
+ "./call-trace": {
72
+ "types": "./dist/call-trace.d.ts",
73
+ "import": "./dist/call-trace.js"
70
74
  }
71
75
  },
72
76
  "files": [
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The trace context of one outgoing call, also on a page with no SDK.
3
+ *
4
+ * A page with no SDK has no active span. So a call of the page sends no `traceparent`, and the record of a failed call
5
+ * has no trace id. `callTrace()` gives the call a trace context: the active span when the SDK operates, else new
6
+ * random ids in a span that does not record. The caller sends `headers` with the request, so the server joins the same
7
+ * trace. On a failure, the caller gives `context` to `errorRecord()` or `reportError()` of `@mark1russell7/otel-ts/error`.
8
+ * The record then has the trace id that the server got.
9
+ *
10
+ * A context manager is not necessary: the caller passes `context` explicitly. This module depends on
11
+ * `@opentelemetry/api` only.
12
+ *
13
+ * @packageDocumentation
14
+ */
15
+ import { context as api, isSpanContextValid, trace, TraceFlags, type Context, type SpanContext } from "@opentelemetry/api";
16
+
17
+ /** The trace context of one outgoing call */
18
+ export interface CallTrace {
19
+ /** The context of the call: give it as `from` to `errorRecord()` or `reportError()`. */
20
+ readonly context: Context;
21
+ /** The trace id, 32 hex digits */
22
+ readonly traceId: string;
23
+ /** The span id that the server gets as its parent, 16 hex digits */
24
+ readonly spanId: string;
25
+ /** True when the trace is sampled. A server with a parent-based sampler then records its span. */
26
+ readonly sampled: boolean;
27
+ /** The W3C `traceparent` of the call, in the form of version `00` */
28
+ readonly traceparent: string;
29
+ /** The headers to add to the request: only `traceparent`. The call sends no baggage. */
30
+ readonly headers: Readonly<{ traceparent: string }>;
31
+ }
32
+
33
+ /** The options of `callTrace()` */
34
+ export interface CallTraceOptions {
35
+ /** The context of the call. Default: the active context. A valid span in it gives the trace of the call. */
36
+ readonly from?: Context;
37
+ /**
38
+ * The sampled flag of a new trace. Default: true, so that the server records the trace of a call that fails. It
39
+ * has no effect when `from` has a valid span: the call then keeps the flags of that span.
40
+ */
41
+ readonly sampled?: boolean;
42
+ }
43
+
44
+ /** `length` random bytes as hex, from the Web Crypto API of the platform, else from `Math.random` */
45
+ function randomHex(length: number): string {
46
+ const bytes = new Uint8Array(length);
47
+ const crypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } }).crypto;
48
+ if (crypto?.getRandomValues) crypto.getRandomValues(bytes);
49
+ else for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);
50
+ // An id of only zeros is not valid (W3C trace context). The chance is 2^-64 or less, but the id must stay valid.
51
+ if (bytes.every((byte) => byte === 0)) bytes[length - 1] = 1;
52
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
53
+ }
54
+
55
+ /** The trace of a call in `context`, with the ids of `span` */
56
+ function traceOf(context: Context, span: SpanContext): CallTrace {
57
+ const flags = (span.traceFlags & 0xff).toString(16).padStart(2, "0");
58
+ const traceparent = `00-${span.traceId}-${span.spanId}-${flags}`;
59
+ return {
60
+ context,
61
+ traceId: span.traceId,
62
+ spanId: span.spanId,
63
+ sampled: (span.traceFlags & TraceFlags.SAMPLED) === TraceFlags.SAMPLED,
64
+ traceparent,
65
+ headers: { traceparent },
66
+ };
67
+ }
68
+
69
+ /**
70
+ * The trace context of one outgoing call. With a valid span in `from` (the SDK operates), the call is in the trace of
71
+ * that span. Else the call starts a new trace with random ids, in a span that does not record. The context keys and
72
+ * the baggage of `from` stay in `context`.
73
+ *
74
+ * ```ts
75
+ * const call = callTrace();
76
+ * const response = await fetch("/map", { headers: call.headers });
77
+ * if (!response.ok) reportError(new Error(`HTTP ${response.status}`), { from: call.context });
78
+ * ```
79
+ */
80
+ export function callTrace(options: CallTraceOptions = {}): CallTrace {
81
+ const from = options.from ?? api.active();
82
+ const active = trace.getSpanContext(from);
83
+ if (active !== undefined && isSpanContextValid(active)) return traceOf(from, active);
84
+ const span: SpanContext = {
85
+ traceId: randomHex(16),
86
+ spanId: randomHex(8),
87
+ traceFlags: (options.sampled ?? true) ? TraceFlags.SAMPLED : TraceFlags.NONE,
88
+ };
89
+ return traceOf(trace.setSpanContext(from, span), span);
90
+ }