@mark1russell7/otel-ts 0.8.2 → 0.8.4

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
@@ -445,6 +445,26 @@ By default, it stops the SDK and sends the last spans at `SIGTERM` and `SIGINT`.
445
445
 
446
446
  The option `resourceAttributes` gives the attributes of the resource of the service, for example `service.version` and `service.instance.id` (the copy of the service). They win over the detected attributes and over `OTEL_RESOURCE_ATTRIBUTES`. `service.name` comes from `serviceName`. The detectors are those of the SDK, from `OTEL_NODE_RESOURCE_DETECTORS`.
447
447
 
448
+ ### A service that exports nothing
449
+
450
+ The entry `/node` loads the SDK of `@opentelemetry/sdk-node` and each exporter, also with export off. In a small service, that is a large part of its memory. The entry `@mark1russell7/otel-ts/node/context` registers the same context with no SDK of `sdk-node`, no exporter and no instrumentation:
451
+
452
+ ```ts
453
+ import { startNodeContext } from "@mark1russell7/otel-ts/node/context";
454
+
455
+ export const telemetry = startNodeContext({
456
+ serviceName: "my-service",
457
+ resourceAttributes: { "service.version": "1.2.3", "service.instance.id": "copy-1" },
458
+ });
459
+ ```
460
+
461
+ - Each span gets a trace id, and a value of `withContext()` stays after `await`.
462
+ - The propagator is the propagator of `/node`: `traceparent` on each call, the context keys in `baggage` only on an internal call.
463
+ - No span leaves the process. A test gives `spanProcessors` with the exporter of its capture.
464
+ - It adds no listener for a signal. Call `telemetry.shutdown()` in the last stage of the service.
465
+
466
+ `startNodeContext()` and `startNodeTelemetry()` refuse each other: only one part of a program registers the context. To export, import `startNodeTelemetry()` from `/node` in its place.
467
+
448
468
  ### A service of `@mark1russell7/service`
449
469
 
450
470
  A service of [`@mark1russell7/service`](https://github.com/mark1russell7/systems/tree/main/packages/service) has a staged shutdown of its own: after the signal, it drains its requests. The stop of telemetry must come after the drain. With `stopOnSignals: true`, the stop removes the context at the signal: the log lines of the drain lose their trace ids, and the spans of the drained requests go. So:
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The entry `@mark1russell7/otel-ts/node/context`: the context of a Node service that exports nothing, with no
3
+ * SDK of `@opentelemetry/sdk-node`.
4
+ *
5
+ * It registers the one context (docs/CONTEXT-DESIGN.md) as the entry `/node` does with export off:
6
+ * AsyncLocalStorage, the propagator of otel-ts (the trace context on each call, the baggage on internal calls
7
+ * only), and a tracer provider with the resource of the service. Each span gets a trace id, so the ids go
8
+ * through the service and into its own log lines.
9
+ *
10
+ * The entry `/node` loads `@opentelemetry/sdk-node` and each exporter also with export off. This entry loads
11
+ * none of them, and no instrumentation. Thus a small service pays only for the context. A service that exports
12
+ * imports `/node`.
13
+ *
14
+ * Only one part of a program registers the context: `startNodeContext()` and `startNodeTelemetry()` refuse each
15
+ * other until the `shutdown()` of the first.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import type { Attributes } from "@opentelemetry/api";
20
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace";
21
+ /** The configuration of `startNodeContext()` */
22
+ export interface NodeContextOptions {
23
+ /** The service name. Default: `OTEL_SERVICE_NAME`, else "node-service". */
24
+ serviceName?: string;
25
+ /**
26
+ * The attributes of the resource of the service, for example `service.version` and `service.instance.id`
27
+ * (the copy of the service). They win over the detected attributes and over `OTEL_RESOURCE_ATTRIBUTES`.
28
+ */
29
+ resourceAttributes?: Attributes;
30
+ /**
31
+ * The span processors. Default: none, and no span leaves the process. A test gives a processor with the
32
+ * exporter of its capture.
33
+ */
34
+ spanProcessors?: readonly SpanProcessor[];
35
+ /** The environment of the service name and of `OTEL_NODE_RESOURCE_DETECTORS`. Default: `process.env`. */
36
+ env?: NodeJS.ProcessEnv;
37
+ }
38
+ /** The result of `startNodeContext()` */
39
+ export interface NodeContext {
40
+ /**
41
+ * Flush the span processors, stop the tracer provider, and remove the registration of the context. A second
42
+ * call does nothing. A service of `@mark1russell7/service` calls it in its last stage, `flush the output`.
43
+ */
44
+ shutdown(): Promise<void>;
45
+ }
46
+ /**
47
+ * Register the context of a Node service that exports nothing. A second call before the `shutdown()` of the
48
+ * first is an error. It adds no listener for a signal: the service calls `shutdown()` at its stop.
49
+ */
50
+ export declare function startNodeContext(options?: NodeContextOptions): NodeContext;
51
+ //# sourceMappingURL=node-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-context.d.ts","sourceRoot":"","sources":["../src/node-context.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAG9D,gDAAgD;AAChD,MAAM,WAAW,kBAAkB;IACjC,2EAA2E;IAC3E,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;OAGG;IACH,kBAAkB,CAAC,EAAE,UAAU,CAAC;IAChC;;;OAGG;IACH,cAAc,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;IAC1C,yGAAyG;IACzG,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;CACzB;AAED,yCAAyC;AACzC,MAAM,WAAW,WAAW;IAC1B;;;OAGG;IACH,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CAC3B;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,kBAAuB,GAAG,WAAW,CAG9E"}
@@ -0,0 +1,10 @@
1
+ import { registerNodeContext } from "./node-registration.js";
2
+ /**
3
+ * Register the context of a Node service that exports nothing. A second call before the `shutdown()` of the
4
+ * first is an error. It adds no listener for a signal: the service calls `shutdown()` at its stop.
5
+ */
6
+ export function startNodeContext(options = {}) {
7
+ const registration = registerNodeContext("startNodeContext()", options);
8
+ return { shutdown: () => registration.stop() };
9
+ }
10
+ //# sourceMappingURL=node-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-context.js","sourceRoot":"","sources":["../src/node-context.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AA6B7D;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,UAA8B,EAAE;IAC/D,MAAM,YAAY,GAAG,mBAAmB,CAAC,oBAAoB,EAAE,OAAO,CAAC,CAAC;IACxE,OAAO,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,EAAE,CAAC;AACjD,CAAC"}
@@ -1,6 +1,4 @@
1
1
  import { type LogRecordExporter, type LogRecordProcessor } from "@opentelemetry/sdk-logs";
2
- import type { Attributes } from "@opentelemetry/api";
3
- import { type ResourceDetector } from "@opentelemetry/resources";
4
2
  import { type AggregationSelector } from "@opentelemetry/sdk-metrics";
5
3
  import { type SpanExporter, type SpanProcessor } from "@opentelemetry/sdk-trace";
6
4
  type Env = Readonly<Record<string, string | undefined>>;
@@ -26,15 +24,6 @@ export declare function otlpProtocol(signal: OtlpSignal, env: Env): OtlpProtocol
26
24
  * Another value is an error.
27
25
  */
28
26
  export declare function histogramAggregation(env: Env): AggregationSelector;
29
- /**
30
- * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
31
- * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
32
- * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
33
- * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
34
- * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
35
- * ignores a name that it does not know, with a warning. This function ignores it too.
36
- */
37
- export declare function nodeResourceDetectors(env: Env, attributes: Attributes): ResourceDetector[];
38
27
  /**
39
28
  * The span processors: the context processor, then a processor for `exporter`,
40
29
  * or for each exporter of the variables. No exporter gives no processor.
@@ -1 +1 @@
1
- {"version":3,"file":"node-exporters.d.ts","sourceRoot":"","sources":["../src/node-exporters.ts"],"names":[],"mappings":"AAYA,OAAO,EAIL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,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"}
1
+ {"version":3,"file":"node-exporters.d.ts","sourceRoot":"","sources":["../src/node-exporters.ts"],"names":[],"mappings":"AAYA,OAAO,EAIL,KAAK,iBAAiB,EACtB,KAAK,kBAAkB,EACxB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAmC,KAAK,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACvG,OAAO,EAAgE,KAAK,YAAY,EAAE,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAG/I,KAAK,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AAExD,mCAAmC;AACnC,MAAM,MAAM,UAAU,GAAG,QAAQ,GAAG,MAAM,CAAC;AAC3C,6FAA6F;AAC7F,MAAM,MAAM,YAAY,GAAG,MAAM,GAAG,SAAS,CAAC;AAC9C,0CAA0C;AAC1C,MAAM,MAAM,YAAY,GAAG,eAAe,GAAG,WAAW,CAAC;AAEzD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,GAAG,GAAG,YAAY,EAAE,CAS1E;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,MAAM,EAAE,UAAU,EAAE,GAAG,EAAE,GAAG,GAAG,YAAY,CAOvE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,GAAG,GAAG,mBAAmB,CAQlE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,EAAE,YAAY,GAAG,aAAa,EAAE,CASrF;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,CAAC,EAAE,iBAAiB,GAAG,kBAAkB,EAAE,CASpG"}
@@ -11,7 +11,6 @@ import { OTLPLogExporter as ProtobufLogExporter } from "@opentelemetry/exporter-
11
11
  import { OTLPTraceExporter as JsonTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
12
12
  import { OTLPTraceExporter as ProtobufTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
13
13
  import { BatchLogRecordProcessor, ConsoleLogRecordExporter, SimpleLogRecordProcessor, } from "@opentelemetry/sdk-logs";
14
- import { envDetector, hostDetector, osDetector, processDetector, serviceInstanceIdDetector } from "@opentelemetry/resources";
15
14
  import { AggregationType, InstrumentType } from "@opentelemetry/sdk-metrics";
16
15
  import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor } from "@opentelemetry/sdk-trace";
17
16
  import { createContextLogRecordProcessor, createContextSpanProcessor, defaultAggregation } from "./context-processors.js";
@@ -60,30 +59,6 @@ export function histogramAggregation(env) {
60
59
  }
61
60
  throw new RangeError(`${variable} has "${value}": otel-ts makes "explicit_bucket_histogram" or "base2_exponential_bucket_histogram"`);
62
61
  }
63
- /** The resource detectors of `OTEL_NODE_RESOURCE_DETECTORS`, with the names and the sequence of the NodeSDK. `env` is last. */
64
- const RESOURCE_DETECTORS = new Map([
65
- ["host", hostDetector],
66
- ["os", osDetector],
67
- ["serviceinstance", serviceInstanceIdDetector],
68
- ["process", processDetector],
69
- ["env", envDetector],
70
- ]);
71
- /**
72
- * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
73
- * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
74
- * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
75
- * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
76
- * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
77
- * ignores a name that it does not know, with a warning. This function ignores it too.
78
- */
79
- export function nodeResourceDetectors(env, attributes) {
80
- const names = (env["OTEL_NODE_RESOURCE_DETECTORS"] ?? "")
81
- .split(",")
82
- .map((name) => name.trim())
83
- .filter((name) => name !== "");
84
- const chosen = names.length === 0 || names.includes("all") ? [...RESOURCE_DETECTORS.values()] : names.includes("none") ? [] : names.flatMap((name) => RESOURCE_DETECTORS.get(name) ?? []);
85
- return [...chosen, { detect: () => ({ attributes: { ...attributes } }) }];
86
- }
87
62
  /**
88
63
  * The span processors: the context processor, then a processor for `exporter`,
89
64
  * or for each exporter of the variables. No exporter gives no processor.
@@ -1 +1 @@
1
- {"version":3,"file":"node-exporters.js","sourceRoot":"","sources":["../src/node-exporters.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,eAAe,IAAI,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAC5F,OAAO,EAAE,eAAe,IAAI,mBAAmB,EAAE,MAAM,yCAAyC,CAAC;AACjG,OAAO,EAAE,iBAAiB,IAAI,iBAAiB,EAAE,MAAM,yCAAyC,CAAC;AACjG,OAAO,EAAE,iBAAiB,IAAI,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AACtG,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,wBAAwB,GAGzB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,eAAe,EAAE,yBAAyB,EAAyB,MAAM,0BAA0B,CAAC;AACpJ,OAAO,EAAE,eAAe,EAAE,cAAc,EAA4B,MAAM,4BAA4B,CAAC;AACvG,OAAO,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,mBAAmB,EAAyC,MAAM,0BAA0B,CAAC;AAC/I,OAAO,EAAE,+BAA+B,EAAE,0BAA0B,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAW1H;;;GAGG;AACH,MAAM,UAAU,aAAa,CAAC,MAAkB,EAAE,GAAQ;IACxD,MAAM,QAAQ,GAAG,QAAQ,MAAM,CAAC,WAAW,EAAE,WAAW,CAAC;IACzD,MAAM,KAAK,GAAG,CAAC,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC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CAAC,IAAI,kBAAkB,CAAC,EAAE,QAAQ,EAAE,YAAY,CAAC,QAAQ,EAAE,GAAG,CAAC,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,iBAAiB,EAAE,CAAC,CAAC,CAAC,IAAI,qBAAqB,EAAE,EAAE,CAAC,CAC9I,CAAC;IACN,OAAO,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,0BAA0B,EAAE,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAClF,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAAC,GAAQ,EAAE,QAA4B;IAC5E,MAAM,SAAS,GAAyB,QAAQ;QAC9C,CAAC,CAAC,CAAC,IAAI,uBAAuB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC7C,CAAC,CAAC,aAAa,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACtC,IAAI,KAAK,SAAS;YAChB,CAAC,CAAC,IAAI,wBAAwB,CAAC,EAAE,QAAQ,EAAE,IAAI,wBAAwB,EAAE,EAAE,CAAC;YAC5E,CAAC,CAAC,IAAI,uBAAuB,CAAC,EAAE,QAAQ,EAAE,YAAY,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,WAAW,CAAC,CAAC,CAAC,IAAI,eAAe,EAAE,CAAC,CAAC,CAAC,IAAI,mBAAmB,EAAE,EAAE,CAAC,CAC7I,CAAC;IACN,OAAO,SAAS,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,+BAA+B,EAAE,EAAE,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AACvF,CAAC"}
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The registration of the context of a Node service with no SDK of `@opentelemetry/sdk-node`
3
+ * (docs/CONTEXT-DESIGN.md, section 4). The entry `/node/context` and the export off of the entry `/node`
4
+ * use it. Thus the two paths register the same context.
5
+ *
6
+ * This module imports no exporter, no instrumentation and no SDK of `@opentelemetry/sdk-node`.
7
+ * The entries test holds this rule.
8
+ */
9
+ import { type Attributes } from "@opentelemetry/api";
10
+ import { type ResourceDetector } from "@opentelemetry/resources";
11
+ import { type SpanProcessor } from "@opentelemetry/sdk-trace";
12
+ type Env = Readonly<Record<string, string | undefined>>;
13
+ /**
14
+ * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
15
+ * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
16
+ * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
17
+ * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
18
+ * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
19
+ * ignores a name that it does not know, with a warning. This function ignores it too.
20
+ */
21
+ export declare function nodeResourceDetectors(env: Env, attributes: Attributes): ResourceDetector[];
22
+ /** The service name of a start: the option, else `OTEL_SERVICE_NAME`, else "node-service" */
23
+ export declare function nodeServiceName(serviceName: string | undefined, env: Env): string;
24
+ /** The configuration of the registration of the context */
25
+ export interface NodeContextRegistrationOptions {
26
+ readonly serviceName?: string | undefined;
27
+ readonly resourceAttributes?: Attributes | undefined;
28
+ readonly spanProcessors?: readonly SpanProcessor[] | undefined;
29
+ readonly env?: Env | undefined;
30
+ }
31
+ /** A registration of the context */
32
+ export interface NodeContextRegistration {
33
+ /** Stop the tracer provider, flush its processors, and remove the registration. A second call gives the same promise. */
34
+ stop(): Promise<void>;
35
+ }
36
+ /**
37
+ * Register the context for `caller`: the claim, AsyncLocalStorage as the context manager, the propagator of
38
+ * otel-ts, and a tracer provider with the resource of the service. A tracer provider of the SDK gives each span
39
+ * a trace id, also with no span processor.
40
+ *
41
+ * `prepare` runs after the claim and before the context. When it throws, the claim goes back.
42
+ */
43
+ export declare function registerNodeContext(caller: string, options: NodeContextRegistrationOptions, prepare?: () => void): NodeContextRegistration;
44
+ export {};
45
+ //# sourceMappingURL=node-registration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-registration.d.ts","sourceRoot":"","sources":["../src/node-registration.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAA+B,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAElF,OAAO,EASL,KAAK,gBAAgB,EACtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAI9E,KAAK,GAAG,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;AAWxD;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,GAAG,EAAE,UAAU,EAAE,UAAU,GAAG,gBAAgB,EAAE,CAO1F;AAED,6FAA6F;AAC7F,wBAAgB,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,GAAG,EAAE,GAAG,GAAG,MAAM,CAEjF;AAED,2DAA2D;AAC3D,MAAM,WAAW,8BAA8B;IAC7C,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAC1C,QAAQ,CAAC,kBAAkB,CAAC,EAAE,UAAU,GAAG,SAAS,CAAC;IACrD,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,aAAa,EAAE,GAAG,SAAS,CAAC;IAC/D,QAAQ,CAAC,GAAG,CAAC,EAAE,GAAG,GAAG,SAAS,CAAC;CAChC;AAED,oCAAoC;AACpC,MAAM,WAAW,uBAAuB;IACtC,yHAAyH;IACzH,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,8BAA8B,EAAE,OAAO,CAAC,EAAE,MAAM,IAAI,GAAG,uBAAuB,CAoC1I"}
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The registration of the context of a Node service with no SDK of `@opentelemetry/sdk-node`
3
+ * (docs/CONTEXT-DESIGN.md, section 4). The entry `/node/context` and the export off of the entry `/node`
4
+ * use it. Thus the two paths register the same context.
5
+ *
6
+ * This module imports no exporter, no instrumentation and no SDK of `@opentelemetry/sdk-node`.
7
+ * The entries test holds this rule.
8
+ */
9
+ import { context, propagation, trace } from "@opentelemetry/api";
10
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
11
+ import { defaultResource, detectResources, envDetector, hostDetector, osDetector, processDetector, resourceFromAttributes, serviceInstanceIdDetector, } from "@opentelemetry/resources";
12
+ import { TracerProvider } from "@opentelemetry/sdk-trace";
13
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
14
+ import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
15
+ /** The resource detectors of `OTEL_NODE_RESOURCE_DETECTORS`, with the names and the sequence of the NodeSDK. `env` is last. */
16
+ const RESOURCE_DETECTORS = new Map([
17
+ ["host", hostDetector],
18
+ ["os", osDetector],
19
+ ["serviceinstance", serviceInstanceIdDetector],
20
+ ["process", processDetector],
21
+ ["env", envDetector],
22
+ ]);
23
+ /**
24
+ * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
25
+ * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
26
+ * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
27
+ * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
28
+ * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
29
+ * ignores a name that it does not know, with a warning. This function ignores it too.
30
+ */
31
+ export function nodeResourceDetectors(env, attributes) {
32
+ const names = (env["OTEL_NODE_RESOURCE_DETECTORS"] ?? "")
33
+ .split(",")
34
+ .map((name) => name.trim())
35
+ .filter((name) => name !== "");
36
+ const chosen = names.length === 0 || names.includes("all") ? [...RESOURCE_DETECTORS.values()] : names.includes("none") ? [] : names.flatMap((name) => RESOURCE_DETECTORS.get(name) ?? []);
37
+ return [...chosen, { detect: () => ({ attributes: { ...attributes } }) }];
38
+ }
39
+ /** The service name of a start: the option, else `OTEL_SERVICE_NAME`, else "node-service" */
40
+ export function nodeServiceName(serviceName, env) {
41
+ return serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service";
42
+ }
43
+ /**
44
+ * Register the context for `caller`: the claim, AsyncLocalStorage as the context manager, the propagator of
45
+ * otel-ts, and a tracer provider with the resource of the service. A tracer provider of the SDK gives each span
46
+ * a trace id, also with no span processor.
47
+ *
48
+ * `prepare` runs after the claim and before the context. When it throws, the claim goes back.
49
+ */
50
+ export function registerNodeContext(caller, options, prepare) {
51
+ const release = claimContextRegistration(caller);
52
+ let tracerProvider;
53
+ try {
54
+ prepare?.();
55
+ const env = options.env ?? process.env;
56
+ // The sequence of the NodeSDK: the default resource, then the detectors, then the service name
57
+ const resource = defaultResource()
58
+ .merge(detectResources({ detectors: nodeResourceDetectors(env, options.resourceAttributes ?? {}) }))
59
+ .merge(resourceFromAttributes({ [ATTR_SERVICE_NAME]: nodeServiceName(options.serviceName, env) }));
60
+ tracerProvider = new TracerProvider({ resource, spanProcessors: [...(options.spanProcessors ?? [])] });
61
+ }
62
+ catch (error) {
63
+ release();
64
+ throw error;
65
+ }
66
+ // OpenTelemetry JS 3.x has no register() on the provider: set the three globals here. A set does not throw.
67
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
68
+ propagation.setGlobalPropagator(new ContextPropagator());
69
+ trace.setGlobalTracerProvider(tracerProvider);
70
+ let stopping;
71
+ return {
72
+ stop: () =>
73
+ // The shutdown of the provider does not wait for an export that a SimpleSpanProcessor started. That export first
74
+ // waits for the async attributes of the resource. Thus the stop flushes first.
75
+ (stopping ??= tracerProvider
76
+ .forceFlush()
77
+ .then(() => tracerProvider.shutdown())
78
+ .catch(() => {
79
+ // a flush that fails at the stop loses its spans, and nothing else
80
+ })
81
+ .finally(() => {
82
+ for (const api of [trace, propagation, context])
83
+ api.disable();
84
+ release();
85
+ })),
86
+ };
87
+ }
88
+ //# sourceMappingURL=node-registration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-registration.js","sourceRoot":"","sources":["../src/node-registration.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,KAAK,EAAmB,MAAM,oBAAoB,CAAC;AAClF,OAAO,EAAE,+BAA+B,EAAE,MAAM,oCAAoC,CAAC;AACrF,OAAO,EACL,eAAe,EACf,eAAe,EACf,WAAW,EACX,YAAY,EACZ,UAAU,EACV,eAAe,EACf,sBAAsB,EACtB,yBAAyB,GAE1B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,cAAc,EAAsB,MAAM,0BAA0B,CAAC;AAC9E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,wBAAwB,EAAE,MAAM,yBAAyB,CAAC;AAItF,+HAA+H;AAC/H,MAAM,kBAAkB,GAA0C,IAAI,GAAG,CAAC;IACxE,CAAC,MAAM,EAAE,YAAY,CAAC;IACtB,CAAC,IAAI,EAAE,UAAU,CAAC;IAClB,CAAC,iBAAiB,EAAE,yBAAyB,CAAC;IAC9C,CAAC,SAAS,EAAE,eAAe,CAAC;IAC5B,CAAC,KAAK,EAAE,WAAW,CAAC;CACrB,CAAC,CAAC;AAEH;;;;;;;GAOG;AACH,MAAM,UAAU,qBAAqB,CAAC,GAAQ,EAAE,UAAsB;IACpE,MAAM,KAAK,GAAG,CAAC,GAAG,CAAC,8BAA8B,CAAC,IAAI,EAAE,CAAC;SACtD,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,E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,CAAC,CAAC;aACnG,KAAK,CAAC,sBAAsB,CAAC,EAAE,CAAC,iBAAiB,CAAC,EAAE,eAAe,CAAC,OAAO,CAAC,WAAW,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;QACrG,cAAc,GAAG,IAAI,cAAc,CAAC,EAAE,QAAQ,EAAE,cAAc,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC;IACzG,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,CAAC;QACV,MAAM,KAAK,CAAC;IACd,CAAC;IACD,4GAA4G;IAC5G,OAAO,CAAC,uBAAuB,CAAC,IAAI,+BAA+B,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC;IAChF,WAAW,CAAC,mBAAmB,CAAC,IAAI,iBAAiB,EAAE,CAAC,CAAC;IACzD,KAAK,CAAC,uBAAuB,CAAC,cAAc,CAAC,CAAC;IAE9C,IAAI,QAAmC,CAAC;IACxC,OAAO;QACL,IAAI,EAAE,GAAG,EAAE;QACT,iHAAiH;QACjH,+EAA+E;QAC/E,CAAC,QAAQ,KAAK,cAAc;aACzB,UAAU,EAAE;aACZ,IAAI,CAAC,GAAG,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,CAAC;aACrC,KAAK,CAAC,GAAG,EAAE;YACV,mEAAmE;QACrE,CAAC,CAAC;aACD,OAAO,CAAC,GAAG,EAAE;YACZ,KAAK,MAAM,GAAG,IAAI,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,CAAC;gBAAE,GAAG,CAAC,OAAO,EAAE,CAAC;YAC/D,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;KACR,CAAC;AACJ,CAAC"}
package/dist/node.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { type Attributes } from "@opentelemetry/api";
2
2
  import { type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
3
3
  import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
4
- import type { SpanExporter } from "@opentelemetry/sdk-trace";
4
+ import { type SpanExporter } from "@opentelemetry/sdk-trace";
5
5
  export { exporterNames, histogramAggregation, otlpProtocol, type ExporterName, type OtlpProtocol, type OtlpSignal } from "./node-exporters.js";
6
6
  export { outgoingTraceparent, createTraceEcho, runInRemoteTrace, type RemoteTraceOptions, type TraceEcho } from "./trace-echo.js";
7
7
  /** The configuration of `startNodeTelemetry()` */
@@ -35,8 +35,9 @@ export interface NodeTelemetryOptions {
35
35
  metricReaders?: NodeSDKConfiguration["metricReaders"];
36
36
  /**
37
37
  * Export on or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a
38
- * value. With export off, the context is registered all the same, so the ids
39
- * go through the service and into its own log lines.
38
+ * value. With export off, it starts no SDK: it registers the context as
39
+ * `startNodeContext()` of the entry `/node/context` does. Each span gets a
40
+ * trace id, so the ids go through the service and into its own log lines.
40
41
  */
41
42
  enabled?: boolean;
42
43
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAyBA,OAAO,EAA8C,KAAK,UAAU,EAAE,MAAM,oBAAoB,CAAC;AACjG,OAAO,EAAW,KAAK,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC7E,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAK7D,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,YAAY,EAAE,KAAK,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAE/I,OAAO,EAAE,mBAAmB,EAAE,eAAe,EAAE,gBAAgB,EAAE,KAAK,kBAAkB,EAAE,KAAK,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAElI,kDAAkD;AAClD,MAAM,WAAW,oBAAoB;IACnC,2E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* registers it.
22
22
  *
23
+ * This entry loads the SDK and each exporter also with export off. A service
24
+ * that exports nothing imports the entry `/node/context`, which loads none of them.
25
+ *
23
26
  * @packageDocumentation
24
27
  */
25
28
  import { register } from "node:module";
26
29
  import { context, logs, metrics, propagation, trace } from "@opentelemetry/api";
30
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
27
31
  import { NodeSDK } from "@opentelemetry/sdk-node";
32
+ import { NoopSpanProcessor } from "@opentelemetry/sdk-trace";
28
33
  import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
29
34
  import { contextMetricViews } from "./context-processors.js";
30
- import { histogramAggregation, nodeLogRecordProcessors, nodeResourceDetectors, nodeSpanProcessors } from "./node-exporters.js";
35
+ import { histogramAggregation, nodeLogRecordProcessors, nodeSpanProcessors } from "./node-exporters.js";
36
+ import { nodeResourceDetectors, nodeServiceName, registerNodeContext } from "./node-registration.js";
31
37
  export { exporterNames, histogramAggregation, otlpProtocol } from "./node-exporters.js";
32
38
  export { outgoingTraceparent, createTraceEcho, runInRemoteTrace } from "./trace-echo.js";
33
39
  /** The signals that stop the SDK when `stopOnSignals` is true */
@@ -41,39 +47,23 @@ const OWN_LISTENERS = new Set();
41
47
  export function startNodeTelemetry(options = {}) {
42
48
  const env = options.env ?? process.env;
43
49
  const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
44
- const release = claimContextRegistration("startNodeTelemetry()");
45
50
  let esmHook = false;
46
- let sdk;
47
- try {
48
- // In the try too: a hook that does not resolve gives back the claim
51
+ // In the claim: a hook that does not resolve gives back the claim
52
+ const registerHook = () => {
49
53
  if (options.importMetaUrl) {
50
54
  register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
51
55
  esmHook = true;
52
56
  }
53
- // With export off: no processor and no reader, so nothing leaves the process
54
- const exports = enabled
55
- ? {
56
- spanProcessors: nodeSpanProcessors(env, options.traceExporter),
57
- logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
58
- ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
59
- }
60
- : { spanProcessors: [], logRecordProcessors: [], metricReaders: [] };
61
- sdk = new NodeSDK({
62
- serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
63
- textMapPropagator: new ContextPropagator(),
64
- // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
65
- // the views replace the preference of each reader
66
- views: contextMetricViews(histogramAggregation(env)),
67
- ...exports,
68
- ...(options.resourceAttributes ? { resourceDetectors: nodeResourceDetectors(env, options.resourceAttributes) } : {}),
69
- ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
70
- });
71
- sdk.start();
72
- }
73
- catch (error) {
74
- release();
75
- throw error;
76
- }
57
+ };
58
+ // With export off: the registration of the entry /node/context, and no SDK. Thus the two paths register the
59
+ // same context, and nothing leaves the process. The instrumentations get the global tracer provider, as in the SDK.
60
+ const stop = enabled
61
+ ? startSdk(options, env, registerHook)
62
+ : registerNodeContext("startNodeTelemetry()", { serviceName: options.serviceName, resourceAttributes: options.resourceAttributes, env }, () => {
63
+ registerHook();
64
+ if (options.instrumentations)
65
+ registerInstrumentations({ instrumentations: options.instrumentations });
66
+ }).stop;
77
67
  // The signal listeners of this start, removed at the stop
78
68
  const listeners = [];
79
69
  // One stop: a second call waits for the flush of the first
@@ -88,17 +78,7 @@ export function startNodeTelemetry(options = {}) {
88
78
  process.removeListener(signal, listener);
89
79
  OWN_LISTENERS.delete(listener);
90
80
  }
91
- return (stopping = sdk
92
- .shutdown()
93
- .catch(() => {
94
- // a flush that fails at the stop loses its spans, and nothing else
95
- })
96
- .finally(() => {
97
- // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
98
- for (const api of [trace, metrics, logs, propagation, context])
99
- api.disable();
100
- release();
101
- }));
81
+ return (stopping = stop());
102
82
  };
103
83
  if (options.stopOnSignals ?? true) {
104
84
  for (const signal of STOP_SIGNALS) {
@@ -121,4 +101,44 @@ export function startNodeTelemetry(options = {}) {
121
101
  }
122
102
  return { enabled, esmHook, shutdown };
123
103
  }
104
+ /** Start the SDK with export on, and give the function that stops it and removes the registration */
105
+ function startSdk(options, env, registerHook) {
106
+ const release = claimContextRegistration("startNodeTelemetry()");
107
+ let sdk;
108
+ try {
109
+ registerHook();
110
+ // The SDK registers its tracer provider only for a list of span processors that is not empty. Without the
111
+ // provider, each span is the span of the API with the trace id zero. A processor that does nothing keeps the
112
+ // provider, so each span gets a trace id, also with the traces exporter "none".
113
+ const exporting = nodeSpanProcessors(env, options.traceExporter);
114
+ sdk = new NodeSDK({
115
+ serviceName: nodeServiceName(options.serviceName, env),
116
+ textMapPropagator: new ContextPropagator(),
117
+ // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
118
+ // the views replace the preference of each reader
119
+ views: contextMetricViews(histogramAggregation(env)),
120
+ spanProcessors: exporting.length > 0 ? exporting : [new NoopSpanProcessor()],
121
+ logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
122
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
123
+ ...(options.resourceAttributes ? { resourceDetectors: nodeResourceDetectors(env, options.resourceAttributes) } : {}),
124
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
125
+ });
126
+ sdk.start();
127
+ }
128
+ catch (error) {
129
+ release();
130
+ throw error;
131
+ }
132
+ return () => sdk
133
+ .shutdown()
134
+ .catch(() => {
135
+ // a flush that fails at the stop loses its spans, and nothing else
136
+ })
137
+ .finally(() => {
138
+ // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
139
+ for (const api of [trace, metrics, logs, propagation, context])
140
+ api.disable();
141
+ release();
142
+ });
143
+ }
124
144
  //# 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;;;;;;;;;;;;;;;;;;;;;;;G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,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,CAAC;QACV,MAAM,KAAK,CAAC;IACd,CAAC;IACD,OAAO,GAAG,EAAE,CACV,GAAG;SACA,QAAQ,EAAE;SACV,KAAK,CAAC,GAAG,EAAE;QACV,mEAAmE;IACrE,CAAC,CAAC;SACD,OAAO,CAAC,GAAG,EAAE;QACZ,0FAA0F;QAC1F,KAAK,MAAM,GAAG,IAAI,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,CAAC;YAAE,GAAG,CAAC,OAAO,EAAE,CAAC;QAC9E,OAAO,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACT,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package",
3
3
  "name": "@mark1russell7/otel-ts",
4
- "version": "0.8.2",
4
+ "version": "0.8.4",
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)",
@@ -40,6 +40,10 @@
40
40
  "types": "./dist/node.d.ts",
41
41
  "import": "./dist/node.js"
42
42
  },
43
+ "./node/context": {
44
+ "types": "./dist/node-context.d.ts",
45
+ "import": "./dist/node-context.js"
46
+ },
43
47
  "./node/testing": {
44
48
  "types": "./dist/node-testing.d.ts",
45
49
  "import": "./dist/node-testing.js"
@@ -59,6 +63,7 @@
59
63
  "@grafana/faro-web-sdk": "^2.13.0",
60
64
  "@opentelemetry/api": "^1.10.0",
61
65
  "@opentelemetry/auto-instrumentations-web": "^0.70.1",
66
+ "@opentelemetry/context-async-hooks": "^3.1.1",
62
67
  "@opentelemetry/context-zone": "^3.1.1",
63
68
  "@opentelemetry/core": "^3.1.1",
64
69
  "@opentelemetry/exporter-logs-otlp-http": "^0.301.2",
@@ -91,7 +96,8 @@
91
96
  "devDependencies": {
92
97
  "@mark1russell7/grafana-infra": "github:mark1russell7/grafana-infra",
93
98
  "@mark1russell7/lag": "^0.5.0",
94
- "@mark1russell7/rigor-testkit": "^0.1.2",
99
+ "@mark1russell7/rigor-bench": "^0.3.2",
100
+ "@mark1russell7/rigor-testkit": "^0.2.0",
95
101
  "@opentelemetry/sdk-node": "~0.301.2",
96
102
  "@types/node": "^26.6.5",
97
103
  "@vitest/coverage-v8": "^4.1.12",
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The entry `@mark1russell7/otel-ts/node/context`: the context of a Node service that exports nothing, with no
3
+ * SDK of `@opentelemetry/sdk-node`.
4
+ *
5
+ * It registers the one context (docs/CONTEXT-DESIGN.md) as the entry `/node` does with export off:
6
+ * AsyncLocalStorage, the propagator of otel-ts (the trace context on each call, the baggage on internal calls
7
+ * only), and a tracer provider with the resource of the service. Each span gets a trace id, so the ids go
8
+ * through the service and into its own log lines.
9
+ *
10
+ * The entry `/node` loads `@opentelemetry/sdk-node` and each exporter also with export off. This entry loads
11
+ * none of them, and no instrumentation. Thus a small service pays only for the context. A service that exports
12
+ * imports `/node`.
13
+ *
14
+ * Only one part of a program registers the context: `startNodeContext()` and `startNodeTelemetry()` refuse each
15
+ * other until the `shutdown()` of the first.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import type { Attributes } from "@opentelemetry/api";
20
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace";
21
+ import { registerNodeContext } from "./node-registration.js";
22
+
23
+ /** The configuration of `startNodeContext()` */
24
+ export interface NodeContextOptions {
25
+ /** The service name. Default: `OTEL_SERVICE_NAME`, else "node-service". */
26
+ serviceName?: string;
27
+ /**
28
+ * The attributes of the resource of the service, for example `service.version` and `service.instance.id`
29
+ * (the copy of the service). They win over the detected attributes and over `OTEL_RESOURCE_ATTRIBUTES`.
30
+ */
31
+ resourceAttributes?: Attributes;
32
+ /**
33
+ * The span processors. Default: none, and no span leaves the process. A test gives a processor with the
34
+ * exporter of its capture.
35
+ */
36
+ spanProcessors?: readonly SpanProcessor[];
37
+ /** The environment of the service name and of `OTEL_NODE_RESOURCE_DETECTORS`. Default: `process.env`. */
38
+ env?: NodeJS.ProcessEnv;
39
+ }
40
+
41
+ /** The result of `startNodeContext()` */
42
+ export interface NodeContext {
43
+ /**
44
+ * Flush the span processors, stop the tracer provider, and remove the registration of the context. A second
45
+ * call does nothing. A service of `@mark1russell7/service` calls it in its last stage, `flush the output`.
46
+ */
47
+ shutdown(): Promise<void>;
48
+ }
49
+
50
+ /**
51
+ * Register the context of a Node service that exports nothing. A second call before the `shutdown()` of the
52
+ * first is an error. It adds no listener for a signal: the service calls `shutdown()` at its stop.
53
+ */
54
+ export function startNodeContext(options: NodeContextOptions = {}): NodeContext {
55
+ const registration = registerNodeContext("startNodeContext()", options);
56
+ return { shutdown: () => registration.stop() };
57
+ }
@@ -17,8 +17,6 @@ import {
17
17
  type LogRecordExporter,
18
18
  type LogRecordProcessor,
19
19
  } from "@opentelemetry/sdk-logs";
20
- import type { Attributes } from "@opentelemetry/api";
21
- import { envDetector, hostDetector, osDetector, processDetector, serviceInstanceIdDetector, type ResourceDetector } from "@opentelemetry/resources";
22
20
  import { AggregationType, InstrumentType, type AggregationSelector } from "@opentelemetry/sdk-metrics";
23
21
  import { BatchSpanProcessor, ConsoleSpanExporter, SimpleSpanProcessor, type SpanExporter, type SpanProcessor } from "@opentelemetry/sdk-trace";
24
22
  import { createContextLogRecordProcessor, createContextSpanProcessor, defaultAggregation } from "./context-processors.js";
@@ -75,32 +73,6 @@ export function histogramAggregation(env: Env): AggregationSelector {
75
73
  throw new RangeError(`${variable} has "${value}": otel-ts makes "explicit_bucket_histogram" or "base2_exponential_bucket_histogram"`);
76
74
  }
77
75
 
78
- /** The resource detectors of `OTEL_NODE_RESOURCE_DETECTORS`, with the names and the sequence of the NodeSDK. `env` is last. */
79
- const RESOURCE_DETECTORS: ReadonlyMap<string, ResourceDetector> = new Map([
80
- ["host", hostDetector],
81
- ["os", osDetector],
82
- ["serviceinstance", serviceInstanceIdDetector],
83
- ["process", processDetector],
84
- ["env", envDetector],
85
- ]);
86
-
87
- /**
88
- * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
89
- * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
90
- * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
91
- * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
92
- * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
93
- * ignores a name that it does not know, with a warning. This function ignores it too.
94
- */
95
- export function nodeResourceDetectors(env: Env, attributes: Attributes): ResourceDetector[] {
96
- const names = (env["OTEL_NODE_RESOURCE_DETECTORS"] ?? "")
97
- .split(",")
98
- .map((name) => name.trim())
99
- .filter((name) => name !== "");
100
- const chosen = names.length === 0 || names.includes("all") ? [...RESOURCE_DETECTORS.values()] : names.includes("none") ? [] : names.flatMap((name) => RESOURCE_DETECTORS.get(name) ?? []);
101
- return [...chosen, { detect: () => ({ attributes: { ...attributes } }) }];
102
- }
103
-
104
76
  /**
105
77
  * The span processors: the context processor, then a processor for `exporter`,
106
78
  * or for each exporter of the variables. No exporter gives no processor.
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The registration of the context of a Node service with no SDK of `@opentelemetry/sdk-node`
3
+ * (docs/CONTEXT-DESIGN.md, section 4). The entry `/node/context` and the export off of the entry `/node`
4
+ * use it. Thus the two paths register the same context.
5
+ *
6
+ * This module imports no exporter, no instrumentation and no SDK of `@opentelemetry/sdk-node`.
7
+ * The entries test holds this rule.
8
+ */
9
+ import { context, propagation, trace, type Attributes } from "@opentelemetry/api";
10
+ import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks";
11
+ import {
12
+ defaultResource,
13
+ detectResources,
14
+ envDetector,
15
+ hostDetector,
16
+ osDetector,
17
+ processDetector,
18
+ resourceFromAttributes,
19
+ serviceInstanceIdDetector,
20
+ type ResourceDetector,
21
+ } from "@opentelemetry/resources";
22
+ import { TracerProvider, type SpanProcessor } from "@opentelemetry/sdk-trace";
23
+ import { ATTR_SERVICE_NAME } from "@opentelemetry/semantic-conventions";
24
+ import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
25
+
26
+ type Env = Readonly<Record<string, string | undefined>>;
27
+
28
+ /** The resource detectors of `OTEL_NODE_RESOURCE_DETECTORS`, with the names and the sequence of the NodeSDK. `env` is last. */
29
+ const RESOURCE_DETECTORS: ReadonlyMap<string, ResourceDetector> = new Map([
30
+ ["host", hostDetector],
31
+ ["os", osDetector],
32
+ ["serviceinstance", serviceInstanceIdDetector],
33
+ ["process", processDetector],
34
+ ["env", envDetector],
35
+ ]);
36
+
37
+ /**
38
+ * The resource detectors that the NodeSDK uses: the names of `OTEL_NODE_RESOURCE_DETECTORS` (`host`, `os`,
39
+ * `serviceinstance`, `process`, `env`, `all` or `none`; default `all`), then a detector that gives
40
+ * `attributes`. That last detector wins over each other detector, also over `OTEL_RESOURCE_ATTRIBUTES` (the
41
+ * detector `env`), as the option `resourceAttributes` of `startNodeSDK()` of the SDK does. Without it, a
42
+ * `service.instance.id` of the service lost to the random id of the detector `serviceinstance`. The NodeSDK
43
+ * ignores a name that it does not know, with a warning. This function ignores it too.
44
+ */
45
+ export function nodeResourceDetectors(env: Env, attributes: Attributes): ResourceDetector[] {
46
+ const names = (env["OTEL_NODE_RESOURCE_DETECTORS"] ?? "")
47
+ .split(",")
48
+ .map((name) => name.trim())
49
+ .filter((name) => name !== "");
50
+ const chosen = names.length === 0 || names.includes("all") ? [...RESOURCE_DETECTORS.values()] : names.includes("none") ? [] : names.flatMap((name) => RESOURCE_DETECTORS.get(name) ?? []);
51
+ return [...chosen, { detect: () => ({ attributes: { ...attributes } }) }];
52
+ }
53
+
54
+ /** The service name of a start: the option, else `OTEL_SERVICE_NAME`, else "node-service" */
55
+ export function nodeServiceName(serviceName: string | undefined, env: Env): string {
56
+ return serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service";
57
+ }
58
+
59
+ /** The configuration of the registration of the context */
60
+ export interface NodeContextRegistrationOptions {
61
+ readonly serviceName?: string | undefined;
62
+ readonly resourceAttributes?: Attributes | undefined;
63
+ readonly spanProcessors?: readonly SpanProcessor[] | undefined;
64
+ readonly env?: Env | undefined;
65
+ }
66
+
67
+ /** A registration of the context */
68
+ export interface NodeContextRegistration {
69
+ /** Stop the tracer provider, flush its processors, and remove the registration. A second call gives the same promise. */
70
+ stop(): Promise<void>;
71
+ }
72
+
73
+ /**
74
+ * Register the context for `caller`: the claim, AsyncLocalStorage as the context manager, the propagator of
75
+ * otel-ts, and a tracer provider with the resource of the service. A tracer provider of the SDK gives each span
76
+ * a trace id, also with no span processor.
77
+ *
78
+ * `prepare` runs after the claim and before the context. When it throws, the claim goes back.
79
+ */
80
+ export function registerNodeContext(caller: string, options: NodeContextRegistrationOptions, prepare?: () => void): NodeContextRegistration {
81
+ const release = claimContextRegistration(caller);
82
+ let tracerProvider: TracerProvider;
83
+ try {
84
+ prepare?.();
85
+ const env = options.env ?? process.env;
86
+ // The sequence of the NodeSDK: the default resource, then the detectors, then the service name
87
+ const resource = defaultResource()
88
+ .merge(detectResources({ detectors: nodeResourceDetectors(env, options.resourceAttributes ?? {}) }))
89
+ .merge(resourceFromAttributes({ [ATTR_SERVICE_NAME]: nodeServiceName(options.serviceName, env) }));
90
+ tracerProvider = new TracerProvider({ resource, spanProcessors: [...(options.spanProcessors ?? [])] });
91
+ } catch (error) {
92
+ release();
93
+ throw error;
94
+ }
95
+ // OpenTelemetry JS 3.x has no register() on the provider: set the three globals here. A set does not throw.
96
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
97
+ propagation.setGlobalPropagator(new ContextPropagator());
98
+ trace.setGlobalTracerProvider(tracerProvider);
99
+
100
+ let stopping: Promise<void> | undefined;
101
+ return {
102
+ stop: () =>
103
+ // The shutdown of the provider does not wait for an export that a SimpleSpanProcessor started. That export first
104
+ // waits for the async attributes of the resource. Thus the stop flushes first.
105
+ (stopping ??= tracerProvider
106
+ .forceFlush()
107
+ .then(() => tracerProvider.shutdown())
108
+ .catch(() => {
109
+ // a flush that fails at the stop loses its spans, and nothing else
110
+ })
111
+ .finally(() => {
112
+ for (const api of [trace, propagation, context]) api.disable();
113
+ release();
114
+ })),
115
+ };
116
+ }
package/src/node.ts CHANGED
@@ -20,16 +20,21 @@
20
20
  * context keys to each span and each log record. Only one part of a program
21
21
  * registers it.
22
22
  *
23
+ * This entry loads the SDK and each exporter also with export off. A service
24
+ * that exports nothing imports the entry `/node/context`, which loads none of them.
25
+ *
23
26
  * @packageDocumentation
24
27
  */
25
28
  import { register } from "node:module";
26
29
  import { context, logs, metrics, propagation, trace, type Attributes } from "@opentelemetry/api";
30
+ import { registerInstrumentations } from "@opentelemetry/instrumentation";
27
31
  import { NodeSDK, type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
28
32
  import type { LogRecordExporter } from "@opentelemetry/sdk-logs";
29
- import type { SpanExporter } from "@opentelemetry/sdk-trace";
33
+ import { NoopSpanProcessor, type SpanExporter } from "@opentelemetry/sdk-trace";
30
34
  import { ContextPropagator, claimContextRegistration } from "./context-propagator.js";
31
35
  import { contextMetricViews } from "./context-processors.js";
32
- import { histogramAggregation, nodeLogRecordProcessors, nodeResourceDetectors, nodeSpanProcessors } from "./node-exporters.js";
36
+ import { histogramAggregation, nodeLogRecordProcessors, nodeSpanProcessors } from "./node-exporters.js";
37
+ import { nodeResourceDetectors, nodeServiceName, registerNodeContext } from "./node-registration.js";
33
38
 
34
39
  export { exporterNames, histogramAggregation, otlpProtocol, type ExporterName, type OtlpProtocol, type OtlpSignal } from "./node-exporters.js";
35
40
 
@@ -66,8 +71,9 @@ export interface NodeTelemetryOptions {
66
71
  metricReaders?: NodeSDKConfiguration["metricReaders"];
67
72
  /**
68
73
  * Export on or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a
69
- * value. With export off, the context is registered all the same, so the ids
70
- * go through the service and into its own log lines.
74
+ * value. With export off, it starts no SDK: it registers the context as
75
+ * `startNodeContext()` of the entry `/node/context` does. Each span gets a
76
+ * trace id, so the ids go through the service and into its own log lines.
71
77
  */
72
78
  enabled?: boolean;
73
79
  /**
@@ -114,39 +120,22 @@ export interface NodeTelemetry {
114
120
  export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTelemetry {
115
121
  const env = options.env ?? process.env;
116
122
  const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
117
- const release = claimContextRegistration("startNodeTelemetry()");
118
-
119
123
  let esmHook = false;
120
- let sdk: NodeSDK;
121
- try {
122
- // In the try too: a hook that does not resolve gives back the claim
124
+ // In the claim: a hook that does not resolve gives back the claim
125
+ const registerHook = (): void => {
123
126
  if (options.importMetaUrl) {
124
127
  register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
125
128
  esmHook = true;
126
129
  }
127
- // With export off: no processor and no reader, so nothing leaves the process
128
- const exports: Partial<NodeSDKConfiguration> = enabled
129
- ? {
130
- spanProcessors: nodeSpanProcessors(env, options.traceExporter),
131
- logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
132
- ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
133
- }
134
- : { spanProcessors: [], logRecordProcessors: [], metricReaders: [] };
135
- sdk = new NodeSDK({
136
- serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
137
- textMapPropagator: new ContextPropagator(),
138
- // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
139
- // the views replace the preference of each reader
140
- views: contextMetricViews(histogramAggregation(env)),
141
- ...exports,
142
- ...(options.resourceAttributes ? { resourceDetectors: nodeResourceDetectors(env, options.resourceAttributes) } : {}),
143
- ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
144
- });
145
- sdk.start();
146
- } catch (error) {
147
- release();
148
- throw error;
149
- }
130
+ };
131
+ // With export off: the registration of the entry /node/context, and no SDK. Thus the two paths register the
132
+ // same context, and nothing leaves the process. The instrumentations get the global tracer provider, as in the SDK.
133
+ const stop = enabled
134
+ ? startSdk(options, env, registerHook)
135
+ : registerNodeContext("startNodeTelemetry()", { serviceName: options.serviceName, resourceAttributes: options.resourceAttributes, env }, () => {
136
+ registerHook();
137
+ if (options.instrumentations) registerInstrumentations({ instrumentations: options.instrumentations });
138
+ }).stop;
150
139
 
151
140
  // The signal listeners of this start, removed at the stop
152
141
  const listeners: Array<[NodeJS.Signals, () => void]> = [];
@@ -161,16 +150,7 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
161
150
  process.removeListener(signal, listener);
162
151
  OWN_LISTENERS.delete(listener);
163
152
  }
164
- return (stopping = sdk
165
- .shutdown()
166
- .catch(() => {
167
- // a flush that fails at the stop loses its spans, and nothing else
168
- })
169
- .finally(() => {
170
- // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
171
- for (const api of [trace, metrics, logs, propagation, context]) api.disable();
172
- release();
173
- }));
153
+ return (stopping = stop());
174
154
  };
175
155
  if (options.stopOnSignals ?? true) {
176
156
  for (const signal of STOP_SIGNALS) {
@@ -192,3 +172,43 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
192
172
  }
193
173
  return { enabled, esmHook, shutdown };
194
174
  }
175
+
176
+ /** Start the SDK with export on, and give the function that stops it and removes the registration */
177
+ function startSdk(options: NodeTelemetryOptions, env: NodeJS.ProcessEnv, registerHook: () => void): () => Promise<void> {
178
+ const release = claimContextRegistration("startNodeTelemetry()");
179
+ let sdk: NodeSDK;
180
+ try {
181
+ registerHook();
182
+ // The SDK registers its tracer provider only for a list of span processors that is not empty. Without the
183
+ // provider, each span is the span of the API with the trace id zero. A processor that does nothing keeps the
184
+ // provider, so each span gets a trace id, also with the traces exporter "none".
185
+ const exporting = nodeSpanProcessors(env, options.traceExporter);
186
+ sdk = new NodeSDK({
187
+ serviceName: nodeServiceName(options.serviceName, env),
188
+ textMapPropagator: new ContextPropagator(),
189
+ // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
190
+ // the views replace the preference of each reader
191
+ views: contextMetricViews(histogramAggregation(env)),
192
+ spanProcessors: exporting.length > 0 ? exporting : [new NoopSpanProcessor()],
193
+ logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
194
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
195
+ ...(options.resourceAttributes ? { resourceDetectors: nodeResourceDetectors(env, options.resourceAttributes) } : {}),
196
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
197
+ });
198
+ sdk.start();
199
+ } catch (error) {
200
+ release();
201
+ throw error;
202
+ }
203
+ return () =>
204
+ sdk
205
+ .shutdown()
206
+ .catch(() => {
207
+ // a flush that fails at the stop loses its spans, and nothing else
208
+ })
209
+ .finally(() => {
210
+ // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
211
+ for (const api of [trace, metrics, logs, propagation, context]) api.disable();
212
+ release();
213
+ });
214
+ }