@nestjs/observe 0.3.24 → 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.
Files changed (97) hide show
  1. package/README.md +26 -1
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +43 -21
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +244 -97
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  34. package/dist/otlp/otlp-span.mapper.js +16 -8
  35. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  36. package/dist/otlp/otlp-trace-exporter.service.js +71 -6
  37. package/dist/outgoing/http.integration.d.ts +8 -4
  38. package/dist/outgoing/http.integration.js +13 -6
  39. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  40. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  41. package/dist/outgoing/llm/llm-providers.js +72 -22
  42. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  43. package/dist/outgoing/llm/llm-usage.js +72 -25
  44. package/dist/outgoing/mssql.integration.js +16 -2
  45. package/dist/outgoing/mysql2.integration.js +17 -1
  46. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  47. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  48. package/dist/outgoing/pg.integration.d.ts +3 -2
  49. package/dist/outgoing/pg.integration.js +39 -11
  50. package/dist/outgoing/sql-statement.util.js +106 -14
  51. package/dist/outgoing/undici.integration.d.ts +13 -0
  52. package/dist/outgoing/undici.integration.js +68 -0
  53. package/dist/protocols/bull-observe-agent.service.js +2 -12
  54. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  55. package/dist/protocols/deferred-trace-completion.js +36 -6
  56. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  57. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  58. package/dist/protocols/graphql-operation-parser.js +72 -18
  59. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  60. package/dist/protocols/http-observe-agent.service.js +177 -59
  61. package/dist/protocols/job-trace-runner.d.ts +35 -3
  62. package/dist/protocols/job-trace-runner.js +136 -31
  63. package/dist/protocols/queue-observe-agent.service.js +44 -20
  64. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  65. package/dist/protocols/rpc-observe-agent.service.js +225 -49
  66. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  67. package/dist/protocols/ws-observe-agent.service.js +226 -20
  68. package/dist/services/index.d.ts +1 -1
  69. package/dist/services/index.js +1 -1
  70. package/dist/services/logger-patcher.service.js +3 -4
  71. package/dist/services/operation-trace.registry.d.ts +45 -1
  72. package/dist/services/operation-trace.registry.js +418 -35
  73. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  74. package/dist/services/stdout-forwarder.service.js +288 -51
  75. package/dist/services/tracer.service.d.ts +23 -0
  76. package/dist/services/tracer.service.js +99 -7
  77. package/dist/utils/capture-request.util.d.ts +3 -1
  78. package/dist/utils/capture-request.util.js +100 -12
  79. package/dist/utils/fit-to-length.util.js +33 -10
  80. package/dist/utils/log-line.parser.d.ts +14 -0
  81. package/dist/utils/log-line.parser.js +7 -3
  82. package/dist/utils/log-redactor.d.ts +14 -0
  83. package/dist/utils/log-redactor.js +512 -61
  84. package/dist/utils/operation-state.util.d.ts +39 -0
  85. package/dist/utils/operation-state.util.js +50 -0
  86. package/dist/utils/redact-url-query.d.ts +26 -4
  87. package/dist/utils/redact-url-query.js +184 -32
  88. package/dist/utils/sensitive-keys.d.ts +4 -1
  89. package/dist/utils/sensitive-keys.js +48 -10
  90. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  91. package/dist/utils/shared-hook-slot.util.js +103 -0
  92. package/dist/utils/source-context.util.d.ts +8 -0
  93. package/dist/utils/source-context.util.js +88 -19
  94. package/dist/utils/source-map-resolver.util.js +8 -2
  95. package/dist/utils/trace-context.util.d.ts +20 -0
  96. package/dist/utils/trace-context.util.js +50 -6
  97. package/package.json +4 -1
@@ -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,24 +50,115 @@ 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
- switch (candidate.constructor?.name) {
57
- case "MongoClient":
58
- return (typeof candidate.startSession === "function" &&
59
- typeof candidate.db === "function");
60
- case "Db":
61
- return (typeof candidate.collection === "function" &&
62
- typeof candidate.databaseName === "string");
63
- default:
64
- return false;
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;
76
+ }
77
+ /**
78
+ * Library classes traced only in part, each with a method only it has, which
79
+ * tells it from an application's own class of the same name - `ValidationPipe`
80
+ * is what Nest's documentation calls the pipe it has readers write themselves,
81
+ * and plenty of applications have a `ConfigService` of their own.
82
+ *
83
+ * - Nest's validating pipes keep only `validate`. `ValidationPipe` runs once
84
+ * per handler argument, and for each one `transform`, `toValidate` and
85
+ * `transformPrimitive` were spans, usually of a few microseconds and each
86
+ * one billed, on runs that mostly validate nothing: 82% of runs across the
87
+ * hosted platform on 2026-11-06, which made it the busiest class after
88
+ * `pg`, and 404,552 of 404,652 on one REST app.
89
+ * - `@nestjs/config`'s `ConfigService` keeps what an application calls. Each
90
+ * `get` made four or five more spans of its private helpers - 2.7M of its
91
+ * 4.6M a day, in 220 projects.
92
+ *
93
+ * Folding cannot reach any of them (`collapseRepeatedSpans`), because each
94
+ * repeats only a few times under its parent.
95
+ *
96
+ * By name, because `StandardSchemaValidationPipe` is not in every supported
97
+ * `@nestjs/common` and an application may carry a second copy of a package.
98
+ * A class that stops matching is simply traced like any other.
99
+ */
100
+ const PARTLY_TRACED_CLASSES = new Map([
101
+ [
102
+ "ValidationPipe",
103
+ { marker: "flattenValidationErrors", traced: new Set(["validate"]) },
104
+ ],
105
+ [
106
+ "StandardSchemaValidationPipe",
107
+ { marker: "formatIssueMessages", traced: new Set(["validate"]) },
108
+ ],
109
+ [
110
+ "ParseFilePipe",
111
+ { marker: "validateFilesOrFile", traced: new Set(["validate"]) },
112
+ ],
113
+ [
114
+ "ConfigService",
115
+ {
116
+ marker: "getFromValidatedEnv",
117
+ traced: new Set(["get", "getOrThrow", "set", "setEnvFilePaths"]),
118
+ },
119
+ ],
120
+ ]);
121
+ /** The methods a prototype's class keeps traced, if it is one of those. */
122
+ function partlyTracedMethodsOf(proto) {
123
+ const candidate = proto;
124
+ const entry = PARTLY_TRACED_CLASSES.get(candidate.constructor?.name ?? "");
125
+ return entry !== undefined && typeof candidate[entry.marker] === "function"
126
+ ? entry.traced
127
+ : null;
128
+ }
129
+ /** Whether an instance is one of those classes, or extends one. */
130
+ function extendsPartlyTracedClass(instance) {
131
+ for (let proto = Object.getPrototypeOf(instance); proto !== null && proto !== Object.prototype; proto = Object.getPrototypeOf(proto)) {
132
+ if (partlyTracedMethodsOf(proto) !== null) {
133
+ return true;
134
+ }
135
+ }
136
+ return false;
137
+ }
138
+ /**
139
+ * Whether a method is one of those classes' internals, and so makes no span.
140
+ *
141
+ * Asked of the class that holds the method, so what an application adds to or
142
+ * overrides in a subclass is still traced. An instance's own function - the
143
+ * `exceptionFactory` a constructor assigns - goes by the instance's class.
144
+ */
145
+ function isLibraryInternal(target, methodName) {
146
+ let holder = target;
147
+ while (holder !== null && !Object.hasOwn(holder, methodName)) {
148
+ holder = Object.getPrototypeOf(holder);
149
+ }
150
+ if (holder === null) {
151
+ return false;
152
+ }
153
+ const traced = partlyTracedMethodsOf(holder === target ? Object.getPrototypeOf(target) : holder);
154
+ return (traced !== null &&
155
+ !(typeof methodName === "string" && traced.has(methodName)));
66
156
  }
67
157
  export function createInstanceDecorator(als, operationTraceRegistry, options) {
68
158
  /**
69
- * 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.
70
162
  *
71
163
  * Every function this creates is named `<className>.<methodName>`, so the
72
164
  * frames instrumentation contributes to a stack trace read like the call the
@@ -80,6 +172,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
80
172
  // "Object.<name>".
81
173
  const call = spec.call;
82
174
  const callUntraced = spec.callUntraced;
175
+ const isAsync = spec.isAsync;
83
176
  const endStep = (requestId, stepId) => operationTraceRegistry.internalEndTraceStep(requestId, spanId, className, methodName, stepId);
84
177
  const recordError = (requestId, stepId, err) => {
85
178
  // Before the registry records the step: `internalEndTraceStep` copies
@@ -108,18 +201,24 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
108
201
  ignoreFailure(() => recordError(requestId, stepId, err));
109
202
  throw err;
110
203
  };
111
- // A plain native promise is swapped for a chained one, just as
112
- // the caller's own `.then` would: a rejection the caller drops
113
- // still raises `unhandledRejection`, as without the span.
114
- if (isPlainPromise(result)) {
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) {
115
209
  return result.then(settled, failed);
116
210
  }
117
- // A promise carrying more than its value (`json()` on a `got`
118
- // request, `kill()` on an `execa` child, a subclass and its own
119
- // members) is handed back as-is, or the caller loses all that.
120
- // It is watched on a side branch instead, the way
121
- // `OutgoingSpanRecorder.endWhenSettled` watches outgoing calls.
122
- // Watching marks it handled, so a rejection the caller drops no
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
123
222
  // longer raises `unhandledRejection`; the span still records it.
124
223
  result.then(settled, (err) => ignoreFailure(() => recordError(requestId, stepId, err)));
125
224
  return result;
@@ -132,44 +231,47 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
132
231
  // Re-throw the error to maintain original behavior
133
232
  throw err;
134
233
  }
135
- finally {
136
- spec.setActive(false);
137
- }
138
234
  });
139
- // A function expression, not an arrow: the wrapper has to forward whatever
140
- // `this` the caller invoked it with.
141
- return named(frameName, function (...args) {
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) => {
142
239
  // Already tracing this callable, invoke it as-is
143
240
  if (spec.isActive()) {
144
- return callUntraced(this, args);
241
+ return callUntraced(thisArg, args);
145
242
  }
146
243
  const store = als.getStore();
147
244
  const requestId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(options.traceIdKey);
148
245
  if (!requestId) {
149
- return callUntraced(this, args);
246
+ return callUntraced(thisArg, args);
150
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.
151
252
  spec.setActive(true);
152
- const callerId = store?.get(CALLER_METADATA_KEY);
153
- const newStepId = operationTraceRegistry.internalStartTraceStep(requestId, className, methodName, callerId);
154
- // No step means the registry holds no snapshot for this trace id: the
155
- // request was dropped by `http.ignore` or sampled out, but its store
156
- // still carries the id - log correlation needs it there. Nothing was
157
- // opened, so nothing must be closed; without this bail-out every
158
- // provider call on an ignored route logged a registry error.
159
- if (newStepId === undefined) {
160
- try {
161
- return callUntraced(this, args);
162
- }
163
- finally {
164
- 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);
165
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);
166
274
  }
167
- // Everything the caller's context holds, with this span as the caller
168
- // of whatever it calls. A copy, so the caller's context still names the
169
- // caller once this call returns.
170
- const spanStore = new Map(store);
171
- spanStore.set(CALLER_METADATA_KEY, newStepId);
172
- return als.run(spanStore, callTraced, this, args, requestId, newStepId);
173
275
  });
174
276
  };
175
277
  const instrumentFunction = (fn) => {
@@ -191,6 +293,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
191
293
  spanId: `${className}#${methodName}`,
192
294
  isActive: () => active,
193
295
  setActive: (value) => (active = value),
296
+ isAsync: types.isAsyncFunction(fn),
194
297
  call: invoke,
195
298
  callUntraced: invoke,
196
299
  });
@@ -199,7 +302,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
199
302
  // static properties, `instanceof` and reflect-metadata lookups. Only
200
303
  // `apply` is trapped, so `new fn()` still constructs the original.
201
304
  return new Proxy(fn, {
202
- apply: named(frameName, (_target, thisArg, args) => Reflect.apply(tracedFn, thisArg, args)),
305
+ apply: named(frameName, (_target, thisArg, args) => tracedFn(thisArg, args)),
203
306
  });
204
307
  };
205
308
  const instrumentObject = (instance) => {
@@ -220,6 +323,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
220
323
  let hasPrivateMembers;
221
324
  let slotBacked;
222
325
  let bareBuiltIn;
326
+ let partlyTraced;
223
327
  try {
224
328
  // Inspected here, inside the guard, for the same reason as the checks
225
329
  // below: reading a provider's constructor can run a trap that throws.
@@ -229,6 +333,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
229
333
  hasPrivateMembers = usesNativePrivateMembers(instance);
230
334
  slotBacked = isSlotBackedBuiltIn(instance);
231
335
  bareBuiltIn = slotBacked && isNativeFunction(instance.constructor);
336
+ partlyTraced = extendsPartlyTracedClass(instance);
232
337
  }
233
338
  catch {
234
339
  // Reading the prototype ran a trap that threw (nestjs-cls proxy
@@ -253,12 +358,21 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
253
358
  // constructors and callable objects.
254
359
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
255
360
  const passedThrough = new WeakSet();
256
- return new Proxy(instance, {
361
+ const proxy = new Proxy(instance, {
257
362
  // Runs for every property read through the proxy - each `this.field`
258
363
  // and `this.dependency.method` inside a traced call - so the common
259
- // answers come first: a value that is no method, then a method already
260
- // wrapped.
364
+ // answers come first: a read by something other than the proxy, a value
365
+ // that is no method, then a method already wrapped.
261
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
+ }
262
376
  const attributeValue = Reflect.get(target, prop);
263
377
  if (typeof attributeValue !== "function" || prop === "constructor") {
264
378
  return attributeValue;
@@ -283,7 +397,10 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
283
397
  // mid-trace). This subsumes the Axios special case that used to sit
284
398
  // here: an Axios instance is a bound `request` carrying its API as
285
399
  // own properties.
286
- !isCallableObject(attributeValue);
400
+ !isCallableObject(attributeValue) &&
401
+ // Handed out as it is, so it still runs against the proxy: the
402
+ // `this.validate()` inside `transform` comes back through here.
403
+ !(partlyTraced && isLibraryInternal(target, prop));
287
404
  if (!shouldProxy) {
288
405
  // Remembered, as a wrapped method is: telling them apart reads the
289
406
  // function's source and its prototype's keys, which a Mongoose
@@ -300,18 +417,19 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
300
417
  const originalMethod = requiresRawReceiver
301
418
  ? attributeValue
302
419
  : Reflect.get(target, prop, receiver);
303
- const tracedReceiver = requiresRawReceiver ? target : receiver;
420
+ const tracedReceiver = requiresRawReceiver ? target : proxy;
304
421
  // The wrapper is made once per method of this instance and cached
305
422
  // below, so a flag of its own guards exactly that callable - checked
306
423
  // and flipped on every traced call, where a lookup keyed by instance
307
424
  // and name used to be.
308
425
  let active = false;
309
- const proxyFn = createTracedWrapper({
426
+ const tracedFn = createTracedWrapper({
310
427
  className,
311
428
  methodName,
312
429
  spanId: generateSpanId(target, methodName),
313
430
  isActive: () => active,
314
431
  setActive: (value) => (active = value),
432
+ isAsync: types.isAsyncFunction(originalMethod),
315
433
  // Traced calls run against the proxy so that a method calling into
316
434
  // itself (`this.other()`) is instrumented as a nested step - except
317
435
  // for private-member classes, whose brand checks only the raw
@@ -319,32 +437,38 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
319
437
  call: named(frameName, (_thisArg, args) => originalMethod.apply(tracedReceiver, args)),
320
438
  callUntraced: named(frameName, (_thisArg, args) => originalMethod.apply(target, args)),
321
439
  });
322
- // V8 hard-codes the type name of a stack frame to "Proxy" whenever the
323
- // frame's receiver is a proxy, and no trap can override that. The
324
- // wrapper never reads `this`, so handing it out with the receiver
325
- // detached costs nothing and makes V8 treat its frame as top-level -
326
- // printing the "<Class>.<method>" name above on its own.
327
- const boundFn = proxyFn.bind(undefined);
328
- // `bind` renames the function to "bound <name>" and drops metadata;
329
- // restore both so the wrapper stays indistinguishable from the original
330
- // to anything reflecting over it (DI, decorators, arity checks).
331
- Object.defineProperty(boundFn, "name", {
332
- value: originalMethod.name,
333
- configurable: true,
334
- });
335
- Object.defineProperty(boundFn, "length", {
336
- value: originalMethod.length,
337
- configurable: true,
338
- });
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 });
339
462
  const metadataKeys = Reflect.getMetadataKeys(originalMethod);
340
463
  for (const key of metadataKeys) {
341
464
  const metadata = Reflect.getMetadata(key, originalMethod);
342
- Reflect.defineMetadata(key, metadata, boundFn);
465
+ Reflect.defineMetadata(key, metadata, wrapped);
343
466
  }
344
- methodRefsCache.set(attributeValue, boundFn);
345
- return boundFn;
467
+ methodRefsCache.set(attributeValue, wrapped);
468
+ return wrapped;
346
469
  },
347
470
  });
471
+ return proxy;
348
472
  };
349
473
  return (instance) => {
350
474
  if (typeof instance === "function") {
@@ -356,19 +480,6 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
356
480
  return instance;
357
481
  };
358
482
  }
359
- /**
360
- * Whether a promise is a bare native one: no subclass, no members of its own.
361
- * Such a promise carries nothing but its value, so a chained promise can stand
362
- * in for it without the caller noticing.
363
- *
364
- * Symbol keys do not count: before Node 24, `AsyncLocalStorage` stamps its
365
- * own (`async_id_symbol`, `kResourceStore`, ...) on every promise created in
366
- * a context, which every traced call runs in.
367
- */
368
- function isPlainPromise(promise) {
369
- return (Object.getPrototypeOf(promise) === Promise.prototype &&
370
- Object.getOwnPropertyNames(promise).length === 0);
371
- }
372
483
  /** Runs span bookkeeping whose failure must not reach the caller. */
373
484
  function ignoreFailure(fn) {
374
485
  try {
@@ -400,22 +511,58 @@ function named(name, fn) {
400
511
  * Only the topmost match is rewritten. Every wrapper on the way out relabels
401
512
  * its own frame, and inner calls unwind before outer ones, so two classes that
402
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`.
403
517
  */
404
518
  function relabelProxyFrame(err, className, methodName) {
405
- if (!(err instanceof Error) || typeof err.stack !== "string") {
406
- return;
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}`);
407
540
  }
408
- // `async` prefixes the type name on frames resumed from an await.
409
- const frame = new RegExp(`(\\n\\s*at (?:async )?)Proxy\\.${escapeRegExp(methodName)}\\b`);
410
- if (!frame.test(err.stack)) {
411
- return;
541
+ catch {
542
+ // Left as it is.
412
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) {
413
559
  try {
414
- err.stack = err.stack.replace(frame, `$1${className}.${methodName}`);
560
+ return ((typeof err.name === "string" ? err.name.length : 0) +
561
+ (typeof err.message === "string" ? err.message.length : 0));
415
562
  }
416
563
  catch {
417
- // Some errors ship a read-only `stack`; the label is cosmetic, so leaving
418
- // it as-is beats masking the original failure.
564
+ // A getter that throws; leave such an error alone.
565
+ return Infinity;
419
566
  }
420
567
  }
421
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;