@nestjs/observe 0.2.3 → 0.3.1

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 (62) hide show
  1. package/README.md +38 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/telemetry-wire-contract.js +1 -0
  4. package/dist/encoders/request-snapshot.encoder.d.ts +1 -0
  5. package/dist/encoders/request-snapshot.encoder.js +1 -0
  6. package/dist/instrument/create-instance-decorator.instrument.js +2 -2
  7. package/dist/interfaces/observe-options.interface.d.ts +90 -4
  8. package/dist/interfaces/request-snapshot.interface.d.ts +8 -0
  9. package/dist/observe.constants.d.ts +16 -0
  10. package/dist/observe.constants.js +16 -0
  11. package/dist/observe.module.js +48 -4
  12. package/dist/outgoing/http.integration.d.ts +36 -0
  13. package/dist/outgoing/http.integration.js +127 -0
  14. package/dist/outgoing/mongodb.integration.d.ts +38 -0
  15. package/dist/outgoing/mongodb.integration.js +141 -0
  16. package/dist/outgoing/mysql2.integration.d.ts +20 -0
  17. package/dist/outgoing/mysql2.integration.js +89 -0
  18. package/dist/outgoing/outgoing-observe-agent.service.d.ts +17 -0
  19. package/dist/outgoing/outgoing-observe-agent.service.js +123 -0
  20. package/dist/outgoing/outgoing-span.recorder.d.ts +54 -0
  21. package/dist/outgoing/outgoing-span.recorder.js +94 -0
  22. package/dist/outgoing/patch-method.util.d.ts +15 -0
  23. package/dist/outgoing/patch-method.util.js +29 -0
  24. package/dist/outgoing/pg.integration.d.ts +22 -0
  25. package/dist/outgoing/pg.integration.js +66 -0
  26. package/dist/outgoing/sql-statement.util.d.ts +21 -0
  27. package/dist/outgoing/sql-statement.util.js +48 -0
  28. package/dist/protocols/bull-observe-agent.service.d.ts +28 -0
  29. package/dist/protocols/bull-observe-agent.service.js +130 -0
  30. package/dist/protocols/graphql-observe-agent.service.js +5 -2
  31. package/dist/protocols/graphql-operation-parser.d.ts +4 -4
  32. package/dist/protocols/graphql-operation-parser.js +28 -4
  33. package/dist/protocols/http-observe-agent.service.js +26 -7
  34. package/dist/protocols/job-trace-runner.d.ts +77 -0
  35. package/dist/protocols/job-trace-runner.js +196 -0
  36. package/dist/protocols/queue-observe-agent.service.d.ts +9 -4
  37. package/dist/protocols/queue-observe-agent.service.js +36 -95
  38. package/dist/protocols/ws-observe-agent.service.d.ts +39 -0
  39. package/dist/protocols/ws-observe-agent.service.js +180 -0
  40. package/dist/services/logger-patcher.service.js +18 -5
  41. package/dist/services/operation-trace.registry.d.ts +17 -1
  42. package/dist/services/operation-trace.registry.js +39 -7
  43. package/dist/services/stdout-forwarder.service.d.ts +14 -4
  44. package/dist/services/stdout-forwarder.service.js +49 -25
  45. package/dist/services/trace-sampler.service.d.ts +4 -0
  46. package/dist/services/tracer.service.js +5 -3
  47. package/dist/utils/capture-request.util.d.ts +57 -0
  48. package/dist/utils/capture-request.util.js +116 -0
  49. package/dist/utils/default-trace-id-generator.util.d.ts +12 -0
  50. package/dist/utils/default-trace-id-generator.util.js +12 -1
  51. package/dist/utils/log-redactor.d.ts +20 -1
  52. package/dist/utils/log-redactor.js +54 -38
  53. package/dist/utils/optional-peer.util.d.ts +13 -0
  54. package/dist/utils/optional-peer.util.js +30 -0
  55. package/dist/utils/redact-url-query.d.ts +10 -1
  56. package/dist/utils/redact-url-query.js +16 -37
  57. package/dist/utils/sensitive-keys.d.ts +15 -0
  58. package/dist/utils/sensitive-keys.js +76 -0
  59. package/dist/utils/source-context.util.d.ts +6 -0
  60. package/dist/utils/source-context.util.js +113 -15
  61. package/dist/utils/source-map-resolver.util.js +12 -0
  62. package/package.json +35 -2
@@ -13,22 +13,16 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  var QueueObserveAgentService_1;
14
14
  import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
- import { uuidv7 } from "../utils/uuid-v7.util.js";
17
16
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
17
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
18
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
19
+ import { JobTraceRunner } from "./job-trace-runner.js";
20
20
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAgentService {
22
- observeAgentSharedBuffer;
23
- options;
24
- operationTraceRegistry;
25
- asyncLocalStorage;
26
22
  logger = new Logger(QueueObserveAgentService_1.name);
23
+ runner;
27
24
  constructor(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage) {
28
- this.observeAgentSharedBuffer = observeAgentSharedBuffer;
29
- this.options = options;
30
- this.operationTraceRegistry = operationTraceRegistry;
31
- this.asyncLocalStorage = asyncLocalStorage;
25
+ this.runner = new JobTraceRunner(observeAgentSharedBuffer, options, operationTraceRegistry, asyncLocalStorage, this.logger);
32
26
  this.patchDecorate();
33
27
  }
34
28
  /**
@@ -50,7 +44,11 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
50
44
  // for a delayed job the gap between the two is a schedule the caller asked
51
45
  // for - not a queue that fell behind. Counting it would report a job dated
52
46
  // a week out as a week of backlog and drag `job_wait_p95` with it.
53
- const availableAt = job.timestamp + (job.delay ?? 0);
47
+ //
48
+ // Read off the options when `job.delay` is zero: BullMQ resets that
49
+ // field as it promotes a delayed job, so by the time a worker holds the
50
+ // job it says 0 whatever was asked for.
51
+ const availableAt = job.timestamp + (job.delay || job.opts?.delay || 0);
54
52
  metadata.waitDuration = Math.max(0, startedAt - availableAt);
55
53
  }
56
54
  if (typeof job.attemptsMade === "number") {
@@ -96,91 +94,34 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
96
94
  return;
97
95
  }
98
96
  ProcessorDecoratorService.prototype["decorate"] =
99
- (processor) => (job) => {
100
- const hasOuterContext = this.asyncLocalStorage
101
- .getStore()
102
- ?.has(this.options.traceIdKey);
103
- // The same map `run` is given, rather than `getStore()` inside the
104
- // callback: identical object, one lookup fewer, and it is known to exist.
105
- const store = new Map();
106
- return this.asyncLocalStorage.run(store, () => {
107
- if (hasOuterContext) {
108
- // If the outer context already has a trace ID
109
- // ignore the inner context
110
- if (this.options.debug) {
111
- this.logger.debug(`Outer context already has a trace ID. Skipping inner context for job "${job.name}" job.id: ${job.id}`);
112
- }
113
- return processor(job);
114
- }
115
- const traceId = uuidv7();
116
- store.set(this.options.traceIdKey, traceId);
117
- if (this.options.jobs?.setAttributes) {
118
- const attributes = this.options.jobs?.setAttributes?.({
119
- queueName: job.queueName,
120
- name: job.name,
121
- id: job.id,
122
- });
123
- if (attributes) {
124
- for (const [key, value] of Object.entries(attributes)) {
125
- store.set(key, value);
126
- }
127
- }
128
- }
129
- // setImmediate(() => {
130
- this.operationTraceRegistry.startTrace(traceId, {
131
- tags: this.options.jobs?.tags,
132
- queueName: job.queueName,
133
- name: job.name,
134
- id: typeof job.id === "number" ? `${job.id}` : job.id,
135
- ...this.readQueueMetadata(job),
136
- });
137
- // });
138
- const endTrace = (status) => {
139
- setTimeout(async () => {
140
- this.operationTraceRegistry.endTrace(traceId, { status });
141
- const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
142
- // `pluckSnapshot` deletes what it returns, so a trace already
143
- // plucked - a job whose handler resolved and rejected, a retry
144
- // reusing the id - answers undefined. The `!` here asserted
145
- // otherwise, and the encoder dereferenced it inside a
146
- // `setTimeout`, where no try/catch can reach: an unhandled
147
- // TypeError that took the whole process down. A worker deployment
148
- // could not finish booting, because draining a queue was enough
149
- // to trigger it.
150
- //
151
- // Dropped rather than reported: there is no snapshot, so there is
152
- // nothing to send, and losing one job's self-instrumentation is
153
- // not worth a crash loop.
154
- if (!snapshot) {
155
- return;
156
- }
157
- this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
158
- }, 0);
159
- };
160
- try {
161
- const returnValue = processor(job);
162
- if (returnValue instanceof Promise) {
163
- return returnValue
164
- .then((ret) => {
165
- endTrace("completed");
166
- return ret;
167
- })
168
- .catch((error) => {
169
- console.error("ending trace with error:", error);
170
- endTrace("failed");
171
- throw error;
172
- });
173
- }
174
- endTrace("completed");
175
- return returnValue;
176
- }
177
- catch (error) {
178
- console.error("rethrowing again?");
179
- endTrace("failed");
180
- throw error;
181
- }
182
- });
183
- };
97
+ (processor) => (job) => this.runner.run({
98
+ queueName: job.queueName,
99
+ name: job.name,
100
+ id: job.id,
101
+ opts: job.opts,
102
+ metadata: this.readQueueMetadata(job),
103
+ }, () => processor(job));
104
+ this.patchQueue();
105
+ }
106
+ /**
107
+ * The enqueuing half: without it a worker has no way to learn which
108
+ * operation a job came from, and every run opens an unrelated trace.
109
+ *
110
+ * `bullmq` is loaded the way `@nestjs/bullmq` loads it, so the prototype
111
+ * patched here is the one behind every `@InjectQueue()`.
112
+ */
113
+ patchQueue() {
114
+ const result = loadOptionalPeer("bullmq");
115
+ if (!result.installed) {
116
+ return;
117
+ }
118
+ const prototype = result.module?.Queue?.prototype;
119
+ if (!prototype) {
120
+ this.logger.warn(`bullmq is installed but its Queue could not be loaded, so jobs will not inherit the trace that enqueued them${result.error ? `: ${describePeerLoadError(result.error)}` : "."}`);
121
+ return;
122
+ }
123
+ // add(name, data, opts)
124
+ this.runner.patchEnqueue(prototype, () => 2);
184
125
  }
185
126
  };
186
127
  QueueObserveAgentService = QueueObserveAgentService_1 = __decorate([
@@ -0,0 +1,39 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
2
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
3
+ import { ObserveModuleOptionsWithDefaults } from "../interfaces/index.js";
4
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
5
+ import { TraceSamplerService } from "../services/trace-sampler.service.js";
6
+ import { KeyOf } from "../types/key-of.type.js";
7
+ /**
8
+ * Gateway message tracing for `@nestjs/websockets`.
9
+ *
10
+ * Unlike the HTTP adapter and the microservice server, a gateway offers no
11
+ * processing hooks, so the one place every `@SubscribeMessage()` handler
12
+ * passes through is patched instead: `WsContextCreator.create`, which builds
13
+ * the guards-pipes-interceptors-handler chain for a message. Wrapping what it
14
+ * returns puts the whole chain inside the trace, whichever platform adapter -
15
+ * socket.io, ws - delivers the message.
16
+ */
17
+ export declare class WsObserveAgentService<Store extends Record<string, unknown>> {
18
+ private readonly observeAgentSharedBuffer;
19
+ private readonly options;
20
+ private readonly operationTraceRegistry;
21
+ private readonly traceSamplerService;
22
+ private readonly asyncLocalStorage;
23
+ private readonly logger;
24
+ constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, traceSamplerService: TraceSamplerService, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
25
+ private loadContextCreator;
26
+ private patchContextCreator;
27
+ /**
28
+ * Nest reads a gateway's handlers off the class prototype and applies them
29
+ * to the instance, which steps around the instrumentation proxy - the one
30
+ * method of the whole chain that would go unrecorded is the handler itself,
31
+ * and a handler that throws before calling anything leaves no span at all.
32
+ *
33
+ * The stand-in calls the same method through the instance instead. Guards,
34
+ * pipes, filters and the message pattern are all looked up as metadata on
35
+ * the callback, so that metadata is carried over.
36
+ */
37
+ private routeThroughInstance;
38
+ private traceMessage;
39
+ }
@@ -0,0 +1,180 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
+ return function (target, key) { decorator(target, key, paramIndex); }
12
+ };
13
+ var WsObserveAgentService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
+ import { AsyncLocalStorage } from "async_hooks";
16
+ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
17
+ import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
+ import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
22
+ const ORIGINAL_CREATE = Symbol.for("nestjs.observe.ws.create");
23
+ /** `@nestjs/websockets`' MESSAGE_METADATA - what `@SubscribeMessage()` writes. */
24
+ const MESSAGE_METADATA = "message";
25
+ /**
26
+ * Gateway message tracing for `@nestjs/websockets`.
27
+ *
28
+ * Unlike the HTTP adapter and the microservice server, a gateway offers no
29
+ * processing hooks, so the one place every `@SubscribeMessage()` handler
30
+ * passes through is patched instead: `WsContextCreator.create`, which builds
31
+ * the guards-pipes-interceptors-handler chain for a message. Wrapping what it
32
+ * returns puts the whole chain inside the trace, whichever platform adapter -
33
+ * socket.io, ws - delivers the message.
34
+ */
35
+ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentService {
36
+ observeAgentSharedBuffer;
37
+ options;
38
+ operationTraceRegistry;
39
+ traceSamplerService;
40
+ asyncLocalStorage;
41
+ logger = new Logger(WsObserveAgentService_1.name);
42
+ constructor(observeAgentSharedBuffer, options, operationTraceRegistry, traceSamplerService, asyncLocalStorage) {
43
+ this.observeAgentSharedBuffer = observeAgentSharedBuffer;
44
+ this.options = options;
45
+ this.operationTraceRegistry = operationTraceRegistry;
46
+ this.traceSamplerService = traceSamplerService;
47
+ this.asyncLocalStorage = asyncLocalStorage;
48
+ this.patchContextCreator();
49
+ }
50
+ loadContextCreator() {
51
+ const result = loadOptionalPeer("@nestjs/websockets", "@nestjs/websockets/context/ws-context-creator");
52
+ if (!result.installed) {
53
+ return undefined;
54
+ }
55
+ if (result.error) {
56
+ this.logger.warn(`@nestjs/websockets is installed but its context creator could not be loaded, so gateway messages will not be instrumented: ${describePeerLoadError(result.error)}`);
57
+ return null;
58
+ }
59
+ return result.module?.WsContextCreator ?? null;
60
+ }
61
+ patchContextCreator() {
62
+ const WsContextCreator = this.loadContextCreator();
63
+ if (WsContextCreator === undefined) {
64
+ // An optional peer. No gateways means nothing to wrap.
65
+ return;
66
+ }
67
+ const prototype = WsContextCreator?.prototype;
68
+ const originalCreate = (prototype?.[ORIGINAL_CREATE] ??
69
+ prototype?.create);
70
+ if (!prototype || typeof originalCreate !== "function") {
71
+ this.logger.warn("WsContextCreator is not available. Please, update to the latest version of @nestjs/websockets. Skipping patching.");
72
+ return;
73
+ }
74
+ // Parked under a symbol so a second agent replaces the wrapper instead of
75
+ // wrapping it again.
76
+ prototype[ORIGINAL_CREATE] = originalCreate;
77
+ const trace = this.traceMessage.bind(this);
78
+ const routeThroughInstance = this.routeThroughInstance.bind(this);
79
+ prototype.create = function (instance, callback, ...rest) {
80
+ const handler = originalCreate.call(this, instance,
81
+ // rest: [moduleKey, methodName, ...]
82
+ routeThroughInstance(instance, callback, rest[1]), ...rest);
83
+ const pattern = Reflect.getMetadata?.(MESSAGE_METADATA, callback);
84
+ const gateway = instance?.constructor?.name || "Gateway";
85
+ return (...args) => trace({ gateway, pattern: String(pattern), client: args[0], data: args[1] }, () => handler(...args));
86
+ };
87
+ }
88
+ /**
89
+ * Nest reads a gateway's handlers off the class prototype and applies them
90
+ * to the instance, which steps around the instrumentation proxy - the one
91
+ * method of the whole chain that would go unrecorded is the handler itself,
92
+ * and a handler that throws before calling anything leaves no span at all.
93
+ *
94
+ * The stand-in calls the same method through the instance instead. Guards,
95
+ * pipes, filters and the message pattern are all looked up as metadata on
96
+ * the callback, so that metadata is carried over.
97
+ */
98
+ routeThroughInstance(instance, callback, methodName) {
99
+ if (typeof methodName !== "string" || typeof callback !== "function") {
100
+ return callback;
101
+ }
102
+ const instrumented = instance[methodName];
103
+ if (typeof instrumented !== "function" || instrumented === callback) {
104
+ return callback;
105
+ }
106
+ const routed = function (...args) {
107
+ return instrumented.apply(this, args);
108
+ };
109
+ Object.defineProperty(routed, "name", { value: callback.name });
110
+ for (const key of Reflect.getMetadataKeys?.(callback) ?? []) {
111
+ Reflect.defineMetadata(key, Reflect.getMetadata(key, callback), routed);
112
+ }
113
+ return routed;
114
+ }
115
+ traceMessage(message, invoke) {
116
+ // Always a store of its own: whatever context the socket's events happen
117
+ // to fire in - the upgrade request, a polling request - is not this
118
+ // message's operation.
119
+ const store = new Map();
120
+ return this.asyncLocalStorage.run(store, () => {
121
+ const traceId = uuidv7();
122
+ store.set(this.options.traceIdKey, traceId);
123
+ const attributes = this.options.ws?.setAttributes?.(message);
124
+ if (attributes) {
125
+ for (const [key, value] of Object.entries(attributes)) {
126
+ store.set(key, value);
127
+ }
128
+ }
129
+ if (this.options.ws?.ignore?.(message) ||
130
+ !this.traceSamplerService.shouldCapture("ws", {
131
+ gateway: message.gateway,
132
+ pattern: message.pattern,
133
+ })) {
134
+ return invoke();
135
+ }
136
+ this.operationTraceRegistry.startTrace(traceId, {
137
+ protocol: "ws",
138
+ operationId: `${message.gateway}:${message.pattern}`,
139
+ tags: this.options.ws?.tags,
140
+ });
141
+ const endTrace = () => {
142
+ setTimeout(async () => {
143
+ this.operationTraceRegistry.endTrace(traceId, {
144
+ userId: this.options.ws?.getUserId?.(message),
145
+ });
146
+ const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
147
+ if (!snapshot) {
148
+ return;
149
+ }
150
+ this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
151
+ }, 0);
152
+ };
153
+ // Nest's ws proxy hands a thrown error to the exception filter and
154
+ // resolves, so there is no rejection to read a failure from here - the
155
+ // handler's own span records it, and the registry lifts a failed root
156
+ // span into the snapshot's status.
157
+ let result;
158
+ try {
159
+ result = invoke();
160
+ }
161
+ catch (error) {
162
+ endTrace();
163
+ throw error;
164
+ }
165
+ if (result instanceof Promise) {
166
+ return result.finally(endTrace);
167
+ }
168
+ endTrace();
169
+ return result;
170
+ });
171
+ }
172
+ };
173
+ WsObserveAgentService = WsObserveAgentService_1 = __decorate([
174
+ Injectable(),
175
+ __param(1, Inject(OBSERVE_OPTIONS)),
176
+ __metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, OperationTraceRegistry,
177
+ TraceSamplerService,
178
+ AsyncLocalStorage])
179
+ ], WsObserveAgentService);
180
+ export { WsObserveAgentService };
@@ -62,14 +62,27 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
62
62
  }
63
63
  return jsonLogObject;
64
64
  };
65
- ConsoleLogger.prototype["formatMessage"] = function (logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff) {
65
+ ConsoleLogger.prototype["formatMessage"] = function (
66
+ // Everything Nest passes is forwarded untouched. Naming the parameters
67
+ // once pinned this wrapper to one release's signature: Nest 12 added a
68
+ // seventh (`params`), and a wrapper that forwarded six silently dropped
69
+ // every structured param from text-mode output.
70
+ ...args) {
71
+ const output = originalFormatMessage.apply(this, args);
66
72
  const store = asyncLocalStorage.getStore();
67
73
  const requestId = store?.get(options.traceIdKey);
68
- const output = originalFormatMessage.call(this, logLevel, message, pidMessage, formattedLogLevel, contextMessage, timestampDiff);
69
- if (requestId) {
70
- return `${output} Trace ID: ${this.colorize(requestId, logLevel)}\n`;
74
+ if (!requestId) {
75
+ return output;
71
76
  }
72
- return output;
77
+ // The suffix has to sit before the line's own newline. Appended after
78
+ // it, the id lands on a line of its own - which the stdout forwarder
79
+ // then ships as a separate, level-less entry, and the parser (which
80
+ // reads the id off the end of the log line) never sees it.
81
+ const [logLevel] = args;
82
+ const suffix = ` Trace ID: ${this.colorize(requestId, logLevel)}`;
83
+ return output.endsWith("\n")
84
+ ? `${output.slice(0, -1)}${suffix}\n`
85
+ : `${output}${suffix}`;
73
86
  };
74
87
  // Add watermark to flag that the logger has been patched
75
88
  Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
@@ -55,12 +55,28 @@ export declare class OperationTraceRegistry {
55
55
  * `configureSpanCollapse`, for the same reason.
56
56
  */
57
57
  configureRedaction(redactor: LogRedactor | null): void;
58
+ /**
59
+ * The redactor error payloads go through, for a caller adding to one - so
60
+ * what it adds is held to the same rules as the rest of the payload.
61
+ */
62
+ getRedactor(): LogRedactor | null;
58
63
  /**
59
64
  * Builds the error payload attached to a span or snapshot, including the source
60
65
  * around each in-app frame when source context is enabled.
61
66
  */
62
67
  private toErrorPayload;
63
- startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">): void;
68
+ /**
69
+ * Whether a trace is open under this key - for a caller about to open one
70
+ * under an id it adopted rather than minted, which a second operation in
71
+ * this process may already hold.
72
+ */
73
+ hasTrace(traceId: TraceId): boolean;
74
+ startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">,
75
+ /**
76
+ * The trace id the snapshot reports under, when it is not the registry
77
+ * key - a job inheriting the id of the operation that enqueued it.
78
+ */
79
+ reportedTraceId?: string): void;
64
80
  endTrace(traceId: string): void;
65
81
  endTrace(traceId: string, opts?: {
66
82
  statusCode?: number;
@@ -70,6 +70,13 @@ export class OperationTraceRegistry {
70
70
  configureRedaction(redactor) {
71
71
  this.redactor = redactor;
72
72
  }
73
+ /**
74
+ * The redactor error payloads go through, for a caller adding to one - so
75
+ * what it adds is held to the same rules as the rest of the payload.
76
+ */
77
+ getRedactor() {
78
+ return this.redactor;
79
+ }
73
80
  /**
74
81
  * Builds the error payload attached to a span or snapshot, including the source
75
82
  * around each in-app frame when source context is enabled.
@@ -78,9 +85,7 @@ export class OperationTraceRegistry {
78
85
  const raw = error instanceof Error
79
86
  ? { message: error.message, stack: error.stack }
80
87
  : { message: String(error), stack: undefined };
81
- // Redacted here, at the one point every error payload passes through,
82
- // and before code frames are read: the frames are keyed off the stack's
83
- // file positions, which the redactor leaves alone.
88
+ // Redacted here, at the one point every error payload passes through.
84
89
  const payload = this.redactor
85
90
  ? {
86
91
  message: this.redactor.redactMessage(raw.message),
@@ -95,14 +100,41 @@ export class OperationTraceRegistry {
95
100
  }
96
101
  if (this.sourceContext !== false) {
97
102
  const settings = this.sourceContext === true ? {} : this.sourceContext;
98
- const codeFrames = collectCodeFrames(payload.stack, settings ?? {});
103
+ // Read off the raw stack with the raw message: the message is what marks
104
+ // where the frames start, and it only matches the stack it came from.
105
+ // Nothing of either is shipped from here - just the file positions.
106
+ const codeFrames = collectCodeFrames(raw.stack, {
107
+ ...settings,
108
+ message: raw.message,
109
+ });
99
110
  if (codeFrames) {
100
- result.codeFrames = codeFrames;
111
+ // Source is as likely to hold a literal secret as a message is, and
112
+ // goes to the same place.
113
+ const redactor = this.redactor;
114
+ result.codeFrames = redactor
115
+ ? codeFrames.map((frame) => ({
116
+ ...frame,
117
+ lines: redactor.redactSource(frame.lines),
118
+ }))
119
+ : codeFrames;
101
120
  }
102
121
  }
103
122
  return result;
104
123
  }
105
- startTrace(traceId, data) {
124
+ /**
125
+ * Whether a trace is open under this key - for a caller about to open one
126
+ * under an id it adopted rather than minted, which a second operation in
127
+ * this process may already hold.
128
+ */
129
+ hasTrace(traceId) {
130
+ return this.traceSnapshots.has(traceId);
131
+ }
132
+ startTrace(traceId, data,
133
+ /**
134
+ * The trace id the snapshot reports under, when it is not the registry
135
+ * key - a job inheriting the id of the operation that enqueued it.
136
+ */
137
+ reportedTraceId = traceId) {
106
138
  if (this.traceSnapshots.has(traceId)) {
107
139
  this.logger.warn(`Trace already started for traceId: "${traceId}". Overwriting existing trace.`);
108
140
  this.traceSnapshots.delete(traceId);
@@ -110,7 +142,7 @@ export class OperationTraceRegistry {
110
142
  }
111
143
  const snapshot = {
112
144
  ...data,
113
- traceId,
145
+ traceId: reportedTraceId,
114
146
  calledAt: new Date().toISOString(),
115
147
  startTimestamp: performance.now(),
116
148
  traces: [],
@@ -8,13 +8,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
8
8
  private readonly als;
9
9
  private readonly logger;
10
10
  /**
11
- * stdout arrives in chunks, not lines: a single write can carry half a line,
11
+ * Output arrives in chunks, not lines: a single write can carry half a line,
12
12
  * several lines, or a line split across two calls. Parsing a chunk directly
13
13
  * would mangle every log that straddles a boundary, so the trailing fragment
14
14
  * is held here until its newline shows up.
15
+ *
16
+ * One fragment per stream: stdout and stderr interleave freely, and joining
17
+ * the tail of one onto the head of the other would fuse two unrelated lines.
15
18
  */
16
- private partialLine;
17
- private originalWrite;
19
+ private readonly partialLines;
20
+ private originalWrites;
18
21
  /**
19
22
  * Null only when redaction has been switched off explicitly. Defaulting to on
20
23
  * matters more here than anywhere else in the agent: enabling `forwardLogs`
@@ -25,9 +28,16 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
25
28
  constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
26
29
  onModuleInit(): void;
27
30
  onModuleDestroy(): void;
31
+ /**
32
+ * Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
33
+ * stderr and every other level to stdout, so a stdout-only patch forwarded
34
+ * warnings and fatals but never a single error - including the line the
35
+ * exceptions handler writes for every unhandled exception.
36
+ */
28
37
  start(): void;
38
+ private patch;
29
39
  /**
30
- * Restores the original stdout.write.
40
+ * Restores the original stdout and stderr writes.
31
41
  *
32
42
  * Without this the patch outlives the module - which matters in tests, where
33
43
  * a torn-down app would keep pushing into a buffer nobody drains, and in any