@nestjs/observe 0.1.10 → 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.
- package/README.md +108 -18
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/degraded-ingest.protocol.d.ts +67 -0
- package/dist/agent/degraded-ingest.protocol.js +86 -0
- package/dist/agent/detached-observe-worker.js +20 -0
- package/dist/agent/observe-agent.shared-buffer.d.ts +28 -0
- package/dist/agent/observe-agent.shared-buffer.js +54 -0
- package/dist/agent/observe-agent.worker.d.ts +18 -0
- package/dist/agent/observe-agent.worker.js +35 -0
- package/dist/interfaces/observe-options.interface.d.ts +44 -0
- package/dist/observe.module.js +10 -1
- package/dist/services/collapse-repeated-spans.util.d.ts +76 -0
- package/dist/services/collapse-repeated-spans.util.js +216 -0
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.js +1 -0
- package/dist/services/operation-trace.registry.d.ts +14 -0
- package/dist/services/operation-trace.registry.js +23 -0
- package/package.json +9 -3
|
@@ -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
|
}
|
|
@@ -218,6 +218,50 @@ export interface ObserveOptions {
|
|
|
218
218
|
* @default 1000
|
|
219
219
|
*/
|
|
220
220
|
maxTracesPerBatch?: number;
|
|
221
|
+
/**
|
|
222
|
+
* Collapses repeated sibling spans before a trace is shipped.
|
|
223
|
+
*
|
|
224
|
+
* A provider the framework calls in a loop - the canonical case is a
|
|
225
|
+
* `ValidationPipe` registered through `APP_PIPE`, which runs once per
|
|
226
|
+
* argument of every GraphQL field resolver - produces thousands of
|
|
227
|
+
* near-identical spans under one parent for a single list query. Every one
|
|
228
|
+
* of them is a metered event, and together they say nothing a count would
|
|
229
|
+
* not.
|
|
230
|
+
*
|
|
231
|
+
* When more than `threshold` siblings under the same parent share a class
|
|
232
|
+
* and method, the slowest `keepSlowest` of them and any that errored stay
|
|
233
|
+
* as ordinary spans, and the rest are replaced by a single node carrying
|
|
234
|
+
* their count (as the `observe.collapsed` tag) and their *summed*
|
|
235
|
+
* duration. That sum is what keeps the parent's self time exact, and the
|
|
236
|
+
* children of the collapsed calls are carried across so class attribution
|
|
237
|
+
* beneath them survives too. The collapsed node is metered as one event.
|
|
238
|
+
*
|
|
239
|
+
* Nothing is skipped and no duration threshold is involved, deliberately:
|
|
240
|
+
* what validation costs is application-specific, and the outliers that
|
|
241
|
+
* explain a slow request are exactly the instances kept whole. What is lost
|
|
242
|
+
* is the relative ordering of the collapsed calls among themselves - the
|
|
243
|
+
* node takes the earliest call's `startOffset` - which is acceptable for
|
|
244
|
+
* calls that are identical by construction.
|
|
245
|
+
*
|
|
246
|
+
* On by default. Set to `false` to ship every span.
|
|
247
|
+
*
|
|
248
|
+
* @default { threshold: 20, keepSlowest: 3 }
|
|
249
|
+
*/
|
|
250
|
+
spanCollapse?: false | {
|
|
251
|
+
/**
|
|
252
|
+
* Number of siblings sharing a class and method that a parent may
|
|
253
|
+
* hold before the surplus is collapsed. Collapsing starts at
|
|
254
|
+
* `threshold + 1`.
|
|
255
|
+
* @default 20
|
|
256
|
+
*/
|
|
257
|
+
threshold?: number;
|
|
258
|
+
/**
|
|
259
|
+
* How many of the slowest instances to keep as individual spans when
|
|
260
|
+
* a group collapses. Errored instances are kept in addition to these.
|
|
261
|
+
* @default 3
|
|
262
|
+
*/
|
|
263
|
+
keepSlowest?: number;
|
|
264
|
+
};
|
|
221
265
|
/**
|
|
222
266
|
* Whether to forward logs to the Observe APM.
|
|
223
267
|
* If true, logs will be forwarded to the Agent for correlation with traces.
|
package/dist/observe.module.js
CHANGED
|
@@ -24,6 +24,7 @@ import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js
|
|
|
24
24
|
import { ScheduleObserveAgentService } from "./protocols/schedule-observe-agent.service.js";
|
|
25
25
|
import { LoggerPatcherService } from "./services/logger-patcher.service.js";
|
|
26
26
|
import { NodeRuntimeMetricsService } from "./services/node-runtime-metrics.service.js";
|
|
27
|
+
import { resolveSpanCollapseSettings } from "./services/collapse-repeated-spans.util.js";
|
|
27
28
|
import { OperationTraceRegistry } from "./services/operation-trace.registry.js";
|
|
28
29
|
import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
|
|
29
30
|
import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
@@ -140,7 +141,15 @@ export function createObserveModule(options = {}) {
|
|
|
140
141
|
},
|
|
141
142
|
{
|
|
142
143
|
provide: OperationTraceRegistry,
|
|
143
|
-
|
|
144
|
+
// The instance already exists (the instrumentation hook below holds
|
|
145
|
+
// it), so this is the one moment the resolved `ObserveOptions` and the
|
|
146
|
+
// registry meet: `spanCollapse` is applied here. Optional because
|
|
147
|
+
// `ASSERT_MODULE_OPTIONS` owns the missing-options error.
|
|
148
|
+
useFactory: (observeOptions) => {
|
|
149
|
+
operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
|
|
150
|
+
return operationTraceRegistry;
|
|
151
|
+
},
|
|
152
|
+
inject: [{ token: OBSERVE_OPTIONS, optional: true }],
|
|
144
153
|
},
|
|
145
154
|
TracerService,
|
|
146
155
|
LoggerPatcherService,
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { ObserveOptions } from "../interfaces/observe-options.interface.js";
|
|
2
|
+
import { CompleteTraceEventNode, OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js";
|
|
3
|
+
/**
|
|
4
|
+
* Tag under which a collapsed node records how many calls it stands for.
|
|
5
|
+
*
|
|
6
|
+
* A tag rather than a field of its own so the wire format does not change:
|
|
7
|
+
* `tags` is already on every span and already declared by the collector's
|
|
8
|
+
* contract, so an agent emitting this needs no matching collector release. A
|
|
9
|
+
* collector that does not know the tag stores it like any other and
|
|
10
|
+
* attributes the node as one call; one that does reads the true count here.
|
|
11
|
+
* Namespaced so it reads as the agent's in a span's tag list, and safe from
|
|
12
|
+
* collision: the node it sits on never exists at runtime, so no user code can
|
|
13
|
+
* set tags on it, and the tags of the calls it replaces are dropped.
|
|
14
|
+
*
|
|
15
|
+
* Absent on an ordinary span, which stands for exactly one call. On a node
|
|
16
|
+
* that carries it, `duration` is the *sum* of the replaced calls' durations,
|
|
17
|
+
* `startOffset` and `spanId` are the earliest call's, and `children` holds
|
|
18
|
+
* every child the replaced calls had - which is what keeps the parent's self
|
|
19
|
+
* time and the subtree's class attribution exactly what they were. Ordering
|
|
20
|
+
* among the replaced calls is lost. The node is one event on the wire and is
|
|
21
|
+
* metered as one.
|
|
22
|
+
*/
|
|
23
|
+
export declare const SPAN_COLLAPSED_TAG = "observe.collapsed";
|
|
24
|
+
/** Resolved form of `ObserveOptions.spanCollapse`. */
|
|
25
|
+
export interface SpanCollapseSettings {
|
|
26
|
+
/** Siblings sharing a frame that may stand before the surplus collapses. */
|
|
27
|
+
threshold: number;
|
|
28
|
+
/** Slowest instances kept whole once a group collapses. */
|
|
29
|
+
keepSlowest: number;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Twenty is above what a hand-written method produces under one parent - a
|
|
33
|
+
* handler calling a repository a dozen times in a loop is still shipped
|
|
34
|
+
* whole - and far below the hundreds a framework hook like `ValidationPipe`
|
|
35
|
+
* produces per GraphQL list query. Three kept instances is enough to show the
|
|
36
|
+
* spread between the slowest calls without the tail of identical ones behind
|
|
37
|
+
* them.
|
|
38
|
+
*/
|
|
39
|
+
export declare const DEFAULT_SPAN_COLLAPSE: SpanCollapseSettings;
|
|
40
|
+
/**
|
|
41
|
+
* Turns the user-facing option into settings the registry can apply, or
|
|
42
|
+
* `undefined` when collapsing is switched off. Unusable values - a negative
|
|
43
|
+
* count, a fraction, `NaN` - fall back to the default for that field rather
|
|
44
|
+
* than disabling the feature: an option typo should not silently reopen the
|
|
45
|
+
* span flood this exists to stop.
|
|
46
|
+
*/
|
|
47
|
+
export declare function resolveSpanCollapseSettings(option: ObserveOptions["spanCollapse"]): SpanCollapseSettings | undefined;
|
|
48
|
+
/**
|
|
49
|
+
* Collapses repeated siblings throughout a completed span tree, in place.
|
|
50
|
+
*
|
|
51
|
+
* Within one list of siblings, auto spans are grouped by `className` and
|
|
52
|
+
* `methodKey`. A group larger than `threshold` keeps its `keepSlowest`
|
|
53
|
+
* longest-running members and every member that errored as ordinary spans;
|
|
54
|
+
* the rest are replaced by one node that records how many calls it stands
|
|
55
|
+
* for (`SPAN_COLLAPSED_TAG`) and the sum of their durations. Manual spans are never collapsed - a
|
|
56
|
+
* user named each of them deliberately - and ongoing nodes, which a shipped
|
|
57
|
+
* tree should not contain, are left alone.
|
|
58
|
+
*
|
|
59
|
+
* Summing the durations, rather than taking the wall-clock envelope, is what
|
|
60
|
+
* keeps the collector's self-time partition exact: a parent's self time is its
|
|
61
|
+
* duration minus the durations of its children, and the sum over the surviving
|
|
62
|
+
* children is the same as it was over the originals. The collapsed calls'
|
|
63
|
+
* own children are carried across onto the collapsed node for the same reason
|
|
64
|
+
* one level down, and then collapsed among themselves in turn - a repeated
|
|
65
|
+
* frame that always calls the same repeated frame collapses at both levels.
|
|
66
|
+
*
|
|
67
|
+
* Siblings are matched wherever they sit in the list, not only when adjacent:
|
|
68
|
+
* a pipe run once per argument interleaves with the resolver calls it
|
|
69
|
+
* validates for. The collapsed node takes the position of the earliest call
|
|
70
|
+
* it replaces, so ordering relative to the *other* siblings is kept; ordering
|
|
71
|
+
* among the collapsed calls themselves is lost.
|
|
72
|
+
*
|
|
73
|
+
* Returns the new sibling list for the level passed in. Descendant lists are
|
|
74
|
+
* rewritten through their parents' `children`.
|
|
75
|
+
*/
|
|
76
|
+
export declare function collapseRepeatedSpans(siblings: Array<CompleteTraceEventNode | OngoingTraceEventNode>, settings: SpanCollapseSettings): Array<CompleteTraceEventNode | OngoingTraceEventNode>;
|