@nestjs/observe 0.3.18 → 0.3.19

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.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export declare const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export declare const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export declare const LINK_COMMAND = "npx @nestjs/observe link";
12
+ export interface CredentialsNotice {
13
+ level: "log" | "warn";
14
+ message: string;
15
+ }
16
+ /**
17
+ * The one line the agent says at start-up when it has no key pair it can send
18
+ * with, so it sends nothing.
19
+ *
20
+ * Two situations look alike from inside the process and want opposite advice.
21
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
22
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
23
+ * step. A deployed process with the same placeholders, or with nothing at
24
+ * all, is almost always a project that was connected on a laptop: link keeps
25
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
26
+ * loads, so production needs the two variables set where it runs. Telling
27
+ * that person to create an account sends them looking for something they
28
+ * already have, so under `NODE_ENV=production` the notice names the
29
+ * variables instead.
30
+ *
31
+ * @param scaffold the options still hold `nest new`'s placeholders
32
+ * @param unset which half of the pair is missing, when the options hold no
33
+ * placeholders but lack a key, a secret or both
34
+ */
35
+ export declare function describeMissingCredentials(input: {
36
+ scaffold: boolean;
37
+ unset?: "both" | "appKey" | "appSecret";
38
+ production: boolean;
39
+ }): CredentialsNotice;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Where a project generated by `nest new` points before it is connected: the
3
+ * hosted demo, which shows what the dashboard will look like.
4
+ */
5
+ export const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
6
+ export const SIGN_UP_URL = "https://observe.nestjs.com";
7
+ /**
8
+ * The command that connects a project in one step: it signs the developer in,
9
+ * writes the key pair into `.env` and makes the start scripts load it.
10
+ */
11
+ export const LINK_COMMAND = "npx @nestjs/observe link";
12
+ /** The variables `ObserveModule` reads a key pair from when its options leave it out. */
13
+ const KEY_VARIABLES = "OBSERVE_APP_KEY and OBSERVE_APP_SECRET";
14
+ /**
15
+ * The one line the agent says at start-up when it has no key pair it can send
16
+ * with, so it sends nothing.
17
+ *
18
+ * Two situations look alike from inside the process and want opposite advice.
19
+ * A project fresh from `nest new` still holds the scaffolded placeholders:
20
+ * the fix is to connect it, which `npx @nestjs/observe link` does in one
21
+ * step. A deployed process with the same placeholders, or with nothing at
22
+ * all, is almost always a project that was connected on a laptop: link keeps
23
+ * the pair in `.env`, which is git-ignored and which `node dist/main` never
24
+ * loads, so production needs the two variables set where it runs. Telling
25
+ * that person to create an account sends them looking for something they
26
+ * already have, so under `NODE_ENV=production` the notice names the
27
+ * variables instead.
28
+ *
29
+ * @param scaffold the options still hold `nest new`'s placeholders
30
+ * @param unset which half of the pair is missing, when the options hold no
31
+ * placeholders but lack a key, a secret or both
32
+ */
33
+ export function describeMissingCredentials(input) {
34
+ if (input.production) {
35
+ const state = input.scaffold
36
+ ? "appKey and appSecret are still the placeholders from nest new"
37
+ : `${describeUnset(input.unset)} not set`;
38
+ return {
39
+ level: "warn",
40
+ message: `Observe is installed but sends nothing: ${state}. ` +
41
+ `Set ${KEY_VARIABLES} in this environment, then restart the process - ` +
42
+ `${LINK_COMMAND} keeps the pair in .env, which is not deployed. ` +
43
+ `The pair is on your project's API Keys page at ${SIGN_UP_URL}.`,
44
+ };
45
+ }
46
+ if (input.scaffold) {
47
+ return {
48
+ level: "log",
49
+ message: `Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
50
+ `Run ${LINK_COMMAND} in this project to connect it, or see what this app will look like first: ${DEMO_URL}`,
51
+ };
52
+ }
53
+ // Said as a warning: a project that names no placeholders was wired by
54
+ // hand, so a missing half is configuration that did not arrive.
55
+ return {
56
+ level: "warn",
57
+ message: `Observe is installed but sends nothing: ${describeUnset(input.unset)} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
58
+ `If they come from the environment, check that ${KEY_VARIABLES} reach this process, then restart it. ` +
59
+ `To get a pair, run ${LINK_COMMAND} or create one at ${SIGN_UP_URL}.`,
60
+ };
61
+ }
62
+ function describeUnset(unset = "both") {
63
+ return unset === "both"
64
+ ? "appKey and appSecret are"
65
+ : unset === "appKey"
66
+ ? "appKey is"
67
+ : "appSecret is";
68
+ }
@@ -2,6 +2,7 @@ import { DEGRADED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-inge
2
2
  import { detachedObserveWorker } from "./detached-observe-worker.js";
3
3
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
4
4
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
5
+ import { readSdkVersion } from "../utils/sdk-version.util.js";
5
6
  /**
6
7
  * How the telemetry worker is put together, in one place.
7
8
  *
@@ -26,6 +27,7 @@ export function detachedWorkerData(input) {
26
27
  wireShapes: SECTION_SHAPES,
27
28
  degradedPrefix: DEGRADED_MESSAGE_PREFIX,
28
29
  pausedPrefix: PAUSED_MESSAGE_PREFIX,
30
+ sdkVersion: readSdkVersion(),
29
31
  };
30
32
  return { sharedBuffer: input.sharedBuffer, config };
31
33
  }
@@ -23,6 +23,11 @@ export interface DetachedWorkerConfig {
23
23
  degradedPrefix: string;
24
24
  /** `PAUSED_MESSAGE_PREFIX`, as data, for the same reason. */
25
25
  pausedPrefix: string;
26
+ /**
27
+ * This package's version (`readSdkVersion`), read on the main thread: the
28
+ * worker runs as eval'd source and cannot resolve a manifest of its own.
29
+ */
30
+ sdkVersion: string;
26
31
  }
27
32
  export interface DetachedWorkerData {
28
33
  sharedBuffer: SharedArrayBuffer;
@@ -68,6 +68,9 @@ describeRefusal) => {
68
68
  // config key would put a broken header on every batch. The value is
69
69
  // pinned by worker-degraded-reply.spec.ts.
70
70
  "x-observe-ingest-modes": "reduced, trimmed, paced, errors-only",
71
+ // Which agent sent the batch, so the collector can tell an application
72
+ // still on an old release that a newer one exists.
73
+ "x-observe-sdk-version": config.sdkVersion,
71
74
  };
72
75
  // Omitted rather than sent empty when unconfigured: a collector in
73
76
  // placeholder mode accepts an unauthenticated batch, and blank credentials
@@ -23,6 +23,7 @@ import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.serv
23
23
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
24
24
  import { parseDegradedMessage, parseOveragePauseReason, parsePausedMessage, } from "./degraded-ingest.protocol.js";
25
25
  import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
26
+ import { describeMissingCredentials, SIGN_UP_URL, } from "./credentials-notice.js";
26
27
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
27
28
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
28
29
  const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
@@ -75,8 +76,6 @@ const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
75
76
  */
76
77
  const SCAFFOLD_APP_KEY = "YOUR_APP_KEY";
77
78
  const SCAFFOLD_APP_SECRET = "YOUR_APP_SECRET";
78
- const DEMO_URL = "https://www.observe-demo.nestjs.com/dashboard";
79
- const SIGN_UP_URL = "https://observe.nestjs.com";
80
79
  const DASHBOARD_URL = `${SIGN_UP_URL}/dashboard`;
81
80
  let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
82
81
  observeAgentSharedBuffer;
@@ -133,23 +132,25 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
133
132
  // needs no key or secret, so a missing one is not worth a warning.
134
133
  this.logger.log("Observe is disabled (enabled: false): nothing is recorded or sent.");
135
134
  }
136
- else if (this.hasScaffoldCredentials) {
135
+ else if (this.hasScaffoldCredentials || this.lacksHostedCredentials) {
137
136
  // Nothing is sent, so there is no worker to start. The flush timer below
138
137
  // still runs and empties the buffer, which the instrumentation keeps
139
138
  // writing into either way.
140
- this.logger.log(`Observe is installed but not connected yet: appKey and appSecret are still the placeholders from nest new, so no telemetry is sent. ` +
141
- `See what this app will look like: ${DEMO_URL} - then create a free account at ${SIGN_UP_URL} for your own key and secret.`);
142
- }
143
- else if (this.lacksHostedCredentials) {
144
- // The same arrangement, said as a warning: this is a deployment missing
145
- // its configuration, not a project fresh from the generator.
146
- const unset = !this.options.appKey && !this.options.appSecret
147
- ? "appKey and appSecret are"
148
- : !this.options.appKey
149
- ? "appKey is"
150
- : "appSecret is";
151
- this.logger.warn(`Observe is installed but sends nothing: ${unset} not set, and the hosted collector accepts no telemetry without a key and a secret. ` +
152
- `If they come from the environment, check that both variables reach this process, then restart it. Create a key and secret at ${SIGN_UP_URL}.`);
139
+ const notice = describeMissingCredentials({
140
+ scaffold: this.hasScaffoldCredentials,
141
+ unset: !this.options.appKey && !this.options.appSecret
142
+ ? "both"
143
+ : !this.options.appKey
144
+ ? "appKey"
145
+ : "appSecret",
146
+ production: process.env.NODE_ENV === "production",
147
+ });
148
+ if (notice.level === "warn") {
149
+ this.logger.warn(notice.message);
150
+ }
151
+ else {
152
+ this.logger.log(notice.message);
153
+ }
153
154
  }
154
155
  else {
155
156
  this.initializeWorker();
@@ -0,0 +1,27 @@
1
+ import type { Logger } from "@nestjs/common";
2
+ /**
3
+ * Runs a callback from the module options, answering `fallback()` when it
4
+ * throws. These callbacks only shape what is recorded, so a bug in one must
5
+ * not fail the request, message or job being recorded - or, thrown from a
6
+ * timer, end the process. The first failure of each callback is reported
7
+ * with its error and `outcome`, what was given up for it; later ones are not.
8
+ */
9
+ export declare function invokeUserCallbackSafely<TArgs extends unknown[], TResult, TFallback>(callback: (...args: TArgs) => TResult, args: TArgs, receiver: unknown, fallback: () => TFallback, logger: Logger, name: string, outcome: string): TResult | TFallback;
10
+ /**
11
+ * The trace id for an operation. A generator that throws is replaced by a
12
+ * fresh uuidv7, which no open trace can share, so the operation is still
13
+ * traced under a registry key of its own.
14
+ */
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;
18
+ /**
19
+ * Whether `ignore` excludes an operation. One that throws excludes it as
20
+ * well: the operation still runs, but recording what a broken predicate may
21
+ * have been written to keep out is not a safe guess.
22
+ */
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. */
25
+ export declare function getUserIdSafely<TArgs extends unknown[]>(callback: ((...args: TArgs) => string | undefined) | undefined, args: TArgs, receiver: unknown, logger: Logger, transport: string): string | undefined;
26
+ /** Run deferred completion without ever leaking a rejection from its timer. */
27
+ export declare function deferTraceCompletion(completion: () => Promise<void>, logger: Logger, transport: string): void;
@@ -0,0 +1,91 @@
1
+ import { uuidv7 } from "../utils/uuid-v7.util.js";
2
+ const reportedCallbacks = new WeakSet();
3
+ const reportedDeferredFailures = new WeakSet();
4
+ function describeFailure(error) {
5
+ try {
6
+ return error instanceof Error ? error.message : String(error);
7
+ }
8
+ catch {
9
+ return "an unprintable error";
10
+ }
11
+ }
12
+ function warnSafely(logger, message) {
13
+ try {
14
+ logger.warn(message);
15
+ }
16
+ catch {
17
+ // Diagnostics must not become another failure in the operation traced -
18
+ // or in its deferred telemetry.
19
+ }
20
+ }
21
+ /**
22
+ * Runs a callback from the module options, answering `fallback()` when it
23
+ * throws. These callbacks only shape what is recorded, so a bug in one must
24
+ * not fail the request, message or job being recorded - or, thrown from a
25
+ * timer, end the process. The first failure of each callback is reported
26
+ * with its error and `outcome`, what was given up for it; later ones are not.
27
+ */
28
+ export function invokeUserCallbackSafely(callback, args, receiver, fallback, logger, name, outcome) {
29
+ try {
30
+ return callback.apply(receiver, args);
31
+ }
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
+ }
37
+ return fallback();
38
+ }
39
+ }
40
+ /**
41
+ * The trace id for an operation. A generator that throws is replaced by a
42
+ * fresh uuidv7, which no open trace can share, so the operation is still
43
+ * traced under a registry key of its own.
44
+ */
45
+ export function generateTraceIdSafely(generator, context, receiver, logger) {
46
+ return invokeUserCallbackSafely(generator, [context], receiver, uuidv7, logger, "traceIdGenerator", "using a random trace id");
47
+ }
48
+ /** Copies an operation's `setAttributes` into its store, unless it throws. */
49
+ export function setAttributesSafely(callback, args, receiver, store, logger, transport) {
50
+ if (!callback) {
51
+ return;
52
+ }
53
+ const attributes = invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.setAttributes`, "continuing without its attributes");
54
+ if (!attributes) {
55
+ return;
56
+ }
57
+ for (const [key, value] of Object.entries(attributes)) {
58
+ store.set(key, value);
59
+ }
60
+ }
61
+ /**
62
+ * Whether `ignore` excludes an operation. One that throws excludes it as
63
+ * well: the operation still runs, but recording what a broken predicate may
64
+ * have been written to keep out is not a safe guess.
65
+ */
66
+ export function shouldIgnoreSafely(callback, args, receiver, logger, transport) {
67
+ if (!callback) {
68
+ return false;
69
+ }
70
+ return invokeUserCallbackSafely(callback, args, receiver, () => true, logger, `${transport}.ignore`, "not tracing the operation");
71
+ }
72
+ /** A bad identity callback must not prevent the trace from being closed. */
73
+ export function getUserIdSafely(callback, args, receiver, logger, transport) {
74
+ if (!callback) {
75
+ return undefined;
76
+ }
77
+ return invokeUserCallbackSafely(callback, args, receiver, () => undefined, logger, `${transport}.getUserId`, "completing the trace without a user id");
78
+ }
79
+ /** Run deferred completion without ever leaking a rejection from its timer. */
80
+ export function deferTraceCompletion(completion, logger, transport) {
81
+ setTimeout(() => {
82
+ void Promise.resolve()
83
+ .then(completion)
84
+ .catch((error) => {
85
+ if (!reportedDeferredFailures.has(logger)) {
86
+ reportedDeferredFailures.add(logger);
87
+ warnSafely(logger, `Deferred ${transport} trace completion failed; later failures are not reported: ${describeFailure(error)}`);
88
+ }
89
+ });
90
+ }, 0);
91
+ }
@@ -19,6 +19,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS, TRACE_REGISTRY_KEY, } from "../ob
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
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  /**
23
24
  * Protocol recorded for a GraphQL operation that arrived over something other
24
25
  * than an instrumented HTTP request. A query over HTTP keeps `http` as its
@@ -172,7 +173,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
172
173
  ...parsed,
173
174
  operationName,
174
175
  });
175
- if (this.options.graphql?.ignore?.(info)) {
176
+ if (shouldIgnoreSafely(this.options.graphql?.ignore, [info], this.options.graphql, this.logger, "graphql")) {
176
177
  return undefined;
177
178
  }
178
179
  const operationId = `${info.parentType.name}.${info.fieldName}`;
@@ -273,7 +274,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
273
274
  if (!shouldCapture) {
274
275
  return undefined;
275
276
  }
276
- const traceId = this.options.traceIdGenerator(info);
277
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, info, this.options, this.logger);
277
278
  const store = new Map();
278
279
  store.set(this.options.traceIdKey, traceId);
279
280
  this.asyncLocalStorage.enterWith(store);
@@ -329,15 +330,15 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
329
330
  * operation out of the success bucket.
330
331
  */
331
332
  endOperationTrace(traceId, context) {
332
- setTimeout(async () => {
333
- const userId = this.options.graphql?.getUserId?.(context);
333
+ deferTraceCompletion(async () => {
334
+ const userId = getUserIdSafely(this.options.graphql?.getUserId, [context], this.options.graphql, this.logger, "graphql");
334
335
  this.operationTraceRegistry.endTrace(traceId, { userId });
335
336
  const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
336
337
  if (!snapshot) {
337
338
  return;
338
339
  }
339
340
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
340
- }, 0);
341
+ }, this.logger, "graphql");
341
342
  }
342
343
  /**
343
344
  * Picks the error a failed operation is recorded with.
@@ -408,13 +409,7 @@ let GraphQLObserveAgentService = GraphQLObserveAgentService_1 = class GraphQLObs
408
409
  if (!store) {
409
410
  return;
410
411
  }
411
- const attributes = this.options.graphql.setAttributes(info, context);
412
- if (!attributes) {
413
- return;
414
- }
415
- for (const [key, value] of Object.entries(attributes)) {
416
- store.set(key, value);
417
- }
412
+ setAttributesSafely(this.options.graphql.setAttributes, [info, context], this.options.graphql, store, this.logger, "graphql");
418
413
  }
419
414
  };
420
415
  GraphQLObserveAgentService = GraphQLObserveAgentService_1 = __decorate([
@@ -6,7 +6,7 @@ import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.
6
6
  import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
7
7
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
8
8
  import { KeyOf } from "../types/key-of.type.js";
9
- /** What the request hook reads of an Express or Fastify request. */
9
+ /** What the request hook reads of an Express, Fastify or Node request. */
10
10
  interface IncomingHttpRequest {
11
11
  url: string;
12
12
  method: string;
@@ -75,7 +75,7 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
75
75
  * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
76
76
  * with an `Access-Control-Request-Method` header - rather than by the
77
77
  * method alone, so an application's own `OPTIONS` handler is still traced.
78
- * Both adapters lower-case header names.
78
+ * Every adapter lower-cases header names.
79
79
  */
80
80
  private isUntracedPreflight;
81
81
  private shouldIgnoreRequest;
@@ -21,6 +21,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
21
21
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
22
22
  import { redactUrlQuery } from "../utils/redact-url-query.js";
23
23
  import { uuidv7 } from "../utils/uuid-v7.util.js";
24
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
24
25
  /**
25
26
  * How long an aborted request's handler gets to finish its spans before the
26
27
  * trace is dropped from the registry. Generous next to a typical handler, tiny
@@ -106,16 +107,9 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
106
107
  // identical object, one lookup fewer, and it is known to exist.
107
108
  const store = new Map();
108
109
  this.asyncLocalStorage.run(store, () => {
109
- const traceId = this.options.traceIdGenerator(req);
110
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, req, this.options, this.logger);
110
111
  store.set(this.options.traceIdKey, traceId);
111
- if (this.options.http?.setAttributes) {
112
- const attributes = this.options.http?.setAttributes?.(req);
113
- if (attributes) {
114
- for (const [key, value] of Object.entries(attributes)) {
115
- store.set(key, value);
116
- }
117
- }
118
- }
112
+ setAttributesSafely(this.options.http?.setAttributes, [req], this.options.http, store, this.logger, "http");
119
113
  // A request that is not recorded still carries its trace id, which an
120
114
  // adopted `x-request-id` can share with a recorded request. A registry
121
115
  // key of its own, never registered, keeps its lookups off that trace.
@@ -174,11 +168,8 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
174
168
  if (!traceId) {
175
169
  return;
176
170
  }
177
- setTimeout(async () => {
178
- let userId;
179
- if (this.options.http?.getUserId) {
180
- userId = this.options.http?.getUserId?.(req);
181
- }
171
+ deferTraceCompletion(async () => {
172
+ const userId = getUserIdSafely(this.options.http?.getUserId, [req], this.options.http, this.logger, "http");
182
173
  this.operationTraceRegistry.endTrace(traceId, {
183
174
  statusCode: res.statusCode,
184
175
  userId,
@@ -194,7 +185,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
194
185
  }
195
186
  }
196
187
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
197
- }, 0);
188
+ }, this.logger, "http");
198
189
  }
199
190
  /**
200
191
  * Frees the trace when the client goes away before the response finishes.
@@ -253,7 +244,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
253
244
  * Recognised by what the CORS spec defines a preflight to be - `OPTIONS`
254
245
  * with an `Access-Control-Request-Method` header - rather than by the
255
246
  * method alone, so an application's own `OPTIONS` handler is still traced.
256
- * Both adapters lower-case header names.
247
+ * Every adapter lower-cases header names.
257
248
  */
258
249
  isUntracedPreflight(req) {
259
250
  return (!this.options.http?.tracePreflights &&
@@ -262,7 +253,7 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
262
253
  }
263
254
  shouldIgnoreRequest(req) {
264
255
  if (typeof this.options.http?.ignore === "function") {
265
- return this.options.http.ignore(req);
256
+ return shouldIgnoreSafely(this.options.http.ignore, [req], this.options.http, this.logger, "http");
266
257
  }
267
258
  if (Array.isArray(this.options.http?.ignore)) {
268
259
  const blocklist = this.options.http.ignore;
@@ -271,13 +262,13 @@ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgent
271
262
  return req.url === item;
272
263
  }
273
264
  if (item instanceof RegExp) {
274
- return item.test(req.url);
265
+ return testIgnoreRegex(item, req.url);
275
266
  }
276
267
  if (typeof item === "object") {
277
268
  return (item.method === req.method &&
278
269
  (typeof item.path === "string"
279
270
  ? req.url === item.path
280
- : item.path.test(req.url)));
271
+ : testIgnoreRegex(item.path, req.url)));
281
272
  }
282
273
  return false;
283
274
  });
@@ -294,6 +285,18 @@ HttpObserveAgentService = HttpObserveAgentService_1 = __decorate([
294
285
  TraceSamplerService])
295
286
  ], HttpObserveAgentService);
296
287
  export { HttpObserveAgentService };
288
+ /**
289
+ * Global and sticky regular expressions carry a lastIndex between calls. Use
290
+ * a fresh expression for each ignore decision so matching always starts at the
291
+ * beginning without changing the user's regex state. Ordinary expressions
292
+ * are stateless here and can be tested directly.
293
+ */
294
+ function testIgnoreRegex(pattern, value) {
295
+ if (!pattern.global && !pattern.sticky) {
296
+ return pattern.test(value);
297
+ }
298
+ return new RegExp(pattern.source, pattern.flags).test(value);
299
+ }
297
300
  /**
298
301
  * Rebuilds a RegExp with the global flag when it lacks one, keeping the
299
302
  * original otherwise. `replaceAll` refuses a non-global pattern outright.
@@ -71,9 +71,9 @@ export declare class JobTraceRunner<Store extends Record<string, unknown>> {
71
71
  */
72
72
  private activeJobOf;
73
73
  /**
74
- * Whether `jobs.ignore` matches this run. A predicate that throws is
75
- * reported and read as "trace it": a bug in tracing configuration must not
76
- * stop the job itself from running.
74
+ * Whether `jobs.ignore` matches this run. A predicate that throws is read
75
+ * as a match, as every other protocol reads its own: the job still runs,
76
+ * just without a trace.
77
77
  */
78
78
  private isIgnored;
79
79
  /**
@@ -1,6 +1,7 @@
1
1
  import { JOB_TRACE_OPTION_KEY, TRACE_REGISTRY_KEY, } from "../observe.constants.js";
2
2
  import { REQUEST_ID_PATTERN } from "../utils/default-trace-id-generator.util.js";
3
3
  import { uuidv7 } from "../utils/uuid-v7.util.js";
4
+ import { deferTraceCompletion, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
4
5
  const ORIGINAL_ADD = Symbol.for("nestjs.observe.queue.add");
5
6
  const ORIGINAL_ADD_BULK = Symbol.for("nestjs.observe.queue.addBulk");
6
7
  /** Where a run records which job it is running, for a layer nested inside it. */
@@ -132,9 +133,9 @@ export class JobTraceRunner {
132
133
  : { queueName: job.queueName, id: String(job.id) };
133
134
  }
134
135
  /**
135
- * Whether `jobs.ignore` matches this run. A predicate that throws is
136
- * reported and read as "trace it": a bug in tracing configuration must not
137
- * stop the job itself from running.
136
+ * Whether `jobs.ignore` matches this run. A predicate that throws is read
137
+ * as a match, as every other protocol reads its own: the job still runs,
138
+ * just without a trace.
138
139
  */
139
140
  isIgnored(context) {
140
141
  // Jobs never reach the sampler, which is where every other protocol
@@ -142,13 +143,7 @@ export class JobTraceRunner {
142
143
  if (this.options.enabled === false) {
143
144
  return true;
144
145
  }
145
- try {
146
- return Boolean(this.options.jobs?.ignore?.(context));
147
- }
148
- catch (error) {
149
- this.logger.warn(`"jobs.ignore" threw for job "${context.name}" (queue "${context.queueName}"); tracing it anyway: ${error instanceof Error ? error.message : String(error)}`);
150
- return false;
151
- }
146
+ return shouldIgnoreSafely(this.options.jobs?.ignore, [context], this.options.jobs, this.logger, "jobs");
152
147
  }
153
148
  /**
154
149
  * Runs one job under a trace.
@@ -197,12 +192,7 @@ export class JobTraceRunner {
197
192
  name: job.name,
198
193
  id: typeof job.id === "number" ? `${job.id}` : job.id,
199
194
  };
200
- const attributes = this.options.jobs?.setAttributes?.(context);
201
- if (attributes) {
202
- for (const [key, value] of Object.entries(attributes)) {
203
- store.set(key, value);
204
- }
205
- }
195
+ setAttributesSafely(this.options.jobs?.setAttributes, [context], this.options.jobs, store, this.logger, "jobs");
206
196
  if (this.isIgnored(context)) {
207
197
  // The trace id stays in the store so logs and jobs enqueued from here
208
198
  // still correlate; nothing is registered under the registry key, so
@@ -220,13 +210,13 @@ export class JobTraceRunner {
220
210
  return;
221
211
  }
222
212
  settled = true;
223
- setTimeout(async () => {
213
+ deferTraceCompletion(async () => {
224
214
  this.operationTraceRegistry.endTrace(registryKey, { status });
225
215
  const snapshot = (await this.operationTraceRegistry.pluckSnapshot(registryKey));
226
216
  // `pluckSnapshot` deletes what it returns, so a trace already
227
217
  // plucked answers undefined, and the encoder would dereference it
228
- // inside a `setTimeout`, where no try/catch can reach: an unhandled
229
- // TypeError that took the whole process down.
218
+ // inside a `setTimeout`, where no try/catch can reach: an
219
+ // unhandled TypeError that took the whole process down.
230
220
  //
231
221
  // Dropped rather than reported: there is no snapshot, so there is
232
222
  // nothing to send, and losing one job's self-instrumentation is
@@ -235,7 +225,7 @@ export class JobTraceRunner {
235
225
  return;
236
226
  }
237
227
  this.observeAgentSharedBuffer.insertJobSnapshot(snapshot);
238
- }, 0);
228
+ }, this.logger, "job");
239
229
  };
240
230
  try {
241
231
  const returnValue = invoke(settle);
@@ -19,6 +19,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
21
21
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
22
+ import { deferTraceCompletion, generateTraceIdSafely, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentService {
23
24
  asyncLocalStorage;
24
25
  options;
@@ -110,17 +111,10 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
110
111
  // identical object, one lookup fewer, and it is known to exist.
111
112
  const store = new Map();
112
113
  return this.asyncLocalStorage.run(store, () => {
113
- const traceId = this.options.traceIdGenerator(ctx);
114
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, ctx, this.options, this.logger);
114
115
  store.set(this.options.traceIdKey, traceId);
115
- if (this.options.rpc?.setAttributes) {
116
- const attributes = this.options.rpc?.setAttributes?.(transportId, ctx);
117
- if (attributes) {
118
- for (const [key, value] of Object.entries(attributes)) {
119
- store.set(key, value);
120
- }
121
- }
122
- }
123
- if (this.options.rpc?.ignore?.(transportId, ctx)) {
116
+ setAttributesSafely(this.options.rpc?.setAttributes, [transportId, ctx], this.options.rpc, store, this.logger, "rpc");
117
+ if (shouldIgnoreSafely(this.options.rpc?.ignore, [transportId, ctx], this.options.rpc, this.logger, "rpc")) {
124
118
  return done();
125
119
  }
126
120
  const shouldCapture = this.traceSamplerService.shouldCapture("rpc", {
@@ -142,19 +136,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
142
136
  // As above: the map `run` is given, not looked back up.
143
137
  const store = new Map();
144
138
  return this.asyncLocalStorage.run(store, () => {
145
- const traceId = this.options.traceIdGenerator(call);
139
+ const traceId = generateTraceIdSafely(this.options.traceIdGenerator, call, this.options, this.logger);
146
140
  store.set(this.options.traceIdKey, traceId);
147
- if (this.options.grpc?.setAttributes) {
148
- const attributes = this.options.grpc?.setAttributes?.(call);
149
- if (attributes) {
150
- for (const [key, value] of Object.entries(attributes)) {
151
- store.set(key, value);
152
- }
153
- }
154
- }
141
+ setAttributesSafely(this.options.grpc?.setAttributes, [call], this.options.grpc, store, this.logger, "grpc");
155
142
  return new Promise((resolve) => {
143
+ // A throw in this timer escapes the promise: `done()` never runs, and
144
+ // the exception is uncaught. Both decisions below are guarded.
156
145
  setTimeout(() => {
157
- if (this.options.grpc?.ignore?.(call)) {
146
+ if (shouldIgnoreSafely(this.options.grpc?.ignore, [call], this.options.grpc, this.logger, "grpc")) {
158
147
  return resolve(done());
159
148
  }
160
149
  const shouldCapture = this.traceSamplerService.shouldCapture("grpc", {
@@ -182,17 +171,14 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
182
171
  if (!traceId) {
183
172
  return;
184
173
  }
185
- setTimeout(async () => {
174
+ const isGrpc = transportId === this.microservices.Transport.GRPC;
175
+ deferTraceCompletion(async () => {
186
176
  let userId;
187
- if (transportId === this.microservices.Transport.GRPC) {
188
- if (this.options.grpc?.getUserId) {
189
- userId = this.options.grpc?.getUserId?.(ctx);
190
- }
177
+ if (isGrpc) {
178
+ userId = getUserIdSafely(this.options.grpc?.getUserId, [ctx], this.options.grpc, this.logger, "grpc");
191
179
  }
192
180
  else {
193
- if (this.options.rpc?.getUserId) {
194
- userId = this.options.rpc?.getUserId?.(transportId, ctx);
195
- }
181
+ userId = getUserIdSafely(this.options.rpc?.getUserId, [transportId, ctx], this.options.rpc, this.logger, "rpc");
196
182
  }
197
183
  this.operationTraceRegistry.endTrace(traceId, {
198
184
  userId,
@@ -202,7 +188,7 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
202
188
  return;
203
189
  }
204
190
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
205
- }, 0);
191
+ }, this.logger, isGrpc ? "grpc" : "rpc");
206
192
  }
207
193
  getOperationIdFromContext(ctx) {
208
194
  const { KafkaContext, MqttContext, NatsContext, RedisContext, RmqContext, TcpContext, } = this.microservices;
@@ -19,6 +19,7 @@ import { OperationTraceRegistry } from "../services/operation-trace.registry.js"
19
19
  import { TraceSamplerService } from "../services/trace-sampler.service.js";
20
20
  import { describePeerLoadError, loadOptionalPeer, } from "../utils/optional-peer.util.js";
21
21
  import { uuidv7 } from "../utils/uuid-v7.util.js";
22
+ import { deferTraceCompletion, getUserIdSafely, setAttributesSafely, shouldIgnoreSafely, } from "./deferred-trace-completion.js";
22
23
  const ORIGINAL_CREATE = Symbol.for("nestjs.observe.ws.create");
23
24
  /** `@nestjs/websockets`' MESSAGE_METADATA - what `@SubscribeMessage()` writes. */
24
25
  const MESSAGE_METADATA = "message";
@@ -120,13 +121,8 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
120
121
  return this.asyncLocalStorage.run(store, () => {
121
122
  const traceId = uuidv7();
122
123
  store.set(this.options.traceIdKey, traceId);
123
- const attributes = this.options.ws?.setAttributes?.(message);
124
- if (attributes) {
125
- for (const [key, value] of Object.entries(attributes)) {
126
- store.set(key, value);
127
- }
128
- }
129
- if (this.options.ws?.ignore?.(message) ||
124
+ setAttributesSafely(this.options.ws?.setAttributes, [message], this.options.ws, store, this.logger, "ws");
125
+ if (shouldIgnoreSafely(this.options.ws?.ignore, [message], this.options.ws, this.logger, "ws") ||
130
126
  !this.traceSamplerService.shouldCapture("ws", {
131
127
  gateway: message.gateway,
132
128
  pattern: message.pattern,
@@ -139,16 +135,16 @@ let WsObserveAgentService = WsObserveAgentService_1 = class WsObserveAgentServic
139
135
  tags: this.options.ws?.tags,
140
136
  });
141
137
  const endTrace = () => {
142
- setTimeout(async () => {
138
+ deferTraceCompletion(async () => {
143
139
  this.operationTraceRegistry.endTrace(traceId, {
144
- userId: this.options.ws?.getUserId?.(message),
140
+ userId: getUserIdSafely(this.options.ws?.getUserId, [message], this.options.ws, this.logger, "ws"),
145
141
  });
146
142
  const snapshot = await this.operationTraceRegistry.pluckSnapshot(traceId);
147
143
  if (!snapshot) {
148
144
  return;
149
145
  }
150
146
  this.observeAgentSharedBuffer.insertRequestSnapshot(snapshot);
151
- }, 0);
147
+ }, this.logger, "ws");
152
148
  };
153
149
  // Nest's ws proxy hands a thrown error to the exception filter and
154
150
  // resolves, so there is no rejection to read a failure from here - the
@@ -1,6 +1,7 @@
1
1
  import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
2
2
  export declare class TraceSamplerService {
3
3
  private readonly options;
4
+ private readonly logger;
4
5
  constructor(options: ObserveModuleOptionsWithDefaults);
5
6
  /**
6
7
  * Determines if a trace should be captured based on the protocol and attributes.
@@ -10,10 +10,13 @@ var __metadata = (this && this.__metadata) || function (k, v) {
10
10
  var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
- import { Inject, Injectable } from "@nestjs/common";
13
+ var TraceSamplerService_1;
14
+ import { Inject, Injectable, Logger } from "@nestjs/common";
14
15
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
15
- let TraceSamplerService = class TraceSamplerService {
16
+ import { invokeUserCallbackSafely } from "../protocols/deferred-trace-completion.js";
17
+ let TraceSamplerService = TraceSamplerService_1 = class TraceSamplerService {
16
18
  options;
19
+ logger = new Logger(TraceSamplerService_1.name);
17
20
  constructor(options) {
18
21
  this.options = options;
19
22
  }
@@ -32,10 +35,13 @@ let TraceSamplerService = class TraceSamplerService {
32
35
  }
33
36
  return Math.random() < this.options.tracesSampleRate; // Randomly capture traces based on sample rate
34
37
  }
35
- return this.options.tracesSampleRate(protocol, attributes);
38
+ // Guarded here rather than at each call site, since every transport asks.
39
+ // A callback that throws keeps the operation out, as a throwing `ignore`
40
+ // does.
41
+ return invokeUserCallbackSafely(this.options.tracesSampleRate, [protocol, attributes], this.options, () => false, this.logger, "tracesSampleRate", "not tracing the operation");
36
42
  }
37
43
  };
38
- TraceSamplerService = __decorate([
44
+ TraceSamplerService = TraceSamplerService_1 = __decorate([
39
45
  Injectable(),
40
46
  __param(0, Inject(OBSERVE_OPTIONS)),
41
47
  __metadata("design:paramtypes", [Object])
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What `x-observe-sdk-version` carries when this package's own manifest cannot
3
+ * be read.
4
+ */
5
+ export declare const UNKNOWN_SDK_VERSION = "unknown";
6
+ /**
7
+ * This package's own version, as its installed `package.json` states it.
8
+ *
9
+ * Sent with every batch so the collector knows which agent an application
10
+ * runs - nothing else tells it, and a project scaffolded with `^0.1.8` keeps
11
+ * installing 0.1.x for as long as nobody edits that range.
12
+ *
13
+ * Resolved by the package's name rather than a relative path, and checked by
14
+ * name: a bundle that moved this file would otherwise read the application's
15
+ * own manifest and report its version instead. A bundle that erased
16
+ * `import.meta.url`, or one shipped without `node_modules`, gets
17
+ * {@link UNKNOWN_SDK_VERSION} - never an exception at start-up.
18
+ */
19
+ export declare function readSdkVersion(): string;
@@ -0,0 +1,34 @@
1
+ import { createRequire } from "module";
2
+ /**
3
+ * What `x-observe-sdk-version` carries when this package's own manifest cannot
4
+ * be read.
5
+ */
6
+ export const UNKNOWN_SDK_VERSION = "unknown";
7
+ /**
8
+ * This package's own version, as its installed `package.json` states it.
9
+ *
10
+ * Sent with every batch so the collector knows which agent an application
11
+ * runs - nothing else tells it, and a project scaffolded with `^0.1.8` keeps
12
+ * installing 0.1.x for as long as nobody edits that range.
13
+ *
14
+ * Resolved by the package's name rather than a relative path, and checked by
15
+ * name: a bundle that moved this file would otherwise read the application's
16
+ * own manifest and report its version instead. A bundle that erased
17
+ * `import.meta.url`, or one shipped without `node_modules`, gets
18
+ * {@link UNKNOWN_SDK_VERSION} - never an exception at start-up.
19
+ */
20
+ export function readSdkVersion() {
21
+ try {
22
+ const require = createRequire(import.meta.url);
23
+ const manifest = require("@nestjs/observe/package.json");
24
+ if (manifest.name === "@nestjs/observe" &&
25
+ typeof manifest.version === "string" &&
26
+ manifest.version.length > 0) {
27
+ return manifest.version;
28
+ }
29
+ }
30
+ catch {
31
+ // Falls through to the placeholder below.
32
+ }
33
+ return UNKNOWN_SDK_VERSION;
34
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.18",
3
+ "version": "0.3.19",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics and custom metrics",
5
5
  "author": "Kamil Mysliwiec",
6
6
  "homepage": "https://observe.nestjs.com",
@@ -128,7 +128,7 @@
128
128
  "@mikro-orm/core": "7.2.0",
129
129
  "@mikro-orm/mysql": "7.2.0",
130
130
  "@mikro-orm/postgresql": "7.2.0",
131
- "@nestjs/apollo": "14.0.0",
131
+ "@nestjs/apollo": "14.1.1",
132
132
  "@nestjs/bull": "12.0.0",
133
133
  "@nestjs/bullmq": "12.0.0",
134
134
  "@nestjs/common": "12.0.1",
@@ -137,6 +137,7 @@
137
137
  "@nestjs/microservices": "12.0.1",
138
138
  "@nestjs/platform-express": "12.0.1",
139
139
  "@nestjs/platform-fastify": "12.0.3",
140
+ "@nestjs/platform-node": "12.3.2",
140
141
  "@nestjs/platform-socket.io": "12.0.3",
141
142
  "@nestjs/platform-ws": "12.0.3",
142
143
  "@nestjs/schedule": "12.0.1",