@nestjs/observe 0.3.5 → 0.3.7

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 (32) hide show
  1. package/README.md +66 -4
  2. package/dist/agent/observe-agent.shared-buffer.js +7 -3
  3. package/dist/agent/observe-agent.worker.d.ts +1 -0
  4. package/dist/agent/observe-agent.worker.js +32 -2
  5. package/dist/agent/telemetry-wire-contract.js +30 -12
  6. package/dist/custom-metrics/counter.d.ts +7 -3
  7. package/dist/custom-metrics/counter.js +34 -7
  8. package/dist/custom-metrics/finite-value.util.d.ts +20 -0
  9. package/dist/custom-metrics/finite-value.util.js +29 -0
  10. package/dist/custom-metrics/gauge.d.ts +2 -0
  11. package/dist/custom-metrics/gauge.js +31 -7
  12. package/dist/custom-metrics/summary.d.ts +5 -0
  13. package/dist/custom-metrics/summary.js +10 -3
  14. package/dist/encoders/custom-metrics.encoder.js +63 -1
  15. package/dist/encoders/trace.encoder.js +34 -0
  16. package/dist/interfaces/custom-metric.interface.d.ts +5 -0
  17. package/dist/interfaces/observe-options.interface.d.ts +23 -14
  18. package/dist/observe.module.js +25 -6
  19. package/dist/protocols/http-observe-agent.service.d.ts +13 -0
  20. package/dist/protocols/http-observe-agent.service.js +34 -8
  21. package/dist/protocols/rpc-observe-agent.service.js +0 -2
  22. package/dist/protocols/schedule-observe-agent.service.js +7 -3
  23. package/dist/services/node-runtime-metrics.service.d.ts +12 -0
  24. package/dist/services/node-runtime-metrics.service.js +95 -41
  25. package/dist/services/operation-trace.registry.js +0 -6
  26. package/dist/services/stdout-forwarder.service.js +2 -2
  27. package/dist/services/tracer.service.js +0 -3
  28. package/dist/utils/fit-service-version.util.js +2 -8
  29. package/dist/utils/fit-to-length.util.d.ts +10 -0
  30. package/dist/utils/fit-to-length.util.js +44 -0
  31. package/package.json +5 -3
  32. package/dist/.tsbuildinfo +0 -1
@@ -1,4 +1,57 @@
1
+ import { fitToLength } from "../utils/fit-to-length.util.js";
1
2
  import { remapKeys } from "./remap-keys.util.js";
3
+ /**
4
+ * The longest name, description and label the collector accepts, and the most
5
+ * labels. It refuses the whole batch over a longer one rather than cutting it,
6
+ * so each is cut to fit here, on the way out - the metric itself keeps what
7
+ * the application gave it, which is what its own label checks compare
8
+ * against. A counter's and a gauge's series keys are bounded where they are
9
+ * made, by `admitsSeries`; a summary's are its labels, and cut with them.
10
+ */
11
+ const MAX_NAME_LENGTH = 100;
12
+ const MAX_DESCRIPTION_LENGTH = 255;
13
+ const MAX_LABEL_LENGTH = 255;
14
+ const MAX_LABELS = 1_000;
15
+ /**
16
+ * Each metric's cut fields, so each is reported once rather than on every
17
+ * flush. Bounded: past it, cuts still happen, silently.
18
+ */
19
+ const reported = new Set();
20
+ const MAX_REPORTED = 100;
21
+ /** `value` cut to `maxLength`, reporting the first cut of this field for this metric. */
22
+ function fit(metricName, field, value, maxLength) {
23
+ const sent = fitToLength(value, maxLength);
24
+ const key = `${field}\u0000${metricName}`;
25
+ if (sent !== value && !reported.has(key) && reported.size < MAX_REPORTED) {
26
+ reported.add(key);
27
+ console.warn(`[observe] Custom metric "${metricName}" has a ${field} of ${value.length} characters, sent as "${sent}": ` +
28
+ `the collector takes at most ${maxLength} and refuses the whole batch over a longer one.`);
29
+ }
30
+ return sent;
31
+ }
32
+ /** At most `MAX_LABELS` labels, each cut to `MAX_LABEL_LENGTH`. */
33
+ function fitLabels(metricName, labels) {
34
+ if (labels.length <= MAX_LABELS &&
35
+ labels.every((label) => label.length <= MAX_LABEL_LENGTH)) {
36
+ return labels;
37
+ }
38
+ return labels
39
+ .slice(0, MAX_LABELS)
40
+ .map((label) => fit(metricName, "label", label, MAX_LABEL_LENGTH));
41
+ }
42
+ /** A summary's map, its label keys cut as `fitLabels` cuts the labels. */
43
+ function fitSummaryKeys(metricName, values) {
44
+ const keys = Object.keys(values);
45
+ if (keys.length <= MAX_LABELS &&
46
+ keys.every((key) => key.length <= MAX_LABEL_LENGTH)) {
47
+ return values;
48
+ }
49
+ const fitted = {};
50
+ for (const key of keys.slice(0, MAX_LABELS)) {
51
+ fitted[fit(metricName, "label", key, MAX_LABEL_LENGTH)] = values[key];
52
+ }
53
+ return fitted;
54
+ }
2
55
  const CUSTOM_METRICS_KEY_MAP = {
3
56
  name: "n",
4
57
  type: "t",
@@ -59,10 +112,19 @@ export class CustomMetricsEncoder {
59
112
  // exist, but the pairing is not something the compiler can follow
60
113
  // through the indirection.
61
114
  encoded[CUSTOM_METRICS_KEY_MAP[key]] =
62
- value;
115
+ fitSummaryKeys(metric.name, value);
63
116
  }
64
117
  }
65
118
  }
119
+ if (typeof encoded.n === "string") {
120
+ encoded.n = fit(metric.name, "name", encoded.n, MAX_NAME_LENGTH);
121
+ }
122
+ if (typeof encoded.d === "string") {
123
+ encoded.d = fit(metric.name, "description", encoded.d, MAX_DESCRIPTION_LENGTH);
124
+ }
125
+ if (Array.isArray(encoded.l)) {
126
+ encoded.l = fitLabels(metric.name, encoded.l);
127
+ }
66
128
  return encoded;
67
129
  }
68
130
  }
@@ -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;