@nestjs/observe 0.3.25 → 0.3.27

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 (109) hide show
  1. package/README.md +55 -2
  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 +201 -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 +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  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/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -16,15 +16,29 @@ import { AsyncLocalStorage } from "async_hooks";
16
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
17
  import { Gauge, Summary } from "../custom-metrics/index.js";
18
18
  import { Counter } from "../custom-metrics/counter.js";
19
+ import { admitsFinite } from "../custom-metrics/finite-value.util.js";
19
20
  import { TraceSpanDelegate } from "../trace-span.delegate.js";
20
21
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
21
22
  import { OperationTraceRegistry } from "./operation-trace.registry.js";
23
+ import { liveTraceId } from "../utils/operation-state.util.js";
24
+ import { getThroughCopies, setThroughCopies, } from "../utils/store-copy.util.js";
22
25
  /**
23
26
  * Longest operation id the collector stores, counted by code point as it
24
27
  * counts. A longer one is cut there anyway; cut here, a name built from a
25
28
  * request body cannot grow the batch it rides in without bound.
26
29
  */
27
30
  const MAX_OPERATION_ID_LENGTH = 255;
31
+ /**
32
+ * Most metrics reported, counters, gauges and summaries together.
33
+ *
34
+ * A metric is kept for the life of the process and puts an entry of its own
35
+ * in every batch it changes in, and the collector refuses a batch whose
36
+ * `custom` section holds more than 5,000 - every request, error, job and log
37
+ * of the window with it. A name built from what a client sent made one per
38
+ * request. A fixed set of names is far below this; what varies belongs in a
39
+ * label, whose series each metric already bounds.
40
+ */
41
+ const MAX_METRICS = 1_000;
28
42
  let TracerService = TracerService_1 = class TracerService {
29
43
  operationTraceRegistry;
30
44
  als;
@@ -38,6 +52,9 @@ let TracerService = TracerService_1 = class TracerService {
38
52
  summaries = new Map();
39
53
  logger = new Logger(TracerService_1.name);
40
54
  hasReportedUnusableOperationId = false;
55
+ hasReportedMetricLimit = false;
56
+ hasReportedUncapturedError = false;
57
+ hasReportedErrorOutsideContext = false;
41
58
  constructor(operationTraceRegistry, als, observeAgentSharedBuffer, options) {
42
59
  this.operationTraceRegistry = operationTraceRegistry;
43
60
  this.als = als;
@@ -47,11 +64,20 @@ let TracerService = TracerService_1 = class TracerService {
47
64
  /**
48
65
  * Creates a new trace span with the given name and executes the provided callback within that span.
49
66
  * The callback can be synchronous or asynchronous.
67
+ * Outside any operation the agent traces, the callback still runs, with a
68
+ * detached delegate whose tags go nowhere, as in an operation that is not
69
+ * recorded.
50
70
  */
51
71
  async createSpan(name, callback) {
52
72
  const store = this.als.getStore();
53
73
  if (!store) {
54
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "createSpan" method within an async context.');
74
+ // No operation of the agent's is in flight: a transport it has no hook
75
+ // on - a GraphQL operation sent over the subscriptions socket -, a
76
+ // lifecycle hook, a timer armed at bootstrap, or an agent switched off.
77
+ // Which of these a handler runs in is often the client's choice, and
78
+ // there being nowhere to record the span is no reason for the work in
79
+ // it not to happen.
80
+ return callback(new TraceSpanDelegate("", name, {}));
55
81
  }
56
82
  const traceId = this.requireTraceId(store, "createSpan");
57
83
  const callerId = store.get(CALLER_METADATA_KEY);
@@ -59,29 +85,31 @@ let TracerService = TracerService_1 = class TracerService {
59
85
  }
60
86
  /**
61
87
  * Retrieves the active span for the current request.
62
- * This method should be called within an async context where the AsyncLocalStorage is active.
63
- * If the operation is traced but no span is active, an error is thrown. An
64
- * operation that is not being recorded (ignored or sampled out) gets a
65
- * detached delegate whose tags go nowhere, as `createSpan` does.
88
+ * Where there is none - the operation is not being recorded (ignored or
89
+ * sampled out), nothing opened a span around the caller, or the call is
90
+ * outside any operation the agent traces - the delegate is a detached one
91
+ * whose tags go nowhere, as `createSpan`'s is then.
66
92
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
67
93
  */
68
94
  async activeSpan() {
69
95
  const store = this.als.getStore();
70
96
  if (!store) {
71
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "activeSpan" method within an async context.');
97
+ // Outside any operation: see `createSpan`.
98
+ return new TraceSpanDelegate("", undefined, {});
72
99
  }
73
100
  const traceId = this.requireTraceId(store, "activeSpan");
74
101
  const callerId = store.get(CALLER_METADATA_KEY);
75
102
  const activeOngoingEvent = this.operationTraceRegistry.getActiveSpan(traceId, callerId);
76
- if (!activeOngoingEvent && !this.operationTraceRegistry.hasTrace(traceId)) {
77
- // The store carries the id for log correlation, but no trace was opened
78
- // under it: `http.ignore`, `jobs.ignore`, or the sampler said no. Which
79
- // operations get recorded is configuration; a handler tagging its span
80
- // must not start failing because someone changed it.
81
- return new TraceSpanDelegate("", undefined, {});
82
- }
83
103
  if (!activeOngoingEvent) {
84
- throw new Error(`No active span found for traceId: ${this.reportedTraceId(store, traceId)}. Ensure that a span is created before calling "activeSpan".`);
104
+ // Either the store carries the id for log correlation and no trace was
105
+ // opened under it - `http.ignore`, `jobs.ignore`, or the sampler said
106
+ // no - or one was, and nothing opened a span around the caller: the
107
+ // resolvers of a GraphQL document the agent cannot label, one that
108
+ // opens with a fragment or is sent as a persisted-query hash alone.
109
+ // Which operations get recorded is configuration, and how a document
110
+ // is spelled is the client's choice; a handler tagging its span must
111
+ // not start failing over either.
112
+ return new TraceSpanDelegate("", undefined, {});
85
113
  }
86
114
  let tags = activeOngoingEvent.tags;
87
115
  if (!tags) {
@@ -98,11 +126,23 @@ let TracerService = TracerService_1 = class TracerService {
98
126
  /**
99
127
  * Captures an error and associates it with the current trace.
100
128
  * This method should be called within an async context where the AsyncLocalStorage is active.
129
+ *
130
+ * The details of at most 20 errors are recorded per trace, counting the
131
+ * root spans that fail as well as captured errors; the span an error is
132
+ * captured on after that is marked as failed, and its tags are still
133
+ * recorded.
134
+ *
135
+ * Called outside any async context, it records nothing and says so once.
101
136
  */
102
137
  async captureError(error, tags) {
103
138
  const store = this.als.getStore();
104
139
  if (!store) {
105
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
140
+ // Reporting an error must not raise one. A handler that reports a
141
+ // failure from a `catch` and answers with a fallback failed over the
142
+ // report instead, and one that did not await it ended the process -
143
+ // wherever the context was lost, by the agent or by the application.
144
+ this.reportErrorOutsideContext();
145
+ return;
106
146
  }
107
147
  const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
108
148
  if (typeof traceId !== "string") {
@@ -116,7 +156,41 @@ let TracerService = TracerService_1 = class TracerService {
116
156
  return;
117
157
  }
118
158
  const callerId = store.get(CALLER_METADATA_KEY);
119
- this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
159
+ try {
160
+ this.operationTraceRegistry.captureError(traceId, callerId, error, tags ?? {}, this.reportedTraceId(store, traceId));
161
+ }
162
+ catch (failure) {
163
+ // For the same reason: a handler that reports a failure and answers
164
+ // with a fallback must not answer 500 over the report, nor - when it
165
+ // does not await this call - take the process down with it.
166
+ this.reportUncapturedError(failure);
167
+ }
168
+ }
169
+ /** Said once: a call site outside any context is outside it every time. */
170
+ reportErrorOutsideContext() {
171
+ if (this.hasReportedErrorOutsideContext) {
172
+ return;
173
+ }
174
+ this.hasReportedErrorOutsideContext = true;
175
+ this.logger.warn('captureError was called outside an async context, so the error is not recorded. Ensure that you are using the "captureError" method within an async context. Later calls outside one are not reported.');
176
+ }
177
+ /**
178
+ * A failure to record an error comes from the same call site on every
179
+ * request, so it is reported once rather than once per request.
180
+ */
181
+ reportUncapturedError(failure) {
182
+ if (this.hasReportedUncapturedError) {
183
+ return;
184
+ }
185
+ this.hasReportedUncapturedError = true;
186
+ let reason;
187
+ try {
188
+ reason = failure instanceof Error ? failure.message : String(failure);
189
+ }
190
+ catch {
191
+ reason = "an unprintable error";
192
+ }
193
+ this.logger.warn(`captureError could not record an error, and the operation goes on without it. Later failures are not reported: ${reason}`);
120
194
  }
121
195
  counter(name, attributes) {
122
196
  const existingRef = this.counters.get(name);
@@ -129,15 +203,20 @@ let TracerService = TracerService_1 = class TracerService {
129
203
  overridableRef.labels = attributes.labels;
130
204
  }
131
205
  // `value` holds one reading per label, so the seed goes to the default
132
- // one; a labelled metric has no unlabelled reading to seed.
206
+ // one; a labelled metric has no unlabelled reading to seed. A seed that
207
+ // is not a finite number is ignored, as the constructor ignores one.
133
208
  if (attributes?.initialValue !== undefined &&
134
209
  !existingRef.labels &&
135
- existingRef.getValue() === 0) {
210
+ existingRef.getValue() === 0 &&
211
+ admitsFinite(name, attributes.initialValue, overridableRef.nonFinite)) {
136
212
  overridableRef.value.default = attributes.initialValue;
137
213
  }
138
214
  return existingRef;
139
215
  }
140
216
  const counter = new Counter(name, attributes?.description, attributes?.initialValue, attributes?.labels);
217
+ if (!this.admitsMetric(name)) {
218
+ return counter;
219
+ }
141
220
  this.registerCounterChangeHandler(counter);
142
221
  this.counters.set(name, counter);
143
222
  return counter;
@@ -153,10 +232,12 @@ let TracerService = TracerService_1 = class TracerService {
153
232
  overridableRef.labels = attributes.labels;
154
233
  }
155
234
  // `value` holds one reading per label, so the seed goes to the default
156
- // one; a labelled metric has no unlabelled reading to seed.
235
+ // one; a labelled metric has no unlabelled reading to seed. A seed that
236
+ // is not a finite number is ignored, as the constructor ignores one.
157
237
  if (attributes?.initialValue !== undefined &&
158
238
  !existingRef.labels &&
159
- existingRef.getValue() === 0) {
239
+ existingRef.getValue() === 0 &&
240
+ admitsFinite(name, attributes.initialValue, overridableRef.nonFinite)) {
160
241
  overridableRef.value.default = attributes.initialValue;
161
242
  }
162
243
  if (attributes?.kind) {
@@ -165,6 +246,9 @@ let TracerService = TracerService_1 = class TracerService {
165
246
  return existingRef;
166
247
  }
167
248
  const gauge = new Gauge(name, attributes ?? {});
249
+ if (!this.admitsMetric(name)) {
250
+ return gauge;
251
+ }
168
252
  this.registerGaugeChangeHandler(gauge);
169
253
  this.gauges.set(name, gauge);
170
254
  return gauge;
@@ -182,6 +266,9 @@ let TracerService = TracerService_1 = class TracerService {
182
266
  return existingRef;
183
267
  }
184
268
  const summary = new Summary(name, attributes ?? {});
269
+ if (!this.admitsMetric(name)) {
270
+ return summary;
271
+ }
185
272
  this.registerSummaryChangeHandler(summary);
186
273
  this.summaries.set(name, summary);
187
274
  return summary;
@@ -189,7 +276,7 @@ let TracerService = TracerService_1 = class TracerService {
189
276
  /**
190
277
  * The id of the trace currently in flight, or `null` outside one.
191
278
  *
192
- * Unlike `getAttribute`/`activeSpan`, this does not throw when there is no
279
+ * Like the rest of this service, this does not throw when there is no
193
280
  * active store - reading the trace id to forward it downstream (an outgoing
194
281
  * HTTP header, gRPC metadata, a queued job payload) is exactly the kind of
195
282
  * call that may legitimately happen outside a traced context, and a thrown
@@ -197,9 +284,9 @@ let TracerService = TracerService_1 = class TracerService {
197
284
  * propagate an id that simply isn't there yet.
198
285
  */
199
286
  currentTraceId() {
200
- const store = this.als.getStore();
201
- const traceId = store?.get(this.options.traceIdKey);
202
- return typeof traceId === "string" ? traceId : null;
287
+ // Null once the operation is over, past a grace period: a timer the
288
+ // operation left armed is outside any trace in flight.
289
+ return liveTraceId(this.als.getStore(), this.options.traceIdKey) ?? null;
203
290
  }
204
291
  /**
205
292
  * Sets the operation id reported for the current request trace, in place of
@@ -248,35 +335,40 @@ let TracerService = TracerService_1 = class TracerService {
248
335
  /**
249
336
  * Sets an attribute on the current trace.
250
337
  * For example, you can use this to add metadata to the current request trace for later use and retrieval.
251
- * This method should be called within an async context where the AsyncLocalStorage is active.
338
+ * Does nothing outside any operation the agent traces, where there is no
339
+ * request context to keep the attribute in.
252
340
  * @param key The attribute key.
253
341
  * @param value The attribute value.
254
342
  */
255
343
  setAttribute(key, value) {
256
344
  const store = this.als.getStore();
257
345
  if (!store) {
258
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "setAttribute" method within an async context.');
346
+ return;
259
347
  }
260
- store.set(key, value);
348
+ // The store may be a span's own copy, gone once the span returns, so the
349
+ // stores it was copied from get the attribute too - see `copyStore`.
350
+ setThroughCopies(store, key, value);
261
351
  }
262
352
  /**
263
353
  * Retrieves an attribute from the current trace (request context).
264
354
  * This allows you to access metadata that was set earlier in the request lifecycle.
265
- * This method should be called within an async context where the AsyncLocalStorage is active.
266
355
  * @param key The attribute key.
267
- * @returns The attribute value or undefined if not found.
356
+ * @returns The attribute value, or undefined if not found or when called
357
+ * outside any operation the agent traces.
268
358
  */
269
359
  getAttribute(key) {
270
360
  const store = this.als.getStore();
271
- if (!store) {
272
- throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "getAttribute" method within an async context.');
273
- }
274
- return store.get(key);
361
+ // The store first, so what the application wrote into it directly wins;
362
+ // then the stores it was copied from, for an attribute set by a span
363
+ // running beside this one.
364
+ return store
365
+ ? getThroughCopies(store, key)
366
+ : undefined;
275
367
  }
276
368
  /**
277
- * Reads the trace id the request was opened under. Its absence means the call
278
- * is outside any traced operation, which is the same mistake as calling these
279
- * methods with no async context at all - and is reported the same way.
369
+ * Reads the trace id the request was opened under. A store that carries none
370
+ * is reported as a mistake. No store at all is not one - it is code running
371
+ * outside any operation - and never gets here.
280
372
  */
281
373
  requireTraceId(store, method) {
282
374
  const traceId = store.get(TRACE_REGISTRY_KEY) ?? store.get(this.options.traceIdKey);
@@ -294,6 +386,23 @@ let TracerService = TracerService_1 = class TracerService {
294
386
  const traceId = store.get(this.options.traceIdKey);
295
387
  return typeof traceId === "string" ? traceId : registryKey;
296
388
  }
389
+ /**
390
+ * Whether a metric not yet registered is, under `MAX_METRICS`. One that is
391
+ * not is still handed to the caller, so the code around it runs as it
392
+ * would, but it is neither reported nor kept: each call gets a new one.
393
+ * Reported once, as it comes from the same call site every time.
394
+ */
395
+ admitsMetric(name) {
396
+ if (this.counters.size + this.gauges.size + this.summaries.size <
397
+ MAX_METRICS) {
398
+ return true;
399
+ }
400
+ if (!this.hasReportedMetricLimit) {
401
+ this.hasReportedMetricLimit = true;
402
+ this.logger.warn(`Metric "${name.slice(0, 100)}" is not reported: at most ${MAX_METRICS} metrics are. Name metrics from a fixed set, and put a value that varies - an id, a client's input - in a label. Later metrics past this limit are not reported either, nor logged.`);
403
+ }
404
+ return false;
405
+ }
297
406
  registerCounterChangeHandler(counter) {
298
407
  counter["_onChange"] = (self) => {
299
408
  this.observeAgentSharedBuffer.upsertCustomMetric(self);
@@ -54,4 +54,6 @@ export declare function shouldCaptureRequest(snapshot: {
54
54
  * and forwarded logs - sensitive keys by name, secrets by pattern - before it
55
55
  * is handed back.
56
56
  */
57
- export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null): CapturedRequest | undefined;
57
+ export declare function captureRequest(req: unknown, options: HttpCaptureOptions | false | undefined, redactor: LogRedactor | null,
58
+ /** `http.queryParamsObfuscateRegex`, global. */
59
+ obfuscateUrl?: RegExp): CapturedRequest | undefined;
@@ -41,7 +41,9 @@ export function shouldCaptureRequest(snapshot, options) {
41
41
  * and forwarded logs - sensitive keys by name, secrets by pattern - before it
42
42
  * is handed back.
43
43
  */
44
- export function captureRequest(req, options, redactor) {
44
+ export function captureRequest(req, options, redactor,
45
+ /** `http.queryParamsObfuscateRegex`, global. */
46
+ obfuscateUrl) {
45
47
  if (options === false || typeof req !== "object" || req === null) {
46
48
  return undefined;
47
49
  }
@@ -56,20 +58,30 @@ export function captureRequest(req, options, redactor) {
56
58
  if (typeof value !== "string" || value.length === 0) {
57
59
  continue;
58
60
  }
59
- const bounded = value.slice(0, MAX_HEADER_VALUE_LENGTH);
60
- // A referer is a URL, and its query string is where the tokens live.
61
- headers[key] =
62
- key === "referer" ? redactUrlQuery(bounded, redactor) : bounded;
61
+ // Any header can carry a URL - `referer`, `x-forwarded-uri`,
62
+ // `x-original-url` - and its query string is where the tokens live.
63
+ // Masking is by key, so a value that is no URL comes back untouched.
64
+ headers[key] = redactUrlQuery(value, redactor, obfuscateUrl);
63
65
  }
64
66
  if (Object.keys(headers).length > 0) {
65
- captured.headers = (redactor ? redactor.redactAttributes(headers) : headers);
67
+ // Redacted whole and cut afterwards, as the body is: the rules that
68
+ // recognise a secret by its end - a JWT's last dot, a closing quote, a
69
+ // card's last digits - stop matching once the cut goes through it, and
70
+ // the head of the secret would be sent.
71
+ const redacted = redactor ? redactor.redactAttributes(headers) : headers;
72
+ captured.headers = Object.fromEntries(Object.entries(redacted ?? {}).map(([key, value]) => [
73
+ key,
74
+ typeof value === "string"
75
+ ? value.slice(0, MAX_HEADER_VALUE_LENGTH)
76
+ : value,
77
+ ]));
66
78
  }
67
79
  }
68
80
  if (options?.body && request.body !== undefined && request.body !== null) {
69
81
  const maxBytes = Math.min(typeof options.body === "object" && options.body.maxBytes
70
82
  ? options.body.maxBytes
71
83
  : DEFAULT_CAPTURED_BODY_BYTES, MAX_CAPTURED_BODY_BYTES);
72
- const serialized = serializeBody(request.body, redactor);
84
+ const serialized = serializeBody(request.body, redactor, maxBytes);
73
85
  if (serialized !== undefined) {
74
86
  if (Buffer.byteLength(serialized) > maxBytes) {
75
87
  const bytes = Buffer.from(serialized);
@@ -94,19 +106,28 @@ export function captureRequest(req, options, redactor) {
94
106
  * Redaction runs on the parsed structure, before serialization and before the
95
107
  * cut - key-based rules need the keys, and truncating first could ship the
96
108
  * surviving half of a secret.
109
+ *
110
+ * A body that arrived as a string but is JSON (sent as `text/plain`, say) is
111
+ * parsed first, so it is held to the same key rules as one the framework
112
+ * parsed.
97
113
  */
98
- function serializeBody(body, redactor) {
114
+ function serializeBody(body, redactor, maxBytes) {
99
115
  if (typeof body === "string") {
100
- return redactor ? redactor.redactMessage(body) : body;
116
+ const parsed = parseJsonDocument(body);
117
+ if (parsed === undefined) {
118
+ return redactor ? redactor.redactMessage(body) : body;
119
+ }
120
+ body = parsed;
101
121
  }
102
- if (Buffer.isBuffer(body) || typeof body !== "object") {
122
+ if (!isParsed(body)) {
103
123
  // A raw buffer is a file or an unparsed stream - nothing readable to show.
104
124
  return undefined;
105
125
  }
106
126
  try {
127
+ const bounded = boundToCap(body, { nodes: maxBytes }, new Set());
107
128
  const redacted = redactor
108
- ? redactor.redactAttributes(body)
109
- : body;
129
+ ? redactor.redactAttributes(bounded)
130
+ : bounded;
110
131
  return JSON.stringify(redacted);
111
132
  }
112
133
  catch {
@@ -114,3 +135,98 @@ function serializeBody(body, redactor) {
114
135
  return undefined;
115
136
  }
116
137
  }
138
+ function parseJsonDocument(body) {
139
+ const first = body.trimStart()[0];
140
+ if (first !== "{" && first !== "[") {
141
+ return undefined;
142
+ }
143
+ try {
144
+ const parsed = JSON.parse(body);
145
+ return typeof parsed === "object" && parsed !== null ? parsed : undefined;
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ }
151
+ /** Deeper than the redactor descends, so nothing it would read is cut off. */
152
+ const MAX_BOUNDED_DEPTH = 10;
153
+ /**
154
+ * Whether a value is what a body parser makes - an array, or an object that
155
+ * is only its fields: JSON, urlencoded and multer bodies all are. Some with
156
+ * no prototype at all, and Fastify's form parser (`fast-querystring`) with
157
+ * one that is itself empty and has none, which is as bare.
158
+ *
159
+ * Anything else is not a parsed body but something left where one would be:
160
+ * Fastify's raw request stream, a Buffer, a typed array, an instance of a
161
+ * class. Walked as fields, a stream's are its internals - its buffered
162
+ * chunks, the request's headers, cookies and API keys included, written out
163
+ * as numbers that no rule reads as a secret - and a Buffer's `toJSON` turns
164
+ * it into the same. So none of these is recorded, at any depth.
165
+ */
166
+ function isParsed(value) {
167
+ if (Array.isArray(value)) {
168
+ return true;
169
+ }
170
+ if (typeof value !== "object" || value === null) {
171
+ return false;
172
+ }
173
+ let prototype = Object.getPrototypeOf(value);
174
+ while (prototype !== null && prototype !== Object.prototype) {
175
+ // A class's prototype has a `constructor` at least.
176
+ if (Reflect.ownKeys(prototype).length > 0) {
177
+ return false;
178
+ }
179
+ prototype = Object.getPrototypeOf(prototype);
180
+ }
181
+ return true;
182
+ }
183
+ /**
184
+ * A copy of the body holding only the nodes that can still show up in the
185
+ * first `maxBytes` of its JSON, in the order JSON writes them. Every value
186
+ * and key takes at least a byte, so past `maxBytes` of them the rest is cut
187
+ * anyway - and the rest can be enormous: multer turns `f[1000000]=x` into an
188
+ * array of a million holes, each written out as `null`, from one short field.
189
+ */
190
+ function boundToCap(value, budget,
191
+ /** The objects above this one, to refuse a cycle as JSON.stringify would. */
192
+ ancestors) {
193
+ budget.nodes -= 1;
194
+ if (value === null || typeof value !== "object") {
195
+ return value;
196
+ }
197
+ if (!isParsed(value)) {
198
+ // Left out, as JSON.stringify leaves out a function: no field, and
199
+ // `null` in an array.
200
+ return undefined;
201
+ }
202
+ if (ancestors.has(value)) {
203
+ throw new TypeError("Converting circular structure to JSON");
204
+ }
205
+ if (ancestors.size >= MAX_BOUNDED_DEPTH) {
206
+ return "[REDACTED]";
207
+ }
208
+ ancestors.add(value);
209
+ try {
210
+ if (Array.isArray(value)) {
211
+ const items = [];
212
+ for (let i = 0; i < value.length && budget.nodes > 0; i++) {
213
+ items.push(boundToCap(value[i], budget, ancestors));
214
+ }
215
+ return items;
216
+ }
217
+ const entries = {};
218
+ for (const key in value) {
219
+ if (budget.nodes <= 0) {
220
+ break;
221
+ }
222
+ if (Object.prototype.hasOwnProperty.call(value, key)) {
223
+ budget.nodes -= 1;
224
+ entries[key] = boundToCap(value[key], budget, ancestors);
225
+ }
226
+ }
227
+ return entries;
228
+ }
229
+ finally {
230
+ ancestors.delete(value);
231
+ }
232
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What a microservice context's accessor - `getMetadata()`, `getPattern()` -
3
+ * answers, or `undefined` for a context without one.
4
+ *
5
+ * The accessor is found by name, since a custom transporter delivers a
6
+ * context class of its own, and there it may be anything - asynchronous,
7
+ * too. What it promises cannot be read here: the callers answer before it
8
+ * settles, so it counts as no answer. But the promise is one this call made
9
+ * and nothing else holds, so its rejection is handled here: unhandled, it
10
+ * ended the process. The handler's own call makes a promise of its own,
11
+ * which stays the application's to await.
12
+ *
13
+ * Kept out of `default-trace-id-generator.util.ts`, one of its callers:
14
+ * everything that module exports is re-exported from the package root.
15
+ */
16
+ export declare function readContextAccessor(context: unknown, name: "getMetadata" | "getPattern"): unknown;
@@ -0,0 +1,28 @@
1
+ import { types } from "util";
2
+ /**
3
+ * What a microservice context's accessor - `getMetadata()`, `getPattern()` -
4
+ * answers, or `undefined` for a context without one.
5
+ *
6
+ * The accessor is found by name, since a custom transporter delivers a
7
+ * context class of its own, and there it may be anything - asynchronous,
8
+ * too. What it promises cannot be read here: the callers answer before it
9
+ * settles, so it counts as no answer. But the promise is one this call made
10
+ * and nothing else holds, so its rejection is handled here: unhandled, it
11
+ * ended the process. The handler's own call makes a promise of its own,
12
+ * which stays the application's to await.
13
+ *
14
+ * Kept out of `default-trace-id-generator.util.ts`, one of its callers:
15
+ * everything that module exports is re-exported from the package root.
16
+ */
17
+ export function readContextAccessor(context, name) {
18
+ const accessor = context?.[name];
19
+ if (typeof accessor !== "function") {
20
+ return undefined;
21
+ }
22
+ const value = accessor.call(context);
23
+ if (types.isPromise(value)) {
24
+ value.then(undefined, () => undefined);
25
+ return undefined;
26
+ }
27
+ return value;
28
+ }
@@ -1,3 +1,4 @@
1
+ import { readContextAccessor } from "./context-accessor.util.js";
1
2
  import { inboundTraceId, w3cTraceIdOf } from "./trace-context.util.js";
2
3
  import { uuidv7 } from "./uuid-v7.util.js";
3
4
  /**
@@ -26,13 +27,10 @@ export function defaultTraceIdGenerator(req) {
26
27
  // which gave their contexts - and the context gRPC hands the processing
27
28
  // hooks - the same `getMetadata()`. Held to the same shape as the header - a
28
29
  // packet is no more trustworthy than a request.
29
- const getMetadata = req?.getMetadata;
30
- if (typeof getMetadata === "function") {
31
- const metadata = getMetadata.call(req);
32
- const requestId = metadata?.["x-request-id"];
33
- if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
34
- return requestId;
35
- }
30
+ const metadata = readContextAccessor(req, "getMetadata");
31
+ const requestId = metadata?.["x-request-id"];
32
+ if (typeof requestId === "string" && REQUEST_ID_PATTERN.test(requestId)) {
33
+ return requestId;
36
34
  }
37
35
  // Minted here, so it can carry its time - see uuidv7.
38
36
  return uuidv7();
@@ -0,0 +1,13 @@
1
+ /**
2
+ * An error's stack as it reads now, for the agent's own use: its first line
3
+ * is still the application's to change.
4
+ */
5
+ export declare function readStack(err: Error): unknown;
6
+ /**
7
+ * Rewrites the frames of an error's stack, likewise.
8
+ *
9
+ * `rewrite` is given the frames alone where the agent keeps them, and the
10
+ * whole text where the stack is a plain string - so it must only match what
11
+ * follows a line break.
12
+ */
13
+ export declare function rewriteStackFrames(err: Error, rewrite: (stack: string) => string): void;