@nestjs/observe 0.3.20 → 0.3.21

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/LICENSE CHANGED
@@ -1,22 +1,105 @@
1
- (The MIT License)
2
-
3
- Copyright (c) 2017-present Kamil Mysliwiec <https://kamilmysliwiec.com>
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining
6
- a copy of this software and associated documentation files (the
7
- 'Software'), to deal in the Software without restriction, including
8
- without limitation the rights to use, copy, modify, merge, publish,
9
- distribute, sublicense, and/or sell copies of the Software, and to
10
- permit persons to whom the Software is furnished to do so, subject to
11
- the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be
14
- included in all copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1
+ NestJS Observe Agent License
2
+
3
+ Copyright (c) 2026-present NestJS Kamil Mysliwiec <https://nestjs.com>
4
+
5
+ This license applies to this repository as published after the release of
6
+ @nestjs/observe 0.3.20, and to every version of @nestjs/observe released
7
+ after 0.3.20. Version 0.3.20 and earlier were released under the MIT License
8
+ and remain available under it (see NOTICE).
9
+
10
+ DEFINITIONS
11
+
12
+ "Licensor" or "NestJS" means NestJS Kamil Mysliwiec (https://nestjs.com).
13
+
14
+ "Software" means the source code, object code and documentation this license
15
+ applies to, and any modified version, part or derivative work of them.
16
+
17
+ "Service" means NestJS Observe, the hosted service the Licensor operates at
18
+ observe.nestjs.com, together with the collector endpoints the Licensor
19
+ operates for it.
20
+
21
+ "Telemetry" means the data the Software records about the applications it
22
+ instruments, such as traces, spans, errors, logs, metrics and profiles.
23
+
24
+ "You" means the individual or entity exercising rights under this license.
25
+
26
+ 1. GRANT
27
+
28
+ Subject to the conditions of this license, the Licensor grants You a
29
+ worldwide, royalty-free, non-exclusive, non-transferable license to use,
30
+ copy, modify and distribute the Software, solely to:
31
+
32
+ (a) instrument Your applications and send their Telemetry to the Service,
33
+ directly or through proxies and gateways that forward it to the
34
+ Service;
35
+
36
+ (b) develop, build, test, deploy and run those applications, including
37
+ with the Software disabled; and
38
+
39
+ (c) develop and test changes to the Software that You submit to the
40
+ Licensor.
41
+
42
+ 2. LIMITATIONS
43
+
44
+ You may not:
45
+
46
+ (a) use the Software to send Telemetry to any collector, backend or
47
+ service other than the Service, or a proxy or gateway that forwards
48
+ it to the Service;
49
+
50
+ (b) use the Software, including its source code, to develop, test,
51
+ document or operate a collector, backend or service that receives
52
+ Telemetry from the Software, or that substitutes for the Service;
53
+
54
+ (c) remove, disable or circumvent any part of the Software that limits
55
+ where it sends Telemetry; or
56
+
57
+ (d) remove or obscure any licensing, copyright or trademark notice in the
58
+ Software.
59
+
60
+ Exporting Telemetry through an export option included in a version of the
61
+ Software the Licensor released, such as OpenTelemetry (OTLP) export, as
62
+ documented for that version, does not violate (a).
63
+
64
+ Passing trace context, such as traceparent or x-request-id headers, between
65
+ Your applications and the services they call does not violate (a) or (b).
66
+
67
+ A collector used solely to test the Software or Your applications, that does
68
+ not store, display or provide monitoring of Telemetry for anyone, does not
69
+ violate (a) or (b).
70
+
71
+ 3. DISTRIBUTION
72
+
73
+ You may distribute the Software, modified or not, including as part of Your
74
+ applications, but only under this license. This license covers only the
75
+ Software, not the rest of Your applications. Every copy You distribute must
76
+ include this license and the NOTICE file. Recipients receive their rights
77
+ from the Licensor under this license, not from You.
78
+
79
+ 4. TERMINATION
80
+
81
+ If You use the Software in violation of this license, Your rights under it
82
+ end. If the Licensor notifies You of a violation and You stop it within 30
83
+ days of that notice, Your rights are reinstated, unless You have been
84
+ notified of a violation before.
85
+
86
+ 5. TRADEMARKS
87
+
88
+ This license grants no rights to use the names "NestJS" or "NestJS Observe",
89
+ or any related logos or trademarks, except to state that Your application
90
+ uses the Software.
91
+
92
+ 6. OTHER USES
93
+
94
+ Uses this license does not allow require a separate written agreement with
95
+ the Licensor.
96
+
97
+ 7. NO WARRANTY; LIMITATION OF LIABILITY
98
+
99
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
100
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
101
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
102
+ LICENSOR OR ANY CONTRIBUTOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
103
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
104
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
105
+ DEALINGS IN THE SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,31 @@
1
+ @nestjs/observe version 0.3.20 and earlier were released under the MIT
2
+ License and remain available under it. Later versions are released under
3
+ the NestJS Observe Agent License (see LICENSE).
4
+
5
+ Portions of this Software were contributed under the MIT License. For those
6
+ portions, the following notice applies:
7
+
8
+ --------------------------------------------------------------------------------
9
+
10
+ (The MIT License)
11
+
12
+ Copyright (c) 2017-present Kamil Mysliwiec <https://kamilmysliwiec.com>
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining
15
+ a copy of this software and associated documentation files (the
16
+ 'Software'), to deal in the Software without restriction, including
17
+ without limitation the rights to use, copy, modify, merge, publish,
18
+ distribute, sublicense, and/or sell copies of the Software, and to
19
+ permit persons to whom the Software is furnished to do so, subject to
20
+ the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be
23
+ included in all copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
26
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
28
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
29
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
30
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
31
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
  <p align="center">
8
8
  <a href="https://www.npmjs.com/package/@nestjs/observe"><img src="https://img.shields.io/npm/v/@nestjs/observe.svg" alt="NPM Version" /></a>
9
9
  <a href="https://www.npmjs.com/package/@nestjs/observe"><img src="https://img.shields.io/npm/dm/@nestjs/observe.svg" alt="NPM Downloads" /></a>
10
- <a href="https://www.npmjs.com/package/@nestjs/observe"><img src="https://img.shields.io/npm/l/@nestjs/observe.svg" alt="Package License" /></a>
10
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-Observe%20Agent-blue.svg" alt="License: NestJS Observe Agent License" /></a>
11
11
  </p>
12
12
 
13
13
  <p align="center">
@@ -38,8 +38,10 @@ Install it, set two environment variables, and the application starts reporting:
38
38
  [custom metrics](https://www.observe.nestjs.com/documentation/sdk#custom-metrics)
39
39
  your code reports through `TracerService`.
40
40
 
41
- Telemetry is serialised on a detached worker thread and shipped from there, so
42
- the request path is untouched by the reporting.
41
+ Telemetry is compressed and sent from a detached worker thread, so a slow or
42
+ unreachable collector never holds a request up. Recording it does cost the
43
+ request path a microsecond or two per traced call - [Overhead](#overhead) has
44
+ the numbers.
43
45
 
44
46
  ### Why not just OpenTelemetry?
45
47
 
@@ -105,8 +107,8 @@ The agent says so once, then backs off - one flush interval, then two, then
105
107
  four, up to one attempt an hour - until the credentials are fixed. They are
106
108
  read at startup, so that takes a restart. Leave `appKey` or `appSecret` unset,
107
109
  with nothing in `OBSERVE_APP_KEY` or `OBSERVE_APP_SECRET` either, and nothing
108
- is sent to the hosted collector at all, with a warning at startup instead; a collector of your own at `endpoint` still receives batches without
109
- them.
110
+ is sent to the hosted collector at all, with a warning at startup instead; a proxy at `endpoint` that adds them on the way to NestJS Observe still
111
+ receives batches without them.
110
112
 
111
113
  To keep an environment from reporting - local development, say - switch the
112
114
  agent off rather than supplying fake credentials, which are sent and refused:
@@ -194,6 +196,92 @@ export class ObserveConfig implements ObserveOptionsFactory {
194
196
  }
195
197
  ```
196
198
 
199
+ ## Overhead
200
+
201
+ What the agent costs an application is mostly the spans it records: every
202
+ provider method a request calls passes through the instrumentation, on the
203
+ thread serving the request. Measured in October 2026 with
204
+ [the benchmark in `bench/`](https://github.com/nestjs/observe/blob/master/bench/README.md),
205
+ the agent at its defaults against the same Nest 12 application without it, on
206
+ Express, Node 24 and an Apple M1 Pro:
207
+
208
+ | Per request | 1 traced call | 9 traced calls | 102 traced calls |
209
+ | -------------------------------------- | ------------- | -------------- | ---------------- |
210
+ | CPU added, process fully busy | +9 µs | +29 µs | +115 µs |
211
+ | Median latency added at 150 requests/s | +0.10 ms | +0.09 ms | +0.45 ms |
212
+
213
+ The nine calls are a guard, an interceptor, a pipe, a controller, a service and
214
+ two repositories awaiting their results; the 102 are a service calling another
215
+ provider in a loop, [collapsed](#repeated-spans) to six spans before shipping.
216
+
217
+ | Per process | Added |
218
+ | -------------------------- | ---------------------------------------------------- |
219
+ | Memory at boot | +11 MB RSS |
220
+ | Memory at 150 requests/s | +32 MB to +64 MB RSS |
221
+ | CPU while idle | 0.3-0.6% of one core, almost all off the main thread |
222
+ | Process start to listening | +30 to +40 ms, within run-to-run noise |
223
+
224
+ As a rule of thumb, **about 8 µs per request plus 1-2.5 µs per traced call**,
225
+ async methods at the dearer end. A traced provider reads its own fields -
226
+ `this.repository`, `this.config.rate` - through a proxy, at about 30 ns a read,
227
+ which a loop over thousands of items pays on every iteration.
228
+
229
+ Spans are recorded on the thread that serves the request. Every
230
+ `flushInterval` (5 s) that thread serialises the batch, and a worker thread
231
+ compresses and sends it. A batch holds at most `maxTracesPerBatch` traces
232
+ (1,000), which also caps what shipping costs: requests past it within a flush
233
+ interval are recorded but not sent. A lightly loaded process pays more CPU per
234
+ request than a busy one, with the agent or without, and the agent's share
235
+ grows with it: at 150 requests a second it added 3.5 to 4 points of one core on
236
+ the 1- and 9-call endpoints, and 10 on the 102-call one.
237
+
238
+ These endpoints do almost no work of their own, so in relative terms the
239
+ figures are a ceiling: an endpoint that spends a millisecond on a query pays
240
+ the same microseconds. They were taken on a development machine with other
241
+ work running, as medians of two runs, and moved by a third between runs - by
242
+ half for a lightly loaded process. The run behind them is in
243
+ [`bench/2026-10-30-results.md`](https://github.com/nestjs/observe/blob/master/bench/2026-10-30-results.md),
244
+ and `npm run bench` in a clone of this repository reproduces it on your own
245
+ hardware in about 8 minutes.
246
+
247
+ ### Compared with other agents
248
+
249
+ We found no overhead figures published by the vendors below, so the table
250
+ takes third-party benchmarks, each measuring an agent on a near-empty endpoint
251
+ on its own hardware. It says which way things lean rather than ranking them:
252
+
253
+ | Agent | Benchmark | Throughput lost | Time added per request |
254
+ | ------------------------------------------- | ---------------------------------------------- | --------------- | ---------------------- |
255
+ | New Relic | [NodeSource][nodesource], Express, Node 22 | 72% | 200 µs |
256
+ | Datadog | [NodeSource][nodesource], Express, Node 22 | 63% | 130 µs |
257
+ | Sentry | [NodeSource][nodesource], Express, Node 22 | 37% | 45 µs |
258
+ | OpenTelemetry, all auto-instrumentations | [Platformatic][platformatic], Fastify, Node 24 | 81% | 77 µs |
259
+ | OpenTelemetry, Fastify instrumentation only | [Platformatic][platformatic], Fastify, Node 24 | 64% | 31 µs |
260
+ | `@nestjs/observe`, 1 traced call | this benchmark, Nest on Express, Node 24 | 22% | 7 µs |
261
+ | `@nestjs/observe`, 9 traced calls | this benchmark, Nest on Express, Node 24 | 33% | 20 µs |
262
+ | `@nestjs/observe`, 102 traced calls | this benchmark, Nest on Express, Node 24 | 69% | 110 µs |
263
+
264
+ Time added per request is what a fully busy process spends on each request with
265
+ the agent, minus without it - one second divided by the requests per second,
266
+ from each benchmark's own figures. It is the time of the thread that serves
267
+ requests, so it reads a little under the CPU added above, which counts every
268
+ thread of the process. Neither column ranks the agents. The machines differ:
269
+ NodeSource's run (July 2025) is on a 4-core 3.6 GHz Linux server where plain
270
+ Express answers 13,000 requests a second, so the same work takes longer there
271
+ than on this laptop, where the Nest application answers 20,000 to 38,000. And a
272
+ percentage depends on how fast the baseline is: the same microseconds are a
273
+ bigger share of a faster one.
274
+
275
+ What neither column shows is how much gets recorded. The agents above trace a
276
+ request, its middleware and its calls out of the process, and OpenTelemetry's
277
+ full set more kinds of call than its Fastify instrumentation alone - DNS
278
+ lookups and sockets among them. This one also traces every provider method the
279
+ request goes through: the class-level waterfall, and the reason an endpoint
280
+ making a hundred provider calls costs it more than it would them.
281
+
282
+ [nodesource]: https://benchmark.nodesource.com/
283
+ [platformatic]: https://blog.platformatic.dev/the-hidden-cost-of-context
284
+
197
285
  ## Repeated spans
198
286
 
199
287
  Every provider is instrumented by default, framework-owned ones included, and
@@ -409,7 +497,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
409
497
  | `appKey`, `appSecret` | required | The credentials the dashboard issues - see [Getting credentials](#getting-credentials). |
410
498
  | `serviceId` | required | Names the service in the dashboard, in at most 100 characters - a longer one is cut to fit, with a warning at startup. |
411
499
  | `serviceVersion` | inferred | The release the process runs, at most 50 characters - see [What it records without any code](#what-it-records-without-any-code). `false` reports none. |
412
- | `endpoint` | `https://observe-api.nestjs.com` | The collector's base URL. `OBSERVE_ENDPOINT` in the environment changes the default without touching the config. |
500
+ | `endpoint` | `https://observe-api.nestjs.com` | The collector's base URL - NestJS Observe, or a proxy that forwards to it. `OBSERVE_ENDPOINT` in the environment changes the default without touching the config. |
413
501
  | `flushInterval` | `5000` | Milliseconds between sends of buffered telemetry; at least `1000`. |
414
502
  | `shutdownFlushTimeout` | `2000` | Milliseconds closing the app waits for buffered telemetry to reach the collector before stopping the agent. `0` skips the final send - for test suites that boot the app with real credentials. |
415
503
  | `maxTracesPerBatch` | `1000` | The most traces one send carries. |
@@ -500,4 +588,4 @@ const { createObserveModule } = require("@nestjs/observe");
500
588
 
501
589
  ## License
502
590
 
503
- `@nestjs/observe` is [MIT licensed](LICENSE).
591
+ `@nestjs/observe` is source-available under the [NestJS Observe Agent License](LICENSE): free to use and modify to send your applications' telemetry to NestJS Observe. Version 0.3.20 and earlier remain [MIT licensed](NOTICE).
@@ -351,13 +351,14 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
351
351
  };
352
352
  worker.once("exit", onExit);
353
353
  try {
354
- // Every protocol records its snapshot from a `setTimeout(0)` after the
355
- // response or job has finished, so the last requests a process served
356
- // may not be in the buffer yet - and an empty buffer would end this
357
- // before they land. A zero timer set now fires after the ones already
358
- // queued, and the microtasks each of those starts run before it does.
359
- // A trace whose spans were still open waits a further second in the
360
- // registry; the loop below waits for those too.
354
+ // Every protocol records its snapshot after the response or job has
355
+ // finished - in a microtask, or from a `setTimeout(0)` when a span was
356
+ // still open - so the last requests a process served may not be in the
357
+ // buffer yet, and an empty buffer would end this before they land. A
358
+ // zero timer set now fires after the microtasks and the timers already
359
+ // queued, and after the microtasks each of those starts. A trace whose
360
+ // spans were still open waits a further second in the registry; the
361
+ // loop below waits for those too.
361
362
  await sleep(0);
362
363
  for (;;) {
363
364
  if (exited) {
@@ -80,8 +80,64 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
80
80
  // "Object.<name>".
81
81
  const call = spec.call;
82
82
  const callUntraced = spec.callUntraced;
83
+ const endStep = (requestId, stepId) => operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId);
84
+ const recordError = (requestId, stepId, err) => {
85
+ // Before the registry records the step: `internalEndTraceStep` copies
86
+ // `err.stack` into the span payload (and, on a root span, into the
87
+ // snapshot that becomes the error group's sample), so relabelling
88
+ // afterwards would leave that copy carrying this frame's `Proxy.`.
89
+ relabelProxyFrame(err, className, methodName);
90
+ operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId, err);
91
+ };
92
+ // Runs the call inside the span's own async context. Made once per
93
+ // wrapper rather than once per call: `als.run` hands it the receiver, the
94
+ // arguments and the span's ids, so a traced call allocates no closure for
95
+ // it - and does not rename one, which cost as much again.
96
+ const callTraced = named(frameName, (thisArg, args, requestId, stepId) => {
97
+ try {
98
+ const result = call(thisArg, args);
99
+ if (result instanceof Promise) {
100
+ // Closing the span is a side effect: a registry failure must
101
+ // leave the caller with the value or rejection it would have
102
+ // seen without the span.
103
+ const settled = (value) => {
104
+ ignoreFailure(() => endStep(requestId, stepId));
105
+ return value;
106
+ };
107
+ const failed = (err) => {
108
+ ignoreFailure(() => recordError(requestId, stepId, err));
109
+ throw err;
110
+ };
111
+ // A plain native promise is swapped for a chained one, just as
112
+ // the caller's own `.then` would: a rejection the caller drops
113
+ // still raises `unhandledRejection`, as without the span.
114
+ if (isPlainPromise(result)) {
115
+ return result.then(settled, failed);
116
+ }
117
+ // A promise carrying more than its value (`json()` on a `got`
118
+ // request, `kill()` on an `execa` child, a subclass and its own
119
+ // members) is handed back as-is, or the caller loses all that.
120
+ // It is watched on a side branch instead, the way
121
+ // `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
122
+ // Watching marks it handled, so a rejection the caller drops no
123
+ // longer raises `unhandledRejection`; the span still records it.
124
+ result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
125
+ return result;
126
+ }
127
+ endStep(requestId, stepId);
128
+ return result;
129
+ }
130
+ catch (err) {
131
+ recordError(requestId, stepId, err);
132
+ // Re-throw the error to maintain original behavior
133
+ throw err;
134
+ }
135
+ finally {
136
+ spec.setActive(false);
137
+ }
138
+ });
83
139
  // A function expression, not an arrow: the wrapper has to forward whatever
84
- // `this` the caller invoked it with. Nested arrows below inherit it.
140
+ // `this` the caller invoked it with.
85
141
  return named(frameName, function (...args) {
86
142
  // Already tracing this callable, invoke it as-is
87
143
  if (spec.isActive()) {
@@ -108,66 +164,12 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
108
164
  spec.setActive(false);
109
165
  }
110
166
  }
111
- const onReturnValue = (res) => {
112
- operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId);
113
- return res;
114
- };
115
- const recordError = (err) => {
116
- // Before the registry records the step: `internalEndTraceStep` copies
117
- // `err.stack` into the span payload (and, on a root span, into the
118
- // snapshot that becomes the error group's sample), so relabelling
119
- // afterwards would leave that copy carrying this frame's `Proxy.`.
120
- relabelProxyFrame(err, className, methodName);
121
- operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId, err);
122
- };
123
- const onError = (err) => {
124
- recordError(err);
125
- // Re-throw the error to maintain original behavior
126
- throw err;
127
- };
128
- return als.run(new Map([
129
- ...(store?.entries() ?? []),
130
- [CALLER_METADATA_KEY, newStepId],
131
- ]), named(frameName, () => {
132
- try {
133
- const result = call(this, args);
134
- if (result instanceof Promise) {
135
- // Closing the span is a side effect: a registry failure must
136
- // leave the caller with the value or rejection it would have
137
- // seen without the span.
138
- const settled = (value) => {
139
- ignoreFailure(() => onReturnValue(value));
140
- return value;
141
- };
142
- const failed = (err) => {
143
- ignoreFailure(() => recordError(err));
144
- throw err;
145
- };
146
- // A plain native promise is swapped for a chained one, just as
147
- // the caller's own `.then` would: a rejection the caller drops
148
- // still raises `unhandledRejection`, as without the span.
149
- if (isPlainPromise(result)) {
150
- return result.then(settled, failed);
151
- }
152
- // A promise carrying more than its value (`json()` on a `got`
153
- // request, `kill()` on an `execa` child, a subclass and its own
154
- // members) is handed back as-is, or the caller loses all that.
155
- // It is watched on a side branch instead, the way
156
- // `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
157
- // Watching marks it handled, so a rejection the caller drops no
158
- // longer raises `unhandledRejection`; the span still records it.
159
- result.then(settled, (err) => ignoreFailure(() => recordError(err)));
160
- return result;
161
- }
162
- return onReturnValue(result);
163
- }
164
- catch (err) {
165
- onError(err);
166
- }
167
- finally {
168
- spec.setActive(false);
169
- }
170
- }));
167
+ // Everything the caller's context holds, with this span as the caller
168
+ // of whatever it calls. A copy, so the caller's context still names the
169
+ // caller once this call returns.
170
+ const spanStore = new Map(store);
171
+ spanStore.set(CALLER_METADATA_KEY, newStepId);
172
+ return als.run(spanStore, callTraced, this, args, requestId, newStepId);
171
173
  });
172
174
  };
173
175
  const instrumentFunction = (fn) => {
@@ -247,16 +249,33 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
247
249
  const requiresRawReceiver = hasPrivateMembers || slotBacked;
248
250
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
249
251
  const methodRefsCache = new WeakMap();
250
- const currentlyTracing = new WeakMap();
252
+ // Functions read off the instance that are handed out as they are:
253
+ // constructors and callable objects.
254
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
255
+ const passedThrough = new WeakSet();
251
256
  return new Proxy(instance, {
257
+ // Runs for every property read through the proxy - each `this.field`
258
+ // and `this.dependency.method` inside a traced call - so the common
259
+ // answers come first: a value that is no method, then a method already
260
+ // wrapped.
252
261
  get: (target, prop, receiver) => {
253
262
  const attributeValue = Reflect.get(target, prop);
254
- const isFunction = typeof attributeValue === "function" && prop !== "constructor";
255
- const shouldProxy = isFunction &&
256
- // A constructor held in a field - pg-pool's `this.Promise` - is
257
- // invoked with `new` and read for statics (`this.Promise.reject`);
258
- // the traced wrapper supports neither.
259
- !isConstructor(attributeValue) &&
263
+ if (typeof attributeValue !== "function" || prop === "constructor") {
264
+ return attributeValue;
265
+ }
266
+ // When "originalMethod" is already proxied, return the cached version
267
+ const cached = methodRefsCache.get(attributeValue);
268
+ if (cached) {
269
+ return cached;
270
+ }
271
+ if (passedThrough.has(attributeValue)) {
272
+ return attributeValue;
273
+ }
274
+ const shouldProxy =
275
+ // A constructor held in a field - pg-pool's `this.Promise` - is
276
+ // invoked with `new` and read for statics (`this.Promise.reject`);
277
+ // the traced wrapper supports neither.
278
+ !isConstructor(attributeValue) &&
260
279
  // A callable *object* - a Mongoose model, an Axios instance, an
261
280
  // EventEmitter-backed client - is a field, not a method. The traced
262
281
  // wrapper is a fresh bound function, so wrapping one silently drops
@@ -266,15 +285,15 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
266
285
  // own properties.
267
286
  !isCallableObject(attributeValue);
268
287
  if (!shouldProxy) {
269
- return Reflect.get(target, prop);
288
+ // Remembered, as a wrapped method is: telling them apart reads the
289
+ // function's source and its prototype's keys, which a Mongoose
290
+ // model read on every query would otherwise pay each time.
291
+ passedThrough.add(attributeValue);
292
+ return attributeValue;
270
293
  }
271
294
  const className = classNameOf(target);
272
295
  const methodName = String(prop);
273
296
  const frameName = `${className}.${methodName}`;
274
- // When "originalMethod" is already proxied, return the cached version
275
- if (methodRefsCache.has(attributeValue)) {
276
- return methodRefsCache.get(attributeValue);
277
- }
278
297
  // For a private-member class, `Reflect.get` with the proxy as receiver
279
298
  // would already throw on an accessor that touches `this.#x`, so the
280
299
  // value fetched against the target above is reused instead.
@@ -282,23 +301,17 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
282
301
  ? attributeValue
283
302
  : Reflect.get(target, prop, receiver);
284
303
  const tracedReceiver = requiresRawReceiver ? target : receiver;
304
+ // The wrapper is made once per method of this instance and cached
305
+ // below, so a flag of its own guards exactly that callable - checked
306
+ // and flipped on every traced call, where a lookup keyed by instance
307
+ // and name used to be.
308
+ let active = false;
285
309
  const proxyFn = createTracedWrapper({
286
310
  className,
287
311
  methodName,
288
312
  spanId: generateSpanId(target, methodName),
289
- isActive: () => currentlyTracing.get(target)?.has(methodName) ?? false,
290
- setActive: (active) => {
291
- if (!currentlyTracing.has(target)) {
292
- currentlyTracing.set(target, new Set());
293
- }
294
- const activeMethods = currentlyTracing.get(target);
295
- if (active) {
296
- activeMethods.add(methodName);
297
- }
298
- else {
299
- activeMethods.delete(methodName);
300
- }
301
- },
313
+ isActive: () => active,
314
+ setActive: (value) => (active = value),
302
315
  // Traced calls run against the proxy so that a method calling into
303
316
  // itself (`this.other()`) is instrumented as a nested step - except
304
317
  // for private-member classes, whose brand checks only the raw
@@ -183,7 +183,8 @@ export interface ObserveOptions {
183
183
  * One setting for telemetry and profiles both, so the two can never point at
184
184
  * different places. Defaults to the hosted collector; set `OBSERVE_ENDPOINT`
185
185
  * in the environment to override that without touching this config, which is
186
- * how a self-hosted or local collector is usually pointed at.
186
+ * how a proxy or gateway that forwards to NestJS Observe is usually pointed
187
+ * at.
187
188
  *
188
189
  * @default 'https://observe-api.nestjs.com'
189
190
  */
@@ -1,6 +1,12 @@
1
1
  import { TraceSpan } from "./trace-span.interface.js";
2
2
  export interface OngoingTraceEventNode extends TraceSpan {
3
- type: "start";
3
+ /**
4
+ * `"start"` while the call runs, `"end"` once it has returned. A node that
5
+ * has ended keeps its other fields where they are - `startTime`, an empty
6
+ * `children` - until its trace is handed off, when the tree is rebuilt into
7
+ * `CompleteTraceEventNode`s holding only what is shipped.
8
+ */
9
+ type: "start" | "end";
4
10
  /**
5
11
  * Represents the host class name, which is the class where the method being traced is defined.
6
12
  */
@@ -17,9 +23,9 @@ export interface OngoingTraceEventNode extends TraceSpan {
17
23
  /**
18
24
  * Milliseconds between the start of the trace root and the start of this span.
19
25
  *
20
- * Captured when the span opens and carried through to the completed node, so
21
- * it survives `startTime` being deleted on completion. Undefined when the
22
- * parent snapshot has already been cleaned up.
26
+ * Captured when the span opens and carried through to the completed node,
27
+ * which has no `startTime`. Undefined when the parent snapshot has already
28
+ * been cleaned up.
23
29
  */
24
30
  startOffset?: number;
25
31
  /**
@@ -31,7 +37,7 @@ export interface OngoingTraceEventNode extends TraceSpan {
31
37
  children: Array<CompleteTraceEventNode | OngoingTraceEventNode>;
32
38
  /**
33
39
  * Optional parent node for ongoing trace events.
34
- * Undefined for root nodes.
40
+ * Undefined for root nodes, and once the node has ended.
35
41
  */
36
42
  parent?: OngoingTraceEventNode;
37
43
  }
@@ -3,11 +3,11 @@ export declare const CALLER_METADATA_KEY = "#caller";
3
3
  /**
4
4
  * Where a store keeps the registry key when it differs from the trace id.
5
5
  *
6
- * A queued job reports under the trace id of the operation that enqueued it,
7
- * and that operation may still be open in this very process - an API that
8
- * also runs its own workers. The registry is keyed per execution, so the job
9
- * gets a key of its own here while `traceIdKey` keeps the id everything
10
- * user-facing reads: logs, `currentTraceId()`, the snapshot.
6
+ * Queued jobs and RPC calls can share the trace id of the operation that
7
+ * dispatched them, including one still open in this process. The registry is
8
+ * keyed per execution, so each gets a key of its own here while `traceIdKey`
9
+ * keeps the id everything user-facing reads: logs, `currentTraceId()`, the
10
+ * snapshot.
11
11
  */
12
12
  export declare const TRACE_REGISTRY_KEY = "#registryKey";
13
13
  /**