@nestjs/observe 0.3.25 → 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 (94) hide show
  1. package/README.md +17 -0
  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 +41 -17
  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 +158 -96
  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.js +7 -3
  34. package/dist/otlp/otlp-trace-exporter.service.js +63 -5
  35. package/dist/outgoing/http.integration.d.ts +8 -4
  36. package/dist/outgoing/http.integration.js +13 -6
  37. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  38. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  39. package/dist/outgoing/llm/llm-providers.js +72 -22
  40. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  41. package/dist/outgoing/llm/llm-usage.js +72 -25
  42. package/dist/outgoing/mssql.integration.js +16 -2
  43. package/dist/outgoing/mysql2.integration.js +17 -1
  44. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  45. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  46. package/dist/outgoing/pg.integration.d.ts +3 -2
  47. package/dist/outgoing/pg.integration.js +39 -11
  48. package/dist/outgoing/sql-statement.util.js +106 -14
  49. package/dist/outgoing/undici.integration.d.ts +13 -0
  50. package/dist/outgoing/undici.integration.js +68 -0
  51. package/dist/protocols/bull-observe-agent.service.js +2 -12
  52. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  53. package/dist/protocols/deferred-trace-completion.js +36 -6
  54. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  55. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  56. package/dist/protocols/graphql-operation-parser.js +72 -18
  57. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  58. package/dist/protocols/http-observe-agent.service.js +177 -59
  59. package/dist/protocols/job-trace-runner.d.ts +35 -3
  60. package/dist/protocols/job-trace-runner.js +126 -29
  61. package/dist/protocols/queue-observe-agent.service.js +44 -20
  62. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  63. package/dist/protocols/rpc-observe-agent.service.js +187 -47
  64. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  65. package/dist/protocols/ws-observe-agent.service.js +226 -20
  66. package/dist/services/index.d.ts +1 -1
  67. package/dist/services/index.js +1 -1
  68. package/dist/services/logger-patcher.service.js +3 -4
  69. package/dist/services/operation-trace.registry.d.ts +45 -1
  70. package/dist/services/operation-trace.registry.js +418 -35
  71. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  72. package/dist/services/stdout-forwarder.service.js +288 -51
  73. package/dist/services/tracer.service.d.ts +23 -0
  74. package/dist/services/tracer.service.js +91 -5
  75. package/dist/utils/capture-request.util.d.ts +3 -1
  76. package/dist/utils/capture-request.util.js +100 -12
  77. package/dist/utils/fit-to-length.util.js +33 -10
  78. package/dist/utils/log-line.parser.d.ts +14 -0
  79. package/dist/utils/log-line.parser.js +7 -3
  80. package/dist/utils/log-redactor.d.ts +14 -0
  81. package/dist/utils/log-redactor.js +512 -61
  82. package/dist/utils/operation-state.util.d.ts +39 -0
  83. package/dist/utils/operation-state.util.js +50 -0
  84. package/dist/utils/redact-url-query.d.ts +26 -4
  85. package/dist/utils/redact-url-query.js +184 -32
  86. package/dist/utils/sensitive-keys.d.ts +4 -1
  87. package/dist/utils/sensitive-keys.js +48 -10
  88. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  89. package/dist/utils/shared-hook-slot.util.js +103 -0
  90. package/dist/utils/source-context.util.d.ts +8 -0
  91. package/dist/utils/source-context.util.js +88 -24
  92. package/dist/utils/source-map-resolver.util.js +8 -2
  93. package/dist/utils/trace-context.util.js +21 -6
  94. package/package.json +2 -2
@@ -0,0 +1,68 @@
1
+ import { AsyncResource } from "node:async_hooks";
2
+ import { patchMethod } from "./patch-method.util.js";
3
+ /**
4
+ * The async context each request was first dispatched in, by its handler.
5
+ *
6
+ * undici creates a request - and publishes `undici:request:create`, which the
7
+ * HTTP integration reads the caller from - in whatever context the dispatch
8
+ * that gets it to a client runs in. The first pass through `dispatch` is the
9
+ * caller's own call. A later one may run from a socket's events, in the
10
+ * context of whichever request opened that socket: a bounded pool handing a
11
+ * queued request to a client as another one drains, a redirect or a retry
12
+ * re-dispatched from a response. Each later pass is run where the first was.
13
+ *
14
+ * Keyed by handler: undici's own `request`, `stream`, `pipeline` and `fetch`
15
+ * make one per request. An application that calls `dispatch()` itself with
16
+ * one handler for several requests gets them all filed under the first.
17
+ */
18
+ const callers = new WeakMap();
19
+ /**
20
+ * `Dispatcher#dispatch` on undici's base class, which `Agent`, `Pool`,
21
+ * `Client` and the rest share, and which every layer passes a request
22
+ * through.
23
+ */
24
+ export function patchUndiciDispatch(module) {
25
+ const base = defaultExport(module);
26
+ return patchMethod(base?.prototype, "dispatch", (original) => function (...args) {
27
+ const handler = args[1];
28
+ if (typeof handler !== "object" || handler === null) {
29
+ return original.apply(this, args);
30
+ }
31
+ const caller = callers.get(handler);
32
+ if (caller) {
33
+ return caller.runInAsyncScope(original, this, ...args);
34
+ }
35
+ callers.set(handler, new AsyncResource("ObserveUndiciDispatch"));
36
+ return original.apply(this, args);
37
+ });
38
+ }
39
+ /**
40
+ * `UnwrapHandler.unwrap` on undici 7, which hands each layer below a new
41
+ * wrapper of the handler on every pass: the wrapper is filed under its
42
+ * handler's caller, so a later pass is recognised below a dispatcher
43
+ * composed - its `dispatch` bound - before the base class was patched.
44
+ */
45
+ export function patchUndiciUnwrap(module) {
46
+ const unwrapHandler = defaultExport(module);
47
+ return patchMethod(unwrapHandler, "unwrap", (original) => function (handler) {
48
+ const wrapped = original.call(this, handler);
49
+ if (wrapped !== handler &&
50
+ typeof wrapped === "object" &&
51
+ wrapped !== null &&
52
+ typeof handler === "object" &&
53
+ handler !== null) {
54
+ let caller = callers.get(handler);
55
+ if (!caller) {
56
+ caller = new AsyncResource("ObserveUndiciDispatch");
57
+ callers.set(handler, caller);
58
+ }
59
+ callers.set(wrapped, caller);
60
+ }
61
+ return wrapped;
62
+ });
63
+ }
64
+ function defaultExport(module) {
65
+ return typeof module === "function"
66
+ ? module
67
+ : module?.default;
68
+ }
@@ -17,7 +17,7 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
17
17
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
18
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
19
19
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
20
- import { JobTraceRunner } from "./job-trace-runner.js";
20
+ import { JobTraceRunner, readJobTimes } from "./job-trace-runner.js";
21
21
  const ORIGINAL_SET_HANDLER = Symbol.for("nestjs.observe.bull.setHandler");
22
22
  /** Bull names an unnamed job this; reporting it would name every job the same. */
23
23
  const BULL_DEFAULT_JOB_NAME = "__default__";
@@ -49,17 +49,7 @@ let BullObserveAgentService = BullObserveAgentService_1 = class BullObserveAgent
49
49
  return result.module?.prototype ?? null;
50
50
  }
51
51
  readQueueMetadata(job) {
52
- const metadata = {};
53
- if (typeof job.timestamp === "number") {
54
- metadata.enqueuedAt = new Date(job.timestamp).toISOString();
55
- const startedAt = typeof job.processedOn === "number" ? job.processedOn : Date.now();
56
- // As with BullMQ: a delay the caller asked for is a schedule, not a
57
- // backlog, so the wait is measured from when the job became runnable.
58
- // `||`, not `??`: the job's own `delay` reads 0 once Bull has promoted
59
- // it, and only the options still say what was asked for.
60
- const delay = job.delay || job.opts?.delay || 0;
61
- metadata.waitDuration = Math.max(0, startedAt - (job.timestamp + delay));
62
- }
52
+ const metadata = readJobTimes(job);
63
53
  if (typeof job.attemptsMade === "number") {
64
54
  metadata.attemptsMade = job.attemptsMade;
65
55
  }
@@ -21,7 +21,15 @@ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: (
21
21
  * have been written to keep out is not a safe guess.
22
22
  */
23
23
  export declare function shouldIgnoreSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => boolean) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): boolean;
24
- /** A bad identity callback must not prevent the trace from being closed. */
24
+ /**
25
+ * A bad identity callback must not prevent the trace from being closed.
26
+ *
27
+ * Made a string here, inside the guard, rather than by whoever records it: a
28
+ * callback typed to return a string can still hand back what a message
29
+ * carried - a TCP packet's metadata is whatever `JSON.parse` made of it - and
30
+ * `String()` throws on `{"toString": 1}`. Thrown between ending the trace and
31
+ * plucking it, that left the trace registered for the life of the process.
32
+ */
25
33
  export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
34
  /**
27
35
  * Completes a trace once its operation has ended, without ever leaking a
@@ -30,13 +30,22 @@ export function invokeUserCallbackSafely(callback, args, receiver, fallback, log
30
30
  return callback.apply(receiver, args);
31
31
  }
32
32
  catch (error) {
33
- if (!reportedCallbacks.has(callback)) {
34
- reportedCallbacks.add(callback);
35
- warnSafely(logger, `"${name}" threw; ${outcome}. Later failures are not reported: ${describeFailure(error)}`);
36
- }
33
+ reportCallbackFailure(callback, logger, name, "threw", outcome, error);
37
34
  return fallback();
38
35
  }
39
36
  }
37
+ /**
38
+ * Reports the first failure of a callback, whichever way it failed: a
39
+ * callback that both throws and returns what cannot be used still says so
40
+ * once.
41
+ */
42
+ function reportCallbackFailure(callback, logger, name, failure, outcome, error) {
43
+ if (reportedCallbacks.has(callback)) {
44
+ return;
45
+ }
46
+ reportedCallbacks.add(callback);
47
+ warnSafely(logger, `"${name}" ${failure}; ${outcome}. Later failures are not reported: ${describeFailure(error)}`);
48
+ }
40
49
  /**
41
50
  * The trace id for an operation. A generator that throws is replaced by a
42
51
  * fresh uuidv7, which no open trace can share, so the operation is still
@@ -69,12 +78,33 @@ export function shouldIgnoreSafely(callback, args, receiver, logger, transport)
69
78
  }
70
79
  return invokeUserCallbackSafely(callback, args, receiver, () => true, logger, `${transport}.ignore`, "not tracing the operation");
71
80
  }
72
- /** A bad identity callback must not prevent the trace from being closed. */
81
+ /**
82
+ * A bad identity callback must not prevent the trace from being closed.
83
+ *
84
+ * Made a string here, inside the guard, rather than by whoever records it: a
85
+ * callback typed to return a string can still hand back what a message
86
+ * carried - a TCP packet's metadata is whatever `JSON.parse` made of it - and
87
+ * `String()` throws on `{"toString": 1}`. Thrown between ending the trace and
88
+ * plucking it, that left the trace registered for the life of the process.
89
+ */
73
90
  export function getUserIdSafely(callback, args, receiver, logger, transport) {
74
91
  if (!callback) {
75
92
  return undefined;
76
93
  }
77
- return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
94
+ const name = `${transport}.getUserId`;
95
+ const outcome = "completing the trace without a user id";
96
+ const userId = invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, name, outcome);
97
+ if (userId === undefined || typeof userId === "string") {
98
+ return userId;
99
+ }
100
+ try {
101
+ // oxlint-disable-next-line typescript/no-base-to-string -- recorded as `String()` always recorded it
102
+ return String(userId);
103
+ }
104
+ catch (error) {
105
+ reportCallbackFailure(callback, logger, name, "returned a value that cannot be made a string", outcome, error);
106
+ return undefined;
107
+ }
78
108
  }
79
109
  /**
80
110
  * Completes a trace once its operation has ended, without ever leaking a
@@ -14,12 +14,19 @@ interface GqlRequestStartContext {
14
14
  }
15
15
  interface GqlRequestEndContext extends GqlRequestStartContext {
16
16
  /** `GraphQLError`s, structurally: the `graphql` package is an optional peer. */
17
- errors?: readonly {
18
- message?: string;
19
- originalError?: unknown;
20
- }[];
17
+ errors?: readonly GqlError[];
21
18
  state?: unknown;
22
19
  }
20
+ /** A `GraphQLError`, as much of it as is read here. */
21
+ interface GqlError {
22
+ message?: string;
23
+ originalError?: unknown;
24
+ /** Where in the response it belongs; absent before execution begins. */
25
+ path?: unknown;
26
+ extensions?: {
27
+ code?: unknown;
28
+ };
29
+ }
23
30
  /**
24
31
  * What the start hook hands the end hook. Everything needed to close the
25
32
  * operation travels in here rather than in a map keyed by trace id, because an
@@ -37,6 +44,8 @@ interface OperationState {
37
44
  /** Whether this service opened the trace, and therefore has to ship it. */
38
45
  ownsTrace: boolean;
39
46
  context: unknown;
47
+ /** Closed already: refused by the application's start hook. */
48
+ ended?: boolean;
40
49
  }
41
50
  /**
42
51
  * GraphQL operation instrumentation.
@@ -53,7 +62,8 @@ interface OperationState {
53
62
  * document is processed, `setOnRequestEndHook` once it has been, right before
54
63
  * the response goes out. Whatever the start hook returns is handed back as
55
64
  * `state`, which is what lets one span be opened in the first and closed in the
56
- * second. This service claims both and gives each operation a span.
65
+ * second. This service uses both and gives each operation a span, beside any
66
+ * hooks the application sets there - see `composeStartHook`.
57
67
  *
58
68
  * The span goes into the trace the HTTP agent already opened whenever there is
59
69
  * one, which keeps the shape a reader expects: one snapshot per HTTP request,
@@ -90,6 +100,22 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
90
100
  constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService, moduleRef: ModuleRef, discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
91
101
  onModuleInit(): Promise<void>;
92
102
  registerRequestHooksIfPossible(): Promise<void>;
103
+ /**
104
+ * The start hook the host is given: this service's part first, so the span
105
+ * covers the application's hook, then the application's, whose result is
106
+ * kept for its own end hook.
107
+ *
108
+ * An application's start hook that throws refuses the document: the driver
109
+ * answers with the error and calls no end hook. The span is closed here
110
+ * then, with the application's error, so the refusal is recorded as a
111
+ * failed operation. A start hook that returns a promise gets one back, and
112
+ * only then - a driver that awaits the hook awaits it, and one that does
113
+ * not hands it to the end hook as the state, which is why the pair is also
114
+ * kept on the promise itself. Its rejection closes the span the same way,
115
+ * and travels on in the promise returned, to a driver that awaits it.
116
+ */
117
+ private composeStartHook;
118
+ private closeRefused;
93
119
  /**
94
120
  * Opens a span for the operation about to be processed.
95
121
  *
@@ -116,6 +142,8 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
116
142
  * its status code and no spans under it.
117
143
  */
118
144
  onRequestEnd(ctx: GqlRequestEndContext): void;
145
+ /** Closes the operation's span once, and ships a trace this service opened. */
146
+ private endOperation;
119
147
  /**
120
148
  * The common case: the operation arrived over an HTTP request the HTTP agent
121
149
  * already opened a trace for. The operation becomes a root span in that trace
@@ -170,6 +198,9 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
170
198
  * `GraphQLError` wrapping it, because that is the error the registry
171
199
  * classifies: an `IntrinsicException` a handler raised on purpose reads as
172
200
  * handled, and it stops being recognisable once GraphQL has wrapped it.
201
+ *
202
+ * An error graphql refused the request with is recorded by its class and
203
+ * code alone - see `toRefusal`.
173
204
  */
174
205
  private toSpanError;
175
206
  private lookupResolverHandler;
@@ -18,8 +18,10 @@ import { ObserveAgentSharedBuffer } from "../agent/observe-agent.shared-buffer.j
18
18
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } 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
+ import { setAgentHook } from "../utils/shared-hook-slot.util.js";
21
22
  import { parseGraphQLOperation, toResolveInfoLike, } from "./graphql-operation-parser.js";
22
23
  import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
24
+ import { endOperation, OPERATION_STATE_KEY, openOperation, } from "../utils/operation-state.util.js";
23
25
  /**
24
26
  * Protocol recorded for a GraphQL operation that arrived over something other
25
27
  * than an instrumented HTTP request. A query over HTTP keeps `http` as its
@@ -36,6 +38,12 @@ const GRAPHQL_PROTOCOL = "graphql";
36
38
  const RESOLVER_TYPE_METADATA = "graphql:resolver_type";
37
39
  const RESOLVER_NAME_METADATA = "graphql:resolver_name";
38
40
  const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
41
+ /**
42
+ * Where the start hook the host is given keeps both sides' state, on what it
43
+ * returns: this service's, and whatever the application's own start hook
44
+ * returned, each handed back to the end hook it belongs to.
45
+ */
46
+ const SHARED_STATE = Symbol("nestjs.observe.graphqlRequestState");
39
47
  /**
40
48
  * GraphQL operation instrumentation.
41
49
  *
@@ -51,7 +59,8 @@ const ROOT_TYPE_NAMES = new Set(["Query", "Mutation", "Subscription"]);
51
59
  * document is processed, `setOnRequestEndHook` once it has been, right before
52
60
  * the response goes out. Whatever the start hook returns is handed back as
53
61
  * `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.
62
+ * second. This service uses both and gives each operation a span, beside any
63
+ * hooks the application sets there - see `composeStartHook`.
55
64
  *
56
65
  * The span goes into the trace the HTTP agent already opened whenever there is
57
66
  * one, which keeps the shape a reader expects: one snapshot per HTTP request,
@@ -147,10 +156,69 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
147
156
  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
157
  return;
149
158
  }
150
- host.setOnRequestStartHook((ctx) => this.onRequestStart(ctx));
151
- host.setOnRequestEndHook((ctx) => this.onRequestEnd(ctx));
159
+ if (this.isPatched) {
160
+ // The other attempt landed while this one waited for the import.
161
+ return;
162
+ }
163
+ // The host's hooks are public API, and the application's to set as well:
164
+ // a check that refuses a document by throwing from the start hook, an
165
+ // audit record written in the end hook. Shared, so neither replaces the
166
+ // other, whichever is set first. The getters hand the application its own
167
+ // hooks - Nest calls the hooks through `onRequestStart` and
168
+ // `onRequestEnd`, never through them.
169
+ setAgentHook(host, "setOnRequestStartHook", (ctx) => this.onRequestStart(ctx), (application, agent) => this.composeStartHook(application, agent), { getter: "getOnRequestStartHook", repointGetter: true });
170
+ setAgentHook(host, "setOnRequestEndHook", (ctx) => this.onRequestEnd(ctx), composeEndHook, { getter: "getOnRequestEndHook", repointGetter: true });
152
171
  this.isPatched = true;
153
172
  }
173
+ /**
174
+ * The start hook the host is given: this service's part first, so the span
175
+ * covers the application's hook, then the application's, whose result is
176
+ * kept for its own end hook.
177
+ *
178
+ * An application's start hook that throws refuses the document: the driver
179
+ * answers with the error and calls no end hook. The span is closed here
180
+ * then, with the application's error, so the refusal is recorded as a
181
+ * failed operation. A start hook that returns a promise gets one back, and
182
+ * only then - a driver that awaits the hook awaits it, and one that does
183
+ * not hands it to the end hook as the state, which is why the pair is also
184
+ * kept on the promise itself. Its rejection closes the span the same way,
185
+ * and travels on in the promise returned, to a driver that awaits it.
186
+ */
187
+ composeStartHook(application, agent) {
188
+ const refuse = (state, error) => this.closeRefused(state, error);
189
+ return function (ctx) {
190
+ const observe = agent.call(this, ctx);
191
+ let returned;
192
+ try {
193
+ returned = application?.call(this, ctx);
194
+ }
195
+ catch (error) {
196
+ refuse(observe, error);
197
+ throw error;
198
+ }
199
+ if (!isThenable(returned)) {
200
+ return toSharedState({ observe, application: returned });
201
+ }
202
+ const settled = Promise.resolve(returned).then((value) => toSharedState({ observe, application: value }), (error) => {
203
+ refuse(observe, error);
204
+ throw error;
205
+ });
206
+ // Handled here, as a driver that does not await it never does: its
207
+ // rejection would otherwise be one only the agent made, beside the
208
+ // application's own promise, which the application may well handle.
209
+ // A driver that awaits it still sees the rejection.
210
+ settled.catch(() => undefined);
211
+ return Object.defineProperty(settled, SHARED_STATE, {
212
+ value: { observe, application: returned },
213
+ });
214
+ };
215
+ }
216
+ closeRefused(state, error) {
217
+ if (!state) {
218
+ return;
219
+ }
220
+ this.endOperation(state, error ?? new Error("Refused by a GraphQL request start hook"));
221
+ }
154
222
  /**
155
223
  * Opens a span for the operation about to be processed.
156
224
  *
@@ -213,6 +281,14 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
213
281
  if (!state) {
214
282
  return;
215
283
  }
284
+ this.endOperation(state, this.toSpanError(ctx.errors));
285
+ }
286
+ /** Closes the operation's span once, and ships a trace this service opened. */
287
+ endOperation(state, error) {
288
+ if (state.ended) {
289
+ return;
290
+ }
291
+ state.ended = true;
216
292
  if (state.store) {
217
293
  // Handing the request back whatever owned it before this operation. The
218
294
  // store is shared by reference across the request, so this is a real
@@ -224,8 +300,9 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
224
300
  state.store.set(CALLER_METADATA_KEY, state.previousCallerId);
225
301
  }
226
302
  }
227
- this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, this.toSpanError(ctx.errors));
303
+ this.operationTraceRegistry.internalEndTraceStep(state.traceId, `${state.className}#${state.methodKey}`, state.className, state.methodKey, state.spanId, error);
228
304
  if (state.ownsTrace) {
305
+ endOperation(state.store?.get(OPERATION_STATE_KEY));
229
306
  this.endOperationTrace(state.traceId, state.context);
230
307
  }
231
308
  }
@@ -277,6 +354,8 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
277
354
  const traceId = generateTraceIdSafely(this.options.traceIdGenerator, info, this.options, this.logger);
278
355
  const store = new Map();
279
356
  store.set(this.options.traceIdKey, traceId);
357
+ // Ended with the operation's trace: see `liveTraceId`.
358
+ openOperation(store);
280
359
  this.asyncLocalStorage.enterWith(store);
281
360
  this.applyAttributes(info, ctx.context);
282
361
  this.operationTraceRegistry.startTrace(traceId, {
@@ -348,13 +427,24 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
348
427
  * `GraphQLError` wrapping it, because that is the error the registry
349
428
  * classifies: an `IntrinsicException` a handler raised on purpose reads as
350
429
  * handled, and it stops being recognisable once GraphQL has wrapped it.
430
+ *
431
+ * An error graphql refused the request with is recorded by its class and
432
+ * code alone - see `toRefusal`.
351
433
  */
352
434
  toSpanError(errors) {
353
435
  const [first] = errors ?? [];
354
436
  if (!first) {
355
437
  return undefined;
356
438
  }
357
- return first.originalError ?? first;
439
+ const original = first.originalError;
440
+ const error = original ?? first;
441
+ // No path: raised by parsing, validation or the coercion of variables,
442
+ // before any resolver ran. A path, and an original error pointing at
443
+ // syntax of its own: an argument refused as its field was executed. A
444
+ // resolver's own error points at none.
445
+ return first.path == null || original?.nodes != null
446
+ ? toRefusal(first, error)
447
+ : error;
358
448
  }
359
449
  lookupResolverHandler(rootTypeName, fieldName) {
360
450
  this.resolverIndex ??= this.buildResolverIndex();
@@ -423,3 +513,74 @@ GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
423
513
  MetadataScanner])
424
514
  ], GraphQLObserveAgentService);
425
515
  export { GraphQLObserveAgentService };
516
+ /**
517
+ * The end hook the host is given: the application's first, with what its own
518
+ * start hook returned, then this service's, whatever the application's did,
519
+ * so the span covers both and is closed either way.
520
+ */
521
+ function composeEndHook(application, agent) {
522
+ return function (ctx) {
523
+ const shared = readSharedState(ctx.state);
524
+ try {
525
+ application?.call(this, shared ? { ...ctx, state: shared.application } : ctx);
526
+ }
527
+ finally {
528
+ agent.call(this, { ...ctx, state: shared?.observe });
529
+ }
530
+ };
531
+ }
532
+ function toSharedState(shared) {
533
+ return { [SHARED_STATE]: shared };
534
+ }
535
+ /**
536
+ * The pair the start hook kept, from its result as the driver hands it on:
537
+ * the object it returned, the promise it returned to a driver that does not
538
+ * await it, or what that promise resolved to for one that does. Nothing for
539
+ * a state no start hook of ours produced.
540
+ */
541
+ function readSharedState(state) {
542
+ return typeof state === "object" && state !== null
543
+ ? state[SHARED_STATE]
544
+ : undefined;
545
+ }
546
+ function isThenable(value) {
547
+ return ((typeof value === "object" || typeof value === "function") &&
548
+ value !== null &&
549
+ typeof value.then === "function");
550
+ }
551
+ /**
552
+ * What a request graphql refused is recorded with: the error's class and its
553
+ * code, `GRAPHQL_VALIDATION_FAILED` or `BAD_USER_INPUT`, and nothing graphql
554
+ * worded. graphql words these errors around the value it refused - `String
555
+ * cannot represent a non string value: 489213`, `found String "..."` - which
556
+ * the recorded document shows blanked, and which no rule can blank in prose:
557
+ * a string is printed there unescaped. The stack is the message again, then
558
+ * frames of graphql and the server, not of the application.
559
+ */
560
+ function toRefusal(first, error) {
561
+ const code = first.extensions?.code ??
562
+ error.extensions?.code;
563
+ const message = typeof code === "string" && /^[A-Z][A-Z0-9_]*$/.test(code)
564
+ ? code
565
+ : "GraphQL request error";
566
+ const refusal = error instanceof Error
567
+ ? Object.create(Object.getPrototypeOf(error))
568
+ : new Error();
569
+ const name = error.constructor
570
+ ?.name;
571
+ // What the registry classifies a failure by: its class, kept above, and
572
+ // the status an `HttpException` thrown by a custom scalar answers with.
573
+ const status = error.status;
574
+ if (typeof status === "number") {
575
+ Object.defineProperty(refusal, "status", { value: status });
576
+ }
577
+ Object.defineProperties(refusal, {
578
+ message: { value: message, configurable: true, writable: true },
579
+ stack: {
580
+ value: `${typeof name === "string" && name ? name : "Error"}: ${message}`,
581
+ configurable: true,
582
+ writable: true,
583
+ },
584
+ });
585
+ return refusal;
586
+ }
@@ -11,12 +11,19 @@
11
11
  * runs on every operation, so it stops at the first field of the first
12
12
  * operation definition and never looks at the rest of the document.
13
13
  */
14
- /** Operation keywords, mapped to the root type each one resolves against. */
15
- const ROOT_TYPE_BY_KEYWORD = {
16
- query: "Query",
17
- mutation: "Mutation",
18
- subscription: "Subscription",
19
- };
14
+ /**
15
+ * Operation keywords, mapped to the root type each one resolves against.
16
+ *
17
+ * A `Map`, not an object literal: the key is the first word of a client's
18
+ * document, and `constructor` or `__proto__` found an inherited member there,
19
+ * whose labelling then threw inside the request hook - a 500 for a document
20
+ * the server would have answered.
21
+ */
22
+ const ROOT_TYPE_BY_KEYWORD = new Map([
23
+ ["query", "Query"],
24
+ ["mutation", "Mutation"],
25
+ ["subscription", "Subscription"],
26
+ ]);
20
27
  /**
21
28
  * Parsed results are cached: a client sends the same handful of documents over
22
29
  * and over, and re-scanning each one per request is pure waste. Bounded in
@@ -147,19 +154,33 @@ function toOperation(words, fieldName, source) {
147
154
  }
148
155
  // Shorthand - `{ orders { id } }` - has no keyword at all and is a query.
149
156
  const keyword = words[0] ? words[0].toLowerCase() : "query";
150
- const rootTypeName = ROOT_TYPE_BY_KEYWORD[keyword];
157
+ const rootTypeName = ROOT_TYPE_BY_KEYWORD.get(keyword);
151
158
  if (!rootTypeName) {
152
159
  return undefined;
153
160
  }
161
+ const operationName = words[0] ? words[1] : undefined;
162
+ // Whitespace is collapsed only here, at the end: `source` positions have to
163
+ // stay valid while the scan is still reading from it.
164
+ const sanitizedDocument = truncate(source.replace(/\s+/g, " ").trim());
165
+ // All three are cut from a string the size of the document, and V8 makes a
166
+ // cut a view that keeps the whole string it was cut from in memory. They
167
+ // outlive the request, on its trace until the batch is flushed, so past
168
+ // what the trace records they are copied out: a 100 kB document whose 8 kB
169
+ // the trace sent kept the 100 kB, twice over.
170
+ if (source.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
171
+ return { rootTypeName, fieldName, operationName, sanitizedDocument };
172
+ }
154
173
  return {
155
174
  rootTypeName,
156
- fieldName,
157
- operationName: words[0] ? words[1] : undefined,
158
- // Whitespace is collapsed only here, at the end: `source` positions have to
159
- // stay valid while the scan is still reading from it.
160
- sanitizedDocument: truncate(source.replace(/\s+/g, " ").trim()),
175
+ fieldName: ownCopy(fieldName),
176
+ operationName: operationName === undefined ? undefined : ownCopy(operationName),
177
+ sanitizedDocument: ownCopy(sanitizedDocument),
161
178
  };
162
179
  }
180
+ /** The same code units, lone surrogates included, in storage of their own. */
181
+ function ownCopy(value) {
182
+ return Buffer.from(value, "utf16le").toString("utf16le");
183
+ }
163
184
  function truncate(document) {
164
185
  if (document.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
165
186
  return document;
@@ -213,16 +234,20 @@ function stripIgnoredTokens(document) {
213
234
  let index = 0;
214
235
  while (index < document.length) {
215
236
  const char = document[index];
237
+ // A comment ends at either line terminator, as graphql-js ends it. Read on
238
+ // to the next `\n`, it swallowed what the server reads after a bare `\r` -
239
+ // the opening quotes of a block string included.
216
240
  if (char === "#") {
217
- while (index < document.length && document[index] !== "\n") {
241
+ while (index < document.length &&
242
+ document[index] !== "\n" &&
243
+ document[index] !== "\r") {
218
244
  index += 1;
219
245
  }
220
246
  continue;
221
247
  }
222
248
  if (char === '"') {
223
249
  if (document.startsWith('"""', index)) {
224
- const end = document.indexOf('"""', index + 3);
225
- index = end === -1 ? document.length : end + 3;
250
+ index = endOfBlockString(document, index + 3);
226
251
  }
227
252
  else {
228
253
  index += 1;
@@ -236,12 +261,27 @@ function stripIgnoredTokens(document) {
236
261
  out += "_";
237
262
  continue;
238
263
  }
264
+ // A name is copied whole, so a digit that continues one (`field2`,
265
+ // `$var1`) never reaches the number rule below. Whether a digit belongs
266
+ // to a name is read from the document, never from `out`: the `_` a
267
+ // literal leaves there is a name character itself, so the number straight
268
+ // after one - `["draft"489213]`, commas being optional - read as its
269
+ // tail, and indexing a string built with `+=` copied all of it, once per
270
+ // digit.
271
+ if (isNameStart(char)) {
272
+ const start = index;
273
+ index += 1;
274
+ while (index < document.length && isNameChar(document[index])) {
275
+ index += 1;
276
+ }
277
+ out += document.slice(start, index);
278
+ continue;
279
+ }
239
280
  // Numbers go the same way as strings. An inline `verifyOtp(code: 489213)`
240
281
  // or `charge(amount: 1999)` is user data exactly as a string literal is,
241
- // and blanking it also keeps `first: 10` and `first: 20` one shape. A
242
- // digit that continues a name (`field2`, `$var1`) is not a literal.
282
+ // and blanking it also keeps `first: 10` and `first: 20` one shape.
243
283
  const startsNumber = isDigit(char) || (char === "-" && isDigit(document[index + 1] ?? ""));
244
- if (startsNumber && !isNameChar(out[out.length - 1] ?? "")) {
284
+ if (startsNumber) {
245
285
  index += 1;
246
286
  while (index < document.length && isNumberChar(document, index)) {
247
287
  index += 1;
@@ -254,6 +294,20 @@ function stripIgnoredTokens(document) {
254
294
  }
255
295
  return out;
256
296
  }
297
+ /**
298
+ * Where a block string that opened before `from` ends, its closing quotes
299
+ * included. `\"""` is three quotes of content, as graphql-js reads it, not the
300
+ * end: ended there, the rest of the literal was recorded as document syntax.
301
+ * A block string has no other escape, so a backslash before the quotes always
302
+ * escapes them.
303
+ */
304
+ function endOfBlockString(document, from) {
305
+ let end = document.indexOf('"""', from);
306
+ while (end > from && document[end - 1] === "\\") {
307
+ end = document.indexOf('"""', end + 3);
308
+ }
309
+ return end === -1 ? document.length : end + 3;
310
+ }
257
311
  function isDigit(char) {
258
312
  return char >= "0" && char <= "9";
259
313
  }