@nestjs/observe 0.3.24 → 0.3.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/README.md +26 -1
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +43 -21
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +244 -97
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  34. package/dist/otlp/otlp-span.mapper.js +16 -8
  35. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  36. package/dist/otlp/otlp-trace-exporter.service.js +71 -6
  37. package/dist/outgoing/http.integration.d.ts +8 -4
  38. package/dist/outgoing/http.integration.js +13 -6
  39. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  40. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  41. package/dist/outgoing/llm/llm-providers.js +72 -22
  42. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  43. package/dist/outgoing/llm/llm-usage.js +72 -25
  44. package/dist/outgoing/mssql.integration.js +16 -2
  45. package/dist/outgoing/mysql2.integration.js +17 -1
  46. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  47. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  48. package/dist/outgoing/pg.integration.d.ts +3 -2
  49. package/dist/outgoing/pg.integration.js +39 -11
  50. package/dist/outgoing/sql-statement.util.js +106 -14
  51. package/dist/outgoing/undici.integration.d.ts +13 -0
  52. package/dist/outgoing/undici.integration.js +68 -0
  53. package/dist/protocols/bull-observe-agent.service.js +2 -12
  54. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  55. package/dist/protocols/deferred-trace-completion.js +36 -6
  56. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  57. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  58. package/dist/protocols/graphql-operation-parser.js +72 -18
  59. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  60. package/dist/protocols/http-observe-agent.service.js +177 -59
  61. package/dist/protocols/job-trace-runner.d.ts +35 -3
  62. package/dist/protocols/job-trace-runner.js +136 -31
  63. package/dist/protocols/queue-observe-agent.service.js +44 -20
  64. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  65. package/dist/protocols/rpc-observe-agent.service.js +225 -49
  66. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  67. package/dist/protocols/ws-observe-agent.service.js +226 -20
  68. package/dist/services/index.d.ts +1 -1
  69. package/dist/services/index.js +1 -1
  70. package/dist/services/logger-patcher.service.js +3 -4
  71. package/dist/services/operation-trace.registry.d.ts +45 -1
  72. package/dist/services/operation-trace.registry.js +418 -35
  73. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  74. package/dist/services/stdout-forwarder.service.js +288 -51
  75. package/dist/services/tracer.service.d.ts +23 -0
  76. package/dist/services/tracer.service.js +99 -7
  77. package/dist/utils/capture-request.util.d.ts +3 -1
  78. package/dist/utils/capture-request.util.js +100 -12
  79. package/dist/utils/fit-to-length.util.js +33 -10
  80. package/dist/utils/log-line.parser.d.ts +14 -0
  81. package/dist/utils/log-line.parser.js +7 -3
  82. package/dist/utils/log-redactor.d.ts +14 -0
  83. package/dist/utils/log-redactor.js +512 -61
  84. package/dist/utils/operation-state.util.d.ts +39 -0
  85. package/dist/utils/operation-state.util.js +50 -0
  86. package/dist/utils/redact-url-query.d.ts +26 -4
  87. package/dist/utils/redact-url-query.js +184 -32
  88. package/dist/utils/sensitive-keys.d.ts +4 -1
  89. package/dist/utils/sensitive-keys.js +48 -10
  90. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  91. package/dist/utils/shared-hook-slot.util.js +103 -0
  92. package/dist/utils/source-context.util.d.ts +8 -0
  93. package/dist/utils/source-context.util.js +88 -19
  94. package/dist/utils/source-map-resolver.util.js +8 -2
  95. package/dist/utils/trace-context.util.d.ts +20 -0
  96. package/dist/utils/trace-context.util.js +50 -6
  97. package/package.json +4 -1
@@ -11,17 +11,20 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var RpcObserveAgentService_1;
14
- import { Inject, Injectable, Logger, } from "@nestjs/common";
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { ModulesContainer } from "@nestjs/core";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
- import { OBSERVE_OPTIONS, TRACE_REGISTRY_KEY } from "../observe.constants.js";
20
+ import { OBSERVE_OPTIONS, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
21
+ import { handedOnTraceContext } from "../utils/trace-context.util.js";
21
22
  import { continueHandedOnTrace } from "../utils/trace-handoff.util.js";
22
23
  import { uuidv7 } from "../utils/uuid-v7.util.js";
24
+ import { setAgentHook } from "../utils/shared-hook-slot.util.js";
23
25
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
24
26
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
27
+ import { endOperation, OPERATION_STATE_KEY, openOperation, } from "../utils/operation-state.util.js";
25
28
  let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
26
29
  asyncLocalStorage;
27
30
  options;
@@ -32,11 +35,22 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
32
35
  logger = new Logger(RpcObserveAgentService_1.name);
33
36
  rpcTargetAddedSubscription;
34
37
  /**
35
- * Assigned in `onModuleInit`. Every use below is reached only through the
38
+ * Assigned in the constructor. Every use below is reached only through the
36
39
  * hooks registered there, after a successful load - a service without the
37
40
  * package has no RPC target to hook.
38
41
  */
39
42
  microservices;
43
+ /**
44
+ * The registry key each operation was started under, by the context Nest
45
+ * hands its end hook. That hook cannot ask the async store: Nest runs it
46
+ * from the teardown of the handler's reply stream, in the async context of
47
+ * whatever ended the stream - a TCP socket's `close`, a gRPC cancellation,
48
+ * a subject another message's handler emitted into. As
49
+ * `HttpObserveAgentService` keeps its keys by request.
50
+ */
51
+ registryKeys = new WeakMap();
52
+ /** The operation each context was started for - see `rememberOperation`. */
53
+ operations = new WeakMap();
40
54
  constructor(asyncLocalStorage, options, modulesContainer, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService) {
41
55
  this.asyncLocalStorage = asyncLocalStorage;
42
56
  this.options = options;
@@ -44,15 +58,23 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
44
58
  this.operationTraceRegistry = operationTraceRegistry;
45
59
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
46
60
  this.traceSamplerService = traceSamplerService;
47
- }
48
- onModuleInit() {
61
+ // From the constructor, while Nest builds the providers: Nest announces
62
+ // a server when it constructs the microservice around it, inside
63
+ // `createMicroservice()` or `connectMicroservice()`, so the hooks are in
64
+ // place before the application is handed the server and can set hooks
65
+ // of its own on it (`getTransportServer()`), which then run beside them.
49
66
  this.microservices = this.loadMicroservices();
50
67
  if (!this.microservices) {
51
68
  return;
52
69
  }
53
- this.rpcTargetAddedSubscription = this.modulesContainer
54
- .getRpcTargetRegistry?.()
55
- .subscribe((target) => this.registerRpcHooks(target));
70
+ try {
71
+ this.rpcTargetAddedSubscription = this.modulesContainer
72
+ .getRpcTargetRegistry?.()
73
+ .subscribe((target) => this.registerRpcHooks(target));
74
+ }
75
+ catch (error) {
76
+ this.logger.warn(`RPC operations will not be instrumented: the microservice registry could not be subscribed to: ${describePeerLoadError(error)}`);
77
+ }
56
78
  }
57
79
  onModuleDestroy() {
58
80
  if (this.rpcTargetAddedSubscription) {
@@ -62,9 +84,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
62
84
  /**
63
85
  * Loads `@nestjs/microservices` without a static import, so a service that
64
86
  * exposes no microservice need not install the package. Loaded here rather
65
- * than lazily because the target registry is subscribed from `onModuleInit`,
66
- * and a dynamic `import()` would resolve after a target may already have
67
- * been announced.
87
+ * than lazily because the target registry is subscribed from the
88
+ * constructor, and a dynamic `import()` would resolve after a target may
89
+ * already have been announced.
68
90
  */
69
91
  loadMicroservices() {
70
92
  const result = loadOptionalPeer("@nestjs/microservices");
@@ -81,20 +103,24 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
81
103
  }
82
104
  return result.module;
83
105
  }
106
+ /**
107
+ * Sets the agent's processing hooks on a server, beside any the application
108
+ * sets on it - see `composeStartHook`.
109
+ */
84
110
  registerRpcHooks(target) {
85
111
  // Return `done()`'s promise, as Nest's default hook does. Nest's servers
86
112
  // hand it back from their message handlers: kafkajs waits on it to commit
87
113
  // the offset or retry the message, and recent Nest versions log its
88
114
  // rejection for most other transports.
89
- target.setOnProcessingStartHook((transportId, ctx, done) => {
115
+ setAgentHook(target, "setOnProcessingStartHook", (transportId, ctx, done) => {
90
116
  if (transportId === this.microservices.Transport.GRPC) {
91
117
  return this.startGrpcRequestTracing(transportId, ctx, done);
92
118
  }
93
- return this.startRpcRequestTracing(transportId, ctx, done);
94
- });
95
- target.setOnProcessingEndHook((transportId, ctx) => {
119
+ return this.startRpcRequestTracing(transportId, ctx, done, target);
120
+ }, composeStartHook);
121
+ setAgentHook(target, "setOnProcessingEndHook", (transportId, ctx) => {
96
122
  this.endRpcRequestTracing(transportId, ctx);
97
- });
123
+ }, composeEndHook);
98
124
  }
99
125
  /**
100
126
  * Names the transport for the snapshot's `protocol` field.
@@ -108,7 +134,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
108
134
  ? transportId.description ?? "custom"
109
135
  : this.microservices.Transport[transportId];
110
136
  }
111
- startRpcRequestTracing(transportId, ctx, done) {
137
+ startRpcRequestTracing(transportId, ctx, done,
138
+ /** The server the message arrived at. */
139
+ target) {
112
140
  // The same map `run` is given, rather than `getStore()` inside the callback:
113
141
  // identical object, one lookup fewer, and it is known to exist.
114
142
  const store = new Map();
@@ -119,6 +147,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
119
147
  // execution before option callbacks can reach another operation's trace.
120
148
  const registryKey = uuidv7();
121
149
  store.set(TRACE_REGISTRY_KEY, registryKey);
150
+ this.rememberRegistryKey(ctx, registryKey);
151
+ // Ended by the end hook, recorded or not: see `liveTraceId`.
152
+ this.rememberOperation(ctx, openOperation(store));
122
153
  // With OpenTelemetry interop on, the handler runs in the W3C trace
123
154
  // context the message was sent in, for an OpenTelemetry SDK in this
124
155
  // process - see `continueHandedOnTrace`. Recorded or not, as an
@@ -129,6 +160,13 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
129
160
  const handle = handedOn === undefined
130
161
  ? done
131
162
  : () => continueHandedOnTrace(handedOn, traceId, done);
163
+ // And the handler's span goes under the span that sent the message, for
164
+ // `otlp`, while the calls it makes carry the caller's decision on - as
165
+ // a request's do with the `traceparent` it arrived with.
166
+ const traceContext = handedOnTraceContext(handedOn, traceId);
167
+ if (traceContext) {
168
+ store.set(TRACE_CONTEXT_KEY, traceContext);
169
+ }
132
170
  setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
133
171
  if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
134
172
  return handle();
@@ -142,9 +180,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
142
180
  }
143
181
  this.operationTraceRegistry.startTrace(registryKey, {
144
182
  protocol: this.toProtocolName(transportId),
145
- operationId: this.getOperationIdFromContext(ctx),
183
+ operationId: this.getOperationIdFromContext(ctx, target),
146
184
  tags: this.options.rpc?.tags,
147
- }, traceId);
185
+ }, traceId, traceContext);
148
186
  return handle();
149
187
  });
150
188
  }
@@ -162,39 +200,66 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
162
200
  return this.asyncLocalStorage.run(store, () => {
163
201
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, call, this.options, this.logger);
164
202
  store.set(this.options.traceIdKey, traceId);
165
- // The key must precede callbacks here too, before the deferred startup.
203
+ // The key must precede callbacks here too.
166
204
  const registryKey = uuidv7();
167
205
  store.set(TRACE_REGISTRY_KEY, registryKey);
206
+ // Nest ends a gRPC call with its request message rather than the
207
+ // context it started it with, so the key is kept by both.
208
+ this.rememberRegistryKey(call, registryKey);
209
+ this.rememberRegistryKey(call?.request, registryKey);
210
+ const operation = openOperation(store);
211
+ this.rememberOperation(call, operation);
212
+ this.rememberOperation(call?.request, operation);
213
+ // As for a message: the call's span goes under the caller's for `otlp`,
214
+ // and the calls the handler makes carry its decision on. Read now, while
215
+ // the span a gRPC instrumentation opened for the call is the active one.
216
+ // Unlike a message's, the handler is not run in the caller's trace: the
217
+ // SDK's gRPC instrumentation carries it there.
218
+ const traceContext = this.openTelemetryInteropOn()
219
+ ? handedOnTraceContext(grpcTraceparent(call), traceId)
220
+ : undefined;
221
+ if (traceContext) {
222
+ store.set(TRACE_CONTEXT_KEY, traceContext);
223
+ }
168
224
  setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
169
- return new Promise((resolve) => {
170
- // A throw in this timer escapes the promise: `done()` never runs, and
171
- // the exception is uncaught. Both decisions below are guarded.
172
- setTimeout(() => {
173
- if (shouldIgnoreSafely(this.options.grpc?.ignore, [call], this.options.grpc, this.logger, "grpc")) {
174
- return resolve(done());
175
- }
176
- const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
177
- call,
178
- });
179
- if (!shouldCapture) {
180
- return resolve(done());
181
- }
182
- this.operationTraceRegistry.startTrace(registryKey, {
183
- protocol: this.toProtocolName(transportId),
184
- operationId: call.operationId,
185
- tags: this.options.grpc?.tags,
186
- }, traceId);
187
- resolve(done());
188
- }, 0);
225
+ // `done` runs before the hook returns, as for any other transport. Nest
226
+ // listens for the call's `cancelled` and `end` events inside it, and
227
+ // grpc-js emits `cancelled` once: run from a timer, a call cancelled or
228
+ // past its deadline on arrival had nothing listening, and a
229
+ // client-streaming handler waited for good on a request stream that
230
+ // never ended, its trace held in the registry.
231
+ if (shouldIgnoreSafely(this.options.grpc?.ignore, [call], this.options.grpc, this.logger, "grpc")) {
232
+ return done();
233
+ }
234
+ const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
235
+ call,
189
236
  });
237
+ if (!shouldCapture) {
238
+ return done();
239
+ }
240
+ this.operationTraceRegistry.startTrace(registryKey, {
241
+ protocol: this.toProtocolName(transportId),
242
+ operationId: call.operationId,
243
+ tags: this.options.grpc?.tags,
244
+ }, traceId, traceContext);
245
+ return done();
190
246
  });
191
247
  }
192
248
  endRpcRequestTracing(transportId, ctx) {
193
- const store = this.asyncLocalStorage.getStore();
194
- if (!store) {
195
- return;
196
- }
197
- const registryKey = store.get(TRACE_REGISTRY_KEY);
249
+ // The key this context was started under, wherever its reply stream
250
+ // ended. The store answers only for a context no key could be kept by:
251
+ // a gRPC call with no request message of its own, as a client stream has
252
+ // none.
253
+ endOperation((typeof ctx === "object" && ctx !== null
254
+ ? this.operations.get(ctx)
255
+ : undefined) ??
256
+ this.asyncLocalStorage
257
+ .getStore()
258
+ ?.get(OPERATION_STATE_KEY));
259
+ const registryKey = (typeof ctx === "object" && ctx !== null
260
+ ? this.registryKeys.get(ctx)
261
+ : undefined) ??
262
+ this.asyncLocalStorage.getStore()?.get(TRACE_REGISTRY_KEY);
198
263
  if (typeof registryKey !== "string" ||
199
264
  !this.operationTraceRegistry.hasTrace(registryKey)) {
200
265
  return;
@@ -218,15 +283,73 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
218
283
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
219
284
  }, this.logger, isGrpc ? "grpc" : "rpc", () => this.operationTraceRegistry.hasOpenSpans(registryKey));
220
285
  }
221
- getOperationIdFromContext(ctx) {
286
+ /**
287
+ * Keeps `registryKey` for the end hook to find by `ctx`. A custom
288
+ * transporter delivers a context of its own making, and a gRPC call need not
289
+ * carry a request message: what cannot key a `WeakMap` is left to the store.
290
+ */
291
+ rememberRegistryKey(ctx, registryKey) {
292
+ if (typeof ctx === "object" && ctx !== null) {
293
+ this.registryKeys.set(ctx, registryKey);
294
+ }
295
+ }
296
+ /** As `rememberRegistryKey`, for the operation the end hook ends. */
297
+ rememberOperation(ctx, operation) {
298
+ if (typeof ctx === "object" && ctx !== null) {
299
+ this.operations.set(ctx, operation);
300
+ }
301
+ }
302
+ /**
303
+ * The route a message's handler is registered under, for the pattern or
304
+ * topic as its sender wrote it. Nest parses a pattern that is JSON and finds
305
+ * the handler by the normalised outcome, so one handler answers to any
306
+ * number of texts - other whitespace, an escape, a key given twice. Named by
307
+ * the text, each was an operation of the sender's choosing, and a route an
308
+ * `@Objective` on the handler was declared for anew.
309
+ *
310
+ * The route is taken only where the server finds that route's handler for
311
+ * the text: a handler reached through a wildcard keeps the text it was
312
+ * reached on, and so does anything the server cannot be asked about.
313
+ */
314
+ toRoute(text, target) {
315
+ if (!target) {
316
+ return text;
317
+ }
318
+ try {
319
+ const handlers = target.getHandlers();
320
+ // What a Nest client sends: the route itself. One lookup, no parse.
321
+ if (handlers.has(text)) {
322
+ return text;
323
+ }
324
+ // Protected in Nest's typings, so read by shape.
325
+ const route = target.getRouteFromPattern?.(text);
326
+ if (typeof route !== "string" || route === text) {
327
+ return text;
328
+ }
329
+ const handler = handlers.get(route);
330
+ return handler !== undefined &&
331
+ handler === target.getHandlerByPattern(text)
332
+ ? route
333
+ : text;
334
+ }
335
+ catch {
336
+ return text;
337
+ }
338
+ }
339
+ /**
340
+ * Kafka, MQTT, RabbitMQ and TCP find a message's handler by the text its
341
+ * context carries - see `toRoute`. NATS and Redis find it by the
342
+ * subscription the message came in on.
343
+ */
344
+ getOperationIdFromContext(ctx, target) {
222
345
  const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
223
346
  switch (true) {
224
347
  case ctx instanceof KafkaContext:
225
348
  case ctx instanceof MqttContext:
226
- return ctx.getTopic();
349
+ return this.toRoute(ctx.getTopic(), target);
227
350
  case ctx instanceof RmqContext:
228
351
  case ctx instanceof TcpContext:
229
- return ctx.getPattern();
352
+ return this.toRoute(ctx.getPattern(), target);
230
353
  case ctx instanceof RedisContext:
231
354
  return ctx.getChannel();
232
355
  case ctx instanceof NatsContext:
@@ -237,7 +360,9 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
237
360
  // routing key. Throwing here would fail the message before `done()`
238
361
  // ever ran, so fall back to a conventional accessor when one exists.
239
362
  const pattern = ctx?.getPattern?.();
240
- return typeof pattern === "string" ? pattern : "unknown";
363
+ return typeof pattern === "string"
364
+ ? this.toRoute(pattern, target)
365
+ : "unknown";
241
366
  }
242
367
  }
243
368
  }
@@ -251,6 +376,40 @@ RpcObserveAgentService = RpcObserveAgentService_1 = __decorate([
251
376
  TraceSamplerService])
252
377
  ], RpcObserveAgentService);
253
378
  export { RpcObserveAgentService };
379
+ /**
380
+ * The start hook the server is given: the application's outside, and the
381
+ * agent's inside the `done` it is handed, returning what the application's
382
+ * returns. The application's hook decides whether a message is handled at
383
+ * all, and the agent opens a trace only once it is: one the application
384
+ * refuses by never calling `done` leaves nothing behind, where the other way
385
+ * round each would leave a trace open in the registry.
386
+ */
387
+ function composeStartHook(application, agent) {
388
+ if (!application) {
389
+ return agent;
390
+ }
391
+ return function (transportId, ctx, done) {
392
+ return application.call(this, transportId, ctx, () => agent.call(this, transportId, ctx, done));
393
+ };
394
+ }
395
+ /**
396
+ * The end hook the server is given: the agent's first, inside the
397
+ * application's as its start hook is, then the application's whatever the
398
+ * agent's did.
399
+ */
400
+ function composeEndHook(application, agent) {
401
+ if (!application) {
402
+ return agent;
403
+ }
404
+ return function (transportId, ctx) {
405
+ try {
406
+ agent.call(this, transportId, ctx);
407
+ }
408
+ finally {
409
+ application.call(this, transportId, ctx);
410
+ }
411
+ };
412
+ }
254
413
  /**
255
414
  * The `traceparent` the sending service's agent put in the packet's metadata
256
415
  * beside `x-request-id` - see `traceparentToHandOn` - on a transport whose
@@ -272,3 +431,20 @@ function handedOnTraceparent(ctx) {
272
431
  return undefined;
273
432
  }
274
433
  }
434
+ /**
435
+ * The `traceparent` a gRPC call's metadata carries - a caller instrumented
436
+ * with OpenTelemetry sends one, and so does one running the agent with
437
+ * `openTelemetry` on - read off grpc-js's `Metadata`, whichever Nest release
438
+ * handed the call over.
439
+ */
440
+ function grpcTraceparent(call) {
441
+ try {
442
+ const metadata = call.metadata;
443
+ const value = metadata?.get?.("traceparent")?.[0];
444
+ return typeof value === "string" ? value : undefined;
445
+ }
446
+ catch {
447
+ // Metadata that cannot be read carries nothing to continue.
448
+ return undefined;
449
+ }
450
+ }
@@ -11,7 +11,8 @@ import { KeyOf } from "../types/key-of.type.js";
11
11
  * processing hooks, so the one place every `@SubscribeMessage()` handler
12
12
  * passes through is patched instead: `WsContextCreator.create`, which builds
13
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 -
14
+ * returns, and subscribing to the stream it resolves to in the same store,
15
+ * puts the whole chain inside the trace, whichever platform adapter -
15
16
  * socket.io, ws - delivers the message.
16
17
  */
17
18
  export declare class WsObserveAgentService<Store extends Record<string, unknown>> {
@@ -21,19 +22,68 @@ export declare class WsObserveAgentService<Store extends Record<string, unknown>
21
22
  private readonly traceSamplerService;
22
23
  private readonly asyncLocalStorage;
23
24
  private readonly logger;
25
+ private readonly tracesByClient;
26
+ private readonly standIns;
24
27
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, traceSamplerService: TraceSamplerService, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
25
28
  private loadContextCreator;
26
29
  private patchContextCreator;
27
30
  /**
31
+ * The handler Nest is given for a `@SubscribeMessage()` method: the same
32
+ * method, called through the instance, telling the message when it runs.
33
+ *
28
34
  * Nest reads a gateway's handlers off the class prototype and applies them
29
35
  * to the instance, which steps around the instrumentation proxy - the one
30
36
  * method of the whole chain that would go unrecorded is the handler itself,
31
37
  * and a handler that throws before calling anything leaves no span at all.
38
+ * The stand-in calls the same method through the instance instead.
39
+ *
40
+ * Behind an interceptor, the chain is cold: Nest's proxy resolves to a
41
+ * stream once the guards have run, and the interceptors, the pipes and the
42
+ * handler run only when the adapter subscribes to it. The stand-in marks
43
+ * the message's state when it is called, so the trace can tell which of
44
+ * the two it was handed, and ends that trace when the handler returns a
45
+ * stream of its own.
46
+ *
47
+ * Guards, pipes, filters and the message pattern are all looked up as
48
+ * metadata on the callback, so that metadata is carried over - once per
49
+ * method, since on a request-scoped path `create` runs for every message.
50
+ */
51
+ private standInFor;
52
+ /**
53
+ * Drops a message's trace when its client goes away before the handler
54
+ * settles, and returns what stops watching for that once the trace ends.
32
55
  *
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.
56
+ * A handler waiting on its client - an acknowledgement without a timeout,
57
+ * the client's next frame - never settles once the client has gone, and
58
+ * nothing else would end its trace: every client that hung up on one left
59
+ * its snapshot registered for the life of the process, and a client that
60
+ * reconnects can leave as many as it likes.
61
+ *
62
+ * One listener per client, however many messages it has in flight, on the
63
+ * events Nest's adapters stop a client's messages at: socket.io's
64
+ * `disconnect`, `ws`' `close`. Dropped at once, as the HTTP agent drops an
65
+ * aborted request: an abandoned trace is never reported, and the registry
66
+ * lets a handler that outlives its client end its spans on a trace that is
67
+ * gone. A client that is no event emitter - a custom adapter's - is not
68
+ * watched.
36
69
  */
37
- private routeThroughInstance;
70
+ private abandonWhenClientLeaves;
38
71
  private traceMessage;
72
+ /**
73
+ * The chain's stream, subscribed in the message's store.
74
+ *
75
+ * Nest's adapters subscribe to what the chain resolves to from the socket's
76
+ * own events, outside the store the message was started in. Behind an
77
+ * interceptor that stream is all of the chain past the guards - the
78
+ * interceptors, the pipes, the handler, the exception filter - and for a
79
+ * handler that returns a stream, the stream and the filter its error goes
80
+ * to. Run without the store, they were missing from the trace, and
81
+ * `TracerService` failed in them.
82
+ *
83
+ * `end` is called at the stream's first value, error or completion, and
84
+ * `abandon` when the subscription is torn down before any: Nest's adapters
85
+ * unsubscribe a client's messages when it disconnects. Both are no-ops once
86
+ * either has run.
87
+ */
88
+ private subscribeInStore;
39
89
  }