@nestjs/observe 0.1.5 → 0.1.6
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/dist/.tsbuildinfo +1 -1
- package/dist/agent/detached-observe-worker.d.ts +2 -1
- package/dist/agent/detached-observe-worker.js +81 -14
- package/dist/agent/observe-agent.shared-buffer.d.ts +1 -1
- package/dist/agent/observe-agent.shared-buffer.js +5 -1
- package/dist/agent/observe-agent.worker.js +9 -3
- package/dist/agent/telemetry-wire-contract.d.ts +127 -0
- package/dist/agent/telemetry-wire-contract.js +414 -0
- package/package.json +1 -1
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
import type { createTelemetrySanitizer } from "./telemetry-wire-contract.js";
|
|
2
|
+
export declare const detachedObserveWorker: (createSanitizer?: typeof createTelemetrySanitizer) => void;
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
export const detachedObserveWorker = (
|
|
1
|
+
export const detachedObserveWorker = (
|
|
2
|
+
// The factory's *source* is inlined as this argument when the worker script
|
|
3
|
+
// is assembled (see `ObserveAgentWorker.initializeWorker`) - a stringified
|
|
4
|
+
// function cannot import it. Type-only import above; a value import would
|
|
5
|
+
// compile and then throw inside the worker.
|
|
6
|
+
createSanitizer) => {
|
|
2
7
|
// This function body is stringified via .toString() and executed as a
|
|
3
8
|
// standalone worker script, so it can't use static ES imports and must
|
|
4
9
|
// require() its dependencies at runtime instead.
|
|
@@ -15,6 +20,14 @@ export const detachedObserveWorker = () => {
|
|
|
15
20
|
const view = new DataView(sharedBuffer, 4, 4);
|
|
16
21
|
const decoder = new TextDecoder();
|
|
17
22
|
const telemetryUrl = `${config.endpoint}/applications/telemetry`;
|
|
23
|
+
/**
|
|
24
|
+
* Built here, used only when the collector answers 400. The shapes travel
|
|
25
|
+
* through `workerData` (they are plain JSON); the factory travels as source.
|
|
26
|
+
* Healthy batches never touch this - the flush path stays gzip-and-send.
|
|
27
|
+
*/
|
|
28
|
+
const sanitizer = typeof createSanitizer === "function" && config.wireShapes
|
|
29
|
+
? createSanitizer(config.wireShapes)
|
|
30
|
+
: null;
|
|
18
31
|
const headers = {
|
|
19
32
|
"Content-Type": "application/json",
|
|
20
33
|
"Content-Encoding": "gzip",
|
|
@@ -125,6 +138,69 @@ export const detachedObserveWorker = () => {
|
|
|
125
138
|
};
|
|
126
139
|
const clearBuffer = () => view.setUint32(0, 0); // Reset length to 0
|
|
127
140
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
141
|
+
const gzipAsync = (data) => new Promise((resolve, reject) => zlib.gzip(data, (err, compressed) => {
|
|
142
|
+
if (err) {
|
|
143
|
+
reject(err);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
resolve(compressed);
|
|
147
|
+
}
|
|
148
|
+
}));
|
|
149
|
+
const postBatch = async (json) => fetch(telemetryUrl, {
|
|
150
|
+
method: "POST",
|
|
151
|
+
headers,
|
|
152
|
+
body: await gzipAsync(json),
|
|
153
|
+
});
|
|
154
|
+
/**
|
|
155
|
+
* Last resort for a 400: brings the batch into contract entry by entry and
|
|
156
|
+
* re-sends it once, so one bad entry costs itself rather than the batch.
|
|
157
|
+
*
|
|
158
|
+
* This is the only place the payload is ever parsed and re-serialized, and
|
|
159
|
+
* it runs on this worker thread, only for a batch the collector has already
|
|
160
|
+
* refused - a healthy application never pays for it. No retry loop: if the
|
|
161
|
+
* repaired batch is refused again the problem is not one the contract
|
|
162
|
+
* describes, and the generic error path reports it.
|
|
163
|
+
*
|
|
164
|
+
* Returns whether the repair path handled the batch (repaired and re-sent,
|
|
165
|
+
* whatever the outcome); false means nothing was repairable and the caller
|
|
166
|
+
* should report the original refusal.
|
|
167
|
+
*/
|
|
168
|
+
const repairAndResend = async (json) => {
|
|
169
|
+
if (!sanitizer) {
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
const payload = JSON.parse(json);
|
|
174
|
+
const repair = sanitizer.sanitizeBatch(payload);
|
|
175
|
+
if (!repair.changed) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
const shown = repair.problems.slice(0, 5).join("; ");
|
|
179
|
+
const remainder = repair.problems.length - 5;
|
|
180
|
+
const summary = shown +
|
|
181
|
+
(remainder > 0 ? ` (and ${remainder} more)` : "") +
|
|
182
|
+
(repair.dropped > 0
|
|
183
|
+
? `; dropped ${repair.dropped} unsalvageable entr${repair.dropped === 1 ? "y" : "ies"}`
|
|
184
|
+
: "");
|
|
185
|
+
const retry = await postBatch(JSON.stringify(payload));
|
|
186
|
+
if (retry.ok) {
|
|
187
|
+
// Error-level on purpose: the send recovered, but something produced
|
|
188
|
+
// out-of-contract telemetry and the field names here are the lead.
|
|
189
|
+
parentPort.postMessage(`Error: Telemetry batch was rejected (400) and repaired: ${summary}. The repaired batch was sent.`);
|
|
190
|
+
}
|
|
191
|
+
else {
|
|
192
|
+
const retryBody = await retry.text().catch(() => "");
|
|
193
|
+
parentPort.postMessage(`Error: Telemetry batch was rejected (400), repaired (${summary}), and rejected again ` +
|
|
194
|
+
`(${retry.status})${retryBody ? ` - ${retryBody.slice(0, 500)}` : ""}. The batch was dropped.`);
|
|
195
|
+
}
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
catch {
|
|
199
|
+
// An unparsable batch or a transport failure on the retry: fall back to
|
|
200
|
+
// reporting the original refusal.
|
|
201
|
+
return false;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
128
204
|
/**
|
|
129
205
|
* Sends one batch, if there is one to send.
|
|
130
206
|
*
|
|
@@ -154,19 +230,7 @@ export const detachedObserveWorker = () => {
|
|
|
154
230
|
// Skip the first 4 bytes (lock) and the next 4 bytes (length)
|
|
155
231
|
const jsonBytes = buffer.slice(8, 8 + jsonLength);
|
|
156
232
|
const jsonStr = decoder.decode(jsonBytes);
|
|
157
|
-
const
|
|
158
|
-
if (err) {
|
|
159
|
-
reject(err);
|
|
160
|
-
}
|
|
161
|
-
else {
|
|
162
|
-
resolve(compressed);
|
|
163
|
-
}
|
|
164
|
-
}));
|
|
165
|
-
const response = await fetch(telemetryUrl, {
|
|
166
|
-
method: "POST",
|
|
167
|
-
headers,
|
|
168
|
-
body: compressed,
|
|
169
|
-
});
|
|
233
|
+
const response = await postBatch(jsonStr);
|
|
170
234
|
if (!response.ok) {
|
|
171
235
|
if (response.status === 401 || response.status === 403) {
|
|
172
236
|
authRejections += 1;
|
|
@@ -197,6 +261,9 @@ export const detachedObserveWorker = () => {
|
|
|
197
261
|
`Pausing sends for ${Math.round(pauseMs / 60000)} minute(s); batches in the meantime are dropped.`);
|
|
198
262
|
return true;
|
|
199
263
|
}
|
|
264
|
+
if (response.status === 400 && (await repairAndResend(jsonStr))) {
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
200
267
|
// Read as text, defensively: an error body is not guaranteed to be
|
|
201
268
|
// JSON, and a parse failure here must not fall through to the catch
|
|
202
269
|
// below and report a reachable collector as unreachable.
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Counter, Gauge, Summary } from "../custom-metrics/index.js";
|
|
2
2
|
import { JobSnapshot } from "../interfaces/job-snapshot.interface.js";
|
|
3
3
|
import { NodeRuntimeMetrics } from "../interfaces/node-runtime-metrics.interface.js";
|
|
4
|
-
import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
|
|
5
4
|
import { ObserveModuleOptionsWithDefaults } from "../interfaces/observe-options.interface.js";
|
|
5
|
+
import { RequestSnapshot } from "../interfaces/request-snapshot.interface.js";
|
|
6
6
|
/**
|
|
7
7
|
* A log line waiting to be shipped.
|
|
8
8
|
*
|
|
@@ -214,7 +214,11 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
214
214
|
}
|
|
215
215
|
const buffered = this._mainThreadBuffer.logs;
|
|
216
216
|
for (const log of logs) {
|
|
217
|
-
|
|
217
|
+
// The `typeof` guard is not redundant with the type: entries arrive from
|
|
218
|
+
// a patched `process.stdout.write`, where a caller passing something
|
|
219
|
+
// unexpected must not crash the host - flush-time sanitization drops the
|
|
220
|
+
// malformed entry instead.
|
|
221
|
+
const entry = typeof log.text === "string" && log.text.length > MAX_LOG_ENTRY_LENGTH
|
|
218
222
|
? { ...log, text: this.truncateLogText(log.text) }
|
|
219
223
|
: log;
|
|
220
224
|
if (buffered.length < MAX_LOGS_PER_TRANSACTION) {
|
|
@@ -21,6 +21,7 @@ import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-sl
|
|
|
21
21
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
22
22
|
import { detachedObserveWorker } from "./detached-observe-worker.js";
|
|
23
23
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
24
|
+
import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
|
|
24
25
|
const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
|
|
25
26
|
const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
|
|
26
27
|
const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
|
|
@@ -187,17 +188,22 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
187
188
|
}
|
|
188
189
|
initializeWorker() {
|
|
189
190
|
this.warnIfCredentialsSentInClear();
|
|
190
|
-
|
|
191
|
+
// The sanitizer factory is inlined as the worker function's argument: the
|
|
192
|
+
// worker is eval'd source with no module scope, so code it needs has to
|
|
193
|
+
// travel as source, and data (the wire shapes are plain JSON) as
|
|
194
|
+
// `workerData`. The factory is written self-contained for exactly this.
|
|
195
|
+
this.worker = new Worker(`(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()})`, {
|
|
191
196
|
eval: true,
|
|
192
197
|
workerData: {
|
|
193
198
|
sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
|
|
194
199
|
// Passed in rather than read from the environment inside the worker:
|
|
195
|
-
// the worker is a stringified function with no access to this
|
|
196
|
-
// configuration.
|
|
200
|
+
// the worker is a stringified function with no access to this
|
|
201
|
+
// module's configuration.
|
|
197
202
|
config: {
|
|
198
203
|
endpoint: this.endpoint,
|
|
199
204
|
appKey: this.options.appKey,
|
|
200
205
|
appSecret: this.options.appSecret,
|
|
206
|
+
wireShapes: SECTION_SHAPES,
|
|
201
207
|
},
|
|
202
208
|
},
|
|
203
209
|
});
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape the ingestion API accepts, declared here rather than imported from
|
|
3
|
+
* the collector's DTOs.
|
|
4
|
+
*
|
|
5
|
+
* The encoders and the API agree on nothing but single-letter key names, so
|
|
6
|
+
* something has to fail when they drift. That used to be the API's
|
|
7
|
+
* `InsertTelemetryDataDto`, reached across the repo boundary - which meant this
|
|
8
|
+
* package could not be built, tested or published on its own. The contract is
|
|
9
|
+
* restated here instead: it is the SDK's copy of the agreement, and the thing
|
|
10
|
+
* that has to be updated in lockstep when the API changes.
|
|
11
|
+
*
|
|
12
|
+
* Deliberately *not* generated from the encoders' key maps. A contract derived
|
|
13
|
+
* from the code it checks asserts only that the code equals itself. Every key
|
|
14
|
+
* below is written out by hand so that changing a key map breaks a test and
|
|
15
|
+
* forces the API change to be made consciously.
|
|
16
|
+
*
|
|
17
|
+
* The clearest example is `st`: both snapshot encoders map `startTimestamp` to
|
|
18
|
+
* it, and it is absent here on purpose. The API does not declare that field, it
|
|
19
|
+
* validates with `forbidNonWhitelisted`, and what keeps it off the wire is
|
|
20
|
+
* `OperationTraceRegistry.endTrace` deleting it before the encoder ever sees
|
|
21
|
+
* the snapshot. A payload that still carries `st` is rejected with a 400, so
|
|
22
|
+
* `validateTelemetryPayload(..., { forbidUnknown: true })` rejects it too.
|
|
23
|
+
*
|
|
24
|
+
* Lives under `src/agent` rather than `src/testing` because the contract is no
|
|
25
|
+
* longer only a test assertion: when the collector answers 400, the detached
|
|
26
|
+
* worker applies it to the rejected batch - stripping what the API refuses and
|
|
27
|
+
* dropping individual unsalvageable entries - then re-sends once, so one bad
|
|
28
|
+
* entry cannot cost the batch. Healthy batches are never touched.
|
|
29
|
+
*/
|
|
30
|
+
type FieldType = "string" | "number" | "boolean" | "object";
|
|
31
|
+
export interface FieldSpec {
|
|
32
|
+
/** Primitive type, or the type of each element for an array field. */
|
|
33
|
+
readonly type: FieldType;
|
|
34
|
+
/**
|
|
35
|
+
* Additional acceptable types beyond `type`, for the few fields the API
|
|
36
|
+
* models as a union. A value matching one of these is passed through as-is,
|
|
37
|
+
* with no nested shape applied.
|
|
38
|
+
*/
|
|
39
|
+
readonly alsoAccepts?: readonly FieldType[];
|
|
40
|
+
/** The field must be present and non-null. */
|
|
41
|
+
readonly required?: boolean;
|
|
42
|
+
/** The field is an array of `type`. */
|
|
43
|
+
readonly array?: boolean;
|
|
44
|
+
/** Nested contract, for object fields the API models rather than passes through. */
|
|
45
|
+
readonly shape?: Shape;
|
|
46
|
+
/** The nested contract is this shape itself - trace nodes nest arbitrarily deep. */
|
|
47
|
+
readonly recursive?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export type Shape = Readonly<Record<string, FieldSpec>>;
|
|
50
|
+
/** The batch body the agent POSTs to the collector. */
|
|
51
|
+
export declare const TELEMETRY_BATCH: Shape;
|
|
52
|
+
/**
|
|
53
|
+
* The sections of a batch whose entries are individually expendable. Maps each
|
|
54
|
+
* to the shape one entry must satisfy, so the flush path can judge entries one
|
|
55
|
+
* at a time instead of the collector judging the batch as a whole.
|
|
56
|
+
*/
|
|
57
|
+
export declare const SECTION_SHAPES: {
|
|
58
|
+
readonly snapshots: Readonly<Record<string, FieldSpec>>;
|
|
59
|
+
readonly jobs: Readonly<Record<string, FieldSpec>>;
|
|
60
|
+
readonly custom: Readonly<Record<string, FieldSpec>>;
|
|
61
|
+
readonly logs: Readonly<Record<string, FieldSpec>>;
|
|
62
|
+
readonly runtime: Readonly<Record<string, FieldSpec>>;
|
|
63
|
+
};
|
|
64
|
+
export type TelemetrySection = keyof typeof SECTION_SHAPES;
|
|
65
|
+
export interface ValidateOptions {
|
|
66
|
+
/**
|
|
67
|
+
* Reject keys the contract does not declare, mirroring the API's
|
|
68
|
+
* `forbidNonWhitelisted` validation. Off by default, matching a plain
|
|
69
|
+
* `validate()` call, which ignores undeclared properties.
|
|
70
|
+
*/
|
|
71
|
+
readonly forbidUnknown?: boolean;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Checks a batch body against the contract and returns one message per problem,
|
|
75
|
+
* empty when the payload is acceptable. Paths are dotted, with array indices, so
|
|
76
|
+
* a failure names the exact field: `snapshots[0].a.sc`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function validateTelemetryPayload(payload: unknown, options?: ValidateOptions): string[];
|
|
79
|
+
export interface SanitizeEntryResult {
|
|
80
|
+
/** Whether the entry is still sendable once stripped. */
|
|
81
|
+
ok: boolean;
|
|
82
|
+
problems: string[];
|
|
83
|
+
}
|
|
84
|
+
export interface SanitizeBatchResult {
|
|
85
|
+
/** Whether anything was stripped or dropped - false means the batch was already in contract. */
|
|
86
|
+
changed: boolean;
|
|
87
|
+
/** Entries removed outright because a required field was beyond repair. */
|
|
88
|
+
dropped: number;
|
|
89
|
+
problems: string[];
|
|
90
|
+
}
|
|
91
|
+
export interface TelemetrySanitizer {
|
|
92
|
+
sanitizeEntry(section: TelemetrySection, entry: unknown): SanitizeEntryResult;
|
|
93
|
+
sanitizeBatch(payload: Record<string, unknown>): SanitizeBatchResult;
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Builds the sanitizer that brings a rejected batch into contract.
|
|
97
|
+
*
|
|
98
|
+
* Two halves, mirroring the two halves of the API's validation. Keys the
|
|
99
|
+
* contract does not declare, and *optional* fields carrying the wrong type,
|
|
100
|
+
* are removed in place - the data they sat next to is still good, and the API
|
|
101
|
+
* would have rejected the whole batch over them (`forbidNonWhitelisted`).
|
|
102
|
+
* A *required* field that is missing or unusable cannot be repaired by
|
|
103
|
+
* removal, so the entry is dropped alone rather than the collector dropping
|
|
104
|
+
* the batch.
|
|
105
|
+
*
|
|
106
|
+
* Numbers must be finite: `NaN` and `Infinity` survive `typeof` but serialize
|
|
107
|
+
* to `null` in JSON, which arrives at the API as a present-but-null field and
|
|
108
|
+
* fails validation there. They are judged here as what they will be on the
|
|
109
|
+
* wire, not as what they are in memory.
|
|
110
|
+
*
|
|
111
|
+
* A factory rather than module-level functions, and deliberately
|
|
112
|
+
* self-contained - it closes over nothing but its own parameter. The detached
|
|
113
|
+
* worker runs as a stringified function with no module scope, so this
|
|
114
|
+
* function's *source* is inlined into the worker script
|
|
115
|
+
* (`createTelemetrySanitizer.toString()`) and called with the shapes passed
|
|
116
|
+
* through `workerData`. Referencing anything from this module's scope would
|
|
117
|
+
* compile, then throw at runtime inside the worker.
|
|
118
|
+
*
|
|
119
|
+
* This is also why sanitization happens in the worker at all: it runs only
|
|
120
|
+
* when the collector has actually answered 400, on the worker thread, so a
|
|
121
|
+
* healthy application never pays for it - not per flush, and not on the main
|
|
122
|
+
* thread.
|
|
123
|
+
*/
|
|
124
|
+
export declare function createTelemetrySanitizer(shapes: Record<TelemetrySection, Shape>): TelemetrySanitizer;
|
|
125
|
+
export declare function sanitizeTelemetryEntry(section: TelemetrySection, entry: unknown): SanitizeEntryResult;
|
|
126
|
+
export declare function sanitizeTelemetryBatch(payload: Record<string, unknown>): SanitizeBatchResult;
|
|
127
|
+
export {};
|