@mark1russell7/otel-ts 0.3.1 → 0.5.0

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.
Files changed (43) hide show
  1. package/README.md +22 -2
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/context-processors.d.ts +48 -0
  4. package/dist/context-processors.d.ts.map +1 -0
  5. package/dist/context-processors.js +92 -0
  6. package/dist/context-processors.js.map +1 -0
  7. package/dist/context-propagator.d.ts +39 -0
  8. package/dist/context-propagator.d.ts.map +1 -0
  9. package/dist/context-propagator.js +88 -0
  10. package/dist/context-propagator.js.map +1 -0
  11. package/dist/init.d.ts.map +1 -1
  12. package/dist/init.js +13 -0
  13. package/dist/init.js.map +1 -1
  14. package/dist/logs.d.ts.map +1 -1
  15. package/dist/logs.js +2 -0
  16. package/dist/logs.js.map +1 -1
  17. package/dist/metrics.d.ts.map +1 -1
  18. package/dist/metrics.js +5 -2
  19. package/dist/metrics.js.map +1 -1
  20. package/dist/node-exporters.d.ts +40 -0
  21. package/dist/node-exporters.d.ts.map +1 -0
  22. package/dist/node-exporters.js +86 -0
  23. package/dist/node-exporters.js.map +1 -0
  24. package/dist/node.d.ts +28 -10
  25. package/dist/node.d.ts.map +1 -1
  26. package/dist/node.js +53 -12
  27. package/dist/node.js.map +1 -1
  28. package/dist/session-processors.d.ts.map +1 -1
  29. package/dist/session-processors.js +6 -19
  30. package/dist/session-processors.js.map +1 -1
  31. package/dist/tracing.d.ts.map +1 -1
  32. package/dist/tracing.js +7 -1
  33. package/dist/tracing.js.map +1 -1
  34. package/package.json +4 -1
  35. package/src/context-processors.ts +106 -0
  36. package/src/context-propagator.ts +96 -0
  37. package/src/init.ts +13 -0
  38. package/src/logs.ts +2 -0
  39. package/src/metrics.ts +5 -2
  40. package/src/node-exporters.ts +104 -0
  41. package/src/node.ts +77 -22
  42. package/src/session-processors.ts +6 -19
  43. package/src/tracing.ts +7 -1
package/dist/node.d.ts CHANGED
@@ -1,4 +1,7 @@
1
1
  import { type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
2
+ import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
3
+ import type { SpanExporter } from "@opentelemetry/sdk-trace-base";
4
+ export { exporterNames, histogramAggregation, otlpProtocol, type ExporterName, type OtlpProtocol, type OtlpSignal } from "./node-exporters.js";
2
5
  export { outgoingTraceparent, createTraceEcho, runInRemoteTrace, type RemoteTraceOptions, type TraceEcho } from "./trace-echo.js";
3
6
  /** The configuration of `startNodeTelemetry()` */
4
7
  export interface NodeTelemetryOptions {
@@ -12,11 +15,22 @@ export interface NodeTelemetryOptions {
12
15
  importMetaUrl?: string;
13
16
  /** The instrumentations, from the dependencies of the service */
14
17
  instrumentations?: NodeSDKConfiguration["instrumentations"];
15
- /** The trace exporter. Default: the exporter that the SDK makes from the `OTEL_*` variables. */
16
- traceExporter?: NodeSDKConfiguration["traceExporter"];
18
+ /**
19
+ * The trace exporter. Default: the exporters of `OTEL_TRACES_EXPORTER`
20
+ * (`otlp`, `console` or `none`; default `otlp`), with the protocol of
21
+ * `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` or `OTEL_EXPORTER_OTLP_PROTOCOL`
22
+ * (`http/protobuf` or `http/json`; default `http/protobuf`).
23
+ */
24
+ traceExporter?: SpanExporter;
25
+ /** The log record exporter. Default: the exporters of `OTEL_LOGS_EXPORTER`, with the same rules as the traces. */
26
+ logExporter?: LogRecordExporter;
17
27
  /** The metric readers. Default: none. */
18
28
  metricReaders?: NodeSDKConfiguration["metricReaders"];
19
- /** On or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a value. */
29
+ /**
30
+ * Export on or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a
31
+ * value. With export off, the context is registered all the same, so the ids
32
+ * go through the service and into its own log lines.
33
+ */
20
34
  enabled?: boolean;
21
35
  /**
22
36
  * Stop the SDK (and flush) at SIGTERM and SIGINT. Default: true. When the
@@ -25,22 +39,26 @@ export interface NodeTelemetryOptions {
25
39
  */
26
40
  stopOnSignals?: boolean;
27
41
  /**
28
- * The environment that sets `enabled` and the service name. Default:
29
- * `process.env`. The SDK reads its exporter settings (`OTEL_EXPORTER_OTLP_*`)
30
- * from `process.env`, not from this object. To send the spans to an
31
- * endpoint of this object, give `traceExporter`.
42
+ * The environment that sets `enabled`, the service name, the exporter
43
+ * names and the protocols. Default: `process.env`. An OTLP exporter and the
44
+ * sampler of the SDK read their settings (endpoint, headers,
45
+ * `OTEL_TRACES_SAMPLER`) from `process.env`, not from this object. To send
46
+ * to an endpoint of this object, give `traceExporter` and `logExporter`.
32
47
  */
33
48
  env?: NodeJS.ProcessEnv;
34
49
  }
35
50
  /** The result of `startNodeTelemetry()` */
36
51
  export interface NodeTelemetry {
37
- /** True when the SDK started */
52
+ /** True when export is on */
38
53
  readonly enabled: boolean;
39
54
  /** True when the loader hook was registered */
40
55
  readonly esmHook: boolean;
41
- /** Stop the SDK and flush the spans and metrics. It does nothing when the SDK did not start. */
56
+ /** Stop the SDK, flush the spans and metrics, and remove the registration of the context. A second call does nothing. */
42
57
  shutdown(): Promise<void>;
43
58
  }
44
- /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
59
+ /**
60
+ * Start OpenTelemetry for a Node service: the loader hook first, then the SDK.
61
+ * A second call before the `shutdown()` of the first is an error.
62
+ */
45
63
  export declare function startNodeTelemetry(options?: NodeTelemetryOptions): NodeTelemetry;
46
64
  //# sourceMappingURL=node.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAW,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE7E,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElI,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACnC,2EAA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,KAAK,kBAAkB,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElI,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACnC,2EAA2E;IAC3E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,iEAAiE;IACjE,gBAAgB,CAAC,EAAE,oBAAoB,CAAC,kBAAkB,CAAC,CAAC;IAC5D;;;;;OAKG;IACH,aAAa,CAAC,EAAE,YAAY,CAAC;IAC7B,kHAAkH;IAClH,WAAW,CAAC,EAAE,iBAAiB,CAAC;IAChC,yCAAyC;IACzC,aAAa,CAAC,EAAE,oBAAoB,CAAC,eAAe,CAAC,CAAC;IACtD;;;;OAIG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB;;;;OAIG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;;;;OAMG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB;AAKD,2CAA2C;AAC3C,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,+CAA+C;IAC/C,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAC1B,yHAAyH;IACzH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,oBAAyB,GAAG,aAAa,CAgEpF"}
package/dist/node.js CHANGED
@@ -13,35 +13,76 @@
13
13
  * of the service (the OpenTelemetry packages must have one version line), so
14
14
  * `@opentelemetry/sdk-node` is a peer dependency of this entry.
15
15
  *
16
+ * It registers the one context (docs/CONTEXT-DESIGN.md) also with export
17
+ * off: AsyncLocalStorage, the propagator of otel-ts (the trace context on each
18
+ * call, the baggage on internal calls only), and the metric view that removes
19
+ * the keys of high cardinality. With export on, the context processors add the
20
+ * context keys to each span and each log record. Only one part of a program
21
+ * registers it.
22
+ *
16
23
  * @packageDocumentation
17
24
  */
18
25
  import { register } from "node:module";
26
+ import { context, metrics, propagation, trace } from "@opentelemetry/api";
27
+ import { logs } from "@opentelemetry/api-logs";
19
28
  import { NodeSDK } from "@opentelemetry/sdk-node";
29
+ import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
30
+ import { contextMetricViews } from "./context-processors.js";
31
+ import { histogramAggregation, nodeLogRecordProcessors, nodeSpanProcessors } from "./node-exporters.js";
32
+ export { exporterNames, histogramAggregation, otlpProtocol } from "./node-exporters.js";
20
33
  export { outgoingTraceparent, createTraceEcho, runInRemoteTrace } from "./trace-echo.js";
21
34
  /** The signals that stop the SDK when `stopOnSignals` is true */
22
35
  const STOP_SIGNALS = ["SIGTERM", "SIGINT"];
23
- /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
36
+ /**
37
+ * Start OpenTelemetry for a Node service: the loader hook first, then the SDK.
38
+ * A second call before the `shutdown()` of the first is an error.
39
+ */
24
40
  export function startNodeTelemetry(options = {}) {
25
41
  const env = options.env ?? process.env;
26
42
  const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
27
- if (!enabled)
28
- return { enabled: false, esmHook: false, shutdown: async () => { } };
43
+ const release = claimContextRegistration("startNodeTelemetry()");
29
44
  let esmHook = false;
30
45
  if (options.importMetaUrl) {
31
46
  register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
32
47
  esmHook = true;
33
48
  }
34
- const sdk = new NodeSDK({
35
- serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
36
- ...(options.traceExporter ? { traceExporter: options.traceExporter } : {}),
37
- ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
38
- ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
39
- });
40
- sdk.start();
49
+ let sdk;
50
+ try {
51
+ // With export off: no processor and no reader, so nothing leaves the process
52
+ const exports = enabled
53
+ ? {
54
+ spanProcessors: nodeSpanProcessors(env, options.traceExporter),
55
+ logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
56
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
57
+ }
58
+ : { spanProcessors: [], logRecordProcessors: [], metricReaders: [] };
59
+ sdk = new NodeSDK({
60
+ serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
61
+ textMapPropagator: new ContextPropagator(),
62
+ // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
63
+ // the views replace the preference of each reader
64
+ views: contextMetricViews(histogramAggregation(env)),
65
+ ...exports,
66
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
67
+ });
68
+ sdk.start();
69
+ }
70
+ catch (error) {
71
+ release();
72
+ throw error;
73
+ }
41
74
  // One stop: a second call waits for the flush of the first
42
75
  let stopping;
43
- const shutdown = () => (stopping ??= sdk.shutdown().catch(() => {
76
+ const shutdown = () => (stopping ??= sdk
77
+ .shutdown()
78
+ .catch(() => {
44
79
  // a flush that fails at the stop loses its spans, and nothing else
80
+ })
81
+ .finally(() => {
82
+ // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
83
+ for (const api of [trace, metrics, logs, propagation, context])
84
+ api.disable();
85
+ release();
45
86
  }));
46
87
  if (options.stopOnSignals ?? true) {
47
88
  for (const signal of STOP_SIGNALS) {
@@ -59,6 +100,6 @@ export function startNodeTelemetry(options = {}) {
59
100
  });
60
101
  }
61
102
  }
62
- return { enabled: true, esmHook, shutdown };
103
+ return { enabled, esmHook, shutdown };
63
104
  }
64
105
  //# sourceMappingURL=node.js.map
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AACvC,OAAO,EAAE,OAAO,EAA6B,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IAAI,YAAY,EAAE,CAAC;YAClC,uFAAuF;YACvF,OAAO,CAAC,mBAAmB,CAAC,MAAM,EAAE,GAAG,EAAE;gBACvC,gFAAgF;gBAChF,mFAAmF;gBACnF,oFAAoF;gBACpF,iFAAiF;gBACjF,MAAM,cAAc,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBACzD,KAAK,QAAQ,EAAE,CAAC,OAAO,CAAC,GAAG,EAAE;oBAC3B,IAAI,CAAC,cAAc;wBAAE,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;gBACzD,CAAC,CAAC,CAAC;YACL,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AACxC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"session-processors.d.ts","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAGnE,yEAAyE;AACzE,MAAM,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC;AAa3C,4DAA4D;AAC5D,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE,eAAe,GAC5B,kBAAkB,CAUpB;AAED,kDAAkD;AAClD,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,eAAe,GAC5B,aAAa,CAWf"}
1
+ {"version":3,"file":"session-processors.d.ts","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAClE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAInE,yEAAyE;AACzE,MAAM,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC;AAgB3C,4DAA4D;AAC5D,wBAAgB,+BAA+B,CAC7C,YAAY,EAAE,eAAe,GAC5B,kBAAkB,CAEpB;AAED,kDAAkD;AAClD,wBAAgB,0BAA0B,CACxC,YAAY,EAAE,eAAe,GAC5B,aAAa,CAEf"}
@@ -1,4 +1,5 @@
1
1
  import { ATTR_SESSION_ID } from "./constants.js";
2
+ import { createAttributesLogRecordProcessor, createAttributesSpanProcessor } from "./context-processors.js";
2
3
  /*
3
4
  * The OpenTelemetry Browser SDK's session-processor pattern: `session.id` is
4
5
  * an attribute of each log record and span, read as the record is created,
@@ -8,30 +9,16 @@ import { ATTR_SESSION_ID } from "./constants.js";
8
9
  *
9
10
  * A `session.id` the caller set explicitly (e.g. on a `session.end` event
10
11
  * for the previous session) is kept.
12
+ *
13
+ * These are a case of the processors of the context keys
14
+ * (context-processors.ts), with the session as the source of the value.
11
15
  */
12
16
  /** Sets `session.id` on each log record as it is emitted */
13
17
  export function createSessionLogRecordProcessor(getSessionId) {
14
- return {
15
- onEmit(logRecord) {
16
- if (logRecord.attributes[ATTR_SESSION_ID] === undefined) {
17
- logRecord.setAttribute(ATTR_SESSION_ID, getSessionId());
18
- }
19
- },
20
- forceFlush: () => Promise.resolve(),
21
- shutdown: () => Promise.resolve(),
22
- };
18
+ return createAttributesLogRecordProcessor(() => ({ [ATTR_SESSION_ID]: getSessionId() }));
23
19
  }
24
20
  /** Sets `session.id` on each span as it starts */
25
21
  export function createSessionSpanProcessor(getSessionId) {
26
- return {
27
- onStart(span) {
28
- if (span.attributes[ATTR_SESSION_ID] === undefined) {
29
- span.setAttribute(ATTR_SESSION_ID, getSessionId());
30
- }
31
- },
32
- onEnd() { },
33
- forceFlush: () => Promise.resolve(),
34
- shutdown: () => Promise.resolve(),
35
- };
22
+ return createAttributesSpanProcessor(() => ({ [ATTR_SESSION_ID]: getSessionId() }));
36
23
  }
37
24
  //# sourceMappingURL=session-processors.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-processors.js","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAKjD;;;;;;;;;GASG;AAEH,4DAA4D;AAC5D,MAAM,UAAU,+BAA+B,CAC7C,YAA6B;IAE7B,OAAO;QACL,MAAM,CAAC,SAAS;YACd,IAAI,SAAS,CAAC,UAAU,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE,CAAC;gBACxD,SAAS,CAAC,YAAY,CAAC,eAAe,EAAE,YAAY,EAAE,CAAC,CAAC;YAC1D,CAAC;QACH,CAAC;QACD,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;QACnC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;KAClC,CAAC;AACJ,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,0BAA0B,CACxC,YAA6B;IAE7B,OAAO;QACL,OAAO,CAAC,IAAI;YACV,IAAI,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,KAAK,SAAS,EAAE,CAAC;gBACnD,IAAI,CAAC,YAAY,CAAC,eAAe,EAAE,YAAY,EAAE,CAAC,CAAC;YACrD,CAAC;QACH,CAAC;QACD,KAAK,KAAI,CAAC;QACV,UAAU,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;QACnC,QAAQ,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,OAAO,EAAE;KAClC,CAAC;AACJ,CAAC"}
1
+ {"version":3,"file":"session-processors.js","sourceRoot":"","sources":["../src/session-processors.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AACjD,OAAO,EAAE,kCAAkC,EAAE,6BAA6B,EAAE,MAAM,yBAAyB,CAAC;AAK5G;;;;;;;;;;;;GAYG;AAEH,4DAA4D;AAC5D,MAAM,UAAU,+BAA+B,CAC7C,YAA6B;IAE7B,OAAO,kCAAkC,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3F,CAAC;AAED,kDAAkD;AAClD,MAAM,UAAU,0BAA0B,CACxC,YAA6B;IAE7B,OAAO,6BAA6B,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,eAAe,CAAC,EAAE,YAAY,EAAE,EAAE,CAAC,CAAC,CAAC;AACtF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"tracing.d.ts","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAMzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AAEjC,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,eAAe,EAC7B,cAAc,EAAE,cAAc,GAC7B,iBAAiB,CA2CnB"}
1
+ {"version":3,"file":"tracing.d.ts","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAMzD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAIjD,OAAO,EAEL,KAAK,eAAe,EACrB,MAAM,yBAAyB,CAAC;AAEjC,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,QAAQ,EAClB,MAAM,EAAE,cAAc,EACtB,YAAY,EAAE,eAAe,EAC7B,cAAc,EAAE,cAAc,GAC7B,iBAAiB,CA+CnB"}
package/dist/tracing.js CHANGED
@@ -5,6 +5,8 @@ import { getWebAutoInstrumentations } from "@opentelemetry/auto-instrumentations
5
5
  import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-task";
6
6
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
7
7
  import { hasDom } from "./env.js";
8
+ import { createContextSpanProcessor } from "./context-processors.js";
9
+ import { ContextPropagator } from "./context-propagator.js";
8
10
  import { createSessionSpanProcessor, } from "./session-processors.js";
9
11
  export function setupTracing(resource, config, getSessionId, contextManager) {
10
12
  // Document-load and user-interaction need a DOM; skip them in Web Workers
@@ -16,10 +18,14 @@ export function setupTracing(resource, config, getSessionId, contextManager) {
16
18
  resource,
17
19
  spanProcessors: [
18
20
  createSessionSpanProcessor(getSessionId),
21
+ // The context keys (docs/CONTEXT-DESIGN.md), before the export too
22
+ createContextSpanProcessor(),
19
23
  new BatchSpanProcessor(exporter),
20
24
  ],
21
25
  });
22
- provider.register({ contextManager });
26
+ // The propagator of otel-ts: `traceparent` on each call that the
27
+ // instrumentations permit, `baggage` only on an internal call
28
+ provider.register({ contextManager, propagator: new ContextPropagator() });
23
29
  registerInstrumentations({
24
30
  instrumentations: [
25
31
  getWebAutoInstrumentations({
@@ -1 +1 @@
1
- {"version":3,"file":"tracing.js","sourceRoot":"","sources":["../src/tracing.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AAC5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAAE,uBAAuB,EAAE,MAAM,0CAA0C,CAAC;AACnF,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAE1E,OAAO,EAAE,MA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AAE;oBAC9C,OAAO,EAAE,MAAM,CAAC,sBAAsB,IAAI,GAAG;iBAC9C;gBACD,sCAAsC,EAAE;oBACtC,OAAO,EAAE,MAAM,CAAC,eAAe;oBAC/B,4BAA4B,EAAE,MAAM,CAAC,4BAA4B;iBAClE;gBACD,iDAAiD,EAAE;oBACjD,OAAO,EAAE,MAAM,CAAC,aAAa;oBAC7B,4BAA4B,EAAE,MAAM,CAAC,4BAA4B;iBAClE;gBACD,iDAAiD,EAAE;oBACjD,OAAO,EAAE,MAAM,CAAC,yBAAyB,IAAI,GAAG;iBACjD;aACF,CAAC;YACF,GAAG,CAAC,MAAM,CAAC,kBAAkB;gBAC3B,CAAC,CAAC,CAAC,IAAI,uBAAuB,EAAE,CAAC;gBACjC,CAAC,CAAC,EAAE,CAAC;SACR;KACF,CAAC,CAAC;IAEH,OAAO,QAAQ,CAAC;AAClB,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.3.1",
4
+ "version": "0.5.0",
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)",
@@ -56,8 +56,10 @@
56
56
  "@opentelemetry/context-zone": "^2.2.0",
57
57
  "@opentelemetry/core": "^2.6.0",
58
58
  "@opentelemetry/exporter-logs-otlp-http": "^0.213.0",
59
+ "@opentelemetry/exporter-logs-otlp-proto": "^0.213.0",
59
60
  "@opentelemetry/exporter-metrics-otlp-http": "^0.213.0",
60
61
  "@opentelemetry/exporter-trace-otlp-http": "^0.213.0",
62
+ "@opentelemetry/exporter-trace-otlp-proto": "^0.213.0",
61
63
  "@opentelemetry/instrumentation": "^0.213.0",
62
64
  "@opentelemetry/instrumentation-long-task": "^0.58.0",
63
65
  "@opentelemetry/resources": "^2.6.0",
@@ -81,6 +83,7 @@
81
83
  "@mark1russell7/grafana-infra": "github:mark1russell7/grafana-infra",
82
84
  "@opentelemetry/sdk-node": "~0.223.0",
83
85
  "@types/node": "^26.6.5",
86
+ "@vitest/coverage-v8": "^4.1.11",
84
87
  "happy-dom": "^21.0.4",
85
88
  "typescript": "^5.9.0",
86
89
  "vitest": "^4.1.11"
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The processors of the context keys (docs/CONTEXT-DESIGN.md, section 4).
3
+ *
4
+ * - Each span and each log record gets the value of each defined context key
5
+ * of its context, as an attribute.
6
+ * - A metric gets no attribute of a key with `cardinality: "high"`: one time
7
+ * series for each user id would fill the store.
8
+ *
9
+ * The `session.id` processors (session-processors.ts) are a case of the same
10
+ * two processors. Of the SDK packages, this file loads only sdk-metrics, which
11
+ * each entry that uses it loads already.
12
+ */
13
+ import { context, type Attributes, type Context } from "@opentelemetry/api";
14
+ import type { LogRecordProcessor } from "@opentelemetry/sdk-logs";
15
+ import {
16
+ AggregationType,
17
+ InstrumentType,
18
+ type AggregationSelector,
19
+ type IAttributesProcessor,
20
+ type ViewOptions,
21
+ } from "@opentelemetry/sdk-metrics";
22
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace-base";
23
+ import { contextKeyRule, contextValues } from "./context.js";
24
+
25
+ /** The attributes to add to a record that starts in the context `from` */
26
+ export type ContextAttributesReader = (from: Context) => Readonly<Record<string, string>>;
27
+
28
+ /** Sets the attributes of `read` on each span as it starts. An attribute that the caller set is kept. */
29
+ export function createAttributesSpanProcessor(read: ContextAttributesReader): SpanProcessor {
30
+ return {
31
+ onStart(span, parentContext) {
32
+ for (const [key, value] of Object.entries(read(parentContext))) {
33
+ if (span.attributes[key] === undefined) span.setAttribute(key, value);
34
+ }
35
+ },
36
+ onEnd() {},
37
+ forceFlush: () => Promise.resolve(),
38
+ shutdown: () => Promise.resolve(),
39
+ };
40
+ }
41
+
42
+ /** Sets the attributes of `read` on each log record as it is emitted. An attribute that the caller set is kept. */
43
+ export function createAttributesLogRecordProcessor(read: ContextAttributesReader): LogRecordProcessor {
44
+ return {
45
+ onEmit(logRecord, from) {
46
+ for (const [key, value] of Object.entries(read(from ?? context.active()))) {
47
+ if (logRecord.attributes[key] === undefined) logRecord.setAttribute(key, value);
48
+ }
49
+ },
50
+ forceFlush: () => Promise.resolve(),
51
+ shutdown: () => Promise.resolve(),
52
+ };
53
+ }
54
+
55
+ /** Sets the value of each defined context key on each span */
56
+ export function createContextSpanProcessor(): SpanProcessor {
57
+ return createAttributesSpanProcessor(contextValues);
58
+ }
59
+
60
+ /** Sets the value of each defined context key on each log record */
61
+ export function createContextLogRecordProcessor(): LogRecordProcessor {
62
+ return createAttributesLogRecordProcessor(contextValues);
63
+ }
64
+
65
+ /**
66
+ * Removes each attribute of a defined key with `cardinality: "high"` from a
67
+ * measurement. It reads the rules at each measurement, so a key defined after
68
+ * the start of the meter provider is removed too.
69
+ */
70
+ export function createContextAttributesProcessor(): IAttributesProcessor {
71
+ return {
72
+ process(incoming: Attributes): Attributes {
73
+ let result: Attributes | undefined;
74
+ for (const key of Object.keys(incoming)) {
75
+ if (contextKeyRule(key)?.cardinality !== "high") continue;
76
+ result ??= { ...incoming };
77
+ delete result[key];
78
+ }
79
+ return result ?? incoming;
80
+ },
81
+ };
82
+ }
83
+
84
+ /** The default aggregation of each instrument type, as the SDK's default reader */
85
+ export const defaultAggregation: AggregationSelector = () => ({ type: AggregationType.DEFAULT });
86
+
87
+ /**
88
+ * The views that remove the keys of high cardinality: one view for each
89
+ * instrument type, so each instrument matches one view.
90
+ *
91
+ * The aggregation of a view replaces the aggregation preference of each
92
+ * reader (sdk-metrics, `MeterSharedState`). So the views take the aggregation
93
+ * of each instrument type from `aggregation`: give the preference that the
94
+ * reader would have, for example base-2 exponential histograms.
95
+ *
96
+ * Give these as the only views of the meter provider: a second view that
97
+ * matches an instrument makes a second stream of it.
98
+ */
99
+ export function contextMetricViews(aggregation: AggregationSelector = defaultAggregation): ViewOptions[] {
100
+ const processor = createContextAttributesProcessor();
101
+ return Object.values(InstrumentType).map((instrumentType) => ({
102
+ instrumentType,
103
+ attributesProcessors: [processor],
104
+ aggregation: aggregation(instrumentType),
105
+ }));
106
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The propagator of the one context (docs/CONTEXT-DESIGN.md, section 5), and
3
+ * the guard that lets only one part of a program register the context.
4
+ *
5
+ * - The W3C trace context (`traceparent`, `tracestate`) goes on each call. It
6
+ * holds only random ids.
7
+ * - The W3C baggage goes only on a call that starts in a context with the
8
+ * internal mark (`withInternalCall` of `/context`), and only with the keys
9
+ * that `defineContextKeys` defined with `propagate: "internal"`. A value
10
+ * longer than the `maxLength` of its key is dropped, not cut.
11
+ * - On extract, the baggage keeps only those keys too, so an entry from
12
+ * outside does not travel on. The W3C limits (180 entries, 8192 bytes) are
13
+ * the limits of the W3C baggage propagator of `@opentelemetry/core`.
14
+ *
15
+ * A server that does not trust its caller removes the extracted baggage with
16
+ * `propagation.deleteBaggage(context)`, and keeps the trace context.
17
+ */
18
+ import {
19
+ propagation,
20
+ type Baggage,
21
+ type Context,
22
+ type TextMapGetter,
23
+ type TextMapPropagator,
24
+ type TextMapSetter,
25
+ } from "@opentelemetry/api";
26
+ import { W3CBaggagePropagator, W3CTraceContextPropagator } from "@opentelemetry/core";
27
+ import { contextKeyRule, isInternalCall } from "./context.js";
28
+
29
+ /** The baggage with only the defined internal keys, each value in its maxLength; undefined when no entry stays */
30
+ export function allowedBaggage(baggage: Baggage): Baggage | undefined {
31
+ let kept = baggage;
32
+ for (const [key, entry] of baggage.getAllEntries()) {
33
+ const rule = contextKeyRule(key);
34
+ if (rule?.propagate !== "internal" || entry.value.length > rule.maxLength) kept = kept.removeEntry(key);
35
+ }
36
+ return kept.getAllEntries().length > 0 ? kept : undefined;
37
+ }
38
+
39
+ /** The W3C trace context on each call, and the allowed baggage on internal calls only */
40
+ export class ContextPropagator implements TextMapPropagator {
41
+ private readonly traceContext = new W3CTraceContextPropagator();
42
+ private readonly baggage = new W3CBaggagePropagator();
43
+
44
+ inject(context: Context, carrier: unknown, setter: TextMapSetter): void {
45
+ this.traceContext.inject(context, carrier, setter);
46
+ if (!isInternalCall(context)) return;
47
+ const baggage = propagation.getBaggage(context);
48
+ const allowed = baggage && allowedBaggage(baggage);
49
+ if (allowed) this.baggage.inject(propagation.setBaggage(context, allowed), carrier, setter);
50
+ }
51
+
52
+ extract(context: Context, carrier: unknown, getter: TextMapGetter): Context {
53
+ const next = this.baggage.extract(this.traceContext.extract(context, carrier, getter), carrier, getter);
54
+ const baggage = propagation.getBaggage(next);
55
+ if (!baggage) return next;
56
+ const allowed = allowedBaggage(baggage);
57
+ return allowed ? propagation.setBaggage(next, allowed) : propagation.deleteBaggage(next);
58
+ }
59
+
60
+ fields(): string[] {
61
+ return [...this.traceContext.fields(), ...this.baggage.fields()];
62
+ }
63
+ }
64
+
65
+ /*
66
+ * The owner of the registration is on globalThis, so two copies of otel-ts in
67
+ * one program also refuse each other.
68
+ */
69
+ const OWNER = Symbol.for("@mark1russell7/otel-ts/context owner");
70
+
71
+ /**
72
+ * Take the registration of the context for `caller` (for example "init()" or
73
+ * "startNodeTelemetry()"), and give the function that gives it back. A second
74
+ * registration while the first holds is an error that names the first caller.
75
+ * The OpenTelemetry API itself keeps the first registration and only writes a
76
+ * diagnostic message.
77
+ */
78
+ export function claimContextRegistration(caller: string): () => void {
79
+ const holder = globalThis as { [OWNER]?: string };
80
+ const owner = holder[OWNER];
81
+ if (owner !== undefined) {
82
+ throw new Error(`The context is registered already by ${owner}. Only one part of a program registers it: call the shutdown() of ${owner} first.`);
83
+ }
84
+ holder[OWNER] = caller;
85
+ let released = false;
86
+ return () => {
87
+ if (released) return;
88
+ released = true;
89
+ if (holder[OWNER] === caller) delete holder[OWNER];
90
+ };
91
+ }
92
+
93
+ /** The caller that holds the registration of the context, or undefined */
94
+ export function contextRegistrationOwner(): string | undefined {
95
+ return (globalThis as { [OWNER]?: string })[OWNER];
96
+ }
package/src/init.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { context, propagation, trace } from "@opentelemetry/api";
1
2
  import { MeterProvider } from "@opentelemetry/sdk-metrics";
2
3
  import { LoggerProvider } from "@opentelemetry/sdk-logs";
3
4
  import type { FlushCause, OtelTsConfig, OtelTsInstance, ResolvedConfig } from "./types.js";
@@ -6,6 +7,7 @@ import { createSessionTracker } from "./session.js";
6
7
  import type { SessionIdReader } from "./session-processors.js";
7
8
  import { createInstanceId, randomUuid } from "./id.js";
8
9
  import { setupTracing } from "./tracing.js";
10
+ import { claimContextRegistration } from "./context-propagator.js";
9
11
  import {
10
12
  createContextManager,
11
13
  type EntryContextManagers,
@@ -86,6 +88,12 @@ export function initWith(
86
88
  ? createContextManager(resolved.contextManager, managers)
87
89
  : undefined;
88
90
 
91
+ // Tracing registers the globals of the context: only one part of a program
92
+ // does that. A second init() before the shutdown() of the first throws here.
93
+ const releaseRegistration = contextManager
94
+ ? claimContextRegistration("init()")
95
+ : undefined;
96
+
89
97
  // Read again for every log record and span, so they follow rotations
90
98
  const getSessionId = createSessionIdReader(resolved.sessionTracking);
91
99
 
@@ -145,6 +153,11 @@ export function initWith(
145
153
  shutdownPromise ??= (async () => {
146
154
  removeLifecycleHandlers();
147
155
  await Promise.allSettled(providers.map((p) => p.shutdown()));
156
+ if (releaseRegistration) {
157
+ // Remove the globals of the context, so a next init() registers its own
158
+ for (const api of [trace, propagation, context]) api.disable();
159
+ releaseRegistration();
160
+ }
148
161
  })();
149
162
  }
150
163
  return shutdownPromise;
package/src/logs.ts CHANGED
@@ -9,6 +9,7 @@ import {
9
9
  createSessionLogRecordProcessor,
10
10
  type SessionIdReader,
11
11
  } from "./session-processors.js";
12
+ import { createContextLogRecordProcessor } from "./context-processors.js";
12
13
 
13
14
  export function setupLogs(
14
15
  resource: Resource,
@@ -24,6 +25,7 @@ export function setupLogs(
24
25
  processors: [
25
26
  // Before the exporting processor, so every exported record has it
26
27
  createSessionLogRecordProcessor(getSessionId),
28
+ createContextLogRecordProcessor(),
27
29
  new BatchLogRecordProcessor(exporter),
28
30
  ],
29
31
  });
package/src/metrics.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { contextMetricViews } from "./context-processors.js";
1
2
  import type { Resource } from "@opentelemetry/resources";
2
3
  import {
3
4
  AggregationType,
@@ -26,8 +27,8 @@ const TEMPORALITY_PREFERENCES: Record<
26
27
  * instrument keeps its default aggregation. Used as the exporter's
27
28
  * aggregation preference — the SDK's equivalent of
28
29
  * OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_exponential_bucket_histogram —
29
- * rather than a View, so it stays the default that any View can override,
30
- * and there are no overlapping Views producing duplicate streams.
30
+ * The context views (contextMetricViews) replace the preference of the
31
+ * exporter, so they take the same selector.
31
32
  */
32
33
  const selectExponentialHistograms: AggregationSelector = (
33
34
  instrumentType,
@@ -53,6 +54,8 @@ export function setupMetrics(
53
54
 
54
55
  return new MeterProvider({
55
56
  resource,
57
+ // Removes each context key of high cardinality from each metric
58
+ views: contextMetricViews(options.aggregationPreference),
56
59
  readers: [
57
60
  new PeriodicExportingMetricReader({
58
61
  exporter,