@nestjs/observe 0.2.2 → 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/detached-observe-worker.assembly.d.ts +18 -0
- package/dist/agent/detached-observe-worker.assembly.js +29 -0
- package/dist/agent/detached-observe-worker.d.ts +21 -0
- package/dist/agent/detached-observe-worker.js +74 -24
- package/dist/agent/observe-agent.shared-buffer.js +7 -5
- package/dist/agent/observe-agent.worker.js +17 -21
- package/dist/agent/telemetry-wire-contract.js +1 -0
- package/dist/encoders/remap-keys.util.js +6 -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 +97 -9
- 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 +55 -6
- 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 +6 -4
- package/dist/protocols/graphql-operation-parser.js +61 -6
- 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 +35 -1
- package/dist/services/operation-trace.registry.js +68 -5
- 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 +121 -15
- package/dist/utils/source-map-resolver.util.js +12 -0
- package/package.json +35 -2
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";
|
|
@@ -31,6 +34,7 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
|
31
34
|
import { TracerService } from "./services/tracer.service.js";
|
|
32
35
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
33
36
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
37
|
+
import { LogRedactor } from "./utils/log-redactor.js";
|
|
34
38
|
/**
|
|
35
39
|
* All three async providers are optional on the options type, but one of them
|
|
36
40
|
* has to be there. Stating that here beats the `undefined` token Nest would
|
|
@@ -143,10 +147,14 @@ export function createObserveModule(options = {}) {
|
|
|
143
147
|
provide: OperationTraceRegistry,
|
|
144
148
|
// The instance already exists (the instrumentation hook below holds
|
|
145
149
|
// it), so this is the one moment the resolved `ObserveOptions` and the
|
|
146
|
-
// registry meet: `spanCollapse`
|
|
147
|
-
// `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
150
|
+
// registry meet: `spanCollapse` and `redaction` are applied here.
|
|
151
|
+
// Optional because `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
152
|
+
// error.
|
|
148
153
|
useFactory: (observeOptions) => {
|
|
149
154
|
operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
|
|
155
|
+
operationTraceRegistry.configureRedaction(observeOptions?.redaction?.enabled === false
|
|
156
|
+
? null
|
|
157
|
+
: new LogRedactor(observeOptions?.redaction));
|
|
150
158
|
return operationTraceRegistry;
|
|
151
159
|
},
|
|
152
160
|
inject: [{ token: OBSERVE_OPTIONS, optional: true }],
|
|
@@ -166,9 +174,14 @@ export function createObserveModule(options = {}) {
|
|
|
166
174
|
// `forwardLogs` is enabled, and it redacts before anything is buffered.
|
|
167
175
|
StdoutForwarderService,
|
|
168
176
|
QueueObserveAgentService,
|
|
177
|
+
// A no-op unless bull - the driver behind @nestjs/bull - is installed.
|
|
178
|
+
BullObserveAgentService,
|
|
169
179
|
// A no-op unless @nestjs/schedule is installed; it patches the explorer
|
|
170
180
|
// from its constructor so the patch lands before any handler is found.
|
|
171
181
|
ScheduleObserveAgentService,
|
|
182
|
+
// A no-op unless @nestjs/websockets is installed.
|
|
183
|
+
WsObserveAgentService,
|
|
184
|
+
OutgoingObserveAgentService,
|
|
172
185
|
],
|
|
173
186
|
exports: [AsyncLocalStorage, TracerService],
|
|
174
187
|
}),
|
|
@@ -193,6 +206,8 @@ export function createObserveModule(options = {}) {
|
|
|
193
206
|
instance instanceof GraphQLObserveAgentService ||
|
|
194
207
|
// Same reason: its wrapper runs inside the job traces it opens.
|
|
195
208
|
instance instanceof ScheduleObserveAgentService ||
|
|
209
|
+
instance instanceof WsObserveAgentService ||
|
|
210
|
+
instance instanceof OutgoingObserveAgentService ||
|
|
196
211
|
// Nest's discovery machinery, which the GraphQL agent walks to map
|
|
197
212
|
// root fields back to their resolver classes. It has to stay
|
|
198
213
|
// unproxied: ModulesContainer extends Map, and a Map method invoked
|
|
@@ -227,14 +242,48 @@ export function createObserveModule(options = {}) {
|
|
|
227
242
|
// skip hook to avoid duplicating APIs). Newer cores additionally wrap
|
|
228
243
|
// this in a safety net that falls back to the undecorated instance,
|
|
229
244
|
// with a warning, should it ever throw.
|
|
230
|
-
instanceDecorator:
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
+
})(),
|
|
234
255
|
},
|
|
235
256
|
ObserveModule,
|
|
236
257
|
};
|
|
237
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
|
+
}
|
|
238
287
|
/**
|
|
239
288
|
* Identifies `@nestjs/graphql`'s `ResolverDecoratorHost` without importing the
|
|
240
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
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { OutgoingSpanRecorder } from "./outgoing-span.recorder.js";
|
|
2
|
+
interface Mysql2Module {
|
|
3
|
+
Connection?: {
|
|
4
|
+
prototype?: object;
|
|
5
|
+
};
|
|
6
|
+
Pool?: {
|
|
7
|
+
prototype?: object;
|
|
8
|
+
};
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Query spans for `mysql2` - the core connection and pool, which the promise
|
|
12
|
+
* wrappers, TypeORM, MikroORM, Knex, Drizzle and Sequelize all go through.
|
|
13
|
+
*
|
|
14
|
+
* A pool's `query` builds the command itself and hands that object to a
|
|
15
|
+
* connection later, possibly from another request's context, so the span is
|
|
16
|
+
* opened at the pool and the command is marked; the connection-level wrapper
|
|
17
|
+
* sees the mark and stands aside.
|
|
18
|
+
*/
|
|
19
|
+
export declare function patchMysql2(mysql2: Mysql2Module, recorder: OutgoingSpanRecorder): boolean;
|
|
20
|
+
export {};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { patchMethod } from "./patch-method.util.js";
|
|
2
|
+
import { describeSqlStatement } from "./sql-statement.util.js";
|
|
3
|
+
/** Marks a command that already has a span, however it reaches a connection. */
|
|
4
|
+
const SPANNED = Symbol.for("nestjs.observe.mysql2.spanned");
|
|
5
|
+
/**
|
|
6
|
+
* Query spans for `mysql2` - the core connection and pool, which the promise
|
|
7
|
+
* wrappers, TypeORM, MikroORM, Knex, Drizzle and Sequelize all go through.
|
|
8
|
+
*
|
|
9
|
+
* A pool's `query` builds the command itself and hands that object to a
|
|
10
|
+
* connection later, possibly from another request's context, so the span is
|
|
11
|
+
* opened at the pool and the command is marked; the connection-level wrapper
|
|
12
|
+
* sees the mark and stands aside.
|
|
13
|
+
*/
|
|
14
|
+
export function patchMysql2(mysql2, recorder) {
|
|
15
|
+
const wrap = (original) => function (...args) {
|
|
16
|
+
const first = args[0];
|
|
17
|
+
if (typeof first === "object" && first?.[SPANNED]) {
|
|
18
|
+
return original.apply(this, args);
|
|
19
|
+
}
|
|
20
|
+
const sql = typeof first === "string" ? first : first?.sql;
|
|
21
|
+
if (typeof sql !== "string") {
|
|
22
|
+
return original.apply(this, args);
|
|
23
|
+
}
|
|
24
|
+
const { operation, statement } = describeSqlStatement(sql);
|
|
25
|
+
const span = recorder.open("mysql2", operation, {
|
|
26
|
+
"db.system": "mysql",
|
|
27
|
+
"db.statement": statement,
|
|
28
|
+
});
|
|
29
|
+
if (!span) {
|
|
30
|
+
return original.apply(this, args);
|
|
31
|
+
}
|
|
32
|
+
// The callback is wrapped where it is passed, not only once it has
|
|
33
|
+
// become the command's `onResult`: a pool's `execute` returns no command
|
|
34
|
+
// at all - it builds one later, on the connection it checks out - and a
|
|
35
|
+
// connection's `execute` reports a failed prepare to the callback it
|
|
36
|
+
// was given, whatever `onResult` has been replaced with since.
|
|
37
|
+
let hasCallback = false;
|
|
38
|
+
const last = args.length - 1;
|
|
39
|
+
if (typeof args[last] === "function") {
|
|
40
|
+
const callback = args[last];
|
|
41
|
+
hasCallback = true;
|
|
42
|
+
args[last] = function (error, ...rest) {
|
|
43
|
+
span.end(error);
|
|
44
|
+
return callback.call(this, error, ...rest);
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
let command;
|
|
48
|
+
try {
|
|
49
|
+
// Covered as well as marked. The mark follows a command *object* to
|
|
50
|
+
// the connection, which is how `pool.query` hands its work over; but
|
|
51
|
+
// `pool.execute` passes the connection the SQL string again, with
|
|
52
|
+
// nothing to carry a mark, and the same query would be recorded twice.
|
|
53
|
+
command = recorder.cover(() => original.apply(this, args));
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
span.end(error);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
if (!command || typeof command !== "object") {
|
|
60
|
+
if (!hasCallback) {
|
|
61
|
+
span.end();
|
|
62
|
+
}
|
|
63
|
+
return command;
|
|
64
|
+
}
|
|
65
|
+
command[SPANNED] = true;
|
|
66
|
+
if (hasCallback) {
|
|
67
|
+
return command;
|
|
68
|
+
}
|
|
69
|
+
if (typeof command.onResult === "function") {
|
|
70
|
+
const onResult = command.onResult;
|
|
71
|
+
command.onResult = function (error, ...rest) {
|
|
72
|
+
span.end(error);
|
|
73
|
+
return onResult.call(this, error, ...rest);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
// The streaming form. `end` always fires; an `error` listener is not
|
|
78
|
+
// added, because without one mysql2 lets the error surface as an
|
|
79
|
+
// uncaught exception, and an agent must not be what silences that.
|
|
80
|
+
command.once?.("end", () => span.end());
|
|
81
|
+
}
|
|
82
|
+
return command;
|
|
83
|
+
};
|
|
84
|
+
const patched = ["query", "execute"].flatMap((method) => [
|
|
85
|
+
patchMethod(mysql2.Connection?.prototype, method, wrap),
|
|
86
|
+
patchMethod(mysql2.Pool?.prototype, method, wrap),
|
|
87
|
+
]);
|
|
88
|
+
return patched.some(Boolean);
|
|
89
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { OnApplicationShutdown } from "@nestjs/common";
|
|
2
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
3
|
+
import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
|
|
4
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
5
|
+
export declare class OutgoingObserveAgentService implements OnApplicationShutdown {
|
|
6
|
+
private readonly options;
|
|
7
|
+
private readonly logger;
|
|
8
|
+
private unsubscribeHttp?;
|
|
9
|
+
constructor(options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<any, any>>);
|
|
10
|
+
onApplicationShutdown(): void;
|
|
11
|
+
/**
|
|
12
|
+
* Patches every copy of a driver the application can end up running on: the
|
|
13
|
+
* one it resolves itself, and the one each ORM that depends on the driver
|
|
14
|
+
* *directly* resolves - see `DRIVER_DEPENDENTS`.
|
|
15
|
+
*/
|
|
16
|
+
private patchDriver;
|
|
17
|
+
}
|