@bymax-one/nest-telemetry 1.0.2 → 1.0.3

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/CHANGELOG.md CHANGED
@@ -8,6 +8,59 @@ The `release.yml` workflow extracts the section matching the pushed `vX.Y.Z` tag
8
8
  as the GitHub Release body, so each released version needs a matching `## [X.Y.Z]`
9
9
  heading here.
10
10
 
11
+ ## [1.0.3] - 2026-11-14
12
+
13
+ ### Added
14
+
15
+ - **`shutdownTimeoutMs`** on `TelemetryOptions`: the longest `shutdown()` and `shutdownTelemetry()` wait for the
16
+ final flush, in milliseconds. It defaults to 5000. A value that is not a finite number above zero, or is above
17
+ 120000, means the default. When the flush has not finished by then, shutdown emits
18
+ `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves; the flush keeps running in the background and a failure after
19
+ the deadline is dropped. Spans still queued at that point may be lost.
20
+ - `BYMAX_TELEMETRY_EXPORT_FAILED`: a span export failed, so the batch was dropped. The warning names the
21
+ exporter and a short upper-case error code (`UNKNOWN` when there is none), never the payload, the endpoint or
22
+ the error message, and repeats at most once a minute. Before, a collector that was down left the application
23
+ silent.
24
+ - **A bound `TELEMETRY_LOGGER` now receives the two runtime warnings.** `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` is
25
+ reported through `errorStructured` under `TELEMETRY_SHUTDOWN_TIMEOUT_KEY` (`TRACING_SHUTDOWN_TIMEOUT`), and
26
+ `BYMAX_TELEMETRY_EXPORT_FAILED` through the optional `warnStructured` under `TELEMETRY_EXPORT_FAILED_KEY`
27
+ (`TRACING_EXPORT_FAILED`), with the exporter kind and the error code as metadata and never a message, an
28
+ endpoint or a payload. With no logger bound, or a logger without the method, they stay process warnings,
29
+ unchanged. Both keys are exported from `./nest`.
30
+ - A **Production** section in the README with measured, scoped figures for sampling, TLS to the collector, a
31
+ collector that is down, CPU, memory and the optional `--max-semi-space-size` lever. "What This Library Does
32
+ NOT Do" says that log records forwarded through `OTEL_LOGS_EXPORTER` are not redacted by this library.
33
+
34
+ ### Changed
35
+
36
+ - **`ignorePaths` never ignores a path longer than 2,048 characters**, and the patterns are not run against it,
37
+ so the request keeps its span. Before, the patterns ran against a path of any length. The query is cut first,
38
+ so only the path counts. The cap does not bound a pattern with nested quantifiers on a short path, so anchor
39
+ patterns with no nested quantifiers.
40
+ - **A down collector now ends shutdown at the deadline with a warning, where it used to reject.** Against a
41
+ closed port, shutdown took 7 seconds before this release and rejected with the connection error. The
42
+ exporter's retries outlast the 5-second default, so shutdown now resolves with
43
+ `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT`.
44
+
45
+ ### Apply to a derived backend
46
+
47
+ The declarations gained `shutdownTimeoutMs`, two exported log keys and an optional `warnStructured` on the logger shape; a derived backend acts on these behaviours:
48
+
49
+ 1. A caller that branches on the rejection of `shutdown()` or `shutdownTelemetry()` to detect a collector that
50
+ is down now has to read the `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and `BYMAX_TELEMETRY_EXPORT_FAILED`
51
+ warnings instead, or set `shutdownTimeoutMs` above the time the exporter needs to give up. Measured against a
52
+ closed port, a deadline of 5000 ms resolved at 5002 ms with the warning, and a deadline of 20000 ms rejected
53
+ with the connection error after 7.8 s. A collector that accepts a connection and never answers took 10
54
+ seconds, the exporter's own timeout.
55
+ 2. Set `shutdownTimeoutMs` to fit the termination grace period of the platform: a shutdown that waits longer
56
+ than the grace period is killed before it finishes.
57
+ 3. A host on `TelemetryModule` that binds `TELEMETRY_LOGGER` now gets a structured entry for a down collector.
58
+ Alert on `TRACING_SHUTDOWN_TIMEOUT` and `TRACING_EXPORT_FAILED`; the first replaces the rejection a down
59
+ collector used to cause at shutdown. A logger that should receive the export failure needs a
60
+ `warnStructured(logKey, message, userId, metadata)` method.
61
+ 4. A route that `ignorePaths` was ignoring with a path over 2,048 characters now produces a span. Anchor the
62
+ patterns, with no nested quantifiers.
63
+
11
64
  ## [1.0.2] - 2026-11-13
12
65
 
13
66
  ### Security
@@ -113,6 +166,7 @@ First release.
113
166
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
114
167
  application, with planted secrets absent from the exported body and negative controls.
115
168
 
169
+ [1.0.3]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.3
116
170
  [1.0.2]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.2
117
171
  [1.0.1]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.1
118
172
  [1.0.0]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.0
package/README.md CHANGED
@@ -81,11 +81,11 @@ Install it with the OpenTelemetry peers you use: the command is in [Quick Start]
81
81
 
82
82
  One package, separate entry points. Import only what your app needs:
83
83
 
84
- | Subpath | Import | Purpose | Dependencies |
85
- | ------------ | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | :-----------------: |
86
- | **SDK** | `@bymax-one/nest-telemetry` | `startTelemetry`, `shutdownTelemetry`, `ignorePaths`, `DEFAULT_REDACTED_QUERY_PARAMS`, types | OpenTelemetry peers |
87
- | **Register** | `@bymax-one/nest-telemetry/register` | The preload for `node --import`; importing it runs it, and it exports nothing | OpenTelemetry peers |
88
- | **Nest** | `@bymax-one/nest-telemetry/nest` | `TelemetryModule`, `TelemetryShutdownHook`, `TELEMETRY_LOGGER`, `TELEMETRY_FLUSH_FAILED_KEY`, `ITelemetryErrorLogger` (type) | NestJS 11 |
84
+ | Subpath | Import | Purpose | Dependencies |
85
+ | ------------ | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :-----------------: |
86
+ | **SDK** | `@bymax-one/nest-telemetry` | `startTelemetry`, `shutdownTelemetry`, `ignorePaths`, `DEFAULT_REDACTED_QUERY_PARAMS`, types | OpenTelemetry peers |
87
+ | **Register** | `@bymax-one/nest-telemetry/register` | The preload for `node --import`; importing it runs it, and it exports nothing | OpenTelemetry peers |
88
+ | **Nest** | `@bymax-one/nest-telemetry/nest` | `TelemetryModule`, `TelemetryShutdownHook`, `TELEMETRY_LOGGER`, `TELEMETRY_FLUSH_FAILED_KEY`, `TELEMETRY_SHUTDOWN_TIMEOUT_KEY`, `TELEMETRY_EXPORT_FAILED_KEY`, `ITelemetryErrorLogger` (type) | NestJS 11 |
89
89
 
90
90
  The SDK entry and `./register` import no `@nestjs/*` package; only `./nest` does. Requiring `./register` from CommonJS throws and names `node --import`.
91
91
 
@@ -165,20 +165,21 @@ This package installs no signal handler and shows none, because handling signals
165
165
 
166
166
  Every field is the host's policy, and none is required.
167
167
 
168
- | Option | Default | What it does |
169
- | -------------------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
170
- | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
171
- | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
172
- | `serviceVersion` | none | The service version. |
173
- | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
174
- | `instrumentations.fs` | `false` | File-system instrumentation. |
175
- | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether pino's records are forwarded to the OpenTelemetry logs pipeline. |
176
- | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
177
- | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
178
- | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
179
- | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
180
- | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args` and `process.command_line` in the resource. Literal `true`. Warns. |
181
- | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
168
+ | Option | Default | What it does |
169
+ | -------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
170
+ | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
171
+ | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
172
+ | `serviceVersion` | none | The service version. |
173
+ | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
174
+ | `instrumentations.fs` | `false` | File-system instrumentation. |
175
+ | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether pino's records are forwarded to the OpenTelemetry logs pipeline. |
176
+ | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
177
+ | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
178
+ | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
179
+ | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
180
+ | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args` and `process.command_line` in the resource. Literal `true`. Warns. |
181
+ | `shutdownTimeoutMs` | `5000` | The longest shutdown waits for the final flush. Past it, shutdown warns and resolves. A value that is not a finite number above zero, or is above `120000`, means the default. |
182
+ | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
182
183
 
183
184
  ### Environment variables
184
185
 
@@ -204,14 +205,16 @@ The OpenTelemetry SDK reads these itself, and the library never touches them: `O
204
205
 
205
206
  The start emits these warnings:
206
207
 
207
- | Code | Meaning |
208
- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
209
- | `BYMAX_TELEMETRY_START_FAILED` | The SDK could not start (a peer is missing, or the SDK threw). Tracing is off. |
210
- | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. |
211
- | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
212
- | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
213
- | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any defined option counts, `env` included. |
214
- | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
208
+ | Code | Meaning |
209
+ | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
210
+ | `BYMAX_TELEMETRY_START_FAILED` | The SDK could not start (a peer is missing, or the SDK threw). Tracing is off. |
211
+ | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. |
212
+ | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
213
+ | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
214
+ | `BYMAX_TELEMETRY_OPTIONS_IGNORED` | A `startTelemetry` call reached an SDK that was already running, so its options were ignored, or `enabled: false` did not stop it. Any defined option counts, `env` included. |
215
+ | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
216
+ | `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` | The final flush did not finish within `shutdownTimeoutMs`. Shutdown resolved without it, and spans still queued may be lost. With `TelemetryModule` and a bound `TELEMETRY_LOGGER`, it is reported through `errorStructured` under `TRACING_SHUTDOWN_TIMEOUT` instead. |
217
+ | `BYMAX_TELEMETRY_EXPORT_FAILED` | A span export failed, so the batch was dropped. The warning names the exporter and a short error code, never the payload or the endpoint, and repeats at most once a minute. With `TelemetryModule` and a bound `TELEMETRY_LOGGER` that has `warnStructured`, it is reported through it under `TRACING_EXPORT_FAILED` instead. |
215
218
 
216
219
  The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
217
220
 
@@ -223,12 +226,25 @@ The programmatic `startTelemetry` keeps its rejection when the SDK cannot start,
223
226
 
224
227
  ### Flushing
225
228
 
226
- Awaiting `shutdown()` or `shutdownTelemetry()` means the spans were exported, whoever started the flush: overlapping callers wait for the same flush, and a shutdown that arrives while the SDK is still starting waits for the start and then stops what it built. A flush the collector refuses is reported, never thrown into your shutdown path, by the Nest module; the programmatic functions reject, so their caller decides.
229
+ Awaiting `shutdown()` or `shutdownTelemetry()` means the spans were exported, whoever started the flush, unless the deadline below passed first: overlapping callers wait for the same flush, and a shutdown that arrives while the SDK is still starting waits for the start and then stops what it built. A flush the collector refuses is reported, never thrown into your shutdown path, by the Nest module; the programmatic functions reject, so their caller decides.
230
+
231
+ The wait is bounded. A collector that accepts a connection and never answers would otherwise hold shutdown for the exporter's own timeout, ten seconds by default, so a flush that has not finished within `shutdownTimeoutMs` (5 seconds unless set, at most 120 seconds) stops holding the caller: shutdown emits `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves. The flush keeps running in the background and a failure after the deadline is dropped. Spans still queued at that point may be lost.
227
232
 
228
233
  A start after a shutdown in the same process is refused: `startTelemetry` rejects, with an error that says to start once per process (in a test suite, once in a global setup), and the process emits `BYMAX_TELEMETRY_RESTART_UNSUPPORTED`. Auto-instrumented spans can never resume after a shutdown, because the modules the first start instrumented are already patched against its tracer provider; spans created through the API could, but a half-working restart is refused on purpose. Measured with an in-process HTTP request and one manual span per run: after a restart that released the API globals, the manual span was exported and the HTTP spans were not. The preload turns the refusal into a `BYMAX_TELEMETRY_START_FAILED` warning and the application still boots.
229
234
 
230
235
  ---
231
236
 
237
+ ## 🏭 Production
238
+
239
+ Every figure here was measured on one laptop, with Node 24 and a handler that does nothing but answer. Read them as orders of magnitude for your own measurement to confirm, not as promises.
240
+
241
+ - **Sampling.** The default samples every trace. For high traffic set `OTEL_TRACES_SAMPLER=parentbased_traceidratio` and `OTEL_TRACES_SAMPLER_ARG=0.1`. Of 2,000 spans created in one run each, the default exported all of them, a ratio of `0.1` exported 210 and a ratio of `0.01` exported 25.
242
+ - **TLS to the collector.** Against a collector whose certificate Node does not trust, every export failed with `self-signed certificate`. Setting `OTEL_EXPORTER_OTLP_CERTIFICATE` to the CA file, or `NODE_EXTRA_CA_CERTS`, exported all 2,000 spans in the same setup.
243
+ - **A collector that is down.** The batch is dropped and the library emits `BYMAX_TELEMETRY_EXPORT_FAILED`, at most once a minute. Shutdown stops waiting at `shutdownTimeoutMs`, 5 seconds by default. Before that deadline existed, shutdown against a closed port took 7,048 ms and 7,214 ms in two runs.
244
+ - **CPU.** One process, 4 runs per mode, median CPU time per request: 25 µs without the library, 26 µs with it loaded and disabled, 58 µs with a healthy collector (range 35 to 66) and 43 µs with the collector down (range 26 to 65). The extra cost in that handler is roughly 10 to 40 µs per request, and a handler that does real I/O dilutes it. The same configuration varied by up to a factor of two between runs.
245
+ - **Memory.** After 10 seconds idle, RSS was 61 to 63 MB without the library and with it disabled, 83 to 95 MB with a healthy collector and 142 to 160 MB with the collector unreachable. Under sustained load with the collector unreachable, the default settings reached between about 195 and 310 MB in one 90-second run.
246
+ - **Small containers.** `node --max-semi-space-size=8` is an optional V8 lever that shrinks the young generation. Under the same unreachable-collector load, RSS had a median of 138 MB (maximum 158) against about 195 to 310 MB for the default settings. The memory figures are one run each, so they are noisy, and a setting of 4 did not do better than 8 (RSS levelled at about 220 MB). At 1,000 requests per second against an unreachable collector, p99 latency over three runs each was 3.6 to 7.3 ms with the default settings and 4.8 to 6.8 ms with 8, so no cost showed at that load. The extra memory with the collector down is most likely churn from failed exports, which was not measured separately.
247
+
232
248
  ## 🔄 OpenTelemetry Versions
233
249
 
234
250
  Every `@opentelemetry/*` package is an optional peer. The `0.x` packages break between minors, and `sdk-node` pins its own dependencies to exact versions, so the ranges here name only the generation the tests run against:
@@ -258,6 +274,7 @@ A caret on a `0.x` version allows patch releases only, so each OpenTelemetry min
258
274
  | HTTP spans but no Redis spans | `ioredis` commands are traced under an active span only, and the client must be loaded after the preload. |
259
275
  | Metrics or logs missing | They are off unless `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` names an exporter. |
260
276
  | The last spans of another module are lost when the application closes | List `TelemetryModule` first in the application module's imports, so it closes last. |
277
+ | No spans arrive and nothing else is logged | `BYMAX_TELEMETRY_EXPORT_FAILED`: the collector did not accept the export. Check the endpoint in `OTEL_EXPORTER_OTLP_ENDPOINT` and that the collector is reachable. |
261
278
  | The last spans are lost on `SIGTERM` | Call `app.enableShutdownHooks()` in Nest, or `shutdownTelemetry()` from your own shutdown path. |
262
279
  | A query string still appears in a span | It is on an attribute other than `url.query`, `url.full`, `http.url` or `http.target`: see [What This Library Does NOT Do](#-what-this-library-does-not-do). |
263
280
 
@@ -361,19 +378,19 @@ pnpm check:runtime # packed-tarball consumer proofs
361
378
 
362
379
  ### SDK: `@bymax-one/nest-telemetry`
363
380
 
364
- | Export | Signature | Purpose |
365
- | ------------------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
366
- | `startTelemetry` | `(options?: TelemetryOptions) => Promise<TelemetryHandle>` | Assembles and starts the SDK; returns the running handle when one exists; rejects when the SDK cannot start or was already shut down in this process |
367
- | `shutdownTelemetry` | `() => Promise<void>` | Waits for a start in progress, then flushes and stops the SDK; resolves at once when none was started |
368
- | `ignorePaths` | `(patterns: readonly RegExp[]) => (request) => boolean` | Predicate for `ignoreIncomingRequest`: matches the request path with its query cut; a request with no target is not matched |
369
- | `DEFAULT_REDACTED_QUERY_PARAMS` | `readonly string[]` | The credential-parameter list redacted from outgoing request URLs |
370
- | `TelemetryOptions` | type | The options of `startTelemetry` ([Configuration](#-configuration)) |
371
- | `TelemetryHandle` | type | `{ enabled: boolean, shutdown(): Promise<void> }` |
372
- | `UnsafeOptions` | type | The literal-`true` redaction opt-outs |
373
- | `InstrumentationOptions` | type | `fs`, `sendLogs` and `overrides` |
374
- | `IncomingRequestTarget` | type | What an incoming-request predicate sees: the request `url` |
381
+ | Export | Signature | Purpose |
382
+ | ------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
383
+ | `startTelemetry` | `(options?: TelemetryOptions) => Promise<TelemetryHandle>` | Assembles and starts the SDK; returns the running handle when one exists; rejects when the SDK cannot start or was already shut down in this process |
384
+ | `shutdownTelemetry` | `() => Promise<void>` | Waits for a start in progress, then flushes and stops the SDK; resolves at once when none was started |
385
+ | `ignorePaths` | `(patterns: readonly RegExp[]) => (request) => boolean` | Predicate for `ignoreIncomingRequest`: matches the request path with its query cut; a request with no target, or a path over 2,048 characters, is not matched |
386
+ | `DEFAULT_REDACTED_QUERY_PARAMS` | `readonly string[]` | The credential-parameter list redacted from outgoing request URLs |
387
+ | `TelemetryOptions` | type | The options of `startTelemetry` ([Configuration](#-configuration)) |
388
+ | `TelemetryHandle` | type | `{ enabled: boolean, shutdown(): Promise<void> }` |
389
+ | `UnsafeOptions` | type | The literal-`true` redaction opt-outs |
390
+ | `InstrumentationOptions` | type | `fs`, `sendLogs` and `overrides` |
391
+ | `IncomingRequestTarget` | type | What an incoming-request predicate sees: the request `url` |
375
392
 
376
- `ignorePaths` copies each pattern without its `g` and `y` flags, which would keep state between calls. Anchor the patterns at both ends; an unanchored one also matches routes that merely contain the word.
393
+ `ignorePaths` copies each pattern without its `g` and `y` flags, which would keep state between calls. Anchor the patterns at both ends, with no nested quantifiers: an unanchored one also matches routes that merely contain the word, and `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on a 28-character path, and the time grows exponentially with the length.
377
394
 
378
395
  ### Register: `@bymax-one/nest-telemetry/register`
379
396
 
@@ -381,13 +398,15 @@ No exports. `node --import @bymax-one/nest-telemetry/register` registers the loa
381
398
 
382
399
  ### Nest: `@bymax-one/nest-telemetry/nest`
383
400
 
384
- | Export | Kind | Purpose |
385
- | ---------------------------- | -------- | ---------------------------------------------------------------------------------------------------- |
386
- | `TelemetryModule` | module | Global; registers `TelemetryShutdownHook`. List it first in the application module's imports |
387
- | `TelemetryShutdownHook` | provider | `OnApplicationShutdown`: awaits `shutdownTelemetry()`; a refused flush is reported and never rejects |
388
- | `TELEMETRY_LOGGER` | token | Optional provider with an `errorStructured(logKey, error)` method, used to report a failed flush |
389
- | `TELEMETRY_FLUSH_FAILED_KEY` | constant | The stable key, `TRACING_FLUSH_FAILED`, under which a failed flush is reported |
390
- | `ITelemetryErrorLogger` | type | The shape `TELEMETRY_LOGGER` provides: `errorStructured(logKey, error)` |
401
+ | Export | Kind | Purpose |
402
+ | -------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
403
+ | `TelemetryModule` | module | Global; registers `TelemetryShutdownHook`. List it first in the application module's imports |
404
+ | `TelemetryShutdownHook` | provider | `OnApplicationShutdown`: awaits `shutdownTelemetry()`; a refused flush is reported and never rejects |
405
+ | `TELEMETRY_LOGGER` | token | Optional provider with an `errorStructured(logKey, error)` method for a failed flush and a shutdown that hit its deadline, and an optional `warnStructured(logKey, message, userId, metadata)` for a failed export |
406
+ | `TELEMETRY_FLUSH_FAILED_KEY` | constant | The stable key, `TRACING_FLUSH_FAILED`, under which a failed flush is reported |
407
+ | `TELEMETRY_SHUTDOWN_TIMEOUT_KEY` | constant | The stable key, `TRACING_SHUTDOWN_TIMEOUT`, under which a shutdown that hit `shutdownTimeoutMs` is reported |
408
+ | `TELEMETRY_EXPORT_FAILED_KEY` | constant | The stable key, `TRACING_EXPORT_FAILED`, under which a failed span export is reported, with the exporter kind and the error code as metadata |
409
+ | `ITelemetryErrorLogger` | type | The shape `TELEMETRY_LOGGER` provides: `errorStructured(logKey, error)` and an optional `warnStructured` |
391
410
 
392
411
  ---
393
412
 
@@ -408,6 +427,7 @@ By design, the following are out of scope:
408
427
  - ❌ **Redact baggage**
409
428
  - ❌ **Redact request and response bodies, or HTTP headers** — they are not captured by default, and they are not redacted if you enable capturing them
410
429
  - ❌ **Redact attributes your own code sets**
430
+ - ❌ **Redact log records forwarded through `OTEL_LOGS_EXPORTER`** — the library redacts spans, and a log record is exported as the logger produced it, so redact in the logger. Measured with `@bymax-one/nest-logger` 1.4.16, which redacts before it hands the record over: a password and a nested token never reached the collector, and the `[REDACTED]` marker did. A plain pino logger with no redaction exported its password
411
431
  - ❌ **Choose a sampler** — configure `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`
412
432
  - ❌ **Run a collector or a backend** — point `OTEL_EXPORTER_OTLP_ENDPOINT` at one
413
433
  - ❌ **Decide your span names** — those come from the instrumentations and from your code
@@ -13,6 +13,17 @@ var __decorateClass = (decorators, target, key, kind) => {
13
13
  };
14
14
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
15
15
 
16
+ // src/sdk/warning-sink.ts
17
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
18
+ function registerWarningSink(sink) {
19
+ Reflect.set(globalThis, SINK_KEY, sink);
20
+ return () => {
21
+ if (Reflect.get(globalThis, SINK_KEY) === sink) {
22
+ Reflect.deleteProperty(globalThis, SINK_KEY);
23
+ }
24
+ };
25
+ }
26
+
16
27
  // src/sdk/handle.ts
17
28
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
18
29
  var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
@@ -30,6 +41,8 @@ async function shutdownTelemetry() {
30
41
 
31
42
  // src/nest/telemetry-shutdown.hook.ts
32
43
  var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
44
+ var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
45
+ var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
33
46
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
34
47
  exports.TelemetryShutdownHook = class TelemetryShutdownHook {
35
48
  /**
@@ -38,6 +51,15 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
38
51
  constructor(moduleRef) {
39
52
  this.moduleRef = moduleRef;
40
53
  }
54
+ /**
55
+ * Routes the library's two runtime warnings to the structured logger the application bound, when
56
+ * there is one. Without it they stay process warnings.
57
+ */
58
+ onModuleInit() {
59
+ if (this.structuredLogger() !== void 0) {
60
+ this.releaseSink = registerWarningSink((warning) => this.route(warning));
61
+ }
62
+ }
41
63
  /**
42
64
  * Flushes and stops the SDK, if one was started.
43
65
  *
@@ -54,7 +76,30 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
54
76
  await shutdownTelemetry();
55
77
  } catch (error) {
56
78
  this.report(error);
79
+ } finally {
80
+ this.releaseSink?.();
81
+ }
82
+ }
83
+ /**
84
+ * Writes a warning to the structured logger under its key.
85
+ *
86
+ * @param warning - The warning.
87
+ * @returns Whether the logger took it; a warning with no key or no method on the logger is left
88
+ * to the process warning.
89
+ */
90
+ route(warning) {
91
+ const logger = this.structuredLogger();
92
+ if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
93
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
94
+ return true;
95
+ }
96
+ if (warning.code === "BYMAX_TELEMETRY_EXPORT_FAILED" && typeof logger?.warnStructured === "function") {
97
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
98
+ ...warning.fields
99
+ });
100
+ return true;
57
101
  }
102
+ return false;
58
103
  }
59
104
  /**
60
105
  * Reports a failed flush: through the structured logger when the application provides a usable
@@ -108,5 +153,7 @@ exports.TelemetryModule = __decorateClass([
108
153
  common.Module({ providers: [exports.TelemetryShutdownHook] })
109
154
  ], exports.TelemetryModule);
110
155
 
156
+ exports.TELEMETRY_EXPORT_FAILED_KEY = TELEMETRY_EXPORT_FAILED_KEY;
111
157
  exports.TELEMETRY_FLUSH_FAILED_KEY = TELEMETRY_FLUSH_FAILED_KEY;
112
158
  exports.TELEMETRY_LOGGER = TELEMETRY_LOGGER;
159
+ exports.TELEMETRY_SHUTDOWN_TIMEOUT_KEY = TELEMETRY_SHUTDOWN_TIMEOUT_KEY;
@@ -1,7 +1,11 @@
1
- import { OnApplicationShutdown } from '@nestjs/common';
1
+ import { OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
2
2
 
3
3
  /** Log key of the entry a failed flush leaves, stable so an alert can match it. */
4
4
  declare const TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
5
+ /** Log key of the entry a shutdown that hit its deadline leaves, stable so an alert can match it. */
6
+ declare const TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
7
+ /** Log key of the entry a failed span export leaves, stable so an alert can match it. */
8
+ declare const TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
5
9
  /** Injection token of the optional structured logger a failed flush is reported through. */
6
10
  declare const TELEMETRY_LOGGER: unique symbol;
7
11
  /** The one call the hook makes on a structured logger. */
@@ -13,6 +17,16 @@ interface ITelemetryErrorLogger {
13
17
  * @param error - The failure.
14
18
  */
15
19
  errorStructured(logKey: string, error: Error): void;
20
+ /**
21
+ * Writes a warning entry under a log key, for a failed span export. Optional: a logger without
22
+ * it gets that warning as a process warning.
23
+ *
24
+ * @param logKey - The entry's log key.
25
+ * @param message - The library's own text, never anything from the exporter.
26
+ * @param userId - Always `undefined`.
27
+ * @param metadata - The exporter kind and a short error code.
28
+ */
29
+ warnStructured?(logKey: string, message: string, userId?: string, metadata?: Record<string, unknown>): void;
16
30
  }
17
31
  /** What the hook needs of Nest's module reference: to look a provider up anywhere in the application. */
18
32
  interface IProviderLookup {
@@ -27,12 +41,19 @@ interface IProviderLookup {
27
41
  }): unknown;
28
42
  }
29
43
  /** Awaits the SDK flush as part of the application's own graceful shutdown. */
30
- declare class TelemetryShutdownHook implements OnApplicationShutdown {
44
+ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleInit {
31
45
  private readonly moduleRef;
46
+ /** Removes this hook's warning sink, when it registered one. */
47
+ private releaseSink;
32
48
  /**
33
49
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
34
50
  */
35
51
  constructor(moduleRef: IProviderLookup);
52
+ /**
53
+ * Routes the library's two runtime warnings to the structured logger the application bound, when
54
+ * there is one. Without it they stay process warnings.
55
+ */
56
+ onModuleInit(): void;
36
57
  /**
37
58
  * Flushes and stops the SDK, if one was started.
38
59
  *
@@ -45,6 +66,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
45
66
  * has been reported. Never rejects.
46
67
  */
47
68
  onApplicationShutdown(): Promise<void>;
69
+ /**
70
+ * Writes a warning to the structured logger under its key.
71
+ *
72
+ * @param warning - The warning.
73
+ * @returns Whether the logger took it; a warning with no key or no method on the logger is left
74
+ * to the process warning.
75
+ */
76
+ private route;
48
77
  /**
49
78
  * Reports a failed flush: through the structured logger when the application provides a usable
50
79
  * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
@@ -72,5 +101,5 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
72
101
  declare class TelemetryModule {
73
102
  }
74
103
 
75
- export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
104
+ export { TELEMETRY_EXPORT_FAILED_KEY, TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TELEMETRY_SHUTDOWN_TIMEOUT_KEY, TelemetryModule, TelemetryShutdownHook };
76
105
  export type { ITelemetryErrorLogger };
@@ -1,7 +1,11 @@
1
- import { OnApplicationShutdown } from '@nestjs/common';
1
+ import { OnApplicationShutdown, OnModuleInit } from '@nestjs/common';
2
2
 
3
3
  /** Log key of the entry a failed flush leaves, stable so an alert can match it. */
4
4
  declare const TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
5
+ /** Log key of the entry a shutdown that hit its deadline leaves, stable so an alert can match it. */
6
+ declare const TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
7
+ /** Log key of the entry a failed span export leaves, stable so an alert can match it. */
8
+ declare const TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
5
9
  /** Injection token of the optional structured logger a failed flush is reported through. */
6
10
  declare const TELEMETRY_LOGGER: unique symbol;
7
11
  /** The one call the hook makes on a structured logger. */
@@ -13,6 +17,16 @@ interface ITelemetryErrorLogger {
13
17
  * @param error - The failure.
14
18
  */
15
19
  errorStructured(logKey: string, error: Error): void;
20
+ /**
21
+ * Writes a warning entry under a log key, for a failed span export. Optional: a logger without
22
+ * it gets that warning as a process warning.
23
+ *
24
+ * @param logKey - The entry's log key.
25
+ * @param message - The library's own text, never anything from the exporter.
26
+ * @param userId - Always `undefined`.
27
+ * @param metadata - The exporter kind and a short error code.
28
+ */
29
+ warnStructured?(logKey: string, message: string, userId?: string, metadata?: Record<string, unknown>): void;
16
30
  }
17
31
  /** What the hook needs of Nest's module reference: to look a provider up anywhere in the application. */
18
32
  interface IProviderLookup {
@@ -27,12 +41,19 @@ interface IProviderLookup {
27
41
  }): unknown;
28
42
  }
29
43
  /** Awaits the SDK flush as part of the application's own graceful shutdown. */
30
- declare class TelemetryShutdownHook implements OnApplicationShutdown {
44
+ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleInit {
31
45
  private readonly moduleRef;
46
+ /** Removes this hook's warning sink, when it registered one. */
47
+ private releaseSink;
32
48
  /**
33
49
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
34
50
  */
35
51
  constructor(moduleRef: IProviderLookup);
52
+ /**
53
+ * Routes the library's two runtime warnings to the structured logger the application bound, when
54
+ * there is one. Without it they stay process warnings.
55
+ */
56
+ onModuleInit(): void;
36
57
  /**
37
58
  * Flushes and stops the SDK, if one was started.
38
59
  *
@@ -45,6 +66,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
45
66
  * has been reported. Never rejects.
46
67
  */
47
68
  onApplicationShutdown(): Promise<void>;
69
+ /**
70
+ * Writes a warning to the structured logger under its key.
71
+ *
72
+ * @param warning - The warning.
73
+ * @returns Whether the logger took it; a warning with no key or no method on the logger is left
74
+ * to the process warning.
75
+ */
76
+ private route;
48
77
  /**
49
78
  * Reports a failed flush: through the structured logger when the application provides a usable
50
79
  * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
@@ -72,5 +101,5 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown {
72
101
  declare class TelemetryModule {
73
102
  }
74
103
 
75
- export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
104
+ export { TELEMETRY_EXPORT_FAILED_KEY, TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TELEMETRY_SHUTDOWN_TIMEOUT_KEY, TelemetryModule, TelemetryShutdownHook };
76
105
  export type { ITelemetryErrorLogger };
@@ -11,6 +11,17 @@ var __decorateClass = (decorators, target, key, kind) => {
11
11
  };
12
12
  var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
13
13
 
14
+ // src/sdk/warning-sink.ts
15
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
16
+ function registerWarningSink(sink) {
17
+ Reflect.set(globalThis, SINK_KEY, sink);
18
+ return () => {
19
+ if (Reflect.get(globalThis, SINK_KEY) === sink) {
20
+ Reflect.deleteProperty(globalThis, SINK_KEY);
21
+ }
22
+ };
23
+ }
24
+
14
25
  // src/sdk/handle.ts
15
26
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
16
27
  var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
@@ -28,6 +39,8 @@ async function shutdownTelemetry() {
28
39
 
29
40
  // src/nest/telemetry-shutdown.hook.ts
30
41
  var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
42
+ var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
43
+ var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
31
44
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
32
45
  var TelemetryShutdownHook = class {
33
46
  /**
@@ -36,6 +49,15 @@ var TelemetryShutdownHook = class {
36
49
  constructor(moduleRef) {
37
50
  this.moduleRef = moduleRef;
38
51
  }
52
+ /**
53
+ * Routes the library's two runtime warnings to the structured logger the application bound, when
54
+ * there is one. Without it they stay process warnings.
55
+ */
56
+ onModuleInit() {
57
+ if (this.structuredLogger() !== void 0) {
58
+ this.releaseSink = registerWarningSink((warning) => this.route(warning));
59
+ }
60
+ }
39
61
  /**
40
62
  * Flushes and stops the SDK, if one was started.
41
63
  *
@@ -52,7 +74,30 @@ var TelemetryShutdownHook = class {
52
74
  await shutdownTelemetry();
53
75
  } catch (error) {
54
76
  this.report(error);
77
+ } finally {
78
+ this.releaseSink?.();
79
+ }
80
+ }
81
+ /**
82
+ * Writes a warning to the structured logger under its key.
83
+ *
84
+ * @param warning - The warning.
85
+ * @returns Whether the logger took it; a warning with no key or no method on the logger is left
86
+ * to the process warning.
87
+ */
88
+ route(warning) {
89
+ const logger = this.structuredLogger();
90
+ if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
91
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
92
+ return true;
93
+ }
94
+ if (warning.code === "BYMAX_TELEMETRY_EXPORT_FAILED" && typeof logger?.warnStructured === "function") {
95
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
96
+ ...warning.fields
97
+ });
98
+ return true;
55
99
  }
100
+ return false;
56
101
  }
57
102
  /**
58
103
  * Reports a failed flush: through the structured logger when the application provides a usable
@@ -106,4 +151,4 @@ TelemetryModule = __decorateClass([
106
151
  Module({ providers: [TelemetryShutdownHook] })
107
152
  ], TelemetryModule);
108
153
 
109
- export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
154
+ export { TELEMETRY_EXPORT_FAILED_KEY, TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TELEMETRY_SHUTDOWN_TIMEOUT_KEY, TelemetryModule, TelemetryShutdownHook };
@@ -193,6 +193,50 @@ function warnAboutIgnoredOptions(options) {
193
193
  }
194
194
  }
195
195
 
196
+ // src/sdk/warning-sink.ts
197
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
198
+ function reportWarning(warning) {
199
+ try {
200
+ const sink = Reflect.get(globalThis, SINK_KEY);
201
+ if (sink?.(warning) === true) {
202
+ return;
203
+ }
204
+ } catch {
205
+ }
206
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
207
+ }
208
+
209
+ // src/sdk/export-failure.ts
210
+ var WINDOW_MS = 6e4;
211
+ var SUCCESS = 0;
212
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
213
+ function codeOf(error) {
214
+ const code = String(Reflect.get(Object(error), "code"));
215
+ return CODE_TOKEN.test(code) ? code : "UNKNOWN";
216
+ }
217
+ function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
218
+ const original = exporter.export.bind(exporter);
219
+ let lastWarning = Number.NEGATIVE_INFINITY;
220
+ exporter.export = (spans, done) => {
221
+ original(spans, (result) => {
222
+ if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
223
+ lastWarning = clock();
224
+ try {
225
+ const code = codeOf(result.error);
226
+ reportWarning({
227
+ code: "BYMAX_TELEMETRY_EXPORT_FAILED",
228
+ text: `Exporting spans failed (${kind}, code ${code}), so the batch was dropped. This warning repeats at most once a minute. Check that the collector is reachable.`,
229
+ fields: { kind, code }
230
+ });
231
+ } catch {
232
+ }
233
+ }
234
+ done(result);
235
+ });
236
+ };
237
+ return exporter;
238
+ }
239
+
196
240
  // src/sdk/handle.ts
197
241
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
198
242
  var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
@@ -216,7 +260,12 @@ function setPendingStart(start) {
216
260
  function clearPendingStart() {
217
261
  delete store[PENDING_KEY];
218
262
  }
219
- function createHandle(stopSdk) {
263
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
264
+ var MAX_SHUTDOWN_TIMEOUT_MS = 12e4;
265
+ function shutdownDeadline(requested) {
266
+ return requested !== void 0 && Number.isFinite(requested) && requested > 0 && requested <= MAX_SHUTDOWN_TIMEOUT_MS ? requested : DEFAULT_SHUTDOWN_TIMEOUT_MS;
267
+ }
268
+ function createHandle(stopSdk, shutdownTimeoutMs) {
220
269
  let flush;
221
270
  let finished = false;
222
271
  const handle = {
@@ -228,12 +277,31 @@ function createHandle(stopSdk) {
228
277
  if (finished) {
229
278
  return Promise.resolve();
230
279
  }
231
- flush ??= stopSdk().finally(() => {
232
- finished = true;
233
- Reflect.set(globalThis, STOPPED_KEY, true);
234
- if (currentHandle() === handle) {
235
- Reflect.deleteProperty(globalThis, HANDLE_KEY);
236
- }
280
+ flush ??= new Promise((resolve, reject) => {
281
+ const deadline = shutdownDeadline(shutdownTimeoutMs);
282
+ const finish = () => {
283
+ finished = true;
284
+ Reflect.set(globalThis, STOPPED_KEY, true);
285
+ if (currentHandle() === handle) {
286
+ Reflect.deleteProperty(globalThis, HANDLE_KEY);
287
+ }
288
+ };
289
+ const timer = setTimeout(() => {
290
+ reportWarning({
291
+ code: "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT",
292
+ text: `The telemetry flush did not finish within ${deadline} ms, so shutdown stopped waiting for it. Spans still queued may be lost. Raise shutdownTimeoutMs or check that the collector answers.`,
293
+ fields: { timeoutMs: deadline }
294
+ });
295
+ finish();
296
+ resolve();
297
+ }, deadline);
298
+ timer.unref();
299
+ new Promise((started) => {
300
+ started(stopSdk());
301
+ }).finally(() => {
302
+ clearTimeout(timer);
303
+ finish();
304
+ }).then(resolve, reject);
237
305
  });
238
306
  return flush;
239
307
  }
@@ -356,7 +424,7 @@ function buildSdk(packages, options, env) {
356
424
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
357
425
  ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
358
426
  new sdkTrace.BatchSpanProcessor({
359
- exporter: new exporter.OTLPTraceExporter(),
427
+ exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
360
428
  ...env.batchSpanProcessor
361
429
  })
362
430
  ],
@@ -370,7 +438,7 @@ async function boot(options, env) {
370
438
  warnAboutMissingServiceName(options, env);
371
439
  const sdk = buildSdk(await loadPackages(), options, env);
372
440
  sdk.start();
373
- const handle = createHandle(() => sdk.shutdown());
441
+ const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
374
442
  registerHandle(handle);
375
443
  return handle;
376
444
  }
@@ -56,6 +56,7 @@ function serializeRedisCommandName(commandName) {
56
56
  }
57
57
 
58
58
  // src/sdk/ignore-paths.ts
59
+ var MAX_PATH_LENGTH = 2048;
59
60
  function ignorePaths(patterns) {
60
61
  const stateless = patterns.map(
61
62
  (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
@@ -66,10 +67,23 @@ function ignorePaths(patterns) {
66
67
  }
67
68
  const cut = request.url.indexOf("?");
68
69
  const path = cut === -1 ? request.url : request.url.slice(0, cut);
69
- return stateless.some((pattern) => pattern.test(path));
70
+ return path.length <= MAX_PATH_LENGTH && stateless.some((pattern) => pattern.test(path));
70
71
  };
71
72
  }
72
73
 
74
+ // src/sdk/warning-sink.ts
75
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
76
+ function reportWarning(warning) {
77
+ try {
78
+ const sink = Reflect.get(globalThis, SINK_KEY);
79
+ if (sink?.(warning) === true) {
80
+ return;
81
+ }
82
+ } catch {
83
+ }
84
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
85
+ }
86
+
73
87
  // src/sdk/handle.ts
74
88
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
75
89
  var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
@@ -93,7 +107,12 @@ function setPendingStart(start) {
93
107
  function clearPendingStart() {
94
108
  delete store[PENDING_KEY];
95
109
  }
96
- function createHandle(stopSdk) {
110
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
111
+ var MAX_SHUTDOWN_TIMEOUT_MS = 12e4;
112
+ function shutdownDeadline(requested) {
113
+ return requested !== void 0 && Number.isFinite(requested) && requested > 0 && requested <= MAX_SHUTDOWN_TIMEOUT_MS ? requested : DEFAULT_SHUTDOWN_TIMEOUT_MS;
114
+ }
115
+ function createHandle(stopSdk, shutdownTimeoutMs) {
97
116
  let flush;
98
117
  let finished = false;
99
118
  const handle = {
@@ -105,12 +124,31 @@ function createHandle(stopSdk) {
105
124
  if (finished) {
106
125
  return Promise.resolve();
107
126
  }
108
- flush ??= stopSdk().finally(() => {
109
- finished = true;
110
- Reflect.set(globalThis, STOPPED_KEY, true);
111
- if (currentHandle() === handle) {
112
- Reflect.deleteProperty(globalThis, HANDLE_KEY);
113
- }
127
+ flush ??= new Promise((resolve, reject) => {
128
+ const deadline = shutdownDeadline(shutdownTimeoutMs);
129
+ const finish = () => {
130
+ finished = true;
131
+ Reflect.set(globalThis, STOPPED_KEY, true);
132
+ if (currentHandle() === handle) {
133
+ Reflect.deleteProperty(globalThis, HANDLE_KEY);
134
+ }
135
+ };
136
+ const timer = setTimeout(() => {
137
+ reportWarning({
138
+ code: "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT",
139
+ text: `The telemetry flush did not finish within ${deadline} ms, so shutdown stopped waiting for it. Spans still queued may be lost. Raise shutdownTimeoutMs or check that the collector answers.`,
140
+ fields: { timeoutMs: deadline }
141
+ });
142
+ finish();
143
+ resolve();
144
+ }, deadline);
145
+ timer.unref();
146
+ new Promise((started) => {
147
+ started(stopSdk());
148
+ }).finally(() => {
149
+ clearTimeout(timer);
150
+ finish();
151
+ }).then(resolve, reject);
114
152
  });
115
153
  return flush;
116
154
  }
@@ -258,6 +296,37 @@ function readTelemetryEnvironment(source = process.env) {
258
296
  };
259
297
  }
260
298
 
299
+ // src/sdk/export-failure.ts
300
+ var WINDOW_MS = 6e4;
301
+ var SUCCESS = 0;
302
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
303
+ function codeOf(error) {
304
+ const code = String(Reflect.get(Object(error), "code"));
305
+ return CODE_TOKEN.test(code) ? code : "UNKNOWN";
306
+ }
307
+ function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
308
+ const original = exporter.export.bind(exporter);
309
+ let lastWarning = Number.NEGATIVE_INFINITY;
310
+ exporter.export = (spans, done) => {
311
+ original(spans, (result) => {
312
+ if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
313
+ lastWarning = clock();
314
+ try {
315
+ const code = codeOf(result.error);
316
+ reportWarning({
317
+ code: "BYMAX_TELEMETRY_EXPORT_FAILED",
318
+ text: `Exporting spans failed (${kind}, code ${code}), so the batch was dropped. This warning repeats at most once a minute. Check that the collector is reachable.`,
319
+ fields: { kind, code }
320
+ });
321
+ } catch {
322
+ }
323
+ }
324
+ done(result);
325
+ });
326
+ };
327
+ return exporter;
328
+ }
329
+
261
330
  // src/sdk/resource-detectors.ts
262
331
  var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
263
332
  var NAMED = /* @__PURE__ */ new Map([
@@ -373,7 +442,7 @@ function buildSdk(packages, options, env) {
373
442
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
374
443
  ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
375
444
  new sdkTrace.BatchSpanProcessor({
376
- exporter: new exporter.OTLPTraceExporter(),
445
+ exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
377
446
  ...env.batchSpanProcessor
378
447
  })
379
448
  ],
@@ -387,7 +456,7 @@ async function boot(options, env) {
387
456
  warnAboutMissingServiceName(options, env);
388
457
  const sdk = buildSdk(await loadPackages(), options, env);
389
458
  sdk.start();
390
- const handle = createHandle(() => sdk.shutdown());
459
+ const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
391
460
  registerHandle(handle);
392
461
  return handle;
393
462
  }
@@ -85,6 +85,13 @@ interface TelemetryOptions {
85
85
  readonly extraRedactedQueryParams?: readonly string[];
86
86
  /** Explicit opt-outs from redaction. */
87
87
  readonly unsafe?: UnsafeOptions;
88
+ /**
89
+ * The longest `shutdown` waits for the final flush, in milliseconds. A collector that accepts a
90
+ * connection and never answers cannot hold the process past it: shutdown warns with
91
+ * `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves, and spans still queued may be lost. Defaults
92
+ * to 5000; a value that is not a finite number above zero, or is above 120000, means the default.
93
+ */
94
+ readonly shutdownTimeoutMs?: number;
88
95
  /**
89
96
  * The environment the library reads, which defaults to the process environment. The OTel SDK
90
97
  * reads `OTEL_EXPORTER_OTLP_*` and the sampler variables from the process environment itself.
@@ -110,8 +117,12 @@ interface TelemetryHandle {
110
117
  * Only the path is compared: the query string is cut first, so an exclusion cannot be switched off
111
118
  * by appending a parameter, and a probe path hidden in a query cannot trigger one. A request with no
112
119
  * target is not matched: failing open costs a span nobody wanted, where the opposite silently drops
113
- * the traffic least likely to be well formed. Anchor the patterns at both ends; an unanchored one
114
- * also matches routes that merely contain the word.
120
+ * the traffic least likely to be well formed. A path longer than 2,048 characters is never ignored
121
+ * and the patterns are not run against it, which bounds the work a long path can cause. Anchor
122
+ * the patterns at both ends and give them no nested quantifiers such as `(a+)+`: an unanchored
123
+ * pattern also matches routes that merely contain the word, and the cap does not bound a nested
124
+ * quantifier on a short path: `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on 28 characters,
125
+ * and the time grows exponentially with the length.
115
126
  *
116
127
  * @param patterns - Patterns tested against the path alone.
117
128
  * @returns A predicate for `TelemetryOptions.ignoreIncomingRequest`.
@@ -85,6 +85,13 @@ interface TelemetryOptions {
85
85
  readonly extraRedactedQueryParams?: readonly string[];
86
86
  /** Explicit opt-outs from redaction. */
87
87
  readonly unsafe?: UnsafeOptions;
88
+ /**
89
+ * The longest `shutdown` waits for the final flush, in milliseconds. A collector that accepts a
90
+ * connection and never answers cannot hold the process past it: shutdown warns with
91
+ * `BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT` and resolves, and spans still queued may be lost. Defaults
92
+ * to 5000; a value that is not a finite number above zero, or is above 120000, means the default.
93
+ */
94
+ readonly shutdownTimeoutMs?: number;
88
95
  /**
89
96
  * The environment the library reads, which defaults to the process environment. The OTel SDK
90
97
  * reads `OTEL_EXPORTER_OTLP_*` and the sampler variables from the process environment itself.
@@ -110,8 +117,12 @@ interface TelemetryHandle {
110
117
  * Only the path is compared: the query string is cut first, so an exclusion cannot be switched off
111
118
  * by appending a parameter, and a probe path hidden in a query cannot trigger one. A request with no
112
119
  * target is not matched: failing open costs a span nobody wanted, where the opposite silently drops
113
- * the traffic least likely to be well formed. Anchor the patterns at both ends; an unanchored one
114
- * also matches routes that merely contain the word.
120
+ * the traffic least likely to be well formed. A path longer than 2,048 characters is never ignored
121
+ * and the patterns are not run against it, which bounds the work a long path can cause. Anchor
122
+ * the patterns at both ends and give them no nested quantifiers such as `(a+)+`: an unanchored
123
+ * pattern also matches routes that merely contain the word, and the cap does not bound a nested
124
+ * quantifier on a short path: `/^\/(a+)+$/` took 2.5 s and 5.5 s in two runs on 28 characters,
125
+ * and the time grows exponentially with the length.
115
126
  *
116
127
  * @param patterns - Patterns tested against the path alone.
117
128
  * @returns A predicate for `TelemetryOptions.ignoreIncomingRequest`.
@@ -54,6 +54,7 @@ function serializeRedisCommandName(commandName) {
54
54
  }
55
55
 
56
56
  // src/sdk/ignore-paths.ts
57
+ var MAX_PATH_LENGTH = 2048;
57
58
  function ignorePaths(patterns) {
58
59
  const stateless = patterns.map(
59
60
  (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
@@ -64,10 +65,23 @@ function ignorePaths(patterns) {
64
65
  }
65
66
  const cut = request.url.indexOf("?");
66
67
  const path = cut === -1 ? request.url : request.url.slice(0, cut);
67
- return stateless.some((pattern) => pattern.test(path));
68
+ return path.length <= MAX_PATH_LENGTH && stateless.some((pattern) => pattern.test(path));
68
69
  };
69
70
  }
70
71
 
72
+ // src/sdk/warning-sink.ts
73
+ var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
74
+ function reportWarning(warning) {
75
+ try {
76
+ const sink = Reflect.get(globalThis, SINK_KEY);
77
+ if (sink?.(warning) === true) {
78
+ return;
79
+ }
80
+ } catch {
81
+ }
82
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
83
+ }
84
+
71
85
  // src/sdk/handle.ts
72
86
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
73
87
  var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
@@ -91,7 +105,12 @@ function setPendingStart(start) {
91
105
  function clearPendingStart() {
92
106
  delete store[PENDING_KEY];
93
107
  }
94
- function createHandle(stopSdk) {
108
+ var DEFAULT_SHUTDOWN_TIMEOUT_MS = 5e3;
109
+ var MAX_SHUTDOWN_TIMEOUT_MS = 12e4;
110
+ function shutdownDeadline(requested) {
111
+ return requested !== void 0 && Number.isFinite(requested) && requested > 0 && requested <= MAX_SHUTDOWN_TIMEOUT_MS ? requested : DEFAULT_SHUTDOWN_TIMEOUT_MS;
112
+ }
113
+ function createHandle(stopSdk, shutdownTimeoutMs) {
95
114
  let flush;
96
115
  let finished = false;
97
116
  const handle = {
@@ -103,12 +122,31 @@ function createHandle(stopSdk) {
103
122
  if (finished) {
104
123
  return Promise.resolve();
105
124
  }
106
- flush ??= stopSdk().finally(() => {
107
- finished = true;
108
- Reflect.set(globalThis, STOPPED_KEY, true);
109
- if (currentHandle() === handle) {
110
- Reflect.deleteProperty(globalThis, HANDLE_KEY);
111
- }
125
+ flush ??= new Promise((resolve, reject) => {
126
+ const deadline = shutdownDeadline(shutdownTimeoutMs);
127
+ const finish = () => {
128
+ finished = true;
129
+ Reflect.set(globalThis, STOPPED_KEY, true);
130
+ if (currentHandle() === handle) {
131
+ Reflect.deleteProperty(globalThis, HANDLE_KEY);
132
+ }
133
+ };
134
+ const timer = setTimeout(() => {
135
+ reportWarning({
136
+ code: "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT",
137
+ text: `The telemetry flush did not finish within ${deadline} ms, so shutdown stopped waiting for it. Spans still queued may be lost. Raise shutdownTimeoutMs or check that the collector answers.`,
138
+ fields: { timeoutMs: deadline }
139
+ });
140
+ finish();
141
+ resolve();
142
+ }, deadline);
143
+ timer.unref();
144
+ new Promise((started) => {
145
+ started(stopSdk());
146
+ }).finally(() => {
147
+ clearTimeout(timer);
148
+ finish();
149
+ }).then(resolve, reject);
112
150
  });
113
151
  return flush;
114
152
  }
@@ -256,6 +294,37 @@ function readTelemetryEnvironment(source = process.env) {
256
294
  };
257
295
  }
258
296
 
297
+ // src/sdk/export-failure.ts
298
+ var WINDOW_MS = 6e4;
299
+ var SUCCESS = 0;
300
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
301
+ function codeOf(error) {
302
+ const code = String(Reflect.get(Object(error), "code"));
303
+ return CODE_TOKEN.test(code) ? code : "UNKNOWN";
304
+ }
305
+ function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
306
+ const original = exporter.export.bind(exporter);
307
+ let lastWarning = Number.NEGATIVE_INFINITY;
308
+ exporter.export = (spans, done) => {
309
+ original(spans, (result) => {
310
+ if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
311
+ lastWarning = clock();
312
+ try {
313
+ const code = codeOf(result.error);
314
+ reportWarning({
315
+ code: "BYMAX_TELEMETRY_EXPORT_FAILED",
316
+ text: `Exporting spans failed (${kind}, code ${code}), so the batch was dropped. This warning repeats at most once a minute. Check that the collector is reachable.`,
317
+ fields: { kind, code }
318
+ });
319
+ } catch {
320
+ }
321
+ }
322
+ done(result);
323
+ });
324
+ };
325
+ return exporter;
326
+ }
327
+
259
328
  // src/sdk/resource-detectors.ts
260
329
  var COMMAND_LINE_ATTRIBUTES = ["process.command_args", "process.command_line"];
261
330
  var NAMED = /* @__PURE__ */ new Map([
@@ -371,7 +440,7 @@ function buildSdk(packages, options, env) {
371
440
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
372
441
  ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
373
442
  new sdkTrace.BatchSpanProcessor({
374
- exporter: new exporter.OTLPTraceExporter(),
443
+ exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
375
444
  ...env.batchSpanProcessor
376
445
  })
377
446
  ],
@@ -385,7 +454,7 @@ async function boot(options, env) {
385
454
  warnAboutMissingServiceName(options, env);
386
455
  const sdk = buildSdk(await loadPackages(), options, env);
387
456
  sdk.start();
388
- const handle = createHandle(() => sdk.shutdown());
457
+ const handle = createHandle(() => sdk.shutdown(), options.shutdownTimeoutMs);
389
458
  registerHandle(handle);
390
459
  return handle;
391
460
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "OpenTelemetry tracing for NestJS 11 and plain Node: starts the SDK before your app loads, redacts secrets from spans by default, and flushes on shutdown. Optional peers, zero cost when disabled.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",
@@ -190,6 +190,7 @@
190
190
  "jest": "^30.4.2",
191
191
  "lint-staged": "^17.0.7",
192
192
  "mysql2": "3.24.6",
193
+ "pino": "10.4.0",
193
194
  "prettier": "^3.8.3",
194
195
  "redis": "^5.12.2",
195
196
  "reflect-metadata": "^0.2.2",