@nestjs/observe 0.3.7 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/agent/detached-observe-worker.js +113 -11
- package/dist/agent/observe-agent.shared-buffer.js +9 -6
- package/dist/interfaces/observe-options.interface.d.ts +14 -0
- package/dist/protocols/http-observe-agent.service.d.ts +18 -5
- package/dist/protocols/http-observe-agent.service.js +14 -1
- package/dist/utils/fallback-operation-id.util.d.ts +23 -0
- package/dist/utils/fallback-operation-id.util.js +35 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -331,7 +331,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
331
331
|
| `forwardLogs` | `false` | Sends the application's log lines, each correlated to the trace it was written in - see [Logs](https://www.observe.nestjs.com/documentation/sdk#logs). |
|
|
332
332
|
| `redaction` | on | How log lines, error messages and captured requests are scrubbed before they leave the process: `enabled`, `useDefaultPatterns`, `patterns`, `keys` and `replacement`. |
|
|
333
333
|
| `outgoing` | on | Query and outbound-HTTP spans. `false` turns both off; `{ database: false }` or `{ http: false }` one of them. |
|
|
334
|
-
| `http` | | `ignore`, `tags`, `setAttributes`, `getUserId
|
|
334
|
+
| `http` | | `ignore`, `tags`, `setAttributes`, `getUserId`, `queryParamsObfuscateRegex`, `tracePreflights` and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
|
|
335
335
|
| `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
|
|
336
336
|
| `graphql` | | The same four, once per GraphQL operation. |
|
|
337
337
|
| `ws` | | The same four, once per gateway message. |
|
|
@@ -14,6 +14,8 @@ describeRefusal) => {
|
|
|
14
14
|
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
15
15
|
const { parentPort, workerData } = require("worker_threads");
|
|
16
16
|
const zlib = require("zlib");
|
|
17
|
+
const http = require("http");
|
|
18
|
+
const https = require("https");
|
|
17
19
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
18
20
|
// `workerData` carries the shared buffer plus the collector config: the
|
|
19
21
|
// stringified function has no access to this module's configuration, so
|
|
@@ -26,8 +28,8 @@ describeRefusal) => {
|
|
|
26
28
|
const telemetryUrl = `${config.endpoint}/applications/telemetry`;
|
|
27
29
|
/**
|
|
28
30
|
* Why the endpoint can never be reached, decided once from its shape; null
|
|
29
|
-
* when it parses.
|
|
30
|
-
* refused connection -
|
|
31
|
+
* when it parses. A malformed URL otherwise fails the request exactly as a
|
|
32
|
+
* refused connection does - an error with a `cause` - so without this the
|
|
31
33
|
* operator is told to check that the collector is running when the fix is
|
|
32
34
|
* the `endpoint` option. `new URL` alone does not settle it: a scheme-less
|
|
33
35
|
* "localhost:4000" parses, with "localhost" as the scheme.
|
|
@@ -174,8 +176,108 @@ describeRefusal) => {
|
|
|
174
176
|
resolve(compressed);
|
|
175
177
|
}
|
|
176
178
|
}));
|
|
177
|
-
/**
|
|
178
|
-
|
|
179
|
+
/**
|
|
180
|
+
* How long a connection to the collector stays open between batches.
|
|
181
|
+
*
|
|
182
|
+
* Batches used to go through `fetch`, whose undici agent drops a socket
|
|
183
|
+
* after 4 s idle - one second short of the default 5 s flush - so every
|
|
184
|
+
* batch paid a new TCP connection and TLS handshake, the collector's
|
|
185
|
+
* certificate chain included. At the hosted collector's load balancer on
|
|
186
|
+
* 2026-10-08 that was 5.8-6.9M new connections a day for 4.5M requests,
|
|
187
|
+
* and ~27 GB/day sent to agents of which response bodies were 4.4 GB.
|
|
188
|
+
*
|
|
189
|
+
* Thirty seconds outlasts the default flush and any `flushInterval` below
|
|
190
|
+
* it, and stays inside common load-balancer idle timeouts (an ALB defaults
|
|
191
|
+
* to 60 s), so the agent lets go of an idle connection before the server
|
|
192
|
+
* does. A server announcing a shorter `Keep-Alive: timeout` is obeyed: the
|
|
193
|
+
* Node agent closes one second before it. An idle socket is unref'd and
|
|
194
|
+
* never holds the process open.
|
|
195
|
+
*/
|
|
196
|
+
const KEEP_ALIVE_IDLE_MS = 30_000;
|
|
197
|
+
// Chosen once: the endpoint cannot change, and a malformed one never gets
|
|
198
|
+
// as far as a request (see `post`).
|
|
199
|
+
const transport = !endpointProblem && new URL(telemetryUrl).protocol === "https:"
|
|
200
|
+
? https
|
|
201
|
+
: http;
|
|
202
|
+
const agent = new transport.Agent({
|
|
203
|
+
keepAlive: true,
|
|
204
|
+
timeout: KEEP_ALIVE_IDLE_MS,
|
|
205
|
+
});
|
|
206
|
+
/**
|
|
207
|
+
* One POST, with the reply read to the end before it resolves.
|
|
208
|
+
*
|
|
209
|
+
* Read whatever the status: a reply left unread keeps its socket busy, and
|
|
210
|
+
* the next batch opens another connection - the 401/403 path never read
|
|
211
|
+
* its body under `fetch`. Collector replies are a few hundred bytes.
|
|
212
|
+
*
|
|
213
|
+
* A transport failure rejects with the failure as `cause`, the shape the
|
|
214
|
+
* reporting below reads (ECONNREFUSED and friends on `err.cause.code`), and
|
|
215
|
+
* says whether the socket was a kept-alive one.
|
|
216
|
+
*/
|
|
217
|
+
const request = (body) => new Promise((resolve, reject) => {
|
|
218
|
+
const req = transport.request(telemetryUrl, {
|
|
219
|
+
method: "POST",
|
|
220
|
+
agent,
|
|
221
|
+
headers: { ...headers, "Content-Length": body.length },
|
|
222
|
+
}, (res) => {
|
|
223
|
+
const chunks = [];
|
|
224
|
+
res.on("data", (chunk) => chunks.push(chunk));
|
|
225
|
+
res.on("error", (err) => reject(new Error("collector reply failed", { cause: err })));
|
|
226
|
+
res.on("end", () => {
|
|
227
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
228
|
+
const status = res.statusCode ?? 0;
|
|
229
|
+
resolve({
|
|
230
|
+
ok: status >= 200 && status < 300,
|
|
231
|
+
status,
|
|
232
|
+
statusText: res.statusMessage ?? "",
|
|
233
|
+
headers: {
|
|
234
|
+
get: (name) => {
|
|
235
|
+
const value = res.headers[name.toLowerCase()];
|
|
236
|
+
if (value === undefined) {
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
return Array.isArray(value) ? value.join(", ") : value;
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
text: async () => text,
|
|
243
|
+
json: async () => JSON.parse(text),
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
req.on("error", (err) => reject(Object.assign(new Error("request to the collector failed", { cause: err }), {
|
|
248
|
+
reusedSocket: req.reusedSocket,
|
|
249
|
+
})));
|
|
250
|
+
req.end(body);
|
|
251
|
+
});
|
|
252
|
+
/**
|
|
253
|
+
* The request and nothing else, so what it throws is a transport failure.
|
|
254
|
+
*
|
|
255
|
+
* Sent once more, on a fresh socket, when a kept-alive socket was reset
|
|
256
|
+
* before any reply: the server closed it while it sat idle and never read
|
|
257
|
+
* the batch (ECONNRESET, or EPIPE when the reset landed before the write).
|
|
258
|
+
* That is the race every keep-alive client has - Node documents this retry
|
|
259
|
+
* on `request.reusedSocket`, and undici makes it for `fetch` on idempotent
|
|
260
|
+
* requests - and without it a batch would be dropped and reported as an
|
|
261
|
+
* unreachable collector.
|
|
262
|
+
*/
|
|
263
|
+
const post = async (body) => {
|
|
264
|
+
if (endpointProblem) {
|
|
265
|
+
throw new Error("the collector endpoint is not a valid http(s) URL", {
|
|
266
|
+
cause: new Error(endpointProblem),
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
return await request(body);
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
const failure = err;
|
|
274
|
+
const code = failure.cause?.code;
|
|
275
|
+
if (failure.reusedSocket && (code === "ECONNRESET" || code === "EPIPE")) {
|
|
276
|
+
return request(body);
|
|
277
|
+
}
|
|
278
|
+
throw err;
|
|
279
|
+
}
|
|
280
|
+
};
|
|
179
281
|
const postBatch = async (json) => post(await gzipAsync(json));
|
|
180
282
|
/**
|
|
181
283
|
* Last resort for a 400: brings the batch into contract entry by entry and
|
|
@@ -260,18 +362,18 @@ describeRefusal) => {
|
|
|
260
362
|
// Only the request is in this `try`, so anything it throws is a
|
|
261
363
|
// transport failure by construction and the outer catch is left for
|
|
262
364
|
// faults in this worker. Telling the two apart by the shape of the error
|
|
263
|
-
// instead - `
|
|
264
|
-
// only until the first exception without one, such as a timeout
|
|
265
|
-
//
|
|
365
|
+
// instead - `post` puts ECONNREFUSED and friends on `err.cause` - holds
|
|
366
|
+
// only until the first exception without one, such as a timeout on the
|
|
367
|
+
// request, which would then be reported as an agent bug.
|
|
266
368
|
let response;
|
|
267
369
|
try {
|
|
268
370
|
response = await post(compressed);
|
|
269
371
|
}
|
|
270
372
|
catch (err) {
|
|
271
|
-
// `
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
//
|
|
373
|
+
// `post` reports every transport failure the same opaque way and puts
|
|
374
|
+
// the reason - ECONNREFUSED, ENOTFOUND, a TLS error - on `err.cause`.
|
|
375
|
+
// Reporting only `err.message` would tell the operator nothing: not
|
|
376
|
+
// what went wrong, and not which URL was tried.
|
|
275
377
|
const cause = err
|
|
276
378
|
?.cause;
|
|
277
379
|
const reason = cause?.code ?? cause?.message;
|
|
@@ -20,6 +20,7 @@ import { JobSnapshotEncoder, } from "../encoders/job-snapshot.encoder.js";
|
|
|
20
20
|
import { RequestSnapshotEncoder, } from "../encoders/request-snapshot.encoder.js";
|
|
21
21
|
import { RuntimeMetricsEncoder, } from "../encoders/runtime-metrics.encoder.js";
|
|
22
22
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
23
|
+
import { fallbackOperationId } from "../utils/fallback-operation-id.util.js";
|
|
23
24
|
const SHARED_BUFFER_SIZE = 1024 * 1024 * 16; // 16 MB
|
|
24
25
|
const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
|
|
25
26
|
/**
|
|
@@ -86,12 +87,14 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
86
87
|
}
|
|
87
88
|
insertRequestSnapshot(snapshot) {
|
|
88
89
|
// A request can end before its route metadata is ever captured - an auth
|
|
89
|
-
// guard rejecting it, or a GraphQL document that never
|
|
90
|
-
// (`{ __typename }`) - leaving no operation id. The
|
|
91
|
-
// on every snapshot and rejects the *entire batch*
|
|
92
|
-
// fall back to the transport's URL, and drop the
|
|
93
|
-
// is absent rather than poison the batch it would
|
|
94
|
-
|
|
90
|
+
// guard rejecting it, a CORS preflight, or a GraphQL document that never
|
|
91
|
+
// reaches a resolver (`{ __typename }`) - leaving no operation id. The
|
|
92
|
+
// collector requires one on every snapshot and rejects the *entire batch*
|
|
93
|
+
// over a single miss, so fall back to the transport's URL, and drop the
|
|
94
|
+
// snapshot when even that is absent rather than poison the batch it would
|
|
95
|
+
// ride in. The URL is folded to a route-like path first, or every query
|
|
96
|
+
// string and id would be a route of its own; `originalUrl` keeps it whole.
|
|
97
|
+
snapshot.operationId ??= fallbackOperationId(snapshot.attributes?.originalUrl);
|
|
95
98
|
if (!snapshot.operationId) {
|
|
96
99
|
if (this.options.debug) {
|
|
97
100
|
this.logger.debug(`Snapshot for traceId "${snapshot.traceId}" has no operation id nor URL to fall back on. Ignoring snapshot.`);
|
|
@@ -354,6 +354,20 @@ export interface ObserveOptions {
|
|
|
354
354
|
method: string;
|
|
355
355
|
path: string | RegExp;
|
|
356
356
|
} | RegExp> | ((req: any) => boolean);
|
|
357
|
+
/**
|
|
358
|
+
* Whether to trace CORS preflight requests - the `OPTIONS` request,
|
|
359
|
+
* carrying an `Access-Control-Request-Method` header, that a browser
|
|
360
|
+
* sends ahead of a cross-origin call.
|
|
361
|
+
*
|
|
362
|
+
* Off by default. A preflight is answered by the CORS middleware before
|
|
363
|
+
* any route matches, so it has no route to be grouped under. Whenever
|
|
364
|
+
* middleware registered ahead of CORS (helmet, compression) records a
|
|
365
|
+
* span for it, it is reported under its URL instead - one "route" per
|
|
366
|
+
* distinct URL, ids included, for every call a browser client makes. An
|
|
367
|
+
* `OPTIONS` request without that header is traced either way.
|
|
368
|
+
* @default false
|
|
369
|
+
*/
|
|
370
|
+
tracePreflights?: boolean;
|
|
357
371
|
/**
|
|
358
372
|
* Tags to be added to all HTTP requests.
|
|
359
373
|
* These tags can be used to provide additional context for the requests.
|
|
@@ -6,6 +6,13 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
|
|
|
6
6
|
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
7
7
|
import { TraceSamplerService } from "../services/trace-sampler.service.js";
|
|
8
8
|
import { KeyOf } from "../types/key-of.type.js";
|
|
9
|
+
/** What the request hook reads of an Express or Fastify request. */
|
|
10
|
+
interface IncomingHttpRequest {
|
|
11
|
+
url: string;
|
|
12
|
+
method: string;
|
|
13
|
+
protocol: string;
|
|
14
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
15
|
+
}
|
|
9
16
|
export declare class HttpObserveAgentService<Store extends Record<string, unknown>> implements OnModuleInit, OnModuleDestroy {
|
|
10
17
|
private readonly httpAdapterHost;
|
|
11
18
|
private readonly asyncLocalStorage;
|
|
@@ -28,11 +35,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
28
35
|
onModuleInit(): void;
|
|
29
36
|
onModuleDestroy(): void;
|
|
30
37
|
registerHttpHooks(): void;
|
|
31
|
-
startHttpRequestTracing(req:
|
|
32
|
-
url: string;
|
|
33
|
-
method: string;
|
|
34
|
-
protocol: string;
|
|
35
|
-
}, res: unknown, done: () => void): void;
|
|
38
|
+
startHttpRequestTracing(req: IncomingHttpRequest, res: unknown, done: () => void): void;
|
|
36
39
|
endHttpRequestTracing(req: unknown, res: {
|
|
37
40
|
statusCode: number;
|
|
38
41
|
}): void;
|
|
@@ -67,5 +70,15 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
|
|
|
67
70
|
* to, so the HTTP side stands aside and everything else is still reported.
|
|
68
71
|
*/
|
|
69
72
|
private hasRequestHooks;
|
|
73
|
+
/**
|
|
74
|
+
* A CORS preflight, when `http.tracePreflights` has not asked for them.
|
|
75
|
+
*
|
|
76
|
+
* Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
|
|
77
|
+
* with an `Access-Control-Request-Method` header - rather than by the
|
|
78
|
+
* method alone, so an application's own `OPTIONS` handler is still traced.
|
|
79
|
+
* Both adapters lower-case header names.
|
|
80
|
+
*/
|
|
81
|
+
private isUntracedPreflight;
|
|
70
82
|
private shouldIgnoreRequest;
|
|
71
83
|
}
|
|
84
|
+
export {};
|
|
@@ -113,7 +113,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
}
|
|
116
|
-
if (this.shouldIgnoreRequest(req)) {
|
|
116
|
+
if (this.shouldIgnoreRequest(req) || this.isUntracedPreflight(req)) {
|
|
117
117
|
return done();
|
|
118
118
|
}
|
|
119
119
|
const shouldCapture = this.traceSamplerService.shouldCapture("http", {
|
|
@@ -238,6 +238,19 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
|
|
|
238
238
|
}
|
|
239
239
|
return false;
|
|
240
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* A CORS preflight, when `http.tracePreflights` has not asked for them.
|
|
243
|
+
*
|
|
244
|
+
* Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
|
|
245
|
+
* with an `Access-Control-Request-Method` header - rather than by the
|
|
246
|
+
* method alone, so an application's own `OPTIONS` handler is still traced.
|
|
247
|
+
* Both adapters lower-case header names.
|
|
248
|
+
*/
|
|
249
|
+
isUntracedPreflight(req) {
|
|
250
|
+
return (!this.options.http?.tracePreflights &&
|
|
251
|
+
req.method === "OPTIONS" &&
|
|
252
|
+
req.headers?.["access-control-request-method"] !== undefined);
|
|
253
|
+
}
|
|
241
254
|
shouldIgnoreRequest(req) {
|
|
242
255
|
if (typeof this.options.http?.ignore === "function") {
|
|
243
256
|
return this.options.http.ignore(req);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The operation id a request that never matched a route is grouped under.
|
|
3
|
+
*
|
|
4
|
+
* A request can end before its route is known - a CORS preflight the cors
|
|
5
|
+
* middleware answered, a guard rejection, a 404 - and the transport's URL is
|
|
6
|
+
* all there is to name it by. Sent verbatim, query string and ids included,
|
|
7
|
+
* every distinct URL became a route of its own in the collector's per-route
|
|
8
|
+
* rollups, and a dashboard reads one row per route per bucket: on the Observe
|
|
9
|
+
* API's own telemetry, preflights carrying project ids and range query strings
|
|
10
|
+
* were most of its distinct routes.
|
|
11
|
+
*
|
|
12
|
+
* So a path is cut at its query string and its UUID segments become `:id`.
|
|
13
|
+
* Numeric segments are left alone: the collector folds the same way, and there
|
|
14
|
+
* a parameterless template such as `/reports/2024` is indistinguishable from
|
|
15
|
+
* its URL. Anything that is not a path - the GraphQL agent falls back to the
|
|
16
|
+
* document, which may hold a `?` inside a string literal - is kept as it is.
|
|
17
|
+
*
|
|
18
|
+
* Must stay identical to `foldFallbackOperationId` in the collector
|
|
19
|
+
* (whisprr-api, `telemetry/utils/fallback-operation-id.util.ts`), which folds
|
|
20
|
+
* what older agents still send. A difference splits one route in two for as
|
|
21
|
+
* long as a fleet runs both versions.
|
|
22
|
+
*/
|
|
23
|
+
export declare function fallbackOperationId(originalUrl: string | undefined): string | undefined;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A path segment that is a UUID, and nothing else. Anchored to whole segments
|
|
3
|
+
* so a slug that merely contains one keeps its shape.
|
|
4
|
+
*/
|
|
5
|
+
const UUID_SEGMENT = /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}(?=\/|$)/gi;
|
|
6
|
+
/**
|
|
7
|
+
* The operation id a request that never matched a route is grouped under.
|
|
8
|
+
*
|
|
9
|
+
* A request can end before its route is known - a CORS preflight the cors
|
|
10
|
+
* middleware answered, a guard rejection, a 404 - and the transport's URL is
|
|
11
|
+
* all there is to name it by. Sent verbatim, query string and ids included,
|
|
12
|
+
* every distinct URL became a route of its own in the collector's per-route
|
|
13
|
+
* rollups, and a dashboard reads one row per route per bucket: on the Observe
|
|
14
|
+
* API's own telemetry, preflights carrying project ids and range query strings
|
|
15
|
+
* were most of its distinct routes.
|
|
16
|
+
*
|
|
17
|
+
* So a path is cut at its query string and its UUID segments become `:id`.
|
|
18
|
+
* Numeric segments are left alone: the collector folds the same way, and there
|
|
19
|
+
* a parameterless template such as `/reports/2024` is indistinguishable from
|
|
20
|
+
* its URL. Anything that is not a path - the GraphQL agent falls back to the
|
|
21
|
+
* document, which may hold a `?` inside a string literal - is kept as it is.
|
|
22
|
+
*
|
|
23
|
+
* Must stay identical to `foldFallbackOperationId` in the collector
|
|
24
|
+
* (whisprr-api, `telemetry/utils/fallback-operation-id.util.ts`), which folds
|
|
25
|
+
* what older agents still send. A difference splits one route in two for as
|
|
26
|
+
* long as a fleet runs both versions.
|
|
27
|
+
*/
|
|
28
|
+
export function fallbackOperationId(originalUrl) {
|
|
29
|
+
if (!originalUrl?.startsWith("/")) {
|
|
30
|
+
return originalUrl;
|
|
31
|
+
}
|
|
32
|
+
const queryAt = originalUrl.indexOf("?");
|
|
33
|
+
const path = queryAt === -1 ? originalUrl : originalUrl.slice(0, queryAt);
|
|
34
|
+
return path.replace(UUID_SEGMENT, "/:id");
|
|
35
|
+
}
|
package/package.json
CHANGED