@nestjs/observe 0.3.9 → 0.3.10
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 +4 -0
- package/dist/agent/degraded-ingest.protocol.d.ts +12 -0
- package/dist/agent/degraded-ingest.protocol.js +18 -0
- package/dist/agent/detached-observe-worker.assembly.js +2 -1
- package/dist/agent/detached-observe-worker.d.ts +2 -0
- package/dist/agent/detached-observe-worker.js +19 -0
- package/dist/agent/observe-agent.shared-buffer.d.ts +21 -1
- package/dist/agent/observe-agent.shared-buffer.js +30 -4
- package/dist/agent/observe-agent.worker.d.ts +80 -1
- package/dist/agent/observe-agent.worker.js +246 -11
- package/dist/agent/telemetry-wire-contract.d.ts +9 -1
- package/dist/agent/telemetry-wire-contract.js +25 -4
- package/dist/encoders/job-snapshot.encoder.d.ts +1 -1
- package/dist/encoders/job-snapshot.encoder.js +1 -3
- package/dist/encoders/request-snapshot.encoder.d.ts +1 -1
- package/dist/encoders/request-snapshot.encoder.js +1 -3
- package/dist/interfaces/observe-options.interface.d.ts +12 -0
- package/dist/services/operation-trace.registry.d.ts +7 -0
- package/dist/services/operation-trace.registry.js +16 -1
- package/dist/services/stdout-forwarder.service.d.ts +8 -0
- package/dist/services/stdout-forwarder.service.js +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -120,11 +120,14 @@ async function bootstrap() {
|
|
|
120
120
|
const app = await NestFactory.create(AppModule, {
|
|
121
121
|
instrument: ObserveInstrument,
|
|
122
122
|
});
|
|
123
|
+
app.enableShutdownHooks();
|
|
123
124
|
await app.listen(3000);
|
|
124
125
|
}
|
|
125
126
|
bootstrap();
|
|
126
127
|
```
|
|
127
128
|
|
|
129
|
+
`enableShutdownHooks()` is what lets the agent send what it still holds when the process is stopped - a deploy, a scale-in. Without it Nest runs no shutdown hooks on `SIGTERM`, and the last few seconds of telemetry, the last requests' errors among them, are lost. For the same reason, import `ObserveModule` before other global modules such as `BullModule`: global modules shut down in reverse order of import, and jobs that finish after the agent has stopped are not sent.
|
|
130
|
+
|
|
128
131
|
### Async configuration
|
|
129
132
|
|
|
130
133
|
`ObserveModule.forRootAsync()` resolves the options from the DI container, via
|
|
@@ -322,6 +325,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
322
325
|
| `serviceVersion` | inferred | The release the process runs, at most 50 characters - see [What it records without any code](#what-it-records-without-any-code). `false` reports none. |
|
|
323
326
|
| `endpoint` | `https://observe-api.nestjs.com` | The collector's base URL. `OBSERVE_ENDPOINT` in the environment changes the default without touching the config. |
|
|
324
327
|
| `flushInterval` | `5000` | Milliseconds between sends of buffered telemetry; at least `1000`. |
|
|
328
|
+
| `shutdownFlushTimeout` | `2000` | Milliseconds closing the app waits for buffered telemetry to reach the collector before stopping the agent. `0` skips the final send - for test suites that boot the app with real credentials. |
|
|
325
329
|
| `maxTracesPerBatch` | `1000` | The most traces one send carries. |
|
|
326
330
|
| `tracesSampleRate` | `1.0` | The share of traces kept, or a function `(protocol, attributes) => boolean` deciding per trace. `0` counts as unset and keeps every trace; `() => false` keeps none. |
|
|
327
331
|
| `spanCollapse` | `{ threshold: 20, keepSlowest: 3 }` | See [Repeated spans](#repeated-spans). `false` ships every span. |
|
|
@@ -21,6 +21,18 @@ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
|
|
|
21
21
|
export declare const DEGRADED_TTL_MS: number;
|
|
22
22
|
/** The worker's line for one batch, or null if this is not that line. */
|
|
23
23
|
export declare function parseDegradedMessage(msg: string): boolean | null;
|
|
24
|
+
/**
|
|
25
|
+
* How the detached worker tells the main thread it will send nothing until a
|
|
26
|
+
* given time (epoch milliseconds): after a 429, until the pause lapses; after
|
|
27
|
+
* rejected credentials, never.
|
|
28
|
+
*
|
|
29
|
+
* Only the final flush reads it. A paused worker leaves the shared slot
|
|
30
|
+
* untouched, so without this a shutdown would wait out its whole deadline for
|
|
31
|
+
* a batch that was never going to be sent.
|
|
32
|
+
*/
|
|
33
|
+
export declare const PAUSED_MESSAGE_PREFIX = "observe:paused-until=";
|
|
34
|
+
/** The time sends are paused until, or null if this is not that line. */
|
|
35
|
+
export declare function parsePausedMessage(msg: string): number | null;
|
|
24
36
|
/**
|
|
25
37
|
* Duration past which the collector treats an execution as notable, in
|
|
26
38
|
* milliseconds.
|
|
@@ -26,6 +26,24 @@ export function parseDegradedMessage(msg) {
|
|
|
26
26
|
}
|
|
27
27
|
return msg.slice(DEGRADED_MESSAGE_PREFIX.length) === "true";
|
|
28
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* How the detached worker tells the main thread it will send nothing until a
|
|
31
|
+
* given time (epoch milliseconds): after a 429, until the pause lapses; after
|
|
32
|
+
* rejected credentials, never.
|
|
33
|
+
*
|
|
34
|
+
* Only the final flush reads it. A paused worker leaves the shared slot
|
|
35
|
+
* untouched, so without this a shutdown would wait out its whole deadline for
|
|
36
|
+
* a batch that was never going to be sent.
|
|
37
|
+
*/
|
|
38
|
+
export const PAUSED_MESSAGE_PREFIX = "observe:paused-until=";
|
|
39
|
+
/** The time sends are paused until, or null if this is not that line. */
|
|
40
|
+
export function parsePausedMessage(msg) {
|
|
41
|
+
if (!msg.startsWith(PAUSED_MESSAGE_PREFIX)) {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
const until = Number(msg.slice(PAUSED_MESSAGE_PREFIX.length));
|
|
45
|
+
return Number.isFinite(until) ? until : null;
|
|
46
|
+
}
|
|
29
47
|
/**
|
|
30
48
|
* Duration past which the collector treats an execution as notable, in
|
|
31
49
|
* milliseconds.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
|
|
1
|
+
import { DEGRADED_MESSAGE_PREFIX, PAUSED_MESSAGE_PREFIX, } from "./degraded-ingest.protocol.js";
|
|
2
2
|
import { detachedObserveWorker } from "./detached-observe-worker.js";
|
|
3
3
|
import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
|
|
4
4
|
import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
|
|
@@ -24,6 +24,7 @@ export function detachedWorkerData(input) {
|
|
|
24
24
|
appSecret: input.appSecret,
|
|
25
25
|
wireShapes: SECTION_SHAPES,
|
|
26
26
|
degradedPrefix: DEGRADED_MESSAGE_PREFIX,
|
|
27
|
+
pausedPrefix: PAUSED_MESSAGE_PREFIX,
|
|
27
28
|
};
|
|
28
29
|
return { sharedBuffer: input.sharedBuffer, config };
|
|
29
30
|
}
|
|
@@ -16,6 +16,8 @@ export interface DetachedWorkerConfig {
|
|
|
16
16
|
wireShapes: Parameters<typeof createTelemetrySanitizer>[0];
|
|
17
17
|
/** `DEGRADED_MESSAGE_PREFIX`, as data - see where it is read below. */
|
|
18
18
|
degradedPrefix: string;
|
|
19
|
+
/** `PAUSED_MESSAGE_PREFIX`, as data, for the same reason. */
|
|
20
|
+
pausedPrefix: string;
|
|
19
21
|
}
|
|
20
22
|
export interface DetachedWorkerData {
|
|
21
23
|
sharedBuffer: SharedArrayBuffer;
|
|
@@ -50,6 +50,7 @@ describeRefusal) => {
|
|
|
50
50
|
// `ReferenceError` here. Passed in so the prefix has a single definition
|
|
51
51
|
// that `parseDegradedMessage` still matches.
|
|
52
52
|
const degradedPrefix = config.degradedPrefix;
|
|
53
|
+
const pausedPrefix = config.pausedPrefix;
|
|
53
54
|
/**
|
|
54
55
|
* Built here, used only when the collector answers 400. The shapes travel
|
|
55
56
|
* through `workerData` (they are plain JSON); the factory travels as source.
|
|
@@ -203,6 +204,17 @@ describeRefusal) => {
|
|
|
203
204
|
keepAlive: true,
|
|
204
205
|
timeout: KEEP_ALIVE_IDLE_MS,
|
|
205
206
|
});
|
|
207
|
+
/**
|
|
208
|
+
* How long a send may go without any activity on its socket before it is
|
|
209
|
+
* abandoned.
|
|
210
|
+
*
|
|
211
|
+
* The agent's `timeout` above only emits an event nobody acts on, and the
|
|
212
|
+
* send holds the shared buffer's lock: a collector or proxy that accepts the
|
|
213
|
+
* connection and never answers would otherwise stop every later batch for
|
|
214
|
+
* the life of the process. Abandoned, it fails like any unreachable
|
|
215
|
+
* collector - reported, the batch dropped, the lock released.
|
|
216
|
+
*/
|
|
217
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
206
218
|
/**
|
|
207
219
|
* One POST, with the reply read to the end before it resolves.
|
|
208
220
|
*
|
|
@@ -247,6 +259,7 @@ describeRefusal) => {
|
|
|
247
259
|
req.on("error", (err) => reject(Object.assign(new Error("request to the collector failed", { cause: err }), {
|
|
248
260
|
reusedSocket: req.reusedSocket,
|
|
249
261
|
})));
|
|
262
|
+
req.setTimeout(REQUEST_TIMEOUT_MS, () => req.destroy(Object.assign(new Error(`no answer within ${REQUEST_TIMEOUT_MS / 1000} s`), { code: "ETIMEDOUT" })));
|
|
250
263
|
req.end(body);
|
|
251
264
|
});
|
|
252
265
|
/**
|
|
@@ -393,6 +406,9 @@ describeRefusal) => {
|
|
|
393
406
|
if (!response.ok) {
|
|
394
407
|
if (response.status === 401 || response.status === 403) {
|
|
395
408
|
authRejections += 1;
|
|
409
|
+
// Nothing will be accepted until a restart, so a final flush has
|
|
410
|
+
// nothing to wait for.
|
|
411
|
+
parentPort.postMessage(`${pausedPrefix}${Number.MAX_SAFE_INTEGER}`);
|
|
396
412
|
// Said plainly, and once. The batch is well-formed and the
|
|
397
413
|
// credentials are not accepted for this application; left as a
|
|
398
414
|
// generic transport failure this reads as a network problem, and the
|
|
@@ -413,6 +429,9 @@ describeRefusal) => {
|
|
|
413
429
|
if (response.status === 429) {
|
|
414
430
|
const pauseMs = rateLimitPauseMs(response);
|
|
415
431
|
rateLimitedUntil = Date.now() + pauseMs;
|
|
432
|
+
// The slot is left alone until then, which a final flush would
|
|
433
|
+
// otherwise read as a send still in progress.
|
|
434
|
+
parentPort.postMessage(`${pausedPrefix}${rateLimitedUntil}`);
|
|
416
435
|
// The body says which refusal this is - a quota, a quota frozen by
|
|
417
436
|
// a declined payment, or a rate cap - and each needs a different
|
|
418
437
|
// fix from the operator. Parsed defensively: a rate-cap body is
|
|
@@ -98,6 +98,23 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
98
98
|
private countTruncated;
|
|
99
99
|
isBufferLocked(): boolean;
|
|
100
100
|
isBufferEmpty(): boolean;
|
|
101
|
+
/** Whether log lines are held back for a later batch. */
|
|
102
|
+
hasPendingLogs(): boolean;
|
|
103
|
+
/** Whether the outgoing batch already carries a runtime-metrics sample. */
|
|
104
|
+
hasRuntimeMetrics(): boolean;
|
|
105
|
+
/**
|
|
106
|
+
* Whether a batch written by `encodeAndWrite` is still in the shared slot -
|
|
107
|
+
* not yet taken by the worker, or taken and still being sent.
|
|
108
|
+
*
|
|
109
|
+
* Once the worker takes the slot it holds the lock until the collector has
|
|
110
|
+
* answered (or the send has failed), and zeroes the length just before it
|
|
111
|
+
* lets go, on every path. So a non-zero length means the worker is not done
|
|
112
|
+
* with the last batch, which is what a shutdown waits on before writing
|
|
113
|
+
* another one or terminating the thread - unless the worker has said it is
|
|
114
|
+
* paused (`PAUSED_MESSAGE_PREFIX`), in which case it leaves the slot alone.
|
|
115
|
+
* Read without the lock: a stale answer only costs the caller one more look.
|
|
116
|
+
*/
|
|
117
|
+
hasBatchAwaitingWorker(): boolean;
|
|
101
118
|
/**
|
|
102
119
|
* Takes the lock, or reports that someone else holds it.
|
|
103
120
|
*
|
|
@@ -144,8 +161,11 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
144
161
|
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
145
162
|
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
146
163
|
* views sort on it.
|
|
164
|
+
*
|
|
165
|
+
* `maxLogs` lifts the per-batch cap for the final flush, which sends the
|
|
166
|
+
* whole backlog in one batch rather than one round trip per 250 lines.
|
|
147
167
|
*/
|
|
148
|
-
drainPendingLogs(): void;
|
|
168
|
+
drainPendingLogs(maxLogs?: number): void;
|
|
149
169
|
private truncateLogText;
|
|
150
170
|
encodeAndWrite(): void;
|
|
151
171
|
resetMainThreadBuffer(): void;
|
|
@@ -119,7 +119,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
119
119
|
// are built from, and those are still being kept - and the count goes
|
|
120
120
|
// with it, because it is the only record these existed.
|
|
121
121
|
this.countTruncated(encodedSnapshot.t);
|
|
122
|
-
|
|
122
|
+
encodedSnapshot.t = [];
|
|
123
123
|
}
|
|
124
124
|
this._mainThreadBuffer.snapshots.push(encodedSnapshot);
|
|
125
125
|
// Read off the raw snapshot: the handler's span carries `Class.method`,
|
|
@@ -161,7 +161,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
161
161
|
// A job carries no status code, so the same rule grades it on its error
|
|
162
162
|
// and its duration - which is what the collector does with it too.
|
|
163
163
|
this.countTruncated(encodedJobSnapshot.t);
|
|
164
|
-
|
|
164
|
+
encodedJobSnapshot.t = [];
|
|
165
165
|
}
|
|
166
166
|
this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
|
|
167
167
|
}
|
|
@@ -209,6 +209,29 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
209
209
|
isBufferEmpty() {
|
|
210
210
|
return !this._mainThreadBuffer;
|
|
211
211
|
}
|
|
212
|
+
/** Whether log lines are held back for a later batch. */
|
|
213
|
+
hasPendingLogs() {
|
|
214
|
+
return this._pendingLogs.length > 0;
|
|
215
|
+
}
|
|
216
|
+
/** Whether the outgoing batch already carries a runtime-metrics sample. */
|
|
217
|
+
hasRuntimeMetrics() {
|
|
218
|
+
return this._mainThreadBuffer?.runtime !== undefined;
|
|
219
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* Whether a batch written by `encodeAndWrite` is still in the shared slot -
|
|
222
|
+
* not yet taken by the worker, or taken and still being sent.
|
|
223
|
+
*
|
|
224
|
+
* Once the worker takes the slot it holds the lock until the collector has
|
|
225
|
+
* answered (or the send has failed), and zeroes the length just before it
|
|
226
|
+
* lets go, on every path. So a non-zero length means the worker is not done
|
|
227
|
+
* with the last batch, which is what a shutdown waits on before writing
|
|
228
|
+
* another one or terminating the thread - unless the worker has said it is
|
|
229
|
+
* paused (`PAUSED_MESSAGE_PREFIX`), in which case it leaves the slot alone.
|
|
230
|
+
* Read without the lock: a stale answer only costs the caller one more look.
|
|
231
|
+
*/
|
|
232
|
+
hasBatchAwaitingWorker() {
|
|
233
|
+
return new DataView(this._sharedBuffer, 4, 4).getUint32(0) !== 0;
|
|
234
|
+
}
|
|
212
235
|
/**
|
|
213
236
|
* Takes the lock, or reports that someone else holds it.
|
|
214
237
|
*
|
|
@@ -328,8 +351,11 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
328
351
|
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
329
352
|
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
330
353
|
* views sort on it.
|
|
354
|
+
*
|
|
355
|
+
* `maxLogs` lifts the per-batch cap for the final flush, which sends the
|
|
356
|
+
* whole backlog in one batch rather than one round trip per 250 lines.
|
|
331
357
|
*/
|
|
332
|
-
drainPendingLogs() {
|
|
358
|
+
drainPendingLogs(maxLogs = MAX_LOGS_PER_TRANSACTION) {
|
|
333
359
|
if (this._pendingLogs.length === 0) {
|
|
334
360
|
return;
|
|
335
361
|
}
|
|
@@ -339,7 +365,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
339
365
|
if (!this._mainThreadBuffer.logs) {
|
|
340
366
|
this._mainThreadBuffer.logs = [];
|
|
341
367
|
}
|
|
342
|
-
const capacity =
|
|
368
|
+
const capacity = maxLogs - this._mainThreadBuffer.logs.length;
|
|
343
369
|
if (capacity <= 0) {
|
|
344
370
|
return;
|
|
345
371
|
}
|
|
@@ -1,11 +1,13 @@
|
|
|
1
1
|
import { OnApplicationShutdown, OnModuleInit } from "@nestjs/common";
|
|
2
2
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
|
|
3
3
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
4
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
4
5
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
5
6
|
export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationShutdown {
|
|
6
7
|
private readonly observeAgentSharedBuffer;
|
|
7
8
|
private readonly options;
|
|
8
9
|
private readonly nodeRuntimeMetricsService;
|
|
10
|
+
private readonly operationTraceRegistry?;
|
|
9
11
|
private readonly logger;
|
|
10
12
|
private worker;
|
|
11
13
|
/**
|
|
@@ -20,8 +22,17 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
20
22
|
private isTerminating;
|
|
21
23
|
private flushInterval;
|
|
22
24
|
private runtimeMetricsInterval;
|
|
25
|
+
/** When the last runtime sample was taken, or sampling started. */
|
|
26
|
+
private lastRuntimeSampleAt;
|
|
23
27
|
private cpuProfiler;
|
|
24
|
-
|
|
28
|
+
/** The one shutdown, however many times Nest asks for it. */
|
|
29
|
+
private shutdownPromise;
|
|
30
|
+
/**
|
|
31
|
+
* Until when the worker has said it will send nothing (epoch ms) - after a
|
|
32
|
+
* 429, or for good after rejected credentials. Read by the final flush only.
|
|
33
|
+
*/
|
|
34
|
+
private sendsPausedUntil;
|
|
35
|
+
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService, operationTraceRegistry?: OperationTraceRegistry | undefined);
|
|
25
36
|
onModuleInit(): void;
|
|
26
37
|
/**
|
|
27
38
|
* Starts the runtime-metrics collector: memory, CPU, GC, event loop.
|
|
@@ -43,7 +54,73 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
43
54
|
* real option comes back.
|
|
44
55
|
*/
|
|
45
56
|
private startContinuousProfiling;
|
|
57
|
+
/**
|
|
58
|
+
* Sends what is still buffered, then stops the worker.
|
|
59
|
+
*
|
|
60
|
+
* Runs in `onApplicationShutdown` rather than `beforeApplicationShutdown`
|
|
61
|
+
* on purpose. Nest closes an application as destroy hooks, then
|
|
62
|
+
* before-shutdown hooks, then the HTTP server (letting in-flight requests
|
|
63
|
+
* finish, and record their snapshots), then shutdown hooks - so this is the
|
|
64
|
+
* last point at which requests are still being recorded. Forwarded log
|
|
65
|
+
* lines stop earlier, in the destroy phase (see StdoutForwarderService).
|
|
66
|
+
*
|
|
67
|
+
* Shutdown hooks run module by module, the root module first and global
|
|
68
|
+
* modules last - but global modules among themselves in reverse order of
|
|
69
|
+
* registration. One registered before ObserveModule shuts down after this
|
|
70
|
+
* hook, and what it records then stays in the main-thread buffer, unsent:
|
|
71
|
+
* BullModule, whose workers let their active jobs finish in their own
|
|
72
|
+
* shutdown hook, is the common case. Hence "import ObserveModule first" in
|
|
73
|
+
* the README; with `forRootAsync({ global: false })` this runs before every
|
|
74
|
+
* global module.
|
|
75
|
+
*
|
|
76
|
+
* On a signal, none of this runs unless the application called
|
|
77
|
+
* `app.enableShutdownHooks()` - without it Node ends the process at once.
|
|
78
|
+
*
|
|
79
|
+
* Called once however many times it is asked: `enableShutdownHooks()` plus
|
|
80
|
+
* an application's own signal handler calling `close()` both get here, and a
|
|
81
|
+
* second run would otherwise race the first for the worker.
|
|
82
|
+
*/
|
|
46
83
|
onApplicationShutdown(): Promise<void>;
|
|
84
|
+
private shutDown;
|
|
85
|
+
/**
|
|
86
|
+
* Hands everything still buffered to the worker and waits for it to be
|
|
87
|
+
* sent, for at most `timeoutMs`.
|
|
88
|
+
*
|
|
89
|
+
* Telemetry sits in up to three places at shutdown: the main-thread batch
|
|
90
|
+
* (plus log lines held back for later batches), the shared slot, and the
|
|
91
|
+
* worker's in-flight request - the worker keeps the slot locked and filled
|
|
92
|
+
* until the collector has answered. The slot holds one batch, and a plain
|
|
93
|
+
* `flush()` skips while the worker holds it, so this is a loop: wait for the
|
|
94
|
+
* slot to empty, write the next batch, repeat until there is nothing left to
|
|
95
|
+
* write and the worker is done with the last one. Waiting for an empty slot
|
|
96
|
+
* before each write is also what stops the final flush overwriting a batch
|
|
97
|
+
* the worker has not read yet.
|
|
98
|
+
*
|
|
99
|
+
* Timed with `node:timers` and `process.uptime()` rather than the global
|
|
100
|
+
* `setTimeout` and `Date.now()`, which test suites' fake timers replace - a
|
|
101
|
+
* shutdown waiting on those would never finish.
|
|
102
|
+
*
|
|
103
|
+
* Never throws for a send: a refused or failed batch is reported by the
|
|
104
|
+
* worker as it always is, and clears the slot like a sent one. A worker
|
|
105
|
+
* paused after a 429, or refused for its credentials, says so and is not
|
|
106
|
+
* waited for.
|
|
107
|
+
*/
|
|
108
|
+
private flushBeforeShutdown;
|
|
109
|
+
/**
|
|
110
|
+
* Adds the last runtime sample to the outgoing batch, or says it must wait
|
|
111
|
+
* until that batch has gone.
|
|
112
|
+
*
|
|
113
|
+
* Skipped when its window would be shorter than
|
|
114
|
+
* `MIN_FINAL_RUNTIME_WINDOW_MS`. Otherwise it rides the first batch the
|
|
115
|
+
* final flush sends - unless that batch already carries a sample, which it
|
|
116
|
+
* would replace; then it is taken last (returns `true`), when on Nest 11
|
|
117
|
+
* the monitors may already have stopped.
|
|
118
|
+
*/
|
|
119
|
+
private takeFinalRuntimeSample;
|
|
120
|
+
/**
|
|
121
|
+
* The runtime-metrics window between the last scheduled sample and now.
|
|
122
|
+
*/
|
|
123
|
+
private addFinalRuntimeMetrics;
|
|
47
124
|
private get hasScaffoldCredentials();
|
|
48
125
|
private get endpoint();
|
|
49
126
|
/**
|
|
@@ -58,6 +135,8 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
58
135
|
*/
|
|
59
136
|
private warnIfCredentialsSentInClear;
|
|
60
137
|
initializeWorker(): void;
|
|
138
|
+
/** The worker's messages, errors, and the restart when it dies. */
|
|
139
|
+
private watchWorker;
|
|
61
140
|
handleMessage(msg: string): void;
|
|
62
141
|
/**
|
|
63
142
|
* Whether the last reply said the collector is discarding spans.
|
|
@@ -11,15 +11,17 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
11
11
|
return function (target, key) { decorator(target, key, paramIndex); }
|
|
12
12
|
};
|
|
13
13
|
var ObserveAgentWorker_1;
|
|
14
|
-
import { Inject, Injectable, Logger, } from "@nestjs/common";
|
|
14
|
+
import { Inject, Injectable, Logger, Optional, } from "@nestjs/common";
|
|
15
15
|
import { hostname } from "node:os";
|
|
16
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
16
17
|
import { Worker } from "worker_threads";
|
|
17
18
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
18
19
|
import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
|
|
19
20
|
import { ProfileUploader } from "../profiling/profile-uploader.js";
|
|
20
21
|
import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
|
|
21
22
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
22
|
-
import {
|
|
23
|
+
import { OperationTraceRegistry } from "../services/operation-trace.registry.js";
|
|
24
|
+
import { parseDegradedMessage, parsePausedMessage, } from "./degraded-ingest.protocol.js";
|
|
23
25
|
import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
|
|
24
26
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
25
27
|
const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
|
|
@@ -30,6 +32,35 @@ const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
|
|
|
30
32
|
*/
|
|
31
33
|
const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
|
|
32
34
|
const MIN_FLUSH_INTERVAL = 1000; // 1 second
|
|
35
|
+
/**
|
|
36
|
+
* How long shutdown waits for buffered telemetry to reach the collector before
|
|
37
|
+
* terminating the worker anyway, unless `shutdownFlushTimeout` says otherwise.
|
|
38
|
+
*
|
|
39
|
+
* Several times a healthy round trip to the hosted collector - gzip, a POST,
|
|
40
|
+
* a few-hundred-byte reply, a fresh TLS handshake if the kept-alive socket has
|
|
41
|
+
* gone - and well inside the grace period an orchestrator gives a process
|
|
42
|
+
* after SIGTERM (30 s on ECS and Kubernetes by default), which also has to
|
|
43
|
+
* cover the application's own shutdown hooks. The worker gives up on a silent
|
|
44
|
+
* collector only after its own, much longer, request timeout, so this is what
|
|
45
|
+
* keeps such a collector from holding shutdown open.
|
|
46
|
+
*/
|
|
47
|
+
const FINAL_FLUSH_TIMEOUT_MS = 2000;
|
|
48
|
+
/**
|
|
49
|
+
* How often the final flush looks at the shared slot while the worker is
|
|
50
|
+
* sending. Not what bounds the drain: every batch also waits out the worker's
|
|
51
|
+
* 50 ms idle sleep before it is picked up, which is why the final flush sends
|
|
52
|
+
* the log backlog as one batch rather than 250 lines per round trip.
|
|
53
|
+
*/
|
|
54
|
+
const FINAL_FLUSH_POLL_MS = 10;
|
|
55
|
+
/**
|
|
56
|
+
* The shortest window a last runtime sample is taken over at shutdown.
|
|
57
|
+
*
|
|
58
|
+
* A sample's CPU and event-loop figures are rates over the time since the
|
|
59
|
+
* previous one. Over a few milliseconds - a process that has only just
|
|
60
|
+
* started, or one stopped straight after a scheduled sample - they read as
|
|
61
|
+
* a pegged CPU and a saturated loop, and mean nothing.
|
|
62
|
+
*/
|
|
63
|
+
const MIN_FINAL_RUNTIME_WINDOW_MS = 10_000;
|
|
33
64
|
/**
|
|
34
65
|
* The credentials `nest new --observe` writes into `AppModule`.
|
|
35
66
|
*
|
|
@@ -45,6 +76,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
45
76
|
observeAgentSharedBuffer;
|
|
46
77
|
options;
|
|
47
78
|
nodeRuntimeMetricsService;
|
|
79
|
+
operationTraceRegistry;
|
|
48
80
|
logger = new Logger(ObserveAgentWorker_1.name);
|
|
49
81
|
// Null before `initializeWorker` and again after termination, which is what
|
|
50
82
|
// the shutdown path below checks for.
|
|
@@ -61,11 +93,21 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
61
93
|
isTerminating = false;
|
|
62
94
|
flushInterval;
|
|
63
95
|
runtimeMetricsInterval = null;
|
|
96
|
+
/** When the last runtime sample was taken, or sampling started. */
|
|
97
|
+
lastRuntimeSampleAt = 0;
|
|
64
98
|
cpuProfiler = null;
|
|
65
|
-
|
|
99
|
+
/** The one shutdown, however many times Nest asks for it. */
|
|
100
|
+
shutdownPromise = null;
|
|
101
|
+
/**
|
|
102
|
+
* Until when the worker has said it will send nothing (epoch ms) - after a
|
|
103
|
+
* 429, or for good after rejected credentials. Read by the final flush only.
|
|
104
|
+
*/
|
|
105
|
+
sendsPausedUntil = 0;
|
|
106
|
+
constructor(observeAgentSharedBuffer, options, nodeRuntimeMetricsService, operationTraceRegistry) {
|
|
66
107
|
this.observeAgentSharedBuffer = observeAgentSharedBuffer;
|
|
67
108
|
this.options = options;
|
|
68
109
|
this.nodeRuntimeMetricsService = nodeRuntimeMetricsService;
|
|
110
|
+
this.operationTraceRegistry = operationTraceRegistry;
|
|
69
111
|
}
|
|
70
112
|
onModuleInit() {
|
|
71
113
|
if (this.hasScaffoldCredentials) {
|
|
@@ -110,7 +152,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
110
152
|
this.logger.warn(`Runtime metrics interval is too short (${interval}ms). Setting to minimum of ${MIN_RUNTIME_METRICS_INTERVAL}ms.`);
|
|
111
153
|
interval = MIN_RUNTIME_METRICS_INTERVAL;
|
|
112
154
|
}
|
|
155
|
+
this.lastRuntimeSampleAt = Date.now();
|
|
113
156
|
this.runtimeMetricsInterval = setInterval(() => {
|
|
157
|
+
this.lastRuntimeSampleAt = Date.now();
|
|
114
158
|
this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
|
|
115
159
|
}, interval);
|
|
116
160
|
if (this.options.debug) {
|
|
@@ -170,10 +214,46 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
170
214
|
});
|
|
171
215
|
this.logger.log("Continuous profiling enabled.");
|
|
172
216
|
}
|
|
173
|
-
|
|
217
|
+
/**
|
|
218
|
+
* Sends what is still buffered, then stops the worker.
|
|
219
|
+
*
|
|
220
|
+
* Runs in `onApplicationShutdown` rather than `beforeApplicationShutdown`
|
|
221
|
+
* on purpose. Nest closes an application as destroy hooks, then
|
|
222
|
+
* before-shutdown hooks, then the HTTP server (letting in-flight requests
|
|
223
|
+
* finish, and record their snapshots), then shutdown hooks - so this is the
|
|
224
|
+
* last point at which requests are still being recorded. Forwarded log
|
|
225
|
+
* lines stop earlier, in the destroy phase (see StdoutForwarderService).
|
|
226
|
+
*
|
|
227
|
+
* Shutdown hooks run module by module, the root module first and global
|
|
228
|
+
* modules last - but global modules among themselves in reverse order of
|
|
229
|
+
* registration. One registered before ObserveModule shuts down after this
|
|
230
|
+
* hook, and what it records then stays in the main-thread buffer, unsent:
|
|
231
|
+
* BullModule, whose workers let their active jobs finish in their own
|
|
232
|
+
* shutdown hook, is the common case. Hence "import ObserveModule first" in
|
|
233
|
+
* the README; with `forRootAsync({ global: false })` this runs before every
|
|
234
|
+
* global module.
|
|
235
|
+
*
|
|
236
|
+
* On a signal, none of this runs unless the application called
|
|
237
|
+
* `app.enableShutdownHooks()` - without it Node ends the process at once.
|
|
238
|
+
*
|
|
239
|
+
* Called once however many times it is asked: `enableShutdownHooks()` plus
|
|
240
|
+
* an application's own signal handler calling `close()` both get here, and a
|
|
241
|
+
* second run would otherwise race the first for the worker.
|
|
242
|
+
*/
|
|
243
|
+
onApplicationShutdown() {
|
|
244
|
+
this.shutdownPromise ??= this.shutDown();
|
|
245
|
+
return this.shutdownPromise;
|
|
246
|
+
}
|
|
247
|
+
async shutDown() {
|
|
174
248
|
if (this.flushInterval) {
|
|
175
249
|
clearInterval(this.flushInterval);
|
|
176
250
|
}
|
|
251
|
+
const timeoutMs = this.options.shutdownFlushTimeout ?? FINAL_FLUSH_TIMEOUT_MS;
|
|
252
|
+
// Before the first `await`: on Nest 11 every shutdown hook in this module
|
|
253
|
+
// starts at once, and NodeRuntimeMetricsService stops its monitors as soon
|
|
254
|
+
// as this one yields. Nest 12 runs this hook first, as this class depends
|
|
255
|
+
// on that service.
|
|
256
|
+
const sampleRuntimeMetricsLast = timeoutMs > 0 && this.worker !== null && this.takeFinalRuntimeSample();
|
|
177
257
|
if (this.runtimeMetricsInterval) {
|
|
178
258
|
clearInterval(this.runtimeMetricsInterval);
|
|
179
259
|
}
|
|
@@ -182,16 +262,160 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
182
262
|
await this.cpuProfiler.stop();
|
|
183
263
|
this.cpuProfiler = null;
|
|
184
264
|
}
|
|
185
|
-
|
|
265
|
+
// No worker - scaffold credentials, or never started - means nothing was
|
|
266
|
+
// ever going to be sent, so there is nothing to flush either.
|
|
267
|
+
const worker = this.worker;
|
|
268
|
+
if (!worker) {
|
|
186
269
|
return;
|
|
187
270
|
}
|
|
271
|
+
// Set before the final flush rather than just before `terminate`: a worker
|
|
272
|
+
// that dies while draining must not be replaced by one nothing will stop.
|
|
188
273
|
this.isTerminating = true;
|
|
189
|
-
|
|
274
|
+
if (timeoutMs > 0) {
|
|
275
|
+
try {
|
|
276
|
+
await this.flushBeforeShutdown(worker, timeoutMs, sampleRuntimeMetricsLast);
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
// `flush` reports its own failures; this is anything else, and a
|
|
280
|
+
// shutdown hook that throws would only trade lost telemetry for a
|
|
281
|
+
// shutdown that does not finish cleanly.
|
|
282
|
+
if (this.options.debug) {
|
|
283
|
+
this.logger.debug(`Final flush before shutdown failed: ${String(error)}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
await worker.terminate();
|
|
190
288
|
if (this.options.debug) {
|
|
191
289
|
this.logger.debug("Worker terminated successfully.");
|
|
192
290
|
}
|
|
193
291
|
this.worker = null;
|
|
194
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* Hands everything still buffered to the worker and waits for it to be
|
|
295
|
+
* sent, for at most `timeoutMs`.
|
|
296
|
+
*
|
|
297
|
+
* Telemetry sits in up to three places at shutdown: the main-thread batch
|
|
298
|
+
* (plus log lines held back for later batches), the shared slot, and the
|
|
299
|
+
* worker's in-flight request - the worker keeps the slot locked and filled
|
|
300
|
+
* until the collector has answered. The slot holds one batch, and a plain
|
|
301
|
+
* `flush()` skips while the worker holds it, so this is a loop: wait for the
|
|
302
|
+
* slot to empty, write the next batch, repeat until there is nothing left to
|
|
303
|
+
* write and the worker is done with the last one. Waiting for an empty slot
|
|
304
|
+
* before each write is also what stops the final flush overwriting a batch
|
|
305
|
+
* the worker has not read yet.
|
|
306
|
+
*
|
|
307
|
+
* Timed with `node:timers` and `process.uptime()` rather than the global
|
|
308
|
+
* `setTimeout` and `Date.now()`, which test suites' fake timers replace - a
|
|
309
|
+
* shutdown waiting on those would never finish.
|
|
310
|
+
*
|
|
311
|
+
* Never throws for a send: a refused or failed batch is reported by the
|
|
312
|
+
* worker as it always is, and clears the slot like a sent one. A worker
|
|
313
|
+
* paused after a 429, or refused for its credentials, says so and is not
|
|
314
|
+
* waited for.
|
|
315
|
+
*/
|
|
316
|
+
async flushBeforeShutdown(worker, timeoutMs, sampleRuntimeMetrics) {
|
|
317
|
+
const buffer = this.observeAgentSharedBuffer;
|
|
318
|
+
const deadline = process.uptime() * 1000 + timeoutMs;
|
|
319
|
+
// A worker that dies mid-drain will never empty the slot; there is no
|
|
320
|
+
// point waiting out the deadline for it.
|
|
321
|
+
let exited = false;
|
|
322
|
+
const onExit = () => {
|
|
323
|
+
exited = true;
|
|
324
|
+
};
|
|
325
|
+
worker.once("exit", onExit);
|
|
326
|
+
try {
|
|
327
|
+
// Every protocol records its snapshot from a `setTimeout(0)` after the
|
|
328
|
+
// response or job has finished, so the last requests a process served
|
|
329
|
+
// may not be in the buffer yet - and an empty buffer would end this
|
|
330
|
+
// before they land. A zero timer set now fires after the ones already
|
|
331
|
+
// queued, and the microtasks each of those starts run before it does.
|
|
332
|
+
// A trace whose spans were still open waits a further second in the
|
|
333
|
+
// registry; the loop below waits for those too.
|
|
334
|
+
await sleep(0);
|
|
335
|
+
for (;;) {
|
|
336
|
+
if (exited) {
|
|
337
|
+
if (this.options.debug) {
|
|
338
|
+
this.logger.debug("Worker exited before the final flush completed. Telemetry still buffered was not sent.");
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (Date.now() < this.sendsPausedUntil) {
|
|
343
|
+
if (this.options.debug) {
|
|
344
|
+
this.logger.debug("The collector refused the last batch and sends are paused. Telemetry still buffered was not sent.");
|
|
345
|
+
}
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
if (!buffer.hasBatchAwaitingWorker()) {
|
|
349
|
+
// The whole backlog in one batch once the batch before it has gone,
|
|
350
|
+
// not 250 lines per round trip: each batch also waits out the
|
|
351
|
+
// worker's idle sleep, and a full backlog would outlast the deadline.
|
|
352
|
+
if (buffer.isBufferEmpty()) {
|
|
353
|
+
buffer.drainPendingLogs(Number.POSITIVE_INFINITY);
|
|
354
|
+
}
|
|
355
|
+
this.flush();
|
|
356
|
+
if (!buffer.hasBatchAwaitingWorker() &&
|
|
357
|
+
buffer.isBufferEmpty() &&
|
|
358
|
+
!buffer.hasPendingLogs() &&
|
|
359
|
+
!this.operationTraceRegistry?.hasSnapshotsAwaitingCompletion()) {
|
|
360
|
+
if (!sampleRuntimeMetrics) {
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
// Taken only now that whatever was already buffered has gone: a
|
|
364
|
+
// batch carries a single runtime sample, and each sample covers the
|
|
365
|
+
// window since the previous one, so taking this earlier could
|
|
366
|
+
// replace an unsent sample and lose its window.
|
|
367
|
+
sampleRuntimeMetrics = false;
|
|
368
|
+
this.addFinalRuntimeMetrics();
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (process.uptime() * 1000 >= deadline) {
|
|
373
|
+
if (this.options.debug) {
|
|
374
|
+
this.logger.debug(`Final flush did not complete within ${timeoutMs}ms. Telemetry still buffered was not sent.`);
|
|
375
|
+
}
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
await sleep(FINAL_FLUSH_POLL_MS);
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
finally {
|
|
382
|
+
worker.off("exit", onExit);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Adds the last runtime sample to the outgoing batch, or says it must wait
|
|
387
|
+
* until that batch has gone.
|
|
388
|
+
*
|
|
389
|
+
* Skipped when its window would be shorter than
|
|
390
|
+
* `MIN_FINAL_RUNTIME_WINDOW_MS`. Otherwise it rides the first batch the
|
|
391
|
+
* final flush sends - unless that batch already carries a sample, which it
|
|
392
|
+
* would replace; then it is taken last (returns `true`), when on Nest 11
|
|
393
|
+
* the monitors may already have stopped.
|
|
394
|
+
*/
|
|
395
|
+
takeFinalRuntimeSample() {
|
|
396
|
+
if (!this.runtimeMetricsInterval ||
|
|
397
|
+
Date.now() - this.lastRuntimeSampleAt < MIN_FINAL_RUNTIME_WINDOW_MS) {
|
|
398
|
+
return false;
|
|
399
|
+
}
|
|
400
|
+
if (this.observeAgentSharedBuffer.hasRuntimeMetrics()) {
|
|
401
|
+
return true;
|
|
402
|
+
}
|
|
403
|
+
this.addFinalRuntimeMetrics();
|
|
404
|
+
return false;
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* The runtime-metrics window between the last scheduled sample and now.
|
|
408
|
+
*/
|
|
409
|
+
addFinalRuntimeMetrics() {
|
|
410
|
+
try {
|
|
411
|
+
this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
|
|
412
|
+
}
|
|
413
|
+
catch (error) {
|
|
414
|
+
if (this.options.debug) {
|
|
415
|
+
this.logger.debug(`Could not collect final runtime metrics: ${String(error)}`);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
195
419
|
get hasScaffoldCredentials() {
|
|
196
420
|
return (this.options.appKey === SCAFFOLD_APP_KEY &&
|
|
197
421
|
this.options.appSecret === SCAFFOLD_APP_SECRET);
|
|
@@ -243,9 +467,14 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
243
467
|
appSecret: this.options.appSecret,
|
|
244
468
|
}),
|
|
245
469
|
});
|
|
246
|
-
this.
|
|
247
|
-
this.
|
|
248
|
-
|
|
470
|
+
this.watchWorker(this.worker);
|
|
471
|
+
this.logger.log("Observe agent worker initialized.");
|
|
472
|
+
}
|
|
473
|
+
/** The worker's messages, errors, and the restart when it dies. */
|
|
474
|
+
watchWorker(worker) {
|
|
475
|
+
worker.on("message", (msg) => this.handleMessage(msg));
|
|
476
|
+
worker.on("error", (error) => this.handleError(error));
|
|
477
|
+
worker.on("exit", (code) => {
|
|
249
478
|
if (this.isTerminating) {
|
|
250
479
|
this.logger.debug("Worker exited on shutdown.");
|
|
251
480
|
return;
|
|
@@ -258,9 +487,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
258
487
|
this.logger.debug("Worker exited gracefully.");
|
|
259
488
|
}
|
|
260
489
|
});
|
|
261
|
-
this.logger.log("Observe agent worker initialized.");
|
|
262
490
|
}
|
|
263
491
|
handleMessage(msg) {
|
|
492
|
+
const pausedUntil = parsePausedMessage(msg);
|
|
493
|
+
if (pausedUntil !== null) {
|
|
494
|
+
this.sendsPausedUntil = pausedUntil;
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
264
497
|
const degraded = parseDegradedMessage(msg);
|
|
265
498
|
if (degraded !== null) {
|
|
266
499
|
this.applyDegraded(degraded);
|
|
@@ -346,6 +579,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
346
579
|
ObserveAgentWorker = ObserveAgentWorker_1 = __decorate([
|
|
347
580
|
Injectable(),
|
|
348
581
|
__param(1, Inject(OBSERVE_OPTIONS)),
|
|
349
|
-
|
|
582
|
+
__param(3, Optional()),
|
|
583
|
+
__metadata("design:paramtypes", [ObserveAgentSharedBuffer, Object, NodeRuntimeMetricsService,
|
|
584
|
+
OperationTraceRegistry])
|
|
350
585
|
], ObserveAgentWorker);
|
|
351
586
|
export { ObserveAgentWorker };
|
|
@@ -39,6 +39,12 @@ export interface FieldSpec {
|
|
|
39
39
|
readonly alsoAccepts?: readonly FieldType[];
|
|
40
40
|
/** The field must be present and non-null. */
|
|
41
41
|
readonly required?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* For a required field whose absence has a meaning: what the sanitizer
|
|
44
|
+
* sends in its place, instead of dropping the entry over it. Plain JSON, as
|
|
45
|
+
* it travels to the worker with the shapes.
|
|
46
|
+
*/
|
|
47
|
+
readonly fallback?: unknown;
|
|
42
48
|
/** The field is an array of `type`. */
|
|
43
49
|
readonly array?: boolean;
|
|
44
50
|
/** Nested contract, for object fields the API models rather than passes through. */
|
|
@@ -101,7 +107,9 @@ export interface TelemetrySanitizer {
|
|
|
101
107
|
* would have rejected the whole batch over them (`forbidNonWhitelisted`).
|
|
102
108
|
* A *required* field that is missing or unusable cannot be repaired by
|
|
103
109
|
* removal, so the entry is dropped alone rather than the collector dropping
|
|
104
|
-
* the batch
|
|
110
|
+
* the batch - unless the contract names a fallback for a missing one, as it
|
|
111
|
+
* does for an operation's spans: an operation without its trace array is sent
|
|
112
|
+
* with an empty one, which is what the absence meant.
|
|
105
113
|
*
|
|
106
114
|
* Numbers must be finite: `NaN` and `Infinity` survive `typeof` but serialize
|
|
107
115
|
* to `null` in JSON, which arrives at the API as a present-but-null field and
|
|
@@ -49,6 +49,20 @@ const REQUEST_ATTRIBUTES = {
|
|
|
49
49
|
sc: { type: "number" },
|
|
50
50
|
ou: { type: "string" },
|
|
51
51
|
};
|
|
52
|
+
/**
|
|
53
|
+
* An operation's spans. Required - the API refuses an operation without the
|
|
54
|
+
* array, and the batch with it - but empty when there are none, including when
|
|
55
|
+
* the agent withheld them from a degraded account. Agents 0.2.1 to 0.3.9
|
|
56
|
+
* deleted the key instead, and every degraded batch carrying an ordinary
|
|
57
|
+
* request or job was refused whole.
|
|
58
|
+
*/
|
|
59
|
+
const TRACES = {
|
|
60
|
+
type: "object",
|
|
61
|
+
array: true,
|
|
62
|
+
required: true,
|
|
63
|
+
fallback: [],
|
|
64
|
+
shape: TRACE_NODE,
|
|
65
|
+
};
|
|
52
66
|
/** No `st`: see the note at the top of this file. */
|
|
53
67
|
const REQUEST_SNAPSHOT = {
|
|
54
68
|
ct: { type: "string" },
|
|
@@ -61,7 +75,7 @@ const REQUEST_SNAPSHOT = {
|
|
|
61
75
|
e: { type: "object" },
|
|
62
76
|
rq: { type: "object" },
|
|
63
77
|
a: { type: "object", shape: REQUEST_ATTRIBUTES },
|
|
64
|
-
t:
|
|
78
|
+
t: TRACES,
|
|
65
79
|
};
|
|
66
80
|
/** No `st` here either, for the same reason. */
|
|
67
81
|
const JOB_SNAPSHOT = {
|
|
@@ -78,7 +92,7 @@ const JOB_SNAPSHOT = {
|
|
|
78
92
|
ma: { type: "number" },
|
|
79
93
|
tg: { type: "object" },
|
|
80
94
|
e: { type: "object" },
|
|
81
|
-
t:
|
|
95
|
+
t: TRACES,
|
|
82
96
|
};
|
|
83
97
|
/**
|
|
84
98
|
* One kind of collection in a runtime window. The encoder shortens the kind's
|
|
@@ -196,6 +210,7 @@ const OBJECTIVE_DECLARATION = {
|
|
|
196
210
|
export const TELEMETRY_BATCH = {
|
|
197
211
|
serviceId: { type: "string", required: true },
|
|
198
212
|
serviceVersion: { type: "string" },
|
|
213
|
+
truncatedSpans: { type: "number" },
|
|
199
214
|
forwardLogs: { type: "boolean" },
|
|
200
215
|
snapshots: { type: "object", array: true, shape: REQUEST_SNAPSHOT },
|
|
201
216
|
jobs: { type: "object", array: true, shape: JOB_SNAPSHOT },
|
|
@@ -290,7 +305,9 @@ function checkField(value, spec, parent, path, options, errors) {
|
|
|
290
305
|
* would have rejected the whole batch over them (`forbidNonWhitelisted`).
|
|
291
306
|
* A *required* field that is missing or unusable cannot be repaired by
|
|
292
307
|
* removal, so the entry is dropped alone rather than the collector dropping
|
|
293
|
-
* the batch
|
|
308
|
+
* the batch - unless the contract names a fallback for a missing one, as it
|
|
309
|
+
* does for an operation's spans: an operation without its trace array is sent
|
|
310
|
+
* with an empty one, which is what the absence meant.
|
|
294
311
|
*
|
|
295
312
|
* Numbers must be finite: `NaN` and `Infinity` survive `typeof` but serialize
|
|
296
313
|
* to `null` in JSON, which arrives at the API as a present-but-null field and
|
|
@@ -330,7 +347,11 @@ export function createTelemetrySanitizer(shapes) {
|
|
|
330
347
|
const fieldPath = `${path}.${key}`;
|
|
331
348
|
const present = value[key] !== undefined && value[key] !== null;
|
|
332
349
|
if (!present) {
|
|
333
|
-
if (spec.required) {
|
|
350
|
+
if (spec.required && spec.fallback !== undefined) {
|
|
351
|
+
problems.push(`${fieldPath}: required, sent as ${JSON.stringify(spec.fallback)}`);
|
|
352
|
+
value[key] = structuredClone(spec.fallback);
|
|
353
|
+
}
|
|
354
|
+
else if (spec.required) {
|
|
334
355
|
problems.push(`${fieldPath}: required`);
|
|
335
356
|
usable = false;
|
|
336
357
|
}
|
|
@@ -20,7 +20,7 @@ declare const SNAPSHOT_KEY_MAP: {
|
|
|
20
20
|
export type EncodedJobSnapshot = Omit<{
|
|
21
21
|
[K in keyof JobSnapshot as K extends keyof typeof SNAPSHOT_KEY_MAP ? (typeof SNAPSHOT_KEY_MAP)[K] : never]: JobSnapshot[K];
|
|
22
22
|
}, "t"> & {
|
|
23
|
-
t
|
|
23
|
+
t: Array<RecursiveEncodedTrace>;
|
|
24
24
|
};
|
|
25
25
|
export declare class JobSnapshotEncoder {
|
|
26
26
|
static encode(snapshot: JobSnapshot): EncodedJobSnapshot;
|
|
@@ -20,9 +20,7 @@ const SNAPSHOT_KEY_MAP = {
|
|
|
20
20
|
export class JobSnapshotEncoder {
|
|
21
21
|
static encode(snapshot) {
|
|
22
22
|
const encoded = remapKeys(snapshot, SNAPSHOT_KEY_MAP);
|
|
23
|
-
|
|
24
|
-
encoded.t = snapshot.traces.map((trace) => encodeTrace(trace));
|
|
25
|
-
}
|
|
23
|
+
encoded.t = (snapshot.traces ?? []).map((trace) => encodeTrace(trace));
|
|
26
24
|
return encoded;
|
|
27
25
|
}
|
|
28
26
|
}
|
|
@@ -25,7 +25,7 @@ export type EncodedAttributes = {
|
|
|
25
25
|
export type EncodedRequestSnapshot = Omit<{
|
|
26
26
|
[K in keyof RequestSnapshot as K extends keyof typeof SNAPSHOT_KEY_MAP ? (typeof SNAPSHOT_KEY_MAP)[K] : never]: RequestSnapshot[K];
|
|
27
27
|
}, "t" | "a"> & {
|
|
28
|
-
t
|
|
28
|
+
t: Array<RecursiveEncodedTrace>;
|
|
29
29
|
a?: EncodedAttributes;
|
|
30
30
|
};
|
|
31
31
|
export declare class RequestSnapshotEncoder {
|
|
@@ -22,9 +22,7 @@ const SNAPSHOT_KEY_MAP = {
|
|
|
22
22
|
export class RequestSnapshotEncoder {
|
|
23
23
|
static encode(snapshot) {
|
|
24
24
|
const encoded = remapKeys(snapshot, SNAPSHOT_KEY_MAP);
|
|
25
|
-
|
|
26
|
-
encoded.t = snapshot.traces.map((trace) => encodeTrace(trace));
|
|
27
|
-
}
|
|
25
|
+
encoded.t = (snapshot.traces ?? []).map((trace) => encodeTrace(trace));
|
|
28
26
|
if (snapshot.attributes) {
|
|
29
27
|
encoded.a = remapKeys(snapshot.attributes, ATTRIBUTES_KEY_MAP);
|
|
30
28
|
}
|
|
@@ -195,6 +195,18 @@ export interface ObserveOptions {
|
|
|
195
195
|
* @default 5000
|
|
196
196
|
*/
|
|
197
197
|
flushInterval?: number;
|
|
198
|
+
/**
|
|
199
|
+
* How long, in milliseconds, closing the application waits for buffered
|
|
200
|
+
* telemetry to reach the collector before stopping the agent anyway. Runs
|
|
201
|
+
* on `app.close()`, and on a shutdown signal when the application called
|
|
202
|
+
* `app.enableShutdownHooks()`.
|
|
203
|
+
*
|
|
204
|
+
* `0` skips the final send - for test suites that boot the application
|
|
205
|
+
* with real credentials and should neither send their requests to the
|
|
206
|
+
* project nor wait on the collector at every `close()`.
|
|
207
|
+
* @default 2000
|
|
208
|
+
*/
|
|
209
|
+
shutdownFlushTimeout?: number;
|
|
198
210
|
/**
|
|
199
211
|
* Whether to collect runtime metrics: memory, CPU load, GC and event loop
|
|
200
212
|
* latency, sampled on an interval and drawn as gauges.
|
|
@@ -176,6 +176,13 @@ export declare class OperationTraceRegistry {
|
|
|
176
176
|
* no response has no status code to file it under.
|
|
177
177
|
*/
|
|
178
178
|
abandonTrace(traceId: TraceId): void;
|
|
179
|
+
/**
|
|
180
|
+
* Plucks waiting out `SNAPSHOT_COMPLETION_TIMEOUT_MS` for spans that were
|
|
181
|
+
* still open when their operation ended. Their snapshots reach the buffer
|
|
182
|
+
* only once the wait is over, which a final flush has to wait for.
|
|
183
|
+
*/
|
|
184
|
+
private awaitingCompletion;
|
|
185
|
+
hasSnapshotsAwaitingCompletion(): boolean;
|
|
179
186
|
pluckSnapshot(traceId: string): Promise<RequestSnapshot | JobSnapshot | undefined>;
|
|
180
187
|
/**
|
|
181
188
|
* Whether `skipSpans` claims a finished operation. Only request snapshots
|
|
@@ -506,6 +506,15 @@ export class OperationTraceRegistry {
|
|
|
506
506
|
this.callerIdsByTraceId.delete(traceId);
|
|
507
507
|
this.traceSnapshots.delete(traceId);
|
|
508
508
|
}
|
|
509
|
+
/**
|
|
510
|
+
* Plucks waiting out `SNAPSHOT_COMPLETION_TIMEOUT_MS` for spans that were
|
|
511
|
+
* still open when their operation ended. Their snapshots reach the buffer
|
|
512
|
+
* only once the wait is over, which a final flush has to wait for.
|
|
513
|
+
*/
|
|
514
|
+
awaitingCompletion = 0;
|
|
515
|
+
hasSnapshotsAwaitingCompletion() {
|
|
516
|
+
return this.awaitingCompletion > 0;
|
|
517
|
+
}
|
|
509
518
|
async pluckSnapshot(traceId) {
|
|
510
519
|
const snapshot = this.traceSnapshots.get(traceId);
|
|
511
520
|
if (snapshot) {
|
|
@@ -515,7 +524,13 @@ export class OperationTraceRegistry {
|
|
|
515
524
|
};
|
|
516
525
|
// Ensure snapshot is complete by checking refsCounter vs refsMarkedAsComplete
|
|
517
526
|
if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
|
|
518
|
-
|
|
527
|
+
this.awaitingCompletion += 1;
|
|
528
|
+
try {
|
|
529
|
+
await new Promise((resolve) => setTimeout(resolve, SNAPSHOT_COMPLETION_TIMEOUT_MS));
|
|
530
|
+
}
|
|
531
|
+
finally {
|
|
532
|
+
this.awaitingCompletion -= 1;
|
|
533
|
+
}
|
|
519
534
|
if (snapshot.refsCounter > snapshot.refsMarkedAsComplete) {
|
|
520
535
|
cleanup();
|
|
521
536
|
return undefined;
|
|
@@ -27,6 +27,14 @@ export declare class StdoutForwarderService implements OnModuleInit, OnModuleDes
|
|
|
27
27
|
private readonly redactor;
|
|
28
28
|
constructor(options: ObserveModuleOptionsWithDefaults, observeAgentSharedBuffer: ObserveAgentSharedBuffer, als: AsyncLocalStorage<Map<string, any>>);
|
|
29
29
|
onModuleInit(): void;
|
|
30
|
+
/**
|
|
31
|
+
* Stops forwarding at the first close phase - before in-flight requests
|
|
32
|
+
* finish and before the final flush. Lines written after this point, a
|
|
33
|
+
* draining request's included, are not sent; its snapshot still is. Moving
|
|
34
|
+
* this later needs care: forwarding during the final flush would feed the
|
|
35
|
+
* agent's own "could not reach the collector" lines back into the batches
|
|
36
|
+
* it is trying to send.
|
|
37
|
+
*/
|
|
30
38
|
onModuleDestroy(): void;
|
|
31
39
|
/**
|
|
32
40
|
* Patches both stdout and stderr. Nest's `ConsoleLogger` writes `error` to
|
|
@@ -86,6 +86,14 @@ let StdoutForwarderService = StdoutForwarderService_1 = class StdoutForwarderSer
|
|
|
86
86
|
this.logger.debug("Forwarding log lines written to stdout and stderr to Observe.");
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
|
+
/**
|
|
90
|
+
* Stops forwarding at the first close phase - before in-flight requests
|
|
91
|
+
* finish and before the final flush. Lines written after this point, a
|
|
92
|
+
* draining request's included, are not sent; its snapshot still is. Moving
|
|
93
|
+
* this later needs care: forwarding during the final flush would feed the
|
|
94
|
+
* agent's own "could not reach the collector" lines back into the batches
|
|
95
|
+
* it is trying to send.
|
|
96
|
+
*/
|
|
89
97
|
onModuleDestroy() {
|
|
90
98
|
this.restore();
|
|
91
99
|
}
|
package/package.json
CHANGED