@nestjs/observe 0.0.1 → 0.1.0
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 +16 -0
- package/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.js +98 -1
- package/dist/agent/observe-agent.shared-buffer.d.ts +82 -0
- package/dist/agent/observe-agent.shared-buffer.js +94 -3
- package/dist/agent/observe-agent.worker.d.ts +28 -0
- package/dist/agent/observe-agent.worker.js +59 -5
- package/dist/custom-metrics/counter.d.ts +124 -0
- package/dist/custom-metrics/counter.js +93 -0
- package/dist/custom-metrics/gauge.d.ts +116 -0
- package/dist/custom-metrics/gauge.js +55 -0
- package/dist/custom-metrics/summary.d.ts +102 -0
- package/dist/custom-metrics/summary.js +100 -0
- package/dist/encoders/custom-metrics.encoder.js +18 -0
- package/dist/encoders/remap-keys.util.d.ts +11 -0
- package/dist/encoders/remap-keys.util.js +15 -0
- package/dist/encoders/trace.encoder.d.ts +7 -0
- package/dist/encoders/trace.encoder.js +12 -0
- package/dist/instrument/create-instance-decorator.instrument.d.ts +8 -0
- package/dist/instrument/create-instance-decorator.instrument.js +67 -0
- package/dist/interfaces/custom-metric.interface.d.ts +74 -0
- package/dist/interfaces/graphql.interfaces.d.ts +16 -0
- package/dist/interfaces/job-snapshot.interface.d.ts +70 -0
- package/dist/interfaces/node-runtime-metrics.interface.d.ts +5 -0
- package/dist/interfaces/observe-options.interface.d.ts +358 -0
- package/dist/interfaces/request-snapshot.interface.d.ts +62 -0
- package/dist/interfaces/trace-events.interfaces.d.ts +51 -0
- package/dist/interfaces/trace-span.interface.d.ts +29 -0
- package/dist/observe.module.js +29 -0
- package/dist/profiling/cpu-profiler.service.d.ts +65 -0
- package/dist/profiling/cpu-profiler.service.js +80 -0
- package/dist/profiling/fold-profile.util.d.ts +20 -0
- package/dist/profiling/fold-profile.util.js +0 -0
- package/dist/profiling/profile-uploader.d.ts +26 -0
- package/dist/profiling/profile-uploader.js +52 -0
- package/dist/profiling/span-slice-recorder.d.ts +51 -0
- package/dist/profiling/span-slice-recorder.js +77 -0
- package/dist/protocols/graphql-observe-agent.service.d.ts +128 -0
- package/dist/protocols/graphql-observe-agent.service.js +166 -0
- package/dist/protocols/graphql-operation-parser.d.ts +26 -0
- package/dist/protocols/graphql-operation-parser.js +66 -0
- package/dist/protocols/http-observe-agent.service.d.ts +19 -0
- package/dist/protocols/http-observe-agent.service.js +34 -0
- package/dist/protocols/queue-observe-agent.service.d.ts +8 -0
- package/dist/protocols/queue-observe-agent.service.js +32 -0
- package/dist/protocols/rpc-observe-agent.service.d.ts +7 -0
- package/dist/protocols/rpc-observe-agent.service.js +12 -0
- package/dist/services/logger-patcher.service.d.ts +4 -0
- package/dist/services/logger-patcher.service.js +13 -1
- package/dist/services/node-runtime-metrics.service.js +24 -8
- package/dist/services/operation-trace.registry.d.ts +56 -1
- package/dist/services/operation-trace.registry.js +145 -6
- package/dist/services/stdout-forwarder.service.d.ts +19 -0
- package/dist/services/stdout-forwarder.service.js +62 -0
- package/dist/services/trace-sampler.service.d.ts +6 -0
- package/dist/services/trace-sampler.service.js +3 -3
- package/dist/services/tracer.service.d.ts +91 -0
- package/dist/services/tracer.service.js +56 -1
- package/dist/trace-span.delegate.d.ts +11 -0
- package/dist/trace-span.delegate.js +11 -0
- package/dist/types/path-value.type.d.ts +4 -0
- package/dist/utils/default-trace-id-generator.util.js +11 -0
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +37 -0
- package/dist/utils/log-redactor.js +65 -0
- package/dist/utils/redact-url-query.d.ts +17 -0
- package/dist/utils/redact-url-query.js +38 -0
- package/dist/utils/source-context.util.d.ts +22 -0
- package/dist/utils/source-context.util.js +60 -0
- package/dist/utils/source-map-resolver.util.d.ts +13 -0
- package/dist/utils/source-map-resolver.util.js +23 -0
- package/package.json +1 -1
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
export const detachedObserveWorker = () => {
|
|
2
|
+
// This function body is stringified via .toString() and executed as a
|
|
3
|
+
// standalone worker script, so it can't use static ES imports and must
|
|
4
|
+
// require() its dependencies at runtime instead.
|
|
5
|
+
/* eslint-disable @typescript-eslint/no-require-imports */
|
|
2
6
|
const { parentPort, workerData } = require("worker_threads");
|
|
3
7
|
const zlib = require("zlib");
|
|
8
|
+
/* eslint-enable @typescript-eslint/no-require-imports */
|
|
9
|
+
// `workerData` carries the shared buffer plus the collector config: the
|
|
10
|
+
// stringified function has no access to this module's configuration, so
|
|
11
|
+
// everything it needs must arrive here.
|
|
4
12
|
const { sharedBuffer, config } = workerData;
|
|
5
13
|
const buffer = new Uint8Array(sharedBuffer);
|
|
6
14
|
const lock = new Int32Array(sharedBuffer, 0, 1);
|
|
@@ -11,15 +19,65 @@ export const detachedObserveWorker = () => {
|
|
|
11
19
|
"Content-Type": "application/json",
|
|
12
20
|
"Content-Encoding": "gzip",
|
|
13
21
|
};
|
|
22
|
+
// Omitted rather than sent empty when unconfigured: a collector in
|
|
23
|
+
// placeholder mode accepts an unauthenticated batch, and blank credentials
|
|
24
|
+
// would be a 401 instead.
|
|
14
25
|
if (config.appKey && config.appSecret) {
|
|
15
26
|
headers["x-api-key"] = config.appKey;
|
|
16
27
|
headers["x-api-secret"] = config.appSecret;
|
|
17
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* Whether the collector has already refused these credentials.
|
|
31
|
+
*
|
|
32
|
+
* Rejected credentials do not recover on their own: the values arrive in the
|
|
33
|
+
* environment and are read once at start-up, so nothing short of a restart
|
|
34
|
+
* can change the answer. Reporting it on every flush therefore adds no
|
|
35
|
+
* information and costs a line every few seconds - 535 identical errors in
|
|
36
|
+
* half an hour, in the run that prompted this - which buries whatever else
|
|
37
|
+
* the service was trying to say.
|
|
38
|
+
*
|
|
39
|
+
* Said once, in full, and then only counted. Flushing continues either way:
|
|
40
|
+
* the batch is dropped rather than queued, so a fixed deployment starts
|
|
41
|
+
* reporting again without anything to drain.
|
|
42
|
+
*/
|
|
18
43
|
let authRejections = 0;
|
|
44
|
+
/**
|
|
45
|
+
* How many rejected batches between reminders. At the default five-second
|
|
46
|
+
* flush this is roughly hourly - often enough that a long-running process
|
|
47
|
+
* silently dropping telemetry is still visible in a day's logs, rare enough
|
|
48
|
+
* that it never competes with anything.
|
|
49
|
+
*/
|
|
19
50
|
const AUTH_REJECTION_REPORT_EVERY = 720;
|
|
51
|
+
/**
|
|
52
|
+
* How long to block waiting for the main thread to release the lock, and how
|
|
53
|
+
* long to sleep when the buffer holds nothing.
|
|
54
|
+
*
|
|
55
|
+
* Both exist to keep this thread off the CPU while idle. The wait carries a
|
|
56
|
+
* timeout rather than blocking forever so a notification that arrives between
|
|
57
|
+
* the load and the wait cannot park this thread indefinitely; the sleep is
|
|
58
|
+
* what stops an empty buffer becoming a spin loop, and its length only adds
|
|
59
|
+
* latency to a flush the main thread performs on a timer anyway.
|
|
60
|
+
*/
|
|
20
61
|
const LOCK_WAIT_MS = 100;
|
|
21
62
|
const IDLE_SLEEP_MS = 50;
|
|
63
|
+
/**
|
|
64
|
+
* Takes the lock if it is free.
|
|
65
|
+
*
|
|
66
|
+
* One `compareExchange` rather than a read followed by a write: the main
|
|
67
|
+
* thread contends for this same word, and between a load saying the lock was
|
|
68
|
+
* free and a store taking it, the other side can take it too - leaving both
|
|
69
|
+
* threads believing they hold it, one writing the buffer while the other
|
|
70
|
+
* reads it. `compareExchange` stores only if the word is still 0 and returns
|
|
71
|
+
* what was there, so the check and the take are one indivisible step.
|
|
72
|
+
*/
|
|
22
73
|
const acquireLock = () => Atomics.compareExchange(lock, 0, 0, 1) === 0;
|
|
74
|
+
/**
|
|
75
|
+
* Blocks while the main thread holds the lock.
|
|
76
|
+
*
|
|
77
|
+
* `Atomics.wait` blocks while the word *equals* the expected value, so the
|
|
78
|
+
* expected value here is 1 - locked - and the load first avoids the syscall
|
|
79
|
+
* entirely when the lock is already free.
|
|
80
|
+
*/
|
|
23
81
|
const waitWhileLocked = () => {
|
|
24
82
|
if (Atomics.load(lock, 0) !== 0) {
|
|
25
83
|
Atomics.wait(lock, 0, 1, LOCK_WAIT_MS);
|
|
@@ -29,18 +87,29 @@ export const detachedObserveWorker = () => {
|
|
|
29
87
|
Atomics.store(lock, 0, 0);
|
|
30
88
|
Atomics.notify(lock, 0);
|
|
31
89
|
};
|
|
32
|
-
const clearBuffer = () => view.setUint32(0, 0);
|
|
90
|
+
const clearBuffer = () => view.setUint32(0, 0); // Reset length to 0
|
|
33
91
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
92
|
+
/**
|
|
93
|
+
* Sends one batch, if there is one to send.
|
|
94
|
+
*
|
|
95
|
+
* Returns whether anything was sent, so the loop below knows to come back
|
|
96
|
+
* immediately or to sleep first.
|
|
97
|
+
*/
|
|
34
98
|
const sendInstrumentationJsonData = async () => {
|
|
35
99
|
waitWhileLocked();
|
|
36
100
|
if (!acquireLock()) {
|
|
101
|
+
// Lost the race to the main thread, which is flushing. Nothing to report
|
|
102
|
+
// - this is the ordinary contention the lock exists for - so the loop
|
|
103
|
+
// simply comes back to it.
|
|
37
104
|
return false;
|
|
38
105
|
}
|
|
39
106
|
try {
|
|
40
107
|
const jsonLength = view.getUint32(0);
|
|
41
108
|
if (jsonLength === 0) {
|
|
109
|
+
// `finally` releases the lock on this path like every other.
|
|
42
110
|
return false;
|
|
43
111
|
}
|
|
112
|
+
// Skip the first 4 bytes (lock) and the next 4 bytes (length)
|
|
44
113
|
const jsonBytes = buffer.slice(8, 8 + jsonLength);
|
|
45
114
|
const jsonStr = decoder.decode(jsonBytes);
|
|
46
115
|
const compressed = await new Promise((resolve, reject) => zlib.gzip(jsonStr, (err, compressed) => {
|
|
@@ -59,16 +128,26 @@ export const detachedObserveWorker = () => {
|
|
|
59
128
|
if (!response.ok) {
|
|
60
129
|
if (response.status === 401 || response.status === 403) {
|
|
61
130
|
authRejections += 1;
|
|
131
|
+
// Said plainly, and once. The batch is well-formed and the
|
|
132
|
+
// credentials are not accepted for this application; left as a
|
|
133
|
+
// generic transport failure this reads as a network problem, and the
|
|
134
|
+
// fix - appKey and appSecret - is nowhere in the message.
|
|
62
135
|
if (authRejections === 1) {
|
|
63
136
|
parentPort.postMessage(`Error: Telemetry rejected (${response.status}). Check that appKey and appSecret are valid; ` +
|
|
64
137
|
`the application is taken from the key. Credentials are read once at start-up, so this ` +
|
|
65
138
|
`will not recover without a restart - further rejections are counted, not logged.`);
|
|
66
139
|
}
|
|
67
140
|
else if (authRejections % AUTH_REJECTION_REPORT_EVERY === 0) {
|
|
141
|
+
// A periodic reminder, rare enough not to bury anything. Without
|
|
142
|
+
// it a process that has been dropping telemetry for a day looks
|
|
143
|
+
// exactly like one that is healthy.
|
|
68
144
|
parentPort.postMessage(`Error: Telemetry still rejected (${response.status}); ${authRejections} batches dropped since start-up.`);
|
|
69
145
|
}
|
|
70
146
|
return true;
|
|
71
147
|
}
|
|
148
|
+
// Read as text, defensively: an error body is not guaranteed to be
|
|
149
|
+
// JSON, and a parse failure here must not fall through to the catch
|
|
150
|
+
// below and report a reachable collector as unreachable.
|
|
72
151
|
const errorBody = await response.text().catch(() => "");
|
|
73
152
|
parentPort.postMessage(`Error: Failed to send data. ${response.statusText} (${response.status})` +
|
|
74
153
|
(errorBody ? ` - ${errorBody.slice(0, 500)}` : ""));
|
|
@@ -78,12 +157,22 @@ export const detachedObserveWorker = () => {
|
|
|
78
157
|
return true;
|
|
79
158
|
}
|
|
80
159
|
catch (err) {
|
|
160
|
+
// `fetch` reports every transport failure as the same opaque "fetch
|
|
161
|
+
// failed", and puts the reason - ECONNREFUSED, ENOTFOUND, a TLS error -
|
|
162
|
+
// on `err.cause`. Reporting only `err.message` therefore tells the
|
|
163
|
+
// operator nothing: not what went wrong, and not which URL was tried.
|
|
164
|
+
// The 401/403 branch above already names what to check; this does the
|
|
165
|
+
// same for the case where the collector was never reached.
|
|
81
166
|
const cause = err
|
|
82
167
|
?.cause;
|
|
83
168
|
const reason = cause?.code ?? cause?.message;
|
|
84
169
|
parentPort.postMessage(`Error: Could not reach the collector at ${telemetryUrl}` +
|
|
85
170
|
(reason ? ` (${reason})` : "") +
|
|
86
171
|
`. Check that it is running and that \`endpoint\` points at it.`);
|
|
172
|
+
// The batch is discarded rather than retried - `clearBuffer` below -
|
|
173
|
+
// which is the right call for a fixed-size buffer the application is
|
|
174
|
+
// still writing into: holding it for a retry would block every batch
|
|
175
|
+
// behind an unreachable collector.
|
|
87
176
|
return true;
|
|
88
177
|
}
|
|
89
178
|
finally {
|
|
@@ -91,6 +180,14 @@ export const detachedObserveWorker = () => {
|
|
|
91
180
|
releaseLock();
|
|
92
181
|
}
|
|
93
182
|
};
|
|
183
|
+
/**
|
|
184
|
+
* The worker's main loop.
|
|
185
|
+
*
|
|
186
|
+
* A flat loop, so the worker's liveness never depends on a recursive call.
|
|
187
|
+
* Sleeping when there was nothing to send is what keeps an idle process off
|
|
188
|
+
* the CPU: without it an empty buffer would be acquired, found empty and
|
|
189
|
+
* released as fast as the thread can go.
|
|
190
|
+
*/
|
|
94
191
|
const run = async () => {
|
|
95
192
|
parentPort.postMessage("Ready to process instrumentation data");
|
|
96
193
|
for (;;) {
|
|
@@ -3,13 +3,43 @@ import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
|
|
|
3
3
|
import { NodeRuntimeMetrics } from "../interfaces/node-runtime-metrics.interface.js";
|
|
4
4
|
import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
|
|
5
5
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
|
|
6
|
+
/**
|
|
7
|
+
* A log line waiting to be shipped.
|
|
8
|
+
*
|
|
9
|
+
* `level`, `context` and `attributes` are optional because they only exist for
|
|
10
|
+
* lines the parser could classify - raw stdout that matches no known format is
|
|
11
|
+
* still forwarded, carrying just its text.
|
|
12
|
+
*/
|
|
6
13
|
interface BufferedLogEntry {
|
|
14
|
+
/**
|
|
15
|
+
* Timestamp of the log entry in milliseconds since epoch.
|
|
16
|
+
*/
|
|
7
17
|
timestamp: number;
|
|
18
|
+
/**
|
|
19
|
+
* Trace the line was emitted under, when one could be resolved.
|
|
20
|
+
*/
|
|
8
21
|
traceId?: string;
|
|
22
|
+
/**
|
|
23
|
+
* Span the line was written inside, when one could be resolved. Only ever set
|
|
24
|
+
* together with `traceId`, and only when that trace is the one the async
|
|
25
|
+
* store is currently in - see StdoutForwarderService#toLogEntry.
|
|
26
|
+
*/
|
|
9
27
|
spanId?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Severity, lowercased to match the API's LogLevel values.
|
|
30
|
+
*/
|
|
10
31
|
level?: string;
|
|
32
|
+
/**
|
|
33
|
+
* Nest logger context - the emitting class name, usually.
|
|
34
|
+
*/
|
|
11
35
|
context?: string;
|
|
36
|
+
/**
|
|
37
|
+
* Fields a structured log carried beyond the modelled ones.
|
|
38
|
+
*/
|
|
12
39
|
attributes?: Record<string, unknown>;
|
|
40
|
+
/**
|
|
41
|
+
* Text content of the log entry.
|
|
42
|
+
*/
|
|
13
43
|
text: string;
|
|
14
44
|
}
|
|
15
45
|
export declare class ObserveAgentSharedBuffer {
|
|
@@ -20,7 +50,17 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
20
50
|
private readonly encoder;
|
|
21
51
|
private readonly logger;
|
|
22
52
|
private _mainThreadBuffer;
|
|
53
|
+
/**
|
|
54
|
+
* Log lines that did not fit the current batch, oldest first. Survives
|
|
55
|
+
* `resetMainThreadBuffer` on purpose - it is the queue the batches are drawn
|
|
56
|
+
* from, not part of any one of them.
|
|
57
|
+
*/
|
|
23
58
|
private readonly _pendingLogs;
|
|
59
|
+
/**
|
|
60
|
+
* Metrics reporting a per-window quantity that is sitting in the current
|
|
61
|
+
* buffer - a counter's increase, a summary's distribution - held so their
|
|
62
|
+
* window can be closed once the payload is actually written.
|
|
63
|
+
*/
|
|
24
64
|
private readonly _awaitingFlushAck;
|
|
25
65
|
get sharedBuffer(): SharedArrayBuffer;
|
|
26
66
|
constructor(options: ObserveModuleOptionsWithDefaults);
|
|
@@ -28,11 +68,53 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
28
68
|
insertJobSnapshot(jobSnapshot: JobSnapshot): void;
|
|
29
69
|
isBufferLocked(): boolean;
|
|
30
70
|
isBufferEmpty(): boolean;
|
|
71
|
+
/**
|
|
72
|
+
* Takes the lock, or reports that someone else holds it.
|
|
73
|
+
*
|
|
74
|
+
* One `compareExchange` rather than a read followed by a write: the worker
|
|
75
|
+
* thread contends for this same word, so between a `load` saying the lock was
|
|
76
|
+
* free and a `store` taking it, the worker can take it too - and both sides
|
|
77
|
+
* then believe they hold it, one writing the buffer while the other reads it.
|
|
78
|
+
* `compareExchange` only stores if the word is still what we read, and
|
|
79
|
+
* returns what was there, so "it was free and it is now ours" is a single
|
|
80
|
+
* indivisible step.
|
|
81
|
+
*/
|
|
31
82
|
acquireLock(): boolean;
|
|
32
83
|
releaseLock(): void;
|
|
33
84
|
addNodeRuntimeMetrics(runtimeMetrics: NodeRuntimeMetrics | undefined): void;
|
|
34
85
|
upsertCustomMetric(metric: Counter<any> | Gauge<any> | Summary<any>): void;
|
|
86
|
+
/**
|
|
87
|
+
* Buffers log entries, filling the current batch first and holding the rest
|
|
88
|
+
* back for later batches. Oversized lines are truncated on the way in.
|
|
89
|
+
*
|
|
90
|
+
* The overflow is deferred rather than discarded: a burst that exceeds one
|
|
91
|
+
* batch is the most interesting thing the logs will ever carry. Only once
|
|
92
|
+
* the backlog is also full does anything get lost.
|
|
93
|
+
*
|
|
94
|
+
* When both are full the *newest* lines are dropped. During a burst the
|
|
95
|
+
* opening lines are usually the ones that explain it; losing the tail of a
|
|
96
|
+
* retry storm costs less than losing its first cause.
|
|
97
|
+
*
|
|
98
|
+
* Unlike the other insert methods this one stays silent when it drops. It is
|
|
99
|
+
* called from the patched `process.stdout.write`, so a debug line here would
|
|
100
|
+
* write to stdout, re-enter `pushLogs`, drop again, and log again - the cap
|
|
101
|
+
* would turn every dropped entry into unbounded recursion.
|
|
102
|
+
*/
|
|
35
103
|
pushLogs(logs: Array<BufferedLogEntry>): void;
|
|
104
|
+
/**
|
|
105
|
+
* Tops the outgoing batch up from the backlog.
|
|
106
|
+
*
|
|
107
|
+
* Called by the worker immediately before it decides whether there is
|
|
108
|
+
* anything worth flushing - which is what stops a backlog stranding itself. A
|
|
109
|
+
* burst leaves lines pending, the process then goes quiet, and with nothing
|
|
110
|
+
* new arriving `pushLogs` would never run again to move them; the buffer
|
|
111
|
+
* would read as empty and those lines would sit there until shutdown.
|
|
112
|
+
*
|
|
113
|
+
* Drained lines are appended after whatever the batch already holds, so a
|
|
114
|
+
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
115
|
+
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
116
|
+
* views sort on it.
|
|
117
|
+
*/
|
|
36
118
|
drainPendingLogs(): void;
|
|
37
119
|
private truncateLogText;
|
|
38
120
|
encodeAndWrite(): void;
|
|
@@ -18,11 +18,37 @@ import { JobSnapshotEncoder, } from "../encoders/job-snapshot.encoder.js";
|
|
|
18
18
|
import { RequestSnapshotEncoder, } from "../encoders/request-snapshot.encoder.js";
|
|
19
19
|
import { RuntimeMetricsEncoder, } from "../encoders/runtime-metrics.encoder.js";
|
|
20
20
|
import { OBSERVE_OPTIONS } from "../observe.constants.js";
|
|
21
|
-
const SHARED_BUFFER_SIZE = 1024 * 1024 * 16;
|
|
21
|
+
const SHARED_BUFFER_SIZE = 1024 * 1024 * 16; // 16 MB
|
|
22
22
|
const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
|
|
23
|
+
/**
|
|
24
|
+
* Caps on the log portion of a batch.
|
|
25
|
+
*
|
|
26
|
+
* Logs are the only unbounded input here - snapshots are gated by
|
|
27
|
+
* `maxTracesPerBatch`, but a chatty service (or one stuck in a retry loop)
|
|
28
|
+
* produces log lines with no natural ceiling. Left uncapped they grow the
|
|
29
|
+
* payload past `SHARED_BUFFER_SIZE`, and `encodeAndWrite` then throws for the
|
|
30
|
+
* whole batch, so noisy logging silently costs you the traces and metrics too.
|
|
31
|
+
*
|
|
32
|
+
* Both limits are needed: the count bounds ordinary chatter, and the per-entry
|
|
33
|
+
* length bounds the single pathological line - a serialised payload dump or a
|
|
34
|
+
* deep stack trace can be megabytes on its own.
|
|
35
|
+
*/
|
|
23
36
|
const MAX_LOGS_PER_TRANSACTION = 250;
|
|
24
|
-
const MAX_LOG_ENTRY_LENGTH = 4 * 1024;
|
|
37
|
+
const MAX_LOG_ENTRY_LENGTH = 4 * 1024; // 4 KB
|
|
25
38
|
const TRUNCATION_SUFFIX = "... [truncated by observe]";
|
|
39
|
+
/**
|
|
40
|
+
* Log lines held back for a later batch when the current one is full.
|
|
41
|
+
*
|
|
42
|
+
* The per-batch cap bounds the *request*; this bounds the *process*. Together
|
|
43
|
+
* they let a batch stay small - at most 250 lines - while up to 2250 can be in
|
|
44
|
+
* flight overall, so a burst larger than one batch spills here instead of
|
|
45
|
+
* being thrown away.
|
|
46
|
+
*
|
|
47
|
+
* Bounded because this is the one input with no natural limit. A process stuck
|
|
48
|
+
* in a retry loop must eventually lose lines rather than grow this array until
|
|
49
|
+
* the heap gives out - dropping telemetry is recoverable, taking the host
|
|
50
|
+
* process down with it is not.
|
|
51
|
+
*/
|
|
26
52
|
const MAX_PENDING_LOGS = 2000;
|
|
27
53
|
let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSharedBuffer {
|
|
28
54
|
options;
|
|
@@ -32,7 +58,17 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
32
58
|
encoder = new TextEncoder();
|
|
33
59
|
logger = new Logger(ObserveAgentSharedBuffer_1.name);
|
|
34
60
|
_mainThreadBuffer = null;
|
|
61
|
+
/**
|
|
62
|
+
* Log lines that did not fit the current batch, oldest first. Survives
|
|
63
|
+
* `resetMainThreadBuffer` on purpose - it is the queue the batches are drawn
|
|
64
|
+
* from, not part of any one of them.
|
|
65
|
+
*/
|
|
35
66
|
_pendingLogs = [];
|
|
67
|
+
/**
|
|
68
|
+
* Metrics reporting a per-window quantity that is sitting in the current
|
|
69
|
+
* buffer - a counter's increase, a summary's distribution - held so their
|
|
70
|
+
* window can be closed once the payload is actually written.
|
|
71
|
+
*/
|
|
36
72
|
_awaitingFlushAck = new Set();
|
|
37
73
|
get sharedBuffer() {
|
|
38
74
|
return this._sharedBuffer;
|
|
@@ -61,6 +97,10 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
61
97
|
if (!this._mainThreadBuffer.jobs) {
|
|
62
98
|
this._mainThreadBuffer.jobs = [];
|
|
63
99
|
}
|
|
100
|
+
// Same cap as request snapshots, for the same reason: the buffer only
|
|
101
|
+
// empties when a flush succeeds, so without a ceiling a stalled flush on
|
|
102
|
+
// the worker service - the process that sees every queue job - grows this
|
|
103
|
+
// array for as long as the stall lasts.
|
|
64
104
|
const maxPerBatch = this.options.maxTracesPerBatch ?? DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION;
|
|
65
105
|
if (this._mainThreadBuffer.jobs.length >= maxPerBatch) {
|
|
66
106
|
if (this.options.debug) {
|
|
@@ -77,6 +117,17 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
77
117
|
isBufferEmpty() {
|
|
78
118
|
return !this._mainThreadBuffer;
|
|
79
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* Takes the lock, or reports that someone else holds it.
|
|
122
|
+
*
|
|
123
|
+
* One `compareExchange` rather than a read followed by a write: the worker
|
|
124
|
+
* thread contends for this same word, so between a `load` saying the lock was
|
|
125
|
+
* free and a `store` taking it, the worker can take it too - and both sides
|
|
126
|
+
* then believe they hold it, one writing the buffer while the other reads it.
|
|
127
|
+
* `compareExchange` only stores if the word is still what we read, and
|
|
128
|
+
* returns what was there, so "it was free and it is now ours" is a single
|
|
129
|
+
* indivisible step.
|
|
130
|
+
*/
|
|
80
131
|
acquireLock() {
|
|
81
132
|
if (Atomics.compareExchange(this.lock, 0, 0, 1) !== 0) {
|
|
82
133
|
return false;
|
|
@@ -88,7 +139,7 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
88
139
|
}
|
|
89
140
|
releaseLock() {
|
|
90
141
|
Atomics.store(this.lock, 0, 0);
|
|
91
|
-
Atomics.notify(this.lock, 0);
|
|
142
|
+
Atomics.notify(this.lock, 0); // Notify any waiting threads
|
|
92
143
|
if (this.options.debug) {
|
|
93
144
|
this.logger.debug("Shared buffer lock released.");
|
|
94
145
|
}
|
|
@@ -124,6 +175,23 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
124
175
|
this._mainThreadBuffer.custom.push(CustomMetricsEncoder.encode(metric));
|
|
125
176
|
}
|
|
126
177
|
}
|
|
178
|
+
/**
|
|
179
|
+
* Buffers log entries, filling the current batch first and holding the rest
|
|
180
|
+
* back for later batches. Oversized lines are truncated on the way in.
|
|
181
|
+
*
|
|
182
|
+
* The overflow is deferred rather than discarded: a burst that exceeds one
|
|
183
|
+
* batch is the most interesting thing the logs will ever carry. Only once
|
|
184
|
+
* the backlog is also full does anything get lost.
|
|
185
|
+
*
|
|
186
|
+
* When both are full the *newest* lines are dropped. During a burst the
|
|
187
|
+
* opening lines are usually the ones that explain it; losing the tail of a
|
|
188
|
+
* retry storm costs less than losing its first cause.
|
|
189
|
+
*
|
|
190
|
+
* Unlike the other insert methods this one stays silent when it drops. It is
|
|
191
|
+
* called from the patched `process.stdout.write`, so a debug line here would
|
|
192
|
+
* write to stdout, re-enter `pushLogs`, drop again, and log again - the cap
|
|
193
|
+
* would turn every dropped entry into unbounded recursion.
|
|
194
|
+
*/
|
|
127
195
|
pushLogs(logs) {
|
|
128
196
|
if (!this._mainThreadBuffer) {
|
|
129
197
|
this._mainThreadBuffer = this.createEmptyPayload();
|
|
@@ -147,6 +215,20 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
147
215
|
return;
|
|
148
216
|
}
|
|
149
217
|
}
|
|
218
|
+
/**
|
|
219
|
+
* Tops the outgoing batch up from the backlog.
|
|
220
|
+
*
|
|
221
|
+
* Called by the worker immediately before it decides whether there is
|
|
222
|
+
* anything worth flushing - which is what stops a backlog stranding itself. A
|
|
223
|
+
* burst leaves lines pending, the process then goes quiet, and with nothing
|
|
224
|
+
* new arriving `pushLogs` would never run again to move them; the buffer
|
|
225
|
+
* would read as empty and those lines would sit there until shutdown.
|
|
226
|
+
*
|
|
227
|
+
* Drained lines are appended after whatever the batch already holds, so a
|
|
228
|
+
* batch is not ordered by time. Nothing downstream depends on that: every
|
|
229
|
+
* entry carries its own timestamp, the recorder inserts by it, and the log
|
|
230
|
+
* views sort on it.
|
|
231
|
+
*/
|
|
150
232
|
drainPendingLogs() {
|
|
151
233
|
if (this._pendingLogs.length === 0) {
|
|
152
234
|
return;
|
|
@@ -178,11 +260,20 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
178
260
|
const jsonBytes = this.encoder.encode(json);
|
|
179
261
|
const jsonLength = jsonBytes.length;
|
|
180
262
|
if (jsonLength > SHARED_BUFFER_SIZE - 8) {
|
|
263
|
+
// 8 bytes reserved for the lock and length
|
|
181
264
|
throw new Error("Payload too large for shared buffer");
|
|
182
265
|
}
|
|
266
|
+
// Offset 4 for the lock value
|
|
183
267
|
const view = new DataView(this._sharedBuffer, 4, 4);
|
|
268
|
+
// Store the length of the JSON data
|
|
184
269
|
view.setUint32(0, jsonLength);
|
|
270
|
+
// Copy the JSON bytes into the shared buffer
|
|
185
271
|
this.sharedBytes.set(jsonBytes, 8);
|
|
272
|
+
// Only now is the payload genuinely handed off, so this is the point at
|
|
273
|
+
// which a counter's reported increase, or a summary's window of
|
|
274
|
+
// observations, can be considered delivered. Doing it any earlier (or in the
|
|
275
|
+
// caller's finally block, which also runs when the write throws) would
|
|
276
|
+
// silently drop a window's worth of measurements.
|
|
186
277
|
for (const metric of this._awaitingFlushAck) {
|
|
187
278
|
metric.markFlushed();
|
|
188
279
|
}
|
|
@@ -13,10 +13,38 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
13
13
|
private cpuProfiler;
|
|
14
14
|
constructor(observeAgentSharedBuffer: ObserveAgentSharedBuffer, options: ObserveModuleOptionsWithDefaults, nodeRuntimeMetricsService: NodeRuntimeMetricsService);
|
|
15
15
|
onModuleInit(): void;
|
|
16
|
+
/**
|
|
17
|
+
* Starts the runtime-metrics collector: memory, CPU, GC, event loop.
|
|
18
|
+
*/
|
|
16
19
|
private startRuntimeMetrics;
|
|
20
|
+
/**
|
|
21
|
+
* Starts the sampling profiler, if the application asked for it.
|
|
22
|
+
*
|
|
23
|
+
* Distinct from `runtimeMetrics`, which gauges how loaded the process is.
|
|
24
|
+
* This one samples stacks to say which code was running, and it is the only
|
|
25
|
+
* one of the two with a cost on the hot path - so it stays off unless asked
|
|
26
|
+
* for, rather than following any existing flag.
|
|
27
|
+
*
|
|
28
|
+
* Currently unreachable: `profiling` is commented out of `ObserveOptions` and
|
|
29
|
+
* the call in `onModuleInit` is commented out with it. The body is kept
|
|
30
|
+
* compiling rather than deleted, so restoring the feature is uncommenting two
|
|
31
|
+
* lines instead of recovering this from history. The local type below is what
|
|
32
|
+
* `ObserveOptions.profiling` declared, and is the thing to delete when the
|
|
33
|
+
* real option comes back.
|
|
34
|
+
*/
|
|
17
35
|
private startContinuousProfiling;
|
|
18
36
|
onApplicationShutdown(): Promise<void>;
|
|
19
37
|
private get endpoint();
|
|
38
|
+
/**
|
|
39
|
+
* Says out loud when credentials are about to cross the network unencrypted.
|
|
40
|
+
*
|
|
41
|
+
* `endpoint` is free-form and both halves of the agent attach `x-api-key` /
|
|
42
|
+
* `x-api-secret` to every request against it. Over `http://` to anything but
|
|
43
|
+
* the local machine, those headers are readable by every hop in between -
|
|
44
|
+
* a misconfiguration worth one warning, not a refusal: private networks and
|
|
45
|
+
* tunnels exist, and an agent that stops reporting over a scheme choice
|
|
46
|
+
* punishes the operator harder than the mistake does.
|
|
47
|
+
*/
|
|
20
48
|
private warnIfCredentialsSentInClear;
|
|
21
49
|
initializeWorker(): void;
|
|
22
50
|
handleMessage(msg: string): void;
|
|
@@ -21,16 +21,21 @@ import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-sl
|
|
|
21
21
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
22
22
|
import { detachedObserveWorker } from "./detached-observe-worker.js";
|
|
23
23
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
24
|
-
const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000;
|
|
25
|
-
const MIN_RUNTIME_METRICS_INTERVAL = 30000;
|
|
26
|
-
const DEFAULT_FLUSH_INTERVAL = 5000;
|
|
24
|
+
const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
|
|
25
|
+
const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
|
|
26
|
+
const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
|
|
27
|
+
/**
|
|
28
|
+
* Where signals are posted when `endpoint` is not configured.
|
|
29
|
+
*/
|
|
27
30
|
const DEFAULT_COLLECTOR_ENDPOINT = process.env.OBSERVE_ENDPOINT ?? "https://observe-api.nestjs.com";
|
|
28
|
-
const MIN_FLUSH_INTERVAL = 1000;
|
|
31
|
+
const MIN_FLUSH_INTERVAL = 1000; // 1 second
|
|
29
32
|
let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
30
33
|
observeAgentSharedBuffer;
|
|
31
34
|
options;
|
|
32
35
|
nodeRuntimeMetricsService;
|
|
33
36
|
logger = new Logger(ObserveAgentWorker_1.name);
|
|
37
|
+
// Null before `initializeWorker` and again after termination, which is what
|
|
38
|
+
// the shutdown path below checks for.
|
|
34
39
|
worker = null;
|
|
35
40
|
flushInterval;
|
|
36
41
|
runtimeMetricsInterval = null;
|
|
@@ -49,7 +54,16 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
49
54
|
}
|
|
50
55
|
this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
|
|
51
56
|
this.startRuntimeMetrics();
|
|
57
|
+
// Continuous profiling is shelved: a flame graph asks more of a reader than
|
|
58
|
+
// most services' owners want to give it, and the signal is not worth the
|
|
59
|
+
// sampling cost until there is a UI that makes it legible. The
|
|
60
|
+
// implementation is kept and tested - restore this call and re-register the
|
|
61
|
+
// /profiles routes to bring it back.
|
|
62
|
+
// this.startContinuousProfiling();
|
|
52
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* Starts the runtime-metrics collector: memory, CPU, GC, event loop.
|
|
66
|
+
*/
|
|
53
67
|
startRuntimeMetrics() {
|
|
54
68
|
if (!this.options.runtimeMetrics) {
|
|
55
69
|
return;
|
|
@@ -66,6 +80,21 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
66
80
|
this.logger.debug(`Collecting runtime metrics every ${interval}ms.`);
|
|
67
81
|
}
|
|
68
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Starts the sampling profiler, if the application asked for it.
|
|
85
|
+
*
|
|
86
|
+
* Distinct from `runtimeMetrics`, which gauges how loaded the process is.
|
|
87
|
+
* This one samples stacks to say which code was running, and it is the only
|
|
88
|
+
* one of the two with a cost on the hot path - so it stays off unless asked
|
|
89
|
+
* for, rather than following any existing flag.
|
|
90
|
+
*
|
|
91
|
+
* Currently unreachable: `profiling` is commented out of `ObserveOptions` and
|
|
92
|
+
* the call in `onModuleInit` is commented out with it. The body is kept
|
|
93
|
+
* compiling rather than deleted, so restoring the feature is uncommenting two
|
|
94
|
+
* lines instead of recovering this from history. The local type below is what
|
|
95
|
+
* `ObserveOptions.profiling` declared, and is the thing to delete when the
|
|
96
|
+
* real option comes back.
|
|
97
|
+
*/
|
|
69
98
|
startContinuousProfiling() {
|
|
70
99
|
const profiling = this.options.profiling;
|
|
71
100
|
if (!profiling?.enabled) {
|
|
@@ -76,6 +105,8 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
76
105
|
endpoint: this.endpoint,
|
|
77
106
|
appKey: this.options.appKey,
|
|
78
107
|
appSecret: this.options.appSecret,
|
|
108
|
+
// One node is one process. Two replicas of a service must not merge into
|
|
109
|
+
// a single tree, so the identity has to distinguish them.
|
|
79
110
|
serviceNode: `${hostname()}:${process.pid}`,
|
|
80
111
|
onError: (message) => this.logger.warn(message),
|
|
81
112
|
});
|
|
@@ -86,10 +117,15 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
86
117
|
maxCpuPercent: profiling.maxCpuPercent,
|
|
87
118
|
onWindow: (window, sampleRateHz) => uploader.enqueue(window, sampleRateHz),
|
|
88
119
|
onDisabled: (reason) => {
|
|
120
|
+
// Said out loud rather than degraded quietly: the customer has asked
|
|
121
|
+
// for profiling and is no longer getting it.
|
|
89
122
|
this.logger.warn(`Continuous profiling stopped - ${reason}`);
|
|
90
123
|
setActiveSliceRecorder(null);
|
|
91
124
|
},
|
|
92
125
|
});
|
|
126
|
+
// Only now does the instrumentation start recording span slices. With
|
|
127
|
+
// profiling off this stays null and every span boundary costs one null
|
|
128
|
+
// check.
|
|
93
129
|
setActiveSliceRecorder(slices);
|
|
94
130
|
void this.cpuProfiler.start().catch((err) => {
|
|
95
131
|
this.logger.warn(`Continuous profiling failed to start: ${String(err)}`);
|
|
@@ -121,6 +157,16 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
121
157
|
get endpoint() {
|
|
122
158
|
return this.options.endpoint ?? DEFAULT_COLLECTOR_ENDPOINT;
|
|
123
159
|
}
|
|
160
|
+
/**
|
|
161
|
+
* Says out loud when credentials are about to cross the network unencrypted.
|
|
162
|
+
*
|
|
163
|
+
* `endpoint` is free-form and both halves of the agent attach `x-api-key` /
|
|
164
|
+
* `x-api-secret` to every request against it. Over `http://` to anything but
|
|
165
|
+
* the local machine, those headers are readable by every hop in between -
|
|
166
|
+
* a misconfiguration worth one warning, not a refusal: private networks and
|
|
167
|
+
* tunnels exist, and an agent that stops reporting over a scheme choice
|
|
168
|
+
* punishes the operator harder than the mistake does.
|
|
169
|
+
*/
|
|
124
170
|
warnIfCredentialsSentInClear() {
|
|
125
171
|
if (!this.options.appKey && !this.options.appSecret) {
|
|
126
172
|
return;
|
|
@@ -136,6 +182,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
136
182
|
}
|
|
137
183
|
}
|
|
138
184
|
catch {
|
|
185
|
+
// An unparsable endpoint fails loudly elsewhere; nothing to add here.
|
|
139
186
|
}
|
|
140
187
|
}
|
|
141
188
|
initializeWorker() {
|
|
@@ -144,6 +191,9 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
144
191
|
eval: true,
|
|
145
192
|
workerData: {
|
|
146
193
|
sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
|
|
194
|
+
// Passed in rather than read from the environment inside the worker:
|
|
195
|
+
// the worker is a stringified function with no access to this module's
|
|
196
|
+
// configuration.
|
|
147
197
|
config: {
|
|
148
198
|
endpoint: this.endpoint,
|
|
149
199
|
appKey: this.options.appKey,
|
|
@@ -156,7 +206,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
156
206
|
this.worker.on("exit", (code) => {
|
|
157
207
|
if (code !== 0) {
|
|
158
208
|
this.logger.error(`Worker stopped with exit code ${code}. Restarting worker...`);
|
|
159
|
-
this.initializeWorker();
|
|
209
|
+
this.initializeWorker(); // Restart the worker
|
|
160
210
|
}
|
|
161
211
|
else {
|
|
162
212
|
this.logger.debug("Worker exited gracefully.");
|
|
@@ -177,6 +227,10 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
177
227
|
this.logger.error(error);
|
|
178
228
|
}
|
|
179
229
|
flush() {
|
|
230
|
+
// Before the emptiness check, not after: lines held back from an earlier
|
|
231
|
+
// batch are the only thing that might need sending once the process has
|
|
232
|
+
// gone quiet, and an empty buffer would otherwise return here and strand
|
|
233
|
+
// them until shutdown.
|
|
180
234
|
this.observeAgentSharedBuffer.drainPendingLogs();
|
|
181
235
|
if (this.observeAgentSharedBuffer.isBufferEmpty()) {
|
|
182
236
|
return;
|