@mark1russell7/otel-ts 0.3.0 → 0.4.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.
package/src/context.ts ADDED
@@ -0,0 +1,207 @@
1
+ /**
2
+ * The entry `@mark1russell7/otel-ts/context`: the one call that adds context
3
+ * ids, for browsers and Node.js (docs/CONTEXT-DESIGN.md, section 3).
4
+ *
5
+ * This entry depends on `@opentelemetry/api` only. It registers nothing: the
6
+ * context manager, the propagators and the processors come from `init()` or
7
+ * `startNodeTelemetry()`. Without a registered context manager, `withContext`
8
+ * still runs its function, but the values do not stay after an `await`.
9
+ *
10
+ * - The keys are data: `defineContextKeys` names each key, its cardinality and
11
+ * where it may go. A key that no call defined is refused.
12
+ * - A key with `propagate: "internal"` goes in the W3C baggage, so the
13
+ * propagator of otel-ts can send it on an internal call.
14
+ * - A key with `propagate: "none"` stays in a context entry of its own. No
15
+ * baggage propagator sees it, so it never leaves the process.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { context, createContextKey, propagation, type Context } from "@opentelemetry/api";
20
+
21
+ /** How many distinct values a key has: "low" may become a metric attribute, "high" never does */
22
+ export type ContextKeyCardinality = "low" | "high";
23
+
24
+ /** Where a key may go: "internal" on internal calls (in the baggage), "none" never out of the process */
25
+ export type ContextKeyPropagation = "internal" | "none";
26
+
27
+ /** The rules of one context key */
28
+ export interface ContextKeySpec {
29
+ readonly cardinality: ContextKeyCardinality;
30
+ readonly propagate: ContextKeyPropagation;
31
+ /** The longest value, in UTF-16 code units. Default: 256. */
32
+ readonly maxLength?: number;
33
+ }
34
+
35
+ /** The rules of one key, with each default filled in */
36
+ export interface ContextKeyRule {
37
+ readonly key: string;
38
+ readonly cardinality: ContextKeyCardinality;
39
+ readonly propagate: ContextKeyPropagation;
40
+ readonly maxLength: number;
41
+ }
42
+
43
+ /** The values of a set of keys. An `undefined` or `null` value adds nothing. */
44
+ export type ContextValues<K extends string = string> = { readonly [P in K]?: string | null | undefined };
45
+
46
+ /** The keys that one call of `defineContextKeys` defined, with typed calls */
47
+ export interface ContextKeys<K extends string> {
48
+ /** The rules of each key of this set */
49
+ readonly rules: ReadonlyMap<K, ContextKeyRule>;
50
+ /** `withContext`, with the key names of this set */
51
+ with<T>(values: ContextValues<K>, fn: () => T): T;
52
+ /** `contextValue`, with the key names of this set */
53
+ get(key: K, from?: Context): string | undefined;
54
+ }
55
+
56
+ /** The default of `maxLength` */
57
+ export const DEFAULT_MAX_LENGTH = 256;
58
+
59
+ /*
60
+ * The W3C baggage key is a token (RFC 7230): letters, digits and
61
+ * !#$%&'*+-.^_`|~. A dot is the separator of the semantic conventions.
62
+ */
63
+ const KEY_PATTERN = /^[A-Za-z0-9!#$%&'*+\-.^_`|~]+$/;
64
+
65
+ /*
66
+ * The registry is on globalThis, so two copies of this package in one program
67
+ * share their keys, as the copies of @opentelemetry/api share their globals.
68
+ */
69
+ const REGISTRY = Symbol.for("@mark1russell7/otel-ts/context-keys");
70
+ type Registry = Map<string, ContextKeyRule>;
71
+ function registry(): Registry {
72
+ const holder = globalThis as { [REGISTRY]?: Registry };
73
+ return (holder[REGISTRY] ??= new Map());
74
+ }
75
+
76
+ /** The context entry of the keys with `propagate: "none"` */
77
+ const LOCAL_VALUES = createContextKey("@mark1russell7/otel-ts/context local values");
78
+ /** The context entry of the internal mark */
79
+ const INTERNAL_CALL = createContextKey("@mark1russell7/otel-ts/context internal call");
80
+
81
+ function ruleOf(key: string, spec: ContextKeySpec): ContextKeyRule {
82
+ if (!KEY_PATTERN.test(key)) throw new TypeError(`The context key "${key}" is not a W3C baggage key: use letters, digits and . _ -`);
83
+ if (spec.cardinality !== "low" && spec.cardinality !== "high") throw new TypeError(`The context key "${key}" has no cardinality "low" or "high"`);
84
+ if (spec.propagate !== "internal" && spec.propagate !== "none") throw new TypeError(`The context key "${key}" has no propagate "internal" or "none"`);
85
+ const maxLength = spec.maxLength ?? DEFAULT_MAX_LENGTH;
86
+ if (!Number.isInteger(maxLength) || maxLength < 1) throw new TypeError(`The maxLength of the context key "${key}" is not a positive integer`);
87
+ return { key, cardinality: spec.cardinality, propagate: spec.propagate, maxLength };
88
+ }
89
+
90
+ function sameRule(a: ContextKeyRule, b: ContextKeyRule): boolean {
91
+ return a.cardinality === b.cardinality && a.propagate === b.propagate && a.maxLength === b.maxLength;
92
+ }
93
+
94
+ /**
95
+ * Define context keys, one time for each program part. A second definition of
96
+ * a key with the same rules is accepted, so a library and an app can both
97
+ * define `request.id`. A second definition with other rules is an error.
98
+ */
99
+ export function defineContextKeys<K extends string>(specs: { readonly [P in K]: ContextKeySpec }): ContextKeys<K> {
100
+ const rules = new Map<K, ContextKeyRule>();
101
+ for (const key of Object.keys(specs) as K[]) rules.set(key, ruleOf(key, specs[key]));
102
+ const known = registry();
103
+ // Check all keys first, so a refused set registers no key
104
+ for (const rule of rules.values()) {
105
+ const earlier = known.get(rule.key);
106
+ if (earlier && !sameRule(earlier, rule)) {
107
+ throw new Error(`The context key "${rule.key}" is defined already with other rules (${describe(earlier)}), not ${describe(rule)}`);
108
+ }
109
+ }
110
+ for (const rule of rules.values()) known.set(rule.key, rule);
111
+ return {
112
+ rules,
113
+ with: (values, fn) => withContext(values, fn),
114
+ get: (key, from) => contextValue(key, from),
115
+ };
116
+ }
117
+
118
+ function describe(rule: ContextKeyRule): string {
119
+ return `cardinality ${rule.cardinality}, propagate ${rule.propagate}, maxLength ${rule.maxLength}`;
120
+ }
121
+
122
+ function knownRule(key: string): ContextKeyRule {
123
+ const rule = registry().get(key);
124
+ if (!rule) throw new Error(`The context key "${key}" is not defined: call defineContextKeys first`);
125
+ return rule;
126
+ }
127
+
128
+ /** The rules of a defined key, or undefined. The processors and the propagator read them. */
129
+ export function contextKeyRule(key: string): ContextKeyRule | undefined {
130
+ return registry().get(key);
131
+ }
132
+
133
+ /** The rules of each defined key */
134
+ export function contextKeyRules(): readonly ContextKeyRule[] {
135
+ return [...registry().values()];
136
+ }
137
+
138
+ /**
139
+ * Run `fn` in a new context with these values, on top of the values of the
140
+ * active context. The async storage keeps the context through `await`,
141
+ * timers and callbacks. A key that is not defined, a value that is not a
142
+ * string and a value longer than the `maxLength` of its key are errors.
143
+ */
144
+ export function withContext<T>(values: ContextValues, fn: () => T): T {
145
+ return context.with(contextWith(values), fn);
146
+ }
147
+
148
+ /** The active context (or `from`) with these values: `withContext` without the call */
149
+ export function contextWith(values: ContextValues, from: Context = context.active()): Context {
150
+ let baggage = propagation.getBaggage(from) ?? propagation.createBaggage();
151
+ let local: Map<string, string> | undefined;
152
+ for (const [key, value] of Object.entries(values)) {
153
+ if (value === undefined || value === null) continue;
154
+ const rule = knownRule(key);
155
+ if (typeof value !== "string") throw new TypeError(`The value of the context key "${key}" is not a string`);
156
+ if (value.length > rule.maxLength) throw new RangeError(`The value of the context key "${key}" has ${value.length} characters, more than its maxLength ${rule.maxLength}`);
157
+ if (rule.propagate === "internal") {
158
+ baggage = baggage.setEntry(key, { value });
159
+ } else {
160
+ local ??= new Map(localValues(from));
161
+ local.set(key, value);
162
+ }
163
+ }
164
+ let next = propagation.setBaggage(from, baggage);
165
+ if (local) next = next.setValue(LOCAL_VALUES, local);
166
+ return next;
167
+ }
168
+
169
+ function localValues(from: Context): ReadonlyMap<string, string> {
170
+ return (from.getValue(LOCAL_VALUES) as ReadonlyMap<string, string> | undefined) ?? new Map();
171
+ }
172
+
173
+ /** The value of a defined key in the active context (or `from`), or undefined */
174
+ export function contextValue(key: string, from: Context = context.active()): string | undefined {
175
+ const rule = knownRule(key);
176
+ if (rule.propagate === "none") return localValues(from).get(key);
177
+ return propagation.getBaggage(from)?.getEntry(key)?.value;
178
+ }
179
+
180
+ /**
181
+ * The value of each defined key in the active context (or `from`). A baggage
182
+ * entry of a key that is not defined is not in the result: an entry from
183
+ * outside does not become an attribute.
184
+ */
185
+ export function contextValues(from: Context = context.active()): Readonly<Record<string, string>> {
186
+ const result: Record<string, string> = {};
187
+ const known = registry();
188
+ for (const [key, entry] of propagation.getBaggage(from)?.getAllEntries() ?? []) {
189
+ if (known.get(key)?.propagate === "internal") result[key] = entry.value;
190
+ }
191
+ for (const [key, value] of localValues(from)) result[key] = value;
192
+ return result;
193
+ }
194
+
195
+ /**
196
+ * Run `fn` with the internal mark: the propagator of otel-ts sends the baggage
197
+ * only on a call that starts in such a context. `@procedures/client` sets the
198
+ * mark around the send of each of its transports.
199
+ */
200
+ export function withInternalCall<T>(fn: () => T): T {
201
+ return context.with(context.active().setValue(INTERNAL_CALL, true), fn);
202
+ }
203
+
204
+ /** True when the active context (or `from`) has the internal mark */
205
+ export function isInternalCall(from: Context = context.active()): boolean {
206
+ return from.getValue(INTERNAL_CALL) === true;
207
+ }
@@ -0,0 +1,88 @@
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 { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, type SpanExporter, type SpanProcessor } from "@opentelemetry/sdk-trace-base";
21
+ import { createContextLogRecordProcessor, createContextSpanProcessor } from "./context-processors.js";
22
+
23
+ type Env = Readonly<Record<string, string | undefined>>;
24
+
25
+ /** A signal that has processors */
26
+ export type OtlpSignal = "traces" | "logs";
27
+ /** An exporter name of `OTEL_TRACES_EXPORTER` and `OTEL_LOGS_EXPORTER` that otel-ts makes */
28
+ export type ExporterName = "otlp" | "console";
29
+ /** An OTLP protocol that otel-ts sends */
30
+ export type OtlpProtocol = "http/protobuf" | "http/json";
31
+
32
+ /**
33
+ * The exporters of `OTEL_<SIGNAL>_EXPORTER`, a list with commas. Default:
34
+ * `otlp`. With `none` in the list: no exporter. Another name is an error.
35
+ */
36
+ export function exporterNames(signal: OtlpSignal, env: Env): ExporterName[] {
37
+ const variable = `OTEL_${signal.toUpperCase()}_EXPORTER`;
38
+ const names = [...new Set((env[variable] ?? "").split(",").map((name) => name.trim().toLowerCase()).filter(Boolean))];
39
+ if (names.length === 0) return ["otlp"];
40
+ if (names.includes("none")) return [];
41
+ for (const name of names) {
42
+ if (name !== "otlp" && name !== "console") throw new RangeError(`${variable} has "${name}": otel-ts makes "otlp", "console" or "none"`);
43
+ }
44
+ return names as ExporterName[];
45
+ }
46
+
47
+ /**
48
+ * The protocol of `OTEL_EXPORTER_OTLP_<SIGNAL>_PROTOCOL`, else of
49
+ * `OTEL_EXPORTER_OTLP_PROTOCOL`. Default: `http/protobuf`, as the SDK.
50
+ */
51
+ export function otlpProtocol(signal: OtlpSignal, env: Env): OtlpProtocol {
52
+ const variable = `OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_PROTOCOL`;
53
+ const value = (env[variable] ?? env["OTEL_EXPORTER_OTLP_PROTOCOL"] ?? "http/protobuf").trim();
54
+ if (value === "http/protobuf" || value === "http/json") return value;
55
+ 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.`);
56
+ }
57
+
58
+ /**
59
+ * The span processors: the context processor, then a processor for `exporter`,
60
+ * or for each exporter of the variables. No exporter gives no processor.
61
+ * An OTLP exporter reads its endpoint, headers and timeout from `process.env`.
62
+ */
63
+ export function nodeSpanProcessors(env: Env, exporter?: SpanExporter): SpanProcessor[] {
64
+ const exporting: SpanProcessor[] = exporter
65
+ ? [new BatchSpanProcessor(exporter)]
66
+ : exporterNames("traces", env).map((name) =>
67
+ name === "console"
68
+ ? new SimpleSpanProcessor(new ConsoleSpanExporter())
69
+ : new BatchSpanProcessor(otlpProtocol("traces", env) === "http/json" ? new JsonTraceExporter() : new ProtobufTraceExporter()),
70
+ );
71
+ return exporting.length > 0 ? [createContextSpanProcessor(), ...exporting] : [];
72
+ }
73
+
74
+ /**
75
+ * The log record processors: the context processor, then a processor for
76
+ * `exporter`, 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 nodeLogRecordProcessors(env: Env, exporter?: LogRecordExporter): LogRecordProcessor[] {
80
+ const exporting: LogRecordProcessor[] = exporter
81
+ ? [new BatchLogRecordProcessor(exporter)]
82
+ : exporterNames("logs", env).map((name) =>
83
+ name === "console"
84
+ ? new SimpleLogRecordProcessor(new ConsoleLogRecordExporter())
85
+ : new BatchLogRecordProcessor(otlpProtocol("logs", env) === "http/json" ? new JsonLogExporter() : new ProtobufLogExporter()),
86
+ );
87
+ return exporting.length > 0 ? [createContextLogRecordProcessor(), ...exporting] : [];
88
+ }
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 { contextMetricView } from "./context-processors.js";
33
+ import { nodeLogRecordProcessors, nodeSpanProcessors } from "./node-exporters.js";
34
+
35
+ export { exporterNames, 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,64 @@ 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
+ views: [contextMetricView()],
125
+ ...exports,
126
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
127
+ });
128
+ sdk.start();
129
+ } catch (error) {
130
+ release();
131
+ throw error;
132
+ }
87
133
 
88
134
  // One stop: a second call waits for the flush of the first
89
135
  let stopping: Promise<void> | undefined;
90
136
  const shutdown = (): Promise<void> =>
91
- (stopping ??= sdk.shutdown().catch(() => {
92
- // a flush that fails at the stop loses its spans, and nothing else
93
- }));
137
+ (stopping ??= sdk
138
+ .shutdown()
139
+ .catch(() => {
140
+ // a flush that fails at the stop loses its spans, and nothing else
141
+ })
142
+ .finally(() => {
143
+ // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
144
+ for (const api of [trace, metrics, logs, propagation, context]) api.disable();
145
+ release();
146
+ }));
94
147
  if (options.stopOnSignals ?? true) {
95
148
  for (const signal of STOP_SIGNALS) {
96
149
  // First in the list, so it sees each listener of the service before that listener runs
@@ -106,5 +159,5 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
106
159
  });
107
160
  }
108
161
  }
109
- return { enabled: true, esmHook, shutdown };
162
+ return { enabled, esmHook, shutdown };
110
163
  }
@@ -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
  }