@nestjs/observe 0.3.5 → 0.3.6

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 (30) hide show
  1. package/README.md +66 -4
  2. package/dist/agent/observe-agent.shared-buffer.js +7 -3
  3. package/dist/agent/telemetry-wire-contract.js +30 -12
  4. package/dist/custom-metrics/counter.d.ts +7 -3
  5. package/dist/custom-metrics/counter.js +34 -7
  6. package/dist/custom-metrics/finite-value.util.d.ts +20 -0
  7. package/dist/custom-metrics/finite-value.util.js +29 -0
  8. package/dist/custom-metrics/gauge.d.ts +2 -0
  9. package/dist/custom-metrics/gauge.js +31 -7
  10. package/dist/custom-metrics/summary.d.ts +5 -0
  11. package/dist/custom-metrics/summary.js +10 -3
  12. package/dist/encoders/custom-metrics.encoder.js +63 -1
  13. package/dist/encoders/trace.encoder.js +34 -0
  14. package/dist/interfaces/custom-metric.interface.d.ts +5 -0
  15. package/dist/interfaces/observe-options.interface.d.ts +23 -14
  16. package/dist/observe.module.js +25 -6
  17. package/dist/protocols/http-observe-agent.service.d.ts +13 -0
  18. package/dist/protocols/http-observe-agent.service.js +34 -8
  19. package/dist/protocols/rpc-observe-agent.service.js +0 -2
  20. package/dist/protocols/schedule-observe-agent.service.js +7 -3
  21. package/dist/services/node-runtime-metrics.service.d.ts +12 -0
  22. package/dist/services/node-runtime-metrics.service.js +95 -41
  23. package/dist/services/operation-trace.registry.js +0 -6
  24. package/dist/services/stdout-forwarder.service.js +2 -2
  25. package/dist/services/tracer.service.js +0 -3
  26. package/dist/utils/fit-service-version.util.js +2 -8
  27. package/dist/utils/fit-to-length.util.d.ts +10 -0
  28. package/dist/utils/fit-to-length.util.js +44 -0
  29. package/package.json +5 -3
  30. package/dist/.tsbuildinfo +0 -1
@@ -1,4 +1,27 @@
1
+ import { fitToLength } from "../utils/fit-to-length.util.js";
1
2
  import { remapKeys } from "./remap-keys.util.js";
3
+ /**
4
+ * The longest span name, class name and method name the collector accepts. It
5
+ * refuses the whole batch over a longer one rather than cutting it, so each is
6
+ * cut to fit here - the same way every time, so a span's numbers still add up
7
+ * under one name.
8
+ */
9
+ const MAX_SPAN_TEXT_LENGTH = 255;
10
+ /** Whether a cut has been reported: once for the process, not per span. */
11
+ let reportedCut = false;
12
+ function fitSpanText(value) {
13
+ if (value.length <= MAX_SPAN_TEXT_LENGTH) {
14
+ return value;
15
+ }
16
+ const sent = fitToLength(value, MAX_SPAN_TEXT_LENGTH);
17
+ if (!reportedCut) {
18
+ reportedCut = true;
19
+ console.warn(`[observe] A span name, class name or method name of ${value.length} characters is sent as "${sent}": ` +
20
+ `the collector takes at most ${MAX_SPAN_TEXT_LENGTH} and refuses the whole batch over a longer one. ` +
21
+ `Others are cut the same way, without another warning.`);
22
+ }
23
+ return sent;
24
+ }
2
25
  export const TRACE_KEY_MAP = {
3
26
  name: "n",
4
27
  origin: "o",
@@ -20,6 +43,17 @@ export const TRACE_KEY_MAP = {
20
43
  */
21
44
  export function encodeTrace(trace) {
22
45
  const encoded = remapKeys(trace, TRACE_KEY_MAP);
46
+ // Assigned only where present: a key added as `undefined` would change
47
+ // which keys a span carries.
48
+ if (typeof encoded.n === "string") {
49
+ encoded.n = fitSpanText(encoded.n);
50
+ }
51
+ if (typeof encoded.c === "string") {
52
+ encoded.c = fitSpanText(encoded.c);
53
+ }
54
+ if (typeof encoded.m === "string") {
55
+ encoded.m = fitSpanText(encoded.m);
56
+ }
23
57
  // Outside the key remapping above, deliberately. Done inside that loop, every
24
58
  // own key of a node re-encoded that node's whole subtree, so the work was
25
59
  // keys^depth rather than one visit per node - a trace a few levels deeper
@@ -4,6 +4,9 @@ export interface CustomMetric<TLabel extends string = "default"> {
4
4
  * The name of the custom metric.
5
5
  * This should be a descriptive name that identifies the metric.
6
6
  * For example, "user_login_count" or "api_response_time".
7
+ *
8
+ * At most 100 characters reach the collector: a longer name is sent as its
9
+ * first 91 and a hash of the whole, with a warning.
7
10
  */
8
11
  name: string;
9
12
  /**
@@ -19,6 +22,7 @@ export interface CustomMetric<TLabel extends string = "default"> {
19
22
  * Description for the custom metric.
20
23
  * This can be used to provide additional context about what the metric represents.
21
24
  * For example, "Number of user logins in the last hour" or "Average response time for API requests".
25
+ * At most 255 characters are sent; a longer one is cut the same way as a name.
22
26
  */
23
27
  description?: string;
24
28
  /**
@@ -34,6 +38,7 @@ export interface CustomMetric<TLabel extends string = "default"> {
34
38
  * Optional labels for the custom metric.
35
39
  * Labels are key-value pairs that can be used to add additional context to the metric.
36
40
  * For example, you might use labels to indicate the environment (e.g., "production", "development") or the service (e.g., "user-service", "order-service").
41
+ * At most 1000 labels of at most 255 characters each are sent; a longer one is cut the same way as a name.
37
42
  */
38
43
  labels?: TLabel[];
39
44
  /**
@@ -166,6 +166,10 @@ export interface ObserveOptions {
166
166
  * If you anticipate running multiple instances of the same service,
167
167
  * consider using a unique identifier such as a hostname or container ID.
168
168
  * This helps in distinguishing between different instances of the service in the APM.
169
+ *
170
+ * At most 100 characters, the longest the collector accepts. A longer one is
171
+ * cut to fit, with a warning when the application starts: its first 91 and a
172
+ * hash of the whole, so two ids that differ only past the cut stay apart.
169
173
  */
170
174
  serviceId: string;
171
175
  /**
@@ -226,9 +230,11 @@ export interface ObserveOptions {
226
230
  /**
227
231
  * The sample rate for traces, which determines the percentage of traces that are sent to the Agent.
228
232
  * A value of 1.0 means all traces are sent, while a value of 0.1 means 10% of traces are sent.
233
+ * A value of 0 reads as unset, so it sends every trace rather than none - pass
234
+ * `() => false` to send none.
229
235
  * @default 1.0
230
236
  */
231
- tracesSampleRate?: number | ((protocal: "http" | "rpc" | "grpc" | "graphql" | "ws", attributes: any) => boolean);
237
+ tracesSampleRate?: number | ((protocol: "http" | "rpc" | "grpc" | "graphql" | "ws", attributes: any) => boolean);
232
238
  /**
233
239
  * Maximum number of traces per batch that can be sent to the Agent.
234
240
  * This is useful for controlling the volume of traces sent, especially in high-traffic applications.
@@ -416,19 +422,21 @@ export interface ObserveOptions {
416
422
  tags?: Record<string, string>;
417
423
  /**
418
424
  * A function to generate additional attributes for RPC requests.
419
- * This function receives the request context and should return an object containing key-value pairs.
425
+ * This function receives the transport and the message context - the
426
+ * transport's own subclass, such as `NatsContext` or `KafkaContext` - and
427
+ * should return an object containing key-value pairs.
420
428
  * These attributes can be retrieved later within the trace.
421
- * @example (ctx) => ({ 'service': ctx.getService(), 'method': ctx.getMethod() })
422
- * @default (ctx) => ({})
429
+ * @example (transportId, ctx) => (ctx instanceof NatsContext ? { subject: ctx.getSubject() } : {})
430
+ * @default (transportId, ctx) => ({})
423
431
  */
424
432
  setAttributes?: (transportId: Transport | symbol, ctx: BaseRpcContext) => {
425
433
  [key: string]: string | number | boolean;
426
434
  };
427
435
  /**
428
- * A function to associate a user identifier with the HTTP request.
429
- * This function receives the request object and should return a string representing the user ID.
430
- * If not provided, no user ID will be associated with the request.
431
- * @example (transportId, ctx) => ctx.getMetadata().userId || 'anonymous'
436
+ * A function to associate a user identifier with the RPC message.
437
+ * This function receives the transport and the message context and should return a string representing the user ID.
438
+ * If not provided, no user ID will be associated with the message.
439
+ * @example (transportId, ctx) => (ctx instanceof NatsContext && ctx.getHeaders()?.get("user-id")) || 'anonymous'
432
440
  * @default undefined
433
441
  */
434
442
  getUserId?: (transportId: Transport | symbol, ctx: BaseRpcContext) => string;
@@ -508,19 +516,20 @@ export interface ObserveOptions {
508
516
  tags?: Record<string, string>;
509
517
  /**
510
518
  * A function to generate additional attributes for gRPC requests.
511
- * This function receives the gRPC call object and should return an object containing key-value pairs.
519
+ * This function receives the gRPC call - its `request`, `metadata` and
520
+ * `operationId` - and should return an object containing key-value pairs.
512
521
  * These attributes can be retrieved later within the trace.
513
- * @example (call) => ({ 'service': call.service, 'method': call.method })
522
+ * @example (call) => ({ operation: call.operationId })
514
523
  * @default (call) => ({})
515
524
  * */
516
525
  setAttributes?: (call: any) => {
517
526
  [key: string]: string | number | boolean;
518
527
  };
519
528
  /**
520
- * A function to associate a user identifier with the HTTP request.
521
- * This function receives the request object and should return a string representing the user ID.
522
- * If not provided, no user ID will be associated with the request.
523
- * @example (call) => call.metadata.userId || 'anonymous'
529
+ * A function to associate a user identifier with the gRPC call.
530
+ * This function receives the call and should return a string representing the user ID.
531
+ * If not provided, no user ID will be associated with the call.
532
+ * @example (call) => String(call.metadata.get('user-id')[0] ?? 'anonymous')
524
533
  * @default undefined
525
534
  */
526
535
  getUserId?: (call: any) => string;
@@ -37,6 +37,7 @@ import { TracerService } from "./services/tracer.service.js";
37
37
  import { assertModuleOptions } from "./utils/assert-module-options.util.js";
38
38
  import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
39
39
  import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-service-version.util.js";
40
+ import { fitToLength } from "./utils/fit-to-length.util.js";
40
41
  import { inferServiceVersion } from "./utils/infer-service-version.util.js";
41
42
  import { LogRedactor } from "./utils/log-redactor.js";
42
43
  /**
@@ -45,6 +46,24 @@ import { LogRedactor } from "./utils/log-redactor.js";
45
46
  * otherwise try to resolve, which fails much later with no mention of why.
46
47
  */
47
48
  const MISSING_ASYNC_OPTIONS_PROVIDER = 'ObserveModule.forRootAsync() requires one of "useFactory", "useClass" or "useExisting".';
49
+ /**
50
+ * The longest `serviceId` the collector accepts. It rides on every batch, and
51
+ * a longer one is not cut there: every batch would be refused.
52
+ */
53
+ const MAX_SERVICE_ID_LENGTH = 100;
54
+ /**
55
+ * `serviceId`, cut to what the collector accepts the way a named release is,
56
+ * with a warning when the application starts.
57
+ */
58
+ function withServiceId(options) {
59
+ const named = options.serviceId;
60
+ if (typeof named !== "string" || named.length <= MAX_SERVICE_ID_LENGTH) {
61
+ return options;
62
+ }
63
+ const sent = fitToLength(named, MAX_SERVICE_ID_LENGTH);
64
+ new Logger("ObserveModule").warn(`serviceId "${named}" is sent as "${sent}": the collector takes at most ${MAX_SERVICE_ID_LENGTH} characters.`);
65
+ return { ...options, serviceId: sent };
66
+ }
48
67
  /**
49
68
  * Names the release when the application did not, so Releases, regressions
50
69
  * and fix verification work without anyone threading a version through the
@@ -97,10 +116,10 @@ export function createObserveModule(options = {}) {
97
116
  providers: [
98
117
  {
99
118
  provide: OBSERVE_OPTIONS,
100
- useValue: withServiceVersion({
119
+ useValue: withServiceVersion(withServiceId({
101
120
  ...options,
102
121
  ...observeOpts,
103
- }),
122
+ })),
104
123
  },
105
124
  ],
106
125
  };
@@ -139,10 +158,10 @@ export function createObserveModule(options = {}) {
139
158
  provide: OBSERVE_OPTIONS,
140
159
  useFactory: async (...args) => {
141
160
  const opts = await useFactory(...args);
142
- return withServiceVersion({
161
+ return withServiceVersion(withServiceId({
143
162
  ...options,
144
163
  ...opts,
145
- });
164
+ }));
146
165
  },
147
166
  inject: asyncOptions.inject || [],
148
167
  };
@@ -153,10 +172,10 @@ export function createObserveModule(options = {}) {
153
172
  }
154
173
  return {
155
174
  provide: OBSERVE_OPTIONS,
156
- useFactory: async (optionsFactory) => withServiceVersion({
175
+ useFactory: async (optionsFactory) => withServiceVersion(withServiceId({
157
176
  ...options,
158
177
  ...(await optionsFactory.createObserveOptions()),
159
- }),
178
+ })),
160
179
  inject: [optionsFactoryToken],
161
180
  };
162
181
  }
@@ -13,6 +13,8 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
13
13
  private readonly operationTraceRegistry;
14
14
  private readonly observeAgentSharedBuffer;
15
15
  private readonly traceSamplerService;
16
+ private readonly logger;
17
+ private warnedAboutHooks;
16
18
  private httpAdapterInitSubscription;
17
19
  /**
18
20
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
@@ -54,5 +56,16 @@ export declare class HttpObserveAgentService<Store extends Record<string, unknow
54
56
  * a shutting-down process open.
55
57
  */
56
58
  private evictTraceOnClientAbort;
59
+ /**
60
+ * Whether the adapter has the hooks requests are traced through, warning
61
+ * the first time it does not.
62
+ *
63
+ * A missing framework hook is a no-op, never an error. Nest added all three
64
+ * in 11.1.4, and this used to throw from the constructor when one was absent
65
+ * - so an application on an earlier 11.x, inside the supported range, did
66
+ * not start at all. Without the hooks there is no request to attach a trace
67
+ * to, so the HTTP side stands aside and everything else is still reported.
68
+ */
69
+ private hasRequestHooks;
57
70
  private shouldIgnoreRequest;
58
71
  }
@@ -10,7 +10,8 @@ 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 HttpObserveAgentService_1;
14
+ import { Inject, Injectable, Logger, } from "@nestjs/common";
14
15
  import { captureRequest, shouldCaptureRequest, } from "../utils/capture-request.util.js";
15
16
  import { HttpAdapterHost } from "@nestjs/core";
16
17
  import { AsyncLocalStorage } from "async_hooks";
@@ -26,13 +27,21 @@ import { uuidv7 } from "../utils/uuid-v7.util.js";
26
27
  * next to a leak that never frees.
27
28
  */
28
29
  const ABORTED_TRACE_EVICTION_GRACE_MS = 30_000;
29
- let HttpObserveAgentService = class HttpObserveAgentService {
30
+ /** The adapter hooks requests are traced through, all added in Nest 11.1.4. */
31
+ const REQUEST_HOOKS = [
32
+ "setOnRequestHook",
33
+ "setOnResponseHook",
34
+ "setOnRouteTriggered",
35
+ ];
36
+ let HttpObserveAgentService = HttpObserveAgentService_1 = class HttpObserveAgentService {
30
37
  httpAdapterHost;
31
38
  asyncLocalStorage;
32
39
  options;
33
40
  operationTraceRegistry;
34
41
  observeAgentSharedBuffer;
35
42
  traceSamplerService;
43
+ logger = new Logger(HttpObserveAgentService_1.name);
44
+ warnedAboutHooks = false;
36
45
  httpAdapterInitSubscription;
37
46
  /**
38
47
  * `http.queryParamsObfuscateRegex`, rebuilt with the global flag when it was
@@ -53,12 +62,9 @@ let HttpObserveAgentService = class HttpObserveAgentService {
53
62
  // The "setOnRouteTriggered" hook must be set immediately
54
63
  // to ensure that route metadata is captured correctly.
55
64
  const { httpAdapter } = this.httpAdapterHost;
56
- if (!httpAdapter) {
65
+ if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
57
66
  return;
58
67
  }
59
- if (!("setOnRouteTriggered" in httpAdapter)) {
60
- throw new Error("The HTTP adapter does not support the 'setOnRouteTriggered' method. Please ensure you are using the latest version of the NestJS HTTP adapter that supports this method.");
61
- }
62
68
  httpAdapter.setOnRouteTriggered((requestMethod, path) => {
63
69
  const store = this.asyncLocalStorage.getStore();
64
70
  if (!store) {
@@ -82,7 +88,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
82
88
  }
83
89
  registerHttpHooks() {
84
90
  const { httpAdapter } = this.httpAdapterHost;
85
- if (!httpAdapter) {
91
+ if (!httpAdapter || !this.hasRequestHooks(httpAdapter)) {
86
92
  return;
87
93
  }
88
94
  httpAdapter.setOnRequestHook((req, res, done) => {
@@ -212,6 +218,26 @@ let HttpObserveAgentService = class HttpObserveAgentService {
212
218
  timer.unref?.();
213
219
  });
214
220
  }
221
+ /**
222
+ * Whether the adapter has the hooks requests are traced through, warning
223
+ * the first time it does not.
224
+ *
225
+ * A missing framework hook is a no-op, never an error. Nest added all three
226
+ * in 11.1.4, and this used to throw from the constructor when one was absent
227
+ * - so an application on an earlier 11.x, inside the supported range, did
228
+ * not start at all. Without the hooks there is no request to attach a trace
229
+ * to, so the HTTP side stands aside and everything else is still reported.
230
+ */
231
+ hasRequestHooks(httpAdapter) {
232
+ if (REQUEST_HOOKS.every((hook) => hook in httpAdapter)) {
233
+ return true;
234
+ }
235
+ if (!this.warnedAboutHooks) {
236
+ this.warnedAboutHooks = true;
237
+ this.logger.warn("HTTP requests will not be traced: this HTTP adapter has no request hooks, which Nest added in 11.1.4. Upgrade @nestjs/core and your @nestjs/platform-* package to trace them.");
238
+ }
239
+ return false;
240
+ }
215
241
  shouldIgnoreRequest(req) {
216
242
  if (typeof this.options.http?.ignore === "function") {
217
243
  return this.options.http.ignore(req);
@@ -237,7 +263,7 @@ let HttpObserveAgentService = class HttpObserveAgentService {
237
263
  return false;
238
264
  }
239
265
  };
240
- HttpObserveAgentService = __decorate([
266
+ HttpObserveAgentService = HttpObserveAgentService_1 = __decorate([
241
267
  Injectable(),
242
268
  __param(2, Inject(OBSERVE_OPTIONS)),
243
269
  __metadata("design:paramtypes", [HttpAdapterHost,
@@ -120,7 +120,6 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
120
120
  }
121
121
  }
122
122
  }
123
- // setImmediate(() => {
124
123
  if (this.options.rpc?.ignore?.(transportId, ctx)) {
125
124
  return done();
126
125
  }
@@ -137,7 +136,6 @@ let RpcObserveAgentService = RpcObserveAgentService_1 = class RpcObserveAgentSer
137
136
  tags: this.options.rpc?.tags,
138
137
  });
139
138
  return done();
140
- // });
141
139
  });
142
140
  }
143
141
  startGrpcRequestTracing(transportId, call, done) {
@@ -71,12 +71,16 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
71
71
  * guarantee of landing before the explorer's `onModuleInit` has already
72
72
  * wrapped every handler.
73
73
  */
74
- loadScheduleExplorer() {
74
+ loadScheduleExplorer(
75
+ // A parameter only so the specs can stand in for the package: the version
76
+ // installed here exports the explorer, which would otherwise leave the
77
+ // deep-path fallback below running in no test at all.
78
+ load = loadOptionalPeer) {
75
79
  // The entry point is the supported source, but it only re-exports the
76
80
  // explorer from 12.0.1 onwards; every earlier version keeps it behind a
77
81
  // deep path. Try the public export first, then the file, so a supported
78
82
  // import is preferred wherever one exists.
79
- const entryPoint = loadOptionalPeer("@nestjs/schedule");
83
+ const entryPoint = load("@nestjs/schedule");
80
84
  if (!entryPoint.installed) {
81
85
  // Nothing scheduled, nothing to patch, and that is not a
82
86
  // misconfiguration.
@@ -85,7 +89,7 @@ let ScheduleObserveAgentService = ScheduleObserveAgentService_1 = class Schedule
85
89
  if (entryPoint.module?.ScheduleExplorer) {
86
90
  return entryPoint.module.ScheduleExplorer;
87
91
  }
88
- const deepPath = loadOptionalPeer("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
92
+ const deepPath = load("@nestjs/schedule", "@nestjs/schedule/dist/schedule.explorer.js");
89
93
  if (deepPath.installed && deepPath.module?.ScheduleExplorer) {
90
94
  return deepPath.module.ScheduleExplorer;
91
95
  }
@@ -5,18 +5,30 @@ export declare class NodeRuntimeMetricsService implements OnModuleInit, OnApplic
5
5
  private readonly options;
6
6
  private readonly logger;
7
7
  private eventLoopDelayMonitor;
8
+ /**
9
+ * The histogram's sample count and running sum of delays (ns) as of the
10
+ * previous sample, so that each sample reports its own window. Differenced
11
+ * rather than reset: `reset()` also forgets when the histogram last ticked,
12
+ * so a stall that started before its next tick - one in the same timers pass
13
+ * as a collection, say - was recorded in neither window. A double holds the
14
+ * sum to within a few nanoseconds even after a year of uptime.
15
+ */
16
+ private lastDelayCount;
17
+ private lastDelayTotal;
8
18
  private gcObserver;
9
19
  private gcCount;
10
20
  private gcTotalDuration;
11
21
  private gcBreakdown;
12
22
  private lastCpuUsage;
13
23
  private lastCpuUsageTimestamp;
24
+ private lastEventLoopUtilization;
14
25
  private osTotalMemory;
15
26
  constructor(options: ObserveModuleOptionsWithDefaults);
16
27
  onModuleInit(): void;
17
28
  onApplicationShutdown(): Promise<void>;
18
29
  monitorEventLoopDelay(): void;
19
30
  observeGcPerformance(): void;
31
+ private recordGarbageCollection;
20
32
  collectNodeRuntimeMetrics(): NodeRuntimeMetrics;
21
33
  private resetGcMetrics;
22
34
  private updateLastCpuUsage;
@@ -13,12 +13,48 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  var NodeRuntimeMetricsService_1;
14
14
  import { Inject, Injectable, Logger, } from "@nestjs/common";
15
15
  import * as os from "node:os";
16
- import { monitorEventLoopDelay, performance, PerformanceObserver, } from "node:perf_hooks";
16
+ import { constants, monitorEventLoopDelay, performance, PerformanceObserver, } from "node:perf_hooks";
17
17
  import { OBSERVE_OPTIONS } from "../observe.constants.js";
18
+ /**
19
+ * V8's young-generation mark-sweep (`kGCTypeMinorMarkSweep`, `1 << 1`), which
20
+ * replaces the scavenger under `--minor-ms`. V8 reports it with the same value
21
+ * on every supported release, but Node only names it from 24.20 and
22
+ * `@types/node` not at all.
23
+ */
24
+ const NODE_PERFORMANCE_GC_MINOR_MARK_SWEEP = constants.NODE_PERFORMANCE_GC_MINOR_MARK_SWEEP ?? 2;
25
+ /**
26
+ * The breakdown bucket for a `gc` entry's `detail.kind`. A weak-callback pass
27
+ * (`NODE_PERFORMANCE_GC_WEAKCB`) has none: it is the embedder's finalisers
28
+ * running after a collection, not a collection of either generation, so it
29
+ * counts towards the window's totals and nothing more.
30
+ */
31
+ function gcBucketOf(kind) {
32
+ switch (kind) {
33
+ case constants.NODE_PERFORMANCE_GC_MINOR:
34
+ case NODE_PERFORMANCE_GC_MINOR_MARK_SWEEP:
35
+ return "minor";
36
+ case constants.NODE_PERFORMANCE_GC_MAJOR:
37
+ return "major";
38
+ case constants.NODE_PERFORMANCE_GC_INCREMENTAL:
39
+ return "incremental";
40
+ default:
41
+ return undefined;
42
+ }
43
+ }
18
44
  let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeMetricsService {
19
45
  options;
20
46
  logger = new Logger(NodeRuntimeMetricsService_1.name);
21
47
  eventLoopDelayMonitor = null;
48
+ /**
49
+ * The histogram's sample count and running sum of delays (ns) as of the
50
+ * previous sample, so that each sample reports its own window. Differenced
51
+ * rather than reset: `reset()` also forgets when the histogram last ticked,
52
+ * so a stall that started before its next tick - one in the same timers pass
53
+ * as a collection, say - was recorded in neither window. A double holds the
54
+ * sum to within a few nanoseconds even after a year of uptime.
55
+ */
56
+ lastDelayCount = 0;
57
+ lastDelayTotal = 0;
22
58
  gcObserver = null;
23
59
  gcCount = 0;
24
60
  gcTotalDuration = 0;
@@ -29,6 +65,7 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
29
65
  // and pins CPU usage at ~0%.
30
66
  lastCpuUsage = process.cpuUsage();
31
67
  lastCpuUsageTimestamp = Date.now();
68
+ lastEventLoopUtilization = performance.eventLoopUtilization();
32
69
  osTotalMemory = os.totalmem();
33
70
  constructor(options) {
34
71
  this.options = options;
@@ -40,6 +77,7 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
40
77
  }
41
78
  this.lastCpuUsage = process.cpuUsage();
42
79
  this.lastCpuUsageTimestamp = Date.now();
80
+ this.lastEventLoopUtilization = performance.eventLoopUtilization();
43
81
  this.osTotalMemory = os.totalmem();
44
82
  this.monitorEventLoopDelay();
45
83
  this.observeGcPerformance();
@@ -61,6 +99,8 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
61
99
  const h = monitorEventLoopDelay();
62
100
  h.enable();
63
101
  this.eventLoopDelayMonitor = h;
102
+ this.lastDelayCount = 0;
103
+ this.lastDelayTotal = 0;
64
104
  }
65
105
  observeGcPerformance() {
66
106
  if (this.options.debug) {
@@ -68,43 +108,39 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
68
108
  }
69
109
  this.gcObserver = new PerformanceObserver((list) => {
70
110
  for (const entry of list.getEntries()) {
71
- if (entry.entryType !== "gc") {
72
- continue;
73
- }
74
- this.gcCount++;
75
- this.gcTotalDuration += entry.duration;
76
- if ("detail" in entry && "kind" in entry.detail) {
77
- const detail = entry.detail;
78
- const kind = detail.kind === 1
79
- ? "major"
80
- : detail.kind === 2
81
- ? "minor"
82
- : detail.kind === 4
83
- ? "incremental"
84
- : undefined;
85
- if (!kind) {
86
- continue;
87
- }
88
- // Seeded with all three kinds at zero on the first collection of the
89
- // window: "no major collections happened" and "major collections were
90
- // not reported" are different facts, and only the seeding keeps them
91
- // apart downstream.
92
- this.gcBreakdown ??= {
93
- minor: { count: 0, duration: 0 },
94
- major: { count: 0, duration: 0 },
95
- incremental: { count: 0, duration: 0 },
96
- };
97
- const bucket = (this.gcBreakdown[kind] ??= {
98
- count: 0,
99
- duration: 0,
100
- });
101
- bucket.count++;
102
- bucket.duration += entry.duration;
103
- }
111
+ this.recordGarbageCollection(entry);
104
112
  }
105
113
  });
106
114
  this.gcObserver.observe({ type: "gc", buffered: true });
107
115
  }
116
+ recordGarbageCollection(entry) {
117
+ if (entry.entryType !== "gc") {
118
+ return;
119
+ }
120
+ this.gcCount++;
121
+ this.gcTotalDuration += entry.duration;
122
+ // Typed only on marks and measures, but every `gc` entry carries one.
123
+ const { detail } = entry;
124
+ const kind = gcBucketOf(detail?.kind);
125
+ if (!kind) {
126
+ return;
127
+ }
128
+ // Seeded with all three kinds at zero on the first collection of the
129
+ // window: "no major collections happened" and "major collections were
130
+ // not reported" are different facts, and only the seeding keeps them
131
+ // apart downstream.
132
+ this.gcBreakdown ??= {
133
+ minor: { count: 0, duration: 0 },
134
+ major: { count: 0, duration: 0 },
135
+ incremental: { count: 0, duration: 0 },
136
+ };
137
+ const bucket = (this.gcBreakdown[kind] ??= {
138
+ count: 0,
139
+ duration: 0,
140
+ });
141
+ bucket.count++;
142
+ bucket.duration += entry.duration;
143
+ }
108
144
  collectNodeRuntimeMetrics() {
109
145
  // Nothing was started, so there is nothing to collect: with metrics turned
110
146
  // off the histogram is never enabled, and every number below would be
@@ -118,13 +154,28 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
118
154
  const memoryUsage = process.memoryUsage();
119
155
  const cpuUsage = process.cpuUsage();
120
156
  const diffCpuUsage = process.cpuUsage(this.lastCpuUsage);
121
- const eventLoop = performance.eventLoopUtilization();
122
- // `mean` is NaN until the histogram has recorded its first sample, so a
123
- // flush that lands immediately after startup would otherwise ship NaN into
124
- // a numeric column - where it survives, poisons every average built over it
125
- // and makes the runtime alert comparisons undefined.
126
- const meanDelay = this.eventLoopDelayMonitor.mean;
127
- const lag = Number.isFinite(meanDelay) ? meanDelay / 1e6 : 0; // ns → ms
157
+ // Differenced against the previous sample's reading, like CPU: read bare,
158
+ // utilisation is cumulative since the process started, and a long-running
159
+ // process averages any busy stretch into a flat line.
160
+ const eventLoopUtilization = performance.eventLoopUtilization();
161
+ const eventLoop = performance.eventLoopUtilization(eventLoopUtilization, this.lastEventLoopUtilization);
162
+ // The mean of this window's delays alone: left as the histogram's `mean`,
163
+ // it covers every delay since startup, and a long-running process flattens
164
+ // any burst of blocking into it. Each delay is a whole interval between two
165
+ // of the histogram's ticks, its 10ms resolution included, so an idle
166
+ // process reads about 10ms - what `monitorEventLoopDelay` reports, and so
167
+ // what the usual exporters report too.
168
+ const delayCount = this.eventLoopDelayMonitor.count;
169
+ // `mean` is NaN until the first sample, hence the guard.
170
+ const delayTotal = delayCount > 0 ? this.eventLoopDelayMonitor.mean * delayCount : 0;
171
+ const windowCount = delayCount - this.lastDelayCount;
172
+ // A window without samples - a flush right after startup, or right after
173
+ // the previous one - reports 0. NaN would survive into a numeric column,
174
+ // poison every average built over it and make the runtime alert
175
+ // comparisons undefined.
176
+ const lag = windowCount > 0
177
+ ? (delayTotal - this.lastDelayTotal) / windowCount / 1e6 // ns → ms
178
+ : 0;
128
179
  const metrics = {
129
180
  memory: {
130
181
  rss: memoryUsage.rss / 1024 / 1024, // Convert bytes to MB
@@ -151,6 +202,9 @@ let NodeRuntimeMetricsService = NodeRuntimeMetricsService_1 = class NodeRuntimeM
151
202
  },
152
203
  };
153
204
  this.resetGcMetrics();
205
+ this.lastDelayCount = delayCount;
206
+ this.lastDelayTotal = delayTotal;
207
+ this.lastEventLoopUtilization = eventLoopUtilization;
154
208
  this.updateLastCpuUsage(cpuUsage, timestamp);
155
209
  return metrics;
156
210
  }
@@ -585,7 +585,6 @@ export class OperationTraceRegistry {
585
585
  return activeSpan;
586
586
  }
587
587
  async createManualSpan(traceId, callerId, name, spanFunction) {
588
- // await new Promise((resolve) => setImmediate(resolve));
589
588
  // The caller may already have completed (its entry survives completion in
590
589
  // `refsByCaller`); it is still the right source for the class and method
591
590
  // labels, which outlive completion. Where the new span *attaches* is
@@ -627,16 +626,11 @@ export class OperationTraceRegistry {
627
626
  this.attachToCaller(snapshot, refsByCaller, callerId, manualSpan);
628
627
  refsByCaller?.set(newNodeId, manualSpan);
629
628
  const onResponse = (res) => {
630
- // setImmediate
631
629
  this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId);
632
630
  return res;
633
631
  };
634
632
  const onError = (err) => {
635
- // setTimeout(
636
- // () =>
637
633
  this.internalEndTraceStep(traceId, newNodeId, manualSpan.className, manualSpan.methodKey, newNodeId, err);
638
- // 0,
639
- // );
640
634
  // Re-throw the error to maintain original behavior
641
635
  throw err;
642
636
  };
@@ -82,8 +82,8 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
82
82
  }
83
83
  }
84
84
  onModuleInit() {
85
- if (this.options.debug) {
86
- this.logger.debug("Forwarding logs to stdout is enabled.");
85
+ if (this.options.debug && this.options.forwardLogs) {
86
+ this.logger.debug("Forwarding log lines written to stdout and stderr to Observe.");
87
87
  }
88
88
  }
89
89
  onModuleDestroy() {