@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
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The span and log processors of a Node service (docs/CONTEXT-DESIGN.md, section 4).
3
+ *
4
+ * The NodeSDK makes its processors from the `OTEL_*` variables, but it has no
5
+ * public way to add a processor to them. So otel-ts makes them: the context
6
+ * processor of C3 first, then one processor for each exporter that the
7
+ * variables name. The sampler and the metric readers stay those of the SDK.
8
+ */
9
+ import { OTLPLogExporter as JsonLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
10
+ import { OTLPLogExporter as ProtobufLogExporter } from "@opentelemetry/exporter-logs-otlp-proto";
11
+ import { OTLPTraceExporter as JsonTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
12
+ import { OTLPTraceExporter as ProtobufTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
13
+ import {
14
+ BatchLogRecordProcessor,
15
+ ConsoleLogRecordExporter,
16
+ SimpleLogRecordProcessor,
17
+ type LogRecordExporter,
18
+ type LogRecordProcessor,
19
+ } from "@opentelemetry/sdk-logs";
20
+ import { AggregationType, InstrumentType, type AggregationSelector } from "@opentelemetry/sdk-metrics";
21
+ import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, type SpanExporter, type SpanProcessor } from "@opentelemetry/sdk-trace-base";
22
+ import { createContextLogRecordProcessor, createContextSpanProcessor, defaultAggregation } from "./context-processors.js";
23
+
24
+ type Env = Readonly<Record<string, string | undefined>>;
25
+
26
+ /** A signal that has processors */
27
+ export type OtlpSignal = "traces" | "logs";
28
+ /** An exporter name of `OTEL_TRACES_EXPORTER` and `OTEL_LOGS_EXPORTER` that otel-ts makes */
29
+ export type ExporterName = "otlp" | "console";
30
+ /** An OTLP protocol that otel-ts sends */
31
+ export type OtlpProtocol = "http/protobuf" | "http/json";
32
+
33
+ /**
34
+ * The exporters of `OTEL_<SIGNAL>_EXPORTER`, a list with commas. Default:
35
+ * `otlp`. With `none` in the list: no exporter. Another name is an error.
36
+ */
37
+ export function exporterNames(signal: OtlpSignal, env: Env): ExporterName[] {
38
+ const variable = `OTEL_${signal.toUpperCase()}_EXPORTER`;
39
+ const names = [...new Set((env[variable] ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean))];
40
+ if (names.length === 0) return ["otlp"];
41
+ if (names.includes("none")) return [];
42
+ for (const name of names) {
43
+ if (name !== "otlp" && name !== "console") throw new RangeError(`${variable} has "${name}": otel-ts makes "otlp", "console" or "none"`);
44
+ }
45
+ return names as ExporterName[];
46
+ }
47
+
48
+ /**
49
+ * The protocol of `OTEL_EXPORTER_OTLP_<SIGNAL>_PROTOCOL`, else of
50
+ * `OTEL_EXPORTER_OTLP_PROTOCOL`. Default: `http/protobuf`, as the SDK.
51
+ */
52
+ export function otlpProtocol(signal: OtlpSignal, env: Env): OtlpProtocol {
53
+ const variable = `OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_PROTOCOL`;
54
+ const value = (env[variable] ?? env["OTEL_EXPORTER_OTLP_PROTOCOL"] ?? "http/protobuf").trim();
55
+ if (value === "http/protobuf" || value === "http/json") return value;
56
+ throw new RangeError(`the OTLP protocol of ${signal} is "${value}": otel-ts sends "http/protobuf" or "http/json". For grpc, give the exporter in the options.`);
57
+ }
58
+
59
+ /**
60
+ * The aggregation of `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION`:
61
+ * `explicit_bucket_histogram` (default) or `base2_exponential_bucket_histogram`.
62
+ * Another value is an error.
63
+ */
64
+ export function histogramAggregation(env: Env): AggregationSelector {
65
+ const variable = "OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION";
66
+ const value = (env[variable] ?? "").trim().toLowerCase();
67
+ if (value === "" || value === "explicit_bucket_histogram") return defaultAggregation;
68
+ if (value === "base2_exponential_bucket_histogram") {
69
+ return (type) => (type === InstrumentType.HISTOGRAM ? { type: AggregationType.EXPONENTIAL_HISTOGRAM } : { type: AggregationType.DEFAULT });
70
+ }
71
+ throw new RangeError(`${variable} has "${value}": otel-ts makes "explicit_bucket_histogram" or "base2_exponential_bucket_histogram"`);
72
+ }
73
+
74
+ /**
75
+ * The span processors: the context processor, then a processor for `exporter`,
76
+ * or for each exporter of the variables. No exporter gives no processor.
77
+ * An OTLP exporter reads its endpoint, headers and timeout from `process.env`.
78
+ */
79
+ export function nodeSpanProcessors(env: Env, exporter?: SpanExporter): SpanProcessor[] {
80
+ const exporting: SpanProcessor[] = exporter
81
+ ? [new BatchSpanProcessor(exporter)]
82
+ : exporterNames("traces", env).map((name) =>
83
+ name === "console"
84
+ ? new SimpleSpanProcessor(new ConsoleSpanExporter())
85
+ : new BatchSpanProcessor(otlpProtocol("traces", env) === "http/json" ? new JsonTraceExporter() : new ProtobufTraceExporter()),
86
+ );
87
+ return exporting.length > 0 ? [createContextSpanProcessor(), ...exporting] : [];
88
+ }
89
+
90
+ /**
91
+ * The log record processors: the context processor, then a processor for
92
+ * `exporter`, or for each exporter of the variables. No exporter gives no processor.
93
+ * An OTLP exporter reads its endpoint, headers and timeout from `process.env`.
94
+ */
95
+ export function nodeLogRecordProcessors(env: Env, exporter?: LogRecordExporter): LogRecordProcessor[] {
96
+ const exporting: LogRecordProcessor[] = exporter
97
+ ? [new BatchLogRecordProcessor(exporter)]
98
+ : exporterNames("logs", env).map((name) =>
99
+ name === "console"
100
+ ? new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())
101
+ : new BatchLogRecordProcessor(otlpProtocol("logs", env) === "http/json" ? new JsonLogExporter() : new ProtobufLogExporter()),
102
+ );
103
+ return exporting.length > 0 ? [createContextLogRecordProcessor(), ...exporting] : [];
104
+ }
package/src/node.ts CHANGED
@@ -13,10 +13,26 @@
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, type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
29
+ import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
30
+ import type { SpanExporter } from "@opentelemetry/sdk-trace-base";
31
+ import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
32
+ import { contextMetricViews } from "./context-processors.js";
33
+ import { histogramAggregation, nodeLogRecordProcessors, nodeSpanProcessors } from "./node-exporters.js";
34
+
35
+ export { exporterNames, histogramAggregation, otlpProtocol, type ExporterName, type OtlpProtocol, type OtlpSignal } from "./node-exporters.js";
20
36
 
21
37
  export { outgoingTraceparent, createTraceEcho, runInRemoteTrace, type RemoteTraceOptions, type TraceEcho } from "./trace-echo.js";
22
38
 
@@ -32,11 +48,22 @@ export interface NodeTelemetryOptions {
32
48
  importMetaUrl?: string;
33
49
  /** The instrumentations, from the dependencies of the service */
34
50
  instrumentations?: NodeSDKConfiguration["instrumentations"];
35
- /** The trace exporter. Default: the exporter that the SDK makes from the `OTEL_*` variables. */
36
- traceExporter?: NodeSDKConfiguration["traceExporter"];
51
+ /**
52
+ * The trace exporter. Default: the exporters of `OTEL_TRACES_EXPORTER`
53
+ * (`otlp`, `console` or `none`; default `otlp`), with the protocol of
54
+ * `OTEL_EXPORTER_OTLP_TRACES_PROTOCOL` or `OTEL_EXPORTER_OTLP_PROTOCOL`
55
+ * (`http/protobuf` or `http/json`; default `http/protobuf`).
56
+ */
57
+ traceExporter?: SpanExporter;
58
+ /** The log record exporter. Default: the exporters of `OTEL_LOGS_EXPORTER`, with the same rules as the traces. */
59
+ logExporter?: LogRecordExporter;
37
60
  /** The metric readers. Default: none. */
38
61
  metricReaders?: NodeSDKConfiguration["metricReaders"];
39
- /** On or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a value. */
62
+ /**
63
+ * Export on or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a
64
+ * value. With export off, the context is registered all the same, so the ids
65
+ * go through the service and into its own log lines.
66
+ */
40
67
  enabled?: boolean;
41
68
  /**
42
69
  * Stop the SDK (and flush) at SIGTERM and SIGINT. Default: true. When the
@@ -45,10 +72,11 @@ export interface NodeTelemetryOptions {
45
72
  */
46
73
  stopOnSignals?: boolean;
47
74
  /**
48
- * The environment that sets `enabled` and the service name. Default:
49
- * `process.env`. The SDK reads its exporter settings (`OTEL_EXPORTER_OTLP_*`)
50
- * from `process.env`, not from this object. To send the spans to an
51
- * endpoint of this object, give `traceExporter`.
75
+ * The environment that sets `enabled`, the service name, the exporter
76
+ * names and the protocols. Default: `process.env`. An OTLP exporter and the
77
+ * sampler of the SDK read their settings (endpoint, headers,
78
+ * `OTEL_TRACES_SAMPLER`) from `process.env`, not from this object. To send
79
+ * to an endpoint of this object, give `traceExporter` and `logExporter`.
52
80
  */
53
81
  env?: NodeJS.ProcessEnv;
54
82
  }
@@ -58,39 +86,66 @@ const STOP_SIGNALS = ["SIGTERM", "SIGINT"] as const;
58
86
 
59
87
  /** The result of `startNodeTelemetry()` */
60
88
  export interface NodeTelemetry {
61
- /** True when the SDK started */
89
+ /** True when export is on */
62
90
  readonly enabled: boolean;
63
91
  /** True when the loader hook was registered */
64
92
  readonly esmHook: boolean;
65
- /** Stop the SDK and flush the spans and metrics. It does nothing when the SDK did not start. */
93
+ /** Stop the SDK, flush the spans and metrics, and remove the registration of the context. A second call does nothing. */
66
94
  shutdown(): Promise<void>;
67
95
  }
68
96
 
69
- /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
97
+ /**
98
+ * Start OpenTelemetry for a Node service: the loader hook first, then the SDK.
99
+ * A second call before the `shutdown()` of the first is an error.
100
+ */
70
101
  export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTelemetry {
71
102
  const env = options.env ?? process.env;
72
103
  const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
73
- if (!enabled) return { enabled: false, esmHook: false, shutdown: async () => {} };
104
+ const release = claimContextRegistration("startNodeTelemetry()");
74
105
 
75
106
  let esmHook = false;
76
107
  if (options.importMetaUrl) {
77
108
  register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
78
109
  esmHook = true;
79
110
  }
80
- const sdk = new NodeSDK({
81
- serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
82
- ...(options.traceExporter ? { traceExporter: options.traceExporter } : {}),
83
- ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
84
- ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
85
- });
86
- sdk.start();
111
+ let sdk: NodeSDK;
112
+ try {
113
+ // With export off: no processor and no reader, so nothing leaves the process
114
+ const exports: Partial<NodeSDKConfiguration> = enabled
115
+ ? {
116
+ spanProcessors: nodeSpanProcessors(env, options.traceExporter),
117
+ logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
118
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
119
+ }
120
+ : { spanProcessors: [], logRecordProcessors: [], metricReaders: [] };
121
+ sdk = new NodeSDK({
122
+ serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
123
+ textMapPropagator: new ContextPropagator(),
124
+ // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
125
+ // the views replace the preference of each reader
126
+ views: contextMetricViews(histogramAggregation(env)),
127
+ ...exports,
128
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
129
+ });
130
+ sdk.start();
131
+ } catch (error) {
132
+ release();
133
+ throw error;
134
+ }
87
135
 
88
136
  // One stop: a second call waits for the flush of the first
89
137
  let stopping: Promise<void> | undefined;
90
138
  const shutdown = (): Promise<void> =>
91
- (stopping ??= sdk.shutdown().catch(() => {
92
- // a flush that fails at the stop loses its spans, and nothing else
93
- }));
139
+ (stopping ??= sdk
140
+ .shutdown()
141
+ .catch(() => {
142
+ // a flush that fails at the stop loses its spans, and nothing else
143
+ })
144
+ .finally(() => {
145
+ // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
146
+ for (const api of [trace, metrics, logs, propagation, context]) api.disable();
147
+ release();
148
+ }));
94
149
  if (options.stopOnSignals ?? true) {
95
150
  for (const signal of STOP_SIGNALS) {
96
151
  // First in the list, so it sees each listener of the service before that listener runs
@@ -106,5 +161,5 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
106
161
  });
107
162
  }
108
163
  }
109
- return { enabled: true, esmHook, shutdown };
164
+ return { enabled, esmHook, shutdown };
110
165
  }
@@ -1,6 +1,7 @@
1
1
  import type { LogRecordProcessor } from "@opentelemetry/sdk-logs";
2
2
  import type { SpanProcessor } from "@opentelemetry/sdk-trace-base";
3
3
  import { ATTR_SESSION_ID } from "./constants.js";
4
+ import { createAttributesLogRecordProcessor, createAttributesSpanProcessor } from "./context-processors.js";
4
5
 
5
6
  /** Returns the current session ID; called once per log record or span */
6
7
  export type SessionIdReader = () => string;
@@ -14,35 +15,21 @@ export type SessionIdReader = () => string;
14
15
  *
15
16
  * A `session.id` the caller set explicitly (e.g. on a `session.end` event
16
17
  * for the previous session) is kept.
18
+ *
19
+ * These are a case of the processors of the context keys
20
+ * (context-processors.ts), with the session as the source of the value.
17
21
  */
18
22
 
19
23
  /** Sets `session.id` on each log record as it is emitted */
20
24
  export function createSessionLogRecordProcessor(
21
25
  getSessionId: SessionIdReader,
22
26
  ): LogRecordProcessor {
23
- return {
24
- onEmit(logRecord) {
25
- if (logRecord.attributes[ATTR_SESSION_ID] === undefined) {
26
- logRecord.setAttribute(ATTR_SESSION_ID, getSessionId());
27
- }
28
- },
29
- forceFlush: () => Promise.resolve(),
30
- shutdown: () => Promise.resolve(),
31
- };
27
+ return createAttributesLogRecordProcessor(() => ({ [ATTR_SESSION_ID]: getSessionId() }));
32
28
  }
33
29
 
34
30
  /** Sets `session.id` on each span as it starts */
35
31
  export function createSessionSpanProcessor(
36
32
  getSessionId: SessionIdReader,
37
33
  ): SpanProcessor {
38
- return {
39
- onStart(span) {
40
- if (span.attributes[ATTR_SESSION_ID] === undefined) {
41
- span.setAttribute(ATTR_SESSION_ID, getSessionId());
42
- }
43
- },
44
- onEnd() {},
45
- forceFlush: () => Promise.resolve(),
46
- shutdown: () => Promise.resolve(),
47
- };
34
+ return createAttributesSpanProcessor(() => ({ [ATTR_SESSION_ID]: getSessionId() }));
48
35
  }
package/src/tracing.ts CHANGED
@@ -8,6 +8,8 @@ import { LongTaskInstrumentation } from "@opentelemetry/instrumentation-long-tas
8
8
  import { registerInstrumentations } from "@opentelemetry/instrumentation";
9
9
  import type { ResolvedConfig } from "./types.js";
10
10
  import { hasDom } from "./env.js";
11
+ import { createContextSpanProcessor } from "./context-processors.js";
12
+ import { ContextPropagator } from "./context-propagator.js";
11
13
  import {
12
14
  createSessionSpanProcessor,
13
15
  type SessionIdReader,
@@ -30,11 +32,15 @@ export function setupTracing(
30
32
  resource,
31
33
  spanProcessors: [
32
34
  createSessionSpanProcessor(getSessionId),
35
+ // The context keys (docs/CONTEXT-DESIGN.md), before the export too
36
+ createContextSpanProcessor(),
33
37
  new BatchSpanProcessor(exporter),
34
38
  ],
35
39
  });
36
40
 
37
- provider.register({ contextManager });
41
+ // The propagator of otel-ts: `traceparent` on each call that the
42
+ // instrumentations permit, `baggage` only on an internal call
43
+ provider.register({ contextManager, propagator: new ContextPropagator() });
38
44
 
39
45
  registerInstrumentations({
40
46
  instrumentations: [