@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
@@ -13,15 +13,29 @@ export declare function invokeUserCallbackSafely<TArgs extends unknown[], TResul
13
13
  * traced under a registry key of its own.
14
14
  */
15
15
  export declare function generateTraceIdSafely(generator: (context: unknown) => string, context: unknown, receiver: unknown, logger: Logger): string;
16
- /** Copies an operation's `setAttributes` into its store, unless it throws. */
17
- export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string): void;
16
+ /**
17
+ * Copies an operation's `setAttributes` into its store, unless it throws.
18
+ *
19
+ * An attribute named `traceIdKey`, or like one of `AGENT_STORE_KEYS`, is left
20
+ * out: the store keeps the agent's own entry there. The first such key each
21
+ * callback returns is reported; later ones are not.
22
+ */
23
+ export declare function setAttributesSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => Record<string, unknown>) | undefined, args: TArgs, receiver: unknown, store: Map<any, unknown>, logger: Logger, transport: string, traceIdKey: string): void;
18
24
  /**
19
25
  * Whether `ignore` excludes an operation. One that throws excludes it as
20
26
  * well: the operation still runs, but recording what a broken predicate may
21
27
  * have been written to keep out is not a safe guess.
22
28
  */
23
29
  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. */
30
+ /**
31
+ * A bad identity callback must not prevent the trace from being closed.
32
+ *
33
+ * Made a string here, inside the guard, rather than by whoever records it: a
34
+ * callback typed to return a string can still hand back what a message
35
+ * carried - a TCP packet's metadata is whatever `JSON.parse` made of it - and
36
+ * `String()` throws on `{"toString": 1}`. Thrown between ending the trace and
37
+ * plucking it, that left the trace registered for the life of the process.
38
+ */
25
39
  export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
40
  /**
27
41
  * Completes a trace once its operation has ended, without ever leaking a
@@ -1,3 +1,6 @@
1
+ import { CALLER_METADATA_KEY, TRACE_CONTEXT_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
+ import { OPERATION_STATE_KEY } from "../utils/operation-state.util.js";
3
+ import { setThroughCopies } from "../utils/store-copy.util.js";
1
4
  import { uuidv7 } from "../utils/uuid-v7.util.js";
2
5
  const reportedCallbacks = new WeakSet();
3
6
  const reportedDeferredFailures = new WeakSet();
@@ -30,13 +33,22 @@ export function invokeUserCallbackSafely(callback, args, receiver, fallback, log
30
33
  return callback.apply(receiver, args);
31
34
  }
32
35
  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
- }
36
+ reportCallbackFailure(callback, logger, name, "threw", outcome, error);
37
37
  return fallback();
38
38
  }
39
39
  }
40
+ /**
41
+ * Reports the first failure of a callback, whichever way it failed: a
42
+ * callback that both throws and returns what cannot be used still says so
43
+ * once.
44
+ */
45
+ function reportCallbackFailure(callback, logger, name, failure, outcome, error) {
46
+ if (reportedCallbacks.has(callback)) {
47
+ return;
48
+ }
49
+ reportedCallbacks.add(callback);
50
+ warnSafely(logger, `"${name}" ${failure}; ${outcome}. Later failures are not reported: ${describeFailure(error)}`);
51
+ }
40
52
  /**
41
53
  * The trace id for an operation. A generator that throws is replaced by a
42
54
  * fresh uuidv7, which no open trace can share, so the operation is still
@@ -45,8 +57,31 @@ export function invokeUserCallbackSafely(callback, args, receiver, fallback, log
45
57
  export function generateTraceIdSafely(generator, context, receiver, logger) {
46
58
  return invokeUserCallbackSafely(generator, [context], receiver, uuidv7, logger, "traceIdGenerator", "using a random trace id");
47
59
  }
48
- /** Copies an operation's `setAttributes` into its store, unless it throws. */
49
- export function setAttributesSafely(callback, args, receiver, store, logger, transport) {
60
+ /**
61
+ * What the agent keeps in an operation's store for itself, beside the trace
62
+ * id under `traceIdKey`. Attributes share that store, and their names can
63
+ * come from a sender - a message's metadata, a query string spread into the
64
+ * result - so one named like any of these is left out rather than written
65
+ * over the agent's own entry. A trace id that arrived that way had been
66
+ * through none of the checks an `x-request-id` goes through, and was sent on
67
+ * to every service called downstream; a registry key or a caller that
68
+ * arrived that way detached the operation from its trace.
69
+ */
70
+ const AGENT_STORE_KEYS = new Set([
71
+ CALLER_METADATA_KEY,
72
+ TRACE_REGISTRY_KEY,
73
+ TRACE_CONTEXT_KEY,
74
+ OPERATION_STATE_KEY,
75
+ ]);
76
+ const reportedReservedKeys = new WeakSet();
77
+ /**
78
+ * Copies an operation's `setAttributes` into its store, unless it throws.
79
+ *
80
+ * An attribute named `traceIdKey`, or like one of `AGENT_STORE_KEYS`, is left
81
+ * out: the store keeps the agent's own entry there. The first such key each
82
+ * callback returns is reported; later ones are not.
83
+ */
84
+ export function setAttributesSafely(callback, args, receiver, store, logger, transport, traceIdKey) {
50
85
  if (!callback) {
51
86
  return;
52
87
  }
@@ -54,8 +89,19 @@ export function setAttributesSafely(callback, args, receiver, store, logger, tra
54
89
  if (!attributes) {
55
90
  return;
56
91
  }
92
+ // Through to the stores this one was copied from, as `setAttribute` writes:
93
+ // an operation started inside a span - GraphQL's, in a request whose
94
+ // middleware set the same key - is the later write, and the one the rest
95
+ // of the request should read.
57
96
  for (const [key, value] of Object.entries(attributes)) {
58
- store.set(key, value);
97
+ if (key === traceIdKey || AGENT_STORE_KEYS.has(key)) {
98
+ if (!reportedReservedKeys.has(callback)) {
99
+ reportedReservedKeys.add(callback);
100
+ warnSafely(logger, `"${transport}.setAttributes" returned an attribute named "${key.slice(0, 100)}", a key the agent keeps for itself; it is left out. Later ones are not reported.`);
101
+ }
102
+ continue;
103
+ }
104
+ setThroughCopies(store, key, value);
59
105
  }
60
106
  }
61
107
  /**
@@ -69,12 +115,33 @@ export function shouldIgnoreSafely(callback, args, receiver, logger, transport)
69
115
  }
70
116
  return invokeUserCallbackSafely(callback, args, receiver, () => true, logger, `${transport}.ignore`, "not tracing the operation");
71
117
  }
72
- /** A bad identity callback must not prevent the trace from being closed. */
118
+ /**
119
+ * A bad identity callback must not prevent the trace from being closed.
120
+ *
121
+ * Made a string here, inside the guard, rather than by whoever records it: a
122
+ * callback typed to return a string can still hand back what a message
123
+ * carried - a TCP packet's metadata is whatever `JSON.parse` made of it - and
124
+ * `String()` throws on `{"toString": 1}`. Thrown between ending the trace and
125
+ * plucking it, that left the trace registered for the life of the process.
126
+ */
73
127
  export function getUserIdSafely(callback, args, receiver, logger, transport) {
74
128
  if (!callback) {
75
129
  return undefined;
76
130
  }
77
- return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
131
+ const name = `${transport}.getUserId`;
132
+ const outcome = "completing the trace without a user id";
133
+ const userId = invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, name, outcome);
134
+ if (userId === undefined || typeof userId === "string") {
135
+ return userId;
136
+ }
137
+ try {
138
+ // oxlint-disable-next-line typescript/no-base-to-string -- recorded as `String()` always recorded it
139
+ return String(userId);
140
+ }
141
+ catch (error) {
142
+ reportCallbackFailure(callback, logger, name, "returned a value that cannot be made a string", outcome, error);
143
+ return undefined;
144
+ }
78
145
  }
79
146
  /**
80
147
  * 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
@@ -31,12 +38,20 @@ interface OperationState {
31
38
  spanId: string;
32
39
  className: string;
33
40
  methodKey: string;
34
- /** The caller this operation displaced, restored once it ends. */
41
+ /**
42
+ * The caller this operation displaced - for one of a batch, the caller the
43
+ * first of them displaced - restored once the last one open has ended.
44
+ */
35
45
  previousCallerId: string | undefined;
36
46
  store: Map<string, unknown> | undefined;
37
47
  /** Whether this service opened the trace, and therefore has to ship it. */
38
48
  ownsTrace: boolean;
39
49
  context: unknown;
50
+ /**
51
+ * Closed already: by the end hook, or refused by the application's start
52
+ * hook. See `openOperationsByStore` too.
53
+ */
54
+ ended?: boolean;
40
55
  }
41
56
  /**
42
57
  * GraphQL operation instrumentation.
@@ -53,7 +68,8 @@ interface OperationState {
53
68
  * document is processed, `setOnRequestEndHook` once it has been, right before
54
69
  * the response goes out. Whatever the start hook returns is handed back as
55
70
  * `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.
71
+ * second. This service uses both and gives each operation a span, beside any
72
+ * hooks the application sets there - see `composeStartHook`.
57
73
  *
58
74
  * The span goes into the trace the HTTP agent already opened whenever there is
59
75
  * one, which keeps the shape a reader expects: one snapshot per HTTP request,
@@ -87,9 +103,67 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
87
103
  * after the schema is built.
88
104
  */
89
105
  private resolverIndex;
106
+ /**
107
+ * The operations each async store has open, in the order they started.
108
+ *
109
+ * Usually one. A batched HTTP request (Apollo's `allowBatchedHttpRequests`)
110
+ * is the exception: its operations run at once in the one store the
111
+ * request has, so the caller a later one found there was the span of the
112
+ * one before it - a sibling, not a caller - and they end in any order.
113
+ * Nested that way, the trace was as deep as the client made the batch
114
+ * long, and a failure behind the first operation was on no root span, so
115
+ * the request was reported as a success.
116
+ *
117
+ * Beside the store rather than in it: a span's store is a copy of its
118
+ * caller's, and an operation started inside the copy really is a callee.
119
+ * Weakly keyed, so an unmatched start - see `onRequestEnd` - leaves
120
+ * nothing behind once the request's store is gone.
121
+ */
122
+ private readonly openOperationsByStore;
90
123
  constructor(asyncLocalStorage: AsyncLocalStorage<Map<KeyOf<Store>, any>>, options: ObserveModuleOptionsWithDefaults, operationTraceRegistry: OperationTraceRegistry, observeAgentSharedBuffer: ObserveAgentSharedBuffer, traceSamplerService: TraceSamplerService, moduleRef: ModuleRef, discoveryService: DiscoveryService, metadataScanner: MetadataScanner);
91
124
  onModuleInit(): Promise<void>;
92
125
  registerRequestHooksIfPossible(): Promise<void>;
126
+ /**
127
+ * Has `@nestjs/graphql` apply a resolver's methods to the instance itself
128
+ * where the instrumentation proxy cannot be their receiver.
129
+ *
130
+ * The explorer reads each `@Query`, `@Mutation`, `@Subscription` and
131
+ * `@ResolveField` method off the class prototype and applies it to the
132
+ * instance the container holds, which is the proxy. For a class with
133
+ * private members (`this.#x`), whose methods only the instance itself can
134
+ * run against, the first such read threw: the proxy only helps the methods
135
+ * read through it. `createContextCallback` is where every one of them is
136
+ * paired with its instance, the field resolvers' fast path included, so
137
+ * that is where the instance behind the proxy is handed over instead -
138
+ * what the explorer would have held without the agent. Only the receiver
139
+ * changes: the method is still the class's own, so `getHandler()`, guards,
140
+ * pipes and interceptors see what they saw before, and no span is added,
141
+ * as none is for any other resolver. A request-scoped resolver reads its
142
+ * method through the instance already, and is left alone.
143
+ *
144
+ * Patched on the prototype from the constructor, which Nest runs before any
145
+ * `onModuleInit`, `GraphQLModule`'s included, where the explorer does its
146
+ * work - synchronously, for the reason given on `loadOptionalPeer`. The
147
+ * original is parked under a symbol, so a second agent replaces the wrapper
148
+ * instead of wrapping it again.
149
+ */
150
+ private patchResolversExplorer;
151
+ /**
152
+ * The start hook the host is given: this service's part first, so the span
153
+ * covers the application's hook, then the application's, whose result is
154
+ * kept for its own end hook.
155
+ *
156
+ * An application's start hook that throws refuses the document: the driver
157
+ * answers with the error and calls no end hook. The span is closed here
158
+ * then, with the application's error, so the refusal is recorded as a
159
+ * failed operation. A start hook that returns a promise gets one back, and
160
+ * only then - a driver that awaits the hook awaits it, and one that does
161
+ * not hands it to the end hook as the state, which is why the pair is also
162
+ * kept on the promise itself. Its rejection closes the span the same way,
163
+ * and travels on in the promise returned, to a driver that awaits it.
164
+ */
165
+ private composeStartHook;
166
+ private closeRefused;
93
167
  /**
94
168
  * Opens a span for the operation about to be processed.
95
169
  *
@@ -116,6 +190,8 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
116
190
  * its status code and no spans under it.
117
191
  */
118
192
  onRequestEnd(ctx: GqlRequestEndContext): void;
193
+ /** Closes the operation's span once, and ships a trace this service opened. */
194
+ private endOperation;
119
195
  /**
120
196
  * The common case: the operation arrived over an HTTP request the HTTP agent
121
197
  * already opened a trace for. The operation becomes a root span in that trace
@@ -154,6 +230,18 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
154
230
  * beside it.
155
231
  */
156
232
  private openSpan;
233
+ /**
234
+ * Takes the operations that have ended off the ones a store has open, and
235
+ * returns the caller the store names from here on.
236
+ *
237
+ * While another operation is open there, that is the one of them that
238
+ * started last, whichever just ended: the work still running in the store
239
+ * belongs to an open operation, and a slot emptied or left naming an ended
240
+ * span put it at the root of the trace, beside the operation, and had
241
+ * `activeSpan()` find nothing. Once the last has ended, it is the caller
242
+ * they displaced.
243
+ */
244
+ private closeOperation;
157
245
  /**
158
246
  * Ends and ships a trace this service opened itself.
159
247
  *
@@ -170,6 +258,9 @@ export declare class GraphQLObserveAgentService<Store extends Record<string, unk
170
258
  * `GraphQLError` wrapping it, because that is the error the registry
171
259
  * classifies: an `IntrinsicException` a handler raised on purpose reads as
172
260
  * handled, and it stops being recognisable once GraphQL has wrapped it.
261
+ *
262
+ * An error graphql refused the request with is recorded by its class and
263
+ * code alone - see `toRefusal`.
173
264
  */
174
265
  private toSpanError;
175
266
  private lookupResolverHandler;