@bymax-one/nest-telemetry 1.0.5 → 1.0.7

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,107 @@ heading here.
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [1.0.7] - 2026-11-20
14
+
15
+ ### Fixed
16
+
17
+ - **An asynchronous `TELEMETRY_LOGGER` can no longer end the process.** The hook reports a failed flush, a
18
+ shutdown that hit its deadline and a failed span export through the application's logger and did not look
19
+ at what the logger returned, so a logger whose promise rejected (a network sink that is down) produced an
20
+ unhandled rejection, which ends a Node process by default. The returned promise is now absorbed, since the
21
+ report is best effort and nothing waits for it.
22
+
23
+ ### Documentation
24
+
25
+ - **The README says what a logger that throws or rejects does.** A synchronous throw, from a
26
+ `TELEMETRY_LOGGER` or from the logger installed with `Logger.overrideLogger`, is absorbed and the shutdown
27
+ still resolves, now pinned through a real Nest logger. A rejecting asynchronous `error` method installed
28
+ with `overrideLogger` is not caught by Nest or by this library and is an unhandled rejection.
29
+ - **The README no longer says the library never touches the sampler variables.** It reads `OTEL_TRACES_SAMPLER`
30
+ and `OTEL_TRACES_SAMPLER_ARG` to warn when the SDK will ignore a ratio argument or sample every trace, and the
31
+ variable table lists them. Two other sentences are clearer: where the Nest module reports a refused flush, and
32
+ why the Nest logger entry leaves out the error message and stack.
33
+
34
+ **Apply note.** No action is needed. If your `TELEMETRY_LOGGER` methods return promises, a rejection is now
35
+ dropped silently instead of surfacing as an unhandled rejection.
36
+
37
+ ## [1.0.6] - 2026-11-18
38
+
39
+ ### Added
40
+
41
+ - **A metrics contributor for `@bymax-one/nest-core`, on the new `./observability` subpath.**
42
+ `TelemetryMetrics` registers the counter `bymax_telemetry_span_export_failures_total`, the span export
43
+ batches the collector did not accept, with no label and with a value of 0 before the first failure. The
44
+ exporter wrapper now counts every failed export, not only the one a minute that warns, and keeps the count
45
+ on `globalThis` so the preload's copy and the application's copy agree. `@bymax-one/nest-core` and
46
+ `prom-client` are optional peers, no other entry loads them, and with the core metrics feature off nothing
47
+ is created.
48
+ - **The README catalogs the domain span names of the Bymax libraries**, with a link to each library, the
49
+ attribute and error rules of the observability standard, and the one propagator requirement of the queue.
50
+ A test now fails when the README leaves out an export of any subpath or an `OTEL_*` variable the
51
+ environment reader names.
52
+ - **A start warning for a sampler name that differs from a known one only by case or whitespace.** The SDK
53
+ compares `OTEL_TRACES_SAMPLER` exactly against `always_on`, `always_off`, `traceidratio`,
54
+ `parentbased_always_on`, `parentbased_always_off` and `parentbased_traceidratio`, replaces any other
55
+ value with its default and samples every trace, noting it only on a diagnostic channel. So
56
+ `TraceIdRatio`, ` traceidratio` or `ALWAYS_OFF` kept every trace in silence. The start now warns once
57
+ with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`, naming the name that was meant and not repeating the value.
58
+ Measured with the real SDK: `TraceIdRatio`, ` traceidratio` and `ALWAYS_OFF` with a ratio of `0` sampled
59
+ all 200 root spans, and the exact names sampled none.
60
+
61
+ ### Changed
62
+
63
+ - **An empty or whitespace-only `OTEL_TRACES_SAMPLER_ARG` is called blank, not unset.** The ratio warning said the
64
+ variable was "not set" for an empty or whitespace-only value, which sends the reader looking for a
65
+ variable that exists. An unset variable still reads "not set".
66
+ - **The winston warning says when to ignore it.** It now says to ignore it when the application never
67
+ creates a winston logger or when `OTEL_LOGS_EXPORTER` is `none`, where nothing is forwarded either way;
68
+ the README says the same and notes that the warning also fires with `instrumentations.sendLogs: true`
69
+ and with the `console` exporter. The sampler matching rule is in the README.
70
+
71
+ ### Fixed
72
+
73
+ - **The failed-flush entry on the Nest logger no longer writes the error's message or stack.** Without a
74
+ bound `TELEMETRY_LOGGER`, `TelemetryShutdownHook` wrote `TRACING_FLUSH_FAILED: <message>` with the stack to
75
+ the Nest logger. The error of an exporter can carry the endpoint it called, credentials included, in both,
76
+ so the entry now holds library text and a short error code (`UNKNOWN` unless it is an upper-case token). A bound
77
+ `TELEMETRY_LOGGER` still receives the `Error` object itself.
78
+ - **The two preload warnings no longer write the error's text.** `BYMAX_TELEMETRY_START_FAILED` and
79
+ `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` interpolated the error, and an SDK or loader error can quote its
80
+ configuration, an endpoint or a header among it. They now name its code and, when its message names one,
81
+ the OpenTelemetry package, so a missing peer is still named. One reader serves them, the flush entry and
82
+ the export warning; it reads a code only when it is a string or a number, so the `code` field of
83
+ `BYMAX_TELEMETRY_EXPORT_FAILED` is `UNKNOWN` for any other type of code, which was passed through as text
84
+ before.
85
+ - **An option key set to `undefined` or `null` is the same as no key, for every option that has a
86
+ default.** A `null` in an instrumentation override, in `ignoreIncomingRequest` or in a repeated call's
87
+ options was read as a given value: an override key set to `undefined` replaced a library default, and a
88
+ repeated start whose options were all `null` was reported as ignoring them. `env: null` threw a `TypeError` at start instead of reading the process environment. The keys are now dropped
89
+ before they are merged with the defaults, and each known option is read by property access, so options
90
+ given as a class instance with getters read as a plain object does. A table covers each defaulted option
91
+ with both values and with a class instance.
92
+
93
+ ### Apply to a derived backend
94
+
95
+ The declarations gained the `./observability` subpath; nothing else about the public types changed, and
96
+ a backend that does not use it changes nothing. A derived backend acts on these behaviours:
97
+
98
+ 1. To publish the failed-export counter, install `@bymax-one/nest-core` (1.1.0 or a later 1.x release) and `prom-client`
99
+ (15), which are optional peers, with `@nestjs/common` and `reflect-metadata` that a Nest application
100
+ already has; add `TelemetryMetrics` from `@bymax-one/nest-telemetry/observability` to the providers of
101
+ any module, and alert on `increase(bymax_telemetry_span_export_failures_total[5m]) > 0`. The exporter
102
+ counts every failed export from this release on, whether or not the metric is published.
103
+ 2. A start can now warn with `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN` for a sampler name that differs from a
104
+ known one only by case or whitespace; an environment that sets such a value was already sampling every
105
+ trace. The existing `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID` warning calls an empty or whitespace-only ratio
106
+ argument blank instead of not set, and the winston warning text says when to ignore it. An alert or a log filter
107
+ that matches either text needs the new words. The `TRACING_FLUSH_FAILED` entry on the Nest logger no
108
+ longer carries the error's message or stack: bind `TELEMETRY_LOGGER` to receive the `Error` itself. The two preload warnings now read `(code <CODE>[, package <name>])` where they quoted the error's text,
109
+ so a log filter that matched that text needs the code. The `code` of `BYMAX_TELEMETRY_EXPORT_FAILED` is `UNKNOWN` for a code that is neither a string nor a number.
110
+ 3. An option key set to `undefined` or `null` is the same as no key. A backend that set a key to `undefined` in an
111
+ instrumentation override now gets the library default, and `env: null` no longer throws a
112
+ `TypeError` at start: the process environment is read.
113
+
13
114
  ## [1.0.5] - 2026-11-17
14
115
 
15
116
  ### Added
@@ -237,6 +338,8 @@ First release.
237
338
  - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
238
339
  application, with planted secrets absent from the exported body and negative controls.
239
340
 
341
+ [1.0.7]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.7
342
+ [1.0.6]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.6
240
343
  [1.0.5]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.5
241
344
  [1.0.4]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.4
242
345
  [1.0.3]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.3
package/README.md CHANGED
@@ -81,13 +81,14 @@ 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`, `TELEMETRY_SHUTDOWN_TIMEOUT_KEY`, `TELEMETRY_EXPORT_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
+ | **Observability** | `@bymax-one/nest-telemetry/observability` | `TelemetryMetrics`, `SPAN_EXPORT_FAILURES_METRIC` | NestJS 11, `@bymax-one/nest-core`, `prom-client` |
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
+ The SDK entry and `./register` import no `@nestjs/*` package; only `./nest` and `./observability` do. `./observability` is optional: it needs `@bymax-one/nest-core` and `prom-client`, which are optional peers, and the other entries never load them. Requiring `./register` from CommonJS throws and names `node --import`.
91
92
 
92
93
  ---
93
94
 
@@ -182,6 +183,8 @@ Every field is the host's policy, and none is required.
182
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. |
183
184
  | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
184
185
 
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
+
185
188
  ### Environment variables
186
189
 
187
190
  The library reads these in one source file, and a test fails if any other file names `process.env`:
@@ -192,9 +195,10 @@ The library reads these in one source file, and a test fails if any other file n
192
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. |
193
196
  | `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | Metrics and logs are exported only when these name an exporter. |
194
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. |
195
199
  | `OTEL_NODE_RESOURCE_DETECTORS` | Selects resource detectors, under the specification's names (`service`, `host`, `process`) and the SDK's older ones. |
196
200
 
197
- 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`.
198
202
 
199
203
  ---
200
204
 
@@ -206,19 +210,20 @@ The OpenTelemetry SDK reads these itself, and the library never touches them: `O
206
210
 
207
211
  The start emits these warnings:
208
212
 
209
- | Code | Meaning |
210
- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
211
- | `BYMAX_TELEMETRY_START_FAILED` | The SDK could not start (a peer is missing, or the SDK threw). Tracing is off. |
212
- | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. |
213
- | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
214
- | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
215
- | `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. |
216
- | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
217
- | `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. |
218
- | `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. |
219
- | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID` | A ratio sampler (`traceidratio` or `parentbased_traceidratio`) is selected and `OTEL_TRACES_SAMPLER_ARG` is not a number from 0 to 1, so the SDK samples every trace. Set the share of traces to keep, such as `0.1`. |
220
- | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` | Log forwarding is on and winston is installed, but `@opentelemetry/winston-transport` cannot be resolved from the winston instrumentation, so winston records are not forwarded. Install it as a direct dependency of the application. |
221
- | `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` | An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 ms was ignored, because a timer cannot hold it and Node would clamp it to 1 ms. The default applies. |
213
+ | Code | Meaning |
214
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
215
+ | `BYMAX_TELEMETRY_START_FAILED` | The SDK could not start (a peer is missing, or the SDK threw). Tracing is off. |
216
+ | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. The warning names the error's code and package in the same way. |
217
+ | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
218
+ | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
219
+ | `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. |
220
+ | `BYMAX_TELEMETRY_RESTART_UNSUPPORTED` | `startTelemetry` was called after a shutdown in the same process, and is refused. |
221
+ | `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. |
222
+ | `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. |
223
+ | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID` | A ratio sampler (`traceidratio` or `parentbased_traceidratio`) is selected and `OTEL_TRACES_SAMPLER_ARG` is unset, blank or not a number from 0 to 1, so the SDK samples every trace. Set the share of traces to keep, such as `0.1`. |
224
+ | `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN` | `OTEL_TRACES_SAMPLER` differs from a sampler name the SDK knows only in letter case or surrounding whitespace. The SDK compares the name exactly, ignores the value and samples every trace. Write the name exactly, as the warning says. |
225
+ | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING` | Log forwarding is on and winston is installed, but `@opentelemetry/winston-transport` cannot be resolved from the winston instrumentation, so winston records are not forwarded. Install it as a direct dependency of the application, or ignore the warning when your application never creates a winston logger or `OTEL_LOGS_EXPORTER` is `none`. |
226
+ | `BYMAX_TELEMETRY_BSP_VALUE_IGNORED` | An `OTEL_BSP_SCHEDULE_DELAY` or `OTEL_BSP_EXPORT_TIMEOUT` above 2147483647 ms was ignored, because a timer cannot hold it and Node would clamp it to 1 ms. The default applies. |
222
227
 
223
228
  The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
224
229
 
@@ -232,11 +237,47 @@ The programmatic `startTelemetry` keeps its rejection when the SDK cannot start,
232
237
 
233
238
  With `OTEL_LOGS_EXPORTER=otlp`, or `instrumentations.sendLogs: true`, the records of pino, winston and bunyan go to the OpenTelemetry logs pipeline. Winston needs one more package: install `@opentelemetry/winston-transport` as a direct dependency of your application. The winston instrumentation loads it with a `require` from its own directory, and the package is not one of that instrumentation's dependencies, so without it winston records are not forwarded. Measured with winston 3.19.0 and `@opentelemetry/winston-transport` 0.35.0: a winston record reached the collector when the package was a direct dependency under npm, under pnpm 11.20.0 with the default layout and under pnpm with `hoist=false`, and it did not under npm without the package. A package that reaches the project only as another package's dependency was not measured.
234
239
 
235
- At start the library warns once, with `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING`, when log sending is on, winston resolves from the script that started the application (from the working directory when there is none), and the transport does not resolve from the winston instrumentation, which is found through `@opentelemetry/auto-instrumentations-node`. The check asks whether winston is installed, not whether it is loaded, because winston is usually not loaded yet at start: an installed winston that your application never uses causes one warning for nothing.
240
+ At start the library warns once, with `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING`, when log sending is on, winston resolves from the script that started the application (from the working directory when there is none), and the transport does not resolve from the winston instrumentation, which is found through `@opentelemetry/auto-instrumentations-node`. The check asks whether winston is installed, not whether it is loaded, because winston is usually not loaded yet at start: an installed winston that your application never uses causes one warning for nothing. The warning also appears with `instrumentations.sendLogs: true` while `OTEL_LOGS_EXPORTER` is `none`, where no record is forwarded whether the transport is installed or not, and with the `console` exporter, where it is correct.
241
+
242
+ ### Metrics
243
+
244
+ With `@bymax-one/nest-core` and `prom-client` installed, the application can publish how many span exports failed. Provide `TelemetryMetrics` from `@bymax-one/nest-telemetry/observability` in any module; `BymaxCoreModule` finds it and hands it the registry its scrape endpoint serves, only when its metrics feature is on. With metrics off, nothing is created.
245
+
246
+ ```ts
247
+ import { Module } from '@nestjs/common'
248
+ import { TelemetryMetrics } from '@bymax-one/nest-telemetry/observability'
249
+
250
+ @Module({ providers: [TelemetryMetrics] })
251
+ export class ObservabilityModule {}
252
+ ```
253
+
254
+ | Metric | Type | Labels | Meaning |
255
+ | -------------------------------------------- | ------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
256
+ | `bymax_telemetry_span_export_failures_total` | counter | none | Span export batches the collector did not accept, so the batch was dropped. Every failure is counted, while `BYMAX_TELEMETRY_EXPORT_FAILED` warns at most once a minute. |
257
+
258
+ The count is the number of failed exports since the process started. It lives on `globalThis`, as the handle does, so it is the same when the SDK starts from the preload and the application loads the library again. The series exists with a value of 0 before the first failure, so an alert on `increase(bymax_telemetry_span_export_failures_total[5m]) > 0` needs no special case. Register the contributor at most once per registry: a second registration of the name fails the boot, and says which name.
259
+
260
+ ### Span names across the Bymax libraries
261
+
262
+ This library starts the SDK and traces what the OpenTelemetry instrumentations cover (HTTP, Redis, databases). The Bymax libraries add spans of their own for their domain operations, under the name `<library>.<operation>`, through the optional `@opentelemetry/api`: with no SDK registered the API does nothing, and with this one started the spans are exported like any other. The standard asks that their attributes use the `bymax.<library>.<attribute>` namespace and closed sets of values, with no secret, no user or tenant id and no payload, and that a failure set the span status to error with the library's error code.
263
+
264
+ The names below are the ones the Bymax observability standard reserves for each library; they are not read from this repository. A library emits one from the release whose CHANGELOG lists it, and its own README documents the attributes.
265
+
266
+ | Library | Span names |
267
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------- |
268
+ | [nest-auth](https://github.com/bymaxone/nest-auth) | `auth.login`, `auth.refresh`, `auth.mfa.verify`, `auth.password_reset` |
269
+ | [nest-queue](https://github.com/bymaxone/nest-queue) | `queue.enqueue`, `queue.process` |
270
+ | [nest-notification](https://github.com/bymaxone/nest-notification) | `notification.send`, `notification.otp.verify` |
271
+ | [nest-storage](https://github.com/bymaxone/nest-storage) | `storage.upload`, `storage.download_url`, `storage.scan` |
272
+ | [nest-realtime](https://github.com/bymaxone/nest-realtime) | `realtime.handshake`, `realtime.reauthenticate` |
273
+ | [nest-ai-tokens](https://github.com/bymaxone/nest-ai-tokens) | `ai_tokens.consume`, `ai_tokens.hold`, `ai_tokens.settle` |
274
+ | [nest-core](https://github.com/bymaxone/nest-core), [nest-cache](https://github.com/bymaxone/nest-cache), [nest-logger](https://github.com/bymaxone/nest-logger), [nest-config](https://github.com/bymaxone/nest-config) | none: HTTP and Redis are traced by the instrumentations, and the other work is not a domain operation |
275
+
276
+ The standard asks `nest-queue` to carry the trace context from the request that enqueues a job into the job, as a W3C `traceparent` in the job's options metadata, so a request, its job and the job's side effects form one trace. That needs the SDK's default propagator: a host that sets `OTEL_PROPAGATORS` to a list without `tracecontext` breaks it. With no SDK registered the propagation writes nothing, and a job without a `traceparent` starts its own trace.
236
277
 
237
278
  ### Flushing
238
279
 
239
- 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.
240
281
 
241
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.
242
283
 
@@ -248,7 +289,7 @@ A start after a shutdown in the same process is refused: `startTelemetry` reject
248
289
 
249
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.
250
291
 
251
- - **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, 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. 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. It reads the process environment, as the SDK does, and not the `env` option.
252
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.
253
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.
254
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.
@@ -280,9 +321,9 @@ A caret on a `0.x` version allows patch releases only, so each OpenTelemetry min
280
321
  | No spans at all | `OTEL_SDK_DISABLED`; that the application was started with `--import`; `OTEL_EXPORTER_OTLP_ENDPOINT`; the start warnings. |
281
322
  | Spans from a CommonJS app but none from a native-ESM app | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE`: install `@opentelemetry/instrumentation`. |
282
323
  | Spans arrive but carry no service name | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING`: set `OTEL_SERVICE_NAME` or the `serviceName` option. A name set only through `OTEL_RESOURCE_ATTRIBUTES` still reaches the spans, unless `OTEL_NODE_RESOURCE_DETECTORS` leaves out both the `env` and the `service` detector. |
283
- | `BYMAX_TELEMETRY_START_FAILED` | The warning names the cause, usually an OpenTelemetry peer that is not installed. |
324
+ | `BYMAX_TELEMETRY_START_FAILED` | The warning names the error's code and, when the message names one, the OpenTelemetry package, usually a peer that is not installed. It never repeats the message, which can quote configuration. |
284
325
  | HTTP spans but no Redis spans | `ioredis` commands are traced under an active span only, and the client must be loaded after the preload. |
285
- | More traces than the sampling ratio should keep | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`: `OTEL_TRACES_SAMPLER_ARG` is unset, blank or not a number from 0 to 1, so the SDK samples every trace. |
326
+ | More traces than the sampling ratio should keep | `BYMAX_TELEMETRY_SAMPLER_ARG_INVALID`: `OTEL_TRACES_SAMPLER_ARG` is unset, blank or not a number from 0 to 1, so the SDK samples every trace; or `BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN`: `OTEL_TRACES_SAMPLER` is not written exactly (letter case or whitespace). |
286
327
  | Winston records missing from the logs pipeline | `BYMAX_TELEMETRY_WINSTON_TRANSPORT_MISSING`: install `@opentelemetry/winston-transport` as a direct dependency of the application. |
287
328
  | Metrics or logs missing | They are off unless `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` names an exporter. |
288
329
  | 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. |
@@ -411,15 +452,24 @@ No exports. `node --import @bymax-one/nest-telemetry/register` registers the loa
411
452
 
412
453
  ### Nest: `@bymax-one/nest-telemetry/nest`
413
454
 
414
- | Export | Kind | Purpose |
415
- | -------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
416
- | `TelemetryModule` | module | Global; registers `TelemetryShutdownHook`. List it first in the application module's imports |
417
- | `TelemetryShutdownHook` | provider | `OnApplicationShutdown`: awaits `shutdownTelemetry()`; a refused flush is reported and never rejects |
418
- | `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 |
419
- | `TELEMETRY_FLUSH_FAILED_KEY` | constant | The stable key, `TRACING_FLUSH_FAILED`, under which a failed flush is reported |
420
- | `TELEMETRY_SHUTDOWN_TIMEOUT_KEY` | constant | The stable key, `TRACING_SHUTDOWN_TIMEOUT`, under which a shutdown that hit `shutdownTimeoutMs` is reported |
421
- | `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 |
422
- | `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. Nest does not do the same for the logger it routes through: an asynchronous `error` method installed with `overrideLogger` 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.
466
+
467
+ ### Observability: `@bymax-one/nest-telemetry/observability`
468
+
469
+ | Export | Kind | Purpose |
470
+ | ----------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
471
+ | `TelemetryMetrics` | provider | A `@bymax-one/nest-core` metrics contributor: registers the `bymax_telemetry_span_export_failures_total` counter on the registry it is handed, with no label |
472
+ | `SPAN_EXPORT_FAILURES_METRIC` | constant | The metric name, `bymax_telemetry_span_export_failures_total` |
423
473
 
424
474
  ---
425
475
 
@@ -13,6 +13,19 @@ 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/error-code.ts
17
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
18
+ function codeOf(error) {
19
+ try {
20
+ const code = Reflect.get(Object(error), "code");
21
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
22
+ const text = String(code);
23
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
24
+ } catch {
25
+ return "UNKNOWN";
26
+ }
27
+ }
28
+
16
29
  // src/sdk/warning-sink.ts
17
30
  var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
18
31
  function registerWarningSink(sink) {
@@ -44,6 +57,9 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
44
57
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
45
58
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
46
59
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
60
+ function absorbRejection(result) {
61
+ Promise.resolve(result).catch(() => void 0);
62
+ }
47
63
  exports.TelemetryShutdownHook = class TelemetryShutdownHook {
48
64
  /**
49
65
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
@@ -90,13 +106,17 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
90
106
  route(warning) {
91
107
  const logger = this.structuredLogger();
92
108
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
93
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
109
+ absorbRejection(
110
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text))
111
+ );
94
112
  return true;
95
113
  }
96
114
  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
- });
115
+ absorbRejection(
116
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
117
+ ...warning.fields
118
+ })
119
+ );
100
120
  return true;
101
121
  }
102
122
  return false;
@@ -116,15 +136,14 @@ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
116
136
  try {
117
137
  const logger = this.structuredLogger();
118
138
  if (typeof logger?.errorStructured === "function") {
119
- logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
139
+ absorbRejection(logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure));
120
140
  return;
121
141
  }
122
142
  } catch {
123
143
  }
124
144
  try {
125
145
  new common.Logger("Telemetry").error(
126
- `${TELEMETRY_FLUSH_FAILED_KEY}: ${failure.message}`,
127
- failure.stack
146
+ `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
128
147
  );
129
148
  } catch {
130
149
  }
@@ -11,6 +11,19 @@ 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/error-code.ts
15
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
16
+ function codeOf(error) {
17
+ try {
18
+ const code = Reflect.get(Object(error), "code");
19
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
20
+ const text = String(code);
21
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
22
+ } catch {
23
+ return "UNKNOWN";
24
+ }
25
+ }
26
+
14
27
  // src/sdk/warning-sink.ts
15
28
  var SINK_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/warning-sink");
16
29
  function registerWarningSink(sink) {
@@ -42,6 +55,9 @@ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
42
55
  var TELEMETRY_SHUTDOWN_TIMEOUT_KEY = "TRACING_SHUTDOWN_TIMEOUT";
43
56
  var TELEMETRY_EXPORT_FAILED_KEY = "TRACING_EXPORT_FAILED";
44
57
  var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
58
+ function absorbRejection(result) {
59
+ Promise.resolve(result).catch(() => void 0);
60
+ }
45
61
  var TelemetryShutdownHook = class {
46
62
  /**
47
63
  * @param moduleRef - Resolves the optional structured logger when a flush fails.
@@ -88,13 +104,17 @@ var TelemetryShutdownHook = class {
88
104
  route(warning) {
89
105
  const logger = this.structuredLogger();
90
106
  if (warning.code === "BYMAX_TELEMETRY_SHUTDOWN_TIMEOUT" && typeof logger?.errorStructured === "function") {
91
- logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text));
107
+ absorbRejection(
108
+ logger.errorStructured(TELEMETRY_SHUTDOWN_TIMEOUT_KEY, new Error(warning.text))
109
+ );
92
110
  return true;
93
111
  }
94
112
  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
- });
113
+ absorbRejection(
114
+ logger.warnStructured(TELEMETRY_EXPORT_FAILED_KEY, warning.text, void 0, {
115
+ ...warning.fields
116
+ })
117
+ );
98
118
  return true;
99
119
  }
100
120
  return false;
@@ -114,15 +134,14 @@ var TelemetryShutdownHook = class {
114
134
  try {
115
135
  const logger = this.structuredLogger();
116
136
  if (typeof logger?.errorStructured === "function") {
117
- logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
137
+ absorbRejection(logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure));
118
138
  return;
119
139
  }
120
140
  } catch {
121
141
  }
122
142
  try {
123
143
  new Logger("Telemetry").error(
124
- `${TELEMETRY_FLUSH_FAILED_KEY}: ${failure.message}`,
125
- failure.stack
144
+ `${TELEMETRY_FLUSH_FAILED_KEY}: the telemetry flush failed (code ${codeOf(failure)}). Bind TELEMETRY_LOGGER to receive the error itself.`
126
145
  );
127
146
  } catch {
128
147
  }
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ var metrics = require('@bymax-one/nest-core/metrics');
4
+ var common = require('@nestjs/common');
5
+ var promClient = require('prom-client');
6
+
7
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8
+ var __decorateClass = (decorators, target, key, kind) => {
9
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
10
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
11
+ if (decorator = decorators[i])
12
+ result = (decorator(result)) || result;
13
+ return result;
14
+ };
15
+
16
+ // src/sdk/export-failure.ts
17
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
18
+ function exportFailureCount() {
19
+ const count = Reflect.get(globalThis, COUNT_KEY);
20
+ return typeof count === "number" ? count : 0;
21
+ }
22
+
23
+ // src/observability/telemetry-metrics.ts
24
+ var SPAN_EXPORT_FAILURES_METRIC = "bymax_telemetry_span_export_failures_total";
25
+ exports.TelemetryMetrics = class TelemetryMetrics {
26
+ /**
27
+ * Registers the counter on the shared registry.
28
+ *
29
+ * @param registry - The registry the scrape endpoint serves.
30
+ */
31
+ registerMetrics(registry) {
32
+ let published = 0;
33
+ new promClient.Counter({
34
+ name: SPAN_EXPORT_FAILURES_METRIC,
35
+ help: "Span export batches the collector did not accept, so the batch was dropped.",
36
+ registers: [registry],
37
+ collect() {
38
+ const total = exportFailureCount();
39
+ if (total > published) this.inc(total - published);
40
+ published = total;
41
+ }
42
+ });
43
+ }
44
+ };
45
+ exports.TelemetryMetrics = __decorateClass([
46
+ metrics.BymaxMetricsContributor(),
47
+ common.Injectable()
48
+ ], exports.TelemetryMetrics);
49
+
50
+ exports.SPAN_EXPORT_FAILURES_METRIC = SPAN_EXPORT_FAILURES_METRIC;
@@ -0,0 +1,19 @@
1
+ import { IMetricsContributor, MetricsRegistry } from '@bymax-one/nest-core/metrics';
2
+
3
+ /** The name of the counter, stable so an alert can match it. */
4
+ declare const SPAN_EXPORT_FAILURES_METRIC = "bymax_telemetry_span_export_failures_total";
5
+ /**
6
+ * Publishes `bymax_telemetry_span_export_failures_total`, the number of span export batches the
7
+ * collector did not accept, on the registry `BymaxCoreModule` hands every contributor. The counter
8
+ * has no label.
9
+ */
10
+ declare class TelemetryMetrics implements IMetricsContributor {
11
+ /**
12
+ * Registers the counter on the shared registry.
13
+ *
14
+ * @param registry - The registry the scrape endpoint serves.
15
+ */
16
+ registerMetrics(registry: MetricsRegistry): void;
17
+ }
18
+
19
+ export { SPAN_EXPORT_FAILURES_METRIC, TelemetryMetrics };
@@ -0,0 +1,19 @@
1
+ import { IMetricsContributor, MetricsRegistry } from '@bymax-one/nest-core/metrics';
2
+
3
+ /** The name of the counter, stable so an alert can match it. */
4
+ declare const SPAN_EXPORT_FAILURES_METRIC = "bymax_telemetry_span_export_failures_total";
5
+ /**
6
+ * Publishes `bymax_telemetry_span_export_failures_total`, the number of span export batches the
7
+ * collector did not accept, on the registry `BymaxCoreModule` hands every contributor. The counter
8
+ * has no label.
9
+ */
10
+ declare class TelemetryMetrics implements IMetricsContributor {
11
+ /**
12
+ * Registers the counter on the shared registry.
13
+ *
14
+ * @param registry - The registry the scrape endpoint serves.
15
+ */
16
+ registerMetrics(registry: MetricsRegistry): void;
17
+ }
18
+
19
+ export { SPAN_EXPORT_FAILURES_METRIC, TelemetryMetrics };
@@ -0,0 +1,48 @@
1
+ import { BymaxMetricsContributor } from '@bymax-one/nest-core/metrics';
2
+ import { Injectable } from '@nestjs/common';
3
+ import { Counter } from 'prom-client';
4
+
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __decorateClass = (decorators, target, key, kind) => {
7
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
8
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
9
+ if (decorator = decorators[i])
10
+ result = (decorator(result)) || result;
11
+ return result;
12
+ };
13
+
14
+ // src/sdk/export-failure.ts
15
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
16
+ function exportFailureCount() {
17
+ const count = Reflect.get(globalThis, COUNT_KEY);
18
+ return typeof count === "number" ? count : 0;
19
+ }
20
+
21
+ // src/observability/telemetry-metrics.ts
22
+ var SPAN_EXPORT_FAILURES_METRIC = "bymax_telemetry_span_export_failures_total";
23
+ var TelemetryMetrics = class {
24
+ /**
25
+ * Registers the counter on the shared registry.
26
+ *
27
+ * @param registry - The registry the scrape endpoint serves.
28
+ */
29
+ registerMetrics(registry) {
30
+ let published = 0;
31
+ new Counter({
32
+ name: SPAN_EXPORT_FAILURES_METRIC,
33
+ help: "Span export batches the collector did not accept, so the batch was dropped.",
34
+ registers: [registry],
35
+ collect() {
36
+ const total = exportFailureCount();
37
+ if (total > published) this.inc(total - published);
38
+ published = total;
39
+ }
40
+ });
41
+ }
42
+ };
43
+ TelemetryMetrics = __decorateClass([
44
+ BymaxMetricsContributor(),
45
+ Injectable()
46
+ ], TelemetryMetrics);
47
+
48
+ export { SPAN_EXPORT_FAILURES_METRIC, TelemetryMetrics };
@@ -6,6 +6,13 @@ import { join } from 'path';
6
6
  // src/sdk/environment.ts
7
7
  var MAX_TIMER_MS = 2147483647;
8
8
  var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
9
+ var SAMPLER_NAMES = [
10
+ "always_on",
11
+ "always_off",
12
+ "parentbased_always_on",
13
+ "parentbased_always_off",
14
+ ...RATIO_SAMPLERS
15
+ ];
9
16
  function readExporterList(raw) {
10
17
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
11
18
  }
@@ -55,7 +62,37 @@ function readTelemetryEnvironment(source = process.env) {
55
62
  function readRatioSampler(source = process.env) {
56
63
  const name = source["OTEL_TRACES_SAMPLER"];
57
64
  const arg = source["OTEL_TRACES_SAMPLER_ARG"];
58
- return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
65
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
66
+ }
67
+ function readSamplerNearMiss(source = process.env) {
68
+ const name = source["OTEL_TRACES_SAMPLER"];
69
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
70
+ const folded = name.trim().toLowerCase();
71
+ return SAMPLER_NAMES.find((known) => known === folded);
72
+ }
73
+
74
+ // src/sdk/error-code.ts
75
+ var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
76
+ var PACKAGE = /@opentelemetry\/[a-z0-9-]+/;
77
+ function codeOf(error) {
78
+ try {
79
+ const code = Reflect.get(Object(error), "code");
80
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
81
+ const text = String(code);
82
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
83
+ } catch {
84
+ return "UNKNOWN";
85
+ }
86
+ }
87
+ function describeFailure(error) {
88
+ const code = `code ${codeOf(error)}`;
89
+ try {
90
+ const message = Reflect.get(Object(error), "message");
91
+ const named = typeof message === "string" ? PACKAGE.exec(message)?.[0] : void 0;
92
+ return named === void 0 ? code : `${code}, package ${named}`;
93
+ } catch {
94
+ return code;
95
+ }
59
96
  }
60
97
 
61
98
  // src/sdk/redaction.ts
@@ -150,6 +187,25 @@ function planSignals(env) {
150
187
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
151
188
  };
152
189
  }
190
+ function isPresent(value) {
191
+ return value !== void 0 && value !== null;
192
+ }
193
+ function readEachOption(options) {
194
+ return {
195
+ enabled: options.enabled,
196
+ serviceName: options.serviceName,
197
+ serviceVersion: options.serviceVersion,
198
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
199
+ instrumentations: options.instrumentations,
200
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
201
+ unsafe: options.unsafe,
202
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
203
+ env: options.env
204
+ };
205
+ }
206
+ function definedEntries(config) {
207
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
208
+ }
153
209
  function nonBlank(value) {
154
210
  const trimmed = value?.trim();
155
211
  return trimmed === "" ? void 0 : trimmed;
@@ -166,7 +222,7 @@ function buildInstrumentationConfig(options, signals) {
166
222
  const instrumentations = options.instrumentations ?? {};
167
223
  const overrides = {};
168
224
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
169
- if (config !== void 0) overrides[name] = { ...config };
225
+ if (isPresent(config)) overrides[name] = definedEntries(config);
170
226
  }
171
227
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
172
228
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -189,7 +245,7 @@ function buildInstrumentationConfig(options, signals) {
189
245
  ...options.extraRedactedQueryParams ?? []
190
246
  ])
191
247
  };
192
- if (options.ignoreIncomingRequest !== void 0) {
248
+ if (isPresent(options.ignoreIncomingRequest)) {
193
249
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
194
250
  }
195
251
  if (redactRedis) {
@@ -236,14 +292,21 @@ function warnAboutUnsafeOptions(options) {
236
292
  var SHOWN_VALUE_LENGTH = 40;
237
293
  function warnAboutSamplerRatio(sampler) {
238
294
  if (sampler === void 0) return;
239
- const ratio = Number(sampler.arg);
295
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
240
296
  if (ratio >= 0 && ratio <= 1) return;
241
- const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
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`;
242
298
  reportWarning({
243
299
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
244
300
  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.`
245
301
  });
246
302
  }
303
+ function warnAboutSamplerName(meant) {
304
+ if (meant === void 0) return;
305
+ reportWarning({
306
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
307
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
308
+ });
309
+ }
247
310
  function warnAboutOversizedTimers(env) {
248
311
  for (const name of env.oversizedTimers) {
249
312
  process.emitWarning(
@@ -254,7 +317,7 @@ function warnAboutOversizedTimers(env) {
254
317
  }
255
318
  function warnAboutIgnoredOptions(options) {
256
319
  const stop = options.enabled === false;
257
- if (stop || Object.values(options).some((v) => v !== void 0)) {
320
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
258
321
  process.emitWarning(
259
322
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
260
323
  IGNORED_WARNING
@@ -264,17 +327,20 @@ function warnAboutIgnoredOptions(options) {
264
327
 
265
328
  // src/sdk/export-failure.ts
266
329
  var WINDOW_MS = 6e4;
267
- var SUCCESS = 0;
268
- var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
269
- function codeOf(error) {
270
- const code = String(Reflect.get(Object(error), "code"));
271
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
330
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
331
+ function exportFailureCount() {
332
+ const count = Reflect.get(globalThis, COUNT_KEY);
333
+ return typeof count === "number" ? count : 0;
272
334
  }
335
+ var SUCCESS = 0;
273
336
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
274
337
  const original = exporter.export.bind(exporter);
275
338
  let lastWarning = Number.NEGATIVE_INFINITY;
276
339
  exporter.export = (spans, done) => {
277
340
  original(spans, (result) => {
341
+ if (result.code !== SUCCESS) {
342
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
343
+ }
278
344
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
279
345
  lastWarning = clock();
280
346
  try {
@@ -423,7 +489,7 @@ function selectResourceDetectors(selection, detectors, keeps) {
423
489
  var TRANSPORT = "@opentelemetry/winston-transport";
424
490
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
425
491
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
426
- var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
492
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
427
493
  var resolveFrom = (id, from) => {
428
494
  try {
429
495
  return createRequire(from).resolve(id);
@@ -455,7 +521,7 @@ var DISABLED_HANDLE = {
455
521
  shutdown: () => Promise.resolve()
456
522
  };
457
523
  async function startTelemetry(options = {}) {
458
- const env = readTelemetryEnvironment(options.env);
524
+ const env = readTelemetryEnvironment(options.env ?? void 0);
459
525
  if (options.enabled === false || env.sdkDisabled) {
460
526
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
461
527
  return DISABLED_HANDLE;
@@ -532,6 +598,7 @@ async function boot(options, env) {
532
598
  warnAboutUnsafeOptions(options);
533
599
  warnAboutMissingServiceName(options, env);
534
600
  warnAboutOversizedTimers(env);
601
+ warnAboutSamplerName(readSamplerNearMiss());
535
602
  warnAboutSamplerRatio(readRatioSampler());
536
603
  warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
537
604
  const sdk = buildSdk(await loadPackages(), options, env);
@@ -565,7 +632,7 @@ async function startOrWarn(start, options) {
565
632
  return await start(options);
566
633
  } catch (error) {
567
634
  process.emitWarning(
568
- `Telemetry could not be started (${String(error)}), so the application continues without it.`,
635
+ `Telemetry could not be started (${describeFailure(error)}), so the application continues without it.`,
569
636
  { type: "Warning", code: "BYMAX_TELEMETRY_START_FAILED" }
570
637
  );
571
638
  return { enabled: false, shutdown: () => Promise.resolve() };
@@ -576,7 +643,7 @@ function registerLoaderHook(register2, parentUrl) {
576
643
  register2(ESM_HOOK_SPECIFIER, parentUrl);
577
644
  } catch (error) {
578
645
  process.emitWarning(
579
- `The OpenTelemetry loader hook could not be registered (${String(error)}), so native ES modules are not instrumented. Install @opentelemetry/instrumentation to instrument them; CommonJS code is unaffected.`,
646
+ `The OpenTelemetry loader hook could not be registered (${describeFailure(error)}), so native ES modules are not instrumented. Install @opentelemetry/instrumentation to instrument them; CommonJS code is unaffected.`,
580
647
  { type: "Warning", code: HOOK_WARNING_CODE }
581
648
  );
582
649
  }
@@ -187,6 +187,25 @@ function planSignals(env) {
187
187
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
188
188
  };
189
189
  }
190
+ function isPresent(value) {
191
+ return value !== void 0 && value !== null;
192
+ }
193
+ function readEachOption(options) {
194
+ return {
195
+ enabled: options.enabled,
196
+ serviceName: options.serviceName,
197
+ serviceVersion: options.serviceVersion,
198
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
199
+ instrumentations: options.instrumentations,
200
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
201
+ unsafe: options.unsafe,
202
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
203
+ env: options.env
204
+ };
205
+ }
206
+ function definedEntries(config) {
207
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
208
+ }
190
209
  function nonBlank(value) {
191
210
  const trimmed = value?.trim();
192
211
  return trimmed === "" ? void 0 : trimmed;
@@ -203,7 +222,7 @@ function buildInstrumentationConfig(options, signals) {
203
222
  const instrumentations = options.instrumentations ?? {};
204
223
  const overrides = {};
205
224
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
206
- if (config !== void 0) overrides[name] = { ...config };
225
+ if (isPresent(config)) overrides[name] = definedEntries(config);
207
226
  }
208
227
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
209
228
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -226,7 +245,7 @@ function buildInstrumentationConfig(options, signals) {
226
245
  ...options.extraRedactedQueryParams ?? []
227
246
  ])
228
247
  };
229
- if (options.ignoreIncomingRequest !== void 0) {
248
+ if (isPresent(options.ignoreIncomingRequest)) {
230
249
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
231
250
  }
232
251
  if (redactRedis) {
@@ -273,14 +292,21 @@ function warnAboutUnsafeOptions(options) {
273
292
  var SHOWN_VALUE_LENGTH = 40;
274
293
  function warnAboutSamplerRatio(sampler) {
275
294
  if (sampler === void 0) return;
276
- const ratio = Number(sampler.arg);
295
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
277
296
  if (ratio >= 0 && ratio <= 1) return;
278
- const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
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`;
279
298
  reportWarning({
280
299
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
281
300
  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.`
282
301
  });
283
302
  }
303
+ function warnAboutSamplerName(meant) {
304
+ if (meant === void 0) return;
305
+ reportWarning({
306
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
307
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
308
+ });
309
+ }
284
310
  function warnAboutOversizedTimers(env) {
285
311
  for (const name of env.oversizedTimers) {
286
312
  process.emitWarning(
@@ -291,7 +317,7 @@ function warnAboutOversizedTimers(env) {
291
317
  }
292
318
  function warnAboutIgnoredOptions(options) {
293
319
  const stop = options.enabled === false;
294
- if (stop || Object.values(options).some((v) => v !== void 0)) {
320
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
295
321
  process.emitWarning(
296
322
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
297
323
  IGNORED_WARNING
@@ -302,6 +328,13 @@ function warnAboutIgnoredOptions(options) {
302
328
  // src/sdk/environment.ts
303
329
  var MAX_TIMER_MS = 2147483647;
304
330
  var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
331
+ var SAMPLER_NAMES = [
332
+ "always_on",
333
+ "always_off",
334
+ "parentbased_always_on",
335
+ "parentbased_always_off",
336
+ ...RATIO_SAMPLERS
337
+ ];
305
338
  function readExporterList(raw) {
306
339
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
307
340
  }
@@ -351,22 +384,44 @@ function readTelemetryEnvironment(source = process.env) {
351
384
  function readRatioSampler(source = process.env) {
352
385
  const name = source["OTEL_TRACES_SAMPLER"];
353
386
  const arg = source["OTEL_TRACES_SAMPLER_ARG"];
354
- return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
387
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
388
+ }
389
+ function readSamplerNearMiss(source = process.env) {
390
+ const name = source["OTEL_TRACES_SAMPLER"];
391
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
392
+ const folded = name.trim().toLowerCase();
393
+ return SAMPLER_NAMES.find((known) => known === folded);
355
394
  }
356
395
 
357
- // src/sdk/export-failure.ts
358
- var WINDOW_MS = 6e4;
359
- var SUCCESS = 0;
396
+ // src/sdk/error-code.ts
360
397
  var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
361
398
  function codeOf(error) {
362
- const code = String(Reflect.get(Object(error), "code"));
363
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
399
+ try {
400
+ const code = Reflect.get(Object(error), "code");
401
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
402
+ const text = String(code);
403
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
404
+ } catch {
405
+ return "UNKNOWN";
406
+ }
364
407
  }
408
+
409
+ // src/sdk/export-failure.ts
410
+ var WINDOW_MS = 6e4;
411
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
412
+ function exportFailureCount() {
413
+ const count = Reflect.get(globalThis, COUNT_KEY);
414
+ return typeof count === "number" ? count : 0;
415
+ }
416
+ var SUCCESS = 0;
365
417
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
366
418
  const original = exporter.export.bind(exporter);
367
419
  let lastWarning = Number.NEGATIVE_INFINITY;
368
420
  exporter.export = (spans, done) => {
369
421
  original(spans, (result) => {
422
+ if (result.code !== SUCCESS) {
423
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
424
+ }
370
425
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
371
426
  lastWarning = clock();
372
427
  try {
@@ -443,7 +498,7 @@ function selectResourceDetectors(selection, detectors, keeps) {
443
498
  var TRANSPORT = "@opentelemetry/winston-transport";
444
499
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
445
500
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
446
- var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
501
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
447
502
  var resolveFrom = (id, from) => {
448
503
  try {
449
504
  return module$1.createRequire(from).resolve(id);
@@ -475,7 +530,7 @@ var DISABLED_HANDLE = {
475
530
  shutdown: () => Promise.resolve()
476
531
  };
477
532
  async function startTelemetry(options = {}) {
478
- const env = readTelemetryEnvironment(options.env);
533
+ const env = readTelemetryEnvironment(options.env ?? void 0);
479
534
  if (options.enabled === false || env.sdkDisabled) {
480
535
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
481
536
  return DISABLED_HANDLE;
@@ -552,6 +607,7 @@ async function boot(options, env) {
552
607
  warnAboutUnsafeOptions(options);
553
608
  warnAboutMissingServiceName(options, env);
554
609
  warnAboutOversizedTimers(env);
610
+ warnAboutSamplerName(readSamplerNearMiss());
555
611
  warnAboutSamplerRatio(readRatioSampler());
556
612
  warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
557
613
  const sdk = buildSdk(await loadPackages(), options, env);
@@ -185,6 +185,25 @@ function planSignals(env) {
185
185
  sendLogs: !env.logsExporters.includes("none") && env.logsExporters.some((name) => LOG_EXPORTERS.has(name))
186
186
  };
187
187
  }
188
+ function isPresent(value) {
189
+ return value !== void 0 && value !== null;
190
+ }
191
+ function readEachOption(options) {
192
+ return {
193
+ enabled: options.enabled,
194
+ serviceName: options.serviceName,
195
+ serviceVersion: options.serviceVersion,
196
+ ignoreIncomingRequest: options.ignoreIncomingRequest,
197
+ instrumentations: options.instrumentations,
198
+ extraRedactedQueryParams: options.extraRedactedQueryParams,
199
+ unsafe: options.unsafe,
200
+ shutdownTimeoutMs: options.shutdownTimeoutMs,
201
+ env: options.env
202
+ };
203
+ }
204
+ function definedEntries(config) {
205
+ return Object.fromEntries(Object.entries(config).filter(([, value]) => isPresent(value)));
206
+ }
188
207
  function nonBlank(value) {
189
208
  const trimmed = value?.trim();
190
209
  return trimmed === "" ? void 0 : trimmed;
@@ -201,7 +220,7 @@ function buildInstrumentationConfig(options, signals) {
201
220
  const instrumentations = options.instrumentations ?? {};
202
221
  const overrides = {};
203
222
  for (const [name, config] of Object.entries(instrumentations.overrides ?? {})) {
204
- if (config !== void 0) overrides[name] = { ...config };
223
+ if (isPresent(config)) overrides[name] = definedEntries(config);
205
224
  }
206
225
  const redactRedis = options.unsafe?.disableRedisArgumentRedaction !== true;
207
226
  const disableLogSending = !(instrumentations.sendLogs ?? signals.sendLogs);
@@ -224,7 +243,7 @@ function buildInstrumentationConfig(options, signals) {
224
243
  ...options.extraRedactedQueryParams ?? []
225
244
  ])
226
245
  };
227
- if (options.ignoreIncomingRequest !== void 0) {
246
+ if (isPresent(options.ignoreIncomingRequest)) {
228
247
  merged[HTTP_INSTRUMENTATION]["ignoreIncomingRequestHook"] = options.ignoreIncomingRequest;
229
248
  }
230
249
  if (redactRedis) {
@@ -271,14 +290,21 @@ function warnAboutUnsafeOptions(options) {
271
290
  var SHOWN_VALUE_LENGTH = 40;
272
291
  function warnAboutSamplerRatio(sampler) {
273
292
  if (sampler === void 0) return;
274
- const ratio = Number(sampler.arg);
293
+ const ratio = sampler.arg?.trim() === "" ? Number.NaN : Number(sampler.arg);
275
294
  if (ratio >= 0 && ratio <= 1) return;
276
- const given = sampler.arg === void 0 ? "not set" : `${JSON.stringify(sampler.arg.slice(0, SHOWN_VALUE_LENGTH))}, which is not a number from 0 to 1`;
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`;
277
296
  reportWarning({
278
297
  code: "BYMAX_TELEMETRY_SAMPLER_ARG_INVALID",
279
298
  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.`
280
299
  });
281
300
  }
301
+ function warnAboutSamplerName(meant) {
302
+ if (meant === void 0) return;
303
+ reportWarning({
304
+ code: "BYMAX_TELEMETRY_SAMPLER_NAME_UNKNOWN",
305
+ text: `OTEL_TRACES_SAMPLER differs from "${meant}" only in letter case or whitespace. The SDK compares the name exactly, so it ignores the value and samples every trace. Write it as "${meant}".`
306
+ });
307
+ }
282
308
  function warnAboutOversizedTimers(env) {
283
309
  for (const name of env.oversizedTimers) {
284
310
  process.emitWarning(
@@ -289,7 +315,7 @@ function warnAboutOversizedTimers(env) {
289
315
  }
290
316
  function warnAboutIgnoredOptions(options) {
291
317
  const stop = options.enabled === false;
292
- if (stop || Object.values(options).some((v) => v !== void 0)) {
318
+ if (stop || Object.values(readEachOption(options)).some(isPresent)) {
293
319
  process.emitWarning(
294
320
  stop ? "startTelemetry({ enabled: false }) was called while telemetry is already running. It does not stop the running SDK: call shutdownTelemetry() for that." : "startTelemetry was called while telemetry is already running, so the options of this call were ignored. Pass them to the first call.",
295
321
  IGNORED_WARNING
@@ -300,6 +326,13 @@ function warnAboutIgnoredOptions(options) {
300
326
  // src/sdk/environment.ts
301
327
  var MAX_TIMER_MS = 2147483647;
302
328
  var RATIO_SAMPLERS = ["traceidratio", "parentbased_traceidratio"];
329
+ var SAMPLER_NAMES = [
330
+ "always_on",
331
+ "always_off",
332
+ "parentbased_always_on",
333
+ "parentbased_always_off",
334
+ ...RATIO_SAMPLERS
335
+ ];
303
336
  function readExporterList(raw) {
304
337
  return (raw ?? "").split(",").map((name) => name.trim()).filter((name) => name !== "");
305
338
  }
@@ -349,22 +382,44 @@ function readTelemetryEnvironment(source = process.env) {
349
382
  function readRatioSampler(source = process.env) {
350
383
  const name = source["OTEL_TRACES_SAMPLER"];
351
384
  const arg = source["OTEL_TRACES_SAMPLER_ARG"];
352
- return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg: arg?.trim() === "" ? void 0 : arg } : void 0;
385
+ return name !== void 0 && RATIO_SAMPLERS.includes(name) ? { name, arg } : void 0;
386
+ }
387
+ function readSamplerNearMiss(source = process.env) {
388
+ const name = source["OTEL_TRACES_SAMPLER"];
389
+ if (name === void 0 || SAMPLER_NAMES.includes(name)) return void 0;
390
+ const folded = name.trim().toLowerCase();
391
+ return SAMPLER_NAMES.find((known) => known === folded);
353
392
  }
354
393
 
355
- // src/sdk/export-failure.ts
356
- var WINDOW_MS = 6e4;
357
- var SUCCESS = 0;
394
+ // src/sdk/error-code.ts
358
395
  var CODE_TOKEN = /^[A-Z0-9_]{1,40}$/;
359
396
  function codeOf(error) {
360
- const code = String(Reflect.get(Object(error), "code"));
361
- return CODE_TOKEN.test(code) ? code : "UNKNOWN";
397
+ try {
398
+ const code = Reflect.get(Object(error), "code");
399
+ if (typeof code !== "string" && typeof code !== "number") return "UNKNOWN";
400
+ const text = String(code);
401
+ return CODE_TOKEN.test(text) ? text : "UNKNOWN";
402
+ } catch {
403
+ return "UNKNOWN";
404
+ }
362
405
  }
406
+
407
+ // src/sdk/export-failure.ts
408
+ var WINDOW_MS = 6e4;
409
+ var COUNT_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/export-failures");
410
+ function exportFailureCount() {
411
+ const count = Reflect.get(globalThis, COUNT_KEY);
412
+ return typeof count === "number" ? count : 0;
413
+ }
414
+ var SUCCESS = 0;
363
415
  function warnOnExportFailure(exporter, kind, clock = () => performance.now()) {
364
416
  const original = exporter.export.bind(exporter);
365
417
  let lastWarning = Number.NEGATIVE_INFINITY;
366
418
  exporter.export = (spans, done) => {
367
419
  original(spans, (result) => {
420
+ if (result.code !== SUCCESS) {
421
+ Reflect.set(globalThis, COUNT_KEY, exportFailureCount() + 1);
422
+ }
368
423
  if (result.code !== SUCCESS && clock() - lastWarning >= WINDOW_MS) {
369
424
  lastWarning = clock();
370
425
  try {
@@ -441,7 +496,7 @@ function selectResourceDetectors(selection, detectors, keeps) {
441
496
  var TRANSPORT = "@opentelemetry/winston-transport";
442
497
  var BUNDLE = "@opentelemetry/auto-instrumentations-node";
443
498
  var INSTRUMENTATION = "@opentelemetry/instrumentation-winston";
444
- var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not reach the logs pipeline. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application does not use winston.`;
499
+ var MESSAGE = `Log forwarding is on and winston is installed, but ${TRANSPORT} cannot be resolved from ${INSTRUMENTATION}, so winston records will not be forwarded. Install ${TRANSPORT} as a direct dependency of the application, or set instrumentations.sendLogs to false. Ignore this if the application never creates a winston logger, or if OTEL_LOGS_EXPORTER is none: nothing is forwarded then either way.`;
445
500
  var resolveFrom = (id, from) => {
446
501
  try {
447
502
  return createRequire(from).resolve(id);
@@ -473,7 +528,7 @@ var DISABLED_HANDLE = {
473
528
  shutdown: () => Promise.resolve()
474
529
  };
475
530
  async function startTelemetry(options = {}) {
476
- const env = readTelemetryEnvironment(options.env);
531
+ const env = readTelemetryEnvironment(options.env ?? void 0);
477
532
  if (options.enabled === false || env.sdkDisabled) {
478
533
  if (currentHandle()?.stopping === false || pendingStart()) warnAboutIgnoredOptions(options);
479
534
  return DISABLED_HANDLE;
@@ -550,6 +605,7 @@ async function boot(options, env) {
550
605
  warnAboutUnsafeOptions(options);
551
606
  warnAboutMissingServiceName(options, env);
552
607
  warnAboutOversizedTimers(env);
608
+ warnAboutSamplerName(readSamplerNearMiss());
553
609
  warnAboutSamplerRatio(readRatioSampler());
554
610
  warnAboutMissingWinstonTransport(options.instrumentations?.sendLogs ?? planSignals(env).sendLogs);
555
611
  const sdk = buildSdk(await loadPackages(), options, env);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-telemetry",
3
- "version": "1.0.5",
3
+ "version": "1.0.7",
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",
@@ -51,6 +51,16 @@
51
51
  "default": "./dist/nest/index.cjs"
52
52
  }
53
53
  },
54
+ "./observability": {
55
+ "import": {
56
+ "types": "./dist/observability/index.d.ts",
57
+ "default": "./dist/observability/index.mjs"
58
+ },
59
+ "require": {
60
+ "types": "./dist/observability/index.d.cts",
61
+ "default": "./dist/observability/index.cjs"
62
+ }
63
+ },
54
64
  "./package.json": "./package.json"
55
65
  },
56
66
  "main": "./dist/sdk/index.cjs",
@@ -63,6 +73,9 @@
63
73
  ],
64
74
  "nest": [
65
75
  "./dist/nest/index.d.cts"
76
+ ],
77
+ "observability": [
78
+ "./dist/observability/index.d.cts"
66
79
  ]
67
80
  }
68
81
  },
@@ -74,6 +87,7 @@
74
87
  "check:mutants": "node scripts/check-mutation-directives.mjs",
75
88
  "check:published": "node scripts/check-published-surface.mjs",
76
89
  "check:file-length": "node scripts/check-file-length.mjs",
90
+ "check:function-length": "node scripts/check-function-length.mjs",
77
91
  "clean": "rm -rf dist coverage",
78
92
  "check:socket-gate": "node scripts/check-socket-gate.mjs",
79
93
  "check:spec-headers": "node scripts/check-spec-headers.mjs",
@@ -105,6 +119,7 @@
105
119
  ]
106
120
  },
107
121
  "peerDependencies": {
122
+ "@bymax-one/nest-core": "^1.1.0",
108
123
  "@nestjs/common": "^11.0.16",
109
124
  "@nestjs/core": "^11.1.18",
110
125
  "@opentelemetry/api": "^1.10.0",
@@ -114,10 +129,14 @@
114
129
  "@opentelemetry/resources": "^3.1.0",
115
130
  "@opentelemetry/sdk-node": "^0.301.0",
116
131
  "@opentelemetry/sdk-trace": "^3.1.0",
132
+ "prom-client": "^15.0.0",
117
133
  "reflect-metadata": "^0.2.0",
118
134
  "rxjs": "^7.8.0"
119
135
  },
120
136
  "peerDependenciesMeta": {
137
+ "@bymax-one/nest-core": {
138
+ "optional": true
139
+ },
121
140
  "@nestjs/common": {
122
141
  "optional": true
123
142
  },
@@ -145,6 +164,9 @@
145
164
  "@opentelemetry/sdk-trace": {
146
165
  "optional": true
147
166
  },
167
+ "prom-client": {
168
+ "optional": true
169
+ },
148
170
  "reflect-metadata": {
149
171
  "optional": true
150
172
  },
@@ -154,6 +176,7 @@
154
176
  },
155
177
  "devDependencies": {
156
178
  "@arethetypeswrong/cli": "^0.18.5",
179
+ "@bymax-one/nest-core": "1.6.10",
157
180
  "@commitlint/cli": "^21.0.2",
158
181
  "@commitlint/config-conventional": "^21.0.2",
159
182
  "@eslint/js": "^9.39.4",
@@ -194,6 +217,7 @@
194
217
  "mysql2": "3.24.6",
195
218
  "pino": "10.4.0",
196
219
  "prettier": "^3.8.3",
220
+ "prom-client": "15.1.3",
197
221
  "redis": "^6.3.1",
198
222
  "reflect-metadata": "^0.2.2",
199
223
  "rxjs": "^7.8.0",