@nestjs/observe 0.3.4 → 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 (33) hide show
  1. package/README.md +98 -5
  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/instrument/create-instance-decorator.instrument.js +20 -4
  15. package/dist/interfaces/custom-metric.interface.d.ts +5 -0
  16. package/dist/interfaces/observe-options.interface.d.ts +28 -14
  17. package/dist/observe.module.js +36 -7
  18. package/dist/protocols/http-observe-agent.service.d.ts +13 -0
  19. package/dist/protocols/http-observe-agent.service.js +34 -8
  20. package/dist/protocols/rpc-observe-agent.service.js +0 -2
  21. package/dist/protocols/schedule-observe-agent.service.js +7 -3
  22. package/dist/services/node-runtime-metrics.service.d.ts +12 -0
  23. package/dist/services/node-runtime-metrics.service.js +95 -41
  24. package/dist/services/operation-trace.registry.js +0 -6
  25. package/dist/services/stdout-forwarder.service.js +2 -2
  26. package/dist/services/tracer.service.js +0 -3
  27. package/dist/utils/fit-service-version.util.d.ts +16 -0
  28. package/dist/utils/fit-service-version.util.js +26 -0
  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/dist/utils/infer-service-version.util.js +9 -11
  32. package/package.json +5 -3
  33. package/dist/.tsbuildinfo +0 -1
@@ -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() {
@@ -40,7 +40,6 @@ let TracerService = class TracerService {
40
40
  * The callback can be synchronous or asynchronous.
41
41
  */
42
42
  async createSpan(name, callback) {
43
- // await new Promise(resolve => setImmediate(resolve));
44
43
  const store = this.als.getStore();
45
44
  if (!store) {
46
45
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "createSpan" method within an async context.');
@@ -58,7 +57,6 @@ let TracerService = class TracerService {
58
57
  * @returns {Promise<TraceSpanDelegate>} A promise that resolves to the active span delegate.
59
58
  */
60
59
  async activeSpan() {
61
- // await new Promise((resolve) => setImmediate(resolve));
62
60
  const store = this.als.getStore();
63
61
  if (!store) {
64
62
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "activeSpan" method within an async context.');
@@ -93,7 +91,6 @@ let TracerService = class TracerService {
93
91
  * This method should be called within an async context where the AsyncLocalStorage is active.
94
92
  */
95
93
  async captureError(error, tags) {
96
- // await new Promise((resolve) => setImmediate(resolve));
97
94
  const store = this.als.getStore();
98
95
  if (!store) {
99
96
  throw new Error('AsyncLocalStorage is not initialized. Ensure that you are using the "captureError" method within an async context.');
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The longest version the collector accepts. A longer one is not truncated
3
+ * there - the whole batch it rides in is refused - so a version is cut to fit
4
+ * before it is ever sent.
5
+ */
6
+ export declare const MAX_SERVICE_VERSION_LENGTH = 50;
7
+ /**
8
+ * `version`, at most as long as the collector accepts.
9
+ *
10
+ * A commit keeps its head, which is what identifies it - and what git and the
11
+ * dashboard shorten it to. Anything else keeps its head too, but ends in a
12
+ * hash of the whole after a `~`: the part each deploy changes can sit past the
13
+ * cut - the tag at the end of an image reference, say - and cut there, every
14
+ * release would arrive as the same one.
15
+ */
16
+ export declare function fitServiceVersion(version: string): string;
@@ -0,0 +1,26 @@
1
+ import { fitToLength } from "./fit-to-length.util.js";
2
+ /**
3
+ * The longest version the collector accepts. A longer one is not truncated
4
+ * there - the whole batch it rides in is refused - so a version is cut to fit
5
+ * before it is ever sent.
6
+ */
7
+ export const MAX_SERVICE_VERSION_LENGTH = 50;
8
+ const HEX = /^[0-9a-f]+$/i;
9
+ /**
10
+ * `version`, at most as long as the collector accepts.
11
+ *
12
+ * A commit keeps its head, which is what identifies it - and what git and the
13
+ * dashboard shorten it to. Anything else keeps its head too, but ends in a
14
+ * hash of the whole after a `~`: the part each deploy changes can sit past the
15
+ * cut - the tag at the end of an image reference, say - and cut there, every
16
+ * release would arrive as the same one.
17
+ */
18
+ export function fitServiceVersion(version) {
19
+ if (version.length <= MAX_SERVICE_VERSION_LENGTH) {
20
+ return version;
21
+ }
22
+ if (HEX.test(version)) {
23
+ return version.slice(0, MAX_SERVICE_VERSION_LENGTH);
24
+ }
25
+ return fitToLength(version, MAX_SERVICE_VERSION_LENGTH);
26
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `value`, at most `maxLength` characters long, for a field the collector
3
+ * bounds. The collector does not cut a longer value down: it refuses the whole
4
+ * batch the value rides in, logs and spans included.
5
+ *
6
+ * Keeps the head, which is what a reader recognises, and ends in a hash of the
7
+ * whole after a `~`, so two values that differ only past the cut stay apart.
8
+ * Never splits a surrogate pair, which would send half a character.
9
+ */
10
+ export declare function fitToLength(value: string, maxLength: number): string;
@@ -0,0 +1,44 @@
1
+ import { createHash } from "crypto";
2
+ /** How much of a cut value is a hash of the whole. */
3
+ const HASH_LENGTH = 8;
4
+ /**
5
+ * Values already cut, so one that keeps arriving - a metric's name, encoded on
6
+ * every increment - is hashed once. Cleared rather than evicted when full: it
7
+ * only ever holds values longer than a limit, which are rare.
8
+ */
9
+ const fitted = new Map();
10
+ const MAX_REMEMBERED = 1_000;
11
+ /**
12
+ * `value`, at most `maxLength` characters long, for a field the collector
13
+ * bounds. The collector does not cut a longer value down: it refuses the whole
14
+ * batch the value rides in, logs and spans included.
15
+ *
16
+ * Keeps the head, which is what a reader recognises, and ends in a hash of the
17
+ * whole after a `~`, so two values that differ only past the cut stay apart.
18
+ * Never splits a surrogate pair, which would send half a character.
19
+ */
20
+ export function fitToLength(value, maxLength) {
21
+ if (value.length <= maxLength) {
22
+ return value;
23
+ }
24
+ const key = `${maxLength}:${value}`;
25
+ const remembered = fitted.get(key);
26
+ if (remembered !== undefined) {
27
+ return remembered;
28
+ }
29
+ let head = maxLength - HASH_LENGTH - 1;
30
+ const last = value.charCodeAt(head - 1);
31
+ if (last >= 0xd800 && last <= 0xdbff) {
32
+ head -= 1;
33
+ }
34
+ const hash = createHash("sha256")
35
+ .update(value)
36
+ .digest("hex")
37
+ .slice(0, HASH_LENGTH);
38
+ const cut = `${value.slice(0, head)}~${hash}`;
39
+ if (fitted.size >= MAX_REMEMBERED) {
40
+ fitted.clear();
41
+ }
42
+ fitted.set(key, cut);
43
+ return cut;
44
+ }
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, statSync } from "fs";
2
2
  import { dirname, join, resolve } from "path";
3
+ import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./fit-service-version.util.js";
3
4
  /**
4
5
  * Environment variables that name the running release, in the order they are
5
6
  * trusted.
@@ -47,14 +48,6 @@ const REVISION_ENV_VARS = [
47
48
  "K_REVISION", // Cloud Run
48
49
  "CONTAINER_APP_REVISION", // Azure Container Apps
49
50
  ];
50
- /**
51
- * The longest version the collector accepts. A longer one is not truncated
52
- * there - the whole batch it rides in is refused - so an inferred version is
53
- * cut to fit before it is ever sent: from the end for a commit, whose head is
54
- * what identifies it, and from the start for a revision, whose head is the
55
- * service's name that every revision shares.
56
- */
57
- const MAX_VERSION_LENGTH = 50;
58
51
  /** A full commit id: SHA-1, or SHA-256 in a repository created with it. */
59
52
  const COMMIT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
60
53
  /**
@@ -69,7 +62,7 @@ export function inferServiceVersion(env = process.env, searchFrom = defaultSearc
69
62
  for (const name of VERSION_ENV_VARS) {
70
63
  const value = env[name]?.trim();
71
64
  if (value) {
72
- return { version: value.slice(0, MAX_VERSION_LENGTH), source: name };
65
+ return { version: fitServiceVersion(value), source: name };
73
66
  }
74
67
  }
75
68
  for (const directory of searchFrom) {
@@ -81,7 +74,12 @@ export function inferServiceVersion(env = process.env, searchFrom = defaultSearc
81
74
  for (const name of REVISION_ENV_VARS) {
82
75
  const value = env[name]?.trim();
83
76
  if (value) {
84
- return { version: value.slice(-MAX_VERSION_LENGTH), source: name };
77
+ // Cut from the start: a revision's head is the service's name, which
78
+ // every revision shares, and its end is the part each deploy changes.
79
+ return {
80
+ version: value.slice(-MAX_SERVICE_VERSION_LENGTH),
81
+ source: name,
82
+ };
85
83
  }
86
84
  }
87
85
  return undefined;
@@ -110,7 +108,7 @@ function readCheckoutHead(start) {
110
108
  if (gitDir) {
111
109
  const commit = readHeadCommit(gitDir);
112
110
  return commit
113
- ? { version: commit.slice(0, MAX_VERSION_LENGTH), source: gitDir }
111
+ ? { version: fitServiceVersion(commit), source: gitDir }
114
112
  : undefined;
115
113
  }
116
114
  const parent = dirname(directory);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.3.4",
4
- "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
3
+ "version": "0.3.6",
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",
7
7
  "repository": {
@@ -38,7 +38,8 @@
38
38
  "./package.json": "./package.json"
39
39
  },
40
40
  "files": [
41
- "dist"
41
+ "dist",
42
+ "!dist/**/*.tsbuildinfo"
42
43
  ],
43
44
  "publishConfig": {
44
45
  "access": "public"
@@ -52,6 +53,7 @@
52
53
  "format": "prettier --write \"src/**/*.ts\"",
53
54
  "lint": "oxlint --type-aware src",
54
55
  "lint:fix": "oxlint --type-aware --fix src",
56
+ "typecheck": "tsc -p tsconfig.json --noEmit --incremental false",
55
57
  "test": "vitest run",
56
58
  "test:watch": "vitest",
57
59
  "test:cov": "vitest run --coverage",