@nestjs/observe 0.3.19 → 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 +105 -22
- package/NOTICE +31 -0
- package/README.md +97 -8
- package/dist/agent/observe-agent.worker.js +8 -7
- package/dist/instrument/create-instance-decorator.instrument.js +134 -88
- package/dist/interfaces/observe-options.interface.d.ts +18 -2
- package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
- package/dist/observe.constants.d.ts +5 -5
- package/dist/observe.constants.js +5 -5
- package/dist/observe.module.js +12 -0
- package/dist/outgoing/http.integration.js +4 -0
- package/dist/outgoing/llm/llm-fetch.integration.d.ts +56 -0
- package/dist/outgoing/llm/llm-fetch.integration.js +236 -0
- package/dist/outgoing/llm/llm-providers.d.ts +25 -0
- package/dist/outgoing/llm/llm-providers.js +96 -0
- package/dist/outgoing/llm/llm-usage.d.ts +67 -0
- package/dist/outgoing/llm/llm-usage.js +263 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +1 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +12 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +9 -0
- package/dist/outgoing/outgoing-span.recorder.js +55 -6
- package/dist/protocols/deferred-trace-completion.d.ts +13 -2
- package/dist/protocols/deferred-trace-completion.js +27 -4
- package/dist/protocols/graphql-observe-agent.service.js +1 -1
- package/dist/protocols/http-observe-agent.service.js +20 -28
- package/dist/protocols/job-trace-runner.js +2 -2
- package/dist/protocols/rpc-observe-agent.service.js +19 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/collapse-repeated-spans.util.js +41 -37
- package/dist/services/operation-trace.registry.d.ts +15 -9
- package/dist/services/operation-trace.registry.js +79 -25
- package/dist/utils/uuid-v7.util.js +53 -15
- package/package.json +5 -3
package/LICENSE
CHANGED
|
@@ -1,22 +1,105 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
Copyright (c)
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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="
|
|
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
|
|
42
|
-
|
|
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
|
|
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
|
|
@@ -288,6 +376,7 @@ Once the module and the instrument are in place, the agent reports, with no furt
|
|
|
288
376
|
- **Requests, GraphQL operations, RPC messages, WebSocket gateway messages, queue jobs and scheduled jobs**, each with its tree of provider method calls.
|
|
289
377
|
- **Database queries**, as a span under the method that ran them, for `pg`, `mysql2`, `mssql` and `mongodb`. Anything built on those drivers is covered without being known by name: TypeORM, Drizzle, MikroORM and Mongoose are tested in this repository, and others (Knex, Sequelize) go through the same driver calls. SQL Server is the exception: `mssql` is what TypeORM and Prisma's SQL Server adapter run on, but Knex, Sequelize and MikroORM talk to SQL Server through `tedious` directly, which is not covered yet (nor is `mssql/msnodesqlv8`). The statement is recorded with every value removed (`SELECT "o"."id" FROM "orders" "o" WHERE "o"."customer_id" = $1`). Prisma's Rust query engine does not go through these drivers and is not covered yet.
|
|
290
378
|
- **Outbound HTTP calls** made with `fetch`/`undici` or `node:http`/`https` (so Axios too), as `POST api.stripe.com`. The current trace id is forwarded as `x-request-id` - by `fetch` on every supported Node version, by `node:http`/`https` from Node 22.12, the first to let a request's headers still be set at that point - so a service that also runs the agent continues the same trace; a header you set yourself is never overwritten.
|
|
379
|
+
- **Model calls**: a `fetch` to OpenAI, Azure OpenAI, Anthropic, Gemini or Vertex, Bedrock, Mistral, Groq, OpenRouter, Together, DeepSeek, xAI, Cohere or Perplexity also reports the model and the input, output and cached tokens its response states - read as the response passes through to your code, streams included, so it arrives exactly as it would have and a stream you cancel is cancelled at the provider too. That covers the official SDKs, the Vercel AI SDK and LangChain, which all use `fetch`; calls made through `node:http` (axios, the AWS SDK) keep their plain span. Prompts and completions are never reported. A gateway in front of the providers is added with `outgoing: { llm: { hosts: ['llm-gateway.internal:4000'] } }`, and `outgoing: { llm: false }` turns this off and leaves the global `fetch` as it was.
|
|
291
380
|
- **Trace ids across queues**: a BullMQ (Pro included) or Bull job enqueued while handling a request carries that request's trace id, so the request and its job show up as one trace. Repeatable (cron) jobs start their own.
|
|
292
381
|
- **The code around an error's throw site**: for each in-app frame of a captured error, a few lines of source either side, read from the running process, so the dashboard shows the failing code next to the stack. This sends fragments of your application's source to Observe, stored with the error. Frames in `node_modules` and Node internals are never read. `createObserveModule({ sourceContext: false })` turns it off; the [documentation](https://www.observe.nestjs.com/documentation/sdk#error-source-context) covers tuning it instead.
|
|
293
382
|
- **The release it is running**, so Releases, regressions and fix verification work without a version threaded through the build: `OBSERVE_SERVICE_VERSION` if the environment sets it, else the commit a platform or CI job exposes (Vercel, Render, Railway, Heroku, GitHub Actions, GitLab CI and others), else the commit checked out where the process runs, else a Cloud Run or Azure Container Apps revision. A container image usually carries none of these, so hand it the commit at build time - `ARG GIT_SHA` then `ENV OBSERVE_SERVICE_VERSION=$GIT_SHA`. `serviceVersion` names the release yourself, in at most 50 characters - a longer one is cut to fit, with a warning at startup; `serviceVersion: false` reports none.
|
|
@@ -408,7 +497,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
408
497
|
| `appKey`, `appSecret` | required | The credentials the dashboard issues - see [Getting credentials](#getting-credentials). |
|
|
409
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. |
|
|
410
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. |
|
|
411
|
-
| `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. |
|
|
412
501
|
| `flushInterval` | `5000` | Milliseconds between sends of buffered telemetry; at least `1000`. |
|
|
413
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. |
|
|
414
503
|
| `maxTracesPerBatch` | `1000` | The most traces one send carries. |
|
|
@@ -437,7 +526,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
437
526
|
| `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
|
|
438
527
|
| `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
|
|
439
528
|
| `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
|
|
440
|
-
| `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` never
|
|
529
|
+
| `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` and the `mongodb` driver's `MongoClient` and `Db` never are, whatever this returns. |
|
|
441
530
|
|
|
442
531
|
## Optional peer dependencies
|
|
443
532
|
|
|
@@ -499,4 +588,4 @@ const { createObserveModule } = require("@nestjs/observe");
|
|
|
499
588
|
|
|
500
589
|
## License
|
|
501
590
|
|
|
502
|
-
`@nestjs/observe` is [MIT licensed](
|
|
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
|
|
355
|
-
//
|
|
356
|
-
//
|
|
357
|
-
//
|
|
358
|
-
//
|
|
359
|
-
//
|
|
360
|
-
//
|
|
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) {
|
|
@@ -22,14 +22,47 @@ const FALLBACK_CLASS_NAME = "Object";
|
|
|
22
22
|
* Matched by shape as well as by class: an application with a second copy of
|
|
23
23
|
* `@nestjs/core` in its tree has a second `Reflector` class, which the
|
|
24
24
|
* `instanceof` alone would miss.
|
|
25
|
+
*
|
|
26
|
+
* A `MongoClient` or `Db` registered as a provider is the other.
|
|
25
27
|
*/
|
|
26
28
|
function isFrameworkNoise(instance) {
|
|
27
29
|
if (instance instanceof Reflector) {
|
|
28
30
|
return true;
|
|
29
31
|
}
|
|
30
32
|
const candidate = instance;
|
|
31
|
-
return (candidate.constructor?.name === "Reflector" &&
|
|
32
|
-
typeof candidate.getAllAndOverride === "function")
|
|
33
|
+
return ((candidate.constructor?.name === "Reflector" &&
|
|
34
|
+
typeof candidate.getAllAndOverride === "function") ||
|
|
35
|
+
isMongoDriverHandle(instance));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Whether an instance is the `mongodb` driver's `MongoClient` or `Db`.
|
|
39
|
+
*
|
|
40
|
+
* Instrumenting them breaks the driver, not just the waterfall. Traced calls
|
|
41
|
+
* run with the proxy as receiver and untraced ones with the raw instance, so
|
|
42
|
+
* what a method keeps of `this` depends on whether a trace was active: a `Db`
|
|
43
|
+
* made at bootstrap holds the raw client, a session started in a traced
|
|
44
|
+
* request holds the proxy, and the driver's `session.client !== client` check
|
|
45
|
+
* throws "ClientSession must be from the same MongoClient" - for every
|
|
46
|
+
* explicit session, transaction and `withSession` on a traced request, while
|
|
47
|
+
* the same calls on a sampled-out one succeed. The command spans the mongodb
|
|
48
|
+
* integration records are the useful part anyway; `Db.collection` and
|
|
49
|
+
* `MongoClient.startSession` spans are not.
|
|
50
|
+
*
|
|
51
|
+
* Matched by name and shape only: the driver is an optional peer, never
|
|
52
|
+
* imported here, and an application may carry more than one copy of it.
|
|
53
|
+
*/
|
|
54
|
+
function isMongoDriverHandle(instance) {
|
|
55
|
+
const candidate = instance;
|
|
56
|
+
switch (candidate.constructor?.name) {
|
|
57
|
+
case "MongoClient":
|
|
58
|
+
return (typeof candidate.startSession === "function" &&
|
|
59
|
+
typeof candidate.db === "function");
|
|
60
|
+
case "Db":
|
|
61
|
+
return (typeof candidate.collection === "function" &&
|
|
62
|
+
typeof candidate.databaseName === "string");
|
|
63
|
+
default:
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
33
66
|
}
|
|
34
67
|
export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
35
68
|
/**
|
|
@@ -47,8 +80,64 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
47
80
|
// "Object.<name>".
|
|
48
81
|
const call = spec.call;
|
|
49
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
|
+
});
|
|
50
139
|
// A function expression, not an arrow: the wrapper has to forward whatever
|
|
51
|
-
// `this` the caller invoked it with.
|
|
140
|
+
// `this` the caller invoked it with.
|
|
52
141
|
return named(frameName, function (...args) {
|
|
53
142
|
// Already tracing this callable, invoke it as-is
|
|
54
143
|
if (spec.isActive()) {
|
|
@@ -75,66 +164,12 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
75
164
|
spec.setActive(false);
|
|
76
165
|
}
|
|
77
166
|
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
// `err.stack` into the span payload (and, on a root span, into the
|
|
85
|
-
// snapshot that becomes the error group's sample), so relabelling
|
|
86
|
-
// afterwards would leave that copy carrying this frame's `Proxy.`.
|
|
87
|
-
relabelProxyFrame(err, className, methodName);
|
|
88
|
-
operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, newStepId, err);
|
|
89
|
-
};
|
|
90
|
-
const onError = (err) => {
|
|
91
|
-
recordError(err);
|
|
92
|
-
// Re-throw the error to maintain original behavior
|
|
93
|
-
throw err;
|
|
94
|
-
};
|
|
95
|
-
return als.run(new Map([
|
|
96
|
-
...(store?.entries() ?? []),
|
|
97
|
-
[CALLER_METADATA_KEY, newStepId],
|
|
98
|
-
]), named(frameName, () => {
|
|
99
|
-
try {
|
|
100
|
-
const result = call(this, args);
|
|
101
|
-
if (result instanceof Promise) {
|
|
102
|
-
// Closing the span is a side effect: a registry failure must
|
|
103
|
-
// leave the caller with the value or rejection it would have
|
|
104
|
-
// seen without the span.
|
|
105
|
-
const settled = (value) => {
|
|
106
|
-
ignoreFailure(() => onReturnValue(value));
|
|
107
|
-
return value;
|
|
108
|
-
};
|
|
109
|
-
const failed = (err) => {
|
|
110
|
-
ignoreFailure(() => recordError(err));
|
|
111
|
-
throw err;
|
|
112
|
-
};
|
|
113
|
-
// A plain native promise is swapped for a chained one, just as
|
|
114
|
-
// the caller's own `.then` would: a rejection the caller drops
|
|
115
|
-
// still raises `unhandledRejection`, as without the span.
|
|
116
|
-
if (isPlainPromise(result)) {
|
|
117
|
-
return result.then(settled, failed);
|
|
118
|
-
}
|
|
119
|
-
// A promise carrying more than its value (`json()` on a `got`
|
|
120
|
-
// request, `kill()` on an `execa` child, a subclass and its own
|
|
121
|
-
// members) is handed back as-is, or the caller loses all that.
|
|
122
|
-
// It is watched on a side branch instead, the way
|
|
123
|
-
// `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
|
|
124
|
-
// Watching marks it handled, so a rejection the caller drops no
|
|
125
|
-
// longer raises `unhandledRejection`; the span still records it.
|
|
126
|
-
result.then(settled, (err) => ignoreFailure(() => recordError(err)));
|
|
127
|
-
return result;
|
|
128
|
-
}
|
|
129
|
-
return onReturnValue(result);
|
|
130
|
-
}
|
|
131
|
-
catch (err) {
|
|
132
|
-
onError(err);
|
|
133
|
-
}
|
|
134
|
-
finally {
|
|
135
|
-
spec.setActive(false);
|
|
136
|
-
}
|
|
137
|
-
}));
|
|
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);
|
|
138
173
|
});
|
|
139
174
|
};
|
|
140
175
|
const instrumentFunction = (fn) => {
|
|
@@ -214,16 +249,33 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
214
249
|
const requiresRawReceiver = hasPrivateMembers || slotBacked;
|
|
215
250
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
216
251
|
const methodRefsCache = new WeakMap();
|
|
217
|
-
|
|
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();
|
|
218
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.
|
|
219
261
|
get: (target, prop, receiver) => {
|
|
220
262
|
const attributeValue = Reflect.get(target, prop);
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
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) &&
|
|
227
279
|
// A callable *object* - a Mongoose model, an Axios instance, an
|
|
228
280
|
// EventEmitter-backed client - is a field, not a method. The traced
|
|
229
281
|
// wrapper is a fresh bound function, so wrapping one silently drops
|
|
@@ -233,15 +285,15 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
233
285
|
// own properties.
|
|
234
286
|
!isCallableObject(attributeValue);
|
|
235
287
|
if (!shouldProxy) {
|
|
236
|
-
|
|
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;
|
|
237
293
|
}
|
|
238
294
|
const className = classNameOf(target);
|
|
239
295
|
const methodName = String(prop);
|
|
240
296
|
const frameName = `${className}.${methodName}`;
|
|
241
|
-
// When "originalMethod" is already proxied, return the cached version
|
|
242
|
-
if (methodRefsCache.has(attributeValue)) {
|
|
243
|
-
return methodRefsCache.get(attributeValue);
|
|
244
|
-
}
|
|
245
297
|
// For a private-member class, `Reflect.get` with the proxy as receiver
|
|
246
298
|
// would already throw on an accessor that touches `this.#x`, so the
|
|
247
299
|
// value fetched against the target above is reused instead.
|
|
@@ -249,23 +301,17 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
249
301
|
? attributeValue
|
|
250
302
|
: Reflect.get(target, prop, receiver);
|
|
251
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;
|
|
252
309
|
const proxyFn = createTracedWrapper({
|
|
253
310
|
className,
|
|
254
311
|
methodName,
|
|
255
312
|
spanId: generateSpanId(target, methodName),
|
|
256
|
-
isActive: () =>
|
|
257
|
-
setActive: (
|
|
258
|
-
if (!currentlyTracing.has(target)) {
|
|
259
|
-
currentlyTracing.set(target, new Set());
|
|
260
|
-
}
|
|
261
|
-
const activeMethods = currentlyTracing.get(target);
|
|
262
|
-
if (active) {
|
|
263
|
-
activeMethods.add(methodName);
|
|
264
|
-
}
|
|
265
|
-
else {
|
|
266
|
-
activeMethods.delete(methodName);
|
|
267
|
-
}
|
|
268
|
-
},
|
|
313
|
+
isActive: () => active,
|
|
314
|
+
setActive: (value) => (active = value),
|
|
269
315
|
// Traced calls run against the proxy so that a method calling into
|
|
270
316
|
// itself (`this.other()`) is instrumented as a nested step - except
|
|
271
317
|
// for private-member classes, whose brand checks only the raw
|