@mark1russell7/otel-ts 0.0.0-bootstrap.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +417 -2
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/before-flush.d.ts +21 -0
  4. package/dist/before-flush.d.ts.map +1 -0
  5. package/dist/before-flush.js +46 -0
  6. package/dist/before-flush.js.map +1 -0
  7. package/dist/common.d.ts +11 -0
  8. package/dist/common.d.ts.map +1 -0
  9. package/dist/common.js +22 -0
  10. package/dist/common.js.map +1 -0
  11. package/dist/constants.d.ts +12 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +12 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/context-manager.d.ts +36 -0
  16. package/dist/context-manager.d.ts.map +1 -0
  17. package/dist/context-manager.js +60 -0
  18. package/dist/context-manager.js.map +1 -0
  19. package/dist/core.d.ts +14 -0
  20. package/dist/core.d.ts.map +1 -0
  21. package/dist/core.js +26 -0
  22. package/dist/core.js.map +1 -0
  23. package/dist/env.d.ts +6 -0
  24. package/dist/env.d.ts.map +1 -0
  25. package/dist/env.js +8 -0
  26. package/dist/env.js.map +1 -0
  27. package/dist/faro.d.ts +8 -0
  28. package/dist/faro.d.ts.map +1 -0
  29. package/dist/faro.js +24 -0
  30. package/dist/faro.js.map +1 -0
  31. package/dist/id.d.ts +22 -0
  32. package/dist/id.d.ts.map +1 -0
  33. package/dist/id.js +54 -0
  34. package/dist/id.js.map +1 -0
  35. package/dist/index.d.ts +14 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +33 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/init.d.ts +8 -0
  40. package/dist/init.d.ts.map +1 -0
  41. package/dist/init.js +135 -0
  42. package/dist/init.js.map +1 -0
  43. package/dist/lifecycle.d.ts +33 -0
  44. package/dist/lifecycle.d.ts.map +1 -0
  45. package/dist/lifecycle.js +39 -0
  46. package/dist/lifecycle.js.map +1 -0
  47. package/dist/logs.d.ts +6 -0
  48. package/dist/logs.d.ts.map +1 -0
  49. package/dist/logs.js +17 -0
  50. package/dist/logs.js.map +1 -0
  51. package/dist/metrics.d.ts +5 -0
  52. package/dist/metrics.d.ts.map +1 -0
  53. package/dist/metrics.js +37 -0
  54. package/dist/metrics.js.map +1 -0
  55. package/dist/node-testing.d.ts +23 -0
  56. package/dist/node-testing.d.ts.map +1 -0
  57. package/dist/node-testing.js +71 -0
  58. package/dist/node-testing.js.map +1 -0
  59. package/dist/node.d.ts +37 -0
  60. package/dist/node.d.ts.map +1 -0
  61. package/dist/node.js +54 -0
  62. package/dist/node.js.map +1 -0
  63. package/dist/resource.d.ts +38 -0
  64. package/dist/resource.d.ts.map +1 -0
  65. package/dist/resource.js +54 -0
  66. package/dist/resource.js.map +1 -0
  67. package/dist/session-processors.d.ts +9 -0
  68. package/dist/session-processors.d.ts.map +1 -0
  69. package/dist/session-processors.js +37 -0
  70. package/dist/session-processors.js.map +1 -0
  71. package/dist/session.d.ts +21 -0
  72. package/dist/session.d.ts.map +1 -0
  73. package/dist/session.js +76 -0
  74. package/dist/session.js.map +1 -0
  75. package/dist/trace-echo.d.ts +60 -0
  76. package/dist/trace-echo.d.ts.map +1 -0
  77. package/dist/trace-echo.js +118 -0
  78. package/dist/trace-echo.js.map +1 -0
  79. package/dist/tracing.d.ts +7 -0
  80. package/dist/tracing.d.ts.map +1 -0
  81. package/dist/tracing.js +48 -0
  82. package/dist/tracing.js.map +1 -0
  83. package/dist/types.d.ts +210 -0
  84. package/dist/types.d.ts.map +1 -0
  85. package/dist/types.js +2 -0
  86. package/dist/types.js.map +1 -0
  87. package/dist/zone.d.ts +14 -0
  88. package/dist/zone.d.ts.map +1 -0
  89. package/dist/zone.js +40 -0
  90. package/dist/zone.js.map +1 -0
  91. package/package.json +84 -5
  92. package/src/before-flush.ts +64 -0
  93. package/src/common.ts +46 -0
  94. package/src/constants.ts +12 -0
  95. package/src/context-manager.ts +82 -0
  96. package/src/core.ts +38 -0
  97. package/src/env.ts +7 -0
  98. package/src/faro.ts +29 -0
  99. package/src/id.ts +59 -0
  100. package/src/index.ts +45 -0
  101. package/src/init.ts +177 -0
  102. package/src/lifecycle.ts +52 -0
  103. package/src/logs.ts +30 -0
  104. package/src/metrics.ts +63 -0
  105. package/src/node-testing.ts +88 -0
  106. package/src/node.ts +89 -0
  107. package/src/resource.ts +73 -0
  108. package/src/session-processors.ts +48 -0
  109. package/src/session.ts +86 -0
  110. package/src/trace-echo.ts +137 -0
  111. package/src/tracing.ts +64 -0
  112. package/src/types.ts +261 -0
  113. package/src/zone.ts +52 -0
package/src/init.ts ADDED
@@ -0,0 +1,177 @@
1
+ import { MeterProvider } from "@opentelemetry/sdk-metrics";
2
+ import { LoggerProvider } from "@opentelemetry/sdk-logs";
3
+ import type { FlushCause, OtelTsConfig, OtelTsInstance, ResolvedConfig } from "./types.js";
4
+ import { buildResource } from "./resource.js";
5
+ import { createSessionTracker } from "./session.js";
6
+ import type { SessionIdReader } from "./session-processors.js";
7
+ import { createInstanceId, randomUuid } from "./id.js";
8
+ import { setupTracing } from "./tracing.js";
9
+ import {
10
+ createContextManager,
11
+ type EntryContextManagers,
12
+ } from "./context-manager.js";
13
+ import { setupMetrics } from "./metrics.js";
14
+ import { setupLogs } from "./logs.js";
15
+ import { setupFaro } from "./faro.js";
16
+ import { registerLifecycleHandlers } from "./lifecycle.js";
17
+ import { createBeforeFlushListeners } from "./before-flush.js";
18
+ import { hasDom } from "./env.js";
19
+ import {
20
+ DEFAULT_METRICS_EXPORT_INTERVAL_MS,
21
+ DEFAULT_OTLP_ENDPOINT,
22
+ DEFAULT_SERVICE_NAME,
23
+ DEFAULT_SERVICE_VERSION,
24
+ SESSION_TTL_MS,
25
+ } from "./constants.js";
26
+
27
+ function resolveConfig(
28
+ config: OtelTsConfig = {},
29
+ managers: EntryContextManagers,
30
+ ): ResolvedConfig {
31
+ return {
32
+ endpoint: config.endpoint ?? DEFAULT_OTLP_ENDPOINT,
33
+ serviceName: config.serviceName ?? DEFAULT_SERVICE_NAME,
34
+ serviceVersion: config.serviceVersion ?? DEFAULT_SERVICE_VERSION,
35
+ // A new writer identity for every init(). An empty string would map to
36
+ // an empty `instance` label, which is the same as none, so replace it too.
37
+ serviceInstanceId: config.serviceInstanceId || createInstanceId(),
38
+ resourceAttributes: config.resourceAttributes ?? {},
39
+ browserAttributes: config.browserAttributes ?? true,
40
+ tracing: config.tracing ?? true,
41
+ contextManager: config.contextManager ?? managers.defaultName,
42
+ propagateTraceHeaderCorsUrls: config.propagateTraceHeaderCorsUrls ?? [/.*/],
43
+ metrics: config.metrics ?? true,
44
+ metricsExportIntervalMs:
45
+ config.metricsExportIntervalMs ?? DEFAULT_METRICS_EXPORT_INTERVAL_MS,
46
+ metricsTemporality: config.metricsTemporality ?? "cumulative",
47
+ histogramAggregation: config.histogramAggregation ?? "explicit",
48
+ logs: config.logs ?? true,
49
+ instrumentDocumentLoad: config.instrumentDocumentLoad ?? true,
50
+ instrumentFetch: config.instrumentFetch ?? true,
51
+ instrumentXhr: config.instrumentXhr ?? true,
52
+ instrumentUserInteraction: config.instrumentUserInteraction ?? true,
53
+ instrumentLongTask: config.instrumentLongTask ?? true,
54
+ faro: config.faro ?? true,
55
+ faroCollectorUrl: config.faroCollectorUrl,
56
+ faroAppName: config.faroAppName,
57
+ sessionTracking: config.sessionTracking ?? true,
58
+ debug: config.debug ?? false,
59
+ };
60
+ }
61
+
62
+ /** Session IDs for this instance: tracked and rotated, or one fixed ID */
63
+ function createSessionIdReader(sessionTracking: boolean): SessionIdReader {
64
+ if (sessionTracking) return createSessionTracker(SESSION_TTL_MS);
65
+
66
+ const sessionId = randomUuid();
67
+ return () => sessionId;
68
+ }
69
+
70
+ /**
71
+ * The `init()` of each entry. `managers` are the context managers of the
72
+ * entry: the entry imports at most one context library.
73
+ */
74
+ export function initWith(
75
+ managers: EntryContextManagers,
76
+ config?: OtelTsConfig,
77
+ ): OtelTsInstance {
78
+ const resolved = resolveConfig(config, managers);
79
+
80
+ // First, so that a manager that the entry does not have throws before
81
+ // anything starts
82
+ const contextManager = resolved.tracing
83
+ ? createContextManager(resolved.contextManager, managers)
84
+ : undefined;
85
+
86
+ // Read again for every log record and span, so they follow rotations
87
+ const getSessionId = createSessionIdReader(resolved.sessionTracking);
88
+
89
+ // Start or resume the session now: a page load counts as activity
90
+ const sessionId = getSessionId();
91
+
92
+ // One resource, so metrics, logs and traces share the service.instance.id
93
+ const resource = buildResource(resolved);
94
+ const providers: Array<{
95
+ forceFlush(): Promise<void>;
96
+ shutdown(): Promise<void>;
97
+ }> = [];
98
+
99
+ if (contextManager) {
100
+ providers.push(
101
+ setupTracing(resource, resolved, getSessionId, contextManager),
102
+ );
103
+ }
104
+
105
+ const meterProvider = resolved.metrics
106
+ ? setupMetrics(resource, resolved)
107
+ : new MeterProvider();
108
+
109
+ providers.push(meterProvider);
110
+
111
+ const loggerProvider = resolved.logs
112
+ ? setupLogs(resource, resolved, getSessionId)
113
+ : new LoggerProvider();
114
+
115
+ providers.push(loggerProvider);
116
+
117
+ // Faro instruments the page (errors, web vitals, views) and needs a DOM.
118
+ // Without a collector URL it has nowhere to send data and logs an error.
119
+ const faroUrl =
120
+ resolved.faro && hasDom() ? resolved.faroCollectorUrl : undefined;
121
+
122
+ if (faroUrl) {
123
+ setupFaro(resolved, faroUrl);
124
+ }
125
+
126
+ // Run synchronously before every flush (page hide, shutdown, manual), so
127
+ // values they record are in it whatever order pagehide listeners run in
128
+ const beforeFlush = createBeforeFlushListeners();
129
+ let shutdownPromise: Promise<void> | undefined;
130
+
131
+ const forceFlush = async (cause: FlushCause = {}): Promise<void> => {
132
+ // Shut-down providers can't flush; wait for their final flush instead
133
+ if (shutdownPromise) return shutdownPromise;
134
+ beforeFlush.run(cause);
135
+ await Promise.allSettled(providers.map((p) => p.forceFlush()));
136
+ };
137
+
138
+ const shutdown = (cause: FlushCause = {}): Promise<void> => {
139
+ if (!shutdownPromise) {
140
+ beforeFlush.run(cause);
141
+ // ??= in case a listener called shutdown() itself
142
+ shutdownPromise ??= (async () => {
143
+ removeLifecycleHandlers();
144
+ await Promise.allSettled(providers.map((p) => p.shutdown()));
145
+ })();
146
+ }
147
+ return shutdownPromise;
148
+ };
149
+
150
+ const removeLifecycleHandlers = registerLifecycleHandlers({
151
+ flush: forceFlush,
152
+ shutdown,
153
+ });
154
+
155
+ if (resolved.debug) {
156
+ console.log("[otel-ts] Initialized", {
157
+ endpoint: resolved.endpoint,
158
+ serviceName: resolved.serviceName,
159
+ serviceInstanceId: resolved.serviceInstanceId,
160
+ sessionId,
161
+ tracing: resolved.tracing,
162
+ metrics: resolved.metrics,
163
+ logs: resolved.logs,
164
+ faro: Boolean(faroUrl),
165
+ });
166
+ }
167
+
168
+ return {
169
+ // A call of the app has no page event
170
+ shutdown: () => shutdown(),
171
+ forceFlush: () => forceFlush(),
172
+ onBeforeFlush: (listener) => beforeFlush.add(listener),
173
+ getSessionId,
174
+ getMeter: (name: string) => meterProvider.getMeter(name),
175
+ getLogger: (name: string) => loggerProvider.getLogger(name),
176
+ };
177
+ }
@@ -0,0 +1,52 @@
1
+ import { getPageLifecycle } from "page-lifecycle-tracker";
2
+ import { hasDom } from "./env.js";
3
+ import type { FlushCause } from "./types.js";
4
+
5
+ export interface LifecycleHandlers {
6
+ /** Export pending telemetry; providers keep running */
7
+ flush(cause: FlushCause): Promise<void>;
8
+
9
+ /** Final flush, then stop all providers */
10
+ shutdown(cause: FlushCause): Promise<void>;
11
+ }
12
+
13
+ /**
14
+ * Exports telemetry before the page can be frozen or discarded. The handlers
15
+ * subscribe to the lifecycle tracker that the page shares
16
+ * (`getPageLifecycle()` of page-lifecycle-tracker), in its `export` phase:
17
+ *
18
+ * - to `hidden`: flush. Happens on every tab switch, and the user may come
19
+ * back, so providers keep running.
20
+ * - to `frozen` (a freeze, or `pagehide` into the back/forward cache): flush,
21
+ * because the page may be restored.
22
+ * - to `terminated` (`pagehide` without `persisted`): shut down.
23
+ *
24
+ * A subscriber in the `export` phase runs after every subscriber in the
25
+ * `observe` phase of the same transition, so values that monitoring libraries
26
+ * record at the end of the page (on the same shared tracker) go out in that
27
+ * flush, whatever order the scripts registered in. Before, otel-ts listened
28
+ * to `pagehide` itself, and Chromium runs window listeners in registration
29
+ * order: it shut down before monitors that registered later recorded.
30
+ *
31
+ * The tracker does not use `beforeunload` or `unload`: they can make the page
32
+ * ineligible for the back/forward cache. Registers nothing where there is no
33
+ * DOM (e.g. in a Web Worker).
34
+ *
35
+ * @returns A function that removes the subscription
36
+ */
37
+ export function registerLifecycleHandlers(
38
+ handlers: LifecycleHandlers,
39
+ ): () => void {
40
+ if (!hasDom()) return () => {};
41
+
42
+ return getPageLifecycle().subscribe(
43
+ (transition) => {
44
+ if (transition.to === "hidden" || transition.to === "frozen") {
45
+ void handlers.flush({ transition });
46
+ } else if (transition.to === "terminated") {
47
+ void handlers.shutdown({ transition });
48
+ }
49
+ },
50
+ { phase: "export" },
51
+ );
52
+ }
package/src/logs.ts ADDED
@@ -0,0 +1,30 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import {
3
+ LoggerProvider,
4
+ BatchLogRecordProcessor,
5
+ } from "@opentelemetry/sdk-logs";
6
+ import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";
7
+ import type { ResolvedConfig } from "./types.js";
8
+ import {
9
+ createSessionLogRecordProcessor,
10
+ type SessionIdReader,
11
+ } from "./session-processors.js";
12
+
13
+ export function setupLogs(
14
+ resource: Resource,
15
+ config: ResolvedConfig,
16
+ getSessionId: SessionIdReader,
17
+ ): LoggerProvider {
18
+ const exporter = new OTLPLogExporter({
19
+ url: `${config.endpoint}/v1/logs`,
20
+ });
21
+
22
+ return new LoggerProvider({
23
+ resource,
24
+ processors: [
25
+ // Before the exporting processor, so every exported record has it
26
+ createSessionLogRecordProcessor(getSessionId),
27
+ new BatchLogRecordProcessor(exporter),
28
+ ],
29
+ });
30
+ }
package/src/metrics.ts ADDED
@@ -0,0 +1,63 @@
1
+ import type { Resource } from "@opentelemetry/resources";
2
+ import {
3
+ AggregationType,
4
+ InstrumentType,
5
+ MeterProvider,
6
+ PeriodicExportingMetricReader,
7
+ type AggregationSelector,
8
+ } from "@opentelemetry/sdk-metrics";
9
+ import {
10
+ AggregationTemporalityPreference,
11
+ OTLPMetricExporter,
12
+ type OTLPMetricExporterOptions,
13
+ } from "@opentelemetry/exporter-metrics-otlp-http";
14
+ import type { MetricsTemporality, ResolvedConfig } from "./types.js";
15
+
16
+ const TEMPORALITY_PREFERENCES: Record<
17
+ MetricsTemporality,
18
+ AggregationTemporalityPreference
19
+ > = {
20
+ cumulative: AggregationTemporalityPreference.CUMULATIVE,
21
+ delta: AggregationTemporalityPreference.DELTA,
22
+ };
23
+
24
+ /**
25
+ * Base-2 exponential histograms for histogram instruments; every other
26
+ * instrument keeps its default aggregation. Used as the exporter's
27
+ * aggregation preference — the SDK's equivalent of
28
+ * OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=base2_exponential_bucket_histogram —
29
+ * rather than a View, so it stays the default that any View can override,
30
+ * and there are no overlapping Views producing duplicate streams.
31
+ */
32
+ const selectExponentialHistograms: AggregationSelector = (
33
+ instrumentType,
34
+ ) =>
35
+ instrumentType === InstrumentType.HISTOGRAM
36
+ ? { type: AggregationType.EXPONENTIAL_HISTOGRAM }
37
+ : { type: AggregationType.DEFAULT };
38
+
39
+ export function setupMetrics(
40
+ resource: Resource,
41
+ config: ResolvedConfig,
42
+ ): MeterProvider {
43
+ const options: OTLPMetricExporterOptions = {
44
+ url: `${config.endpoint}/v1/metrics`,
45
+ temporalityPreference: TEMPORALITY_PREFERENCES[config.metricsTemporality],
46
+ };
47
+
48
+ if (config.histogramAggregation === "exponential") {
49
+ options.aggregationPreference = selectExponentialHistograms;
50
+ }
51
+
52
+ const exporter = new OTLPMetricExporter(options);
53
+
54
+ return new MeterProvider({
55
+ resource,
56
+ readers: [
57
+ new PeriodicExportingMetricReader({
58
+ exporter,
59
+ exportIntervalMillis: config.metricsExportIntervalMs,
60
+ }),
61
+ ],
62
+ });
63
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * `@mark1russell7/otel-ts/node/testing`: a stand-in OTLP collector for the CI
3
+ * check of a Node service. A change of the load order (for example a move to
4
+ * ES modules) breaks the instrumentations without an error: the service
5
+ * operates, and some spans are not there. A check starts the service with
6
+ * `OTEL_EXPORTER_OTLP_ENDPOINT` set to `collector.endpoint`, sends requests,
7
+ * and waits until each instrumentation that it expects has spans.
8
+ *
9
+ * The collector reads OTLP/HTTP JSON, the default of
10
+ * `@opentelemetry/exporter-trace-otlp-http`.
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ import { createServer, type Server } from "node:http";
15
+ import type { AddressInfo } from "node:net";
16
+
17
+ /** A stand-in OTLP/HTTP collector */
18
+ export interface StubCollector {
19
+ /** The endpoint for `OTEL_EXPORTER_OTLP_ENDPOINT`, for example http://127.0.0.1:43211 */
20
+ readonly endpoint: string;
21
+ /** The count of the trace exports that arrived */
22
+ readonly exports: number;
23
+ /** The span names of each instrumentation scope, for example "@opentelemetry/instrumentation-http" */
24
+ spansByScope(): Map<string, Set<string>>;
25
+ /** True when each of these scopes has one span or more */
26
+ has(scopes: readonly string[]): boolean;
27
+ /** The scopes of a list that have no span */
28
+ missing(scopes: readonly string[]): string[];
29
+ /** Wait until each scope has spans, `timeoutMs` at most (default 20 s). It gives the scopes that are still missing. */
30
+ waitFor(scopes: readonly string[], options?: { timeoutMs?: number; intervalMs?: number; poke?: () => Promise<unknown> }): Promise<string[]>;
31
+ close(): Promise<void>;
32
+ }
33
+
34
+ /** Start a stand-in OTLP/HTTP collector on a free port of 127.0.0.1 */
35
+ export async function startStubCollector(): Promise<StubCollector> {
36
+ const seen = new Map<string, Set<string>>();
37
+ let exports = 0;
38
+ const server: Server = createServer((req, res) => {
39
+ let body = "";
40
+ req.on("data", (chunk) => {
41
+ body += chunk;
42
+ });
43
+ req.on("end", () => {
44
+ if (req.url === "/v1/traces") {
45
+ exports++;
46
+ try {
47
+ const parsed = JSON.parse(body) as {
48
+ resourceSpans?: { scopeSpans?: { scope?: { name?: string }; spans?: { name?: string }[] }[] }[];
49
+ };
50
+ for (const rs of parsed.resourceSpans ?? []) {
51
+ for (const ss of rs.scopeSpans ?? []) {
52
+ const scope = ss.scope?.name ?? "?";
53
+ const names = seen.get(scope) ?? new Set<string>();
54
+ for (const span of ss.spans ?? []) names.add(span.name ?? "?");
55
+ seen.set(scope, names);
56
+ }
57
+ }
58
+ } catch {
59
+ // an export that is not JSON (protobuf): the check expects JSON
60
+ }
61
+ }
62
+ res.writeHead(200, { "Content-Type": "application/json" });
63
+ res.end("{}");
64
+ });
65
+ });
66
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
67
+ const { port } = server.address() as AddressInfo;
68
+ const missing = (scopes: readonly string[]): string[] => scopes.filter((s) => !(seen.get(s)?.size));
69
+ return {
70
+ endpoint: `http://127.0.0.1:${port}`,
71
+ get exports() {
72
+ return exports;
73
+ },
74
+ spansByScope: () => seen,
75
+ has: (scopes) => missing(scopes).length === 0,
76
+ missing,
77
+ async waitFor(scopes, options = {}) {
78
+ const until = Date.now() + (options.timeoutMs ?? 20_000);
79
+ while (Date.now() < until) {
80
+ await options.poke?.().catch(() => undefined);
81
+ if (missing(scopes).length === 0) return [];
82
+ await new Promise((r) => setTimeout(r, options.intervalMs ?? 500));
83
+ }
84
+ return missing(scopes);
85
+ },
86
+ close: () => new Promise<void>((resolve) => server.close(() => resolve())),
87
+ };
88
+ }
package/src/node.ts ADDED
@@ -0,0 +1,89 @@
1
+ /**
2
+ * The Node.js entry, `@mark1russell7/otel-ts/node`: OpenTelemetry for a Node
3
+ * service, with the order that an ES module service needs.
4
+ *
5
+ * Load the module that calls `startNodeTelemetry()` with `node --import`,
6
+ * before the service: the instrumentations patch `http`, `express` and the
7
+ * database drivers when those modules load. In an ES module service, the
8
+ * require hook does not see a package that an ES module imports. The loader
9
+ * hook of OpenTelemetry (`@opentelemetry/instrumentation/hook.mjs`) patches
10
+ * those imports. `startNodeTelemetry()` registers it before the SDK starts.
11
+ *
12
+ * The SDK, the exporters and the instrumentations come from the dependencies
13
+ * of the service (the OpenTelemetry packages must have one version line), so
14
+ * `@opentelemetry/sdk-node` is a peer dependency of this entry.
15
+ *
16
+ * @packageDocumentation
17
+ */
18
+ import { register } from "node:module";
19
+ import { NodeSDK, type NodeSDKConfiguration } from "@opentelemetry/sdk-node";
20
+
21
+ export { outgoingTraceparent, createTraceEcho, runInRemoteTrace, type RemoteTraceOptions, type TraceEcho } from "./trace-echo.js";
22
+
23
+ /** The configuration of `startNodeTelemetry()` */
24
+ export interface NodeTelemetryOptions {
25
+ /** The service name. Default: `OTEL_SERVICE_NAME`, else "node-service". */
26
+ serviceName?: string;
27
+ /**
28
+ * The `import.meta.url` of the module that calls this function. The loader
29
+ * hook resolves from it, so it is the instance of the service's
30
+ * instrumentations. Without it, no loader hook is registered.
31
+ */
32
+ importMetaUrl?: string;
33
+ /** The instrumentations, from the dependencies of the service */
34
+ instrumentations?: NodeSDKConfiguration["instrumentations"];
35
+ /** The trace exporter. Default: the exporter that the SDK makes from the `OTEL_*` variables. */
36
+ traceExporter?: NodeSDKConfiguration["traceExporter"];
37
+ /** The metric readers. Default: none. */
38
+ metricReaders?: NodeSDKConfiguration["metricReaders"];
39
+ /** On or off. Default: on when `OTEL_EXPORTER_OTLP_ENDPOINT` has a value. */
40
+ enabled?: boolean;
41
+ /** Stop the SDK (and flush) at SIGTERM and SIGINT. Default: true. */
42
+ stopOnSignals?: boolean;
43
+ /** The environment. Default: `process.env`. */
44
+ env?: NodeJS.ProcessEnv;
45
+ }
46
+
47
+ /** The result of `startNodeTelemetry()` */
48
+ export interface NodeTelemetry {
49
+ /** True when the SDK started */
50
+ readonly enabled: boolean;
51
+ /** True when the loader hook was registered */
52
+ readonly esmHook: boolean;
53
+ /** Stop the SDK and flush the spans and metrics. It does nothing when the SDK did not start. */
54
+ shutdown(): Promise<void>;
55
+ }
56
+
57
+ /** Start OpenTelemetry for a Node service: the loader hook first, then the SDK. */
58
+ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTelemetry {
59
+ const env = options.env ?? process.env;
60
+ const enabled = options.enabled ?? !!env["OTEL_EXPORTER_OTLP_ENDPOINT"];
61
+ if (!enabled) return { enabled: false, esmHook: false, shutdown: async () => {} };
62
+
63
+ let esmHook = false;
64
+ if (options.importMetaUrl) {
65
+ register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
66
+ esmHook = true;
67
+ }
68
+ const sdk = new NodeSDK({
69
+ serviceName: options.serviceName ?? env["OTEL_SERVICE_NAME"] ?? "node-service",
70
+ ...(options.traceExporter ? { traceExporter: options.traceExporter } : {}),
71
+ ...(options.metricReaders ? { metricReaders: options.metricReaders } : {}),
72
+ ...(options.instrumentations ? { instrumentations: options.instrumentations } : {}),
73
+ });
74
+ sdk.start();
75
+
76
+ let stopped = false;
77
+ const shutdown = async (): Promise<void> => {
78
+ if (stopped) return;
79
+ stopped = true;
80
+ await sdk.shutdown().catch(() => {
81
+ // a flush that fails at the stop loses its spans, and nothing else
82
+ });
83
+ };
84
+ if (options.stopOnSignals ?? true) {
85
+ process.once("SIGTERM", () => void shutdown());
86
+ process.once("SIGINT", () => void shutdown());
87
+ }
88
+ return { enabled: true, esmHook, shutdown };
89
+ }
@@ -0,0 +1,73 @@
1
+ import { resourceFromAttributes } from "@opentelemetry/resources";
2
+ import type { AttributeValue } from "@opentelemetry/api";
3
+ import {
4
+ ATTR_SERVICE_INSTANCE_ID,
5
+ ATTR_SERVICE_NAME,
6
+ ATTR_SERVICE_VERSION,
7
+ ATTR_USER_AGENT_ORIGINAL,
8
+ } from "@opentelemetry/semantic-conventions";
9
+ import type { ResolvedConfig } from "./types.js";
10
+
11
+ /** The parts of `navigator` that the browser attributes use, in a page or a worker */
12
+ interface NavigatorLike {
13
+ userAgent?: string;
14
+ language?: string;
15
+ userAgentData?: {
16
+ brands?: ReadonlyArray<{ brand: string; version: string }>;
17
+ mobile?: boolean;
18
+ platform?: string;
19
+ };
20
+ }
21
+
22
+ /**
23
+ * The browser attributes of the OpenTelemetry semantic conventions, from
24
+ * `navigator`: `browser.brands`, `browser.platform` and `browser.mobile`
25
+ * (User-Agent Client Hints, only Chromium has them), `browser.language` and
26
+ * `user_agent.original`. A page and a worker both have `navigator`; where
27
+ * there is none (Node.js), there are no attributes. The `browser.*` names are
28
+ * in the incubating conventions, thus they are written here and not imported.
29
+ */
30
+ export function browserAttributes(
31
+ nav: NavigatorLike | undefined,
32
+ ): Record<string, AttributeValue> {
33
+ if (!nav) return {};
34
+ const attributes: Record<string, AttributeValue> = {};
35
+ const hints = nav.userAgentData;
36
+ if (hints?.brands && hints.brands.length > 0) {
37
+ attributes["browser.brands"] = hints.brands.map(({ brand, version }) => `${brand} ${version}`);
38
+ }
39
+ if (typeof hints?.platform === "string" && hints.platform !== "") {
40
+ attributes["browser.platform"] = hints.platform;
41
+ }
42
+ if (typeof hints?.mobile === "boolean") attributes["browser.mobile"] = hints.mobile;
43
+ if (typeof nav.language === "string" && nav.language !== "") {
44
+ attributes["browser.language"] = nav.language;
45
+ }
46
+ if (typeof nav.userAgent === "string" && nav.userAgent !== "") {
47
+ attributes[ATTR_USER_AGENT_ORIGINAL] = nav.userAgent;
48
+ }
49
+ return attributes;
50
+ }
51
+
52
+ /**
53
+ * The resource shared by the metrics, logs and traces providers. It holds no
54
+ * `session.id`: that is set on each log record and span instead (see
55
+ * session-processors.ts), because the resource can't follow a session
56
+ * rotation and on metrics it would inflate `target_info`.
57
+ *
58
+ * With `browserAttributes` (the default), it has the browser attributes of
59
+ * the semantic conventions (see `browserAttributes()`), from the global `navigator`. They do not change
60
+ * during the life of a page, thus they fit the resource. The attributes of
61
+ * the config have priority over them.
62
+ */
63
+ export function buildResource(config: ResolvedConfig) {
64
+ return resourceFromAttributes({
65
+ ...(config.browserAttributes
66
+ ? browserAttributes((globalThis as { navigator?: NavigatorLike }).navigator)
67
+ : {}),
68
+ [ATTR_SERVICE_NAME]: config.serviceName,
69
+ [ATTR_SERVICE_VERSION]: config.serviceVersion,
70
+ [ATTR_SERVICE_INSTANCE_ID]: config.serviceInstanceId,
71
+ ...config.resourceAttributes,
72
+ });
73
+ }
@@ -0,0 +1,48 @@
1
+ import type { LogRecordProcessor } from "@opentelemetry/sdk-logs";
2
+ import type { SpanProcessor } from "@opentelemetry/sdk-trace-base";
3
+ import { ATTR_SESSION_ID } from "./constants.js";
4
+
5
+ /** Returns the current session ID; called once per log record or span */
6
+ export type SessionIdReader = () => string;
7
+
8
+ /*
9
+ * The OpenTelemetry Browser SDK's session-processor pattern: `session.id` is
10
+ * an attribute of each log record and span, read as the record is created,
11
+ * not a resource attribute. Resources are fixed for the life of a provider,
12
+ * so a resource `session.id` goes stale when the session rotates, and on the
13
+ * metrics resource it inflates Prometheus `target_info`.
14
+ *
15
+ * A `session.id` the caller set explicitly (e.g. on a `session.end` event
16
+ * for the previous session) is kept.
17
+ */
18
+
19
+ /** Sets `session.id` on each log record as it is emitted */
20
+ export function createSessionLogRecordProcessor(
21
+ getSessionId: SessionIdReader,
22
+ ): 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
+ };
32
+ }
33
+
34
+ /** Sets `session.id` on each span as it starts */
35
+ export function createSessionSpanProcessor(
36
+ getSessionId: SessionIdReader,
37
+ ): 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
+ };
48
+ }