@nestjs/observe 0.2.3 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/telemetry-wire-contract.js +1 -0
- package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
- package/dist/encoders/request-snapshot.encoder.js +1 -0
- package/dist/instrument/create-instance-decorator.instrument.js +2 -2
- package/dist/interfaces/observe-options.interface.d.ts +90 -4
- package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
- package/dist/observe.constants.d.ts +16 -0
- package/dist/observe.constants.js +16 -0
- package/dist/observe.module.js +48 -4
- package/dist/outgoing/http.integration.d.ts +36 -0
- package/dist/outgoing/http.integration.js +127 -0
- package/dist/outgoing/mongodb.integration.d.ts +38 -0
- package/dist/outgoing/mongodb.integration.js +141 -0
- package/dist/outgoing/mysql2.integration.d.ts +20 -0
- package/dist/outgoing/mysql2.integration.js +89 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
- package/dist/outgoing/outgoing-span.recorder.js +94 -0
- package/dist/outgoing/patch-method.util.d.ts +15 -0
- package/dist/outgoing/patch-method.util.js +29 -0
- package/dist/outgoing/pg.integration.d.ts +22 -0
- package/dist/outgoing/pg.integration.js +66 -0
- package/dist/outgoing/sql-statement.util.d.ts +21 -0
- package/dist/outgoing/sql-statement.util.js +48 -0
- package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
- package/dist/protocols/bull-observe-agent.service.js +130 -0
- package/dist/protocols/graphql-observe-agent.service.js +5 -2
- package/dist/protocols/graphql-operation-parser.d.ts +4 -4
- package/dist/protocols/graphql-operation-parser.js +28 -4
- package/dist/protocols/http-observe-agent.service.js +26 -7
- package/dist/protocols/job-trace-runner.d.ts +77 -0
- package/dist/protocols/job-trace-runner.js +196 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
- package/dist/protocols/queue-observe-agent.service.js +36 -95
- package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
- package/dist/protocols/ws-observe-agent.service.js +180 -0
- package/dist/services/operation-trace.registry.d.ts +17 -1
- package/dist/services/operation-trace.registry.js +39 -7
- package/dist/services/trace-sampler.service.d.ts +4 -0
- package/dist/services/tracer.service.js +5 -3
- package/dist/utils/capture-request.util.d.ts +57 -0
- package/dist/utils/capture-request.util.js +116 -0
- package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
- package/dist/utils/default-trace-id-generator.util.js +12 -1
- package/dist/utils/log-redactor.d.ts +20 -1
- package/dist/utils/log-redactor.js +54 -38
- package/dist/utils/optional-peer.util.d.ts +13 -0
- package/dist/utils/optional-peer.util.js +30 -0
- package/dist/utils/redact-url-query.d.ts +10 -1
- package/dist/utils/redact-url-query.js +16 -37
- package/dist/utils/sensitive-keys.d.ts +15 -0
- package/dist/utils/sensitive-keys.js +76 -0
- package/dist/utils/source-context.util.d.ts +6 -0
- package/dist/utils/source-context.util.js +113 -15
- package/dist/utils/source-map-resolver.util.js +12 -0
- package/package.json +35 -2
|
@@ -17,6 +17,7 @@ declare const SNAPSHOT_KEY_MAP: {
|
|
|
17
17
|
readonly tags: "tg";
|
|
18
18
|
readonly error: "e";
|
|
19
19
|
readonly userId: "u";
|
|
20
|
+
readonly request: "rq";
|
|
20
21
|
};
|
|
21
22
|
export type EncodedAttributes = {
|
|
22
23
|
[K in keyof RequestSnapshot["attributes"] as K extends keyof typeof ATTRIBUTES_KEY_MAP ? (typeof ATTRIBUTES_KEY_MAP)[K] : never]: RequestSnapshot["attributes"][K];
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
1
|
+
import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
2
2
|
/**
|
|
3
3
|
* Stand-in "class name" for instrumented standalone functions. Unlike methods,
|
|
4
4
|
* they have no enclosing class to borrow a name from, so every span they emit
|
|
@@ -29,7 +29,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
29
29
|
return callUntraced(this, args);
|
|
30
30
|
}
|
|
31
31
|
const store = als.getStore();
|
|
32
|
-
const requestId = store?.get(options.traceIdKey);
|
|
32
|
+
const requestId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(options.traceIdKey);
|
|
33
33
|
if (!requestId) {
|
|
34
34
|
return callUntraced(this, args);
|
|
35
35
|
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { OutgoingHttpOptions } from "../outgoing/http.integration.js";
|
|
2
|
+
import type { HttpCaptureOptions } from "../utils/capture-request.util.js";
|
|
1
3
|
import { FactoryProvider, ModuleMetadata, Provider, Type } from "@nestjs/common";
|
|
2
4
|
import { BaseRpcContext, Transport } from "@nestjs/microservices";
|
|
3
5
|
import { GraphQLResolveInfoLike } from "./graphql.interfaces.js";
|
|
@@ -16,9 +18,15 @@ export interface RedactionOptions {
|
|
|
16
18
|
*/
|
|
17
19
|
patterns?: RegExp[];
|
|
18
20
|
/**
|
|
19
|
-
* Extra
|
|
20
|
-
*
|
|
21
|
-
*
|
|
21
|
+
* Extra keys whose values are masked outright, on top of the built-in
|
|
22
|
+
* rules - wherever masking is by key: log attributes, captured headers and
|
|
23
|
+
* bodies, and the query string of a recorded URL. Compared
|
|
24
|
+
* case-insensitively, ignoring `-` and `_`, so "apiKey", "api_key" and
|
|
25
|
+
* "API-KEY" are one entry.
|
|
26
|
+
*
|
|
27
|
+
* The built-in rules already match a name by what it ends in (`resetToken`,
|
|
28
|
+
* `client_secret`, `X-Amz-Signature`), so this is for names that do not say
|
|
29
|
+
* what they hold.
|
|
22
30
|
*/
|
|
23
31
|
keys?: string[];
|
|
24
32
|
/**
|
|
@@ -211,7 +219,7 @@ export interface ObserveOptions {
|
|
|
211
219
|
* A value of 1.0 means all traces are sent, while a value of 0.1 means 10% of traces are sent.
|
|
212
220
|
* @default 1.0
|
|
213
221
|
*/
|
|
214
|
-
tracesSampleRate?: number | ((protocal: "http" | "rpc" | "grpc" | "graphql", attributes: any) => boolean);
|
|
222
|
+
tracesSampleRate?: number | ((protocal: "http" | "rpc" | "grpc" | "graphql" | "ws", attributes: any) => boolean);
|
|
215
223
|
/**
|
|
216
224
|
* Maximum number of traces per batch that can be sent to the Agent.
|
|
217
225
|
* This is useful for controlling the volume of traces sent, especially in high-traffic applications.
|
|
@@ -325,6 +333,19 @@ export interface ObserveOptions {
|
|
|
325
333
|
* @default undefined
|
|
326
334
|
*/
|
|
327
335
|
queryParamsObfuscateRegex?: RegExp;
|
|
336
|
+
/**
|
|
337
|
+
* What to record of the request itself - the inputs that tell a
|
|
338
|
+
* reproducible problem from a one-off - for a request that **failed**, or
|
|
339
|
+
* one slower than `slowerThanMs` when that is set. Never recorded for an
|
|
340
|
+
* ordinary request.
|
|
341
|
+
*
|
|
342
|
+
* By default a short allow-list of headers that neither authenticate nor
|
|
343
|
+
* identify the caller (`user-agent`, `content-type`, `referer`, ...) and
|
|
344
|
+
* no body. Everything recorded passes through `redaction` first. Set to
|
|
345
|
+
* `false` to record nothing.
|
|
346
|
+
* @example { headers: ['user-agent', 'x-tenant-id'], body: { maxBytes: 4096 }, slowerThanMs: 2000 }
|
|
347
|
+
*/
|
|
348
|
+
capture?: HttpCaptureOptions | false;
|
|
328
349
|
/**
|
|
329
350
|
* A function to associate a user identifier with the HTTP request.
|
|
330
351
|
* This function receives the request object and should return a string representing the user ID.
|
|
@@ -461,6 +482,60 @@ export interface ObserveOptions {
|
|
|
461
482
|
*/
|
|
462
483
|
getUserId?: (call: any) => string;
|
|
463
484
|
};
|
|
485
|
+
/**
|
|
486
|
+
* Spans for what leaves the process: database queries (`pg`, `mysql2`,
|
|
487
|
+
* `mongodb` - and so every ORM built on them) and outbound HTTP requests
|
|
488
|
+
* (`fetch`/undici and `node:http`, so axios too). On by default; `false`
|
|
489
|
+
* switches all of it off.
|
|
490
|
+
*
|
|
491
|
+
* A query span is named after its verb and table (`SELECT users`) and
|
|
492
|
+
* carries the statement with every literal removed; bound parameters are
|
|
493
|
+
* never read. An HTTP span is named after the method and host, and carries
|
|
494
|
+
* the URL with sensitive query parameters masked.
|
|
495
|
+
*/
|
|
496
|
+
outgoing?: false | {
|
|
497
|
+
/** @default true */
|
|
498
|
+
database?: boolean;
|
|
499
|
+
/** @default true */
|
|
500
|
+
http?: boolean | OutgoingHttpOptions;
|
|
501
|
+
};
|
|
502
|
+
/**
|
|
503
|
+
* WebSocket gateway configuration options for the Observe APM.
|
|
504
|
+
*
|
|
505
|
+
* The unit is one inbound message handled by a `@SubscribeMessage()`
|
|
506
|
+
* method, reported as a request whose operation id is
|
|
507
|
+
* `GatewayClass:pattern`. Connection and disconnection are not operations
|
|
508
|
+
* and are not reported. A message has no carrier for a trace id, so each one
|
|
509
|
+
* opens a trace of its own.
|
|
510
|
+
*/
|
|
511
|
+
ws?: {
|
|
512
|
+
/**
|
|
513
|
+
* A function that determines whether to skip tracing a given message.
|
|
514
|
+
* @example (message) => message.pattern === 'ping'
|
|
515
|
+
* @default () => false
|
|
516
|
+
*/
|
|
517
|
+
ignore?: (message: WsMessageContext) => boolean;
|
|
518
|
+
/**
|
|
519
|
+
* Tags to be added to every gateway message trace.
|
|
520
|
+
* @default {}
|
|
521
|
+
*/
|
|
522
|
+
tags?: Record<string, string | number | boolean>;
|
|
523
|
+
/**
|
|
524
|
+
* A function to generate additional attributes for a message. These can be
|
|
525
|
+
* retrieved later within the trace.
|
|
526
|
+
* @default () => ({})
|
|
527
|
+
*/
|
|
528
|
+
setAttributes?: (message: WsMessageContext) => {
|
|
529
|
+
[key: string]: string | number | boolean;
|
|
530
|
+
};
|
|
531
|
+
/**
|
|
532
|
+
* A function to associate a user identifier with the message - typically
|
|
533
|
+
* read from whatever the connection handler attached to the client.
|
|
534
|
+
* @example (message) => message.client.data?.userId
|
|
535
|
+
* @default undefined
|
|
536
|
+
*/
|
|
537
|
+
getUserId?: (message: WsMessageContext) => string | undefined;
|
|
538
|
+
};
|
|
464
539
|
/**
|
|
465
540
|
* Jobs configuration options for the Observe APM.
|
|
466
541
|
*
|
|
@@ -522,3 +597,14 @@ export interface ObserveModuleAsyncOptions extends Pick<ModuleMetadata, "imports
|
|
|
522
597
|
*/
|
|
523
598
|
global?: boolean;
|
|
524
599
|
}
|
|
600
|
+
/** What a `ws` option hook is told about the message being handled. */
|
|
601
|
+
export interface WsMessageContext {
|
|
602
|
+
/** Class name of the gateway handling the message. */
|
|
603
|
+
gateway: string;
|
|
604
|
+
/** The `@SubscribeMessage()` pattern. */
|
|
605
|
+
pattern: string;
|
|
606
|
+
/** The client socket, as the platform adapter hands it to the gateway. */
|
|
607
|
+
client: any;
|
|
608
|
+
/** The message payload. Never recorded - it is here for the hooks only. */
|
|
609
|
+
data: unknown;
|
|
610
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { CapturedRequest } from "../utils/capture-request.util.js";
|
|
1
2
|
import { CompleteTraceEventNode, OngoingTraceEventNode } from "./trace-events.interfaces.js";
|
|
2
3
|
export interface RequestSnapshot {
|
|
3
4
|
/**
|
|
@@ -52,6 +53,13 @@ export interface RequestSnapshot {
|
|
|
52
53
|
stack?: string;
|
|
53
54
|
tags?: Record<string, string | number | boolean>;
|
|
54
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* The request's own inputs - headers, and the body when asked for - when
|
|
58
|
+
* `http.capture` decides this request is worth them: it failed, or it ran
|
|
59
|
+
* past `slowerThanMs`. A field of its own rather than part of `error`, so
|
|
60
|
+
* that what triggered the capture never decides where it is read from.
|
|
61
|
+
*/
|
|
62
|
+
request?: CapturedRequest;
|
|
55
63
|
/**
|
|
56
64
|
* Optional user identifier associated with the request.
|
|
57
65
|
*/
|
|
@@ -1,2 +1,18 @@
|
|
|
1
1
|
export declare const OBSERVE_OPTIONS = "OBSERVE_OPTIONS";
|
|
2
2
|
export declare const CALLER_METADATA_KEY = "#caller";
|
|
3
|
+
/**
|
|
4
|
+
* Where a store keeps the registry key when it differs from the trace id.
|
|
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.
|
|
11
|
+
*/
|
|
12
|
+
export declare const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
|
+
/**
|
|
14
|
+
* The job option the enqueuing side stamps the active trace id into. Both
|
|
15
|
+
* BullMQ and Bull persist unknown options verbatim, so it survives the trip
|
|
16
|
+
* through Redis without touching the job's data.
|
|
17
|
+
*/
|
|
18
|
+
export declare const JOB_TRACE_OPTION_KEY = "observeTraceId";
|
|
@@ -1,2 +1,18 @@
|
|
|
1
1
|
export const OBSERVE_OPTIONS = "OBSERVE_OPTIONS";
|
|
2
2
|
export const CALLER_METADATA_KEY = "#caller";
|
|
3
|
+
/**
|
|
4
|
+
* Where a store keeps the registry key when it differs from the trace id.
|
|
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.
|
|
11
|
+
*/
|
|
12
|
+
export const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
|
+
/**
|
|
14
|
+
* The job option the enqueuing side stamps the active trace id into. Both
|
|
15
|
+
* BullMQ and Bull persist unknown options verbatim, so it survives the trip
|
|
16
|
+
* through Redis without touching the job's data.
|
|
17
|
+
*/
|
|
18
|
+
export const JOB_TRACE_OPTION_KEY = "observeTraceId";
|
package/dist/observe.module.js
CHANGED
|
@@ -19,9 +19,12 @@ import { createInstanceDecorator } from "./instrument/create-instance-decorator.
|
|
|
19
19
|
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
|
|
20
20
|
import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
|
|
21
21
|
import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
|
|
22
|
+
import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
|
|
23
|
+
import { BullObserveAgentService } from "./protocols/bull-observe-agent.service.js";
|
|
22
24
|
import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
|
|
23
25
|
import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js";
|
|
24
26
|
import { ScheduleObserveAgentService } from "./protocols/schedule-observe-agent.service.js";
|
|
27
|
+
import { WsObserveAgentService } from "./protocols/ws-observe-agent.service.js";
|
|
25
28
|
import { LoggerPatcherService } from "./services/logger-patcher.service.js";
|
|
26
29
|
import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
|
|
27
30
|
import { resolveSpanCollapseSettings } from "./services/collapse-repeated-spans.util.js";
|
|
@@ -171,9 +174,14 @@ export function createObserveModule(options = {}) {
|
|
|
171
174
|
// `forwardLogs` is enabled, and it redacts before anything is buffered.
|
|
172
175
|
StdoutForwarderService,
|
|
173
176
|
QueueObserveAgentService,
|
|
177
|
+
// A no-op unless bull - the driver behind @nestjs/bull - is installed.
|
|
178
|
+
BullObserveAgentService,
|
|
174
179
|
// A no-op unless @nestjs/schedule is installed; it patches the explorer
|
|
175
180
|
// from its constructor so the patch lands before any handler is found.
|
|
176
181
|
ScheduleObserveAgentService,
|
|
182
|
+
// A no-op unless @nestjs/websockets is installed.
|
|
183
|
+
WsObserveAgentService,
|
|
184
|
+
OutgoingObserveAgentService,
|
|
177
185
|
],
|
|
178
186
|
exports: [AsyncLocalStorage, TracerService],
|
|
179
187
|
}),
|
|
@@ -198,6 +206,8 @@ export function createObserveModule(options = {}) {
|
|
|
198
206
|
instance instanceof GraphQLObserveAgentService ||
|
|
199
207
|
// Same reason: its wrapper runs inside the job traces it opens.
|
|
200
208
|
instance instanceof ScheduleObserveAgentService ||
|
|
209
|
+
instance instanceof WsObserveAgentService ||
|
|
210
|
+
instance instanceof OutgoingObserveAgentService ||
|
|
201
211
|
// Nest's discovery machinery, which the GraphQL agent walks to map
|
|
202
212
|
// root fields back to their resolver classes. It has to stay
|
|
203
213
|
// unproxied: ModulesContainer extends Map, and a Map method invoked
|
|
@@ -232,14 +242,48 @@ export function createObserveModule(options = {}) {
|
|
|
232
242
|
// skip hook to avoid duplicating APIs). Newer cores additionally wrap
|
|
233
243
|
// this in a safety net that falls back to the undecorated instance,
|
|
234
244
|
// with a warning, should it ever throw.
|
|
235
|
-
instanceDecorator:
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
245
|
+
instanceDecorator: (() => {
|
|
246
|
+
const decorate = createInstanceDecorator(asyncLocalStorage, operationTraceRegistry, {
|
|
247
|
+
traceIdKey: options.traceIdKey,
|
|
248
|
+
skipInstrumentation,
|
|
249
|
+
});
|
|
250
|
+
return (instance) => {
|
|
251
|
+
propagateTraceIdThrough(instance, () => asyncLocalStorage.getStore()?.get(options.traceIdKey));
|
|
252
|
+
return decorate(instance);
|
|
253
|
+
};
|
|
254
|
+
})(),
|
|
239
255
|
},
|
|
240
256
|
ObserveModule,
|
|
241
257
|
};
|
|
242
258
|
}
|
|
259
|
+
/**
|
|
260
|
+
* Makes a microservice client send the current trace id with every packet.
|
|
261
|
+
*
|
|
262
|
+
* `setOnDispatchHook` is the client-side counterpart of the server's
|
|
263
|
+
* processing hooks, and only exists on `@nestjs/microservices` versions that
|
|
264
|
+
* carry packet metadata - so this is a feature test, and a no-op on every
|
|
265
|
+
* version before. The id goes out under the same name an HTTP hop uses, and
|
|
266
|
+
* `defaultTraceIdGenerator` reads it back from the receiving context.
|
|
267
|
+
*/
|
|
268
|
+
function propagateTraceIdThrough(instance, currentTraceId) {
|
|
269
|
+
const client = instance;
|
|
270
|
+
try {
|
|
271
|
+
if (typeof client?.setOnDispatchHook !== "function") {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
// A provider whose mere inspection throws - the decorator's own
|
|
277
|
+
// exclusions deal with it; it is certainly not a microservice client.
|
|
278
|
+
return;
|
|
279
|
+
}
|
|
280
|
+
client.setOnDispatchHook((packet) => {
|
|
281
|
+
const traceId = currentTraceId();
|
|
282
|
+
if (typeof traceId === "string" && !packet.metadata?.["x-request-id"]) {
|
|
283
|
+
packet.metadata = { ...packet.metadata, "x-request-id": traceId };
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
}
|
|
243
287
|
/**
|
|
244
288
|
* Identifies `@nestjs/graphql`'s `ResolverDecoratorHost` without importing the
|
|
245
289
|
* package, which is an optional peer. `decorate`/`setDecorator` plus the
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { LogRedactor } from "../utils/log-redactor.js";
|
|
2
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
3
|
+
export interface OutgoingHttpOptions {
|
|
4
|
+
/**
|
|
5
|
+
* Skip requests to matching URLs - no span, no trace header.
|
|
6
|
+
* @example (url) => url.startsWith('https://telemetry.internal')
|
|
7
|
+
*/
|
|
8
|
+
ignore?: (url: string) => boolean;
|
|
9
|
+
/**
|
|
10
|
+
* Send the current trace id as `x-request-id`, unless the request already
|
|
11
|
+
* carries one. It is what a downstream service running `@nestjs/observe`
|
|
12
|
+
* adopts as its own trace id, which makes HTTP-to-HTTP calls one trace with
|
|
13
|
+
* no application code. A function narrows it to the URLs it returns true
|
|
14
|
+
* for - your own services, say, and not third parties.
|
|
15
|
+
* @default true
|
|
16
|
+
*/
|
|
17
|
+
propagateTraceId?: boolean | ((url: string) => boolean);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Spans for outbound HTTP, from the diagnostics channels Node publishes on its
|
|
21
|
+
* own: `undici` - which is also what the global `fetch` runs on - and the
|
|
22
|
+
* `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
|
|
23
|
+
* so there is no HTTP client to keep up with.
|
|
24
|
+
*
|
|
25
|
+
* The handlers run synchronously inside the call that makes the request, which
|
|
26
|
+
* is what puts the span under the right parent; the span is then carried to
|
|
27
|
+
* the completion events on the request object itself.
|
|
28
|
+
*
|
|
29
|
+
* Returns the function that removes every subscription.
|
|
30
|
+
*/
|
|
31
|
+
export declare function subscribeOutgoingHttp(recorder: OutgoingSpanRecorder, currentTraceId: () => string | undefined, options?: OutgoingHttpOptions,
|
|
32
|
+
/**
|
|
33
|
+
* Read per request rather than passed once: the redactor is configured
|
|
34
|
+
* after the module's options resolve, which can be after this subscribes.
|
|
35
|
+
*/
|
|
36
|
+
getRedactor?: () => LogRedactor | null): () => void;
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { subscribe, unsubscribe } from "diagnostics_channel";
|
|
2
|
+
import { redactUrlQuery } from "../utils/redact-url-query.js";
|
|
3
|
+
const TRACE_HEADER = "x-request-id";
|
|
4
|
+
/**
|
|
5
|
+
* Spans for outbound HTTP, from the diagnostics channels Node publishes on its
|
|
6
|
+
* own: `undici` - which is also what the global `fetch` runs on - and the
|
|
7
|
+
* `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
|
|
8
|
+
* so there is no HTTP client to keep up with.
|
|
9
|
+
*
|
|
10
|
+
* The handlers run synchronously inside the call that makes the request, which
|
|
11
|
+
* is what puts the span under the right parent; the span is then carried to
|
|
12
|
+
* the completion events on the request object itself.
|
|
13
|
+
*
|
|
14
|
+
* Returns the function that removes every subscription.
|
|
15
|
+
*/
|
|
16
|
+
export function subscribeOutgoingHttp(recorder, currentTraceId, options = {},
|
|
17
|
+
/**
|
|
18
|
+
* Read per request rather than passed once: the redactor is configured
|
|
19
|
+
* after the module's options resolve, which can be after this subscribes.
|
|
20
|
+
*/
|
|
21
|
+
getRedactor = () => null) {
|
|
22
|
+
const spans = new WeakMap();
|
|
23
|
+
const subscriptions = [];
|
|
24
|
+
const on = (channel, handler) => {
|
|
25
|
+
const guarded = (message) => {
|
|
26
|
+
// A handler that throws here throws inside the application's own
|
|
27
|
+
// `fetch()` or `http.request()` call.
|
|
28
|
+
try {
|
|
29
|
+
handler(message);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
/* an unobserved request is the whole cost */
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
subscribe(channel, guarded);
|
|
36
|
+
subscriptions.push([channel, guarded]);
|
|
37
|
+
};
|
|
38
|
+
const shouldPropagate = (url) => typeof options.propagateTraceId === "function"
|
|
39
|
+
? options.propagateTraceId(url)
|
|
40
|
+
: options.propagateTraceId !== false;
|
|
41
|
+
const open = (request, method, url, host) => {
|
|
42
|
+
if (options.ignore?.(url)) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
const span = recorder.open("http", `${method} ${host}`, {
|
|
46
|
+
"http.method": method,
|
|
47
|
+
"http.url": redactUrlQuery(url, getRedactor()),
|
|
48
|
+
});
|
|
49
|
+
if (span) {
|
|
50
|
+
spans.set(request, span);
|
|
51
|
+
}
|
|
52
|
+
return true;
|
|
53
|
+
};
|
|
54
|
+
const close = (request, error) => {
|
|
55
|
+
spans.get(request)?.end(error);
|
|
56
|
+
spans.delete(request);
|
|
57
|
+
};
|
|
58
|
+
// --- undici / fetch ------------------------------------------------------
|
|
59
|
+
on("undici:request:create", ({ request }) => {
|
|
60
|
+
const origin = String(request.origin ?? "");
|
|
61
|
+
const url = `${origin}${request.path ?? ""}`;
|
|
62
|
+
const host = origin.replace(/^[a-z]+:\/\//i, "");
|
|
63
|
+
const method = (request.method ?? "GET").toUpperCase();
|
|
64
|
+
if (!open(request, method, url, host)) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const traceId = currentTraceId();
|
|
68
|
+
if (traceId &&
|
|
69
|
+
shouldPropagate(url) &&
|
|
70
|
+
typeof request.addHeader === "function" &&
|
|
71
|
+
!hasUndiciHeader(request.headers, TRACE_HEADER)) {
|
|
72
|
+
request.addHeader(TRACE_HEADER, traceId);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
on("undici:request:trailers", ({ request }) => close(request));
|
|
76
|
+
on("undici:request:error", ({ request, error }) => close(request, error));
|
|
77
|
+
// --- node:http / node:https ----------------------------------------------
|
|
78
|
+
const describeNodeRequest = (request) => {
|
|
79
|
+
const host = String(request.getHeader?.("host") ?? request.host ?? "");
|
|
80
|
+
const url = `${request.protocol ?? "http:"}//${host}${request.path ?? ""}`;
|
|
81
|
+
return { host, url, method: (request.method ?? "GET").toUpperCase() };
|
|
82
|
+
};
|
|
83
|
+
// Published while headers can still be set (Node 22.12+). On older
|
|
84
|
+
// runtimes there is simply no propagation for this client; `start` below
|
|
85
|
+
// fires after the header block is already on its way.
|
|
86
|
+
on("http.client.request.created", ({ request }) => {
|
|
87
|
+
const { url } = describeNodeRequest(request);
|
|
88
|
+
const traceId = currentTraceId();
|
|
89
|
+
if (traceId &&
|
|
90
|
+
!options.ignore?.(url) &&
|
|
91
|
+
shouldPropagate(url) &&
|
|
92
|
+
!request.getHeader?.(TRACE_HEADER)) {
|
|
93
|
+
request.setHeader?.(TRACE_HEADER, traceId);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
on("http.client.request.start", ({ request }) => {
|
|
97
|
+
const { host, url, method } = describeNodeRequest(request);
|
|
98
|
+
if (!open(request, method, url, host)) {
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
// `close` always fires, with or without a response. An `error` listener
|
|
102
|
+
// would tell more, but adding one changes what an otherwise unhandled
|
|
103
|
+
// request error does to the process.
|
|
104
|
+
request.once?.("close", () => close(request, request.res
|
|
105
|
+
? undefined
|
|
106
|
+
: new Error("Request closed with no response")));
|
|
107
|
+
});
|
|
108
|
+
on("http.client.request.error", ({ request, error }) => close(request, error));
|
|
109
|
+
on("http.client.response.finish", ({ request }) => close(request));
|
|
110
|
+
return () => {
|
|
111
|
+
for (const [channel, handler] of subscriptions) {
|
|
112
|
+
unsubscribe(channel, handler);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
/** undici keeps headers as a flat `[name, value, ...]` array or a raw string. */
|
|
117
|
+
function hasUndiciHeader(headers, name) {
|
|
118
|
+
if (Array.isArray(headers)) {
|
|
119
|
+
for (let index = 0; index < headers.length; index += 2) {
|
|
120
|
+
if (String(headers[index]).toLowerCase() === name) {
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
return (typeof headers === "string" && headers.toLowerCase().includes(`${name}:`));
|
|
127
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
2
|
+
interface MongoConnectionModule {
|
|
3
|
+
Connection?: {
|
|
4
|
+
prototype?: object;
|
|
5
|
+
};
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* A command with its values removed: field names and operators stay, since
|
|
9
|
+
* they are the query's shape, and every primitive becomes `?`.
|
|
10
|
+
*
|
|
11
|
+
* Arrays come in two kinds and are told apart by what they hold. A list of
|
|
12
|
+
* values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
|
|
13
|
+
* query. A list of documents is structure, not data: the stages of an
|
|
14
|
+
* aggregation pipeline, the branches of an `$or`. Keeping one of those would
|
|
15
|
+
* report a five-stage pipeline as its `$match` alone.
|
|
16
|
+
*/
|
|
17
|
+
export declare function describeMongoCommand(command: Record<string, unknown>): {
|
|
18
|
+
operation: string;
|
|
19
|
+
statement: string;
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Command spans for the `mongodb` driver, and so for Mongoose and the Mongo
|
|
23
|
+
* modes of TypeORM and MikroORM.
|
|
24
|
+
*
|
|
25
|
+
* A write the server rejects - a duplicate key, a failed validator - does
|
|
26
|
+
* not fail here. The command itself succeeds and carries the rejection in its
|
|
27
|
+
* reply as `writeErrors`; the driver raises it a layer up. Reading the reply
|
|
28
|
+
* to find out would mean parsing the driver's lazily-decoded response, so the
|
|
29
|
+
* command's span stays clean and the error lands where the driver throws it:
|
|
30
|
+
* on the application method that made the call, one row above in the trace.
|
|
31
|
+
*
|
|
32
|
+
* Patched at the connection, where every operation - whichever collection
|
|
33
|
+
* helper or cursor produced it - becomes one wire command. The driver's own
|
|
34
|
+
* command monitoring would be the supported route, but it is switched on by a
|
|
35
|
+
* `MongoClient` option, which is the application's to pass, not an agent's.
|
|
36
|
+
*/
|
|
37
|
+
export declare function patchMongodb(connectionModule: MongoConnectionModule, recorder: OutgoingSpanRecorder): boolean;
|
|
38
|
+
export {};
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { patchMethod } from "./patch-method.util.js";
|
|
2
|
+
const MAX_STATEMENT_LENGTH = 2048;
|
|
3
|
+
const MAX_DEPTH = 10;
|
|
4
|
+
/** Pipeline stages and `$and`/`$or` branches kept before the rest are cut. */
|
|
5
|
+
const MAX_ARRAY_DOCUMENTS = 20;
|
|
6
|
+
/**
|
|
7
|
+
* Commands the driver issues for itself: the handshake and authentication of
|
|
8
|
+
* a connection it is opening, liveness checks, session and cursor cleanup.
|
|
9
|
+
* They are not the application's work, but a pool that grows to serve a burst
|
|
10
|
+
* opens its connections - and so shakes hands - inside the async context of
|
|
11
|
+
* whichever request caused the burst, where they would appear as spans that
|
|
12
|
+
* request never asked for.
|
|
13
|
+
*/
|
|
14
|
+
const DRIVER_HOUSEKEEPING = new Set([
|
|
15
|
+
"hello",
|
|
16
|
+
"ismaster",
|
|
17
|
+
"isMaster",
|
|
18
|
+
"saslStart",
|
|
19
|
+
"saslContinue",
|
|
20
|
+
"authenticate",
|
|
21
|
+
"getnonce",
|
|
22
|
+
"ping",
|
|
23
|
+
"buildInfo",
|
|
24
|
+
"endSessions",
|
|
25
|
+
"killCursors",
|
|
26
|
+
]);
|
|
27
|
+
/**
|
|
28
|
+
* A command with its values removed: field names and operators stay, since
|
|
29
|
+
* they are the query's shape, and every primitive becomes `?`.
|
|
30
|
+
*
|
|
31
|
+
* Arrays come in two kinds and are told apart by what they hold. A list of
|
|
32
|
+
* values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same
|
|
33
|
+
* query. A list of documents is structure, not data: the stages of an
|
|
34
|
+
* aggregation pipeline, the branches of an `$or`. Keeping one of those would
|
|
35
|
+
* report a five-stage pipeline as its `$match` alone.
|
|
36
|
+
*/
|
|
37
|
+
export function describeMongoCommand(command) {
|
|
38
|
+
const [name] = Object.keys(command);
|
|
39
|
+
const target = name === undefined ? undefined : command[name];
|
|
40
|
+
const operation = name === undefined
|
|
41
|
+
? "command"
|
|
42
|
+
: typeof target === "string"
|
|
43
|
+
? `${name} ${target}`
|
|
44
|
+
: name;
|
|
45
|
+
const scrub = (value, depth) => {
|
|
46
|
+
if (value === null || typeof value !== "object") {
|
|
47
|
+
return "?";
|
|
48
|
+
}
|
|
49
|
+
if (depth >= MAX_DEPTH) {
|
|
50
|
+
return "?";
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(value)) {
|
|
53
|
+
const documents = value.filter((item) => item !== null && typeof item === "object");
|
|
54
|
+
if (documents.length === 0) {
|
|
55
|
+
return value.length === 0 ? [] : ["?"];
|
|
56
|
+
}
|
|
57
|
+
return documents
|
|
58
|
+
.slice(0, MAX_ARRAY_DOCUMENTS)
|
|
59
|
+
.map((item) => scrub(item, depth + 1));
|
|
60
|
+
}
|
|
61
|
+
// ObjectId, Date, Binary, Long: BSON values, not sub-documents.
|
|
62
|
+
const proto = Object.getPrototypeOf(value);
|
|
63
|
+
if (proto !== Object.prototype && proto !== null) {
|
|
64
|
+
return "?";
|
|
65
|
+
}
|
|
66
|
+
const out = {};
|
|
67
|
+
for (const [key, item] of Object.entries(value)) {
|
|
68
|
+
out[key] = scrub(item, depth + 1);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
};
|
|
72
|
+
const shape = {};
|
|
73
|
+
for (const [key, value] of Object.entries(command)) {
|
|
74
|
+
// Session, cluster time and read preference: driver bookkeeping.
|
|
75
|
+
if (key === "lsid" || key.startsWith("$")) {
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
shape[key] =
|
|
79
|
+
key === name && typeof value === "string" ? value : scrub(value, 0);
|
|
80
|
+
}
|
|
81
|
+
let statement;
|
|
82
|
+
try {
|
|
83
|
+
statement = JSON.stringify(shape).slice(0, MAX_STATEMENT_LENGTH);
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
statement = operation;
|
|
87
|
+
}
|
|
88
|
+
return { operation, statement };
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Command spans for the `mongodb` driver, and so for Mongoose and the Mongo
|
|
92
|
+
* modes of TypeORM and MikroORM.
|
|
93
|
+
*
|
|
94
|
+
* A write the server rejects - a duplicate key, a failed validator - does
|
|
95
|
+
* not fail here. The command itself succeeds and carries the rejection in its
|
|
96
|
+
* reply as `writeErrors`; the driver raises it a layer up. Reading the reply
|
|
97
|
+
* to find out would mean parsing the driver's lazily-decoded response, so the
|
|
98
|
+
* command's span stays clean and the error lands where the driver throws it:
|
|
99
|
+
* on the application method that made the call, one row above in the trace.
|
|
100
|
+
*
|
|
101
|
+
* Patched at the connection, where every operation - whichever collection
|
|
102
|
+
* helper or cursor produced it - becomes one wire command. The driver's own
|
|
103
|
+
* command monitoring would be the supported route, but it is switched on by a
|
|
104
|
+
* `MongoClient` option, which is the application's to pass, not an agent's.
|
|
105
|
+
*/
|
|
106
|
+
export function patchMongodb(connectionModule, recorder) {
|
|
107
|
+
return patchMethod(connectionModule.Connection?.prototype, "command", (original) => function (...args) {
|
|
108
|
+
const command = args[1];
|
|
109
|
+
if (!command || typeof command !== "object") {
|
|
110
|
+
return original.apply(this, args);
|
|
111
|
+
}
|
|
112
|
+
const [commandName] = Object.keys(command);
|
|
113
|
+
if (commandName === undefined || DRIVER_HOUSEKEEPING.has(commandName)) {
|
|
114
|
+
return original.apply(this, args);
|
|
115
|
+
}
|
|
116
|
+
const { operation, statement } = describeMongoCommand(command);
|
|
117
|
+
const span = recorder.open("mongodb", operation, {
|
|
118
|
+
"db.system": "mongodb",
|
|
119
|
+
"db.statement": statement,
|
|
120
|
+
});
|
|
121
|
+
if (!span) {
|
|
122
|
+
return original.apply(this, args);
|
|
123
|
+
}
|
|
124
|
+
// Nothing in the arguments is touched. The last one looks like a
|
|
125
|
+
// callback and is not: `command(ns, command, options, responseType)`
|
|
126
|
+
// passes a response *class*, and wrapping it - as a first version of
|
|
127
|
+
// this did, taking any trailing function for a legacy callback - makes
|
|
128
|
+
// every operation throw inside the driver. A 4.x driver that really
|
|
129
|
+
// does pass a callback returns no promise, and `endWhenSettled` then
|
|
130
|
+
// closes the span on the spot: a span without its duration, which is
|
|
131
|
+
// the right price for never standing between a driver and its own
|
|
132
|
+
// arguments.
|
|
133
|
+
try {
|
|
134
|
+
return recorder.endWhenSettled(span, original.apply(this, args));
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
span.end(error);
|
|
138
|
+
throw error;
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|