@nestjs/observe 0.3.9 → 0.3.11
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 +5 -1
- package/dist/agent/degraded-ingest.protocol.d.ts +35 -2
- package/dist/agent/degraded-ingest.protocol.js +35 -2
- 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 +35 -9
- package/dist/agent/observe-agent.shared-buffer.d.ts +27 -1
- package/dist/agent/observe-agent.shared-buffer.js +41 -6
- package/dist/agent/observe-agent.worker.d.ts +87 -7
- package/dist/agent/observe-agent.worker.js +273 -28
- package/dist/agent/telemetry-wire-contract.d.ts +43 -2
- package/dist/agent/telemetry-wire-contract.js +164 -34
- 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/instrument/create-instance-decorator.instrument.js +29 -0
- package/dist/interfaces/observe-options.interface.d.ts +18 -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 +16 -0
- package/dist/services/stdout-forwarder.service.js +43 -3
- package/dist/utils/log-line.parser.d.ts +2 -1
- package/dist/utils/log-line.parser.js +74 -11
- package/dist/utils/log-redactor.js +6 -1
- 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. |
|
|
@@ -348,7 +352,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
348
352
|
| `traceIdGenerator` | the `x-request-id` header, else a UUIDv7 | Gives each request its trace id. |
|
|
349
353
|
| `traceIdKey` | `'traceId'` | The key the trace id is stored under in the request context. |
|
|
350
354
|
| `attachTraceIdToLogs` | `true` | Adds the trace id to the `ConsoleLogger`'s own output, on Nest 11.2 and later. Sending lines to the dashboard is `forwardLogs`. |
|
|
351
|
-
| `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented.
|
|
355
|
+
| `skipInstrumentation` | `() => false` | Returns `true` for a provider instance that must not be instrumented. Nest's `Reflector` never is, whatever this returns. |
|
|
352
356
|
|
|
353
357
|
## Optional peer dependencies
|
|
354
358
|
|
|
@@ -6,8 +6,23 @@
|
|
|
6
6
|
* is already strings - every other line it posts is human-readable prose the
|
|
7
7
|
* parent logs - and a second message shape would have to be threaded through
|
|
8
8
|
* the same handler anyway. Parsed in exactly one place on each side.
|
|
9
|
+
*
|
|
10
|
+
* The value after it is `false`, `true`, or `trimmed` - see `IngestMode`.
|
|
9
11
|
*/
|
|
10
12
|
export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
|
|
13
|
+
/**
|
|
14
|
+
* What the collector said it does with a batch's spans.
|
|
15
|
+
*
|
|
16
|
+
* - `full`: keeps them all.
|
|
17
|
+
* - `reduced`: the account has used its monthly allowance - Free's reduced
|
|
18
|
+
* ingest - and only notable traces keep their spans.
|
|
19
|
+
* - `trimmed`: a paying account past its threshold has its traces trimmed by
|
|
20
|
+
* the same rule, to keep its bill down.
|
|
21
|
+
*
|
|
22
|
+
* Both of the last two withhold exactly the same trees; they differ only in
|
|
23
|
+
* why, which is what the operator is told and what they can do about it.
|
|
24
|
+
*/
|
|
25
|
+
export type IngestMode = "full" | "reduced" | "trimmed";
|
|
11
26
|
/**
|
|
12
27
|
* How long the main thread keeps withholding spans after the last batch that
|
|
13
28
|
* reported degradation.
|
|
@@ -19,8 +34,26 @@ export declare const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
|
|
|
19
34
|
* recover, which is what a sticky flag would have cost.
|
|
20
35
|
*/
|
|
21
36
|
export declare const DEGRADED_TTL_MS: number;
|
|
22
|
-
/**
|
|
23
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The worker's line for one batch, or null if this is not that line.
|
|
39
|
+
*
|
|
40
|
+
* `true` and `false` are what the line has always carried, and they mean what
|
|
41
|
+
* they always did; `trimmed` is the one addition. Anything else reads as
|
|
42
|
+
* `full`, as every value but `true` always has.
|
|
43
|
+
*/
|
|
44
|
+
export declare function parseDegradedMessage(msg: string): IngestMode | null;
|
|
45
|
+
/**
|
|
46
|
+
* How the detached worker tells the main thread it will send nothing until a
|
|
47
|
+
* given time (epoch milliseconds): after a 429, until the pause lapses; after
|
|
48
|
+
* rejected credentials, never.
|
|
49
|
+
*
|
|
50
|
+
* Only the final flush reads it. A paused worker leaves the shared slot
|
|
51
|
+
* untouched, so without this a shutdown would wait out its whole deadline for
|
|
52
|
+
* a batch that was never going to be sent.
|
|
53
|
+
*/
|
|
54
|
+
export declare const PAUSED_MESSAGE_PREFIX = "observe:paused-until=";
|
|
55
|
+
/** The time sends are paused until, or null if this is not that line. */
|
|
56
|
+
export declare function parsePausedMessage(msg: string): number | null;
|
|
24
57
|
/**
|
|
25
58
|
* Duration past which the collector treats an execution as notable, in
|
|
26
59
|
* milliseconds.
|
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
* is already strings - every other line it posts is human-readable prose the
|
|
7
7
|
* parent logs - and a second message shape would have to be threaded through
|
|
8
8
|
* the same handler anyway. Parsed in exactly one place on each side.
|
|
9
|
+
*
|
|
10
|
+
* The value after it is `false`, `true`, or `trimmed` - see `IngestMode`.
|
|
9
11
|
*/
|
|
10
12
|
export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
|
|
11
13
|
/**
|
|
@@ -19,12 +21,43 @@ export const DEGRADED_MESSAGE_PREFIX = "observe:degraded=";
|
|
|
19
21
|
* recover, which is what a sticky flag would have cost.
|
|
20
22
|
*/
|
|
21
23
|
export const DEGRADED_TTL_MS = 5 * 60 * 1000;
|
|
22
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* The worker's line for one batch, or null if this is not that line.
|
|
26
|
+
*
|
|
27
|
+
* `true` and `false` are what the line has always carried, and they mean what
|
|
28
|
+
* they always did; `trimmed` is the one addition. Anything else reads as
|
|
29
|
+
* `full`, as every value but `true` always has.
|
|
30
|
+
*/
|
|
23
31
|
export function parseDegradedMessage(msg) {
|
|
24
32
|
if (!msg.startsWith(DEGRADED_MESSAGE_PREFIX)) {
|
|
25
33
|
return null;
|
|
26
34
|
}
|
|
27
|
-
|
|
35
|
+
switch (msg.slice(DEGRADED_MESSAGE_PREFIX.length)) {
|
|
36
|
+
case "true":
|
|
37
|
+
return "reduced";
|
|
38
|
+
case "trimmed":
|
|
39
|
+
return "trimmed";
|
|
40
|
+
default:
|
|
41
|
+
return "full";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* How the detached worker tells the main thread it will send nothing until a
|
|
46
|
+
* given time (epoch milliseconds): after a 429, until the pause lapses; after
|
|
47
|
+
* rejected credentials, never.
|
|
48
|
+
*
|
|
49
|
+
* Only the final flush reads it. A paused worker leaves the shared slot
|
|
50
|
+
* untouched, so without this a shutdown would wait out its whole deadline for
|
|
51
|
+
* a batch that was never going to be sent.
|
|
52
|
+
*/
|
|
53
|
+
export const PAUSED_MESSAGE_PREFIX = "observe:paused-until=";
|
|
54
|
+
/** The time sends are paused until, or null if this is not that line. */
|
|
55
|
+
export function parsePausedMessage(msg) {
|
|
56
|
+
if (!msg.startsWith(PAUSED_MESSAGE_PREFIX)) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const until = Number(msg.slice(PAUSED_MESSAGE_PREFIX.length));
|
|
60
|
+
return Number.isFinite(until) ? until : null;
|
|
28
61
|
}
|
|
29
62
|
/**
|
|
30
63
|
* Duration past which the collector treats an execution as notable, in
|
|
@@ -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
|
|
@@ -442,23 +461,30 @@ describeRefusal) => {
|
|
|
442
461
|
}
|
|
443
462
|
/*
|
|
444
463
|
* The collector answers 200 while it is discarding the spans in the
|
|
445
|
-
* batch - an account past its plan's allowance
|
|
446
|
-
*
|
|
447
|
-
*
|
|
448
|
-
*
|
|
449
|
-
* that die on
|
|
464
|
+
* batch - an account past its plan's allowance, or a paying one past
|
|
465
|
+
* its trim threshold, keeps its requests, jobs and errors and loses the
|
|
466
|
+
* trace trees of all but its notable traces. Nothing in the status says
|
|
467
|
+
* so, so the body is the only way to learn it, and an agent that does
|
|
468
|
+
* not look keeps building, serializing and gzipping trees that die on
|
|
469
|
+
* arrival.
|
|
450
470
|
*
|
|
451
471
|
* Read defensively and treated as absent on anything unexpected: an
|
|
452
472
|
* older collector returns no body at all, and a parse failure here must
|
|
453
473
|
* never turn a successful send into a reported failure.
|
|
454
474
|
*/
|
|
455
475
|
const accepted = await response.json().catch(() => undefined);
|
|
456
|
-
const
|
|
457
|
-
|
|
458
|
-
|
|
476
|
+
const reply = (typeof accepted === "object" && accepted !== null ? accepted : {});
|
|
477
|
+
// `false`, `true` or `trimmed`. `trimmed` says only why the spans are
|
|
478
|
+
// discarded, so it counts only beside `degraded`; a collector that never
|
|
479
|
+
// sends it gets exactly the line it always did.
|
|
480
|
+
const verdict = reply.degraded !== true
|
|
481
|
+
? "false"
|
|
482
|
+
: reply.trimmed === true
|
|
483
|
+
? "trimmed"
|
|
484
|
+
: "true";
|
|
459
485
|
// A protocol line, not prose: the parent keys off the prefix and the
|
|
460
486
|
// value, and is the side that decides what to do about it.
|
|
461
|
-
parentPort.postMessage(`${degradedPrefix}${
|
|
487
|
+
parentPort.postMessage(`${degradedPrefix}${verdict}`);
|
|
462
488
|
parentPort.postMessage("Tracing and instrumentation data sent successfully");
|
|
463
489
|
return true;
|
|
464
490
|
}
|
|
@@ -96,8 +96,31 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
96
96
|
* actually produced.
|
|
97
97
|
*/
|
|
98
98
|
private countTruncated;
|
|
99
|
+
/**
|
|
100
|
+
* `maxTracesPerBatch`, held to the most the collector accepts in one section
|
|
101
|
+
* of a batch. It refuses a batch holding more whole, so a setting above that
|
|
102
|
+
* would cost a busy window every operation in it rather than the overflow.
|
|
103
|
+
*/
|
|
104
|
+
private get maxOperationsPerBatch();
|
|
99
105
|
isBufferLocked(): boolean;
|
|
100
106
|
isBufferEmpty(): boolean;
|
|
107
|
+
/** Whether log lines are held back for a later batch. */
|
|
108
|
+
hasPendingLogs(): boolean;
|
|
109
|
+
/** Whether the outgoing batch already carries a runtime-metrics sample. */
|
|
110
|
+
hasRuntimeMetrics(): boolean;
|
|
111
|
+
/**
|
|
112
|
+
* Whether a batch written by `encodeAndWrite` is still in the shared slot -
|
|
113
|
+
* not yet taken by the worker, or taken and still being sent.
|
|
114
|
+
*
|
|
115
|
+
* Once the worker takes the slot it holds the lock until the collector has
|
|
116
|
+
* answered (or the send has failed), and zeroes the length just before it
|
|
117
|
+
* lets go, on every path. So a non-zero length means the worker is not done
|
|
118
|
+
* with the last batch, which is what a shutdown waits on before writing
|
|
119
|
+
* another one or terminating the thread - unless the worker has said it is
|
|
120
|
+
* paused (`PAUSED_MESSAGE_PREFIX`), in which case it leaves the slot alone.
|
|
121
|
+
* Read without the lock: a stale answer only costs the caller one more look.
|
|
122
|
+
*/
|
|
123
|
+
hasBatchAwaitingWorker(): boolean;
|
|
101
124
|
/**
|
|
102
125
|
* Takes the lock, or reports that someone else holds it.
|
|
103
126
|
*
|
|
@@ -144,8 +167,11 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
144
167
|
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
145
168
|
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
146
169
|
* views sort on it.
|
|
170
|
+
*
|
|
171
|
+
* `maxLogs` lifts the per-batch cap for the final flush, which sends the
|
|
172
|
+
* whole backlog in one batch rather than one round trip per 250 lines.
|
|
147
173
|
*/
|
|
148
|
-
drainPendingLogs(): void;
|
|
174
|
+
drainPendingLogs(maxLogs?: number): void;
|
|
149
175
|
private truncateLogText;
|
|
150
176
|
encodeAndWrite(): void;
|
|
151
177
|
resetMainThreadBuffer(): void;
|
|
@@ -12,6 +12,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
|
12
12
|
};
|
|
13
13
|
var ObserveAgentSharedBuffer_1;
|
|
14
14
|
import { countTraceNodes, DEGRADED_TTL_MS, isNotableSnapshot, } from "./degraded-ingest.protocol.js";
|
|
15
|
+
import { MAX_BATCH_ITEMS } from "./telemetry-wire-contract.js";
|
|
15
16
|
import { Inject, Injectable, Logger, Optional } from "@nestjs/common";
|
|
16
17
|
import { Counter, Summary } from "../custom-metrics/index.js";
|
|
17
18
|
import { ObjectivesRegistry, } from "../objectives/objectives.registry.js";
|
|
@@ -104,7 +105,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
104
105
|
if (!this._mainThreadBuffer) {
|
|
105
106
|
this._mainThreadBuffer = this.createEmptyPayload();
|
|
106
107
|
}
|
|
107
|
-
const maxPerBatch = this.
|
|
108
|
+
const maxPerBatch = this.maxOperationsPerBatch;
|
|
108
109
|
if (this._mainThreadBuffer.snapshots.length >= maxPerBatch) {
|
|
109
110
|
if (this.options.debug) {
|
|
110
111
|
this.logger.debug(`Max snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
|
|
@@ -119,7 +120,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
119
120
|
// are built from, and those are still being kept - and the count goes
|
|
120
121
|
// with it, because it is the only record these existed.
|
|
121
122
|
this.countTruncated(encodedSnapshot.t);
|
|
122
|
-
|
|
123
|
+
encodedSnapshot.t = [];
|
|
123
124
|
}
|
|
124
125
|
this._mainThreadBuffer.snapshots.push(encodedSnapshot);
|
|
125
126
|
// Read off the raw snapshot: the handler's span carries `Class.method`,
|
|
@@ -149,7 +150,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
149
150
|
// empties when a flush succeeds, so without a ceiling a stalled flush on
|
|
150
151
|
// the worker service - the process that sees every queue job - grows this
|
|
151
152
|
// array for as long as the stall lasts.
|
|
152
|
-
const maxPerBatch = this.
|
|
153
|
+
const maxPerBatch = this.maxOperationsPerBatch;
|
|
153
154
|
if (this._mainThreadBuffer.jobs.length >= maxPerBatch) {
|
|
154
155
|
if (this.options.debug) {
|
|
155
156
|
this.logger.debug(`Max job snapshots per transaction reached: ${maxPerBatch}. Ignoring snapshot.`);
|
|
@@ -161,7 +162,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
161
162
|
// A job carries no status code, so the same rule grades it on its error
|
|
162
163
|
// and its duration - which is what the collector does with it too.
|
|
163
164
|
this.countTruncated(encodedJobSnapshot.t);
|
|
164
|
-
|
|
165
|
+
encodedJobSnapshot.t = [];
|
|
165
166
|
}
|
|
166
167
|
this._mainThreadBuffer.jobs.push(encodedJobSnapshot);
|
|
167
168
|
}
|
|
@@ -203,12 +204,43 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
203
204
|
this._mainThreadBuffer.truncatedSpans =
|
|
204
205
|
(this._mainThreadBuffer.truncatedSpans ?? 0) + countTraceNodes(traces);
|
|
205
206
|
}
|
|
207
|
+
/**
|
|
208
|
+
* `maxTracesPerBatch`, held to the most the collector accepts in one section
|
|
209
|
+
* of a batch. It refuses a batch holding more whole, so a setting above that
|
|
210
|
+
* would cost a busy window every operation in it rather than the overflow.
|
|
211
|
+
*/
|
|
212
|
+
get maxOperationsPerBatch() {
|
|
213
|
+
return Math.min(this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION, MAX_BATCH_ITEMS);
|
|
214
|
+
}
|
|
206
215
|
isBufferLocked() {
|
|
207
216
|
return Atomics.load(this.lock, 0) !== 0;
|
|
208
217
|
}
|
|
209
218
|
isBufferEmpty() {
|
|
210
219
|
return !this._mainThreadBuffer;
|
|
211
220
|
}
|
|
221
|
+
/** Whether log lines are held back for a later batch. */
|
|
222
|
+
hasPendingLogs() {
|
|
223
|
+
return this._pendingLogs.length > 0;
|
|
224
|
+
}
|
|
225
|
+
/** Whether the outgoing batch already carries a runtime-metrics sample. */
|
|
226
|
+
hasRuntimeMetrics() {
|
|
227
|
+
return this._mainThreadBuffer?.runtime !== undefined;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Whether a batch written by `encodeAndWrite` is still in the shared slot -
|
|
231
|
+
* not yet taken by the worker, or taken and still being sent.
|
|
232
|
+
*
|
|
233
|
+
* Once the worker takes the slot it holds the lock until the collector has
|
|
234
|
+
* answered (or the send has failed), and zeroes the length just before it
|
|
235
|
+
* lets go, on every path. So a non-zero length means the worker is not done
|
|
236
|
+
* with the last batch, which is what a shutdown waits on before writing
|
|
237
|
+
* another one or terminating the thread - unless the worker has said it is
|
|
238
|
+
* paused (`PAUSED_MESSAGE_PREFIX`), in which case it leaves the slot alone.
|
|
239
|
+
* Read without the lock: a stale answer only costs the caller one more look.
|
|
240
|
+
*/
|
|
241
|
+
hasBatchAwaitingWorker() {
|
|
242
|
+
return new DataView(this._sharedBuffer, 4, 4).getUint32(0) !== 0;
|
|
243
|
+
}
|
|
212
244
|
/**
|
|
213
245
|
* Takes the lock, or reports that someone else holds it.
|
|
214
246
|
*
|
|
@@ -328,8 +360,11 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
328
360
|
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
329
361
|
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
330
362
|
* views sort on it.
|
|
363
|
+
*
|
|
364
|
+
* `maxLogs` lifts the per-batch cap for the final flush, which sends the
|
|
365
|
+
* whole backlog in one batch rather than one round trip per 250 lines.
|
|
331
366
|
*/
|
|
332
|
-
drainPendingLogs() {
|
|
367
|
+
drainPendingLogs(maxLogs = MAX_LOGS_PER_TRANSACTION) {
|
|
333
368
|
if (this._pendingLogs.length === 0) {
|
|
334
369
|
return;
|
|
335
370
|
}
|
|
@@ -339,7 +374,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
339
374
|
if (!this._mainThreadBuffer.logs) {
|
|
340
375
|
this._mainThreadBuffer.logs = [];
|
|
341
376
|
}
|
|
342
|
-
const capacity =
|
|
377
|
+
const capacity = maxLogs - this._mainThreadBuffer.logs.length;
|
|
343
378
|
if (capacity <= 0) {
|
|
344
379
|
return;
|
|
345
380
|
}
|
|
@@ -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,25 +135,28 @@ 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
|
+
* What the last reply said the collector does with spans.
|
|
64
143
|
*
|
|
65
144
|
* Kept beside the log rather than read from the buffer so the notice fires
|
|
66
145
|
* once per transition: an account sits in this state for days, and a line
|
|
67
146
|
* per flush would bury the one thing worth reading.
|
|
68
147
|
*/
|
|
69
|
-
private
|
|
148
|
+
private reportedMode;
|
|
70
149
|
/**
|
|
71
150
|
* Stops sending trace trees the collector has told us it is throwing away,
|
|
72
|
-
* and says so once.
|
|
151
|
+
* and says so once - and again only when the reason changes.
|
|
73
152
|
*
|
|
74
153
|
* Said at `warn` rather than `debug`: the application is still being
|
|
75
|
-
* observed,
|
|
154
|
+
* observed, most waterfalls are not being kept, and a developer who finds
|
|
76
155
|
* that out by opening a trace and seeing nothing has been let down by an
|
|
77
|
-
* agent that knew.
|
|
156
|
+
* agent that knew. Each line says what is still kept, because the traces
|
|
157
|
+
* worth opening - server errors, slow requests, failed jobs - still are.
|
|
78
158
|
*/
|
|
79
|
-
private
|
|
159
|
+
private applyIngestMode;
|
|
80
160
|
handleError(error: Error): void;
|
|
81
161
|
flush(): void;
|
|
82
162
|
}
|