@nestjs/observe 0.3.25 → 0.3.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +55 -2
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +201 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -15,11 +15,15 @@ import { Inject, Injectable, Logger } from "@nestjs/common";
15
15
  import { DiscoveryService, MetadataScanner, ModuleRef } from "@nestjs/core";
16
16
  import { AsyncLocalStorage } from "async_hooks";
17
17
  import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.js";
18
+ import { rawReceiverOf } from "../instrument/raw-receiver.js";
18
19
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
19
20
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
22
+ import { setAgentHook } from "../utils/shared-hook-slot.util.js";
23
+ import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
24
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
25
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
26
+ import { endOperation, OPERATION_STATE_KEY, openOperation, } from "../utils/operation-state.util.js";
23
27
  /**
24
28
  * Protocol recorded for a GraphQL operation that arrived over something other
25
29
  * than an instrumented HTTP request. A query over HTTP keeps `http` as its
@@ -36,6 +40,12 @@ const GRAPHQL_PROTOCOL = "graphql";
36
40
  const RESOLVER_TYPE_METADATA = "graphql:resolver_type";
37
41
  const RESOLVER_NAME_METADATA = "graphql:resolver_name";
38
42
  const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
43
+ /**
44
+ * Where the start hook the host is given keeps both sides' state, on what it
45
+ * returns: this service's, and whatever the application's own start hook
46
+ * returned, each handed back to the end hook it belongs to.
47
+ */
48
+ const SHARED_STATE = Symbol("nestjs.observe.graphqlRequestState");
39
49
  /**
40
50
  * GraphQL operation instrumentation.
41
51
  *
@@ -51,7 +61,8 @@ const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
51
61
  * document is processed, `setOnRequestEndHook` once it has been, right before
52
62
  * the response goes out. Whatever the start hook returns is handed back as
53
63
  * `state`, which is what lets one span be opened in the first and closed in the
54
- * second. This service claims both and gives each operation a span.
64
+ * second. This service uses both and gives each operation a span, beside any
65
+ * hooks the application sets there - see `composeStartHook`.
55
66
  *
56
67
  * The span goes into the trace the HTTP agent already opened whenever there is
57
68
  * one, which keeps the shape a reader expects: one snapshot per HTTP request,
@@ -85,6 +96,23 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
85
96
  * after the schema is built.
86
97
  */
87
98
  resolverIndex;
99
+ /**
100
+ * The operations each async store has open, in the order they started.
101
+ *
102
+ * Usually one. A batched HTTP request (Apollo's `allowBatchedHttpRequests`)
103
+ * is the exception: its operations run at once in the one store the
104
+ * request has, so the caller a later one found there was the span of the
105
+ * one before it - a sibling, not a caller - and they end in any order.
106
+ * Nested that way, the trace was as deep as the client made the batch
107
+ * long, and a failure behind the first operation was on no root span, so
108
+ * the request was reported as a success.
109
+ *
110
+ * Beside the store rather than in it: a span's store is a copy of its
111
+ * caller's, and an operation started inside the copy really is a callee.
112
+ * Weakly keyed, so an unmatched start - see `onRequestEnd` - leaves
113
+ * nothing behind once the request's store is gone.
114
+ */
115
+ openOperationsByStore = new WeakMap();
88
116
  constructor(asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService, moduleRef, discoveryService, metadataScanner) {
89
117
  this.asyncLocalStorage = asyncLocalStorage;
90
118
  this.options = options;
@@ -94,6 +122,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
94
122
  this.moduleRef = moduleRef;
95
123
  this.discoveryService = discoveryService;
96
124
  this.metadataScanner = metadataScanner;
125
+ this.patchResolversExplorer();
97
126
  // Attempted twice, and idempotent, because `GraphQLModule` may be
98
127
  // instantiated on either side of this service. Whichever module Nest
99
128
  // reaches first, one of the two attempts lands: if GraphQLModule came
@@ -147,10 +176,130 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
147
176
  this.logger.warn("The installed version of @nestjs/graphql does not expose the GraphQL request lifecycle hooks ('setOnRequestStartHook' / 'setOnRequestEndHook'), so GraphQL operations cannot be instrumented. Upgrade @nestjs/graphql to collect per-operation traces.");
148
177
  return;
149
178
  }
150
- host.setOnRequestStartHook((ctx) => this.onRequestStart(ctx));
151
- host.setOnRequestEndHook((ctx) => this.onRequestEnd(ctx));
179
+ if (this.isPatched) {
180
+ // The other attempt landed while this one waited for the import.
181
+ return;
182
+ }
183
+ // The host's hooks are public API, and the application's to set as well:
184
+ // a check that refuses a document by throwing from the start hook, an
185
+ // audit record written in the end hook. Shared, so neither replaces the
186
+ // other, whichever is set first. The getters hand the application its own
187
+ // hooks - Nest calls the hooks through `onRequestStart` and
188
+ // `onRequestEnd`, never through them.
189
+ setAgentHook(host, "setOnRequestStartHook", (ctx) => this.onRequestStart(ctx), (application, agent) => this.composeStartHook(application, agent), { getter: "getOnRequestStartHook", repointGetter: true });
190
+ setAgentHook(host, "setOnRequestEndHook", (ctx) => this.onRequestEnd(ctx), composeEndHook, { getter: "getOnRequestEndHook", repointGetter: true });
152
191
  this.isPatched = true;
153
192
  }
193
+ /**
194
+ * Has `@nestjs/graphql` apply a resolver's methods to the instance itself
195
+ * where the instrumentation proxy cannot be their receiver.
196
+ *
197
+ * The explorer reads each `@Query`, `@Mutation`, `@Subscription` and
198
+ * `@ResolveField` method off the class prototype and applies it to the
199
+ * instance the container holds, which is the proxy. For a class with
200
+ * private members (`this.#x`), whose methods only the instance itself can
201
+ * run against, the first such read threw: the proxy only helps the methods
202
+ * read through it. `createContextCallback` is where every one of them is
203
+ * paired with its instance, the field resolvers' fast path included, so
204
+ * that is where the instance behind the proxy is handed over instead -
205
+ * what the explorer would have held without the agent. Only the receiver
206
+ * changes: the method is still the class's own, so `getHandler()`, guards,
207
+ * pipes and interceptors see what they saw before, and no span is added,
208
+ * as none is for any other resolver. A request-scoped resolver reads its
209
+ * method through the instance already, and is left alone.
210
+ *
211
+ * Patched on the prototype from the constructor, which Nest runs before any
212
+ * `onModuleInit`, `GraphQLModule`'s included, where the explorer does its
213
+ * work - synchronously, for the reason given on `loadOptionalPeer`. The
214
+ * original is parked under a symbol, so a second agent replaces the wrapper
215
+ * instead of wrapping it again.
216
+ */
217
+ patchResolversExplorer() {
218
+ // The entry point first, although it does not export the explorer: the
219
+ // explorer's file sits on an import cycle that only resolves when the
220
+ // package is entered the way an application enters it. Loaded on its
221
+ // own, it throws "Cannot access 'ResolversExplorerService' before
222
+ // initialization".
223
+ const entryPoint = loadOptionalPeer("@nestjs/graphql");
224
+ if (!entryPoint.installed || !entryPoint.module) {
225
+ // An optional peer; absent, or unable to load, it serves no resolvers.
226
+ return;
227
+ }
228
+ let explorer = entryPoint.module.ResolversExplorerService;
229
+ let loadError;
230
+ if (!explorer) {
231
+ const deepPath = loadOptionalPeer("@nestjs/graphql", "@nestjs/graphql/dist/services/resolvers-explorer.service.js");
232
+ if (deepPath.installed) {
233
+ explorer = deepPath.module?.ResolversExplorerService;
234
+ loadError = deepPath.error;
235
+ }
236
+ }
237
+ const prototype = explorer?.prototype;
238
+ const originalCreate = (prototype?.[ORIGINAL_CREATE_CONTEXT_CALLBACK] ??
239
+ prototype?.createContextCallback);
240
+ if (!prototype || typeof originalCreate !== "function") {
241
+ // Worth saying out loud: the symptom otherwise is a resolver that
242
+ // fails on its own private members for no visible reason.
243
+ const cause = loadError ? `: ${describePeerLoadError(loadError)}` : "";
244
+ this.logger.warn(`The installed version of @nestjs/graphql does not expose 'ResolversExplorerService.createContextCallback', so resolvers that use private members (#field) will throw when instrumented${cause}. Skipping patching.`);
245
+ return;
246
+ }
247
+ prototype[ORIGINAL_CREATE_CONTEXT_CALLBACK] = originalCreate;
248
+ prototype.createContextCallback = function (instance, resolverPrototype, wrapper, ...rest) {
249
+ // rest: [moduleRef, resolver, isRequestScoped, transform]
250
+ const receiver = rest[2] === true ? instance : resolverReceiverOf(instance, wrapper);
251
+ return originalCreate.call(this, receiver, resolverPrototype, wrapper, ...rest);
252
+ };
253
+ }
254
+ /**
255
+ * The start hook the host is given: this service's part first, so the span
256
+ * covers the application's hook, then the application's, whose result is
257
+ * kept for its own end hook.
258
+ *
259
+ * An application's start hook that throws refuses the document: the driver
260
+ * answers with the error and calls no end hook. The span is closed here
261
+ * then, with the application's error, so the refusal is recorded as a
262
+ * failed operation. A start hook that returns a promise gets one back, and
263
+ * only then - a driver that awaits the hook awaits it, and one that does
264
+ * not hands it to the end hook as the state, which is why the pair is also
265
+ * kept on the promise itself. Its rejection closes the span the same way,
266
+ * and travels on in the promise returned, to a driver that awaits it.
267
+ */
268
+ composeStartHook(application, agent) {
269
+ const refuse = (state, error) => this.closeRefused(state, error);
270
+ return function (ctx) {
271
+ const observe = agent.call(this, ctx);
272
+ let returned;
273
+ try {
274
+ returned = application?.call(this, ctx);
275
+ }
276
+ catch (error) {
277
+ refuse(observe, error);
278
+ throw error;
279
+ }
280
+ if (!isThenable(returned)) {
281
+ return toSharedState({ observe, application: returned });
282
+ }
283
+ const settled = Promise.resolve(returned).then((value) => toSharedState({ observe, application: value }), (error) => {
284
+ refuse(observe, error);
285
+ throw error;
286
+ });
287
+ // Handled here, as a driver that does not await it never does: its
288
+ // rejection would otherwise be one only the agent made, beside the
289
+ // application's own promise, which the application may well handle.
290
+ // A driver that awaits it still sees the rejection.
291
+ settled.catch(() => undefined);
292
+ return Object.defineProperty(settled, SHARED_STATE, {
293
+ value: { observe, application: returned },
294
+ });
295
+ };
296
+ }
297
+ closeRefused(state, error) {
298
+ if (!state) {
299
+ return;
300
+ }
301
+ this.endOperation(state, error ?? new Error("Refused by a GraphQL request start hook"));
302
+ }
154
303
  /**
155
304
  * Opens a span for the operation about to be processed.
156
305
  *
@@ -173,7 +322,37 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
173
322
  ...parsed,
174
323
  operationName,
175
324
  });
325
+ const store = this.asyncLocalStorage.getStore();
326
+ // The registry key, where the transport in front gave the request one
327
+ // of its own; the trace id otherwise, which is then the key as well.
328
+ const traceId = store?.get(TRACE_REGISTRY_KEY) ??
329
+ store?.get(this.options.traceIdKey);
330
+ if (traceId) {
331
+ // Ahead of `ignore`, as every other transport does: what a resolver
332
+ // reads back with `TracerService.getAttribute` must not depend on
333
+ // whether the operation is recorded. `ignore` is asked about the
334
+ // document's first root field, which the client picks, and the
335
+ // resolvers of the fields behind it run all the same. With no
336
+ // transport in front there is no store yet; `startAsOperation` opens
337
+ // one and sets them there.
338
+ this.applyAttributes(info, ctx.context);
339
+ }
176
340
  if (shouldIgnoreSafely(this.options.graphql?.ignore, [info], this.options.graphql, this.logger, "graphql")) {
341
+ if (traceId && !this.operationTraceRegistry.hasOperationId(traceId)) {
342
+ // Not opening the operation's span is not enough where a transport
343
+ // in front opened a trace for the request, which it did before the
344
+ // operation was known. Left open, it went on recording every
345
+ // provider, guard and outbound call the operation made, failures
346
+ // with their stacks and headers included, and shipped them as
347
+ // `/graphql`. Dropped, the request goes on as one `http.ignore`
348
+ // excluded: its store keeps the key, and nothing is registered
349
+ // under it. Only while nothing has named the trace, though: a
350
+ // route handler that runs the operation in-process, or a batch an
351
+ // operation that is recorded leads, keeps its trace. The trace is
352
+ // the request's, so a batch an ignored operation leads is not
353
+ // recorded at all.
354
+ this.operationTraceRegistry.abandonTrace(traceId);
355
+ }
177
356
  return undefined;
178
357
  }
179
358
  const operationId = `${info.parentType.name}.${info.fieldName}`;
@@ -186,11 +365,6 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
186
365
  const attributes = {
187
366
  originalUrl: parsed.sanitizedDocument,
188
367
  };
189
- const store = this.asyncLocalStorage.getStore();
190
- // The registry key, where the transport in front gave the request one
191
- // of its own; the trace id otherwise, which is then the key as well.
192
- const traceId = store?.get(TRACE_REGISTRY_KEY) ??
193
- store?.get(this.options.traceIdKey);
194
368
  if (traceId) {
195
369
  return this.startWithinRequest(traceId, operationId, attributes, info, ctx);
196
370
  }
@@ -213,19 +387,30 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
213
387
  if (!state) {
214
388
  return;
215
389
  }
390
+ this.endOperation(state, this.toSpanError(ctx.errors));
391
+ }
392
+ /** Closes the operation's span once, and ships a trace this service opened. */
393
+ endOperation(state, error) {
394
+ if (state.ended) {
395
+ return;
396
+ }
397
+ state.ended = true;
216
398
  if (state.store) {
217
- // Handing the request back whatever owned it before this operation. The
218
- // store is shared by reference across the request, so this is a real
219
- // restore rather than a scoped one.
220
- if (state.previousCallerId === undefined) {
399
+ // Handing the request to an operation of its still open, or back to
400
+ // whatever owned it before them. The store is shared by reference
401
+ // across the request, so this is a real restore rather than a scoped
402
+ // one.
403
+ const callerId = this.closeOperation(state, state.store);
404
+ if (callerId === undefined) {
221
405
  state.store.delete(CALLER_METADATA_KEY);
222
406
  }
223
407
  else {
224
- state.store.set(CALLER_METADATA_KEY, state.previousCallerId);
408
+ state.store.set(CALLER_METADATA_KEY, callerId);
225
409
  }
226
410
  }
227
- this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, this.toSpanError(ctx.errors));
411
+ this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, error);
228
412
  if (state.ownsTrace) {
413
+ endOperation(state.store?.get(OPERATION_STATE_KEY));
229
414
  this.endOperationTrace(state.traceId, state.context);
230
415
  }
231
416
  }
@@ -236,7 +421,6 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
236
421
  * shipping the snapshot.
237
422
  */
238
423
  startWithinRequest(traceId, operationId, attributes, info, ctx) {
239
- this.applyAttributes(info, ctx.context);
240
424
  this.operationTraceRegistry.addGraphQLMetadataToTrace(traceId, {
241
425
  operationId,
242
426
  tags: this.options.graphql?.tags,
@@ -277,6 +461,8 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
277
461
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, info, this.options, this.logger);
278
462
  const store = new Map();
279
463
  store.set(this.options.traceIdKey, traceId);
464
+ // Ended with the operation's trace: see `liveTraceId`.
465
+ openOperation(store);
280
466
  this.asyncLocalStorage.enterWith(store);
281
467
  this.applyAttributes(info, ctx.context);
282
468
  this.operationTraceRegistry.startTrace(traceId, {
@@ -302,7 +488,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
302
488
  const className = handler?.className ?? info.parentType.name;
303
489
  const methodKey = handler?.methodKey ?? info.fieldName;
304
490
  const store = this.asyncLocalStorage.getStore();
305
- const previousCallerId = store?.get(CALLER_METADATA_KEY);
491
+ // With another operation open in this store, the caller the store names
492
+ // is that operation: the one before this in a batch. This one takes the
493
+ // caller that one took instead, which makes the operations of a batch
494
+ // siblings - each a root span of the request, reporting its own failure.
495
+ const openOperations = store && this.openOperationsByStore.get(store);
496
+ const sibling = openOperations?.at(-1);
497
+ const previousCallerId = sibling
498
+ ? sibling.previousCallerId
499
+ : store?.get(CALLER_METADATA_KEY);
306
500
  const spanId = this.operationTraceRegistry.internalStartTraceStep(traceId, className, methodKey, previousCallerId);
307
501
  if (!spanId) {
308
502
  // The trace was sampled out, or never started - an HTTP request that
@@ -311,7 +505,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
311
505
  return undefined;
312
506
  }
313
507
  store?.set(CALLER_METADATA_KEY, spanId);
314
- return {
508
+ const state = {
315
509
  traceId,
316
510
  spanId,
317
511
  className,
@@ -321,6 +515,40 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
321
515
  ownsTrace,
322
516
  context: ctx.context,
323
517
  };
518
+ if (openOperations) {
519
+ openOperations.push(state);
520
+ }
521
+ else if (store) {
522
+ this.openOperationsByStore.set(store, [state]);
523
+ }
524
+ return state;
525
+ }
526
+ /**
527
+ * Takes the operations that have ended off the ones a store has open, and
528
+ * returns the caller the store names from here on.
529
+ *
530
+ * While another operation is open there, that is the one of them that
531
+ * started last, whichever just ended: the work still running in the store
532
+ * belongs to an open operation, and a slot emptied or left naming an ended
533
+ * span put it at the root of the trace, beside the operation, and had
534
+ * `activeSpan()` find nothing. Once the last has ended, it is the caller
535
+ * they displaced.
536
+ */
537
+ closeOperation(state, store) {
538
+ const openOperations = this.openOperationsByStore.get(store);
539
+ // Ended ones are dropped once nothing open is left above them, so a batch
540
+ // that ends in the order it started does not search the list every time.
541
+ while (openOperations?.at(-1)?.ended) {
542
+ openOperations.pop();
543
+ }
544
+ const current = openOperations?.at(-1);
545
+ if (current) {
546
+ return current.spanId;
547
+ }
548
+ this.openOperationsByStore.delete(store);
549
+ // The same for every operation of a batch: each later one took it from
550
+ // the one before.
551
+ return state.previousCallerId;
324
552
  }
325
553
  /**
326
554
  * Ends and ships a trace this service opened itself.
@@ -348,13 +576,24 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
348
576
  * `GraphQLError` wrapping it, because that is the error the registry
349
577
  * classifies: an `IntrinsicException` a handler raised on purpose reads as
350
578
  * handled, and it stops being recognisable once GraphQL has wrapped it.
579
+ *
580
+ * An error graphql refused the request with is recorded by its class and
581
+ * code alone - see `toRefusal`.
351
582
  */
352
583
  toSpanError(errors) {
353
584
  const [first] = errors ?? [];
354
585
  if (!first) {
355
586
  return undefined;
356
587
  }
357
- return first.originalError ?? first;
588
+ const original = first.originalError;
589
+ const error = original ?? first;
590
+ // No path: raised by parsing, validation or the coercion of variables,
591
+ // before any resolver ran. A path, and an original error pointing at
592
+ // syntax of its own: an argument refused as its field was executed. A
593
+ // resolver's own error points at none.
594
+ return first.path == null || original?.nodes != null
595
+ ? toRefusal(first, error)
596
+ : error;
358
597
  }
359
598
  lookupResolverHandler(rootTypeName, fieldName) {
360
599
  this.resolverIndex ??= this.buildResolverIndex();
@@ -409,7 +648,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
409
648
  if (!store) {
410
649
  return;
411
650
  }
412
- setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql");
651
+ setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql", this.options.traceIdKey);
413
652
  }
414
653
  };
415
654
  GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
@@ -423,3 +662,99 @@ GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
423
662
  MetadataScanner])
424
663
  ], GraphQLObserveAgentService);
425
664
  export { GraphQLObserveAgentService };
665
+ /**
666
+ * The end hook the host is given: the application's first, with what its own
667
+ * start hook returned, then this service's, whatever the application's did,
668
+ * so the span covers both and is closed either way.
669
+ */
670
+ function composeEndHook(application, agent) {
671
+ return function (ctx) {
672
+ const shared = readSharedState(ctx.state);
673
+ try {
674
+ application?.call(this, shared ? { ...ctx, state: shared.application } : ctx);
675
+ }
676
+ finally {
677
+ agent.call(this, { ...ctx, state: shared?.observe });
678
+ }
679
+ };
680
+ }
681
+ function toSharedState(shared) {
682
+ return { [SHARED_STATE]: shared };
683
+ }
684
+ /**
685
+ * The pair the start hook kept, from its result as the driver hands it on:
686
+ * the object it returned, the promise it returned to a driver that does not
687
+ * await it, or what that promise resolved to for one that does. Nothing for
688
+ * a state no start hook of ours produced.
689
+ */
690
+ function readSharedState(state) {
691
+ return typeof state === "object" && state !== null
692
+ ? state[SHARED_STATE]
693
+ : undefined;
694
+ }
695
+ function isThenable(value) {
696
+ return ((typeof value === "object" || typeof value === "function") &&
697
+ value !== null &&
698
+ typeof value.then === "function");
699
+ }
700
+ /**
701
+ * What a request graphql refused is recorded with: the error's class and its
702
+ * code, `GRAPHQL_VALIDATION_FAILED` or `BAD_USER_INPUT`, and nothing graphql
703
+ * worded. graphql words these errors around the value it refused - `String
704
+ * cannot represent a non string value: 489213`, `found String "..."` - which
705
+ * the recorded document shows blanked, and which no rule can blank in prose:
706
+ * a string is printed there unescaped. The stack is the message again, then
707
+ * frames of graphql and the server, not of the application.
708
+ */
709
+ function toRefusal(first, error) {
710
+ const code = first.extensions?.code ??
711
+ error.extensions?.code;
712
+ const message = typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)
713
+ ? code
714
+ : "GraphQL request error";
715
+ const refusal = error instanceof Error
716
+ ? Object.create(Object.getPrototypeOf(error))
717
+ : new Error();
718
+ const name = error.constructor
719
+ ?.name;
720
+ // What the registry classifies a failure by: its class, kept above, and
721
+ // the status an `HttpException` thrown by a custom scalar answers with.
722
+ const status = error.status;
723
+ if (typeof status === "number") {
724
+ Object.defineProperty(refusal, "status", { value: status });
725
+ }
726
+ Object.defineProperties(refusal, {
727
+ message: { value: message, configurable: true, writable: true },
728
+ stack: {
729
+ value: `${typeof name === "string" && name ? name : "Error"}: ${message}`,
730
+ configurable: true,
731
+ writable: true,
732
+ },
733
+ });
734
+ return refusal;
735
+ }
736
+ const ORIGINAL_CREATE_CONTEXT_CALLBACK = Symbol.for("nestjs.observe.graphql.createContextCallback");
737
+ /**
738
+ * The instance `@nestjs/graphql` applies a resolver's methods to: the one
739
+ * behind the instrumentation proxy for a class whose methods cannot run
740
+ * against the proxy, the container's own for every other.
741
+ *
742
+ * Only for a resolver registered under its own class. Nest finds the module
743
+ * of one registered under another token
744
+ * (`{ provide: "TOKEN", useClass: Resolver }`) by looking for the instance
745
+ * the container holds, and with any other it finds none: the resolver would
746
+ * run with the guards, pipes and interceptors that module provides silently
747
+ * left out. Such a resolver keeps the proxy, and still fails on its private
748
+ * members.
749
+ */
750
+ function resolverReceiverOf(instance, wrapper) {
751
+ const receiver = rawReceiverOf(instance);
752
+ if (receiver === undefined) {
753
+ return instance;
754
+ }
755
+ const token = wrapper?.token;
756
+ return typeof token === "function" &&
757
+ token.prototype === Object.getPrototypeOf(receiver)
758
+ ? receiver
759
+ : instance;
760
+ }