@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
@@ -19,10 +19,53 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "../observe.constants.js";
19
19
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
20
20
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
21
21
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
+ /**
23
+ * Protocol recorded for a GraphQL operation that arrived over something other
24
+ * than an instrumented HTTP request. A query over HTTP keeps `http` as its
25
+ * protocol, because that is what the request was; the GraphQL layer only
26
+ * sharpens its operation id.
27
+ */
22
28
  const GRAPHQL_PROTOCOL = "graphql";
29
+ /**
30
+ * `@nestjs/graphql`'s metadata keys, inlined as strings so the package stays an
31
+ * optional peer. `@Query`/`@Mutation`/`@Subscription` stamp both onto the
32
+ * resolver method: the root type it registers against, and the schema field
33
+ * name when the decorator was given one (the method name serves otherwise).
34
+ */
23
35
  const RESOLVER_TYPE_METADATA = "graphql:resolver_type";
24
36
  const RESOLVER_NAME_METADATA = "graphql:resolver_name";
25
37
  const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
38
+ /**
39
+ * GraphQL operation instrumentation.
40
+ *
41
+ * Nest serves GraphQL as raw middleware mounted on a single path, so from
42
+ * HTTP's point of view every operation a service handles is one `POST /graphql`
43
+ * with no route handler behind it. That is a problem in both directions: the
44
+ * trace has no spans, so `OperationTraceRegistry.endTrace` discards it as a
45
+ * request that never reached a handler, and even if it survived, every query
46
+ * and mutation in the schema would aggregate into a single row.
47
+ *
48
+ * `@nestjs/graphql` exposes `ResolverDecoratorHost`, whose request-lifecycle
49
+ * hooks bracket a single operation: `setOnRequestStartHook` fires before the
50
+ * document is processed, `setOnRequestEndHook` once it has been, right before
51
+ * the response goes out. Whatever the start hook returns is handed back as
52
+ * `state`, which is what lets one span be opened in the first and closed in the
53
+ * second. This service claims both and gives each operation a span.
54
+ *
55
+ * The span goes into the trace the HTTP agent already opened whenever there is
56
+ * one, which keeps the shape a reader expects: one snapshot per HTTP request,
57
+ * with `Query.orders` as the operation id and the operation - plus every
58
+ * instrumented provider it reached - as the trace tree underneath. Only when no
59
+ * such trace exists does this service open one of its own.
60
+ *
61
+ * Measuring the operation rather than each root field is the point of using
62
+ * these hooks over the resolver decorator they replace. A span now covers
63
+ * parsing, validation and execution together, which is the number a client
64
+ * actually waited for; a document selecting several root fields is one span
65
+ * instead of several competing to name the trace; and a resolver that calls
66
+ * nothing instrumented still produces a trace rather than being discarded for
67
+ * having recorded no spans.
68
+ */
26
69
  let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObserveAgentService {
27
70
  asyncLocalStorage;
28
71
  options;
@@ -34,6 +77,12 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
34
77
  metadataScanner;
35
78
  logger = new Logger(GraphQLObserveAgentService_1.name);
36
79
  isPatched = false;
80
+ /**
81
+ * `Query.orders` -> the resolver class and method that registered it. Built
82
+ * lazily on the first operation, by which point every provider exists.
83
+ * `undefined` until then; never rebuilt, because resolvers cannot be added
84
+ * after the schema is built.
85
+ */
37
86
  resolverIndex;
38
87
  constructor(asyncLocalStorage, options, operationTraceRegistry, observeAgentSharedBuffer, traceSamplerService, moduleRef, discoveryService, metadataScanner) {
39
88
  this.asyncLocalStorage = asyncLocalStorage;
@@ -44,6 +93,13 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
44
93
  this.moduleRef = moduleRef;
45
94
  this.discoveryService = discoveryService;
46
95
  this.metadataScanner = metadataScanner;
96
+ // Attempted twice, and idempotent, because `GraphQLModule` may be
97
+ // instantiated on either side of this service. Whichever module Nest
98
+ // reaches first, one of the two attempts lands: if GraphQLModule came
99
+ // first, the host already exists here in the constructor; if it comes
100
+ // after, every provider is nonetheless constructed before any init hook
101
+ // runs, so the `onModuleInit` attempt below finds it. The hooks themselves
102
+ // are read lazily at request time, so registering late is safe either way.
47
103
  void this.registerRequestHooksIfPossible();
48
104
  }
49
105
  async onModuleInit() {
@@ -58,9 +114,13 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
58
114
  ({ ResolverDecoratorHost } = (await import("@nestjs/graphql")));
59
115
  }
60
116
  catch {
117
+ // The @nestjs/graphql package is an optional peer. A service that does not
118
+ // speak GraphQL has nothing to patch, and that is not a misconfiguration.
61
119
  return;
62
120
  }
63
121
  if (!ResolverDecoratorHost) {
122
+ // Installed, but too old to expose the host. Worth saying out loud: the
123
+ // symptom otherwise is a GraphQL service that silently reports nothing.
64
124
  this.logger.warn("The installed version of @nestjs/graphql does not expose 'ResolverDecoratorHost', so GraphQL operations cannot be instrumented. Upgrade @nestjs/graphql to collect per-operation traces.");
65
125
  return;
66
126
  }
@@ -71,6 +131,8 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
71
131
  });
72
132
  }
73
133
  catch {
134
+ // GraphQLModule is not registered in this application, or has not been
135
+ // instantiated yet - the second attempt, from onModuleInit, decides.
74
136
  return;
75
137
  }
76
138
  if (!host) {
@@ -78,6 +140,9 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
78
140
  }
79
141
  if (typeof host.setOnRequestStartHook !== "function" ||
80
142
  typeof host.setOnRequestEndHook !== "function") {
143
+ // The host predates the request-lifecycle hooks. Deliberately not falling
144
+ // back to `setDecorator`: two ways of measuring the same operation, only
145
+ // one of which is exercised, is worse than one that says why it is off.
81
146
  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.");
82
147
  return;
83
148
  }
@@ -85,6 +150,18 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
85
150
  host.setOnRequestEndHook((ctx) => this.onRequestEnd(ctx));
86
151
  this.isPatched = true;
87
152
  }
153
+ /**
154
+ * Opens a span for the operation about to be processed.
155
+ *
156
+ * Returns the state the end hook needs, or `undefined` for an operation this
157
+ * does not measure - one that was ignored, sampled out, or whose document
158
+ * nothing could be learned from. `undefined` is the end hook's signal to do
159
+ * nothing, so the two stay paired without a second flag.
160
+ *
161
+ * Hook exceptions are not swallowed by the driver, so nothing in here may
162
+ * throw on a caller's behalf: a failure to label a trace must not turn into a
163
+ * failed GraphQL request.
164
+ */
88
165
  onRequestStart(ctx) {
89
166
  const parsed = parseGraphQLOperation(ctx.query);
90
167
  if (!parsed) {
@@ -99,6 +176,12 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
99
176
  return undefined;
100
177
  }
101
178
  const operationId = `${info.parentType.name}.${info.fieldName}`;
179
+ // The document replaces the transport's originalUrl. Every operation over
180
+ // HTTP shares one mount path, so `/graphql` says nothing; the document is
181
+ // what tells two requests to the same root field apart, and it lands in
182
+ // the field every reader - detail views, search, the trigram index -
183
+ // already treats as "what was this request". The operation name is not
184
+ // recorded separately: a document that has one carries it inline.
102
185
  const attributes = {
103
186
  originalUrl: parsed.sanitizedDocument,
104
187
  };
@@ -109,12 +192,27 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
109
192
  }
110
193
  return this.startAsOperation(operationId, attributes, info, ctx);
111
194
  }
195
+ /**
196
+ * Closes the span, and - when this service opened the trace - ends and ships
197
+ * it.
198
+ *
199
+ * Not guaranteed to run for every start. Mercurius resolves an operation
200
+ * through `onResolution`, which never fires for a document that failed
201
+ * parsing or validation, so a start hook there can go unmatched. Nothing is
202
+ * leaked when it does: the state lives in the hook's return value rather than
203
+ * in this service, and the registry drops a trace whose spans never closed.
204
+ * The one visible consequence is that a malformed document collects nothing
205
+ * on Mercurius, which is what it collected before any of this existed.
206
+ */
112
207
  onRequestEnd(ctx) {
113
208
  const state = ctx.state;
114
209
  if (!state) {
115
210
  return;
116
211
  }
117
212
  if (state.store) {
213
+ // Handing the request back whatever owned it before this operation. The
214
+ // store is shared by reference across the request, so this is a real
215
+ // restore rather than a scoped one.
118
216
  if (state.previousCallerId === undefined) {
119
217
  state.store.delete(CALLER_METADATA_KEY);
120
218
  }
@@ -127,6 +225,12 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
127
225
  this.endOperationTrace(state.traceId, state.context);
128
226
  }
129
227
  }
228
+ /**
229
+ * The common case: the operation arrived over an HTTP request the HTTP agent
230
+ * already opened a trace for. The operation becomes a root span in that trace
231
+ * and lends it its operation id; the HTTP response hook still owns ending and
232
+ * shipping the snapshot.
233
+ */
130
234
  startWithinRequest(traceId, operationId, attributes, info, ctx) {
131
235
  this.applyAttributes(info, ctx.context);
132
236
  this.operationTraceRegistry.addGraphQLMetadataToTrace(traceId, {
@@ -136,6 +240,29 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
136
240
  });
137
241
  return this.openSpan(traceId, info, ctx, false);
138
242
  }
243
+ /**
244
+ * No enclosing trace - any transport with no agent of its own in front of it.
245
+ * The operation is the whole trace here, so this opens it, samples it, and
246
+ * ships the snapshot itself.
247
+ *
248
+ * The store is installed with `enterWith` rather than `run`, because a hook
249
+ * that returns cannot wrap the work that follows it. That makes this a
250
+ * best-effort path, and the way it can be wrong is worth naming: `enterWith`
251
+ * binds the store to the driver's *current* execution context and everything
252
+ * continuing from it, so where that context is shared between operations -
253
+ * rather than created per request, as an HTTP transport does - one
254
+ * operation's spans can be recorded against another's trace. In a service
255
+ * handling several tenants' operations that is telemetry attributed to the
256
+ * wrong one, not merely a trace with the wrong shape.
257
+ *
258
+ * There is no fix available at this layer, and pretending otherwise would be
259
+ * worse than the risk: the caller has already established that no enclosing
260
+ * trace exists, so there is nothing here to defend against, and the leak is
261
+ * outward rather than inward. Closing it needs the GraphQL driver to offer a
262
+ * hook that *wraps* execution - which `run` could then scope exactly - rather
263
+ * than one that returns into it. Until then, a deployment that cares should
264
+ * put a transport agent in front: the HTTP path never takes this branch.
265
+ */
139
266
  startAsOperation(operationId, attributes, info, ctx) {
140
267
  const shouldCapture = this.traceSamplerService.shouldCapture("graphql", {
141
268
  operationId,
@@ -156,7 +283,17 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
156
283
  });
157
284
  return this.openSpan(traceId, info, ctx, true);
158
285
  }
286
+ /**
287
+ * Opens the span and registers it as the caller in the async store, which is
288
+ * what makes everything the operation reaches - instrumented providers,
289
+ * manual spans, forwarded log lines - hang underneath this node rather than
290
+ * beside it.
291
+ */
159
292
  openSpan(traceId, info, ctx, ownsTrace) {
293
+ // The resolver class that registered the field, so the span groups under
294
+ // `OrdersResolver` rather than the schema's `Query`/`Mutation`. The schema
295
+ // type remains the fallback for a field no decorated class claims - a
296
+ // schema-first resolver map, or a field served by a plugin.
160
297
  const handler = this.lookupResolverHandler(info.parentType.name, info.fieldName);
161
298
  const className = handler?.className ?? info.parentType.name;
162
299
  const methodKey = handler?.methodKey ?? info.fieldName;
@@ -164,6 +301,9 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
164
301
  const previousCallerId = store?.get(CALLER_METADATA_KEY);
165
302
  const spanId = this.operationTraceRegistry.internalStartTraceStep(traceId, className, methodKey, previousCallerId);
166
303
  if (!spanId) {
304
+ // The trace was sampled out, or never started - an HTTP request that
305
+ // `http.ignore` dropped still carries a trace id in its store. Nothing to
306
+ // close, so the end hook is told to stand down.
167
307
  return undefined;
168
308
  }
169
309
  store?.set(CALLER_METADATA_KEY, spanId);
@@ -178,6 +318,13 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
178
318
  context: ctx.context,
179
319
  };
180
320
  }
321
+ /**
322
+ * Ends and ships a trace this service opened itself.
323
+ *
324
+ * No status code is passed: GraphQL has none. An operation that errored is
325
+ * classified from its root span instead, which is what keeps a failing
326
+ * operation out of the success bucket.
327
+ */
181
328
  endOperationTrace(traceId, context) {
182
329
  setTimeout(async () => {
183
330
  const userId = this.options.graphql?.getUserId?.(context);
@@ -189,6 +336,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
189
336
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
190
337
  }, 0);
191
338
  }
339
+ /**
340
+ * Picks the error a failed operation is recorded with.
341
+ *
342
+ * The first one wins - a span carries one error, and a document with several
343
+ * failing fields has to pick. `originalError` is preferred over the
344
+ * `GraphQLError` wrapping it, because that is the error the registry
345
+ * classifies: an `IntrinsicException` a handler raised on purpose reads as
346
+ * handled, and it stops being recognisable once GraphQL has wrapped it.
347
+ */
192
348
  toSpanError(errors) {
193
349
  const [first] = errors ?? [];
194
350
  if (!first) {
@@ -200,6 +356,13 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
200
356
  this.resolverIndex ??= this.buildResolverIndex();
201
357
  return this.resolverIndex.get(`${rootTypeName}.${fieldName}`);
202
358
  }
359
+ /**
360
+ * Walks every provider for methods `@Query`/`@Mutation`/`@Subscription`
361
+ * decorated, and records which class hosts each root field. Read from the
362
+ * prototypes' decorator metadata rather than the schema, because the schema
363
+ * only knows the field - the class that registered it is exactly what it
364
+ * erases, and what the services page wants back.
365
+ */
203
366
  buildResolverIndex() {
204
367
  const index = new Map();
205
368
  for (const wrapper of this.discoveryService.getProviders()) {
@@ -223,6 +386,9 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
223
386
  }
224
387
  const rootTypeName = Reflect.getMetadata(RESOLVER_TYPE_METADATA, method);
225
388
  if (!rootTypeName || !ROOT_TYPE_NAMES.has(rootTypeName)) {
389
+ // Not a root-field method. `@ResolveField` methods land here too:
390
+ // they carry a name but no root type, and the operation span never
391
+ // needs them.
226
392
  continue;
227
393
  }
228
394
  const fieldName = Reflect.getMetadata(RESOLVER_NAME_METADATA, method) ?? methodKey;
@@ -1,10 +1,36 @@
1
1
  import { GraphQLResolveInfoLike } from "../interfaces/index.js";
2
2
  export interface ParsedGraphQLOperation {
3
+ /** The root type the operation resolves against - `Query`, `Mutation`, `Subscription`. */
3
4
  rootTypeName: string;
5
+ /** The first root field the document selects, e.g. `orders`. */
4
6
  fieldName: string;
7
+ /** The operation's name, when the document gave it one. */
5
8
  operationName?: string;
9
+ /**
10
+ * The document with comments dropped, string literals blanked to `_`, and
11
+ * whitespace collapsed. What a trace records as the shape of the request:
12
+ * stable across formatting, and stripped of the one token kind that
13
+ * routinely carries user data inline.
14
+ */
6
15
  sanitizedDocument: string;
7
16
  }
17
+ /**
18
+ * Builds the `GraphQLResolveInfo`-shaped object the `graphql` options receive.
19
+ *
20
+ * It is genuinely synthetic - there is no single field being resolved when the
21
+ * whole operation is the unit of measurement - but it carries the same values
22
+ * a root field's real info would, which is the shape `ignore` and
23
+ * `setAttributes` are written against.
24
+ */
8
25
  export declare function toResolveInfoLike(operation: Pick<ParsedGraphQLOperation, "rootTypeName" | "fieldName" | "operationName">): GraphQLResolveInfoLike;
26
+ /**
27
+ * Finds the first operation definition in a document and its first root field.
28
+ *
29
+ * Returns `undefined` for anything it cannot label with confidence - a document
30
+ * whose first selection is a fragment spread, or one that does not parse as far
31
+ * as a selection set. Callers fall back to the operation name, and failing that
32
+ * leave the operation uninstrumented.
33
+ */
9
34
  export declare function parseGraphQLOperation(document: string | undefined): ParsedGraphQLOperation | undefined;
35
+ /** Test seam: the cache is process-wide and would leak between cases. */
10
36
  export declare function clearGraphQLOperationCache(): void;
@@ -1,10 +1,38 @@
1
+ /**
2
+ * Reads the operation out of a GraphQL document, without parsing it.
3
+ *
4
+ * The request-lifecycle hooks hand this module a query *string*, and
5
+ * everything the module labels a trace with - the operation id, and the
6
+ * `GraphQLResolveInfo`-shaped `info` the `graphql` options are called with -
7
+ * is derived from it here.
8
+ *
9
+ * `graphql`'s own `parse` is deliberately not used. It is an optional peer, it
10
+ * builds a full AST, and the server is about to do exactly that anyway: this
11
+ * runs on every operation, so it stops at the first field of the first
12
+ * operation definition and never looks at the rest of the document.
13
+ */
14
+ /** Operation keywords, mapped to the root type each one resolves against. */
1
15
  const ROOT_TYPE_BY_KEYWORD = {
2
16
  query: "Query",
3
17
  mutation: "Mutation",
4
18
  subscription: "Subscription",
5
19
  };
20
+ /**
21
+ * Parsed results are cached: a client sends the same handful of documents over
22
+ * and over, and re-scanning each one per request is pure waste. Bounded because
23
+ * the key is attacker-supplied - a client sending unique documents must not be
24
+ * able to grow this without limit.
25
+ */
6
26
  const CACHE_LIMIT = 512;
7
27
  const cache = new Map();
28
+ /**
29
+ * Builds the `GraphQLResolveInfo`-shaped object the `graphql` options receive.
30
+ *
31
+ * It is genuinely synthetic - there is no single field being resolved when the
32
+ * whole operation is the unit of measurement - but it carries the same values
33
+ * a root field's real info would, which is the shape `ignore` and
34
+ * `setAttributes` are written against.
35
+ */
8
36
  export function toResolveInfoLike(operation) {
9
37
  return {
10
38
  fieldName: operation.fieldName,
@@ -17,6 +45,14 @@ export function toResolveInfoLike(operation) {
17
45
  },
18
46
  };
19
47
  }
48
+ /**
49
+ * Finds the first operation definition in a document and its first root field.
50
+ *
51
+ * Returns `undefined` for anything it cannot label with confidence - a document
52
+ * whose first selection is a fragment spread, or one that does not parse as far
53
+ * as a selection set. Callers fall back to the operation name, and failing that
54
+ * leave the operation uninstrumented.
55
+ */
20
56
  export function parseGraphQLOperation(document) {
21
57
  if (!document) {
22
58
  return undefined;
@@ -26,11 +62,15 @@ export function parseGraphQLOperation(document) {
26
62
  }
27
63
  const parsed = scan(document);
28
64
  if (cache.size >= CACHE_LIMIT) {
65
+ // Oldest entry out. Map iterates in insertion order, so this is the least
66
+ // recently *added* document rather than the least recently used one - close
67
+ // enough for a cache whose job is to absorb a client's fixed set of queries.
29
68
  cache.delete(cache.keys().next().value);
30
69
  }
31
70
  cache.set(document, parsed);
32
71
  return parsed;
33
72
  }
73
+ /** Test seam: the cache is process-wide and would leak between cases. */
34
74
  export function clearGraphQLOperationCache() {
35
75
  cache.clear();
36
76
  }
@@ -48,6 +88,8 @@ function scan(document) {
48
88
  words.push(source.slice(start, index));
49
89
  continue;
50
90
  }
91
+ // A directive's name is not part of the definition's header - `query @live`
92
+ // must not read `live` as the operation name.
51
93
  if (char === "@") {
52
94
  index += 1;
53
95
  while (index < source.length && isNameChar(source[index])) {
@@ -55,12 +97,16 @@ function scan(document) {
55
97
  }
56
98
  continue;
57
99
  }
100
+ // Variable definitions, with default values that may themselves contain
101
+ // braces: `query Q($filter: F = { paid: true })`.
58
102
  if (char === "(") {
59
103
  index = skipBalanced(source, index, "(", ")");
60
104
  continue;
61
105
  }
62
106
  if (char === "{") {
63
107
  if (words[0] === "fragment") {
108
+ // A fragment may precede the operation it is used by. Skip its body and
109
+ // keep looking for a definition that is one.
64
110
  index = skipBalanced(source, index, "{", "}");
65
111
  words.length = 0;
66
112
  continue;
@@ -75,6 +121,7 @@ function toOperation(words, fieldName, source) {
75
121
  if (!fieldName) {
76
122
  return undefined;
77
123
  }
124
+ // Shorthand - `{ orders { id } }` - has no keyword at all and is a query.
78
125
  const keyword = words[0] ? words[0].toLowerCase() : "query";
79
126
  const rootTypeName = ROOT_TYPE_BY_KEYWORD[keyword];
80
127
  if (!rootTypeName) {
@@ -84,9 +131,16 @@ function toOperation(words, fieldName, source) {
84
131
  rootTypeName,
85
132
  fieldName,
86
133
  operationName: words[0] ? words[1] : undefined,
134
+ // Whitespace is collapsed only here, at the end: `source` positions have to
135
+ // stay valid while the scan is still reading from it.
87
136
  sanitizedDocument: source.replace(/\s+/g, " ").trim(),
88
137
  };
89
138
  }
139
+ /**
140
+ * Reads the first field selected inside a selection set, seeing through an
141
+ * alias: `latest: orders` is a selection of `orders`, and that is the name a
142
+ * resolver's info would have reported.
143
+ */
90
144
  function readFirstFieldName(source, from) {
91
145
  let index = from;
92
146
  while (index < source.length) {
@@ -102,11 +156,16 @@ function readFirstFieldName(source, from) {
102
156
  lookahead += 1;
103
157
  }
104
158
  if (source[lookahead] === ":") {
159
+ // An alias: the selected field is the next name. Iteration, not
160
+ // recursion - the document is caller-supplied, and a long enough run
161
+ // of colons must cost a loop pass each, never a stack frame each.
105
162
  index = lookahead + 1;
106
163
  continue;
107
164
  }
108
165
  return name;
109
166
  }
167
+ // A fragment spread or inline fragment first: the field is defined
168
+ // elsewhere in the document, and chasing it is not worth an AST.
110
169
  if (char === "." || char === "}") {
111
170
  return undefined;
112
171
  }
@@ -114,6 +173,11 @@ function readFirstFieldName(source, from) {
114
173
  }
115
174
  return undefined;
116
175
  }
176
+ /**
177
+ * Blanks out comments and strings, so neither can be mistaken for a name or a
178
+ * brace. Offsets are not preserved - nothing downstream maps back to the
179
+ * original text.
180
+ */
117
181
  function stripIgnoredTokens(document) {
118
182
  let out = "";
119
183
  let index = 0;
@@ -137,6 +201,8 @@ function stripIgnoredTokens(document) {
137
201
  }
138
202
  index += 1;
139
203
  }
204
+ // Left as a token that is neither a name nor a brace, so a default value
205
+ // of `""` still reads as a value rather than as nothing at all.
140
206
  out += "_";
141
207
  continue;
142
208
  }
@@ -26,6 +26,25 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
26
26
  endHttpRequestTracing(req: unknown, res: {
27
27
  statusCode: number;
28
28
  }): void;
29
+ /**
30
+ * Frees the trace when the client goes away before the response finishes.
31
+ *
32
+ * The adapter's response hook rides `res.on("finish")`, and an aborted
33
+ * request never emits it - the socket emits `close` instead. Without this,
34
+ * every abort leaves its snapshot and span map in the registry for the life
35
+ * of the process; on an ingest endpoint taking 16MB bodies over slow links,
36
+ * aborts are routine, not exceptional.
37
+ *
38
+ * On the normal path `close` follows `finish` with `writableFinished`
39
+ * already true, so this stays a no-op there - `endHttpRequestTracing` has
40
+ * either plucked the trace or is about to.
41
+ *
42
+ * Eviction is deferred, not immediate: Express does not cancel the handler
43
+ * on abort, so its spans are usually still closing when `close` fires, and
44
+ * each one ending after the snapshot is gone would log an error. The grace
45
+ * period lets the handler drain first; `unref` keeps the timer from holding
46
+ * a shutting-down process open.
47
+ */
29
48
  private evictTraceOnClientAbort;
30
49
  private shouldIgnoreRequest;
31
50
  }
@@ -18,6 +18,11 @@ import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { redactUrlQuery } from "../utils/redact-url-query.js";
21
+ /**
22
+ * How long an aborted request's handler gets to finish its spans before the
23
+ * trace is dropped from the registry. Generous next to a typical handler, tiny
24
+ * next to a leak that never frees.
25
+ */
21
26
  const ABORTED_TRACE_EVICTION_GRACE_MS = 30_000;
22
27
  let HttpObserveAgentService = class HttpObserveAgentService {
23
28
  httpAdapterHost;
@@ -34,6 +39,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
34
39
  this.operationTraceRegistry = operationTraceRegistry;
35
40
  this.observeAgentSharedBuffer = observeAgentSharedBuffer;
36
41
  this.traceSamplerService = traceSamplerService;
42
+ // The "setOnRouteTriggered" hook must be set immediately
43
+ // to ensure that route metadata is captured correctly.
37
44
  const { httpAdapter } = this.httpAdapterHost;
38
45
  if (!httpAdapter) {
39
46
  return;
@@ -74,6 +81,8 @@ let HttpObserveAgentService = class HttpObserveAgentService {
74
81
  });
75
82
  }
76
83
  startHttpRequestTracing(req, res, done) {
84
+ // The same map `run` is given, rather than `getStore()` inside the callback:
85
+ // identical object, one lookup fewer, and it is known to exist.
77
86
  const store = new Map();
78
87
  this.asyncLocalStorage.run(store, () => {
79
88
  const traceId = this.options.traceIdGenerator(req);
@@ -96,6 +105,12 @@ let HttpObserveAgentService = class HttpObserveAgentService {
96
105
  if (!shouldCapture) {
97
106
  return done();
98
107
  }
108
+ // Sensitive query parameters are masked whether or not the deployment
109
+ // configured anything: an opt-in redactor protects only those who
110
+ // already knew to ask, and a reset token in a stored URL is the same
111
+ // disclosure either way. A configured regex still applies, on top rather
112
+ // than instead - it exists for the keys only that deployment knows
113
+ // about.
99
114
  const redactedUrl = redactUrlQuery(req.url);
100
115
  const originalUrl = this.options.http?.queryParamsObfuscateRegex
101
116
  ? redactedUrl.replaceAll(this.options.http.queryParamsObfuscateRegex, "[REDACTED]")
@@ -137,6 +152,25 @@ let HttpObserveAgentService = class HttpObserveAgentService {
137
152
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
138
153
  }, 0);
139
154
  }
155
+ /**
156
+ * Frees the trace when the client goes away before the response finishes.
157
+ *
158
+ * The adapter's response hook rides `res.on("finish")`, and an aborted
159
+ * request never emits it - the socket emits `close` instead. Without this,
160
+ * every abort leaves its snapshot and span map in the registry for the life
161
+ * of the process; on an ingest endpoint taking 16MB bodies over slow links,
162
+ * aborts are routine, not exceptional.
163
+ *
164
+ * On the normal path `close` follows `finish` with `writableFinished`
165
+ * already true, so this stays a no-op there - `endHttpRequestTracing` has
166
+ * either plucked the trace or is about to.
167
+ *
168
+ * Eviction is deferred, not immediate: Express does not cancel the handler
169
+ * on abort, so its spans are usually still closing when `close` fires, and
170
+ * each one ending after the snapshot is gone would log an error. The grace
171
+ * period lets the handler drain first; `unref` keeps the timer from holding
172
+ * a shutting-down process open.
173
+ */
140
174
  evictTraceOnClientAbort(res, traceId) {
141
175
  const response = res;
142
176
  if (typeof response?.on !== "function") {
@@ -10,6 +10,14 @@ export declare class QueueObserveAgentService<Store extends Record<string, unkno
10
10
  private readonly asyncLocalStorage;
11
11
  private readonly logger;
12
12
  constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>);
13
+ /**
14
+ * Queue-level facts BullMQ already tracks but that never reached telemetry:
15
+ * how long the job waited before a worker took it, and which attempt this is.
16
+ *
17
+ * Read defensively - these are optional on the Job type and absent when a
18
+ * queue driver does not populate them, in which case the fields are simply
19
+ * omitted rather than reported as zero.
20
+ */
13
21
  private readQueueMetadata;
14
22
  private patchDecorate;
15
23
  }
@@ -31,11 +31,25 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
31
31
  this.asyncLocalStorage = asyncLocalStorage;
32
32
  this.patchDecorate();
33
33
  }
34
+ /**
35
+ * Queue-level facts BullMQ already tracks but that never reached telemetry:
36
+ * how long the job waited before a worker took it, and which attempt this is.
37
+ *
38
+ * Read defensively - these are optional on the Job type and absent when a
39
+ * queue driver does not populate them, in which case the fields are simply
40
+ * omitted rather than reported as zero.
41
+ */
34
42
  readQueueMetadata(job) {
35
43
  const metadata = {};
36
44
  if (typeof job.timestamp === "number") {
37
45
  metadata.enqueuedAt = new Date(job.timestamp).toISOString();
46
+ // processedOn is set by the worker immediately before the processor runs.
47
+ // Falling back to now() keeps the measurement honest if it is missing.
38
48
  const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
49
+ // `timestamp` is when the job was created, not when it became runnable, so
50
+ // for a delayed job the gap between the two is a schedule the caller asked
51
+ // for - not a queue that fell behind. Counting it would report a job dated
52
+ // a week out as a week of backlog and drag `job_wait_p95` with it.
39
53
  const availableAt = job.timestamp + (job.delay ?? 0);
40
54
  metadata.waitDuration = Math.max(0, startedAt - availableAt);
41
55
  }
@@ -58,9 +72,13 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
58
72
  const hasOuterContext = this.asyncLocalStorage
59
73
  .getStore()
60
74
  ?.has(this.options.traceIdKey);
75
+ // The same map `run` is given, rather than `getStore()` inside the
76
+ // callback: identical object, one lookup fewer, and it is known to exist.
61
77
  const store = new Map();
62
78
  return this.asyncLocalStorage.run(store, () => {
63
79
  if (hasOuterContext) {
80
+ // If the outer context already has a trace ID
81
+ // ignore the inner context
64
82
  if (this.options.debug) {
65
83
  this.logger.debug(`Outer context already has a trace ID. Skipping inner context for job "${job.name}" job.id: ${job.id}`);
66
84
  }
@@ -80,6 +98,7 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
80
98
  }
81
99
  }
82
100
  }
101
+ // setImmediate(() => {
83
102
  this.operationTraceRegistry.startTrace(traceId, {
84
103
  tags: this.options.jobs?.tags,
85
104
  queueName: job.queueName,
@@ -87,10 +106,23 @@ let QueueObserveAgentService = QueueObserveAgentService_1 = class QueueObserveAg
87
106
  id: typeof job.id === "number" ? `${job.id}` : job.id,
88
107
  ...this.readQueueMetadata(job),
89
108
  });
109
+ // });
90
110
  const endTrace = (status) => {
91
111
  setTimeout(async () => {
92
112
  this.operationTraceRegistry.endTrace(traceId, { status });
93
113
  const snapshot = (await this.operationTraceRegistry.pluckSnapshot(traceId));
114
+ // `pluckSnapshot` deletes what it returns, so a trace already
115
+ // plucked - a job whose handler resolved and rejected, a retry
116
+ // reusing the id - answers undefined. The `!` here asserted
117
+ // otherwise, and the encoder dereferenced it inside a
118
+ // `setTimeout`, where no try/catch can reach: an unhandled
119
+ // TypeError that took the whole process down. A worker deployment
120
+ // could not finish booting, because draining a queue was enough
121
+ // to trigger it.
122
+ //
123
+ // Dropped rather than reported: there is no snapshot, so there is
124
+ // nothing to send, and losing one job's self-instrumentation is
125
+ // not worth a crash loop.
94
126
  if (!snapshot) {
95
127
  return;
96
128
  }