@nestjs/observe 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +38 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/detached-observe-worker.assembly.d.ts +18 -0
  4. package/dist/agent/detached-observe-worker.assembly.js +29 -0
  5. package/dist/agent/detached-observe-worker.d.ts +21 -0
  6. package/dist/agent/detached-observe-worker.js +74 -24
  7. package/dist/agent/observe-agent.shared-buffer.js +7 -5
  8. package/dist/agent/observe-agent.worker.js +17 -21
  9. package/dist/agent/telemetry-wire-contract.js +1 -0
  10. package/dist/encoders/remap-keys.util.js +6 -0
  11. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  12. package/dist/encoders/request-snapshot.encoder.js +1 -0
  13. package/dist/instrument/create-instance-decorator.instrument.js +2 -2
  14. package/dist/interfaces/observe-options.interface.d.ts +97 -9
  15. package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
  16. package/dist/observe.constants.d.ts +16 -0
  17. package/dist/observe.constants.js +16 -0
  18. package/dist/observe.module.js +55 -6
  19. package/dist/outgoing/http.integration.d.ts +36 -0
  20. package/dist/outgoing/http.integration.js +127 -0
  21. package/dist/outgoing/mongodb.integration.d.ts +38 -0
  22. package/dist/outgoing/mongodb.integration.js +141 -0
  23. package/dist/outgoing/mysql2.integration.d.ts +20 -0
  24. package/dist/outgoing/mysql2.integration.js +89 -0
  25. package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
  26. package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
  27. package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
  28. package/dist/outgoing/outgoing-span.recorder.js +94 -0
  29. package/dist/outgoing/patch-method.util.d.ts +15 -0
  30. package/dist/outgoing/patch-method.util.js +29 -0
  31. package/dist/outgoing/pg.integration.d.ts +22 -0
  32. package/dist/outgoing/pg.integration.js +66 -0
  33. package/dist/outgoing/sql-statement.util.d.ts +21 -0
  34. package/dist/outgoing/sql-statement.util.js +48 -0
  35. package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
  36. package/dist/protocols/bull-observe-agent.service.js +130 -0
  37. package/dist/protocols/graphql-observe-agent.service.js +5 -2
  38. package/dist/protocols/graphql-operation-parser.d.ts +6 -4
  39. package/dist/protocols/graphql-operation-parser.js +61 -6
  40. package/dist/protocols/http-observe-agent.service.js +26 -7
  41. package/dist/protocols/job-trace-runner.d.ts +77 -0
  42. package/dist/protocols/job-trace-runner.js +196 -0
  43. package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
  44. package/dist/protocols/queue-observe-agent.service.js +36 -95
  45. package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
  46. package/dist/protocols/ws-observe-agent.service.js +180 -0
  47. package/dist/services/operation-trace.registry.d.ts +35 -1
  48. package/dist/services/operation-trace.registry.js +68 -5
  49. package/dist/services/trace-sampler.service.d.ts +4 -0
  50. package/dist/services/tracer.service.js +5 -3
  51. package/dist/utils/capture-request.util.d.ts +57 -0
  52. package/dist/utils/capture-request.util.js +116 -0
  53. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  54. package/dist/utils/default-trace-id-generator.util.js +12 -1
  55. package/dist/utils/log-redactor.d.ts +20 -1
  56. package/dist/utils/log-redactor.js +54 -38
  57. package/dist/utils/optional-peer.util.d.ts +13 -0
  58. package/dist/utils/optional-peer.util.js +30 -0
  59. package/dist/utils/redact-url-query.d.ts +10 -1
  60. package/dist/utils/redact-url-query.js +16 -37
  61. package/dist/utils/sensitive-keys.d.ts +15 -0
  62. package/dist/utils/sensitive-keys.js +76 -0
  63. package/dist/utils/source-context.util.d.ts +6 -0
  64. package/dist/utils/source-context.util.js +121 -15
  65. package/dist/utils/source-map-resolver.util.js +12 -0
  66. package/package.json +35 -2
@@ -0,0 +1,18 @@
1
+ import type { DetachedWorkerData } from "./detached-observe-worker.js";
2
+ /**
3
+ * How the telemetry worker is put together, in one place.
4
+ *
5
+ * The worker runs as eval'd source with no module scope, so the code it needs
6
+ * travels as stringified functions and the data it needs as `workerData`.
7
+ * `ObserveAgentWorker.initializeWorker` and the worker's own tests both build
8
+ * it from here on purpose: a test that assembled its own copy would keep
9
+ * passing after the real assembly forgot something, which is exactly the
10
+ * failure it exists to catch.
11
+ */
12
+ export declare function detachedWorkerSource(): string;
13
+ export declare function detachedWorkerData(input: {
14
+ sharedBuffer: SharedArrayBuffer;
15
+ endpoint: string;
16
+ appKey?: string;
17
+ appSecret?: string;
18
+ }): DetachedWorkerData;
@@ -0,0 +1,29 @@
1
+ import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
2
+ import { detachedObserveWorker } from "./detached-observe-worker.js";
3
+ import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
4
+ import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
5
+ /**
6
+ * How the telemetry worker is put together, in one place.
7
+ *
8
+ * The worker runs as eval'd source with no module scope, so the code it needs
9
+ * travels as stringified functions and the data it needs as `workerData`.
10
+ * `ObserveAgentWorker.initializeWorker` and the worker's own tests both build
11
+ * it from here on purpose: a test that assembled its own copy would keep
12
+ * passing after the real assembly forgot something, which is exactly the
13
+ * failure it exists to catch.
14
+ */
15
+ export function detachedWorkerSource() {
16
+ return `(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()}, ${describeIngestRefusal.toString()})`;
17
+ }
18
+ export function detachedWorkerData(input) {
19
+ // Spelled out against the interface rather than spread, so a key the worker
20
+ // starts reading is a compile error here until it is supplied.
21
+ const config = {
22
+ endpoint: input.endpoint,
23
+ appKey: input.appKey,
24
+ appSecret: input.appSecret,
25
+ wireShapes: SECTION_SHAPES,
26
+ degradedPrefix: DEGRADED_MESSAGE_PREFIX,
27
+ };
28
+ return { sharedBuffer: input.sharedBuffer, config };
29
+ }
@@ -1,3 +1,24 @@
1
1
  import type { createTelemetrySanitizer } from "./telemetry-wire-contract.js";
2
2
  import type { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
3
+ /**
4
+ * What arrives on `workerData.config`.
5
+ *
6
+ * Declared beside the code that reads it and `import type`d by the side that
7
+ * builds it (`detachedWorkerData`), so the two cannot drift: a key added here
8
+ * and forgotten there is a compile error, not a worker quietly posting
9
+ * `undefined` inside a protocol line.
10
+ */
11
+ export interface DetachedWorkerConfig {
12
+ endpoint: string;
13
+ appKey?: string;
14
+ appSecret?: string;
15
+ /** Plain JSON, so it travels as data; the sanitizer that reads it travels as source. */
16
+ wireShapes: Parameters<typeof createTelemetrySanitizer>[0];
17
+ /** `DEGRADED_MESSAGE_PREFIX`, as data - see where it is read below. */
18
+ degradedPrefix: string;
19
+ }
20
+ export interface DetachedWorkerData {
21
+ sharedBuffer: SharedArrayBuffer;
22
+ config: DetachedWorkerConfig;
23
+ }
3
24
  export declare const detachedObserveWorker: (createSanitizer?: typeof createTelemetrySanitizer, describeRefusal?: typeof describeIngestRefusal) => void;
@@ -1,4 +1,3 @@
1
- import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
2
1
  export const detachedObserveWorker = (
3
2
  // The factory's *source* is inlined as this argument when the worker script
4
3
  // is assembled (see `ObserveAgentWorker.initializeWorker`) - a stringified
@@ -25,6 +24,30 @@ describeRefusal) => {
25
24
  const view = new DataView(sharedBuffer, 4, 4);
26
25
  const decoder = new TextDecoder();
27
26
  const telemetryUrl = `${config.endpoint}/applications/telemetry`;
27
+ /**
28
+ * Why the endpoint can never be reached, decided once from its shape; null
29
+ * when it parses. `fetch` reports a malformed URL exactly as it reports a
30
+ * refused connection - a `TypeError` with a `cause` - so without this the
31
+ * operator is told to check that the collector is running when the fix is
32
+ * the `endpoint` option. `new URL` alone does not settle it: a scheme-less
33
+ * "localhost:4000" parses, with "localhost" as the scheme.
34
+ */
35
+ const endpointProblem = (() => {
36
+ try {
37
+ const { protocol } = new URL(telemetryUrl);
38
+ return protocol === "http:" || protocol === "https:"
39
+ ? null
40
+ : `its scheme is "${protocol}" rather than http: or https:`;
41
+ }
42
+ catch {
43
+ return "it is not a valid URL";
44
+ }
45
+ })();
46
+ // Arrives as data rather than being imported: this function body is eval'd
47
+ // with no module scope, so a reference to the exported constant would be a
48
+ // `ReferenceError` here. Passed in so the prefix has a single definition
49
+ // that `parseDegradedMessage` still matches.
50
+ const degradedPrefix = config.degradedPrefix;
28
51
  /**
29
52
  * Built here, used only when the collector answers 400. The shapes travel
30
53
  * through `workerData` (they are plain JSON); the factory travels as source.
@@ -151,11 +174,9 @@ describeRefusal) => {
151
174
  resolve(compressed);
152
175
  }
153
176
  }));
154
- const postBatch = async (json) => fetch(telemetryUrl, {
155
- method: "POST",
156
- headers,
157
- body: await gzipAsync(json),
158
- });
177
+ /** The request and nothing else, so what it throws is a transport failure. */
178
+ const post = (body) => fetch(telemetryUrl, { method: "POST", headers, body });
179
+ const postBatch = async (json) => post(await gzipAsync(json));
159
180
  /**
160
181
  * Last resort for a 400: brings the batch into contract entry by entry and
161
182
  * re-sends it once, so one bad entry costs itself rather than the batch.
@@ -235,7 +256,38 @@ describeRefusal) => {
235
256
  // Skip the first 4 bytes (lock) and the next 4 bytes (length)
236
257
  const jsonBytes = buffer.slice(8, 8 + jsonLength);
237
258
  const jsonStr = decoder.decode(jsonBytes);
238
- const response = await postBatch(jsonStr);
259
+ const compressed = await gzipAsync(jsonStr);
260
+ // Only the request is in this `try`, so anything it throws is a
261
+ // transport failure by construction and the outer catch is left for
262
+ // faults in this worker. Telling the two apart by the shape of the error
263
+ // instead - `fetch` puts ECONNREFUSED and friends on `err.cause` - holds
264
+ // only until the first exception without one, such as a timeout signal
265
+ // on the request, which would then be reported as an agent bug.
266
+ let response;
267
+ try {
268
+ response = await post(compressed);
269
+ }
270
+ catch (err) {
271
+ // `fetch` reports every transport failure as the same opaque "fetch
272
+ // failed" and puts the reason - ECONNREFUSED, ENOTFOUND, a TLS error -
273
+ // on `err.cause`. Reporting only `err.message` would tell the operator
274
+ // nothing: not what went wrong, and not which URL was tried.
275
+ const cause = err
276
+ ?.cause;
277
+ const reason = cause?.code ?? cause?.message;
278
+ parentPort.postMessage(endpointProblem
279
+ ? `Error: Could not send telemetry: \`endpoint\` is set to ` +
280
+ `${JSON.stringify(config.endpoint)} and ${endpointProblem}. ` +
281
+ `Fix the endpoint option.`
282
+ : `Error: Could not reach the collector at ${telemetryUrl}` +
283
+ (reason ? ` (${reason})` : "") +
284
+ `. Check that it is running and that \`endpoint\` points at it.`);
285
+ // Discarded rather than retried - `clearBuffer` in `finally` - which
286
+ // is the right call for a fixed-size buffer the application is still
287
+ // writing into: holding it for a retry would block every batch behind
288
+ // an unreachable collector.
289
+ return true;
290
+ }
239
291
  if (!response.ok) {
240
292
  if (response.status === 401 || response.status === 403) {
241
293
  authRejections += 1;
@@ -304,27 +356,25 @@ describeRefusal) => {
304
356
  accepted.degraded === true;
305
357
  // A protocol line, not prose: the parent keys off the prefix and the
306
358
  // value, and is the side that decides what to do about it.
307
- parentPort.postMessage(`${DEGRADED_MESSAGE_PREFIX}${degraded}`);
359
+ parentPort.postMessage(`${degradedPrefix}${degraded}`);
308
360
  parentPort.postMessage("Tracing and instrumentation data sent successfully");
309
361
  return true;
310
362
  }
311
363
  catch (err) {
312
- // `fetch` reports every transport failure as the same opaque "fetch
313
- // failed", and puts the reason - ECONNREFUSED, ENOTFOUND, a TLS error -
314
- // on `err.cause`. Reporting only `err.message` therefore tells the
315
- // operator nothing: not what went wrong, and not which URL was tried.
316
- // The 401/403 branch above already names what to check; this does the
317
- // same for the case where the collector was never reached.
318
- const cause = err
319
- ?.cause;
320
- const reason = cause?.code ?? cause?.message;
321
- parentPort.postMessage(`Error: Could not reach the collector at ${telemetryUrl}` +
322
- (reason ? ` (${reason})` : "") +
323
- `. Check that it is running and that \`endpoint\` points at it.`);
324
- // The batch is discarded rather than retried - `clearBuffer` below -
325
- // which is the right call for a fixed-size buffer the application is
326
- // still writing into: holding it for a retry would block every batch
327
- // behind an unreachable collector.
364
+ // Not the request - that has its own catch above - so this is a fault
365
+ // in the worker itself: decoding the buffer, compressing, reading the
366
+ // reply or posting to the parent. Said so rather than blamed on the
367
+ // network: an operator can report a stack line, and can do nothing with
368
+ // the claim that a collector which just answered is unreachable.
369
+ const cause = err?.cause;
370
+ const causeText = cause instanceof Error || typeof cause === "string"
371
+ ? String(cause)
372
+ : undefined;
373
+ parentPort.postMessage(`Error: Telemetry worker failed while sending a batch to ${telemetryUrl} - ` +
374
+ String(err) +
375
+ (causeText === undefined ? "" : ` (cause: ${causeText})`) +
376
+ `. This is most likely a fault in the observe agent rather than a ` +
377
+ `connectivity problem; please report it.`);
328
378
  return true;
329
379
  }
330
380
  finally {
@@ -24,11 +24,13 @@ const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
24
24
  /**
25
25
  * Caps on the log portion of a batch.
26
26
  *
27
- * Logs are the only unbounded input here - snapshots are gated by
28
- * `maxTracesPerBatch`, but a chatty service (or one stuck in a retry loop)
29
- * produces log lines with no natural ceiling. Left uncapped they grow the
30
- * payload past `SHARED_BUFFER_SIZE`, and `encodeAndWrite` then throws for the
31
- * whole batch, so noisy logging silently costs you the traces and metrics too.
27
+ * Logs are the one input with no natural ceiling - snapshots are gated by
28
+ * `maxTracesPerBatch` and their largest caller-chosen field, the GraphQL
29
+ * document, is capped where it is parsed - but a chatty service (or one stuck
30
+ * in a retry loop) produces log lines without limit. Left uncapped they grow
31
+ * the payload past `SHARED_BUFFER_SIZE`, and `encodeAndWrite` then throws for
32
+ * the whole batch, so noisy logging silently costs you the traces and metrics
33
+ * too.
32
34
  *
33
35
  * Both limits are needed: the count bounds ordinary chatter, and the per-entry
34
36
  * length bounds the single pathological line - a serialised payload dump or a
@@ -19,11 +19,9 @@ import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
19
19
  import { ProfileUploader } from "../profiling/profile-uploader.js";
20
20
  import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
21
21
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
22
- import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
23
- import { detachedObserveWorker } from "./detached-observe-worker.js";
24
22
  import { parseDegradedMessage } from "./degraded-ingest.protocol.js";
23
+ import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
25
24
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
26
- import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
27
25
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
26
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
29
27
  const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
@@ -60,9 +58,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
60
58
  }
61
59
  onModuleInit() {
62
60
  this.initializeWorker();
63
- const flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
61
+ let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
64
62
  if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
65
63
  this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
64
+ // Clamp the value the timer is armed with, not just the recorded option:
65
+ // the warning above used to be a lie, and a `flushInterval: 50` flushed
66
+ // twenty times a second while claiming it had been raised to 1s.
67
+ flushIntervalTime = MIN_FLUSH_INTERVAL;
66
68
  this.options.flushInterval = MIN_FLUSH_INTERVAL;
67
69
  }
68
70
  this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
@@ -201,25 +203,19 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
201
203
  }
202
204
  initializeWorker() {
203
205
  this.warnIfCredentialsSentInClear();
204
- // The sanitizer factory and the refusal describer are inlined as the
205
- // worker function's arguments: the worker is eval'd source with no module
206
- // scope, so code it needs has to travel as source, and data (the wire
207
- // shapes are plain JSON) as `workerData`. Both are written self-contained
208
- // for exactly this.
209
- this.worker = new Worker(`(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()}, ${describeIngestRefusal.toString()})`, {
206
+ // Source and data both come from the assembly module, which the worker's
207
+ // tests build from too: the worker is eval'd with no module scope, so the
208
+ // code it needs travels as stringified functions and the configuration as
209
+ // `workerData`, and the one place that puts them together is the one
210
+ // place a forgotten value can be caught.
211
+ this.worker = new Worker(detachedWorkerSource(), {
210
212
  eval: true,
211
- workerData: {
213
+ workerData: detachedWorkerData({
212
214
  sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
213
- // Passed in rather than read from the environment inside the worker:
214
- // the worker is a stringified function with no access to this
215
- // module's configuration.
216
- config: {
217
- endpoint: this.endpoint,
218
- appKey: this.options.appKey,
219
- appSecret: this.options.appSecret,
220
- wireShapes: SECTION_SHAPES,
221
- },
222
- },
215
+ endpoint: this.endpoint,
216
+ appKey: this.options.appKey,
217
+ appSecret: this.options.appSecret,
218
+ }),
223
219
  });
224
220
  this.worker.on("message", (msg) => this.handleMessage(msg));
225
221
  this.worker.on("error", (error) => this.handleError(error));
@@ -59,6 +59,7 @@ const REQUEST_SNAPSHOT = {
59
59
  u: { type: "string" },
60
60
  tg: { type: "object" },
61
61
  e: { type: "object" },
62
+ rq: { type: "object" },
62
63
  a: { type: "object", shape: REQUEST_ATTRIBUTES },
63
64
  t: { type: "object", array: true, shape: TRACE_NODE },
64
65
  };
@@ -16,6 +16,12 @@ export function remapKeys(source, keyMap) {
16
16
  // on the prototype where neither form can see them - those are copied across
17
17
  // explicitly by `CustomMetricsEncoder`.
18
18
  for (const key in source) {
19
+ // `hasOwn` rather than a truthiness check: `keyMap["toString"]` is the
20
+ // inherited function, and an attribute named that way would land under a
21
+ // key spelt from its source code.
22
+ if (!Object.hasOwn(keyMap, key)) {
23
+ continue;
24
+ }
19
25
  const mapped = keyMap[key];
20
26
  if (mapped) {
21
27
  encoded[mapped] = source[key];
@@ -17,6 +17,7 @@ declare const SNAPSHOT_KEY_MAP: {
17
17
  readonly tags: "tg";
18
18
  readonly error: "e";
19
19
  readonly userId: "u";
20
+ readonly request: "rq";
20
21
  };
21
22
  export type EncodedAttributes = {
22
23
  [K in keyof RequestSnapshot["attributes"] as K extends keyof typeof ATTRIBUTES_KEY_MAP ? (typeof ATTRIBUTES_KEY_MAP)[K] : never]: RequestSnapshot["attributes"][K];
@@ -17,6 +17,7 @@ const SNAPSHOT_KEY_MAP = {
17
17
  tags: "tg",
18
18
  error: "e",
19
19
  userId: "u",
20
+ request: "rq",
20
21
  };
21
22
  export class RequestSnapshotEncoder {
22
23
  static encode(snapshot) {
@@ -1,4 +1,4 @@
1
- import { CALLER_METADATA_KEY } from "../observe.constants.js";
1
+ import { CALLER_METADATA_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
2
  /**
3
3
  * Stand-in "class name" for instrumented standalone functions. Unlike methods,
4
4
  * they have no enclosing class to borrow a name from, so every span they emit
@@ -29,7 +29,7 @@ export function createInstanceDecorator(als, operationTraceRegistry, options) {
29
29
  return callUntraced(this, args);
30
30
  }
31
31
  const store = als.getStore();
32
- const requestId = store?.get(options.traceIdKey);
32
+ const requestId = store?.get(TRACE_REGISTRY_KEY) ?? store?.get(options.traceIdKey);
33
33
  if (!requestId) {
34
34
  return callUntraced(this, args);
35
35
  }
@@ -1,3 +1,5 @@
1
+ import type { OutgoingHttpOptions } from "../outgoing/http.integration.js";
2
+ import type { HttpCaptureOptions } from "../utils/capture-request.util.js";
1
3
  import { FactoryProvider, ModuleMetadata, Provider, Type } from "@nestjs/common";
2
4
  import { BaseRpcContext, Transport } from "@nestjs/microservices";
3
5
  import { GraphQLResolveInfoLike } from "./graphql.interfaces.js";
@@ -16,9 +18,15 @@ export interface RedactionOptions {
16
18
  */
17
19
  patterns?: RegExp[];
18
20
  /**
19
- * Extra attribute keys whose values are masked outright, on top of the
20
- * built-in list. Compared case-insensitively, ignoring `-` and `_`, so
21
- * "apiKey", "api_key" and "API-KEY" are one entry.
21
+ * Extra keys whose values are masked outright, on top of the built-in
22
+ * rules - wherever masking is by key: log attributes, captured headers and
23
+ * bodies, and the query string of a recorded URL. Compared
24
+ * case-insensitively, ignoring `-` and `_`, so "apiKey", "api_key" and
25
+ * "API-KEY" are one entry.
26
+ *
27
+ * The built-in rules already match a name by what it ends in (`resetToken`,
28
+ * `client_secret`, `X-Amz-Signature`), so this is for names that do not say
29
+ * what they hold.
22
30
  */
23
31
  keys?: string[];
24
32
  /**
@@ -211,7 +219,7 @@ export interface ObserveOptions {
211
219
  * A value of 1.0 means all traces are sent, while a value of 0.1 means 10% of traces are sent.
212
220
  * @default 1.0
213
221
  */
214
- tracesSampleRate?: number | ((protocal: "http" | "rpc" | "grpc" | "graphql", attributes: any) => boolean);
222
+ tracesSampleRate?: number | ((protocal: "http" | "rpc" | "grpc" | "graphql" | "ws", attributes: any) => boolean);
215
223
  /**
216
224
  * Maximum number of traces per batch that can be sent to the Agent.
217
225
  * This is useful for controlling the volume of traces sent, especially in high-traffic applications.
@@ -269,12 +277,14 @@ export interface ObserveOptions {
269
277
  */
270
278
  forwardLogs?: boolean;
271
279
  /**
272
- * How log lines are scrubbed before leaving the process.
280
+ * How log lines and error payloads are scrubbed before leaving the process.
273
281
  *
274
- * Redaction is on by default whenever `forwardLogs` is enabled - forwarding
275
- * logs moves them onto someone else's disk, and secrets reach logs by accident
276
- * far more often than by design, so the safe behaviour is the one you get
277
- * without asking. Set `enabled: false` to turn it off deliberately.
282
+ * Applies to forwarded log lines (when `forwardLogs` is enabled) and to the
283
+ * message and stack of every error attached to a trace - a database error
284
+ * quoting its connection string, a failed request quoting a URL with a token
285
+ * in it. Both move text onto someone else's disk, and secrets reach them by
286
+ * accident far more often than by design, so the safe behaviour is the one
287
+ * you get without asking. Set `enabled: false` to turn it off deliberately.
278
288
  */
279
289
  redaction?: RedactionOptions;
280
290
  /**
@@ -323,6 +333,19 @@ export interface ObserveOptions {
323
333
  * @default undefined
324
334
  */
325
335
  queryParamsObfuscateRegex?: RegExp;
336
+ /**
337
+ * What to record of the request itself - the inputs that tell a
338
+ * reproducible problem from a one-off - for a request that **failed**, or
339
+ * one slower than `slowerThanMs` when that is set. Never recorded for an
340
+ * ordinary request.
341
+ *
342
+ * By default a short allow-list of headers that neither authenticate nor
343
+ * identify the caller (`user-agent`, `content-type`, `referer`, ...) and
344
+ * no body. Everything recorded passes through `redaction` first. Set to
345
+ * `false` to record nothing.
346
+ * @example { headers: ['user-agent', 'x-tenant-id'], body: { maxBytes: 4096 }, slowerThanMs: 2000 }
347
+ */
348
+ capture?: HttpCaptureOptions | false;
326
349
  /**
327
350
  * A function to associate a user identifier with the HTTP request.
328
351
  * This function receives the request object and should return a string representing the user ID.
@@ -459,6 +482,60 @@ export interface ObserveOptions {
459
482
  */
460
483
  getUserId?: (call: any) => string;
461
484
  };
485
+ /**
486
+ * Spans for what leaves the process: database queries (`pg`, `mysql2`,
487
+ * `mongodb` - and so every ORM built on them) and outbound HTTP requests
488
+ * (`fetch`/undici and `node:http`, so axios too). On by default; `false`
489
+ * switches all of it off.
490
+ *
491
+ * A query span is named after its verb and table (`SELECT users`) and
492
+ * carries the statement with every literal removed; bound parameters are
493
+ * never read. An HTTP span is named after the method and host, and carries
494
+ * the URL with sensitive query parameters masked.
495
+ */
496
+ outgoing?: false | {
497
+ /** @default true */
498
+ database?: boolean;
499
+ /** @default true */
500
+ http?: boolean | OutgoingHttpOptions;
501
+ };
502
+ /**
503
+ * WebSocket gateway configuration options for the Observe APM.
504
+ *
505
+ * The unit is one inbound message handled by a `@SubscribeMessage()`
506
+ * method, reported as a request whose operation id is
507
+ * `GatewayClass:pattern`. Connection and disconnection are not operations
508
+ * and are not reported. A message has no carrier for a trace id, so each one
509
+ * opens a trace of its own.
510
+ */
511
+ ws?: {
512
+ /**
513
+ * A function that determines whether to skip tracing a given message.
514
+ * @example (message) => message.pattern === 'ping'
515
+ * @default () => false
516
+ */
517
+ ignore?: (message: WsMessageContext) => boolean;
518
+ /**
519
+ * Tags to be added to every gateway message trace.
520
+ * @default {}
521
+ */
522
+ tags?: Record<string, string | number | boolean>;
523
+ /**
524
+ * A function to generate additional attributes for a message. These can be
525
+ * retrieved later within the trace.
526
+ * @default () => ({})
527
+ */
528
+ setAttributes?: (message: WsMessageContext) => {
529
+ [key: string]: string | number | boolean;
530
+ };
531
+ /**
532
+ * A function to associate a user identifier with the message - typically
533
+ * read from whatever the connection handler attached to the client.
534
+ * @example (message) => message.client.data?.userId
535
+ * @default undefined
536
+ */
537
+ getUserId?: (message: WsMessageContext) => string | undefined;
538
+ };
462
539
  /**
463
540
  * Jobs configuration options for the Observe APM.
464
541
  *
@@ -520,3 +597,14 @@ export interface ObserveModuleAsyncOptions extends Pick<ModuleMetadata, "imports
520
597
  */
521
598
  global?: boolean;
522
599
  }
600
+ /** What a `ws` option hook is told about the message being handled. */
601
+ export interface WsMessageContext {
602
+ /** Class name of the gateway handling the message. */
603
+ gateway: string;
604
+ /** The `@SubscribeMessage()` pattern. */
605
+ pattern: string;
606
+ /** The client socket, as the platform adapter hands it to the gateway. */
607
+ client: any;
608
+ /** The message payload. Never recorded - it is here for the hooks only. */
609
+ data: unknown;
610
+ }
@@ -1,3 +1,4 @@
1
+ import type { CapturedRequest } from "../utils/capture-request.util.js";
1
2
  import { CompleteTraceEventNode, OngoingTraceEventNode } from "./trace-events.interfaces.js";
2
3
  export interface RequestSnapshot {
3
4
  /**
@@ -52,6 +53,13 @@ export interface RequestSnapshot {
52
53
  stack?: string;
53
54
  tags?: Record<string, string | number | boolean>;
54
55
  };
56
+ /**
57
+ * The request's own inputs - headers, and the body when asked for - when
58
+ * `http.capture` decides this request is worth them: it failed, or it ran
59
+ * past `slowerThanMs`. A field of its own rather than part of `error`, so
60
+ * that what triggered the capture never decides where it is read from.
61
+ */
62
+ request?: CapturedRequest;
55
63
  /**
56
64
  * Optional user identifier associated with the request.
57
65
  */
@@ -1,2 +1,18 @@
1
1
  export declare const OBSERVE_OPTIONS = "OBSERVE_OPTIONS";
2
2
  export declare const CALLER_METADATA_KEY = "#caller";
3
+ /**
4
+ * Where a store keeps the registry key when it differs from the trace id.
5
+ *
6
+ * A queued job reports under the trace id of the operation that enqueued it,
7
+ * and that operation may still be open in this very process - an API that
8
+ * also runs its own workers. The registry is keyed per execution, so the job
9
+ * gets a key of its own here while `traceIdKey` keeps the id everything
10
+ * user-facing reads: logs, `currentTraceId()`, the snapshot.
11
+ */
12
+ export declare const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * The job option the enqueuing side stamps the active trace id into. Both
15
+ * BullMQ and Bull persist unknown options verbatim, so it survives the trip
16
+ * through Redis without touching the job's data.
17
+ */
18
+ export declare const JOB_TRACE_OPTION_KEY = "observeTraceId";
@@ -1,2 +1,18 @@
1
1
  export const OBSERVE_OPTIONS = "OBSERVE_OPTIONS";
2
2
  export const CALLER_METADATA_KEY = "#caller";
3
+ /**
4
+ * Where a store keeps the registry key when it differs from the trace id.
5
+ *
6
+ * A queued job reports under the trace id of the operation that enqueued it,
7
+ * and that operation may still be open in this very process - an API that
8
+ * also runs its own workers. The registry is keyed per execution, so the job
9
+ * gets a key of its own here while `traceIdKey` keeps the id everything
10
+ * user-facing reads: logs, `currentTraceId()`, the snapshot.
11
+ */
12
+ export const TRACE_REGISTRY_KEY = "#registryKey";
13
+ /**
14
+ * The job option the enqueuing side stamps the active trace id into. Both
15
+ * BullMQ and Bull persist unknown options verbatim, so it survives the trip
16
+ * through Redis without touching the job's data.
17
+ */
18
+ export const JOB_TRACE_OPTION_KEY = "observeTraceId";