@bymax-one/nest-telemetry 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,46 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@bymax-one/nest-telemetry` are documented here.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
+
7
+ The `release.yml` workflow extracts the section matching the pushed `vX.Y.Z` tag
8
+ as the GitHub Release body, so each released version needs a matching `## [X.Y.Z]`
9
+ heading here.
10
+
11
+ ## [1.0.0] - Unreleased
12
+
13
+ First release.
14
+
15
+ ### Added
16
+
17
+ - **`.`**: `startTelemetry(options)` assembles the OpenTelemetry SDK from the host's options and the
18
+ standard `OTEL_*` variables and returns a handle; `shutdownTelemetry()` drains it; `ignorePaths(patterns)`
19
+ builds the incoming-request predicate; `DEFAULT_REDACTED_QUERY_PARAMS`. The SDK part imports no
20
+ `@nestjs/*` package.
21
+ - **`./register`**: a zero-config preload for `node --import`. It registers the OpenTelemetry loader
22
+ hook so native ES modules are instrumented, starts the SDK from the standard variables and flushes on
23
+ a natural exit. A failed start or hook is a warning, never a failed boot. Its CommonJS entry refuses to
24
+ load and names `node --import`.
25
+ - **`./nest`**: `TelemetryModule` and `TelemetryShutdownHook` flush the SDK when the application closes.
26
+ A failed flush never rejects and is reported under the stable key `TRACING_FLUSH_FAILED`, through the
27
+ structured logger bound to `TELEMETRY_LOGGER` or the Nest logger.
28
+ - **Redaction on by default**: `url.query`, `url.full`, `http.url` and `http.target` on every span; a
29
+ credential-parameter list for outgoing request URLs that a host can add to and not replace; Redis
30
+ command arguments, `EVAL` payloads included; the process command line in the exported resource. Each
31
+ of the others has an explicit `unsafe` off switch that emits a `SecurityWarning`; the credential-parameter list has none. `instrumentations.overrides`
32
+ cannot undo a layer.
33
+ - **Zero cost when disabled**: a boot with `OTEL_SDK_DISABLED=true` registers no hook and loads no
34
+ OpenTelemetry package, `@opentelemetry/api` included.
35
+ - One module reads the environment. `OTEL_SERVICE_NAME` overrides the `serviceName` option, and
36
+ `OTEL_SDK_DISABLED=true` always disables.
37
+ - Warnings with stable codes: `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED`,
38
+ `BYMAX_TELEMETRY_SERVICE_NAME_MISSING`, `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE`,
39
+ `BYMAX_TELEMETRY_START_FAILED`.
40
+ - Optional peers: `@opentelemetry/api`, `sdk-node`, `sdk-trace`, `resources`, `exporter-trace-otlp-http`,
41
+ `auto-instrumentations-node`, `instrumentation`, and `@nestjs/common`, `@nestjs/core`,
42
+ `reflect-metadata`, `rxjs` for `./nest`.
43
+ - Verification from the packed tarball: real `node --import` processes in a CommonJS and a native-ESM
44
+ application, with planted secrets absent from the exported body and negative controls.
45
+
46
+ [1.0.0]: https://github.com/bymaxone/nest-telemetry/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bymax One
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,277 @@
1
+ # @bymax-one/nest-telemetry
2
+
3
+ OpenTelemetry tracing for NestJS 11 and plain Node. It starts the SDK before your application loads, redacts secrets from spans by default (URL query strings, Redis arguments, the process command line), keeps probe paths out of your traces and flushes on shutdown.
4
+
5
+ Every OpenTelemetry package is an optional peer dependency, and a boot with telemetry disabled loads none of them. See [Security and threat model](#security-and-threat-model) for what is redacted and what is not.
6
+
7
+ ## Support matrix
8
+
9
+ | Part | Supported |
10
+ | ------------------------ | ---------------------------------------------------------------------------------------------------------------------- |
11
+ | Node.js | 24 or newer |
12
+ | NestJS (`./nest` only) | 11 |
13
+ | Applications | CommonJS and native ES modules |
14
+ | OpenTelemetry generation | `sdk-node` and exporters 0.301.x, `sdk-trace` and `resources` 3.1.x, `api` 1.10.x, `auto-instrumentations-node` 0.83.x |
15
+
16
+ The OpenTelemetry generation is the one the tests run against; how a range is widened, and how the next release is checked, is in [Peer dependencies and OpenTelemetry versions](#peer-dependencies-and-opentelemetry-versions).
17
+
18
+ **Native ES modules.** Auto-instrumentation patches CommonJS modules as they load, and native ES modules only through a loader hook. The preload registers that hook, and it needs the optional peer `@opentelemetry/instrumentation`. Without that package, a native-ESM application gets no auto-instrumentation at all; CommonJS code is unaffected, and the start warns (`BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE`) so the gap is not silent. Measured on real consumers: an ESM application with the SDK started and no hook exported no HTTP span; with the hook it did.
19
+
20
+ ## Why this exists
21
+
22
+ - **Zero cost when disabled.** A boot with `OTEL_SDK_DISABLED=true` registers no loader hook and loads no OpenTelemetry package, `@opentelemetry/api` included. This is checked from the packed tarball in ESM and CommonJS, with a positive control that proves the check can fail.
23
+ - **Secret-safe by default.** Span data is a leak surface: a magic-link token in a query string, a Redis `EVAL` payload, a secret in a command line. Each is redacted by default, and turning one off takes an explicit option that also emits a warning. There is no environment variable that turns redaction off.
24
+ - **Preload ordering done right.** The SDK has to start before the libraries it instruments are loaded, and starting it from `main.ts` is too late. A `node --import` preload runs first, and this package ships one that reads only the standard `OTEL_*` variables.
25
+
26
+ ## Quickstart: NestJS
27
+
28
+ Install the package and the OpenTelemetry peers you use:
29
+
30
+ ```sh
31
+ pnpm add @bymax-one/nest-telemetry \
32
+ @opentelemetry/api @opentelemetry/sdk-node @opentelemetry/sdk-trace @opentelemetry/resources \
33
+ @opentelemetry/exporter-trace-otlp-http @opentelemetry/auto-instrumentations-node \
34
+ @opentelemetry/instrumentation
35
+ ```
36
+
37
+ Name your service and point the exporter at a collector, using standard variables:
38
+
39
+ ```sh
40
+ export OTEL_SERVICE_NAME=billing
41
+ export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
42
+ ```
43
+
44
+ Start the application with the preload:
45
+
46
+ ```sh
47
+ node --import @bymax-one/nest-telemetry/register dist/main.js
48
+ ```
49
+
50
+ Import the module, so Nest flushes the SDK when the application closes, and enable Nest's shutdown hooks so a signal runs them:
51
+
52
+ ```ts
53
+ import { Module } from '@nestjs/common'
54
+
55
+ import { TelemetryModule } from '@bymax-one/nest-telemetry/nest'
56
+
57
+ @Module({ imports: [TelemetryModule] })
58
+ export class AppModule {}
59
+ ```
60
+
61
+ Things to know before you rely on it:
62
+
63
+ 1. **Traces only, by default.** Metrics and logs stay off unless `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` names an exporter. This departs from the OpenTelemetry default, which exports both through OTLP, and it does so on purpose: otherwise a host that already ships metrics and logs another way would send them twice.
64
+ 2. **Name your service.** With neither `OTEL_SERVICE_NAME` nor a `serviceName` option, the start warns once (`BYMAX_TELEMETRY_SERVICE_NAME_MISSING`) and spans are exported as `unknown_service:node`, which groups unrelated services under one name. The start is never refused.
65
+ 3. **Signals.** The preload flushes when the process runs out of work. It installs no signal handler, because a handler in the preload would race the application's own shutdown. In Nest, call `app.enableShutdownHooks()` so `SIGTERM` closes the application, and the module flushes the SDK. In plain Node, call `shutdownTelemetry()` yourself.
66
+
67
+ ## Quickstart: plain Node
68
+
69
+ The SDK part never imports `@nestjs/*`. Start it from your own preload, or from the first lines of your entry point if nothing instrumented has been imported yet:
70
+
71
+ ```ts
72
+ import { ignorePaths, startTelemetry } from '@bymax-one/nest-telemetry'
73
+
74
+ const telemetry = await startTelemetry({
75
+ serviceName: 'billing',
76
+ serviceVersion: '1.4.2',
77
+ ignoreIncomingRequest: ignorePaths([/^\/health\/(live|ready)\/?$/, /^\/metrics\/?$/])
78
+ })
79
+
80
+ // ... run your application ...
81
+
82
+ // In your own graceful-shutdown path, after your resources are closed:
83
+ await telemetry.shutdown()
84
+ ```
85
+
86
+ This package installs no signal handler and shows none, because handling signals belongs to the application: a `SIGTERM` listener replaces Node's default termination, so it has to end the process itself once its work is done. `startTelemetry` resolves to a handle with `enabled` and `shutdown()`. Starting twice returns the handle already running, including across two copies of the module (an ES-module preload and a CommonJS application share the handle through `globalThis`).
87
+
88
+ ## Using with the bymax-one template
89
+
90
+ If you build on the bymax-one backend template, this package is its tracing library, selected by default and optional: a derivation that does not select it deletes the dependency and its wiring together. The template keeps the policy and passes it in:
91
+
92
+ - its own `OTEL_ENABLED` switch becomes `enabled`;
93
+ - its probe paths become `ignoreIncomingRequest: ignorePaths(...)`;
94
+ - its service name and version variables become `serviceName` and `serviceVersion`, with `OTEL_SERVICE_NAME` still overriding;
95
+ - `TELEMETRY_LOGGER` is bound to its structured logger, so a failed flush keeps arriving under the key `TRACING_FLUSH_FAILED` that alerts already match.
96
+
97
+ Some behaviours differ from the code the template used before: the service name has no library default (the template passes its own), the handle is shared under a `Symbol.for` key instead of a string, and turning a redaction off now warns.
98
+
99
+ ```ts
100
+ import { Module } from '@nestjs/common'
101
+
102
+ import { TELEMETRY_LOGGER, TelemetryModule } from '@bymax-one/nest-telemetry/nest'
103
+
104
+ class AppLogger {
105
+ errorStructured(logKey: string, error: Error): void {
106
+ console.error(logKey, error.message)
107
+ }
108
+ }
109
+
110
+ @Module({
111
+ imports: [TelemetryModule],
112
+ providers: [AppLogger, { provide: TELEMETRY_LOGGER, useExisting: AppLogger }]
113
+ })
114
+ export class AppModule {}
115
+ ```
116
+
117
+ ## How it behaves
118
+
119
+ ### Enabling and disabling
120
+
121
+ The SDK starts unless something says no, and `OTEL_SDK_DISABLED=true` always says no, whatever the code passes. `enabled: false` also disables it. `OTEL_SERVICE_NAME` overrides the `serviceName` option, because the operator's standard variable should win over what the code chose. Blank values count as absent.
122
+
123
+ ### The preload
124
+
125
+ `./register` is for `node --import`. It registers the loader hook, starts the SDK from the standard variables and flushes on a natural exit. It is ES-module only in substance: requiring it from CommonJS throws and names `node --import`, because starting the SDK is asynchronous and a `--require` preload cannot wait for it, which would let the application load first, unnoticed.
126
+
127
+ Tracing never takes down a boot. Each failure the preload can meet is a warning, and the application still starts:
128
+
129
+ | Code | Meaning |
130
+ | ------------------------------------------- | ------------------------------------------------------------------------------ |
131
+ | `BYMAX_TELEMETRY_START_FAILED` | The SDK could not start (a peer is missing, or the SDK threw). Tracing is off. |
132
+ | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE` | The loader hook could not be registered. Native-ESM code is not instrumented. |
133
+ | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING` | No service name is set; spans use `unknown_service:node`. |
134
+ | `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED` | A redaction was turned off through an `unsafe` option. |
135
+
136
+ The programmatic `startTelemetry` keeps its rejection when the SDK cannot start, for callers that want it.
137
+
138
+ ### What is traced
139
+
140
+ - **Load order matters only for modules your application loads itself.** The core `http` module is patched even when the preload runs after it. A client such as `ioredis` is patched only if the preload ran before the application required it. Measured: an application that required `ioredis` first exported no `ioredis` span.
141
+ - **Redis commands are traced only under an active span.** The `ioredis` instrumentation defaults to `requireParentSpan: true`, so a command issued outside any request produces no span. Commands inside a request handler do.
142
+ - **`fs` instrumentation is off by default**, because it floods traces with disk activity that has no context. Turn it on with `instrumentations.fs`.
143
+
144
+ ### Flushing
145
+
146
+ Awaiting `shutdown()` or `shutdownTelemetry()` means the spans were exported, whoever started the flush: overlapping callers wait for the same flush, and a shutdown that arrives while the SDK is still starting waits for the start and then stops what it built. A flush the collector refuses is reported, never thrown into your shutdown path, by the Nest module; the programmatic functions reject, so their caller decides.
147
+
148
+ ## Configuration reference
149
+
150
+ ### `startTelemetry(options)`
151
+
152
+ | Option | Default | What it does |
153
+ | -------------------------------------- | ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
154
+ | `enabled` | `true` | `false` never starts the SDK. `OTEL_SDK_DISABLED=true` disables it regardless. |
155
+ | `serviceName` | `unknown_service:node` | The service name. `OTEL_SERVICE_NAME` overrides it. |
156
+ | `serviceVersion` | none | The service version. |
157
+ | `ignoreIncomingRequest` | none | Returns `true` for an incoming request that must produce no server span. `ignorePaths(patterns)` builds one from anchored patterns. |
158
+ | `instrumentations.fs` | `false` | File-system instrumentation. |
159
+ | `instrumentations.sendLogs` | follows `OTEL_LOGS_EXPORTER` | Whether pino's records are forwarded to the OpenTelemetry logs pipeline. |
160
+ | `instrumentations.overrides` | none | Per-instrumentation configuration, merged over the library's. Redaction settings cannot be replaced here. |
161
+ | `extraRedactedQueryParams` | none | Names added to the list redacted from outgoing request URLs. They add to the defaults and never replace them. |
162
+ | `unsafe.disableUrlRedaction` | off | Keeps `url.query`, `url.full`, `http.url` and `http.target` as recorded. Literal `true`. Warns. |
163
+ | `unsafe.disableRedisArgumentRedaction` | off | Keeps Redis command arguments in `db.query.text`. Literal `true`. Warns. |
164
+ | `unsafe.exportProcessCommandArgs` | off | Keeps `process.command_args` and `process.command_line` in the resource. Literal `true`. Warns. |
165
+ | `env` | the process environment | The environment the library reads. The OpenTelemetry SDK itself always reads the process environment. |
166
+
167
+ ### Environment variables
168
+
169
+ The library reads these in one source file, and a test fails if any other file names `process.env`:
170
+
171
+ | Variable | Effect |
172
+ | ----------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
173
+ | `OTEL_SDK_DISABLED` | `true` (any letter case) disables the SDK. |
174
+ | `OTEL_SERVICE_NAME` | Service name; overrides the option. |
175
+ | `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER` | Metrics and logs are exported only when these name an exporter. |
176
+ | `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. |
177
+ | `OTEL_NODE_RESOURCE_DETECTORS` | Selects resource detectors, under the specification's names (`service`, `host`, `process`) and the SDK's older ones. |
178
+
179
+ 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`.
180
+
181
+ ### Exports
182
+
183
+ | Subpath | Exports |
184
+ | ------------ | ---------------------------------------------------------------------------------------------------- |
185
+ | `.` | `startTelemetry`, `shutdownTelemetry`, `ignorePaths`, `DEFAULT_REDACTED_QUERY_PARAMS`, and the types |
186
+ | `./register` | nothing: importing it runs the preload |
187
+ | `./nest` | `TelemetryModule`, `TelemetryShutdownHook`, `TELEMETRY_LOGGER`, `TELEMETRY_FLUSH_FAILED_KEY` |
188
+
189
+ ## Security and threat model
190
+
191
+ A span can carry whatever an instrumentation or your code records on it. This package redacts what it can know is dangerous, by default, and says plainly what it does not cover.
192
+
193
+ ### Redacted by default
194
+
195
+ | Layer | What it removes |
196
+ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
197
+ | Span end, every span | `url.query` is replaced by `[redacted]`, and the query is cut from `url.full`, `http.url` and `http.target`. It runs on spans from any instrumentation, not only HTTP. |
198
+ | Outgoing request URLs | The HTTP instrumentation redacts a list of credential-bearing parameters (`token`, `code`, `access_token`, `signature`, `X-Amz-*`, and more). A host can add names, not drop them. The list is compared in a test with the SDK's own default list, so a name the SDK adds later is caught. |
199
+ | Redis | `db.query.text` holds the command name only. `EVAL` and `EVALSHA` payloads, which carry `KEYS` and `ARGV`, never leave the process. |
200
+ | Resource | `process.command_args` and `process.command_line` are left out, because command-line arguments are a common carrier of secrets. |
201
+
202
+ Each layer except the outgoing request URL list has one off switch, an `unsafe` option set to the literal `true`, and each one emits a process warning of type `SecurityWarning` with the code `BYMAX_TELEMETRY_UNSAFE_REDACTION_DISABLED`. `instrumentations.overrides` cannot undo a layer: a list of parameters you supply is added to the library's, and the Redis serializer stays the library's.
203
+
204
+ ### Not covered
205
+
206
+ These are not redacted, and you should treat them as yours to handle:
207
+
208
+ - **Secrets in the URL path.** Only the query string is removed. A path such as `/reset/<token>` is exported as it is.
209
+ - **SQL text with inline literals.** Database instrumentations record the statement; values written into it are exported.
210
+ - **`exception.message` in span events.** An exception's message is exported as recorded.
211
+ - **Span names your own code builds from raw URLs.**
212
+ - **Baggage.**
213
+ - **Request and response bodies, and HTTP headers.** They are not captured by default, and they are not redacted if you enable capturing them.
214
+ - **Attributes your own code sets.**
215
+
216
+ ### Exported on purpose
217
+
218
+ The resource carries `host.name`, `os.*`, `process.pid`, `process.owner`, the executable path and runtime facts, and `service.instance.id`. They identify the instance during an incident. If you do not want them, set `OTEL_NODE_RESOURCE_DETECTORS`.
219
+
220
+ ### How this is verified
221
+
222
+ The packed tarball is installed and run with real `node --import` processes, in a CommonJS application and a native-ESM application, against a local OTLP receiver and a fake Redis. A real HTTP request carries a planted query secret and a real `EVAL` carries a planted argument; both are absent from the whole exported body, while the HTTP spans and the Redis command name are present. Negative controls (no loader hook, no preload, a preload loaded after `ioredis`, `OTEL_SDK_DISABLED=true`) export no such span, so the checks can fail. The proof covers the HTTP and `ioredis` instrumentations; the span-end layer works on attributes, so it applies to spans from other instrumentations too, but those are not each proven individually.
223
+
224
+ To report a vulnerability, follow [SECURITY.md](./SECURITY.md).
225
+
226
+ ## Peer dependencies and OpenTelemetry versions
227
+
228
+ Every `@opentelemetry/*` package is an optional peer. The `0.x` packages break between minors, and `sdk-node` pins its own dependencies to exact versions, so the ranges here name only the generation the tests run against:
229
+
230
+ | Package | Range |
231
+ | ------------------------------------------- | ---------- |
232
+ | `@opentelemetry/api` | `^1.10.0` |
233
+ | `@opentelemetry/sdk-node` | `^0.301.0` |
234
+ | `@opentelemetry/exporter-trace-otlp-http` | `^0.301.0` |
235
+ | `@opentelemetry/instrumentation` | `^0.301.0` |
236
+ | `@opentelemetry/sdk-trace` | `^3.1.0` |
237
+ | `@opentelemetry/resources` | `^3.1.0` |
238
+ | `@opentelemetry/auto-instrumentations-node` | `^0.83.0` |
239
+
240
+ A caret on a `0.x` version allows patch releases only, so each OpenTelemetry minor needs a release of this package to widen the range. That is a human decision: a weekly job runs the unit and end-to-end suites, the build and the tarball checks against the newest release of every OpenTelemetry package, ignoring the lockfile, and opens an issue when they fail. A range is widened in a pull request after the job passes against the new generation. Dependabot groups the OpenTelemetry packages, so they move as one set.
241
+
242
+ ## Comparison with wiring the SDK by hand
243
+
244
+ | You would otherwise write and maintain | This package |
245
+ | ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------- |
246
+ | A preload that starts the SDK before the application loads | `node --import @bymax-one/nest-telemetry/register`, reading the standard variables |
247
+ | The loader hook for native-ESM applications | Registered by the preload, with a warning when its peer is missing |
248
+ | Query-string redaction for every span, and the credential parameter list | On by default; the list is checked against the SDK's own |
249
+ | A Redis serializer that keeps `EVAL` payloads out of spans | On by default |
250
+ | Keeping the command line out of the resource | On by default |
251
+ | Mapping `OTEL_BSP_*` onto the batch processor you pass | Done |
252
+ | Sharing the SDK between a preload and the application | A handle under a `Symbol.for` key, one SDK even across module copies |
253
+ | Flushing on shutdown without racing the framework's own shutdown | `TelemetryModule` flushes through Nest's hook; a failed flush is reported, never thrown |
254
+ | Making sure a telemetry failure cannot stop the host from booting | Each failure the preload can meet is a warning |
255
+
256
+ What it does not do for you: choose a sampler, run a collector, or decide your span names. Those stay standard OpenTelemetry configuration.
257
+
258
+ ## Troubleshooting
259
+
260
+ | You see | Look at |
261
+ | -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
262
+ | No spans at all | `OTEL_SDK_DISABLED`; that the application was started with `--import`; `OTEL_EXPORTER_OTLP_ENDPOINT`; the start warnings. |
263
+ | Spans from a CommonJS app but none from a native-ESM app | `BYMAX_TELEMETRY_ESM_HOOK_UNAVAILABLE`: install `@opentelemetry/instrumentation`. |
264
+ | Spans arrive but carry no service name | `BYMAX_TELEMETRY_SERVICE_NAME_MISSING`: set `OTEL_SERVICE_NAME` or the `serviceName` option. |
265
+ | `BYMAX_TELEMETRY_START_FAILED` | The warning names the cause, usually an OpenTelemetry peer that is not installed. |
266
+ | HTTP spans but no Redis spans | Commands are traced under an active span only, and `ioredis` must be loaded after the preload. |
267
+ | Metrics or logs missing | They are off unless `OTEL_METRICS_EXPORTER` or `OTEL_LOGS_EXPORTER` names an exporter. |
268
+ | The last spans are lost on `SIGTERM` | Call `app.enableShutdownHooks()` in Nest, or `shutdownTelemetry()` from your own shutdown path. |
269
+ | A query string still appears in a span | It is on an attribute other than `url.query`, `url.full`, `http.url` or `http.target`: see [Not covered](#not-covered). |
270
+
271
+ ## Compatibility and versioning
272
+
273
+ This package does not promise strict semantic versioning. Each release in the [CHANGELOG](./CHANGELOG.md) says what changed and what to do about it, and the version number alone is not the compatibility information. See [CONTRIBUTING.md](./CONTRIBUTING.md) to contribute.
274
+
275
+ ## License
276
+
277
+ [MIT](./LICENSE)
@@ -0,0 +1,111 @@
1
+ 'use strict';
2
+
3
+ var common = require('@nestjs/common');
4
+ var core = require('@nestjs/core');
5
+
6
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
+ var __decorateClass = (decorators, target, key, kind) => {
8
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
9
+ for (var i = decorators.length - 1, decorator; i >= 0; i--)
10
+ if (decorator = decorators[i])
11
+ result = (decorator(result)) || result;
12
+ return result;
13
+ };
14
+ var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
15
+
16
+ // src/sdk/handle.ts
17
+ var HANDLE_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/handle");
18
+ var PENDING_KEY = /* @__PURE__ */ Symbol.for("@bymax-one/nest-telemetry/pending-start");
19
+ var store = globalThis;
20
+ function currentHandle() {
21
+ return store[HANDLE_KEY];
22
+ }
23
+ function pendingStart() {
24
+ return store[PENDING_KEY];
25
+ }
26
+ async function shutdownTelemetry() {
27
+ await Promise.allSettled([pendingStart()]);
28
+ await currentHandle()?.shutdown();
29
+ }
30
+
31
+ // src/nest/telemetry-shutdown.hook.ts
32
+ var TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
33
+ var TELEMETRY_LOGGER = /* @__PURE__ */ Symbol("TELEMETRY_LOGGER");
34
+ exports.TelemetryShutdownHook = class TelemetryShutdownHook {
35
+ /**
36
+ * @param moduleRef - Resolves the optional structured logger when a flush fails.
37
+ */
38
+ constructor(moduleRef) {
39
+ this.moduleRef = moduleRef;
40
+ }
41
+ /**
42
+ * Flushes and stops the SDK, if one was started.
43
+ *
44
+ * Nest awaits this while closing the application, so awaiting the flush here guarantees buffered
45
+ * spans are exported before the process exits. A flush the collector refuses, or one the batch
46
+ * processor abandons after its export timeout, is reported and ends there: an orchestrator reads
47
+ * the exit code, and a collector outage is not a crashed instance.
48
+ *
49
+ * @returns A promise that resolves once buffered spans are exported, or once a failed export
50
+ * has been reported. Never rejects.
51
+ */
52
+ async onApplicationShutdown() {
53
+ try {
54
+ await shutdownTelemetry();
55
+ } catch (error) {
56
+ this.report(error);
57
+ }
58
+ }
59
+ /**
60
+ * Reports a failed flush: through the structured logger when the application provides a usable
61
+ * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
62
+ * every step, because the hook's one job is to keep shutdown from failing: a logger the
63
+ * application bound to the token that is the wrong value, or that throws, falls through to the
64
+ * Nest logger, and a Nest logger that throws ends the report.
65
+ *
66
+ * @param error - The rejection. A value that is not an `Error` is not stringified, since its
67
+ * `toString` could throw here.
68
+ */
69
+ report(error) {
70
+ const failure = error instanceof Error ? error : new Error("The telemetry SDK failed to shut down.");
71
+ try {
72
+ const logger = this.structuredLogger();
73
+ if (typeof logger?.errorStructured === "function") {
74
+ logger.errorStructured(TELEMETRY_FLUSH_FAILED_KEY, failure);
75
+ return;
76
+ }
77
+ } catch {
78
+ }
79
+ try {
80
+ new common.Logger("Telemetry").error(
81
+ `${TELEMETRY_FLUSH_FAILED_KEY}: ${failure.message}`,
82
+ failure.stack
83
+ );
84
+ } catch {
85
+ }
86
+ }
87
+ /**
88
+ * Looks the structured logger up.
89
+ *
90
+ * @returns The logger, or `undefined` when the application provides none.
91
+ */
92
+ structuredLogger() {
93
+ try {
94
+ return this.moduleRef.get(TELEMETRY_LOGGER, { strict: false });
95
+ } catch {
96
+ return void 0;
97
+ }
98
+ }
99
+ };
100
+ exports.TelemetryShutdownHook = __decorateClass([
101
+ common.Injectable(),
102
+ __decorateParam(0, common.Inject(core.ModuleRef))
103
+ ], exports.TelemetryShutdownHook);
104
+ exports.TelemetryModule = class TelemetryModule {
105
+ };
106
+ exports.TelemetryModule = __decorateClass([
107
+ common.Module({ providers: [exports.TelemetryShutdownHook] })
108
+ ], exports.TelemetryModule);
109
+
110
+ exports.TELEMETRY_FLUSH_FAILED_KEY = TELEMETRY_FLUSH_FAILED_KEY;
111
+ exports.TELEMETRY_LOGGER = TELEMETRY_LOGGER;
@@ -0,0 +1,76 @@
1
+ import { OnApplicationShutdown } from '@nestjs/common';
2
+
3
+ /** Log key of the entry a failed flush leaves, stable so an alert can match it. */
4
+ declare const TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
5
+ /** Injection token of the optional structured logger a failed flush is reported through. */
6
+ declare const TELEMETRY_LOGGER: unique symbol;
7
+ /** The one call the hook makes on a structured logger. */
8
+ interface ITelemetryErrorLogger {
9
+ /**
10
+ * Writes an error entry under a log key.
11
+ *
12
+ * @param logKey - The entry's log key.
13
+ * @param error - The failure.
14
+ */
15
+ errorStructured(logKey: string, error: Error): void;
16
+ }
17
+ /** What the hook needs of Nest's module reference: to look a provider up anywhere in the application. */
18
+ interface IProviderLookup {
19
+ /**
20
+ * Resolves a provider by token, throwing when there is none.
21
+ *
22
+ * @param token - The injection token.
23
+ * @param options - Looks beyond the hook's own module.
24
+ */
25
+ get(token: symbol, options: {
26
+ strict: false;
27
+ }): unknown;
28
+ }
29
+ /** Awaits the SDK flush as part of the application's own graceful shutdown. */
30
+ declare class TelemetryShutdownHook implements OnApplicationShutdown {
31
+ private readonly moduleRef;
32
+ /**
33
+ * @param moduleRef - Resolves the optional structured logger when a flush fails.
34
+ */
35
+ constructor(moduleRef: IProviderLookup);
36
+ /**
37
+ * Flushes and stops the SDK, if one was started.
38
+ *
39
+ * Nest awaits this while closing the application, so awaiting the flush here guarantees buffered
40
+ * spans are exported before the process exits. A flush the collector refuses, or one the batch
41
+ * processor abandons after its export timeout, is reported and ends there: an orchestrator reads
42
+ * the exit code, and a collector outage is not a crashed instance.
43
+ *
44
+ * @returns A promise that resolves once buffered spans are exported, or once a failed export
45
+ * has been reported. Never rejects.
46
+ */
47
+ onApplicationShutdown(): Promise<void>;
48
+ /**
49
+ * Reports a failed flush: through the structured logger when the application provides a usable
50
+ * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
51
+ * every step, because the hook's one job is to keep shutdown from failing: a logger the
52
+ * application bound to the token that is the wrong value, or that throws, falls through to the
53
+ * Nest logger, and a Nest logger that throws ends the report.
54
+ *
55
+ * @param error - The rejection. A value that is not an `Error` is not stringified, since its
56
+ * `toString` could throw here.
57
+ */
58
+ private report;
59
+ /**
60
+ * Looks the structured logger up.
61
+ *
62
+ * @returns The logger, or `undefined` when the application provides none.
63
+ */
64
+ private structuredLogger;
65
+ }
66
+
67
+ /**
68
+ * Import it in the application module. Nest then awaits the SDK flush while closing the
69
+ * application, so buffered spans are exported before the process exits. The SDK itself is started
70
+ * by the `./register` preload or by `startTelemetry`, outside Nest.
71
+ */
72
+ declare class TelemetryModule {
73
+ }
74
+
75
+ export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
76
+ export type { ITelemetryErrorLogger };
@@ -0,0 +1,76 @@
1
+ import { OnApplicationShutdown } from '@nestjs/common';
2
+
3
+ /** Log key of the entry a failed flush leaves, stable so an alert can match it. */
4
+ declare const TELEMETRY_FLUSH_FAILED_KEY = "TRACING_FLUSH_FAILED";
5
+ /** Injection token of the optional structured logger a failed flush is reported through. */
6
+ declare const TELEMETRY_LOGGER: unique symbol;
7
+ /** The one call the hook makes on a structured logger. */
8
+ interface ITelemetryErrorLogger {
9
+ /**
10
+ * Writes an error entry under a log key.
11
+ *
12
+ * @param logKey - The entry's log key.
13
+ * @param error - The failure.
14
+ */
15
+ errorStructured(logKey: string, error: Error): void;
16
+ }
17
+ /** What the hook needs of Nest's module reference: to look a provider up anywhere in the application. */
18
+ interface IProviderLookup {
19
+ /**
20
+ * Resolves a provider by token, throwing when there is none.
21
+ *
22
+ * @param token - The injection token.
23
+ * @param options - Looks beyond the hook's own module.
24
+ */
25
+ get(token: symbol, options: {
26
+ strict: false;
27
+ }): unknown;
28
+ }
29
+ /** Awaits the SDK flush as part of the application's own graceful shutdown. */
30
+ declare class TelemetryShutdownHook implements OnApplicationShutdown {
31
+ private readonly moduleRef;
32
+ /**
33
+ * @param moduleRef - Resolves the optional structured logger when a flush fails.
34
+ */
35
+ constructor(moduleRef: IProviderLookup);
36
+ /**
37
+ * Flushes and stops the SDK, if one was started.
38
+ *
39
+ * Nest awaits this while closing the application, so awaiting the flush here guarantees buffered
40
+ * spans are exported before the process exits. A flush the collector refuses, or one the batch
41
+ * processor abandons after its export timeout, is reported and ends there: an orchestrator reads
42
+ * the exit code, and a collector outage is not a crashed instance.
43
+ *
44
+ * @returns A promise that resolves once buffered spans are exported, or once a failed export
45
+ * has been reported. Never rejects.
46
+ */
47
+ onApplicationShutdown(): Promise<void>;
48
+ /**
49
+ * Reports a failed flush: through the structured logger when the application provides a usable
50
+ * one, else through the Nest logger with the key in the message. Reporting is itself guarded at
51
+ * every step, because the hook's one job is to keep shutdown from failing: a logger the
52
+ * application bound to the token that is the wrong value, or that throws, falls through to the
53
+ * Nest logger, and a Nest logger that throws ends the report.
54
+ *
55
+ * @param error - The rejection. A value that is not an `Error` is not stringified, since its
56
+ * `toString` could throw here.
57
+ */
58
+ private report;
59
+ /**
60
+ * Looks the structured logger up.
61
+ *
62
+ * @returns The logger, or `undefined` when the application provides none.
63
+ */
64
+ private structuredLogger;
65
+ }
66
+
67
+ /**
68
+ * Import it in the application module. Nest then awaits the SDK flush while closing the
69
+ * application, so buffered spans are exported before the process exits. The SDK itself is started
70
+ * by the `./register` preload or by `startTelemetry`, outside Nest.
71
+ */
72
+ declare class TelemetryModule {
73
+ }
74
+
75
+ export { TELEMETRY_FLUSH_FAILED_KEY, TELEMETRY_LOGGER, TelemetryModule, TelemetryShutdownHook };
76
+ export type { ITelemetryErrorLogger };