@nestjs/observe 0.3.25 → 0.3.26
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 +17 -0
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +196 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +7 -1
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +28 -3
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/project-files.d.ts +42 -1
- package/dist/cli/project-files.js +146 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +73 -2
- package/dist/instrument/create-instance-decorator.instrument.js +158 -96
- package/dist/interfaces/observe-options.interface.d.ts +3 -1
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.js +7 -3
- package/dist/otlp/otlp-trace-exporter.service.js +63 -5
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +13 -6
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mssql.integration.js +16 -2
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +106 -14
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +2 -12
- package/dist/protocols/deferred-trace-completion.d.ts +9 -1
- package/dist/protocols/deferred-trace-completion.js +36 -6
- package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
- package/dist/protocols/graphql-observe-agent.service.js +166 -5
- package/dist/protocols/graphql-operation-parser.js +72 -18
- package/dist/protocols/http-observe-agent.service.d.ts +43 -9
- package/dist/protocols/http-observe-agent.service.js +177 -59
- package/dist/protocols/job-trace-runner.d.ts +35 -3
- package/dist/protocols/job-trace-runner.js +126 -29
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
- package/dist/protocols/rpc-observe-agent.service.js +187 -47
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +226 -20
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +3 -4
- package/dist/services/operation-trace.registry.d.ts +45 -1
- package/dist/services/operation-trace.registry.js +418 -35
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +288 -51
- package/dist/services/tracer.service.d.ts +23 -0
- package/dist/services/tracer.service.js +91 -5
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +100 -12
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +7 -3
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +512 -61
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +26 -4
- package/dist/utils/redact-url-query.js +184 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +8 -0
- package/dist/utils/source-context.util.js +88 -24
- package/dist/utils/source-map-resolver.util.js +8 -2
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Reflector } from "@nestjs/core";
|
|
2
|
+
import { types } from "node:util";
|
|
2
3
|
import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
|
|
3
4
|
/**
|
|
4
5
|
* Stand-in "class name" for instrumented standalone functions. Unlike methods,
|
|
@@ -49,20 +50,29 @@ function isFrameworkNoise(instance) {
|
|
|
49
50
|
* `MongoClient.startSession` spans are not.
|
|
50
51
|
*
|
|
51
52
|
* 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
|
+
* imported here, and an application may carry more than one copy of it. The
|
|
54
|
+
* name is looked for on every class up the prototype chain, so a provider
|
|
55
|
+
* class that extends either one - `class MongoService extends MongoClient` -
|
|
56
|
+
* is left alone too, for the same reason.
|
|
53
57
|
*/
|
|
54
58
|
function isMongoDriverHandle(instance) {
|
|
55
59
|
const candidate = instance;
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
60
|
+
for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
|
|
61
|
+
const name = Object.hasOwn(proto, "constructor")
|
|
62
|
+
? proto.constructor?.name
|
|
63
|
+
: undefined;
|
|
64
|
+
if (name === "MongoClient" &&
|
|
65
|
+
typeof candidate.startSession === "function" &&
|
|
66
|
+
typeof candidate.db === "function") {
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
if (name === "Db" &&
|
|
70
|
+
typeof candidate.collection === "function" &&
|
|
71
|
+
typeof candidate.databaseName === "string") {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
65
74
|
}
|
|
75
|
+
return false;
|
|
66
76
|
}
|
|
67
77
|
/**
|
|
68
78
|
* Library classes traced only in part, each with a method only it has, which
|
|
@@ -146,7 +156,9 @@ function isLibraryInternal(target, methodName) {
|
|
|
146
156
|
}
|
|
147
157
|
export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
148
158
|
/**
|
|
149
|
-
* Builds the tracing wrapper shared by methods and standalone functions
|
|
159
|
+
* Builds the tracing wrapper shared by methods and standalone functions:
|
|
160
|
+
* called with the receiver and the arguments of the call it stands in for,
|
|
161
|
+
* as the `apply` trap that dispatches to it is handed them.
|
|
150
162
|
*
|
|
151
163
|
* Every function this creates is named `<className>.<methodName>`, so the
|
|
152
164
|
* frames instrumentation contributes to a stack trace read like the call the
|
|
@@ -160,6 +172,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
160
172
|
// "Object.<name>".
|
|
161
173
|
const call = spec.call;
|
|
162
174
|
const callUntraced = spec.callUntraced;
|
|
175
|
+
const isAsync = spec.isAsync;
|
|
163
176
|
const endStep = (requestId, stepId) => operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId);
|
|
164
177
|
const recordError = (requestId, stepId, err) => {
|
|
165
178
|
// Before the registry records the step: `internalEndTraceStep` copies
|
|
@@ -188,18 +201,24 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
188
201
|
ignoreFailure(() => recordError(requestId, stepId, err));
|
|
189
202
|
throw err;
|
|
190
203
|
};
|
|
191
|
-
//
|
|
192
|
-
// the caller's own `.then` would:
|
|
193
|
-
//
|
|
194
|
-
|
|
204
|
+
// The promise of a native `async` method is swapped for a chained
|
|
205
|
+
// one, just as the caller's own `.then` would: nothing but the
|
|
206
|
+
// caller can hold it, so a rejection the caller drops still
|
|
207
|
+
// raises `unhandledRejection`, as without the span.
|
|
208
|
+
if (isAsync) {
|
|
195
209
|
return result.then(settled, failed);
|
|
196
210
|
}
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
-
//
|
|
200
|
-
//
|
|
201
|
-
//
|
|
202
|
-
//
|
|
211
|
+
// Any other promise is handed back as-is and watched on a side
|
|
212
|
+
// branch, the way `OutgoingSpanRecorder.endWhenSettled` watches
|
|
213
|
+
// outgoing calls. It may be held elsewhere - a `.catch` the method
|
|
214
|
+
// attached itself, an in-flight promise callers share, the
|
|
215
|
+
// callback ioredis answers a command through - and a chained copy
|
|
216
|
+
// rejected where those handlers do not reach: dropped by the
|
|
217
|
+
// caller, it was an unhandled rejection, and under Node's default
|
|
218
|
+
// it ended a process that handled the failure. Handed back, it
|
|
219
|
+
// also keeps what it carries beyond its value (`json()` on a
|
|
220
|
+
// `got` request, `kill()` on an `execa` child, a subclass).
|
|
221
|
+
// Watching marks it handled, so a rejection nobody handles no
|
|
203
222
|
// longer raises `unhandledRejection`; the span still records it.
|
|
204
223
|
result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
|
|
205
224
|
return result;
|
|
@@ -212,44 +231,47 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
212
231
|
// Re-throw the error to maintain original behavior
|
|
213
232
|
throw err;
|
|
214
233
|
}
|
|
215
|
-
finally {
|
|
216
|
-
spec.setActive(false);
|
|
217
|
-
}
|
|
218
234
|
});
|
|
219
|
-
//
|
|
220
|
-
//
|
|
221
|
-
|
|
235
|
+
// The receiver the call was made with is handed on, not read off `this`:
|
|
236
|
+
// the wrapper is called as a plain function, so V8 prints its frame as
|
|
237
|
+
// top-level, under the name above.
|
|
238
|
+
return named(frameName, (thisArg, args) => {
|
|
222
239
|
// Already tracing this callable, invoke it as-is
|
|
223
240
|
if (spec.isActive()) {
|
|
224
|
-
return callUntraced(
|
|
241
|
+
return callUntraced(thisArg, args);
|
|
225
242
|
}
|
|
226
243
|
const store = als.getStore();
|
|
227
244
|
const requestId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(options.traceIdKey);
|
|
228
245
|
if (!requestId) {
|
|
229
|
-
return callUntraced(
|
|
246
|
+
return callUntraced(thisArg, args);
|
|
230
247
|
}
|
|
248
|
+
// Cleared in the frame that set it, whatever throws in between: opening
|
|
249
|
+
// the step, copying the store and entering it can each run out of
|
|
250
|
+
// stack, and a flag left set sent every later call of this method, from
|
|
251
|
+
// any request, down the untraced path until the process restarted.
|
|
231
252
|
spec.setActive(true);
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
finally {
|
|
244
|
-
spec.setActive(false);
|
|
253
|
+
try {
|
|
254
|
+
const callerId = store?.get(CALLER_METADATA_KEY);
|
|
255
|
+
const newStepId = operationTraceRegistry.internalStartTraceStep(requestId, className, methodName, callerId);
|
|
256
|
+
// No step means the registry holds no snapshot for this trace id -
|
|
257
|
+
// the request was dropped by `http.ignore` or sampled out, but its
|
|
258
|
+
// store still carries the id, which log correlation needs there - or
|
|
259
|
+
// the operation has opened as many spans as one may. Nothing was
|
|
260
|
+
// opened, so nothing must be closed; without this bail-out every
|
|
261
|
+
// provider call on an ignored route logged a registry error.
|
|
262
|
+
if (newStepId === undefined) {
|
|
263
|
+
return callUntraced(thisArg, args);
|
|
245
264
|
}
|
|
265
|
+
// Everything the caller's context holds, with this span as the caller
|
|
266
|
+
// of whatever it calls. A copy, so the caller's context still names
|
|
267
|
+
// the caller once this call returns.
|
|
268
|
+
const spanStore = new Map(store);
|
|
269
|
+
spanStore.set(CALLER_METADATA_KEY, newStepId);
|
|
270
|
+
return als.run(spanStore, callTraced, thisArg, args, requestId, newStepId);
|
|
271
|
+
}
|
|
272
|
+
finally {
|
|
273
|
+
spec.setActive(false);
|
|
246
274
|
}
|
|
247
|
-
// Everything the caller's context holds, with this span as the caller
|
|
248
|
-
// of whatever it calls. A copy, so the caller's context still names the
|
|
249
|
-
// caller once this call returns.
|
|
250
|
-
const spanStore = new Map(store);
|
|
251
|
-
spanStore.set(CALLER_METADATA_KEY, newStepId);
|
|
252
|
-
return als.run(spanStore, callTraced, this, args, requestId, newStepId);
|
|
253
275
|
});
|
|
254
276
|
};
|
|
255
277
|
const instrumentFunction = (fn) => {
|
|
@@ -271,6 +293,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
271
293
|
spanId: `${className}#${methodName}`,
|
|
272
294
|
isActive: () => active,
|
|
273
295
|
setActive: (value) => (active = value),
|
|
296
|
+
isAsync: types.isAsyncFunction(fn),
|
|
274
297
|
call: invoke,
|
|
275
298
|
callUntraced: invoke,
|
|
276
299
|
});
|
|
@@ -279,7 +302,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
279
302
|
// static properties, `instanceof` and reflect-metadata lookups. Only
|
|
280
303
|
// `apply` is trapped, so `new fn()` still constructs the original.
|
|
281
304
|
return new Proxy(fn, {
|
|
282
|
-
apply: named(frameName, (_target, thisArg, args) =>
|
|
305
|
+
apply: named(frameName, (_target, thisArg, args) => tracedFn(thisArg, args)),
|
|
283
306
|
});
|
|
284
307
|
};
|
|
285
308
|
const instrumentObject = (instance) => {
|
|
@@ -335,12 +358,21 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
335
358
|
// constructors and callable objects.
|
|
336
359
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
337
360
|
const passedThrough = new WeakSet();
|
|
338
|
-
|
|
361
|
+
const proxy = new Proxy(instance, {
|
|
339
362
|
// Runs for every property read through the proxy - each `this.field`
|
|
340
363
|
// and `this.dependency.method` inside a traced call - so the common
|
|
341
|
-
// answers come first: a
|
|
342
|
-
// wrapped.
|
|
364
|
+
// answers come first: a read by something other than the proxy, a value
|
|
365
|
+
// that is no method, then a method already wrapped.
|
|
343
366
|
get: (target, prop, receiver) => {
|
|
367
|
+
// An object that inherits from the proxy - what a traced method
|
|
368
|
+
// derives from `this` with `Object.create(this)`, as pino's
|
|
369
|
+
// `logger.child()` does - reads its property as it would without the
|
|
370
|
+
// proxy, accessors against itself, and calls its methods with itself
|
|
371
|
+
// as `this`. Wrapped and cached, the first such object to read a
|
|
372
|
+
// method was the `this` of every later call of it, from any request.
|
|
373
|
+
if (receiver !== proxy) {
|
|
374
|
+
return Reflect.get(target, prop, receiver);
|
|
375
|
+
}
|
|
344
376
|
const attributeValue = Reflect.get(target, prop);
|
|
345
377
|
if (typeof attributeValue !== "function" || prop === "constructor") {
|
|
346
378
|
return attributeValue;
|
|
@@ -385,18 +417,19 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
385
417
|
const originalMethod = requiresRawReceiver
|
|
386
418
|
? attributeValue
|
|
387
419
|
: Reflect.get(target, prop, receiver);
|
|
388
|
-
const tracedReceiver = requiresRawReceiver ? target :
|
|
420
|
+
const tracedReceiver = requiresRawReceiver ? target : proxy;
|
|
389
421
|
// The wrapper is made once per method of this instance and cached
|
|
390
422
|
// below, so a flag of its own guards exactly that callable - checked
|
|
391
423
|
// and flipped on every traced call, where a lookup keyed by instance
|
|
392
424
|
// and name used to be.
|
|
393
425
|
let active = false;
|
|
394
|
-
const
|
|
426
|
+
const tracedFn = createTracedWrapper({
|
|
395
427
|
className,
|
|
396
428
|
methodName,
|
|
397
429
|
spanId: generateSpanId(target, methodName),
|
|
398
430
|
isActive: () => active,
|
|
399
431
|
setActive: (value) => (active = value),
|
|
432
|
+
isAsync: types.isAsyncFunction(originalMethod),
|
|
400
433
|
// Traced calls run against the proxy so that a method calling into
|
|
401
434
|
// itself (`this.other()`) is instrumented as a nested step - except
|
|
402
435
|
// for private-member classes, whose brand checks only the raw
|
|
@@ -404,32 +437,38 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
404
437
|
call: named(frameName, (_thisArg, args) => originalMethod.apply(tracedReceiver, args)),
|
|
405
438
|
callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
|
|
406
439
|
});
|
|
407
|
-
//
|
|
408
|
-
//
|
|
409
|
-
//
|
|
410
|
-
//
|
|
411
|
-
//
|
|
412
|
-
|
|
413
|
-
//
|
|
414
|
-
//
|
|
415
|
-
//
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
440
|
+
// A method read off the provider is not always called on it. ioredis
|
|
441
|
+
// copies a client's custom commands onto every `Pipeline` it makes
|
|
442
|
+
// (`this[name] = redis[name]`), and each queues on the `this` it is
|
|
443
|
+
// called with: run against the client regardless, a command written
|
|
444
|
+
// into `multi()` was sent at once, outside the transaction. Called on
|
|
445
|
+
// another object, the method runs as it would without the proxy -
|
|
446
|
+
// against that object, untraced. Called on the provider, or on
|
|
447
|
+
// nothing, it is traced against the receiver chosen above.
|
|
448
|
+
//
|
|
449
|
+
// Bound, so V8 prints the trap's frame as top-level, under its name:
|
|
450
|
+
// called as the handler's `apply`, it would carry "[as apply]".
|
|
451
|
+
const apply = named(frameName, (_target, thisArg, args) => thisArg === proxy ||
|
|
452
|
+
thisArg === target ||
|
|
453
|
+
thisArg === undefined ||
|
|
454
|
+
thisArg === null
|
|
455
|
+
? tracedFn(thisArg, args)
|
|
456
|
+
: Reflect.apply(originalMethod, thisArg, args)).bind(undefined);
|
|
457
|
+
// A proxy of the method itself, so `name`, `length` and everything
|
|
458
|
+
// else read off it are the original's, to anything reflecting over it
|
|
459
|
+
// (DI, decorators, arity checks). Metadata is held by identity, so it
|
|
460
|
+
// is copied onto the proxy.
|
|
461
|
+
const wrapped = new Proxy(originalMethod, { apply });
|
|
424
462
|
const metadataKeys = Reflect.getMetadataKeys(originalMethod);
|
|
425
463
|
for (const key of metadataKeys) {
|
|
426
464
|
const metadata = Reflect.getMetadata(key, originalMethod);
|
|
427
|
-
Reflect.defineMetadata(key, metadata,
|
|
465
|
+
Reflect.defineMetadata(key, metadata, wrapped);
|
|
428
466
|
}
|
|
429
|
-
methodRefsCache.set(attributeValue,
|
|
430
|
-
return
|
|
467
|
+
methodRefsCache.set(attributeValue, wrapped);
|
|
468
|
+
return wrapped;
|
|
431
469
|
},
|
|
432
470
|
});
|
|
471
|
+
return proxy;
|
|
433
472
|
};
|
|
434
473
|
return (instance) => {
|
|
435
474
|
if (typeof instance === "function") {
|
|
@@ -441,19 +480,6 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
|
|
|
441
480
|
return instance;
|
|
442
481
|
};
|
|
443
482
|
}
|
|
444
|
-
/**
|
|
445
|
-
* Whether a promise is a bare native one: no subclass, no members of its own.
|
|
446
|
-
* Such a promise carries nothing but its value, so a chained promise can stand
|
|
447
|
-
* in for it without the caller noticing.
|
|
448
|
-
*
|
|
449
|
-
* Symbol keys do not count: before Node 24, `AsyncLocalStorage` stamps its
|
|
450
|
-
* own (`async_id_symbol`, `kResourceStore`, ...) on every promise created in
|
|
451
|
-
* a context, which every traced call runs in.
|
|
452
|
-
*/
|
|
453
|
-
function isPlainPromise(promise) {
|
|
454
|
-
return (Object.getPrototypeOf(promise) === Promise.prototype &&
|
|
455
|
-
Object.getOwnPropertyNames(promise).length === 0);
|
|
456
|
-
}
|
|
457
483
|
/** Runs span bookkeeping whose failure must not reach the caller. */
|
|
458
484
|
function ignoreFailure(fn) {
|
|
459
485
|
try {
|
|
@@ -485,22 +511,58 @@ function named(name, fn) {
|
|
|
485
511
|
* Only the topmost match is rewritten. Every wrapper on the way out relabels
|
|
486
512
|
* its own frame, and inner calls unwind before outer ones, so two classes that
|
|
487
513
|
* happen to share a method name each end up with the right label.
|
|
514
|
+
*
|
|
515
|
+
* An error with a long `name` and `message` is left as it is - see
|
|
516
|
+
* `MAX_RELABELLED_HEADER_LENGTH`.
|
|
488
517
|
*/
|
|
489
518
|
function relabelProxyFrame(err, className, methodName) {
|
|
490
|
-
|
|
491
|
-
|
|
519
|
+
// The label is cosmetic, so nothing here may take the place of the error
|
|
520
|
+
// the method threw: a `stack` that is a getter can throw on being read, as
|
|
521
|
+
// a read-only one throws on being written.
|
|
522
|
+
try {
|
|
523
|
+
// Measured first: reading `stack` is what writes it out.
|
|
524
|
+
if (!(err instanceof Error) ||
|
|
525
|
+
stackHeaderLength(err) > MAX_RELABELLED_HEADER_LENGTH) {
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
const stack = err.stack;
|
|
529
|
+
if (typeof stack !== "string") {
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
// `async` prefixes the type name on frames resumed from an await. Spaces
|
|
533
|
+
// and tabs only after the newline, not `\s`: a newline matched there too,
|
|
534
|
+
// and a message of newlines then rescanned the run after each one.
|
|
535
|
+
const frame = new RegExp(`(\\n[ \\t]*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
|
|
536
|
+
if (!frame.test(stack)) {
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
err.stack = stack.replace(frame, `$1${className}.${methodName}`);
|
|
492
540
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
if (!frame.test(err.stack)) {
|
|
496
|
-
return;
|
|
541
|
+
catch {
|
|
542
|
+
// Left as it is.
|
|
497
543
|
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* The longest `name` plus `message` of an error whose stack is relabelled.
|
|
547
|
+
*
|
|
548
|
+
* V8 writes an error's stack out when it is first read, opening it with the
|
|
549
|
+
* two. Until then a message that quotes the request - `Unknown id ${id}` - is
|
|
550
|
+
* a reference to the text it quotes, however long, and the frames are held in
|
|
551
|
+
* a compact form. Searching the stack writes all of it out, and the copy stays
|
|
552
|
+
* on the error as long as anything holds it: one call per element of a
|
|
553
|
+
* client's array, each failing with a long quote, then held by
|
|
554
|
+
* `Promise.allSettled`, held a copy each. The label is cosmetic, so an error
|
|
555
|
+
* past this keeps `Proxy.` rather than cost that.
|
|
556
|
+
*/
|
|
557
|
+
const MAX_RELABELLED_HEADER_LENGTH = 1024;
|
|
558
|
+
function stackHeaderLength(err) {
|
|
498
559
|
try {
|
|
499
|
-
err.
|
|
560
|
+
return ((typeof err.name === "string" ? err.name.length : 0) +
|
|
561
|
+
(typeof err.message === "string" ? err.message.length : 0));
|
|
500
562
|
}
|
|
501
563
|
catch {
|
|
502
|
-
//
|
|
503
|
-
|
|
564
|
+
// A getter that throws; leave such an error alone.
|
|
565
|
+
return Infinity;
|
|
504
566
|
}
|
|
505
567
|
}
|
|
506
568
|
function escapeRegExp(value) {
|
|
@@ -489,7 +489,9 @@ export interface ObserveOptions {
|
|
|
489
489
|
* Applied *in addition to* the built-in redaction, which always masks the
|
|
490
490
|
* values of well-known sensitive parameters (`token`, `password`, `code`,
|
|
491
491
|
* `signature`, ...) whether or not this is set. Use it for the parameters
|
|
492
|
-
* only your application knows are sensitive.
|
|
492
|
+
* only your application knows are sensitive. It is matched against every
|
|
493
|
+
* URL the agent records: the request's own, a URL in a captured request
|
|
494
|
+
* header (`referer`, ...) and the URL of an outgoing HTTP call.
|
|
493
495
|
* @default undefined
|
|
494
496
|
*/
|
|
495
497
|
queryParamsObfuscateRegex?: RegExp;
|
|
@@ -31,6 +31,7 @@ const MAX_SPANS_SEARCHED = 200;
|
|
|
31
31
|
const MAX_OBJECTIVES_PER_HANDLER = 10;
|
|
32
32
|
const MAX_HANDLER_LENGTH = 255;
|
|
33
33
|
const MAX_ROUTE_LENGTH = 255;
|
|
34
|
+
const MAX_METHOD_LENGTH = 10;
|
|
34
35
|
/** `@nestjs/common`'s METHOD_METADATA - what `@Get()`, `@Post()` and the rest write. */
|
|
35
36
|
const METHOD_METADATA = "method";
|
|
36
37
|
/** `@nestjs/common`'s PATH_METADATA and VERSION_METADATA, on the controller and the handler. */
|
|
@@ -176,6 +177,17 @@ let ObjectivesRegistry = class ObjectivesRegistry {
|
|
|
176
177
|
}
|
|
177
178
|
return undefined;
|
|
178
179
|
}
|
|
180
|
+
// Only a handler routed for every method is declared under the request's
|
|
181
|
+
// own, and Node parses one longer than the collector takes: UNSUBSCRIBE.
|
|
182
|
+
// Nothing is stated, so the next request with an ordinary method declares
|
|
183
|
+
// the route as usual.
|
|
184
|
+
if (method !== undefined && method.length > MAX_METHOD_LENGTH) {
|
|
185
|
+
if (!this.refusedRoutes.has(route)) {
|
|
186
|
+
this.refusedRoutes.add(route);
|
|
187
|
+
this.logger.warn(`@Objective on ${handler} not declared for a ${method} request: a method is at most ${MAX_METHOD_LENGTH} characters.`);
|
|
188
|
+
}
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
179
191
|
const stated = this.statedAt.get(route);
|
|
180
192
|
if (stated !== undefined && now - stated < RESTATE_EVERY_MS) {
|
|
181
193
|
return undefined;
|
package/dist/observe.module.js
CHANGED
|
@@ -13,13 +13,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
13
13
|
import { Inject, Logger, Module, } from "@nestjs/common";
|
|
14
14
|
import { DiscoveryModule, DiscoveryService, HttpAdapterHost, MetadataScanner, ModulesContainer, } from "@nestjs/core";
|
|
15
15
|
import { AsyncLocalStorage } from "async_hooks";
|
|
16
|
+
import { isObservable, Observable } from "rxjs";
|
|
16
17
|
import { ObserveAgentSharedBuffer } from "./agent/observe-agent.shared-buffer.js";
|
|
17
18
|
import { ObserveAgentWorker } from "./agent/observe-agent.worker.js";
|
|
18
19
|
import { ObjectivesRegistry } from "./objectives/objectives.registry.js";
|
|
19
20
|
import { createInstanceDecorator } from "./instrument/create-instance-decorator.instrument.js";
|
|
20
21
|
import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
|
|
21
22
|
import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
|
|
22
|
-
import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
|
|
23
|
+
import { HttpObserveAgentService, shareHttpAdapterHooks, } from "./protocols/http-observe-agent.service.js";
|
|
23
24
|
import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
|
|
24
25
|
import { OtlpTraceExporter } from "./otlp/otlp-trace-exporter.service.js";
|
|
25
26
|
import { installLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./outgoing/llm/llm-fetch.integration.js";
|
|
@@ -37,6 +38,7 @@ import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
|
|
|
37
38
|
import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
38
39
|
import { TracerService } from "./services/tracer.service.js";
|
|
39
40
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
41
|
+
import { setAgentHook } from "./utils/shared-hook-slot.util.js";
|
|
40
42
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
41
43
|
import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
|
|
42
44
|
import { OpenTelemetryInteropGate, traceparentToHandOn, } from "./utils/trace-handoff.util.js";
|
|
@@ -44,6 +46,7 @@ import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-serv
|
|
|
44
46
|
import { fitToLength } from "./utils/fit-to-length.util.js";
|
|
45
47
|
import { inferServiceVersion } from "./utils/infer-service-version.util.js";
|
|
46
48
|
import { LogRedactor } from "./utils/log-redactor.js";
|
|
49
|
+
import { liveTraceId } from "./utils/operation-state.util.js";
|
|
47
50
|
/**
|
|
48
51
|
* All three async providers are optional on the options type, but one of them
|
|
49
52
|
* has to be there. Stating that here beats the `undefined` token Nest would
|
|
@@ -371,7 +374,12 @@ export function createObserveModule(options = {}) {
|
|
|
371
374
|
skipInstrumentation,
|
|
372
375
|
});
|
|
373
376
|
return (instance) => {
|
|
374
|
-
|
|
377
|
+
shareHooksOfHttpAdapter(instance);
|
|
378
|
+
deliverRepliesToTheirCaller(instance, asyncLocalStorage);
|
|
379
|
+
propagateTraceIdThrough(instance,
|
|
380
|
+
// Not a finished operation's, past its grace period: a message a
|
|
381
|
+
// timer it left armed sends is no part of its trace.
|
|
382
|
+
() => liveTraceId(asyncLocalStorage.getStore(), options.traceIdKey), (traceId) => openTelemetryInterop.isOn()
|
|
375
383
|
? traceparentToHandOn(asyncLocalStorage.getStore(), traceId)
|
|
376
384
|
: undefined);
|
|
377
385
|
return decorate(instance);
|
|
@@ -381,6 +389,23 @@ export function createObserveModule(options = {}) {
|
|
|
381
389
|
ObserveModule,
|
|
382
390
|
};
|
|
383
391
|
}
|
|
392
|
+
/**
|
|
393
|
+
* Shares the HTTP adapter's request and response hooks with the application
|
|
394
|
+
* from the moment Nest creates the `HttpAdapterHost`, ahead of every provider
|
|
395
|
+
* of the application's, so a hook it sets on the adapter runs beside the
|
|
396
|
+
* agent's - see `shareHttpAdapterHooks`.
|
|
397
|
+
*/
|
|
398
|
+
function shareHooksOfHttpAdapter(instance) {
|
|
399
|
+
try {
|
|
400
|
+
if (instance instanceof HttpAdapterHost) {
|
|
401
|
+
shareHttpAdapterHooks(instance);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
// `instanceof` runs a proxy's prototype trap, which may throw, and Nest
|
|
406
|
+
// 11 does not guard the instance decorator.
|
|
407
|
+
}
|
|
408
|
+
}
|
|
384
409
|
/**
|
|
385
410
|
* Makes a microservice client send the current trace id with every packet.
|
|
386
411
|
*
|
|
@@ -399,6 +424,14 @@ export function createObserveModule(options = {}) {
|
|
|
399
424
|
* With OpenTelemetry interop on, `traceparentFor` names a W3C `traceparent`
|
|
400
425
|
* to send beside it, which the receiving agent hands to an OpenTelemetry SDK
|
|
401
426
|
* in its process - see `traceparentToHandOn`.
|
|
427
|
+
*
|
|
428
|
+
* The hook is the application's to set too - Nest names a tenant and a
|
|
429
|
+
* locale as packet metadata - so the agent's part is set beside it: a
|
|
430
|
+
* dispatch hook the application sets on the client from here on runs first,
|
|
431
|
+
* and the agent's after it, adding the id beside what it wrote and never
|
|
432
|
+
* over an id it chose. Nest hands the same client over again for an alias,
|
|
433
|
+
* which replaces the agent's part rather than nesting it. A hook set in the
|
|
434
|
+
* client's own factory is already in place, and cannot be read.
|
|
402
435
|
*/
|
|
403
436
|
function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
|
|
404
437
|
const client = instance;
|
|
@@ -412,7 +445,7 @@ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
|
|
|
412
445
|
// exclusions deal with it; it is certainly not a microservice client.
|
|
413
446
|
return;
|
|
414
447
|
}
|
|
415
|
-
client
|
|
448
|
+
setAgentHook(client, "setOnDispatchHook", (packet) => {
|
|
416
449
|
const traceId = currentTraceId();
|
|
417
450
|
if (typeof traceId !== "string") {
|
|
418
451
|
return;
|
|
@@ -429,6 +462,89 @@ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
|
|
|
429
462
|
packet.metadata = { ...packet.metadata, traceparent };
|
|
430
463
|
}
|
|
431
464
|
}
|
|
465
|
+
}, composeDispatchHook);
|
|
466
|
+
}
|
|
467
|
+
/** The dispatch hook the client is given: the application's, then the agent's. */
|
|
468
|
+
function composeDispatchHook(application, agent) {
|
|
469
|
+
if (!application) {
|
|
470
|
+
return agent;
|
|
471
|
+
}
|
|
472
|
+
return function (packet) {
|
|
473
|
+
application.call(this, packet);
|
|
474
|
+
agent.call(this, packet);
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Makes what a microservice client's call emits arrive in the async context
|
|
479
|
+
* of the caller that subscribed to it.
|
|
480
|
+
*
|
|
481
|
+
* A client's replies come from events of its connection, and Node runs those
|
|
482
|
+
* in the async context the connection was opened in: a `ClientProxy`
|
|
483
|
+
* connects on first use, in the request that used it first, and grpc-js
|
|
484
|
+
* starts the calls made while its channel connects from the first one's
|
|
485
|
+
* attempt. Whatever a later caller chained onto its reply - a log line, a
|
|
486
|
+
* span, the next call's packet - read that request's store, and carried its
|
|
487
|
+
* trace id, for as long as the connection lived.
|
|
488
|
+
*
|
|
489
|
+
* Only what the client hands out is wrapped: the `Observable` of
|
|
490
|
+
* `ClientProxy#send`, and of each method a `ClientGrpc#getService` service
|
|
491
|
+
* has. Matched by shape, as the optional peer is never imported here; an
|
|
492
|
+
* instance that cannot be inspected or written to is left as it is.
|
|
493
|
+
*/
|
|
494
|
+
function deliverRepliesToTheirCaller(instance, asyncLocalStorage) {
|
|
495
|
+
const client = instance;
|
|
496
|
+
const inCaller = (replies) => isObservable(replies)
|
|
497
|
+
? inSubscriberContext(replies, asyncLocalStorage)
|
|
498
|
+
: replies;
|
|
499
|
+
try {
|
|
500
|
+
const { send, getService } = client ?? {};
|
|
501
|
+
if (typeof getService === "function" &&
|
|
502
|
+
typeof client.getClientByServiceName === "function") {
|
|
503
|
+
client.getService = function (...args) {
|
|
504
|
+
const service = getService.apply(this, args);
|
|
505
|
+
if (typeof service === "object" && service !== null) {
|
|
506
|
+
const methods = service;
|
|
507
|
+
for (const name of Object.keys(methods)) {
|
|
508
|
+
const method = methods[name];
|
|
509
|
+
if (typeof method === "function") {
|
|
510
|
+
methods[name] = function (...callArgs) {
|
|
511
|
+
return inCaller(method.apply(this, callArgs));
|
|
512
|
+
};
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return service;
|
|
517
|
+
};
|
|
518
|
+
}
|
|
519
|
+
else if (typeof send === "function" &&
|
|
520
|
+
typeof client.emit === "function" &&
|
|
521
|
+
typeof client.connect === "function" &&
|
|
522
|
+
typeof client.close === "function" &&
|
|
523
|
+
typeof client.dispatchEvent === "function") {
|
|
524
|
+
client.send = function (...args) {
|
|
525
|
+
return inCaller(send.apply(this, args));
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
catch {
|
|
530
|
+
// A provider that throws on inspection, or cannot be written to, is not
|
|
531
|
+
// a client this can help - the decorator's own exclusions deal with it.
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* `source`, with each value, error and completion delivered in the store the
|
|
536
|
+
* subscriber subscribed in. The store is re-entered rather than every async
|
|
537
|
+
* context with it: the agent's own is what its trace id is read from, and a
|
|
538
|
+
* reply whose context is already that store pays nothing more.
|
|
539
|
+
*/
|
|
540
|
+
function inSubscriberContext(source, asyncLocalStorage) {
|
|
541
|
+
return new Observable((subscriber) => {
|
|
542
|
+
const store = asyncLocalStorage.getStore();
|
|
543
|
+
return source.subscribe({
|
|
544
|
+
next: (value) => asyncLocalStorage.run(store, () => subscriber.next(value)),
|
|
545
|
+
error: (error) => asyncLocalStorage.run(store, () => subscriber.error(error)),
|
|
546
|
+
complete: () => asyncLocalStorage.run(store, () => subscriber.complete()),
|
|
547
|
+
});
|
|
432
548
|
});
|
|
433
549
|
}
|
|
434
550
|
/**
|