@nestjs/observe 0.0.1 → 0.1.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 (72) hide show
  1. package/README.md +16 -0
  2. package/dist/.tsbuildinfo +1 -1
  3. package/dist/agent/detached-observe-worker.js +98 -1
  4. package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
  5. package/dist/agent/observe-agent.shared-buffer.js +94 -3
  6. package/dist/agent/observe-agent.worker.d.ts +28 -0
  7. package/dist/agent/observe-agent.worker.js +59 -5
  8. package/dist/custom-metrics/counter.d.ts +124 -0
  9. package/dist/custom-metrics/counter.js +93 -0
  10. package/dist/custom-metrics/gauge.d.ts +116 -0
  11. package/dist/custom-metrics/gauge.js +55 -0
  12. package/dist/custom-metrics/summary.d.ts +102 -0
  13. package/dist/custom-metrics/summary.js +100 -0
  14. package/dist/encoders/custom-metrics.encoder.js +18 -0
  15. package/dist/encoders/remap-keys.util.d.ts +11 -0
  16. package/dist/encoders/remap-keys.util.js +15 -0
  17. package/dist/encoders/trace.encoder.d.ts +7 -0
  18. package/dist/encoders/trace.encoder.js +12 -0
  19. package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
  20. package/dist/instrument/create-instance-decorator.instrument.js +67 -0
  21. package/dist/interfaces/custom-metric.interface.d.ts +74 -0
  22. package/dist/interfaces/graphql.interfaces.d.ts +16 -0
  23. package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
  24. package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
  25. package/dist/interfaces/observe-options.interface.d.ts +358 -0
  26. package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
  27. package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
  28. package/dist/interfaces/trace-span.interface.d.ts +29 -0
  29. package/dist/observe.module.js +29 -0
  30. package/dist/profiling/cpu-profiler.service.d.ts +65 -0
  31. package/dist/profiling/cpu-profiler.service.js +80 -0
  32. package/dist/profiling/fold-profile.util.d.ts +20 -0
  33. package/dist/profiling/fold-profile.util.js +0 -0
  34. package/dist/profiling/profile-uploader.d.ts +26 -0
  35. package/dist/profiling/profile-uploader.js +52 -0
  36. package/dist/profiling/span-slice-recorder.d.ts +51 -0
  37. package/dist/profiling/span-slice-recorder.js +77 -0
  38. package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
  39. package/dist/protocols/graphql-observe-agent.service.js +166 -0
  40. package/dist/protocols/graphql-operation-parser.d.ts +26 -0
  41. package/dist/protocols/graphql-operation-parser.js +66 -0
  42. package/dist/protocols/http-observe-agent.service.d.ts +19 -0
  43. package/dist/protocols/http-observe-agent.service.js +34 -0
  44. package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
  45. package/dist/protocols/queue-observe-agent.service.js +32 -0
  46. package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
  47. package/dist/protocols/rpc-observe-agent.service.js +12 -0
  48. package/dist/services/logger-patcher.service.d.ts +4 -0
  49. package/dist/services/logger-patcher.service.js +13 -1
  50. package/dist/services/node-runtime-metrics.service.js +24 -8
  51. package/dist/services/operation-trace.registry.d.ts +56 -1
  52. package/dist/services/operation-trace.registry.js +145 -6
  53. package/dist/services/stdout-forwarder.service.d.ts +19 -0
  54. package/dist/services/stdout-forwarder.service.js +62 -0
  55. package/dist/services/trace-sampler.service.d.ts +6 -0
  56. package/dist/services/trace-sampler.service.js +3 -3
  57. package/dist/services/tracer.service.d.ts +91 -0
  58. package/dist/services/tracer.service.js +56 -1
  59. package/dist/trace-span.delegate.d.ts +11 -0
  60. package/dist/trace-span.delegate.js +11 -0
  61. package/dist/types/path-value.type.d.ts +4 -0
  62. package/dist/utils/default-trace-id-generator.util.js +11 -0
  63. package/dist/utils/log-line.parser.d.ts +14 -0
  64. package/dist/utils/log-line.parser.js +37 -0
  65. package/dist/utils/log-redactor.js +65 -0
  66. package/dist/utils/redact-url-query.d.ts +17 -0
  67. package/dist/utils/redact-url-query.js +38 -0
  68. package/dist/utils/source-context.util.d.ts +22 -0
  69. package/dist/utils/source-context.util.js +60 -0
  70. package/dist/utils/source-map-resolver.util.d.ts +13 -0
  71. package/dist/utils/source-map-resolver.util.js +23 -0
  72. package/package.json +1 -1
@@ -24,6 +24,13 @@ export declare class RpcObserveAgentService<Store extends Record<string, unknown
24
24
  onModuleInit(): void;
25
25
  onModuleDestroy(): void;
26
26
  registerRpcHooks(target: Server): void;
27
+ /**
28
+ * Names the transport for the snapshot's `protocol` field.
29
+ *
30
+ * A custom transport is registered under a symbol rather than a `Transport`
31
+ * member, and indexing the enum with one yields `undefined` - so every custom
32
+ * transport used to arrive with no protocol at all.
33
+ */
27
34
  private toProtocolName;
28
35
  startRpcRequestTracing(transportId: Transport | symbol, ctx: BaseRpcContext, done: () => Promise<any>): void;
29
36
  startGrpcRequestTracing(transportId: Transport | symbol, call: GrpcCall, done: () => Promise<any>): void;
@@ -56,12 +56,21 @@ let RpcObserveAgentService = class RpcObserveAgentService {
56
56
  this.endRpcRequestTracing(transportId, ctx);
57
57
  });
58
58
  }
59
+ /**
60
+ * Names the transport for the snapshot's `protocol` field.
61
+ *
62
+ * A custom transport is registered under a symbol rather than a `Transport`
63
+ * member, and indexing the enum with one yields `undefined` - so every custom
64
+ * transport used to arrive with no protocol at all.
65
+ */
59
66
  toProtocolName(transportId) {
60
67
  return typeof transportId === "symbol"
61
68
  ? transportId.description ?? "custom"
62
69
  : Transport[transportId];
63
70
  }
64
71
  startRpcRequestTracing(transportId, ctx, done) {
72
+ // The same map `run` is given, rather than `getStore()` inside the callback:
73
+ // identical object, one lookup fewer, and it is known to exist.
65
74
  const store = new Map();
66
75
  this.asyncLocalStorage.run(store, () => {
67
76
  const traceId = this.options.traceIdGenerator(ctx);
@@ -74,6 +83,7 @@ let RpcObserveAgentService = class RpcObserveAgentService {
74
83
  }
75
84
  }
76
85
  }
86
+ // setImmediate(() => {
77
87
  if (this.options.rpc?.ignore?.(transportId, ctx)) {
78
88
  return done();
79
89
  }
@@ -90,9 +100,11 @@ let RpcObserveAgentService = class RpcObserveAgentService {
90
100
  tags: this.options.rpc?.tags,
91
101
  });
92
102
  done();
103
+ // });
93
104
  });
94
105
  }
95
106
  startGrpcRequestTracing(transportId, call, done) {
107
+ // As above: the map `run` is given, not looked back up.
96
108
  const store = new Map();
97
109
  this.asyncLocalStorage.run(store, () => {
98
110
  const traceId = this.options.traceIdGenerator(call);
@@ -8,5 +8,9 @@ export declare class LoggerPatcherService implements OnModuleInit {
8
8
  private readonly patchedWatermark;
9
9
  constructor(asyncLocalStorage: AsyncLocalStorage<any>, options: ObserveModuleOptionsWithDefaults);
10
10
  onModuleInit(): void;
11
+ /**
12
+ * Injects the trace ID into the logs if the `attachTraceIdToLogs` option is enabled.
13
+ * This method modifies the ConsoleLogger's methods to include the trace ID in the log output.
14
+ */
11
15
  injectTraceIdIntoLogs(): void;
12
16
  }
@@ -26,6 +26,10 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
26
26
  onModuleInit() {
27
27
  this.injectTraceIdIntoLogs();
28
28
  }
29
+ /**
30
+ * Injects the trace ID into the logs if the `attachTraceIdToLogs` option is enabled.
31
+ * This method modifies the ConsoleLogger's methods to include the trace ID in the log output.
32
+ */
29
33
  injectTraceIdIntoLogs() {
30
34
  if (!this.options.attachTraceIdToLogs) {
31
35
  return;
@@ -42,11 +46,18 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
42
46
  this.logger.warn('ConsoleLogger methods "formatMessage" or "getJsonLogObject" are not available, which means that you are likely using a version of NestJS that does not support these methods. Please, upgrade to at least NestJS 11.2.0. Skipping trace ID injection.');
43
47
  return;
44
48
  }
45
- ConsoleLogger.prototype["getJsonLogObject"] = function (message, logOptions) {
49
+ ConsoleLogger.prototype["getJsonLogObject"] = function (
50
+ // Nest calls this as `(message, options)`. The wrapper used to declare
51
+ // `(logLevel, message, context)` and forward all three: the values still
52
+ // landed correctly by accident - `message` in the first slot, the options
53
+ // bag in the second - and the third argument was dropped on the floor.
54
+ message, logOptions) {
46
55
  const store = asyncLocalStorage.getStore();
47
56
  const requestId = store?.get(options.traceIdKey);
48
57
  const jsonLogObject = originalGetJsonLogObject.call(this, message, logOptions);
49
58
  if (requestId) {
59
+ // Not a field Nest models on the returned object, which is the whole
60
+ // point of the patch.
50
61
  jsonLogObject["traceId"] = requestId;
51
62
  }
52
63
  return jsonLogObject;
@@ -60,6 +71,7 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
60
71
  }
61
72
  return output;
62
73
  };
74
+ // Add watermark to flag that the logger has been patched
63
75
  Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
64
76
  value: true,
65
77
  writable: false,
@@ -23,6 +23,10 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
23
23
  gcCount = 0;
24
24
  gcTotalDuration = 0;
25
25
  gcBreakdown = null;
26
+ // Seeded here rather than in `onModuleInit`, which never runs when runtime
27
+ // metrics are disabled and returns early before setting them. A sample taken
28
+ // in that window used to difference against `null`, which reads as the epoch
29
+ // and pins CPU usage at ~0%.
26
30
  lastCpuUsage = process.cpuUsage();
27
31
  lastCpuUsageTimestamp = Date.now();
28
32
  osTotalMemory = os.totalmem();
@@ -81,6 +85,10 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
81
85
  if (!kind) {
82
86
  continue;
83
87
  }
88
+ // Seeded with all three kinds at zero on the first collection of the
89
+ // window: "no major collections happened" and "major collections were
90
+ // not reported" are different facts, and only the seeding keeps them
91
+ // apart downstream.
84
92
  this.gcBreakdown ??= {
85
93
  minor: { count: 0, duration: 0 },
86
94
  major: { count: 0, duration: 0 },
@@ -98,6 +106,10 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
98
106
  this.gcObserver.observe({ type: "gc", buffered: true });
99
107
  }
100
108
  collectNodeRuntimeMetrics() {
109
+ // Nothing was started, so there is nothing to collect: with metrics turned
110
+ // off the histogram is never enabled, and every number below would be
111
+ // fabricated. This used to surface as a TypeError from dereferencing the
112
+ // absent monitor; it is stated outright so the reason survives.
101
113
  if (!this.eventLoopDelayMonitor) {
102
114
  throw new Error("Runtime metrics are not being collected. `collectNodeRuntimeMetrics()` requires `onModuleInit()` to have run with the `runtimeMetrics` option enabled.");
103
115
  }
@@ -107,20 +119,24 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
107
119
  const cpuUsage = process.cpuUsage();
108
120
  const diffCpuUsage = process.cpuUsage(this.lastCpuUsage);
109
121
  const eventLoop = performance.eventLoopUtilization();
122
+ // `mean` is NaN until the histogram has recorded its first sample, so a
123
+ // flush that lands immediately after startup would otherwise ship NaN into
124
+ // a numeric column - where it survives, poisons every average built over it
125
+ // and makes the runtime alert comparisons undefined.
110
126
  const meanDelay = this.eventLoopDelayMonitor.mean;
111
- const lag = Number.isFinite(meanDelay) ? meanDelay / 1e6 : 0;
127
+ const lag = Number.isFinite(meanDelay) ? meanDelay / 1e6 : 0; // ns → ms
112
128
  const metrics = {
113
129
  memory: {
114
- rss: memoryUsage.rss / 1024 / 1024,
115
- heapTotal: memoryUsage.heapTotal / 1024 / 1024,
116
- heapUsed: memoryUsage.heapUsed / 1024 / 1024,
117
- external: memoryUsage.external / 1024 / 1024,
118
- arrayBuffers: memoryUsage.arrayBuffers / 1024 / 1024,
130
+ rss: memoryUsage.rss / 1024 / 1024, // Convert bytes to MB
131
+ heapTotal: memoryUsage.heapTotal / 1024 / 1024, // Convert bytes to MB
132
+ heapUsed: memoryUsage.heapUsed / 1024 / 1024, // Convert bytes to MB
133
+ external: memoryUsage.external / 1024 / 1024, // Convert bytes to MB
134
+ arrayBuffers: memoryUsage.arrayBuffers / 1024 / 1024, // Convert bytes to MB
119
135
  percentageUsed: (memoryUsage.rss / this.osTotalMemory) * 100,
120
136
  },
121
137
  cpu: {
122
- user: diffCpuUsage.user / 1000,
123
- system: diffCpuUsage.system / 1000,
138
+ user: diffCpuUsage.user / 1000, // Convert from µs to ms
139
+ system: diffCpuUsage.system / 1000, // Convert from µs to ms
124
140
  percentageUsed: ((diffCpuUsage.user + diffCpuUsage.system) / 1000 / elapsedTime) *
125
141
  100,
126
142
  },
@@ -14,10 +14,19 @@ export declare class OperationTraceRegistry {
14
14
  private readonly traceSnapshots;
15
15
  private readonly callerIdsByTraceId;
16
16
  private readonly logger;
17
+ /**
18
+ * An application started without `instrument` fails this way on *every*
19
+ * request, and the guidance below is long enough that repeating it verbatim
20
+ * would bury everything else in the log. Full text once, one line after.
21
+ */
17
22
  private hasReportedMissingInstrumentation;
18
23
  constructor(als: AsyncLocalStorage<Map<KeyOf<{
19
24
  [CALLER_METADATA_KEY]: string;
20
25
  }>, unknown>>, sourceContext?: CreateObserveModuleOptions["sourceContext"]);
26
+ /**
27
+ * Builds the error payload attached to a span or snapshot, including the source
28
+ * around each in-app frame when source context is enabled.
29
+ */
21
30
  private toErrorPayload;
22
31
  startTrace(traceId: TraceId, data: Omit<RequestSnapshot, "traces" | "startTimestamp" | "calledAt" | "traceId"> | Omit<JobSnapshot, "duration">): void;
23
32
  endTrace(traceId: string): void;
@@ -28,19 +37,65 @@ export declare class OperationTraceRegistry {
28
37
  endTrace(traceId: string, opts?: {
29
38
  status?: JobSnapshot["status"];
30
39
  }): void;
40
+ /**
41
+ * Reports a handler that ran without instrumentation. The example is spelled
42
+ * out because the fix is never in the file the developer is looking at: the
43
+ * symptom appears in a controller, the cause is in `main.ts`.
44
+ */
31
45
  private reportMissingInstrumentation;
46
+ /**
47
+ * Classifies a failed operation for transports that report no status code.
48
+ *
49
+ * `IntrinsicException` is the line Nest itself draws between a failure the
50
+ * handler raised on purpose and one that leaked out of it, so it is the line
51
+ * used here: intrinsic errors land in the handled bucket, everything else in
52
+ * the unhandled one. An `HttpException` keeps its own code when that code
53
+ * already reads as handled - a 5xx one would otherwise be counted against the
54
+ * handler that deliberately raised it.
55
+ */
32
56
  private toErrorStatusCode;
33
57
  private setStatusCode;
34
58
  internalStartTraceStep(traceId: TraceId, className: string, methodKey: string, callerId: string | undefined): string | undefined;
35
- internalEndTraceStep(traceId: TraceId, spanId: string | undefined, className: string, methodKey: string, callerId: string | undefined, error?: Error | string | object): void;
59
+ internalEndTraceStep(traceId: TraceId,
60
+ /**
61
+ * Diagnostic label only - it names the span in the two warnings below and
62
+ * is read nowhere else. Absent for a step that never opened, which is the
63
+ * same condition `callerId` reports.
64
+ */
65
+ spanId: string | undefined, className: string, methodKey: string, callerId: string | undefined, error?: Error | string | object): void;
36
66
  addRouteMetadataToTrace(requestId: string, requestMethod: RequestMethod, path: string): void;
67
+ /**
68
+ * Labels a trace with the GraphQL root field being resolved.
69
+ *
70
+ * Only the first root field of a request wins. A document may select several
71
+ * (`{ orders { id } customers { id } }`), and an operation id that changed
72
+ * with the last field to finish would scatter one endpoint's traffic across
73
+ * several rows; first-one-wins is arbitrary but stable. It also means a
74
+ * `/graphql` route label - were one ever set - is not overwritten silently.
75
+ */
37
76
  addGraphQLMetadataToTrace(traceId: TraceId, metadata: {
38
77
  operationId: string;
39
78
  tags?: Record<string, string | number | boolean>;
40
79
  attributes?: RequestSnapshot["attributes"];
41
80
  }): void;
81
+ /**
82
+ * Offset of a span's start from the start of its trace root, in milliseconds.
83
+ *
84
+ * Captured when the span opens rather than when it closes: `startTimestamp` is
85
+ * deleted once the trace ends, and a span that outlives its trace (an un-awaited
86
+ * async call) would otherwise lose its offset entirely.
87
+ */
42
88
  private toStartOffset;
43
89
  captureError(traceId: string, callerId: string | undefined, error: Error | string, tags: Record<string, string | number | boolean>): void;
90
+ /**
91
+ * Drops a trace that will never be plucked, freeing both maps.
92
+ *
93
+ * The HTTP agent calls this when a client aborts: the adapter's response
94
+ * hook rides `finish`, which an aborted response never emits, so without
95
+ * this the snapshot - spans, error payloads, code frames - would stay
96
+ * registered for the life of the process. Nothing is reported; a trace with
97
+ * no response has no status code to file it under.
98
+ */
44
99
  abandonTrace(traceId: TraceId): void;
45
100
  pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
46
101
  getActiveSpan(traceId: string, callerId: string | undefined): OngoingTraceEventNode | undefined;
@@ -5,19 +5,39 @@ import { TraceSpanDelegate } from "../trace-span.delegate.js";
5
5
  import { collectCodeFrames } from "../utils/source-context.util.js";
6
6
  import { CALLER_METADATA_KEY } from "../observe.constants.js";
7
7
  const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
8
+ /**
9
+ * An error the business logic did not model. `IntrinsicException` is what Nest
10
+ * itself uses to tell a deliberately raised failure from a leaked one.
11
+ */
8
12
  const UNHANDLED_ERROR_STATUS_CODE = 500;
13
+ /**
14
+ * A failure the handler raised on purpose. 4xx is what the backend's aggregates
15
+ * count as handled; the exact code only matters when the exception carries one.
16
+ */
9
17
  const HANDLED_ERROR_STATUS_CODE = 400;
10
18
  export class OperationTraceRegistry {
11
19
  als;
12
20
  sourceContext;
13
21
  traceSnapshots = new Map();
22
+ // Keyed by `string | undefined` because a root span has no caller: entries
23
+ // are only ever stored under a real span id, but the lookup domain includes
24
+ // "no caller", which is a legitimate miss rather than a type error.
14
25
  callerIdsByTraceId = new Map();
15
26
  logger = new Logger(OperationTraceRegistry.name);
27
+ /**
28
+ * An application started without `instrument` fails this way on *every*
29
+ * request, and the guidance below is long enough that repeating it verbatim
30
+ * would bury everything else in the log. Full text once, one line after.
31
+ */
16
32
  hasReportedMissingInstrumentation = false;
17
33
  constructor(als, sourceContext = true) {
18
34
  this.als = als;
19
35
  this.sourceContext = sourceContext;
20
36
  }
37
+ /**
38
+ * Builds the error payload attached to a span or snapshot, including the source
39
+ * around each in-app frame when source context is enabled.
40
+ */
21
41
  toErrorPayload(error) {
22
42
  const payload = error instanceof Error
23
43
  ? { message: error.message, stack: error.stack }
@@ -59,19 +79,37 @@ export class OperationTraceRegistry {
59
79
  }
60
80
  if (snapshot.traces.length === 0) {
61
81
  if ("operationId" in snapshot) {
82
+ // An operationId means a handler ran, and zero traces means nothing
83
+ // recorded a span for it. Both at once has one cause: the instance
84
+ // decorator never wrapped the providers, because `instrument` never
85
+ // reached NestFactory.
62
86
  this.reportMissingInstrumentation(snapshot);
63
87
  this.traceSnapshots.delete(traceId);
64
88
  return;
65
89
  }
90
+ // Ignore snapshots that have no traces as that means
91
+ // the request didnt even have a handler in the first place
66
92
  this.traceSnapshots.delete(traceId);
67
93
  return;
68
94
  }
95
+ // Set by `startTrace` and deleted a few lines below, so it is always there
96
+ // for a snapshot still in the registry. The fallback keeps a duration of 0
97
+ // rather than a NaN that would poison every average built over it.
69
98
  const startTimestamp = snapshot.startTimestamp ?? performance.now();
70
99
  snapshot.duration = performance.now() - startTimestamp;
71
100
  const reportedStatusCode = "statusCode" in opts && typeof opts.statusCode === "number"
72
101
  ? opts.statusCode
73
102
  : undefined;
74
103
  const errorStatusCode = "protocol" in snapshot ? snapshot.errorStatusCode : undefined;
104
+ // A root span that threw outranks a success status code reported by the
105
+ // transport. Two cases need this. Transports that carry no status code of
106
+ // their own (RPC, gRPC) end their trace without one at all, and the backend
107
+ // buckets errors by status code alone - so a failing message pattern would
108
+ // otherwise report zero handled *and* zero unhandled errors. GraphQL is the
109
+ // sharper case: it answers 200 even when the resolver threw, reporting the
110
+ // error in the body, so trusting the transport would give a service with a
111
+ // failing resolver a flat zero error rate. 500 marks the failure as
112
+ // unhandled, 4xx as deliberate.
75
113
  const statusCode = errorStatusCode !== undefined &&
76
114
  (reportedStatusCode === undefined || reportedStatusCode < 400)
77
115
  ? errorStatusCode
@@ -87,18 +125,25 @@ export class OperationTraceRegistry {
87
125
  const requestSnapshot = snapshot;
88
126
  requestSnapshot.userId = String(opts.userId);
89
127
  }
90
- delete snapshot.startTimestamp;
128
+ delete snapshot.startTimestamp; // Clean up to avoid confusion
91
129
  if (snapshot.traces && snapshot.traces.length > 0) {
130
+ // Iterate through root traces to check if any have errors
92
131
  for (const trace of snapshot.traces) {
93
132
  if ("error" in trace && trace.error) {
133
+ // If any root trace has an error, we mark the entire snapshot as having an error
94
134
  if (typeof trace.error === "object") {
95
135
  snapshot.error = trace.error;
96
136
  }
97
- break;
137
+ break; // No need to check further once an error is found
98
138
  }
99
139
  }
100
140
  }
101
141
  }
142
+ /**
143
+ * Reports a handler that ran without instrumentation. The example is spelled
144
+ * out because the fix is never in the file the developer is looking at: the
145
+ * symptom appears in a controller, the cause is in `main.ts`.
146
+ */
102
147
  reportMissingInstrumentation(snapshot) {
103
148
  const method = snapshot.attributes?.method;
104
149
  const operation = method
@@ -126,6 +171,16 @@ export class OperationTraceRegistry {
126
171
  `NestFactory.createMicroservice() accepts the same option. Later occurrences of this error are logged on a single line.`,
127
172
  ].join("\n"));
128
173
  }
174
+ /**
175
+ * Classifies a failed operation for transports that report no status code.
176
+ *
177
+ * `IntrinsicException` is the line Nest itself draws between a failure the
178
+ * handler raised on purpose and one that leaked out of it, so it is the line
179
+ * used here: intrinsic errors land in the handled bucket, everything else in
180
+ * the unhandled one. An `HttpException` keeps its own code when that code
181
+ * already reads as handled - a 5xx one would otherwise be counted against the
182
+ * handler that deliberately raised it.
183
+ */
129
184
  toErrorStatusCode(error) {
130
185
  if (!(error instanceof IntrinsicException)) {
131
186
  return UNHANDLED_ERROR_STATUS_CODE;
@@ -151,6 +206,10 @@ export class OperationTraceRegistry {
151
206
  snapshot.refsCounter += 1;
152
207
  const newNodeId = randomUUID();
153
208
  const startTime = performance.now();
209
+ // Records which span owns the thread from here. A no-op unless continuous
210
+ // profiling is on, and the only way profile samples can be attributed to a
211
+ // span: V8 hands back a batch afterwards, so there is nothing to label at
212
+ // the moment a sample fires.
154
213
  activeSliceRecorder()?.enter(traceId, newNodeId, startTime);
155
214
  const newNode = {
156
215
  origin: "auto",
@@ -160,6 +219,11 @@ export class OperationTraceRegistry {
160
219
  startTime,
161
220
  startOffset: this.toStartOffset(snapshot, startTime),
162
221
  children: [],
222
+ // The caller id doubles as the span id rather than a second identifier
223
+ // being minted for it. That is what lets a log line name the span it was
224
+ // written inside: the forwarder reads this exact value out of the async
225
+ // store (CALLER_METADATA_KEY), so the two sides agree by construction
226
+ // instead of by a timing heuristic. It costs a uuid per span on the wire.
163
227
  spanId: newNodeId,
164
228
  };
165
229
  let refsByCaller = this.callerIdsByTraceId.get(traceId);
@@ -169,6 +233,7 @@ export class OperationTraceRegistry {
169
233
  newNode.parent = caller;
170
234
  }
171
235
  else {
236
+ // No caller means insert trace at the root level
172
237
  snapshot.traces.push(newNode);
173
238
  }
174
239
  if (!refsByCaller) {
@@ -178,7 +243,17 @@ export class OperationTraceRegistry {
178
243
  refsByCaller.set(newNodeId, newNode);
179
244
  return newNodeId;
180
245
  }
181
- internalEndTraceStep(traceId, spanId, className, methodKey, callerId, error) {
246
+ internalEndTraceStep(traceId,
247
+ /**
248
+ * Diagnostic label only - it names the span in the two warnings below and
249
+ * is read nowhere else. Absent for a step that never opened, which is the
250
+ * same condition `callerId` reports.
251
+ */
252
+ spanId, className, methodKey,
253
+ // Undefined when `internalStartTraceStep` found no snapshot to open the
254
+ // step against; the lookup below then misses and warns, as it does for any
255
+ // other unknown caller.
256
+ callerId, error) {
182
257
  const snapshot = this.traceSnapshots.get(traceId);
183
258
  if (!snapshot) {
184
259
  this.logger.error(`No snapshot found for traceId: "${traceId}". Cannot end trace step for "${className}#${methodKey}".`);
@@ -197,14 +272,20 @@ export class OperationTraceRegistry {
197
272
  return;
198
273
  }
199
274
  const duration = performance.now() - cursor.startTime;
275
+ // `type`, `startTime` and `parent` are exactly what separates an ongoing
276
+ // node from a complete one, so removing them *is* the conversion the cast
277
+ // below records. They go through a view that admits their absence rather
278
+ // than each needing its own suppression.
200
279
  const completing = cursor;
201
- delete completing.type;
202
- delete completing.startTime;
280
+ delete completing.type; // The node is now complete
281
+ delete completing.startTime; // The duration is now set
203
282
  const parent = cursor.parent;
204
- delete completing.parent;
283
+ delete completing.parent; // Complete nodes carry no parent reference
284
+ // Remove tags if empty
205
285
  if (Object.keys(cursor.tags || {}).length === 0) {
206
286
  delete completing.tags;
207
287
  }
288
+ // Clean up children array if it is empty
208
289
  if (cursor.children.length === 0) {
209
290
  delete completing.children;
210
291
  }
@@ -213,7 +294,12 @@ export class OperationTraceRegistry {
213
294
  if (error && !activeTrace.error) {
214
295
  const isRootSpan = !parent;
215
296
  if (isRootSpan) {
297
+ // Only a root span decides this: an error thrown deeper down may well
298
+ // have been caught and handled by its caller, in which case the
299
+ // operation did not fail at all.
216
300
  snapshot.errorStatusCode = this.toErrorStatusCode(error);
301
+ // If this is the root span, we can directly set the error on the snapshot
302
+ // if it's a non-intrinsic error
217
303
  if (typeof error === "object") {
218
304
  activeTrace.error = this.toErrorPayload(error);
219
305
  }
@@ -233,6 +319,15 @@ export class OperationTraceRegistry {
233
319
  }
234
320
  snapshot.operationId = path;
235
321
  }
322
+ /**
323
+ * Labels a trace with the GraphQL root field being resolved.
324
+ *
325
+ * Only the first root field of a request wins. A document may select several
326
+ * (`{ orders { id } customers { id } }`), and an operation id that changed
327
+ * with the last field to finish would scatter one endpoint's traffic across
328
+ * several rows; first-one-wins is arbitrary but stable. It also means a
329
+ * `/graphql` route label - were one ever set - is not overwritten silently.
330
+ */
236
331
  addGraphQLMetadataToTrace(traceId, metadata) {
237
332
  const snapshot = this.traceSnapshots.get(traceId);
238
333
  if (!snapshot) {
@@ -243,9 +338,19 @@ export class OperationTraceRegistry {
243
338
  snapshot.tags = { ...snapshot.tags, ...metadata.tags };
244
339
  }
245
340
  if (metadata.attributes) {
341
+ // Merged over whatever the transport recorded. Method and status code
342
+ // survive; `originalUrl` is deliberately replaced - the GraphQL document
343
+ // is the informative value, the shared mount path is not.
246
344
  snapshot.attributes = { ...snapshot.attributes, ...metadata.attributes };
247
345
  }
248
346
  }
347
+ /**
348
+ * Offset of a span's start from the start of its trace root, in milliseconds.
349
+ *
350
+ * Captured when the span opens rather than when it closes: `startTimestamp` is
351
+ * deleted once the trace ends, and a span that outlives its trace (an un-awaited
352
+ * async call) would otherwise lose its offset entirely.
353
+ */
249
354
  toStartOffset(snapshot, startTime) {
250
355
  if (typeof snapshot?.startTimestamp !== "number") {
251
356
  return undefined;
@@ -271,9 +376,19 @@ export class OperationTraceRegistry {
271
376
  if (!targetSpan.tags) {
272
377
  targetSpan.tags = {};
273
378
  }
379
+ // Merge tags
274
380
  Object.assign(targetSpan.tags, tags);
275
381
  targetSpan.error = this.toErrorPayload(error);
276
382
  }
383
+ /**
384
+ * Drops a trace that will never be plucked, freeing both maps.
385
+ *
386
+ * The HTTP agent calls this when a client aborts: the adapter's response
387
+ * hook rides `finish`, which an aborted response never emits, so without
388
+ * this the snapshot - spans, error payloads, code frames - would stay
389
+ * registered for the life of the process. Nothing is reported; a trace with
390
+ * no response has no status code to file it under.
391
+ */
277
392
  abandonTrace(traceId) {
278
393
  this.callerIdsByTraceId.delete(traceId);
279
394
  this.traceSnapshots.delete(traceId);
@@ -285,6 +400,7 @@ export class OperationTraceRegistry {
285
400
  this.callerIdsByTraceId.delete(traceId);
286
401
  this.traceSnapshots.delete(traceId);
287
402
  };
403
+ // Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
288
404
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
289
405
  await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
290
406
  if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
@@ -293,6 +409,8 @@ export class OperationTraceRegistry {
293
409
  }
294
410
  }
295
411
  cleanup();
412
+ // These three are what distinguish the registry's working copy from the
413
+ // snapshot the API receives, so removing them is the hand-off.
296
414
  const bookkeeping = snapshot;
297
415
  delete bookkeeping.refsCounter;
298
416
  delete bookkeeping.refsMarkedAsComplete;
@@ -310,18 +428,32 @@ export class OperationTraceRegistry {
310
428
  return activeSpan;
311
429
  }
312
430
  async createManualSpan(traceId, callerId, name, spanFunction) {
431
+ // await new Promise((resolve) => setImmediate(resolve));
313
432
  const activeSpan = this.getActiveSpan(traceId, callerId);
314
433
  if (!activeSpan) {
315
434
  return spanFunction(new TraceSpanDelegate("", name, {}));
316
435
  }
317
436
  const snapshot = this.traceSnapshots.get(traceId);
437
+ // Book the span in the same ledger auto spans use. Completion goes through
438
+ // internalEndTraceStep, which increments refsMarkedAsComplete - without
439
+ // the matching increment here, every completed manual span pushed the
440
+ // completed count one ahead, and a trace holding one leaked auto span plus
441
+ // one manual span read as complete: pluckSnapshot then shipped a
442
+ // half-built tree whose ongoing node still held its circular `parent`
443
+ // reference, and JSON.stringify threw away the whole flush window.
318
444
  if (snapshot) {
319
445
  snapshot.refsCounter += 1;
320
446
  }
321
447
  const newNodeId = randomUUID();
322
448
  const startTime = performance.now();
449
+ // Same as internalStartTraceStep: without an enter, the exit issued on
450
+ // completion no-ops and the span's execution time is silently attributed
451
+ // to its parent - profile correlation for manual spans found nothing.
323
452
  activeSliceRecorder()?.enter(traceId, newNodeId, startTime);
324
453
  const manualSpan = {
454
+ // Same identity rule as auto spans: the span id *is* the caller id it is
455
+ // registered under, so a log line written inside this span carries an id
456
+ // that resolves back to this node.
325
457
  spanId: newNodeId,
326
458
  name,
327
459
  origin: "manual",
@@ -336,11 +468,17 @@ export class OperationTraceRegistry {
336
468
  activeSpan.children.push(manualSpan);
337
469
  this.callerIdsByTraceId.get(traceId)?.set(newNodeId, manualSpan);
338
470
  const onResponse = (res) => {
471
+ // setImmediate
339
472
  this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId);
340
473
  return res;
341
474
  };
342
475
  const onError = (err) => {
476
+ // setTimeout(
477
+ // () =>
343
478
  this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId, err);
479
+ // 0,
480
+ // );
481
+ // Re-throw the error to maintain original behavior
344
482
  throw err;
345
483
  };
346
484
  const tags = {};
@@ -357,6 +495,7 @@ export class OperationTraceRegistry {
357
495
  }
358
496
  catch (err) {
359
497
  onError(err);
498
+ // Re-throw to maintain original behavior
360
499
  throw err;
361
500
  }
362
501
  });
@@ -7,13 +7,32 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
7
7
  private readonly observeAgentSharedBuffer;
8
8
  private readonly als;
9
9
  private readonly logger;
10
+ /**
11
+ * stdout arrives in chunks, not lines: a single write can carry half a line,
12
+ * several lines, or a line split across two calls. Parsing a chunk directly
13
+ * would mangle every log that straddles a boundary, so the trailing fragment
14
+ * is held here until its newline shows up.
15
+ */
10
16
  private partialLine;
11
17
  private originalWrite;
18
+ /**
19
+ * Null only when redaction has been switched off explicitly. Defaulting to on
20
+ * matters more here than anywhere else in the agent: enabling `forwardLogs`
21
+ * moves every log line onto another machine, and the failure mode of getting
22
+ * it wrong is a credential in someone else's database.
23
+ */
12
24
  private readonly redactor;
13
25
  constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
14
26
  onModuleInit(): void;
15
27
  onModuleDestroy(): void;
16
28
  start(): void;
29
+ /**
30
+ * Restores the original stdout.write.
31
+ *
32
+ * Without this the patch outlives the module - which matters in tests, where
33
+ * a torn-down app would keep pushing into a buffer nobody drains, and in any
34
+ * process that recreates the Nest application.
35
+ */
17
36
  private restore;
18
37
  private consume;
19
38
  private flushPartial;