@bymax-one/nest-telemetry 1.0.6 → 1.0.8

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
@@ -10,6 +10,67 @@ heading here.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [1.0.8] - 2026-11-20
14
+
15
+ ### Fixed
16
+
17
+ - **The sampler ratio warning escapes direction and invisible characters in the value it repeats.** It quoted the
18
+ operator's `OTEL_TRACES_SAMPLER_ARG` with `JSON.stringify`, which leaves the control characters from the delete
19
+ character to the C1 range, every format character (the soft hyphen, the zero-width characters, the direction
20
+ marks and overrides, the invisible operators and the byte order mark) and the line and paragraph separators as
21
+ they are, so a value could reorder or hide the warning line. They are now written as `\uXXXX`, or `\u{X}`
22
+ beyond the first plane, chosen by Unicode category.
23
+ - **The unsafe options are read once for each step that needs them.** The SDK build read `options.unsafe` three
24
+ times and the warning about turned-off redactions four times, so an option object whose `unsafe` is a getter
25
+ could make the warning and the SDK disagree. Each step reads it once.
26
+ - **A bound logger whose promise rejects no longer swallows the report.** The hook absorbed the rejection of a
27
+ `TELEMETRY_LOGGER` method (1.0.7) but then wrote nothing, so a failed flush, a shutdown that hit its deadline or
28
+ a failed span export vanished with it. The failed flush now goes to the Nest logger under `TRACING_FLUSH_FAILED`
29
+ with a short code, and the other two take a process warning, as they do with no logger bound.
30
+
31
+ ### Documentation
32
+
33
+ - **The README says that an unknown sampler name is not warned about.** A name that is not a sampler name
34
+ up to case and whitespace, such as `xyz` or `always_offf`, samples every trace without a warning. It also names
35
+ `app.useLogger()` next to `Logger.overrideLogger`, which it calls, and says where a rejected report goes.
36
+ - **The README `env` option row says where the two sampler variables come from.** `OTEL_TRACES_SAMPLER` and
37
+ `OTEL_TRACES_SAMPLER_ARG` are always read from the process environment, whatever the `env` option holds, as the
38
+ SDK reads them.
39
+
40
+ ### Apply to a derived backend
41
+
42
+ The declarations changed only by a private method on `TelemetryShutdownHook` (`reportToNestLogger`), which no
43
+ backend can call, so nothing in your types changes. A derived backend acts on these behaviours:
44
+
45
+ 1. A sampler ratio warning now shows a direction or invisible character in the value as an escape, so a log match
46
+ on that text sees the escape.
47
+ 2. If a `TELEMETRY_LOGGER` method returns a promise that rejects, you now also get the Nest logger entry
48
+ `TRACING_FLUSH_FAILED` or a process warning, where 1.0.7 wrote nothing.
49
+
50
+ ## [1.0.7] - 2026-11-20
51
+
52
+ ### Fixed
53
+
54
+ - **An asynchronous `TELEMETRY_LOGGER` can no longer end the process.** The hook reports a failed flush, a
55
+ shutdown that hit its deadline and a failed span export through the application's logger and did not look
56
+ at what the logger returned, so a logger whose promise rejected (a network sink that is down) produced an
57
+ unhandled rejection, which ends a Node process by default. The returned promise is now absorbed, since the
58
+ report is best effort and nothing waits for it.
59
+
60
+ ### Documentation
61
+
62
+ - **The README says what a logger that throws or rejects does.** A synchronous throw, from a
63
+ `TELEMETRY_LOGGER` or from the logger installed with `Logger.overrideLogger`, is absorbed and the shutdown
64
+ still resolves, now pinned through a real Nest logger. A rejecting asynchronous `error` method installed
65
+ with `overrideLogger` is not caught by Nest or by this library and is an unhandled rejection.
66
+ - **The README no longer says the library never touches the sampler variables.** It reads `OTEL_TRACES_SAMPLER`
67
+ and `OTEL_TRACES_SAMPLER_ARG` to warn when the SDK will ignore a ratio argument or sample every trace, and the
68
+ variable table lists them. Two other sentences are clearer: where the Nest module reports a refused flush, and
69
+ why the Nest logger entry leaves out the error message and stack.
70
+
71
+ **Apply note.** No action is needed. If your `TELEMETRY_LOGGER` methods return promises, a rejection is now
72
+ dropped silently instead of surfacing as an unhandled rejection.
73
+
13
74
  ## [1.0.6] - 2026-11-18
14
75
 
15
76
  ### Added
@@ -314,6 +375,8 @@ First release.
314
375
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
315
376
  application, with planted secrets absent from the exported body and negative controls.
316
377
 
378
+ [1.0.8]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.8
379
+ [1.0.7]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.7
317
380
  [1.0.6]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.6
318
381
  [1.0.5]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.5
319
382
  [1.0.4]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.4
package/README.md CHANGED
@@ -166,22 +166,22 @@ This package installs no signal handler and shows none, because handling signals
166
166
 
167
167
  Every field is the host's policy, and none is required.
168
168
 
169
- | Option | Default | What it does |
170
- | -------------------------------------- | ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
- | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
172
- | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
173
- | `serviceVersion` | none | The service version. |
174
- | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
175
- | `instrumentations.fs` | `false` | File-system instrumentation. |
176
- | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs pipeline. Winston also needs `@opentelemetry/winston-transport` installed by your application, see [Forwarding log records](#forwarding-log-records). |
177
- | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
178
- | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
179
- | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
180
- | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
181
- | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args`, `process.command_line` and `process.command` in the resource. Literal `true`. Warns. |
182
- | `unsafe.exportHostId` | off | Keeps `host.id`, the machine identifier, in the resource. Literal `true`. Warns. |
183
- | `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. |
184
- | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
169
+ | Option | Default | What it does |
170
+ | -------------------------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
171
+ | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
172
+ | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
173
+ | `serviceVersion` | none | The service version. |
174
+ | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
175
+ | `instrumentations.fs` | `false` | File-system instrumentation. |
176
+ | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether the records of pino, winston and bunyan are forwarded to the OpenTelemetry logs pipeline. Winston also needs `@opentelemetry/winston-transport` installed by your application, see [Forwarding log records](#forwarding-log-records). |
177
+ | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
178
+ | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
179
+ | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
180
+ | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
181
+ | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args`, `process.command_line` and `process.command` in the resource. Literal `true`. Warns. |
182
+ | `unsafe.exportHostId` | off | Keeps `host.id`, the machine identifier, in the resource. Literal `true`. Warns. |
183
+ | `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. |
184
+ | `env` | the process environment | The environment the library reads its variables from, except `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`, which are always read from the process environment, as the SDK reads them. The SDK itself always reads the process environment. |
185
185
 
186
186
  A key set to `undefined` or `null` in any option is the same as no key. An override is copied by its own enumerable keys, so pass a plain object: getters on a class prototype are not read.
187
187
 
@@ -195,9 +195,10 @@ The library reads these in one source file, and a test fails if any other file n
195
195
  | `OTEL_SERVICE_NAME` | Service name; overrides the option, because the operator's standard variable wins over what the code chose. Blank values count as absent. |
196
196
  | `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | Metrics and logs are exported only when these name an exporter. |
197
197
  | `OTEL_BSP_MAX_QUEUE_SIZE`, `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BSP_EXPORT_TIMEOUT`, `OTEL_BSP_MAX_EXPORT_BATCH_SIZE` | Mapped onto the batch span processor the library passes; the SDK applies them only to one it builds itself. A schedule delay or export timeout above 2147483647 ms is ignored with a warning, because a timer cannot hold it. |
198
+ | `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG` | The SDK acts on them. The library only reads them to warn when the SDK will ignore a ratio argument or sample every trace; see the warning table. |
198
199
  | `OTEL_NODE_RESOURCE_DETECTORS` | Selects resource detectors, under the specification's names (`service`, `host`, `process`) and the SDK's older ones. |
199
200
 
200
- The OpenTelemetry SDK reads these itself, and the library never touches them: `OTEL_EXPORTER_OTLP_*`, `OTEL_TRACES_SAMPLER` and `OTEL_TRACES_SAMPLER_ARG`, `OTEL_RESOURCE_ATTRIBUTES`.
201
+ The OpenTelemetry SDK reads these itself, and the library never touches them: `OTEL_EXPORTER_OTLP_*` and `OTEL_RESOURCE_ATTRIBUTES`.
201
202
 
202
203
  ---
203
204
 
@@ -276,7 +277,7 @@ The standard asks `nest-queue` to carry the trace context from the request that
276
277
 
277
278
  ### Flushing
278
279
 
279
- 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.
280
+ 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. The Nest module reports a flush the collector refuses and never throws it into your shutdown path; the programmatic functions reject, so their caller decides.
280
281
 
281
282
  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.
282
283
 
@@ -288,7 +289,7 @@ A start after a shutdown in the same process is refused: `startTelemetry` reject
288
289
 
289
290
  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.
290
291
 
291
- - **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. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when one was given, the value (a blank value is called blank, not unset). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. It reads the process environment, as the SDK does, and not the `env` option.
292
+ - **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. A ratio sampler needs `OTEL_TRACES_SAMPLER_ARG` to be a number from 0 to 1. When it is unset, empty or only whitespace, not a number or outside that range, the SDK falls back to a ratio of 1 and samples every trace, noting it only on a diagnostic channel; the start warns once with `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`, naming the variable and, when one was given, the value (a blank value is called blank, not unset). The SDK matches the sampler name exactly: `always_on`, `always_off`, `traceidratio`, `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, in lower case and without surrounding whitespace. Any other value, `TraceIdRatio` included, is replaced by its default and samples every trace; when the value differs from one of those names only in letter case or surrounding whitespace, the start warns once with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value. A name that is not one of those up to case and whitespace, such as `xyz` or a misspelling like `always_offf`, is not warned about: it samples every trace as well, so check the spelling of the variable. It reads the process environment, as the SDK does, and not the `env` option.
292
293
  - **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.
293
294
  - **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.
294
295
  - **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.
@@ -451,15 +452,17 @@ No exports. `node --import @bymax-one/nest-telemetry/register` registers the loa
451
452
 
452
453
  ### Nest: `@bymax-one/nest-telemetry/nest`
453
454
 
454
- | Export | Kind | Purpose |
455
- | -------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
456
- | `TelemetryModule` | module | Global; registers `TelemetryShutdownHook`. List it first in the application module's imports |
457
- | `TelemetryShutdownHook` | provider | `OnApplicationShutdown`: awaits `shutdownTelemetry()`; a refused flush is reported and never rejects |
458
- | `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. Without it, a failed flush goes to the Nest logger under `TRACING_FLUSH_FAILED` with a short error code and no message or stack, which can carry the collector's endpoint |
459
- | `TELEMETRY_FLUSH_FAILED_KEY` | constant | The stable key, `TRACING_FLUSH_FAILED`, under which a failed flush is reported |
460
- | `TELEMETRY_SHUTDOWN_TIMEOUT_KEY` | constant | The stable key, `TRACING_SHUTDOWN_TIMEOUT`, under which a shutdown that hit `shutdownTimeoutMs` is reported |
461
- | `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 |
462
- | `ITelemetryErrorLogger` | type | The shape `TELEMETRY_LOGGER` provides: `errorStructured(logKey, error)` and an optional `warnStructured` |
455
+ | Export | Kind | Purpose |
456
+ | -------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
457
+ | `TelemetryModule` | module | Global; registers `TelemetryShutdownHook`. List it first in the application module's imports |
458
+ | `TelemetryShutdownHook` | provider | `OnApplicationShutdown`: awaits `shutdownTelemetry()`; a refused flush is reported and never rejects |
459
+ | `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. Without it, a failed flush goes to the Nest logger under `TRACING_FLUSH_FAILED` with a short error code. The message and the stack are left out, because they can carry the collector's endpoint |
460
+ | `TELEMETRY_FLUSH_FAILED_KEY` | constant | The stable key, `TRACING_FLUSH_FAILED`, under which a failed flush is reported |
461
+ | `TELEMETRY_SHUTDOWN_TIMEOUT_KEY` | constant | The stable key, `TRACING_SHUTDOWN_TIMEOUT`, under which a shutdown that hit `shutdownTimeoutMs` is reported |
462
+ | `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 |
463
+ | `ITelemetryErrorLogger` | type | The shape `TELEMETRY_LOGGER` provides: `errorStructured(logKey, error)` and an optional `warnStructured` |
464
+
465
+ **A logger that throws or rejects.** The hook's job is to keep shutdown from failing, so every way it reports is guarded. A logger that throws synchronously, whether it is a `TELEMETRY_LOGGER` or the logger the application installed with `Logger.overrideLogger` or `app.useLogger()`, is absorbed, and the shutdown still resolves. A promise that a `TELEMETRY_LOGGER` method returns is not awaited, and its rejection is absorbed; the entry the logger did not take goes to the channel that needs no logger, the Nest logger for a failed flush and a process warning for a shutdown timeout or a failed export. Nest does not do the same for the logger it routes through: an asynchronous `error` method installed with `overrideLogger` or `app.useLogger()` that rejects is not caught by Nest or by this library, and Node reports it as an unhandled rejection, which ends the process by default. Write a logger for Nest so that `error` never rejects.
463
466
 
464
467
  ### Observability: `@bymax-one/nest-telemetry/observability`
465
468
 
@@ -36,6 +36,9 @@ function registerWarningSink(sink) {
36
36
  }
37
37
  };
38
38
  }
39
+ function emitAsProcessWarning(warning) {
40
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
41
+ }
39
42
 
40
43
  // src/sdk/handle.ts
41
44
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
@@ -57,6 +60,9 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
57
60
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
58
61
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
59
62
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
63
+ function absorbRejection(result, fallback) {
64
+ Promise.resolve(result).catch(fallback).catch(() => void 0);
65
+ }
60
66
  exports.TelemetryShutdownHook = class TelemetryShutdownHook {
61
67
  /**
62
68
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
@@ -103,13 +109,19 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
103
109
  route(warning) {
104
110
  const logger = this.structuredLogger();
105
111
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
106
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
112
+ absorbRejection(
113
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text)),
114
+ () => emitAsProcessWarning(warning)
115
+ );
107
116
  return true;
108
117
  }
109
118
  if (warning.code === "BYMAX_TELEMETRY_EXPORT_FAILED" && typeof logger?.warnStructured === "function") {
110
- logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
111
- ...warning.fields
112
- });
119
+ absorbRejection(
120
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
121
+ ...warning.fields
122
+ }),
123
+ () => emitAsProcessWarning(warning)
124
+ );
113
125
  return true;
114
126
  }
115
127
  return false;
@@ -129,11 +141,24 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
129
141
  try {
130
142
  const logger = this.structuredLogger();
131
143
  if (typeof logger?.errorStructured === "function") {
132
- logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
144
+ absorbRejection(
145
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure),
146
+ () => this.reportToNestLogger(failure)
147
+ );
133
148
  return;
134
149
  }
135
150
  } catch {
136
151
  }
152
+ this.reportToNestLogger(failure);
153
+ }
154
+ /**
155
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
156
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
157
+ * fail.
158
+ *
159
+ * @param failure - The failure, of which only a short code is written.
160
+ */
161
+ reportToNestLogger(failure) {
137
162
  try {
138
163
  new common.Logger("Telemetry").error(
139
164
  `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
@@ -85,6 +85,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleIn
85
85
  * `toString` could throw here.
86
86
  */
87
87
  private report;
88
+ /**
89
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
90
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
91
+ * fail.
92
+ *
93
+ * @param failure - The failure, of which only a short code is written.
94
+ */
95
+ private reportToNestLogger;
88
96
  /**
89
97
  * Looks the structured logger up.
90
98
  *
@@ -85,6 +85,14 @@ declare class TelemetryShutdownHook implements OnApplicationShutdown, OnModuleIn
85
85
  * `toString` could throw here.
86
86
  */
87
87
  private report;
88
+ /**
89
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
90
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
91
+ * fail.
92
+ *
93
+ * @param failure - The failure, of which only a short code is written.
94
+ */
95
+ private reportToNestLogger;
88
96
  /**
89
97
  * Looks the structured logger up.
90
98
  *
@@ -34,6 +34,9 @@ function registerWarningSink(sink) {
34
34
  }
35
35
  };
36
36
  }
37
+ function emitAsProcessWarning(warning) {
38
+ process.emitWarning(warning.text, { type: "Warning", code: warning.code });
39
+ }
37
40
 
38
41
  // src/sdk/handle.ts
39
42
  var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
@@ -55,6 +58,9 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
55
58
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
56
59
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
57
60
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
61
+ function absorbRejection(result, fallback) {
62
+ Promise.resolve(result).catch(fallback).catch(() => void 0);
63
+ }
58
64
  var TelemetryShutdownHook = class {
59
65
  /**
60
66
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
@@ -101,13 +107,19 @@ var TelemetryShutdownHook = class {
101
107
  route(warning) {
102
108
  const logger = this.structuredLogger();
103
109
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
104
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
110
+ absorbRejection(
111
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text)),
112
+ () => emitAsProcessWarning(warning)
113
+ );
105
114
  return true;
106
115
  }
107
116
  if (warning.code === "BYMAX_TELEMETRY_EXPORT_FAILED" && typeof logger?.warnStructured === "function") {
108
- logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
109
- ...warning.fields
110
- });
117
+ absorbRejection(
118
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
119
+ ...warning.fields
120
+ }),
121
+ () => emitAsProcessWarning(warning)
122
+ );
111
123
  return true;
112
124
  }
113
125
  return false;
@@ -127,11 +139,24 @@ var TelemetryShutdownHook = class {
127
139
  try {
128
140
  const logger = this.structuredLogger();
129
141
  if (typeof logger?.errorStructured === "function") {
130
- logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
142
+ absorbRejection(
143
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure),
144
+ () => this.reportToNestLogger(failure)
145
+ );
131
146
  return;
132
147
  }
133
148
  } catch {
134
149
  }
150
+ this.reportToNestLogger(failure);
151
+ }
152
+ /**
153
+ * Writes the failed flush to the Nest logger, which needs nothing the application bound. It never
154
+ * throws: nothing is left to report through when this one fails, and the shutdown must still not
155
+ * fail.
156
+ *
157
+ * @param failure - The failure, of which only a short code is written.
158
+ */
159
+ reportToNestLogger(failure) {
135
160
  try {
136
161
  new Logger("Telemetry").error(
137
162
  `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
@@ -160,6 +160,9 @@ function reportWarning(warning) {
160
160
  }
161
161
  } catch {
162
162
  }
163
+ emitAsProcessWarning(warning);
164
+ }
165
+ function emitAsProcessWarning(warning) {
163
166
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
164
167
  }
165
168
 
@@ -264,25 +267,26 @@ function warnAboutMissingServiceName(options, env) {
264
267
  }
265
268
  }
266
269
  function warnAboutUnsafeOptions(options) {
267
- if (options.unsafe?.disableUrlRedaction === true) {
270
+ const unsafe = options.unsafe;
271
+ if (unsafe?.disableUrlRedaction === true) {
268
272
  process.emitWarning(
269
273
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
270
274
  WARNING_OPTIONS
271
275
  );
272
276
  }
273
- if (options.unsafe?.exportProcessCommandArgs === true) {
277
+ if (unsafe?.exportProcessCommandArgs === true) {
274
278
  process.emitWarning(
275
279
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
276
280
  WARNING_OPTIONS
277
281
  );
278
282
  }
279
- if (options.unsafe?.exportHostId === true) {
283
+ if (unsafe?.exportHostId === true) {
280
284
  process.emitWarning(
281
285
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
282
286
  WARNING_OPTIONS
283
287
  );
284
288
  }
285
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
289
+ if (unsafe?.disableRedisArgumentRedaction === true) {
286
290
  process.emitWarning(
287
291
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
288
292
  WARNING_OPTIONS
@@ -290,11 +294,18 @@ function warnAboutUnsafeOptions(options) {
290
294
  }
291
295
  }
292
296
  var SHOWN_VALUE_LENGTH = 40;
297
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
298
+ function quoteOperatorValue(value) {
299
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
300
+ const hex = Number(char.codePointAt(0)).toString(16);
301
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
302
+ });
303
+ }
293
304
  function warnAboutSamplerRatio(sampler) {
294
305
  if (sampler === void 0) return;
295
306
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
307
  if (ratio >= 0 && ratio <= 1) return;
297
- const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
308
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
298
309
  reportWarning({
299
310
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
311
  text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
@@ -564,6 +575,7 @@ async function loadPackages() {
564
575
  function buildSdk(packages, options, env) {
565
576
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
566
577
  const signals = planSignals(env);
578
+ const unsafe = options.unsafe;
567
579
  return new sdkNode.NodeSDK({
568
580
  ...signals.overrides,
569
581
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -577,13 +589,13 @@ function buildSdk(packages, options, env) {
577
589
  serviceinstance: resources.serviceInstanceIdDetector
578
590
  },
579
591
  {
580
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
581
- keepHostId: options.unsafe?.exportHostId === true
592
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
593
+ keepHostId: unsafe?.exportHostId === true
582
594
  }
583
595
  ),
584
596
  spanProcessors: [
585
597
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
586
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
598
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
587
599
  new sdkTrace.BatchSpanProcessor({
588
600
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
589
601
  ...env.batchSpanProcessor
@@ -84,6 +84,9 @@ function reportWarning(warning) {
84
84
  }
85
85
  } catch {
86
86
  }
87
+ emitAsProcessWarning(warning);
88
+ }
89
+ function emitAsProcessWarning(warning) {
87
90
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
88
91
  }
89
92
 
@@ -264,25 +267,26 @@ function warnAboutMissingServiceName(options, env) {
264
267
  }
265
268
  }
266
269
  function warnAboutUnsafeOptions(options) {
267
- if (options.unsafe?.disableUrlRedaction === true) {
270
+ const unsafe = options.unsafe;
271
+ if (unsafe?.disableUrlRedaction === true) {
268
272
  process.emitWarning(
269
273
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
270
274
  WARNING_OPTIONS
271
275
  );
272
276
  }
273
- if (options.unsafe?.exportProcessCommandArgs === true) {
277
+ if (unsafe?.exportProcessCommandArgs === true) {
274
278
  process.emitWarning(
275
279
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
276
280
  WARNING_OPTIONS
277
281
  );
278
282
  }
279
- if (options.unsafe?.exportHostId === true) {
283
+ if (unsafe?.exportHostId === true) {
280
284
  process.emitWarning(
281
285
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
282
286
  WARNING_OPTIONS
283
287
  );
284
288
  }
285
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
289
+ if (unsafe?.disableRedisArgumentRedaction === true) {
286
290
  process.emitWarning(
287
291
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
288
292
  WARNING_OPTIONS
@@ -290,11 +294,18 @@ function warnAboutUnsafeOptions(options) {
290
294
  }
291
295
  }
292
296
  var SHOWN_VALUE_LENGTH = 40;
297
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
298
+ function quoteOperatorValue(value) {
299
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
300
+ const hex = Number(char.codePointAt(0)).toString(16);
301
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
302
+ });
303
+ }
293
304
  function warnAboutSamplerRatio(sampler) {
294
305
  if (sampler === void 0) return;
295
306
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
296
307
  if (ratio >= 0 && ratio <= 1) return;
297
- const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
308
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
298
309
  reportWarning({
299
310
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
300
311
  text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
@@ -573,6 +584,7 @@ async function loadPackages() {
573
584
  function buildSdk(packages, options, env) {
574
585
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
575
586
  const signals = planSignals(env);
587
+ const unsafe = options.unsafe;
576
588
  return new sdkNode.NodeSDK({
577
589
  ...signals.overrides,
578
590
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -586,13 +598,13 @@ function buildSdk(packages, options, env) {
586
598
  serviceinstance: resources.serviceInstanceIdDetector
587
599
  },
588
600
  {
589
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
590
- keepHostId: options.unsafe?.exportHostId === true
601
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
602
+ keepHostId: unsafe?.exportHostId === true
591
603
  }
592
604
  ),
593
605
  spanProcessors: [
594
606
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
595
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
607
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
596
608
  new sdkTrace.BatchSpanProcessor({
597
609
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
598
610
  ...env.batchSpanProcessor
@@ -82,6 +82,9 @@ function reportWarning(warning) {
82
82
  }
83
83
  } catch {
84
84
  }
85
+ emitAsProcessWarning(warning);
86
+ }
87
+ function emitAsProcessWarning(warning) {
85
88
  process.emitWarning(warning.text, { type: "Warning", code: warning.code });
86
89
  }
87
90
 
@@ -262,25 +265,26 @@ function warnAboutMissingServiceName(options, env) {
262
265
  }
263
266
  }
264
267
  function warnAboutUnsafeOptions(options) {
265
- if (options.unsafe?.disableUrlRedaction === true) {
268
+ const unsafe = options.unsafe;
269
+ if (unsafe?.disableUrlRedaction === true) {
266
270
  process.emitWarning(
267
271
  "URL redaction is disabled: url.query, url.full, http.url and http.target are exported as recorded.",
268
272
  WARNING_OPTIONS
269
273
  );
270
274
  }
271
- if (options.unsafe?.exportProcessCommandArgs === true) {
275
+ if (unsafe?.exportProcessCommandArgs === true) {
272
276
  process.emitWarning(
273
277
  "Process command-line redaction is disabled: process.command_args, process.command_line and process.command are exported in the resource, and command-line arguments can carry secrets.",
274
278
  WARNING_OPTIONS
275
279
  );
276
280
  }
277
- if (options.unsafe?.exportHostId === true) {
281
+ if (unsafe?.exportHostId === true) {
278
282
  process.emitWarning(
279
283
  "Host id redaction is disabled: host.id, the machine identifier, is exported in the resource, and it identifies the machine to every collector and backend.",
280
284
  WARNING_OPTIONS
281
285
  );
282
286
  }
283
- if (options.unsafe?.disableRedisArgumentRedaction === true) {
287
+ if (unsafe?.disableRedisArgumentRedaction === true) {
284
288
  process.emitWarning(
285
289
  "Redis argument redaction is disabled: command arguments, EVAL and EVALSHA payloads included, are exported in db.query.text.",
286
290
  WARNING_OPTIONS
@@ -288,11 +292,18 @@ function warnAboutUnsafeOptions(options) {
288
292
  }
289
293
  }
290
294
  var SHOWN_VALUE_LENGTH = 40;
295
+ var UNSAFE_IN_LOG = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu;
296
+ function quoteOperatorValue(value) {
297
+ return JSON.stringify(value.slice(0, SHOWN_VALUE_LENGTH)).replace(UNSAFE_IN_LOG, (char) => {
298
+ const hex = Number(char.codePointAt(0)).toString(16);
299
+ return hex.length > 4 ? `\\u{${hex}}` : `\\u${hex.padStart(4, "0")}`;
300
+ });
301
+ }
291
302
  function warnAboutSamplerRatio(sampler) {
292
303
  if (sampler === void 0) return;
293
304
  const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
294
305
  if (ratio >= 0 && ratio <= 1) return;
295
- const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
306
+ const given = sampler.arg === void 0 ? "not set" : sampler.arg.trim() === "" ? "blank" : `${quoteOperatorValue(sampler.arg)}, which is not a number from 0 to 1`;
296
307
  reportWarning({
297
308
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
298
309
  text: `OTEL_TRACES_SAMPLER is ${sampler.name}, but OTEL_TRACES_SAMPLER_ARG is ${given}, so the SDK samples every trace. Set it to the share of traces to keep, from 0 to 1, such as 0.1.`
@@ -571,6 +582,7 @@ async function loadPackages() {
571
582
  function buildSdk(packages, options, env) {
572
583
  const { sdkNode, sdkTrace, autoInstrumentations, exporter, resources } = packages;
573
584
  const signals = planSignals(env);
585
+ const unsafe = options.unsafe;
574
586
  return new sdkNode.NodeSDK({
575
587
  ...signals.overrides,
576
588
  resource: resources.resourceFromAttributes(buildResourceAttributes(options, env)),
@@ -584,13 +596,13 @@ function buildSdk(packages, options, env) {
584
596
  serviceinstance: resources.serviceInstanceIdDetector
585
597
  },
586
598
  {
587
- keepCommandLine: options.unsafe?.exportProcessCommandArgs === true,
588
- keepHostId: options.unsafe?.exportHostId === true
599
+ keepCommandLine: unsafe?.exportProcessCommandArgs === true,
600
+ keepHostId: unsafe?.exportHostId === true
589
601
  }
590
602
  ),
591
603
  spanProcessors: [
592
604
  // Ordered before the batch processor, so each span is redacted in place before it is exported.
593
- ...options.unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
605
+ ...unsafe?.disableUrlRedaction === true ? [] : [createUrlQueryRedactor()],
594
606
  new sdkTrace.BatchSpanProcessor({
595
607
  exporter: warnOnExportFailure(new exporter.OTLPTraceExporter(), "otlp-http traces"),
596
608
  ...env.batchSpanProcessor
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
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",