@nestjs/observe 0.3.27 → 0.3.29

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.
@@ -150,6 +150,21 @@ function isCryptoHandle(instance) {
150
150
  * - `@nestjs/config`'s `ConfigService` keeps what an application calls. Each
151
151
  * `get` made four or five more spans of its private helpers - 2.7M of its
152
152
  * 4.6M a day, in 220 projects.
153
+ * - `@nestjs/throttler`'s `ThrottlerGuard` keeps `canActivate`, and its
154
+ * in-memory `ThrottlerStorageService` nothing. Per named throttler, every
155
+ * request made 19 more spans: `resolveValue` and `toNumber` three times
156
+ * each, `handleRequest`, `getRequestResponse`, `setResponseHeader` three
157
+ * times, and `increment` with seven calls of the store's helpers - with
158
+ * `shouldSkip`, 40 a request for two throttlers where one is kept now. They
159
+ * were in 61 to 77 of 187 active projects, about 1.5M a week, and up to ~50
160
+ * of the events a health-check-only app was billed for each probe.
161
+ * The store is a `Map` and a timer: `increment` does no I/O, so its time is
162
+ * all in the `canActivate` span already. A store that does, such as a Redis
163
+ * one, is another class and keeps its own spans and its client's.
164
+ *
165
+ * An application's subclass - a `GqlThrottlerGuard` overriding
166
+ * `getRequestResponse`, a guard overriding `getTracker` or `shouldSkip` -
167
+ * keeps a span for each method it overrides.
153
168
  *
154
169
  * Folding cannot reach any of them (`collapseRepeatedSpans`), because each
155
170
  * repeats only a few times under its parent.
@@ -178,6 +193,17 @@ const PARTLY_TRACED_CLASSES = new Map([
178
193
  traced: new Set(["get", "getOrThrow", "set", "setEnvFilePaths"]),
179
194
  },
180
195
  ],
196
+ // `throwThrottlingException` is on every ThrottlerGuard from 4.x to 6.8,
197
+ // and `fireHitCount` on every ThrottlerStorageService since 6.0, which
198
+ // covers every release that supports Nest 11 and 12.
199
+ [
200
+ "ThrottlerGuard",
201
+ {
202
+ marker: "throwThrottlingException",
203
+ traced: new Set(["canActivate"]),
204
+ },
205
+ ],
206
+ ["ThrottlerStorageService", { marker: "fireHitCount", traced: new Set() }],
181
207
  ]);
182
208
  /**
183
209
  * The methods a prototype's class keeps traced, if it is one of those.
@@ -374,6 +374,9 @@ export function createObserveModule(options = {}) {
374
374
  skipInstrumentation,
375
375
  });
376
376
  return (instance) => {
377
+ // Proof that `instrument` reached NestFactory: the registry then
378
+ // stops reading an operation with no spans as its absence.
379
+ operationTraceRegistry.markInstrumented();
377
380
  shareHooksOfHttpAdapter(instance);
378
381
  deliverRepliesToTheirCaller(instance, asyncLocalStorage);
379
382
  propagateTraceIdThrough(instance,
@@ -26,7 +26,9 @@ export function patchMysql2(mysql2, recorder) {
26
26
  args[last] = AsyncResource.bind(args[last]);
27
27
  }
28
28
  const sql = typeof first === "string" ? first : first?.sql;
29
- if (typeof sql !== "string") {
29
+ // Asked before the statement is described: an untraced or sampled-out
30
+ // call should not pay for tokenizing it.
31
+ if (typeof sql !== "string" || !recorder.isRecording()) {
30
32
  return original.apply(this, args);
31
33
  }
32
34
  const { operation, statement } = describeSqlStatement(sql, "mysql");
@@ -29,6 +29,11 @@ export function patchPg(pg, recorder) {
29
29
  if (typeof text !== "string" || typeof config?.submit === "function") {
30
30
  return original.apply(this, args);
31
31
  }
32
+ // Asked before the statement is described: an untraced or sampled-out
33
+ // call should not pay for tokenizing it.
34
+ if (!recorder.isRecording()) {
35
+ return original.apply(this, args);
36
+ }
32
37
  const { operation, statement } = describeSqlStatement(text, "postgresql");
33
38
  const span = recorder.open("pg", operation, {
34
39
  "db.system": "postgresql",
@@ -5,7 +5,6 @@ export declare class LoggerPatcherService implements OnModuleInit {
5
5
  private readonly asyncLocalStorage;
6
6
  private readonly options;
7
7
  private readonly logger;
8
- private readonly patchedWatermark;
9
8
  constructor(asyncLocalStorage: AsyncLocalStorage<any>, options: ObserveModuleOptionsWithDefaults);
10
9
  onModuleInit(): void;
11
10
  /**
@@ -14,12 +14,32 @@ var LoggerPatcherService_1;
14
14
  import { ConsoleLogger, Inject, Injectable, Logger, } from "@nestjs/common";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
16
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
17
+ import { stripAnsi } from "../utils/log-line.parser.js";
17
18
  import { liveTraceId } from "../utils/operation-state.util.js";
19
+ /** What precedes the trace id the text output ends its first line with. */
20
+ const TRACE_ID_MARKER = "Trace ID:";
21
+ /**
22
+ * The stores, and the trace id keys read from each, that `ConsoleLogger` is
23
+ * already patched for. Once per pair rather than once per patcher: every
24
+ * application booted from the same module has a patcher of its own - a test
25
+ * suite that boots two had every log line wrapped, and suffixed, twice - and
26
+ * once per process would leave a second `createObserveModule()`, with a store
27
+ * of its own, without ids.
28
+ */
29
+ const patchedStores = new WeakMap();
30
+ /**
31
+ * Whether a line already ends with this trace's id, after the marker: the
32
+ * suffix of another patch - a second copy of this package, say - or the
33
+ * message's own last words. Read off the first line, without its colours,
34
+ * the way the stdout forwarder reads it.
35
+ */
36
+ function endsWithTraceId(line, traceId) {
37
+ return stripAnsi(line).trimEnd().endsWith(`${TRACE_ID_MARKER} ${traceId}`);
38
+ }
18
39
  let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
19
40
  asyncLocalStorage;
20
41
  options;
21
42
  logger = new Logger(LoggerPatcherService_1.name);
22
- patchedWatermark = Symbol("observe:logger_patched");
23
43
  constructor(asyncLocalStorage, options) {
24
44
  this.asyncLocalStorage = asyncLocalStorage;
25
45
  this.options = options;
@@ -35,12 +55,12 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
35
55
  if (!this.options.attachTraceIdToLogs) {
36
56
  return;
37
57
  }
38
- const isAlreadyPatched = Reflect.getOwnPropertyDescriptor(ConsoleLogger.prototype, this.patchedWatermark)?.value === true;
39
- if (isAlreadyPatched) {
40
- return;
41
- }
42
58
  const options = this.options;
43
59
  const asyncLocalStorage = this.asyncLocalStorage;
60
+ const patchedKeys = patchedStores.get(asyncLocalStorage) ?? new Set();
61
+ if (patchedKeys.has(options.traceIdKey)) {
62
+ return;
63
+ }
44
64
  const originalFormatMessage = ConsoleLogger.prototype["formatMessage"];
45
65
  const originalGetJsonLogObject = ConsoleLogger.prototype["getJsonLogObject"];
46
66
  if (!originalFormatMessage || !originalGetJsonLogObject) {
@@ -85,21 +105,22 @@ let LoggerPatcherService = LoggerPatcherService_1 = class LoggerPatcherService {
85
105
  // with the error's message - whose own last words, `Trace ID: <id>`
86
106
  // from a client's value, then named the trace the line was filed under.
87
107
  const [logLevel] = args;
88
- const suffix = ` Trace ID: ${this.colorize(requestId, logLevel)}`;
89
108
  const newline = output.indexOf("\n");
90
- if (newline === -1) {
91
- return `${output}${suffix}`;
109
+ const lineEnd = newline === -1
110
+ ? output.length
111
+ : output[newline - 1] === "\r"
112
+ ? newline - 1
113
+ : newline;
114
+ // Once per line: a line that already names this trace there needs no
115
+ // second suffix saying the same.
116
+ if (endsWithTraceId(output.slice(0, lineEnd), requestId)) {
117
+ return output;
92
118
  }
93
- const lineEnd = output[newline - 1] === "\r" ? newline - 1 : newline;
119
+ const suffix = ` ${TRACE_ID_MARKER} ${this.colorize(requestId, logLevel)}`;
94
120
  return `${output.slice(0, lineEnd)}${suffix}${output.slice(lineEnd)}`;
95
121
  };
96
- // Add watermark to flag that the logger has been patched
97
- Reflect.defineProperty(ConsoleLogger.prototype, this.patchedWatermark, {
98
- value: true,
99
- writable: false,
100
- enumerable: false,
101
- configurable: false,
102
- });
122
+ patchedKeys.add(options.traceIdKey);
123
+ patchedStores.set(asyncLocalStorage, patchedKeys);
103
124
  }
104
125
  };
105
126
  LoggerPatcherService = LoggerPatcherService_1 = __decorate([
@@ -40,6 +40,13 @@ export declare class OperationTraceRegistry {
40
40
  * would bury everything else in the log. Full text once, one line after.
41
41
  */
42
42
  private hasReportedMissingInstrumentation;
43
+ /**
44
+ * Set by `markInstrumented` the first time the instance decorator of the
45
+ * `instrument` that shares this registry runs. Until then an operation
46
+ * that ends with a name and no spans is a sign that `instrument` never
47
+ * reached NestFactory; after it, it is not - see `endTrace`.
48
+ */
49
+ private instrumented;
43
50
  /** See `reportSpanDepthLimit`. */
44
51
  private hasReportedSpanDepthLimit;
45
52
  /** See `reportCapturedErrorLimit`. */
@@ -279,6 +286,12 @@ export declare class OperationTraceRegistry {
279
286
  * given the same input.
280
287
  */
281
288
  private countUnrecordedSpan;
289
+ /**
290
+ * Records that the instance decorator ran, so that a routed operation with
291
+ * no spans is no longer taken to mean `instrument` is missing - see
292
+ * `endTrace`.
293
+ */
294
+ markInstrumented(): void;
282
295
  /**
283
296
  * Reports the trace even if it ends with no span recorded under it.
284
297
  *
@@ -394,6 +394,13 @@ export class OperationTraceRegistry {
394
394
  * would bury everything else in the log. Full text once, one line after.
395
395
  */
396
396
  hasReportedMissingInstrumentation = false;
397
+ /**
398
+ * Set by `markInstrumented` the first time the instance decorator of the
399
+ * `instrument` that shares this registry runs. Until then an operation
400
+ * that ends with a name and no spans is a sign that `instrument` never
401
+ * reached NestFactory; after it, it is not - see `endTrace`.
402
+ */
403
+ instrumented = false;
397
404
  /** See `reportSpanDepthLimit`. */
398
405
  hasReportedSpanDepthLimit = false;
399
406
  /** See `reportCapturedErrorLimit`. */
@@ -593,11 +600,11 @@ export class OperationTraceRegistry {
593
600
  return;
594
601
  }
595
602
  if (snapshot.traces.length === 0) {
596
- if ("operationId" in snapshot) {
597
- // An operationId means a handler ran, and zero traces means nothing
598
- // recorded a span for it. Both at once has one cause: the instance
599
- // decorator never wrapped the providers, because `instrument` never
600
- // reached NestFactory.
603
+ if ("operationId" in snapshot && !this.instrumented) {
604
+ // An operationId means the operation was routed to a handler, and
605
+ // zero traces means nothing recorded a span for it. With the instance
606
+ // decorator never run in this process, both at once has one cause:
607
+ // `instrument` never reached NestFactory.
601
608
  //
602
609
  // Dropped before the line is written, not after: a logger taken from
603
610
  // the container is wrapped like any provider and writes inside this
@@ -608,6 +615,22 @@ export class OperationTraceRegistry {
608
615
  this.reportMissingInstrumentation(snapshot);
609
616
  return;
610
617
  }
618
+ // Instrumented, a routed operation can still end before anything that
619
+ // records a span ran: a request-scoped provider whose constructor
620
+ // throws fails the request while Nest resolves the handler's instance,
621
+ // ahead of every guard, interceptor and the handler itself. A transport
622
+ // that reports a failed status code says how it ended, so it is kept -
623
+ // a 404 or a 500 with no spans under it, rather than a request missing
624
+ // from the traces. Any other is dropped as before: one that reports
625
+ // none (WS, RPC, a job) would ship looking successful, and a success
626
+ // with no spans - a handler `skipInstrumentation` left alone - has
627
+ // nothing to show.
628
+ if ("operationId" in snapshot &&
629
+ "statusCode" in opts &&
630
+ typeof opts.statusCode === "number" &&
631
+ opts.statusCode >= 400) {
632
+ snapshot.keptWithoutSpans = true;
633
+ }
611
634
  // Ignore snapshots that have no traces as that means
612
635
  // the request didnt even have a handler in the first place - unless
613
636
  // the transport said the operation is complete without one.
@@ -1098,6 +1121,14 @@ export class OperationTraceRegistry {
1098
1121
  this.hasReportedSpanLimit = true;
1099
1122
  this.logger.warn(`Trace "${snapshot.traceId}" opened ${MAX_SPANS_PER_TRACE} spans; the calls it makes after that run untraced, and the snapshot counts them under the "${UNRECORDED_SPANS_TAG}" tag. Later traces past this limit are not reported.`);
1100
1123
  }
1124
+ /**
1125
+ * Records that the instance decorator ran, so that a routed operation with
1126
+ * no spans is no longer taken to mean `instrument` is missing - see
1127
+ * `endTrace`.
1128
+ */
1129
+ markInstrumented() {
1130
+ this.instrumented = true;
1131
+ }
1101
1132
  /**
1102
1133
  * Reports the trace even if it ends with no span recorded under it.
1103
1134
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.27",
3
+ "version": "0.3.29",
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",
@@ -125,7 +125,7 @@
125
125
  }
126
126
  },
127
127
  "devDependencies": {
128
- "@apollo/server": "5.5.1",
128
+ "@apollo/server": "5.5.2",
129
129
  "@as-integrations/express5": "1.1.2",
130
130
  "@commitlint/cli": "21.2.4",
131
131
  "@commitlint/config-angular": "21.2.4",
@@ -148,6 +148,7 @@
148
148
  "@nestjs/platform-ws": "12.3.3",
149
149
  "@nestjs/schedule": "12.0.1",
150
150
  "@nestjs/testing": "12.3.3",
151
+ "@nestjs/throttler": "6.8.0",
151
152
  "@nestjs/websockets": "12.3.3",
152
153
  "@opentelemetry/api": "1.9.1",
153
154
  "@opentelemetry/auto-instrumentations-node": "0.81.0",
@@ -175,7 +176,7 @@
175
176
  "husky": "9.1.7",
176
177
  "ioredis": "6.0.0",
177
178
  "kafkajs": "2.2.4",
178
- "lint-staged": "17.6.0",
179
+ "lint-staged": "17.6.1",
179
180
  "mongodb": "7.6.0",
180
181
  "mongoose": "9.10.1",
181
182
  "mssql": "12.7.13",