@nestjs/observe 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,67 @@
1
+ /**
2
+ * How the detached worker tells the main thread that the collector is
3
+ * accepting batches while discarding their spans.
4
+ *
5
+ * A string prefix rather than a structured message because the worker channel
6
+ * is already strings - every other line it posts is human-readable prose the
7
+ * parent logs - and a second message shape would have to be threaded through
8
+ * the same handler anyway. Parsed in exactly one place on each side.
9
+ */
10
+ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
11
+ /**
12
+ * How long the main thread keeps withholding spans after the last batch that
13
+ * reported degradation.
14
+ *
15
+ * The state is advisory and the collector never announces the end of it: an
16
+ * upgrade or the turn of the billing period simply starts keeping spans
17
+ * again. So it expires on its own, and the cost of it being briefly stale is
18
+ * one flush of spans sent and discarded - against a restart being required to
19
+ * recover, which is what a sticky flag would have cost.
20
+ */
21
+ export declare const DEGRADED_TTL_MS: number;
22
+ /** The worker's line for one batch, or null if this is not that line. */
23
+ export declare function parseDegradedMessage(msg: string): boolean | null;
24
+ /**
25
+ * Duration past which the collector treats an execution as notable, in
26
+ * milliseconds.
27
+ *
28
+ * Mirrors the collector's `NOTABLE_TRACE_DURATION_MS`. Duplicated because the
29
+ * agent cannot reach the server's constants, and the cost of drift is bounded
30
+ * and one-directional: too low here sends trees the collector discards, too
31
+ * high withholds ones it would have kept.
32
+ */
33
+ export declare const NOTABLE_DURATION_MS = 1000;
34
+ /**
35
+ * Whether the collector would keep this execution's spans even while degraded.
36
+ *
37
+ * Degraded ingestion truncates ordinary traffic and keeps the executions worth
38
+ * looking at. The agent has to make the same call before it withholds
39
+ * anything, or an account past its allowance loses exactly the waterfalls the
40
+ * collector was still willing to store - and loses them silently.
41
+ *
42
+ * The rule mirrors the collector's, including the part that looks wrong:
43
+ * where there is a status code it decides alone, and the error object is not
44
+ * consulted beside it. An expected 401 carries an error exactly like a 500
45
+ * does, and on that platform 401s and 429s are most of the daily error count -
46
+ * so consulting the error first would send a tree for every unauthenticated
47
+ * probe, which is the traffic this exists to stop sending.
48
+ */
49
+ export declare function isNotableSnapshot(snapshot: {
50
+ d?: number;
51
+ e?: unknown;
52
+ a?: {
53
+ sc?: number;
54
+ };
55
+ }): boolean;
56
+ /**
57
+ * Nodes in an encoded trace tree, counted the way the collector counts them.
58
+ *
59
+ * Every node, children included - which is what the meter bills and what the
60
+ * collector's own `countTraceNodes` walks. Counting roots instead would report
61
+ * a fraction of what was withheld and measure the account against the wrong
62
+ * volume; on an auto-instrumented request, where a single root routinely
63
+ * carries eighty-odd children, it would be off by roughly that factor.
64
+ *
65
+ * Children live under `ch`, matching the encoded shape the collector parses.
66
+ */
67
+ export declare function countTraceNodes(traces: unknown): number;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * How the detached worker tells the main thread that the collector is
3
+ * accepting batches while discarding their spans.
4
+ *
5
+ * A string prefix rather than a structured message because the worker channel
6
+ * is already strings - every other line it posts is human-readable prose the
7
+ * parent logs - and a second message shape would have to be threaded through
8
+ * the same handler anyway. Parsed in exactly one place on each side.
9
+ */
10
+ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
11
+ /**
12
+ * How long the main thread keeps withholding spans after the last batch that
13
+ * reported degradation.
14
+ *
15
+ * The state is advisory and the collector never announces the end of it: an
16
+ * upgrade or the turn of the billing period simply starts keeping spans
17
+ * again. So it expires on its own, and the cost of it being briefly stale is
18
+ * one flush of spans sent and discarded - against a restart being required to
19
+ * recover, which is what a sticky flag would have cost.
20
+ */
21
+ export const DEGRADED_TTL_MS = 5 * 60 * 1000;
22
+ /** The worker's line for one batch, or null if this is not that line. */
23
+ export function parseDegradedMessage(msg) {
24
+ if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
25
+ return null;
26
+ }
27
+ return msg.slice(DEGRADED_MESSAGE_PREFIX.length) === "true";
28
+ }
29
+ /**
30
+ * Duration past which the collector treats an execution as notable, in
31
+ * milliseconds.
32
+ *
33
+ * Mirrors the collector's `NOTABLE_TRACE_DURATION_MS`. Duplicated because the
34
+ * agent cannot reach the server's constants, and the cost of drift is bounded
35
+ * and one-directional: too low here sends trees the collector discards, too
36
+ * high withholds ones it would have kept.
37
+ */
38
+ export const NOTABLE_DURATION_MS = 1_000;
39
+ const SERVER_ERROR_FLOOR = 500;
40
+ /**
41
+ * Whether the collector would keep this execution's spans even while degraded.
42
+ *
43
+ * Degraded ingestion truncates ordinary traffic and keeps the executions worth
44
+ * looking at. The agent has to make the same call before it withholds
45
+ * anything, or an account past its allowance loses exactly the waterfalls the
46
+ * collector was still willing to store - and loses them silently.
47
+ *
48
+ * The rule mirrors the collector's, including the part that looks wrong:
49
+ * where there is a status code it decides alone, and the error object is not
50
+ * consulted beside it. An expected 401 carries an error exactly like a 500
51
+ * does, and on that platform 401s and 429s are most of the daily error count -
52
+ * so consulting the error first would send a tree for every unauthenticated
53
+ * probe, which is the traffic this exists to stop sending.
54
+ */
55
+ export function isNotableSnapshot(snapshot) {
56
+ const slow = typeof snapshot.d === "number" && snapshot.d > NOTABLE_DURATION_MS;
57
+ const statusCode = snapshot.a?.sc;
58
+ if (typeof statusCode === "number") {
59
+ return statusCode >= SERVER_ERROR_FLOOR || slow;
60
+ }
61
+ // No status code: a job, or a non-HTTP entry point. Nothing grades these but
62
+ // the error, so here it is the signal rather than the noise.
63
+ return Boolean(snapshot.e) || slow;
64
+ }
65
+ /**
66
+ * Nodes in an encoded trace tree, counted the way the collector counts them.
67
+ *
68
+ * Every node, children included - which is what the meter bills and what the
69
+ * collector's own `countTraceNodes` walks. Counting roots instead would report
70
+ * a fraction of what was withheld and measure the account against the wrong
71
+ * volume; on an auto-instrumented request, where a single root routinely
72
+ * carries eighty-odd children, it would be off by roughly that factor.
73
+ *
74
+ * Children live under `ch`, matching the encoded shape the collector parses.
75
+ */
76
+ export function countTraceNodes(traces) {
77
+ if (!Array.isArray(traces)) {
78
+ return 0;
79
+ }
80
+ let count = 0;
81
+ for (const node of traces) {
82
+ count += 1;
83
+ count += countTraceNodes(node?.ch);
84
+ }
85
+ return count;
86
+ }
@@ -1,3 +1,4 @@
1
+ import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
1
2
  export const detachedObserveWorker = (
2
3
  // The factory's *source* is inlined as this argument when the worker script
3
4
  // is assembled (see `ObserveAgentWorker.initializeWorker`) - a stringified
@@ -285,6 +286,25 @@ describeRefusal) => {
285
286
  (errorBody ? ` - ${errorBody.slice(0, 500)}` : ""));
286
287
  return true;
287
288
  }
289
+ /*
290
+ * The collector answers 200 while it is discarding the spans in the
291
+ * batch - an account past its plan's allowance keeps its requests, jobs
292
+ * and errors and loses the trace trees underneath them. Nothing in the
293
+ * status says so, so the body is the only way to learn it, and an agent
294
+ * that does not look keeps building, serializing and gzipping trees
295
+ * that die on arrival.
296
+ *
297
+ * Read defensively and treated as absent on anything unexpected: an
298
+ * older collector returns no body at all, and a parse failure here must
299
+ * never turn a successful send into a reported failure.
300
+ */
301
+ const accepted = await response.json().catch(() => undefined);
302
+ const degraded = typeof accepted === "object" &&
303
+ accepted !== null &&
304
+ accepted.degraded === true;
305
+ // A protocol line, not prose: the parent keys off the prefix and the
306
+ // value, and is the side that decides what to do about it.
307
+ parentPort.postMessage(`${DEGRADED_MESSAGE_PREFIX}${degraded}`);
288
308
  parentPort.postMessage("Tracing and instrumentation data sent successfully");
289
309
  return true;
290
310
  }
@@ -66,6 +66,34 @@ export declare class ObserveAgentSharedBuffer {
66
66
  constructor(options: ObserveModuleOptionsWithDefaults);
67
67
  insertRequestSnapshot(snapshot: RequestSnapshot): void;
68
68
  insertJobSnapshot(jobSnapshot: JobSnapshot): void;
69
+ /**
70
+ * Until when the collector's last answer says spans are being discarded.
71
+ *
72
+ * Zero means "not degraded", which is also where a fresh process starts:
73
+ * the state is learned from a reply, so the first batch after start-up
74
+ * always carries its spans. One batch of wasted trees is the price of not
75
+ * persisting a guess across restarts.
76
+ */
77
+ private degradedUntil;
78
+ /**
79
+ * Records what the collector said about the last batch.
80
+ *
81
+ * Refreshed on every reply rather than latched, so the window slides while
82
+ * the account stays over its allowance and lapses on its own once it does
83
+ * not - the collector has no way to announce the end of it, and an upgrade
84
+ * must not need a restart to take effect.
85
+ */
86
+ setDegraded(degraded: boolean): void;
87
+ isDegraded(): boolean;
88
+ /**
89
+ * Adds a withheld tree to the batch's reported truncation.
90
+ *
91
+ * Every node, not every root: the collector meters a trace by its node
92
+ * count, so a number that counted roots would under-report by the shape of
93
+ * the tree and the account would be measured against a fraction of what it
94
+ * actually produced.
95
+ */
96
+ private countTruncated;
69
97
  isBufferLocked(): boolean;
70
98
  isBufferEmpty(): boolean;
71
99
  /**
@@ -11,6 +11,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
11
11
  return function (target, key) { decorator(target, key, paramIndex); }
12
12
  };
13
13
  var ObserveAgentSharedBuffer_1;
14
+ import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, } from "./degraded-ingest.protocol.js";
14
15
  import { Inject, Injectable, Logger } from "@nestjs/common";
15
16
  import { Counter, Summary } from "../custom-metrics/index.js";
16
17
  import { CustomMetricsEncoder, } from "../encoders/custom-metrics.encoder.js";
@@ -101,6 +102,15 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
101
102
  return;
102
103
  }
103
104
  const encodedSnapshot = RequestSnapshotEncoder.encode(snapshot);
105
+ if (this.isDegraded() && !isNotableSnapshot(encodedSnapshot)) {
106
+ // The collector is discarding these on arrival; shipping them costs the
107
+ // application its own CPU and bandwidth for nothing. The snapshot still
108
+ // goes - the request, its duration and its error are what the charts
109
+ // are built from, and those are still being kept - and the count goes
110
+ // with it, because it is the only record these existed.
111
+ this.countTruncated(encodedSnapshot.t);
112
+ delete encodedSnapshot.t;
113
+ }
104
114
  this._mainThreadBuffer.snapshots.push(encodedSnapshot);
105
115
  }
106
116
  insertJobSnapshot(jobSnapshot) {
@@ -122,8 +132,52 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
122
132
  return;
123
133
  }
124
134
  const encodedJobSnapshot = JobSnapshotEncoder.encode(jobSnapshot);
135
+ if (this.isDegraded() && !isNotableSnapshot(encodedJobSnapshot)) {
136
+ // A job carries no status code, so the same rule grades it on its error
137
+ // and its duration - which is what the collector does with it too.
138
+ this.countTruncated(encodedJobSnapshot.t);
139
+ delete encodedJobSnapshot.t;
140
+ }
125
141
  this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
126
142
  }
143
+ /**
144
+ * Until when the collector's last answer says spans are being discarded.
145
+ *
146
+ * Zero means "not degraded", which is also where a fresh process starts:
147
+ * the state is learned from a reply, so the first batch after start-up
148
+ * always carries its spans. One batch of wasted trees is the price of not
149
+ * persisting a guess across restarts.
150
+ */
151
+ degradedUntil = 0;
152
+ /**
153
+ * Records what the collector said about the last batch.
154
+ *
155
+ * Refreshed on every reply rather than latched, so the window slides while
156
+ * the account stays over its allowance and lapses on its own once it does
157
+ * not - the collector has no way to announce the end of it, and an upgrade
158
+ * must not need a restart to take effect.
159
+ */
160
+ setDegraded(degraded) {
161
+ this.degradedUntil = degraded ? Date.now() + DEGRADED_TTL_MS : 0;
162
+ }
163
+ isDegraded() {
164
+ return this.degradedUntil > Date.now();
165
+ }
166
+ /**
167
+ * Adds a withheld tree to the batch's reported truncation.
168
+ *
169
+ * Every node, not every root: the collector meters a trace by its node
170
+ * count, so a number that counted roots would under-report by the shape of
171
+ * the tree and the account would be measured against a fraction of what it
172
+ * actually produced.
173
+ */
174
+ countTruncated(traces) {
175
+ if (!this._mainThreadBuffer) {
176
+ return;
177
+ }
178
+ this._mainThreadBuffer.truncatedSpans =
179
+ (this._mainThreadBuffer.truncatedSpans ?? 0) + countTraceNodes(traces);
180
+ }
127
181
  isBufferLocked() {
128
182
  return Atomics.load(this.lock, 0) !== 0;
129
183
  }
@@ -48,6 +48,24 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
48
48
  private warnIfCredentialsSentInClear;
49
49
  initializeWorker(): void;
50
50
  handleMessage(msg: string): void;
51
+ /**
52
+ * Whether the last reply said the collector is discarding spans.
53
+ *
54
+ * Kept beside the log rather than read from the buffer so the notice fires
55
+ * once per transition: an account sits in this state for days, and a line
56
+ * per flush would bury the one thing worth reading.
57
+ */
58
+ private reportedDegraded;
59
+ /**
60
+ * Stops sending trace trees the collector has told us it is throwing away,
61
+ * and says so once.
62
+ *
63
+ * Said at `warn` rather than `debug`: the application is still being
64
+ * observed, the waterfalls are not being kept, and a developer who finds
65
+ * that out by opening a trace and seeing nothing has been let down by an
66
+ * agent that knew.
67
+ */
68
+ private applyDegraded;
51
69
  handleError(error: Error): void;
52
70
  flush(): void;
53
71
  }
@@ -21,6 +21,7 @@ import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-sl
21
21
  import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
22
22
  import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
23
23
  import { detachedObserveWorker } from "./detached-observe-worker.js";
24
+ import { parseDegradedMessage } from "./degraded-ingest.protocol.js";
24
25
  import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
25
26
  import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
26
27
  const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
@@ -223,6 +224,11 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
223
224
  this.logger.log("Observe agent worker initialized.");
224
225
  }
225
226
  handleMessage(msg) {
227
+ const degraded = parseDegradedMessage(msg);
228
+ if (degraded !== null) {
229
+ this.applyDegraded(degraded);
230
+ return;
231
+ }
226
232
  if (msg.includes("Error:")) {
227
233
  this.logger.error(msg);
228
234
  return;
@@ -231,6 +237,35 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
231
237
  this.logger.debug(msg);
232
238
  }
233
239
  }
240
+ /**
241
+ * Whether the last reply said the collector is discarding spans.
242
+ *
243
+ * Kept beside the log rather than read from the buffer so the notice fires
244
+ * once per transition: an account sits in this state for days, and a line
245
+ * per flush would bury the one thing worth reading.
246
+ */
247
+ reportedDegraded = false;
248
+ /**
249
+ * Stops sending trace trees the collector has told us it is throwing away,
250
+ * and says so once.
251
+ *
252
+ * Said at `warn` rather than `debug`: the application is still being
253
+ * observed, the waterfalls are not being kept, and a developer who finds
254
+ * that out by opening a trace and seeing nothing has been let down by an
255
+ * agent that knew.
256
+ */
257
+ applyDegraded(degraded) {
258
+ this.observeAgentSharedBuffer.setDegraded(degraded);
259
+ if (degraded && !this.reportedDegraded) {
260
+ this.logger.warn("Observe: this account has spent its monthly event allowance. Requests, jobs " +
261
+ "and errors are still being recorded; spans are not, so traces will show no " +
262
+ "waterfall. The agent has stopped sending them. See /dashboard/billing.");
263
+ }
264
+ else if (!degraded && this.reportedDegraded) {
265
+ this.logger.log("Observe: spans are being recorded again.");
266
+ }
267
+ this.reportedDegraded = degraded;
268
+ }
234
269
  handleError(error) {
235
270
  this.logger.error(error);
236
271
  }
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@nestjs/observe",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Observability and APM agent for NestJS - traces, runtime metrics, custom metrics and CPU profiles",
5
5
  "author": "Kamil Mysliwiec",
6
- "homepage": "https://nestjs.com",
6
+ "homepage": "https://observe.nestjs.com",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/nestjs/observe.git"
@@ -20,7 +20,13 @@
20
20
  "telemetry",
21
21
  "metrics",
22
22
  "profiling",
23
- "instrumentation"
23
+ "instrumentation",
24
+ "monitoring",
25
+ "opentelemetry",
26
+ "distributed-tracing",
27
+ "error-tracking",
28
+ "logging",
29
+ "performance"
24
30
  ],
25
31
  "main": "./dist/index.js",
26
32
  "types": "./dist/index.d.ts",