@mark1russell7/otel-ts 0.8.3 → 0.8.5

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/dist/pull.d.ts ADDED
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { MetricReader, type ResourceMetrics } from "@opentelemetry/sdk-metrics";
11
+ /**
12
+ * The temporality of a pull reader. With `"cumulative"`, each collection gives the totals from the start. With
13
+ * `"delta"`, the counters and the histograms give the change after the last collection, and the up-down counters
14
+ * and the gauges stay cumulative, as with the OTLP delta preference.
15
+ */
16
+ export type PullTemporality = "cumulative" | "delta";
17
+ /** The options of a {@link PullMetricReader}. */
18
+ export interface PullMetricReaderOptions {
19
+ /** The temporality of each collection. The default is `"cumulative"`. */
20
+ readonly temporality?: PullTemporality;
21
+ }
22
+ /**
23
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
24
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
25
+ *
26
+ * ```ts no-run
27
+ * const reader = new PullMetricReader();
28
+ * const provider = new MeterProvider({ readers: [reader] });
29
+ * const { readings } = await collectReadings(reader, Date.now());
30
+ * ```
31
+ */
32
+ export declare class PullMetricReader extends MetricReader {
33
+ constructor(options?: PullMetricReaderOptions);
34
+ protected onForceFlush(): Promise<void>;
35
+ protected onShutdown(): Promise<void>;
36
+ }
37
+ /** One reading of a series: its key, the UTC time of the collection and its value. */
38
+ export interface MetricReading {
39
+ /**
40
+ * The key of the series. It is the name of the metric, then its attributes in the order of their keys, for example
41
+ * `http.requests{method="GET",status=200}`. With `attributes: "sum"`, it is the name only. A histogram gives the
42
+ * series `<name>.count` and `<name>.sum`.
43
+ */
44
+ readonly series: string;
45
+ /** The UTC time of the collection, in the ISO 8601 form. */
46
+ readonly at: string;
47
+ readonly value: number;
48
+ }
49
+ /** The options of {@link metricReadings}. */
50
+ export interface MetricReadingsOptions {
51
+ /**
52
+ * The series of a metric. With `"series"` (the default), each set of attributes is a series. With `"sum"`, the
53
+ * metric is one series: the sum of its data points over all attributes.
54
+ */
55
+ readonly attributes?: "series" | "sum";
56
+ }
57
+ /**
58
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
59
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
60
+ * their series.
61
+ */
62
+ export declare function metricReadings(metrics: ResourceMetrics, at: number, options?: MetricReadingsOptions): MetricReading[];
63
+ /** The result of one collection: the readings, and the count of the errors of the callbacks. */
64
+ export interface ReadingsCollection {
65
+ readonly readings: readonly MetricReading[];
66
+ readonly errors: number;
67
+ }
68
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
69
+ export declare function collectReadings(reader: MetricReader, at: number, options?: MetricReadingsOptions): Promise<ReadingsCollection>;
70
+ //# sourceMappingURL=pull.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.d.ts","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAIL,YAAY,EAEZ,KAAK,eAAe,EACrB,MAAM,4BAA4B,CAAC;AAEpC;;;;GAIG;AACH,MAAM,MAAM,eAAe,GAAG,YAAY,GAAG,OAAO,CAAC;AAErD,iDAAiD;AACjD,MAAM,WAAW,uBAAuB;IACtC,yEAAyE;IACzE,QAAQ,CAAC,WAAW,CAAC,EAAE,eAAe,CAAC;CACxC;AASD;;;;;;;;;GASG;AACH,qBAAa,gBAAiB,SAAQ,YAAY;gBACpC,OAAO,GAAE,uBAA4B;cAQ9B,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;cAI7B,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;CAG/C;AAED,sFAAsF;AACtF,MAAM,WAAW,aAAa;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACxB;AAED,6CAA6C;AAC7C,MAAM,WAAW,qBAAqB;IACpC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,QAAQ,GAAG,KAAK,CAAC;CACxC;AA2BD;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,aAAa,EAAE,CAiBzH;AAED,gGAAgG;AAChG,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB;AAED,0HAA0H;AAC1H,wBAAsB,eAAe,CAAC,MAAM,EAAE,YAAY,EAAE,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAGxI"}
package/dist/pull.js ADDED
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The entry `/pull`: the metrics of a process, read when the program asks. A {@link PullMetricReader} has no timer
3
+ * and no export. A program collects it at the times that it chooses, for example after the start and after each pass
4
+ * of a lab run, and {@link metricReadings} gives the value of each series at that time.
5
+ *
6
+ * The entry needs only `@opentelemetry/sdk-metrics`. It starts no SDK and sends nothing.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+ import { AggregationTemporality, DataPointType, InstrumentType, MetricReader, } from "@opentelemetry/sdk-metrics";
11
+ /** The instruments that the delta preference reads as a change. The others stay cumulative. */
12
+ const DELTA_INSTRUMENTS = new Set([
13
+ InstrumentType.COUNTER,
14
+ InstrumentType.OBSERVABLE_COUNTER,
15
+ InstrumentType.HISTOGRAM,
16
+ ]);
17
+ /**
18
+ * A metric reader that collects only when the program asks. It has no timer and no export, and its flush and its
19
+ * shutdown do nothing. Give it to a `MeterProvider` in `readers`, or to the SDK as a metric reader.
20
+ *
21
+ * ```ts no-run
22
+ * const reader = new PullMetricReader();
23
+ * const provider = new MeterProvider({ readers: [reader] });
24
+ * const { readings } = await collectReadings(reader, Date.now());
25
+ * ```
26
+ */
27
+ export class PullMetricReader extends MetricReader {
28
+ constructor(options = {}) {
29
+ const delta = options.temporality === "delta";
30
+ super({
31
+ aggregationTemporalitySelector: (type) => delta && DELTA_INSTRUMENTS.has(type) ? AggregationTemporality.DELTA : AggregationTemporality.CUMULATIVE,
32
+ });
33
+ }
34
+ onForceFlush() {
35
+ return Promise.resolve();
36
+ }
37
+ onShutdown() {
38
+ return Promise.resolve();
39
+ }
40
+ }
41
+ /** This function gives the key of a series: the name, then the attributes in the order of their keys. */
42
+ const seriesKey = (name, attributes) => {
43
+ const keys = Object.keys(attributes)
44
+ .filter((key) => attributes[key] !== undefined)
45
+ .sort();
46
+ if (keys.length === 0)
47
+ return name;
48
+ return `${name}{${keys.map((key) => `${key}=${JSON.stringify(attributes[key])}`).join(",")}}`;
49
+ };
50
+ /** This function gives the named values of each data point of a metric, with the attributes of the point. */
51
+ const pointValues = (metric) => {
52
+ const name = metric.descriptor.name;
53
+ switch (metric.dataPointType) {
54
+ case DataPointType.SUM:
55
+ case DataPointType.GAUGE:
56
+ return metric.dataPoints.map((point) => ({ attributes: point.attributes, values: [[name, point.value]] }));
57
+ case DataPointType.HISTOGRAM:
58
+ case DataPointType.EXPONENTIAL_HISTOGRAM:
59
+ return metric.dataPoints.map((point) => ({
60
+ attributes: point.attributes,
61
+ values: [[`${name}.count`, point.value.count], ...(point.value.sum === undefined ? [] : [[`${name}.sum`, point.value.sum]])],
62
+ }));
63
+ }
64
+ };
65
+ /**
66
+ * This function gives the readings of one collection at the time `at`, in ms from the epoch. Each sum and each gauge
67
+ * gives one reading for each series. Each histogram gives its count and its sum. The readings are in the order of
68
+ * their series.
69
+ */
70
+ export function metricReadings(metrics, at, options = {}) {
71
+ const time = new Date(at).toISOString();
72
+ const sum = options.attributes === "sum";
73
+ const values = new Map();
74
+ for (const scope of metrics.scopeMetrics) {
75
+ for (const metric of scope.metrics) {
76
+ for (const point of pointValues(metric)) {
77
+ for (const [name, value] of point.values) {
78
+ const series = sum ? name : seriesKey(name, point.attributes);
79
+ values.set(series, (values.get(series) ?? 0) + value);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ return [...values.keys()]
85
+ .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
86
+ .map((series) => ({ series, at: time, value: values.get(series) ?? 0 }));
87
+ }
88
+ /** This function collects the reader and gives the readings at the time `at`. Each failed callback adds 1 to `errors`. */
89
+ export async function collectReadings(reader, at, options = {}) {
90
+ const result = await reader.collect();
91
+ return { readings: metricReadings(result.resourceMetrics, at, options), errors: result.errors.length };
92
+ }
93
+ //# sourceMappingURL=pull.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pull.js","sourceRoot":"","sources":["../src/pull.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EACL,sBAAsB,EACtB,aAAa,EACb,cAAc,EACd,YAAY,GAGb,MAAM,4BAA4B,CAAC;AAepC,+FAA+F;AAC/F,MAAM,iBAAiB,GAAgC,IAAI,GAAG,CAAC;IAC7D,cAAc,CAAC,OAAO;IACtB,cAAc,CAAC,kBAAkB;IACjC,cAAc,CAAC,SAAS;CACzB,CAAC,CAAC;AAEH;;;;;;;;;GASG;AACH,MAAM,OAAO,gBAAiB,SAAQ,YAAY;IAChD,YAAY,UAAmC,EAAE;QAC/C,MAAM,KAAK,GAAG,OAAO,CAAC,WAAW,KAAK,OAAO,CAAC;QAC9C,KAAK,CAAC;YACJ,8BAA8B,EAAE,CAAC,IAAI,EAAE,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SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;oBAC9D,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,GAAG,KAAK,CAAC,CAAC;gBACxD,CAAC;YACH,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;SACtB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SAC5C,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC7E,CAAC;AAQD,0HAA0H;AAC1H,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,MAAoB,EAAE,EAAU,EAAE,UAAiC,EAAE;IACzG,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACtC,OAAO,EAAE,QAAQ,EAAE,cAAc,CAAC,MAAM,CAAC,eAAe,EAAE,EAAE,EAAE,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;AACzG,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.3",
4
+ "version": "0.8.5",
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"
@@ -47,6 +51,10 @@
47
51
  "./lag": {
48
52
  "types": "./dist/lag.d.ts",
49
53
  "import": "./dist/lag.js"
54
+ },
55
+ "./pull": {
56
+ "types": "./dist/pull.d.ts",
57
+ "import": "./dist/pull.js"
50
58
  }
51
59
  },
52
60
  "files": [
@@ -59,6 +67,7 @@
59
67
  "@grafana/faro-web-sdk": "^2.13.0",
60
68
  "@opentelemetry/api": "^1.10.0",
61
69
  "@opentelemetry/auto-instrumentations-web": "^0.70.1",
70
+ "@opentelemetry/context-async-hooks": "^3.1.1",
62
71
  "@opentelemetry/context-zone": "^3.1.1",
63
72
  "@opentelemetry/core": "^3.1.1",
64
73
  "@opentelemetry/exporter-logs-otlp-http": "^0.301.2",
@@ -91,6 +100,7 @@
91
100
  "devDependencies": {
92
101
  "@mark1russell7/grafana-infra": "github:mark1russell7/grafana-infra",
93
102
  "@mark1russell7/lag": "^0.5.0",
103
+ "@mark1russell7/rigor-bench": "^0.3.2",
94
104
  "@mark1russell7/rigor-testkit": "^0.2.0",
95
105
  "@opentelemetry/sdk-node": "~0.301.2",
96
106
  "@types/node": "^26.6.5",
@@ -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
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,9 +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, and each
70
- * span gets a trace id. So the ids go through the service and into its own
71
- * 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.
72
77
  */
73
78
  enabled?: boolean;
74
79
  /**
@@ -115,44 +120,22 @@ export interface NodeTelemetry {
115
120
  export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTelemetry {
116
121
  const env = options.env ?? process.env;
117
122
  const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
118
- const release = claimContextRegistration("startNodeTelemetry()");
119
-
120
123
  let esmHook = false;
121
- let sdk: NodeSDK;
122
- try {
123
- // 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 => {
124
126
  if (options.importMetaUrl) {
125
127
  register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
126
128
  esmHook = true;
127
129
  }
128
- // With export off: no exporter and no reader, so nothing leaves the process.
129
- // The SDK registers its tracer provider only for a list of span processors that is not empty. Without the
130
- // provider, each span is the span of the API with the trace id zero. A processor that does nothing keeps the
131
- // provider, so each span gets a trace id, also with export off or with the traces exporter "none".
132
- const exporting = enabled ? nodeSpanProcessors(env, options.traceExporter) : [];
133
- const spanProcessors = exporting.length > 0 ? exporting : [new NoopSpanProcessor()];
134
- const exports: Partial<NodeSDKConfiguration> = enabled
135
- ? {
136
- spanProcessors,
137
- logRecordProcessors: nodeLogRecordProcessors(env, options.logExporter),
138
- ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
139
- }
140
- : { spanProcessors, logRecordProcessors: [], metricReaders: [] };
141
- sdk = new NodeSDK({
142
- serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
143
- textMapPropagator: new ContextPropagator(),
144
- // The aggregation of OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION:
145
- // the views replace the preference of each reader
146
- views: contextMetricViews(histogramAggregation(env)),
147
- ...exports,
148
- ...(options.resourceAttributes ? { resourceDetectors: nodeResourceDetectors(env, options.resourceAttributes) } : {}),
149
- ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
150
- });
151
- sdk.start();
152
- } catch (error) {
153
- release();
154
- throw error;
155
- }
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;
156
139
 
157
140
  // The signal listeners of this start, removed at the stop
158
141
  const listeners: Array<[NodeJS.Signals, () => void]> = [];
@@ -167,16 +150,7 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
167
150
  process.removeListener(signal, listener);
168
151
  OWN_LISTENERS.delete(listener);
169
152
  }
170
- return (stopping = sdk
171
- .shutdown()
172
- .catch(() => {
173
- // a flush that fails at the stop loses its spans, and nothing else
174
- })
175
- .finally(() => {
176
- // The SDK leaves its globals at the stop. Remove them, so a next start registers its own.
177
- for (const api of [trace, metrics, logs, propagation, context]) api.disable();
178
- release();
179
- }));
153
+ return (stopping = stop());
180
154
  };
181
155
  if (options.stopOnSignals ?? true) {
182
156
  for (const signal of STOP_SIGNALS) {
@@ -198,3 +172,43 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
198
172
  }
199
173
  return { enabled, esmHook, shutdown };
200
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
+ }