@mark1russell7/otel-ts 0.7.0 → 0.7.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/src/init.ts CHANGED
@@ -94,6 +94,40 @@ export function initWith(
94
94
  ? claimContextRegistration("init()")
95
95
  : undefined;
96
96
 
97
+ // The providers that started, so a failure after the claim can stop them
98
+ const providers: Provider[] = [];
99
+ try {
100
+ return startInstance(resolved, contextManager, releaseRegistration, providers);
101
+ } catch (error) {
102
+ // A part failed after the claim. Stop the parts that started, and give
103
+ // back the claim: else no later init() or startNodeTelemetry() of the
104
+ // program could start, and no instance could call shutdown()
105
+ void Promise.allSettled(providers.map((p) => p.shutdown()));
106
+ releaseContext(releaseRegistration);
107
+ throw error;
108
+ }
109
+ }
110
+
111
+ /** A provider of a signal that init() started */
112
+ type Provider = { forceFlush(): Promise<void>; shutdown(): Promise<void> };
113
+
114
+ /**
115
+ * Remove the globals of the context and give back the claim, so a next
116
+ * init() registers its own. Without a claim, init() registered nothing.
117
+ */
118
+ function releaseContext(releaseRegistration: (() => void) | undefined): void {
119
+ if (!releaseRegistration) return;
120
+ for (const api of [trace, propagation, context]) api.disable();
121
+ releaseRegistration();
122
+ }
123
+
124
+ /** The parts of init() after the claim. Each provider that starts goes into `providers`. */
125
+ function startInstance(
126
+ resolved: ResolvedConfig,
127
+ contextManager: ReturnType<typeof createContextManager> | undefined,
128
+ releaseRegistration: (() => void) | undefined,
129
+ providers: Provider[],
130
+ ): OtelTsInstance {
97
131
  // Read again for every log record and span, so they follow rotations
98
132
  const getSessionId = createSessionIdReader(resolved.sessionTracking);
99
133
 
@@ -102,10 +136,6 @@ export function initWith(
102
136
 
103
137
  // One resource, so metrics, logs and traces share the service.instance.id
104
138
  const resource = buildResource(resolved);
105
- const providers: Array<{
106
- forceFlush(): Promise<void>;
107
- shutdown(): Promise<void>;
108
- }> = [];
109
139
 
110
140
  // Faro instruments the page (errors, web vitals, views) and needs a DOM.
111
141
  // Without a collector URL it has nowhere to send data and logs an error.
@@ -154,11 +184,7 @@ export function initWith(
154
184
  shutdownPromise ??= (async () => {
155
185
  removeLifecycleHandlers();
156
186
  await Promise.allSettled(providers.map((p) => p.shutdown()));
157
- if (releaseRegistration) {
158
- // Remove the globals of the context, so a next init() registers its own
159
- for (const api of [trace, propagation, context]) api.disable();
160
- releaseRegistration();
161
- }
187
+ releaseContext(releaseRegistration);
162
188
  })();
163
189
  }
164
190
  return shutdownPromise;
package/src/lag.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The OpenTelemetry dependencies of the monitors of `@mark1russell7/lag`, from one instance of
3
+ * otel-ts (decision D7, roadmap C15). Without this entry, each app connects the meter, the logger,
4
+ * the events, the spans and the flush by hand.
5
+ *
6
+ * The adapters are the adapters of lag. This entry only gives them the providers of the instance.
7
+ * `@mark1russell7/lag` is an optional peer dependency: only an app that imports this entry needs it.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { init } from "@mark1russell7/otel-ts";
12
+ * import { lagDeps } from "@mark1russell7/otel-ts/lag";
13
+ * import { createBrowserDeps, setupAllMonitors } from "@mark1russell7/lag";
14
+ *
15
+ * const otel = init({ serviceName: "checkout-web" });
16
+ * const lag = lagDeps(otel);
17
+ * const monitors = setupAllMonitors(createBrowserDeps(window, lag));
18
+ * lag.connect(monitors);
19
+ * ```
20
+ *
21
+ * @packageDocumentation
22
+ */
23
+ import { ROOT_CONTEXT, trace, type Tracer } from "@opentelemetry/api";
24
+ import {
25
+ createOtelEventSink,
26
+ createOtelLoggerAdapter,
27
+ createOtelSpanSink,
28
+ type EventSink,
29
+ type Logger,
30
+ type Meter,
31
+ type SpanSink,
32
+ } from "@mark1russell7/lag";
33
+ import type { OtelTsInstance } from "./types.js";
34
+
35
+ /** The options of `lagDeps` */
36
+ export interface LagDepsOptions {
37
+ /** The name of the meter, the logger and the tracer. Default: `lag`. */
38
+ name?: string;
39
+ /** The tracer of the spans of the monitors. Default: the global tracer of `name`. */
40
+ tracer?: Tracer;
41
+ }
42
+
43
+ /** The monitors of lag, as `connect` needs them: the result of `setupAllMonitors()` fits. */
44
+ export interface LagFlushTarget {
45
+ flush(): void;
46
+ }
47
+
48
+ /** The OpenTelemetry dependencies of the monitors of lag. Give them to `createBrowserDeps()` of lag. */
49
+ export interface LagDeps {
50
+ /** The meter of the instance, with the name of the options */
51
+ readonly meter: Meter;
52
+ /** The diagnostics of lag, as log records of the instance */
53
+ readonly logger: Logger;
54
+ /** The events of the monitors, as log records with `eventName` */
55
+ readonly events: EventSink;
56
+ /** The spans of the monitors, through the tracer of the options */
57
+ readonly spans: SpanSink;
58
+ /**
59
+ * Record the values that the monitors keep until a checkpoint before each flush of the instance.
60
+ * Thus the final export of a page has the final values of the page view.
61
+ *
62
+ * @returns A function that removes the connection
63
+ */
64
+ connect(monitors: LagFlushTarget): () => void;
65
+ }
66
+
67
+ /**
68
+ * The meter, the logger, the event sink and the span sink of the monitors of lag, from one instance
69
+ * of otel-ts. `connect()` records the values of the monitors before each flush of the instance.
70
+ */
71
+ export function lagDeps(
72
+ instance: Pick<OtelTsInstance, "getMeter" | "getLogger" | "onBeforeFlush">,
73
+ options: LagDepsOptions = {},
74
+ ): LagDeps {
75
+ const name = options.name ?? "lag";
76
+ const logger = instance.getLogger(name);
77
+ return {
78
+ meter: instance.getMeter(name),
79
+ logger: createOtelLoggerAdapter(logger),
80
+ events: createOtelEventSink(logger),
81
+ spans: createOtelSpanSink(options.tracer ?? trace.getTracer(name), { trace, ROOT_CONTEXT }),
82
+ connect: (monitors) => instance.onBeforeFlush(() => monitors.flush()),
83
+ };
84
+ }
@@ -51,7 +51,9 @@ export function exporterNames(signal: OtlpSignal, env: Env): ExporterName[] {
51
51
  */
52
52
  export function otlpProtocol(signal: OtlpSignal, env: Env): OtlpProtocol {
53
53
  const variable = `OTEL_EXPORTER_OTLP_${signal.toUpperCase()}_PROTOCOL`;
54
- const value = (env[variable] ?? env["OTEL_EXPORTER_OTLP_PROTOCOL"] ?? "http/protobuf").trim();
54
+ // An empty variable is not set, as in the specification of the variables
55
+ const set = (name: string): string | undefined => env[name]?.trim() || undefined;
56
+ const value = set(variable) ?? set("OTEL_EXPORTER_OTLP_PROTOCOL") ?? "http/protobuf";
55
57
  if (value === "http/protobuf" || value === "http/json") return value;
56
58
  throw new RangeError(`the OTLP protocol of ${signal} is "${value}": otel-ts sends "http/protobuf" or "http/json". For grpc, give the exporter in the options.`);
57
59
  }
package/src/node.ts CHANGED
@@ -84,6 +84,9 @@ export interface NodeTelemetryOptions {
84
84
  /** The signals that stop the SDK when `stopOnSignals` is true */
85
85
  const STOP_SIGNALS = ["SIGTERM", "SIGINT"] as const;
86
86
 
87
+ /** The signal listeners of otel-ts. They are not listeners of the service. */
88
+ const OWN_LISTENERS = new Set<Function>();
89
+
87
90
  /** The result of `startNodeTelemetry()` */
88
91
  export interface NodeTelemetry {
89
92
  /** True when export is on */
@@ -104,12 +107,13 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
104
107
  const release = claimContextRegistration("startNodeTelemetry()");
105
108
 
106
109
  let esmHook = false;
107
- if (options.importMetaUrl) {
108
- register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
109
- esmHook = true;
110
- }
111
110
  let sdk: NodeSDK;
112
111
  try {
112
+ // In the try too: a hook that does not resolve gives back the claim
113
+ if (options.importMetaUrl) {
114
+ register("@opentelemetry/instrumentation/hook.mjs", options.importMetaUrl);
115
+ esmHook = true;
116
+ }
113
117
  // With export off: no processor and no reader, so nothing leaves the process
114
118
  const exports: Partial<NodeSDKConfiguration> = enabled
115
119
  ? {
@@ -133,10 +137,20 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
133
137
  throw error;
134
138
  }
135
139
 
140
+ // The signal listeners of this start, removed at the stop
141
+ const listeners: Array<[NodeJS.Signals, () => void]> = [];
136
142
  // One stop: a second call waits for the flush of the first
137
143
  let stopping: Promise<void> | undefined;
138
- const shutdown = (): Promise<void> =>
139
- (stopping ??= sdk
144
+ const shutdown = (): Promise<void> => {
145
+ if (stopping) return stopping;
146
+ // Before, the listeners stayed after the stop. At a signal after a new start, the
147
+ // listener of the new start counted the old one as a listener of the service, and the
148
+ // old one ended the process before the new SDK flushed.
149
+ for (const [signal, listener] of listeners) {
150
+ process.removeListener(signal, listener);
151
+ OWN_LISTENERS.delete(listener);
152
+ }
153
+ return (stopping = sdk
140
154
  .shutdown()
141
155
  .catch(() => {
142
156
  // a flush that fails at the stop loses its spans, and nothing else
@@ -146,19 +160,23 @@ export function startNodeTelemetry(options: NodeTelemetryOptions = {}): NodeTele
146
160
  for (const api of [trace, metrics, logs, propagation, context]) api.disable();
147
161
  release();
148
162
  }));
163
+ };
149
164
  if (options.stopOnSignals ?? true) {
150
165
  for (const signal of STOP_SIGNALS) {
151
- // First in the list, so it sees each listener of the service before that listener runs
152
- process.prependOnceListener(signal, () => {
166
+ const listener = (): void => {
153
167
  // A listener for a signal removes the default action of Node.js, which ends the
154
168
  // process. This listener is gone now. When the service has no listener of its own,
155
169
  // raise the signal again after the flush: the default action then ends the process.
156
170
  // Before, a service without a listener continued to run after SIGTERM or SIGINT.
157
- const serviceListens = process.listenerCount(signal) > 0;
171
+ const serviceListens = process.listeners(signal).some((other) => !OWN_LISTENERS.has(other));
158
172
  void shutdown().finally(() => {
159
173
  if (!serviceListens) process.kill(process.pid, signal);
160
174
  });
161
- });
175
+ };
176
+ listeners.push([signal, listener]);
177
+ OWN_LISTENERS.add(listener);
178
+ // First in the list, so it sees each listener of the service before that listener runs
179
+ process.prependOnceListener(signal, listener);
162
180
  }
163
181
  }
164
182
  return { enabled, esmHook, shutdown };
package/src/trace-echo.ts CHANGED
@@ -8,23 +8,49 @@
8
8
  *
9
9
  * @packageDocumentation
10
10
  */
11
- import { context, defaultTextMapGetter, propagation, ROOT_CONTEXT, SpanKind, SpanStatusCode, trace, type Attributes, type Tracer } from "@opentelemetry/api";
11
+ import {
12
+ context,
13
+ defaultTextMapGetter,
14
+ isSpanContextValid,
15
+ propagation,
16
+ ROOT_CONTEXT,
17
+ SpanKind,
18
+ SpanStatusCode,
19
+ trace,
20
+ type Attributes,
21
+ type Context,
22
+ type Tracer,
23
+ } from "@opentelemetry/api";
12
24
  import { W3CTraceContextPropagator } from "@opentelemetry/core";
13
25
 
14
- /** The W3C propagator of runInRemoteTrace: it reads the traceparent also when no global propagator is set. */
26
+ /** The W3C propagator of this module: it reads the traceparent also when no global propagator is set. */
15
27
  const W3C = new W3CTraceContextPropagator();
16
28
 
17
- const TRACEPARENT = /^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/;
29
+ /**
30
+ * The remote parent of a W3C `traceparent`, or undefined when the value is not a valid traceparent. The check is
31
+ * `isSpanContextValid` of `@opentelemetry/api`: a trace id or a span id of only zeros is not valid.
32
+ */
33
+ function remoteParent(traceparent: unknown): Context | undefined {
34
+ if (typeof traceparent !== "string") return undefined;
35
+ const parent = W3C.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
36
+ const spanContext = trace.getSpanContext(parent);
37
+ return spanContext && isSpanContextValid(spanContext) ? parent : undefined;
38
+ }
18
39
 
19
40
  /**
20
41
  * The W3C trace context to pass on: the context of the active span when the
21
- * SDK operates, else the `traceparent` header of the request.
42
+ * SDK operates, else the `traceparent` header of the request. The header comes
43
+ * back in the W3C form of version `00`.
22
44
  */
23
45
  export function outgoingTraceparent(header: unknown): string | undefined {
24
46
  const carrier: Record<string, string> = {};
25
47
  propagation.inject(context.active(), carrier);
26
- const value = carrier["traceparent"] ?? (typeof header === "string" ? header : undefined);
27
- return value && TRACEPARENT.test(value) ? value : undefined;
48
+ const parent = remoteParent(carrier["traceparent"]) ?? remoteParent(header);
49
+ const spanContext = parent && trace.getSpanContext(parent);
50
+ if (!spanContext) return undefined;
51
+ // Not W3C.inject: in core 2.12 it writes the flags 0x10 to 0xff with three digits ("0ff").
52
+ const flags = (spanContext.traceFlags & 0xff).toString(16).padStart(2, "0");
53
+ return `00-${spanContext.traceId}-${spanContext.spanId}-${flags}`;
28
54
  }
29
55
 
30
56
  /** A store of the trace contexts of the writes, until their echoes arrive */
@@ -103,8 +129,8 @@ export interface RemoteTraceOptions {
103
129
  * ```
104
130
  */
105
131
  export function runInRemoteTrace<T>(traceparent: string | undefined, fn: () => T, options: RemoteTraceOptions = {}): T {
106
- if (!traceparent || !TRACEPARENT.test(traceparent)) return fn();
107
- const parent = W3C.extract(ROOT_CONTEXT, { traceparent }, defaultTextMapGetter);
132
+ const parent = remoteParent(traceparent);
133
+ if (!parent) return fn();
108
134
  const tracer = options.tracer ?? trace.getTracer("@mark1russell7/otel-ts");
109
135
  const span = tracer.startSpan(options.name ?? "remote.apply", { kind: SpanKind.CONSUMER, ...(options.attributes ? { attributes: options.attributes } : {}) }, parent);
110
136
  const fail = (error: unknown): void => {