@devopsplaybook.io/otel-utils 1.9.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -62,6 +62,7 @@ span.end();
62
62
  - `startSpan(name, parentSpan?, options?)` — Creates a span and returns the SDK `Span` from `@opentelemetry/sdk-trace`. Span names are sanitized to `[a-zA-Z0-9-_/]`. `parentSpan` accepts any API `Span` (for example from `trace.getSpan(context)` or `trace.wrapSpanContext(...)`), so callers need no cast. When neither `parentSpan` nor `options` is given, the span is `SpanKind.INTERNAL` and carries `http.request.method=BACKEND` and a synthetic `http.route` attribute with the value `${serviceName}-${version}-${sanitizedSpanName}`. Passing a `parentSpan`, an `options` object (e.g. `{ kind: SpanKind.SERVER }`), or both forwards them to the OpenTelemetry SDK instead and skips those synthetic attributes, because the caller then describes the span itself. Generic HTTP dashboards that group by `http.request.method`/`http.route` count these spans as `BACKEND` requests with a synthetic route; this is intentional and consumed by otel-light.
63
63
  - `static updateHttpHeader<T extends object = Record<string, string>>(context, headers?)` — Injects the W3C trace context of `context` into an HTTP headers object for propagation to downstream services, and returns that same object (a new one when omitted). Only `traceparent` and `tracestate` are injected: the propagation context is built from the span alone, so baggage and other active-context values are **not** propagated and an existing `baggage` header is left untouched.
64
64
  - `shutdown()` — Flushes buffered spans and shuts the tracer provider down. Idempotent.
65
+ - `forceFlush()` — Flushes buffered spans to the collector without shutting the provider down; resolves immediately when no collector is configured. Use it at checkpoints in short-lived jobs and serverless handlers.
65
66
 
66
67
  ### StandardLogger
67
68
 
@@ -79,10 +80,11 @@ moduleLog.info("Hello world");
79
80
 
80
81
  **Methods:**
81
82
 
82
- - `initOTel(config)` — Initializes the logger provider and optional OTLP exporter, and registers the provider globally when a logs endpoint is configured and no other logger provider is registered. Returns `Promise<void>`: the first call initializes synchronously; await it when re-initializing, because a previous provider is flushed and shut down first.
83
+ - `initOTel(config)` — Initializes the logger provider and optional OTLP exporter, and registers the provider globally when a logs endpoint is configured and no other logger provider is registered. Returns `Promise<void>`; a previous provider is flushed and shut down first. Queued in call order with `shutdown()` — see [Provider lifecycle](#provider-lifecycle).
83
84
  - `getLogger()` — Returns the underlying OTel `Logger` or `undefined` (also `undefined` after `shutdown()`).
84
85
  - `createModuleLogger(moduleName)` — Creates a `ModuleLogger` scoped to a module name.
85
- - `shutdown()` — Flushes buffered log records and shuts the logger provider down. Idempotent. No-op when no logs endpoint is configured.
86
+ - `shutdown()` — Flushes buffered log records and shuts the logger provider down. Idempotent. No-op when no logs endpoint is configured. Queued in call order with `initOTel()`.
87
+ - `forceFlush()` — Flushes buffered log records to the collector without shutting the provider down; resolves immediately when no logger provider exists. Use it at checkpoints in short-lived jobs and serverless handlers.
86
88
 
87
89
  **Batch tunables and loss window**
88
90
 
@@ -211,6 +213,7 @@ These defaults are unchanged: existing metric names keep working.
211
213
  - `createHistogram(key, options?)` — Creates a `Histogram` named `${serviceName}.${key}`; with `{ unprefixed: true }` the histogram is created exactly as `key`, without the service-name prefix. Options also accept the OTel instrument options (`description`, `unit`, `valueType`, `advice`).
212
214
  - `createObservableGauge(key, callback, descriptionOrOptions?)` — Creates an `ObservableGauge` named `key` with a callback. The third argument is an optional description string or an options object (`description`, `unit`, `valueType`, `advice`).
213
215
  - `shutdown()` — Flushes buffered metrics and shuts the meter provider down. Idempotent.
216
+ - `forceFlush()` — Flushes buffered metrics to the collector without shutting the meter provider down; resolves immediately when no collector is configured. Use it at checkpoints in short-lived jobs and serverless handlers.
214
217
 
215
218
  ## Provider lifecycle
216
219
 
@@ -219,6 +222,7 @@ OpenTelemetry's global API accepts one provider per signal per process, and the
219
222
  - **One provider per signal per process.** The first `StandardTracer`, configured `StandardLogger` and configured `StandardMeter` created in a process each register their provider globally. Global-API calls (`trace.getTracer`, `logs.getLogger`, `metrics.getMeter`) resolve to those first providers until they shut down.
220
223
  - **Additional instances keep working, locally.** A second instance does not replace the global provider: it logs a `console.warn` and still exports through its own provider, with its own `service.name`/`service.version`. Its records/spans/metrics are never attributed to another service.
221
224
  - **Re-initialisation.** Calling `StandardLogger.initOTel()` again on the same instance flushes and shuts down the previous provider (its buffered records are exported), then registers the new one as the global provider if possible. Await the returned promise when re-initializing.
225
+ - **Serialised init/shutdown (`StandardLogger`).** `initOTel()` and `shutdown()` run through one promise queue, in call order, and never interleave. An init queued while a shutdown is in flight waits for it, then creates and registers its provider; a shutdown queued behind an init shuts the provider created by that init. The queue survives validation failures (only the failing operation rejects), and `forceFlush()` is non-terminal: it never changes the lifecycle state or the global registration.
222
226
  - **Shutdown.** `shutdown()` flushes pending telemetry, shuts the provider down and is idempotent. If the instance owns the global provider, it also calls `trace.disable()` / `logs.disable()` / `metrics.disable()`, returning the global API to Noop and allowing a later instance to register again. Shutting down a non-owner leaves the global provider untouched. After `StandardLogger.shutdown()`, `getLogger()` is `undefined`.
223
227
  - **Context propagation.** One `AsyncLocalStorageContextManager` is installed per process on the first `StandardTracer` construction, only when no other context manager is registered. It stays active for the process lifetime (it is never disabled), so re-initialisation keeps working.
224
228
 
@@ -226,19 +230,36 @@ OpenTelemetry's global API accepts one provider per signal per process, and the
226
230
 
227
231
  `StandardTracer`, `StandardLogger` and `StandardMeter` buffer telemetry: `BatchSpanProcessor`, `BatchLogRecordProcessor` and `PeriodicExportingMetricReader` hold data until their next export cycle. On process exit that buffered data would be lost, so flush it on `SIGTERM`/`SIGINT`.
228
232
 
229
- The opt-in `registerShutdownHooks` helper does this for every configured provider and exits the process with code 0 after flushing:
233
+ The opt-in `registerShutdownHooks` helper does this for every configured provider and, by default, exits the process with code 0 once the flush completes or times out:
230
234
 
231
235
  ```typescript
232
236
  import { registerShutdownHooks } from "@devopsplaybook.io/otel-utils";
233
237
 
234
- const cleanup = registerShutdownHooks([tracer, logger, meter]);
238
+ const cleanup = registerShutdownHooks([tracer, logger, meter], {
239
+ signals: ["SIGTERM", "SIGINT"], // default
240
+ timeoutMillis: 10_000, // default
241
+ exit: true, // default
242
+ });
235
243
  // later, if the application manages its own signals:
236
244
  // cleanup();
237
245
  ```
238
246
 
239
- Register it once, with all configured providers. A second signal received while shutting down does not exit or flush again. The returned function only removes the signal listeners.
247
+ Options:
248
+
249
+ - `signals` — signals to listen to, default `["SIGTERM", "SIGINT"]`; duplicates are removed. It replaces the defaults rather than extending them.
250
+ - `timeoutMillis` — upper bound of the flush, default 10 000 ms; non-integer or non-positive values fall back to the default. Keep it below the container's `terminationGracePeriodSeconds` (30 s by default in Kubernetes) and consistent with the providers' export timeouts (30 s SDK default), otherwise the pod is SIGKILLed mid-flush. When it elapses, one `[otel-utils] shutdown timed out after ...` warning is logged and the process continues (or exits with code 0) without waiting for the remaining providers.
251
+ - `exit` — `true` (default) exits with code 0 after the flush or timeout; `false` only flushes and never calls `process.exit`, for applications that own HTTP draining and database shutdown.
252
+
253
+ Signal semantics:
240
254
 
241
- For custom flows, `shutdownAll` flushes every provider and always resolves — a failing provider is reported with `console.warn` and does not block the others:
255
+ - Handlers use `process.on`, not `process.once`. The first signal starts one shutdown; any later `SIGTERM`/`SIGINT` (the same one or the other) is ignored while it runs — no re-flush and no early termination, even when the flush is slow.
256
+ - The listeners are removed when the flush completes (and by the returned cleanup function), so the process regains Node's default signal behaviour. `cleanup()` is idempotent, does not cancel an in-flight flush and removes only the listeners this call registered.
257
+
258
+ Choose the helper that matches who owns the shutdown:
259
+
260
+ - `registerShutdownHooks(providers)` — the library owns the signals and the process exit.
261
+ - `registerShutdownHooks(providers, { exit: false })` — the application owns the shutdown sequence (drain HTTP, close the database, then exit) and uses the helper as one bounded telemetry-flush step; combine it with the returned `cleanup()`.
262
+ - `shutdownAll(providers)` — a fully custom flow: it flushes every provider, has no timeout, always resolves (a failing provider is reported with `console.warn` and does not block the others) and never calls `process.exit`:
242
263
 
243
264
  ```typescript
244
265
  import { shutdownAll } from "@devopsplaybook.io/otel-utils";
@@ -247,6 +268,8 @@ await shutdownAll([tracer, logger, meter]);
247
268
  process.exit(0);
248
269
  ```
249
270
 
271
+ To flush without shutting anything down or exiting — at a checkpoint in a short-lived job or a serverless handler — call `forceFlush()` on the tracer, logger or meter.
272
+
250
273
  Each `shutdown()` flushes pending telemetry to the collector before resolving; the methods are idempotent and can be called even when no collector was configured (they resolve immediately).
251
274
 
252
275
  ## Internal Utilities
@@ -1,16 +1,45 @@
1
1
  export interface ShutdownableInterface {
2
2
  shutdown(): Promise<void>;
3
3
  }
4
+ export interface RegisterShutdownHooksOptions {
5
+ /**
6
+ * Signals that trigger the shutdown. Defaults to `["SIGTERM", "SIGINT"]`.
7
+ * Duplicates are removed.
8
+ */
9
+ signals?: NodeJS.Signals[];
10
+ /**
11
+ * Upper bound of the flush, in milliseconds. Defaults to 10 000 ms; invalid
12
+ * values fall back to the default.
13
+ */
14
+ timeoutMillis?: number;
15
+ /**
16
+ * When `true` (default) the process exits with code 0 once the flush
17
+ * completes or times out. When `false` the providers are flushed without
18
+ * calling `process.exit`, leaving the exit to the application.
19
+ */
20
+ exit?: boolean;
21
+ }
4
22
  /**
5
23
  * Flushes and shuts down every provider, resolving even when one of them
6
- * fails (the failure is reported with `console.warn`).
24
+ * fails (the failure is reported with `console.warn`). There is no timeout:
25
+ * use {@link registerShutdownHooks} for a bounded flush.
7
26
  */
8
27
  export declare function shutdownAll(providers: ReadonlyArray<ShutdownableInterface>): Promise<void>;
9
28
  /**
10
- * Registers one-shot `SIGTERM`/`SIGINT` handlers that flush and shut down all
11
- * providers, then exit the process with code 0.
29
+ * Registers `SIGTERM`/`SIGINT` handlers that flush and shut down all providers.
30
+ *
31
+ * A signal starts one bounded shutdown: further signals (the same one or the
32
+ * other one) are ignored while it runs, so a repeated signal can neither
33
+ * re-flush nor terminate the process mid-flush. The flush is bounded by
34
+ * `timeoutMillis`; when it elapses a warning is logged and the process
35
+ * continues instead of hanging. Listeners are removed when the flush completes
36
+ * and by the returned cleanup function, restoring Node's default signal
37
+ * behaviour.
12
38
  *
13
- * Register once with every configured provider. The returned function removes
14
- * the handlers without shutting anything down.
39
+ * With the default `exit: true` the process exits with code 0 after the flush;
40
+ * with `exit: false` it only flushes, for applications that own their shutdown
41
+ * sequence. Register once with every configured provider. The returned
42
+ * function removes the listeners without shutting anything down; it is
43
+ * idempotent and does not cancel an in-flight flush.
15
44
  */
16
- export declare function registerShutdownHooks(providers: ReadonlyArray<ShutdownableInterface>): () => void;
45
+ export declare function registerShutdownHooks(providers: ReadonlyArray<ShutdownableInterface>, options?: RegisterShutdownHooksOptions): () => void;
@@ -2,35 +2,89 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.shutdownAll = shutdownAll;
4
4
  exports.registerShutdownHooks = registerShutdownHooks;
5
+ const configValidation_1 = require("./utils/configValidation");
6
+ const DEFAULT_SIGNALS = ["SIGTERM", "SIGINT"];
7
+ const DEFAULT_TIMEOUT_MILLIS = 10000;
5
8
  /**
6
9
  * Flushes and shuts down every provider, resolving even when one of them
7
- * fails (the failure is reported with `console.warn`).
10
+ * fails (the failure is reported with `console.warn`). There is no timeout:
11
+ * use {@link registerShutdownHooks} for a bounded flush.
8
12
  */
9
13
  async function shutdownAll(providers) {
10
- await Promise.all(providers.map((provider) => provider.shutdown().catch((error) => {
14
+ await Promise.all(providers.map((provider) => Promise.resolve()
15
+ .then(() => provider.shutdown())
16
+ .catch((error) => {
11
17
  console.warn("[otel-utils] shutdown failed", error);
12
18
  })));
13
19
  }
20
+ function shutdownWithTimeout(providers, timeoutMillis) {
21
+ return new Promise((resolve) => {
22
+ let settled = false;
23
+ let timer;
24
+ const finish = () => {
25
+ if (settled) {
26
+ return;
27
+ }
28
+ settled = true;
29
+ clearTimeout(timer);
30
+ resolve();
31
+ };
32
+ timer = setTimeout(() => {
33
+ if (settled) {
34
+ return;
35
+ }
36
+ settled = true;
37
+ console.warn(`[otel-utils] shutdown timed out after ${timeoutMillis} ms; continuing without waiting for the remaining providers`);
38
+ resolve();
39
+ }, timeoutMillis);
40
+ void shutdownAll(providers).then(finish, finish);
41
+ });
42
+ }
14
43
  /**
15
- * Registers one-shot `SIGTERM`/`SIGINT` handlers that flush and shut down all
16
- * providers, then exit the process with code 0.
44
+ * Registers `SIGTERM`/`SIGINT` handlers that flush and shut down all providers.
45
+ *
46
+ * A signal starts one bounded shutdown: further signals (the same one or the
47
+ * other one) are ignored while it runs, so a repeated signal can neither
48
+ * re-flush nor terminate the process mid-flush. The flush is bounded by
49
+ * `timeoutMillis`; when it elapses a warning is logged and the process
50
+ * continues instead of hanging. Listeners are removed when the flush completes
51
+ * and by the returned cleanup function, restoring Node's default signal
52
+ * behaviour.
17
53
  *
18
- * Register once with every configured provider. The returned function removes
19
- * the handlers without shutting anything down.
54
+ * With the default `exit: true` the process exits with code 0 after the flush;
55
+ * with `exit: false` it only flushes, for applications that own their shutdown
56
+ * sequence. Register once with every configured provider. The returned
57
+ * function removes the listeners without shutting anything down; it is
58
+ * idempotent and does not cancel an in-flight flush.
20
59
  */
21
- function registerShutdownHooks(providers) {
60
+ function registerShutdownHooks(providers, options = {}) {
61
+ var _a, _b;
62
+ const signals = [...new Set((_a = options.signals) !== null && _a !== void 0 ? _a : DEFAULT_SIGNALS)];
63
+ const timeoutMillis = (0, configValidation_1.normalizePositiveInteger)(options.timeoutMillis, DEFAULT_TIMEOUT_MILLIS);
64
+ const exitOnComplete = (_b = options.exit) !== null && _b !== void 0 ? _b : true;
22
65
  let shuttingDown = false;
23
- const onSignal = () => {
66
+ function cleanup() {
67
+ for (const signal of signals) {
68
+ process.removeListener(signal, onSignal);
69
+ }
70
+ }
71
+ function runShutdown() {
72
+ void shutdownWithTimeout(providers, timeoutMillis).then(() => {
73
+ cleanup();
74
+ if (exitOnComplete) {
75
+ process.exit(0);
76
+ }
77
+ });
78
+ }
79
+ function onSignal() {
24
80
  if (shuttingDown) {
25
81
  return;
26
82
  }
27
83
  shuttingDown = true;
28
- void shutdownAll(providers).then(() => process.exit(0));
29
- };
30
- process.once("SIGTERM", onSignal);
31
- process.once("SIGINT", onSignal);
32
- return () => {
33
- process.removeListener("SIGTERM", onSignal);
34
- process.removeListener("SIGINT", onSignal);
35
- };
84
+ runShutdown();
85
+ }
86
+ for (const signal of signals) {
87
+ process.on(signal, onSignal);
88
+ }
89
+ return cleanup;
36
90
  }
@@ -8,12 +8,15 @@ export declare class StandardLogger implements StandardLoggerInterface {
8
8
  private serviceVersion?;
9
9
  private serviceName?;
10
10
  private ownsGlobalProvider;
11
- private shutdownPromise?;
11
+ private operationQueue;
12
12
  private consoleMode;
13
13
  initOTel(config: ConfigOTelInterface): Promise<void>;
14
14
  shutdown(): Promise<void>;
15
+ forceFlush(): Promise<void>;
15
16
  getLogger(): OTelLogger | undefined;
16
17
  createModuleLogger(moduleName: string): ModuleLogger;
18
+ private enqueue;
19
+ private doInitOTel;
17
20
  private registerGlobalProvider;
18
21
  private releaseProvider;
19
22
  }
@@ -12,9 +12,34 @@ const ALREADY_REGISTERED_WARNING = "[otel-utils] A global logger provider is alr
12
12
  class StandardLogger {
13
13
  constructor() {
14
14
  this.ownsGlobalProvider = false;
15
+ this.operationQueue = Promise.resolve();
15
16
  this.consoleMode = "always";
16
17
  }
17
- async initOTel(config) {
18
+ initOTel(config) {
19
+ return this.enqueue(() => this.doInitOTel(config));
20
+ }
21
+ shutdown() {
22
+ return this.enqueue(() => this.releaseProvider());
23
+ }
24
+ forceFlush() {
25
+ var _a;
26
+ var _b;
27
+ return (_b = (_a = this.loggerProvider) === null || _a === void 0 ? void 0 : _a.forceFlush()) !== null && _b !== void 0 ? _b : Promise.resolve();
28
+ }
29
+ getLogger() {
30
+ return this.logger;
31
+ }
32
+ createModuleLogger(moduleName) {
33
+ return new ModuleLogger_1.ModuleLogger(moduleName, this, {
34
+ consoleMode: this.consoleMode,
35
+ });
36
+ }
37
+ enqueue(operation) {
38
+ const result = this.operationQueue.then(operation, operation);
39
+ this.operationQueue = result.then(() => undefined, () => undefined);
40
+ return result;
41
+ }
42
+ async doInitOTel(config) {
18
43
  // Validate before releasing the previous provider: a bad re-init must keep
19
44
  // the working provider in place.
20
45
  (0, configValidation_1.validateServiceIdentity)(config);
@@ -23,7 +48,6 @@ class StandardLogger {
23
48
  if (this.loggerProvider) {
24
49
  await this.releaseProvider();
25
50
  }
26
- this.shutdownPromise = undefined;
27
51
  this.serviceName = config.SERVICE_ID;
28
52
  this.serviceVersion = config.VERSION;
29
53
  if (!config.OPENTELEMETRY_COLLECTOR_HTTP_LOGS) {
@@ -53,20 +77,6 @@ class StandardLogger {
53
77
  this.logger = this.loggerProvider.getLogger(`${this.serviceName}:${this.serviceVersion}`);
54
78
  this.registerGlobalProvider();
55
79
  }
56
- shutdown() {
57
- if (!this.shutdownPromise) {
58
- this.shutdownPromise = this.releaseProvider();
59
- }
60
- return this.shutdownPromise;
61
- }
62
- getLogger() {
63
- return this.logger;
64
- }
65
- createModuleLogger(moduleName) {
66
- return new ModuleLogger_1.ModuleLogger(moduleName, this, {
67
- consoleMode: this.consoleMode,
68
- });
69
- }
70
80
  registerGlobalProvider() {
71
81
  if (globalLoggerProvider) {
72
82
  if (globalLoggerProvider === api_1.logs.getLoggerProvider()) {
@@ -22,6 +22,7 @@ export declare class StandardMeter {
22
22
  private shutdownPromise?;
23
23
  constructor(config: ConfigOTelInterface);
24
24
  shutdown(): Promise<void>;
25
+ forceFlush(): Promise<void>;
25
26
  createCounter(key: string, options?: MetricOptions): Counter;
26
27
  createUpDownCounter(key: string, options?: MetricOptions): UpDownCounter;
27
28
  createHistogram(key: string, options?: StandardMeterCreateHistogramOptions): Histogram;
@@ -53,6 +53,9 @@ class StandardMeter {
53
53
  }
54
54
  return this.shutdownPromise;
55
55
  }
56
+ forceFlush() {
57
+ return this.meterProvider.forceFlush();
58
+ }
56
59
  createCounter(key, options) {
57
60
  return this.meter.createCounter(`${this.serviceName}.${key}`, options);
58
61
  }
@@ -26,6 +26,7 @@ export declare class StandardTracer {
26
26
  private shutdownPromise?;
27
27
  constructor(config: ConfigOTelInterface);
28
28
  shutdown(): Promise<void>;
29
+ forceFlush(): Promise<void>;
29
30
  startSpan(name: string, parentSpan?: ApiSpan, options?: StandardTracerStartSpanOptions): Span;
30
31
  /**
31
32
  * Injects the W3C trace context of `context` into `headers` and returns it.
@@ -55,6 +55,9 @@ class StandardTracer {
55
55
  }
56
56
  return this.shutdownPromise;
57
57
  }
58
+ forceFlush() {
59
+ return this.traceProvider.forceFlush();
60
+ }
58
61
  startSpan(name, parentSpan, options) {
59
62
  const sanitizedName = name.replace(StandardTracer.SPAN_NAME_SANITIZE_RE, "_");
60
63
  if (parentSpan) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devopsplaybook.io/otel-utils",
3
- "version": "1.9.1",
3
+ "version": "1.10.0",
4
4
  "description": "Utility to simplify integration with Open Telemetry",
5
5
  "keywords": [
6
6
  "Open",