@nestjs/observe 0.2.2 → 0.2.3
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.assembly.d.ts +18 -0
- package/dist/agent/detached-observe-worker.assembly.js +29 -0
- package/dist/agent/detached-observe-worker.d.ts +21 -0
- package/dist/agent/detached-observe-worker.js +74 -24
- package/dist/agent/observe-agent.shared-buffer.js +7 -5
- package/dist/agent/observe-agent.worker.js +17 -21
- package/dist/encoders/remap-keys.util.js +6 -0
- package/dist/interfaces/observe-options.interface.d.ts +7 -5
- package/dist/observe.module.js +7 -2
- package/dist/protocols/graphql-operation-parser.d.ts +2 -0
- package/dist/protocols/graphql-operation-parser.js +35 -4
- package/dist/services/operation-trace.registry.d.ts +18 -0
- package/dist/services/operation-trace.registry.js +32 -1
- package/dist/utils/source-context.util.js +8 -0
- package/package.json +1 -1
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DetachedWorkerData } from "./detached-observe-worker.js";
|
|
2
|
+
/**
|
|
3
|
+
* How the telemetry worker is put together, in one place.
|
|
4
|
+
*
|
|
5
|
+
* The worker runs as eval'd source with no module scope, so the code it needs
|
|
6
|
+
* travels as stringified functions and the data it needs as `workerData`.
|
|
7
|
+
* `ObserveAgentWorker.initializeWorker` and the worker's own tests both build
|
|
8
|
+
* it from here on purpose: a test that assembled its own copy would keep
|
|
9
|
+
* passing after the real assembly forgot something, which is exactly the
|
|
10
|
+
* failure it exists to catch.
|
|
11
|
+
*/
|
|
12
|
+
export declare function detachedWorkerSource(): string;
|
|
13
|
+
export declare function detachedWorkerData(input: {
|
|
14
|
+
sharedBuffer: SharedArrayBuffer;
|
|
15
|
+
endpoint: string;
|
|
16
|
+
appKey?: string;
|
|
17
|
+
appSecret?: string;
|
|
18
|
+
}): DetachedWorkerData;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
|
|
2
|
+
import { detachedObserveWorker } from "./detached-observe-worker.js";
|
|
3
|
+
import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
|
|
4
|
+
import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
|
|
5
|
+
/**
|
|
6
|
+
* How the telemetry worker is put together, in one place.
|
|
7
|
+
*
|
|
8
|
+
* The worker runs as eval'd source with no module scope, so the code it needs
|
|
9
|
+
* travels as stringified functions and the data it needs as `workerData`.
|
|
10
|
+
* `ObserveAgentWorker.initializeWorker` and the worker's own tests both build
|
|
11
|
+
* it from here on purpose: a test that assembled its own copy would keep
|
|
12
|
+
* passing after the real assembly forgot something, which is exactly the
|
|
13
|
+
* failure it exists to catch.
|
|
14
|
+
*/
|
|
15
|
+
export function detachedWorkerSource() {
|
|
16
|
+
return `(${detachedObserveWorker.toString()})(${createTelemetrySanitizer.toString()}, ${describeIngestRefusal.toString()})`;
|
|
17
|
+
}
|
|
18
|
+
export function detachedWorkerData(input) {
|
|
19
|
+
// Spelled out against the interface rather than spread, so a key the worker
|
|
20
|
+
// starts reading is a compile error here until it is supplied.
|
|
21
|
+
const config = {
|
|
22
|
+
endpoint: input.endpoint,
|
|
23
|
+
appKey: input.appKey,
|
|
24
|
+
appSecret: input.appSecret,
|
|
25
|
+
wireShapes: SECTION_SHAPES,
|
|
26
|
+
degradedPrefix: DEGRADED_MESSAGE_PREFIX,
|
|
27
|
+
};
|
|
28
|
+
return { sharedBuffer: input.sharedBuffer, config };
|
|
29
|
+
}
|
|
@@ -1,3 +1,24 @@
|
|
|
1
1
|
import type { createTelemetrySanitizer } from "./telemetry-wire-contract.js";
|
|
2
2
|
import type { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
|
|
3
|
+
/**
|
|
4
|
+
* What arrives on `workerData.config`.
|
|
5
|
+
*
|
|
6
|
+
* Declared beside the code that reads it and `import type`d by the side that
|
|
7
|
+
* builds it (`detachedWorkerData`), so the two cannot drift: a key added here
|
|
8
|
+
* and forgotten there is a compile error, not a worker quietly posting
|
|
9
|
+
* `undefined` inside a protocol line.
|
|
10
|
+
*/
|
|
11
|
+
export interface DetachedWorkerConfig {
|
|
12
|
+
endpoint: string;
|
|
13
|
+
appKey?: string;
|
|
14
|
+
appSecret?: string;
|
|
15
|
+
/** Plain JSON, so it travels as data; the sanitizer that reads it travels as source. */
|
|
16
|
+
wireShapes: Parameters<typeof createTelemetrySanitizer>[0];
|
|
17
|
+
/** `DEGRADED_MESSAGE_PREFIX`, as data - see where it is read below. */
|
|
18
|
+
degradedPrefix: string;
|
|
19
|
+
}
|
|
20
|
+
export interface DetachedWorkerData {
|
|
21
|
+
sharedBuffer: SharedArrayBuffer;
|
|
22
|
+
config: DetachedWorkerConfig;
|
|
23
|
+
}
|
|
3
24
|
export declare const detachedObserveWorker: (createSanitizer?: typeof createTelemetrySanitizer, describeRefusal?: typeof describeIngestRefusal) => void;
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { DEGRADED_MESSAGE_PREFIX } from "./degraded-ingest.protocol.js";
|
|
2
1
|
export const detachedObserveWorker = (
|
|
3
2
|
// The factory's *source* is inlined as this argument when the worker script
|
|
4
3
|
// is assembled (see `ObserveAgentWorker.initializeWorker`) - a stringified
|
|
@@ -25,6 +24,30 @@ describeRefusal) => {
|
|
|
25
24
|
const view = new DataView(sharedBuffer, 4, 4);
|
|
26
25
|
const decoder = new TextDecoder();
|
|
27
26
|
const telemetryUrl = `${config.endpoint}/applications/telemetry`;
|
|
27
|
+
/**
|
|
28
|
+
* Why the endpoint can never be reached, decided once from its shape; null
|
|
29
|
+
* when it parses. `fetch` reports a malformed URL exactly as it reports a
|
|
30
|
+
* refused connection - a `TypeError` with a `cause` - so without this the
|
|
31
|
+
* operator is told to check that the collector is running when the fix is
|
|
32
|
+
* the `endpoint` option. `new URL` alone does not settle it: a scheme-less
|
|
33
|
+
* "localhost:4000" parses, with "localhost" as the scheme.
|
|
34
|
+
*/
|
|
35
|
+
const endpointProblem = (() => {
|
|
36
|
+
try {
|
|
37
|
+
const { protocol } = new URL(telemetryUrl);
|
|
38
|
+
return protocol === "http:" || protocol === "https:"
|
|
39
|
+
? null
|
|
40
|
+
: `its scheme is "${protocol}" rather than http: or https:`;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return "it is not a valid URL";
|
|
44
|
+
}
|
|
45
|
+
})();
|
|
46
|
+
// Arrives as data rather than being imported: this function body is eval'd
|
|
47
|
+
// with no module scope, so a reference to the exported constant would be a
|
|
48
|
+
// `ReferenceError` here. Passed in so the prefix has a single definition
|
|
49
|
+
// that `parseDegradedMessage` still matches.
|
|
50
|
+
const degradedPrefix = config.degradedPrefix;
|
|
28
51
|
/**
|
|
29
52
|
* Built here, used only when the collector answers 400. The shapes travel
|
|
30
53
|
* through `workerData` (they are plain JSON); the factory travels as source.
|
|
@@ -151,11 +174,9 @@ describeRefusal) => {
|
|
|
151
174
|
resolve(compressed);
|
|
152
175
|
}
|
|
153
176
|
}));
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
body: await gzipAsync(json),
|
|
158
|
-
});
|
|
177
|
+
/** The request and nothing else, so what it throws is a transport failure. */
|
|
178
|
+
const post = (body) => fetch(telemetryUrl, { method: "POST", headers, body });
|
|
179
|
+
const postBatch = async (json) => post(await gzipAsync(json));
|
|
159
180
|
/**
|
|
160
181
|
* Last resort for a 400: brings the batch into contract entry by entry and
|
|
161
182
|
* re-sends it once, so one bad entry costs itself rather than the batch.
|
|
@@ -235,7 +256,38 @@ describeRefusal) => {
|
|
|
235
256
|
// Skip the first 4 bytes (lock) and the next 4 bytes (length)
|
|
236
257
|
const jsonBytes = buffer.slice(8, 8 + jsonLength);
|
|
237
258
|
const jsonStr = decoder.decode(jsonBytes);
|
|
238
|
-
const
|
|
259
|
+
const compressed = await gzipAsync(jsonStr);
|
|
260
|
+
// Only the request is in this `try`, so anything it throws is a
|
|
261
|
+
// transport failure by construction and the outer catch is left for
|
|
262
|
+
// faults in this worker. Telling the two apart by the shape of the error
|
|
263
|
+
// instead - `fetch` puts ECONNREFUSED and friends on `err.cause` - holds
|
|
264
|
+
// only until the first exception without one, such as a timeout signal
|
|
265
|
+
// on the request, which would then be reported as an agent bug.
|
|
266
|
+
let response;
|
|
267
|
+
try {
|
|
268
|
+
response = await post(compressed);
|
|
269
|
+
}
|
|
270
|
+
catch (err) {
|
|
271
|
+
// `fetch` reports every transport failure as the same opaque "fetch
|
|
272
|
+
// failed" and puts the reason - ECONNREFUSED, ENOTFOUND, a TLS error -
|
|
273
|
+
// on `err.cause`. Reporting only `err.message` would tell the operator
|
|
274
|
+
// nothing: not what went wrong, and not which URL was tried.
|
|
275
|
+
const cause = err
|
|
276
|
+
?.cause;
|
|
277
|
+
const reason = cause?.code ?? cause?.message;
|
|
278
|
+
parentPort.postMessage(endpointProblem
|
|
279
|
+
? `Error: Could not send telemetry: \`endpoint\` is set to ` +
|
|
280
|
+
`${JSON.stringify(config.endpoint)} and ${endpointProblem}. ` +
|
|
281
|
+
`Fix the endpoint option.`
|
|
282
|
+
: `Error: Could not reach the collector at ${telemetryUrl}` +
|
|
283
|
+
(reason ? ` (${reason})` : "") +
|
|
284
|
+
`. Check that it is running and that \`endpoint\` points at it.`);
|
|
285
|
+
// Discarded rather than retried - `clearBuffer` in `finally` - which
|
|
286
|
+
// is the right call for a fixed-size buffer the application is still
|
|
287
|
+
// writing into: holding it for a retry would block every batch behind
|
|
288
|
+
// an unreachable collector.
|
|
289
|
+
return true;
|
|
290
|
+
}
|
|
239
291
|
if (!response.ok) {
|
|
240
292
|
if (response.status === 401 || response.status === 403) {
|
|
241
293
|
authRejections += 1;
|
|
@@ -304,27 +356,25 @@ describeRefusal) => {
|
|
|
304
356
|
accepted.degraded === true;
|
|
305
357
|
// A protocol line, not prose: the parent keys off the prefix and the
|
|
306
358
|
// value, and is the side that decides what to do about it.
|
|
307
|
-
parentPort.postMessage(`${
|
|
359
|
+
parentPort.postMessage(`${degradedPrefix}${degraded}`);
|
|
308
360
|
parentPort.postMessage("Tracing and instrumentation data sent successfully");
|
|
309
361
|
return true;
|
|
310
362
|
}
|
|
311
363
|
catch (err) {
|
|
312
|
-
//
|
|
313
|
-
//
|
|
314
|
-
//
|
|
315
|
-
// operator
|
|
316
|
-
//
|
|
317
|
-
|
|
318
|
-
const
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
parentPort.postMessage(`Error:
|
|
322
|
-
(
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
// still writing into: holding it for a retry would block every batch
|
|
327
|
-
// behind an unreachable collector.
|
|
364
|
+
// Not the request - that has its own catch above - so this is a fault
|
|
365
|
+
// in the worker itself: decoding the buffer, compressing, reading the
|
|
366
|
+
// reply or posting to the parent. Said so rather than blamed on the
|
|
367
|
+
// network: an operator can report a stack line, and can do nothing with
|
|
368
|
+
// the claim that a collector which just answered is unreachable.
|
|
369
|
+
const cause = err?.cause;
|
|
370
|
+
const causeText = cause instanceof Error || typeof cause === "string"
|
|
371
|
+
? String(cause)
|
|
372
|
+
: undefined;
|
|
373
|
+
parentPort.postMessage(`Error: Telemetry worker failed while sending a batch to ${telemetryUrl} - ` +
|
|
374
|
+
String(err) +
|
|
375
|
+
(causeText === undefined ? "" : ` (cause: ${causeText})`) +
|
|
376
|
+
`. This is most likely a fault in the observe agent rather than a ` +
|
|
377
|
+
`connectivity problem; please report it.`);
|
|
328
378
|
return true;
|
|
329
379
|
}
|
|
330
380
|
finally {
|
|
@@ -24,11 +24,13 @@ const DEFAULT_MAX_SNAPSHOTS_PER_TRANSACTION = 1000;
|
|
|
24
24
|
/**
|
|
25
25
|
* Caps on the log portion of a batch.
|
|
26
26
|
*
|
|
27
|
-
* Logs are the
|
|
28
|
-
* `maxTracesPerBatch
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
27
|
+
* Logs are the one input with no natural ceiling - snapshots are gated by
|
|
28
|
+
* `maxTracesPerBatch` and their largest caller-chosen field, the GraphQL
|
|
29
|
+
* document, is capped where it is parsed - but a chatty service (or one stuck
|
|
30
|
+
* in a retry loop) produces log lines without limit. Left uncapped they grow
|
|
31
|
+
* the payload past `SHARED_BUFFER_SIZE`, and `encodeAndWrite` then throws for
|
|
32
|
+
* the whole batch, so noisy logging silently costs you the traces and metrics
|
|
33
|
+
* too.
|
|
32
34
|
*
|
|
33
35
|
* Both limits are needed: the count bounds ordinary chatter, and the per-entry
|
|
34
36
|
* length bounds the single pathological line - a serialised payload dump or a
|
|
@@ -19,11 +19,9 @@ import { CpuProfilerService } from "../profiling/cpu-profiler.service.js";
|
|
|
19
19
|
import { ProfileUploader } from "../profiling/profile-uploader.js";
|
|
20
20
|
import { setActiveSliceRecorder, SpanSliceRecorder, } from "../profiling/span-slice-recorder.js";
|
|
21
21
|
import { NodeRuntimeMetricsService } from "../services/node-runtime-metrics.service.js";
|
|
22
|
-
import { describeIngestRefusal } from "../utils/ingest-refusal.util.js";
|
|
23
|
-
import { detachedObserveWorker } from "./detached-observe-worker.js";
|
|
24
22
|
import { parseDegradedMessage } from "./degraded-ingest.protocol.js";
|
|
23
|
+
import { detachedWorkerData, detachedWorkerSource, } from "./detached-observe-worker.assembly.js";
|
|
25
24
|
import { ObserveAgentSharedBuffer } from "./observe-agent.shared-buffer.js";
|
|
26
|
-
import { createTelemetrySanitizer, SECTION_SHAPES, } from "./telemetry-wire-contract.js";
|
|
27
25
|
const DEFAULT_RUNTIME_METRICS_INTERVAL = 60000; // 60 seconds
|
|
28
26
|
const MIN_RUNTIME_METRICS_INTERVAL = 30000; // 30 seconds
|
|
29
27
|
const DEFAULT_FLUSH_INTERVAL = 5000; // 5 seconds
|
|
@@ -60,9 +58,13 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
60
58
|
}
|
|
61
59
|
onModuleInit() {
|
|
62
60
|
this.initializeWorker();
|
|
63
|
-
|
|
61
|
+
let flushIntervalTime = this.options.flushInterval ?? DEFAULT_FLUSH_INTERVAL;
|
|
64
62
|
if (flushIntervalTime < MIN_FLUSH_INTERVAL) {
|
|
65
63
|
this.logger.warn(`Flush interval is too short (${flushIntervalTime}ms). Setting to minimum of ${MIN_FLUSH_INTERVAL}ms.`);
|
|
64
|
+
// Clamp the value the timer is armed with, not just the recorded option:
|
|
65
|
+
// the warning above used to be a lie, and a `flushInterval: 50` flushed
|
|
66
|
+
// twenty times a second while claiming it had been raised to 1s.
|
|
67
|
+
flushIntervalTime = MIN_FLUSH_INTERVAL;
|
|
66
68
|
this.options.flushInterval = MIN_FLUSH_INTERVAL;
|
|
67
69
|
}
|
|
68
70
|
this.flushInterval = setInterval(() => this.flush(), flushIntervalTime);
|
|
@@ -201,25 +203,19 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
201
203
|
}
|
|
202
204
|
initializeWorker() {
|
|
203
205
|
this.warnIfCredentialsSentInClear();
|
|
204
|
-
//
|
|
205
|
-
//
|
|
206
|
-
//
|
|
207
|
-
//
|
|
208
|
-
//
|
|
209
|
-
this.worker = new Worker(
|
|
206
|
+
// Source and data both come from the assembly module, which the worker's
|
|
207
|
+
// tests build from too: the worker is eval'd with no module scope, so the
|
|
208
|
+
// code it needs travels as stringified functions and the configuration as
|
|
209
|
+
// `workerData`, and the one place that puts them together is the one
|
|
210
|
+
// place a forgotten value can be caught.
|
|
211
|
+
this.worker = new Worker(detachedWorkerSource(), {
|
|
210
212
|
eval: true,
|
|
211
|
-
workerData: {
|
|
213
|
+
workerData: detachedWorkerData({
|
|
212
214
|
sharedBuffer: this.observeAgentSharedBuffer.sharedBuffer,
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
endpoint: this.endpoint,
|
|
218
|
-
appKey: this.options.appKey,
|
|
219
|
-
appSecret: this.options.appSecret,
|
|
220
|
-
wireShapes: SECTION_SHAPES,
|
|
221
|
-
},
|
|
222
|
-
},
|
|
215
|
+
endpoint: this.endpoint,
|
|
216
|
+
appKey: this.options.appKey,
|
|
217
|
+
appSecret: this.options.appSecret,
|
|
218
|
+
}),
|
|
223
219
|
});
|
|
224
220
|
this.worker.on("message", (msg) => this.handleMessage(msg));
|
|
225
221
|
this.worker.on("error", (error) => this.handleError(error));
|
|
@@ -16,6 +16,12 @@ export function remapKeys(source, keyMap) {
|
|
|
16
16
|
// on the prototype where neither form can see them - those are copied across
|
|
17
17
|
// explicitly by `CustomMetricsEncoder`.
|
|
18
18
|
for (const key in source) {
|
|
19
|
+
// `hasOwn` rather than a truthiness check: `keyMap["toString"]` is the
|
|
20
|
+
// inherited function, and an attribute named that way would land under a
|
|
21
|
+
// key spelt from its source code.
|
|
22
|
+
if (!Object.hasOwn(keyMap, key)) {
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
19
25
|
const mapped = keyMap[key];
|
|
20
26
|
if (mapped) {
|
|
21
27
|
encoded[mapped] = source[key];
|
|
@@ -269,12 +269,14 @@ export interface ObserveOptions {
|
|
|
269
269
|
*/
|
|
270
270
|
forwardLogs?: boolean;
|
|
271
271
|
/**
|
|
272
|
-
* How log lines are scrubbed before leaving the process.
|
|
272
|
+
* How log lines and error payloads are scrubbed before leaving the process.
|
|
273
273
|
*
|
|
274
|
-
*
|
|
275
|
-
*
|
|
276
|
-
*
|
|
277
|
-
*
|
|
274
|
+
* Applies to forwarded log lines (when `forwardLogs` is enabled) and to the
|
|
275
|
+
* message and stack of every error attached to a trace - a database error
|
|
276
|
+
* quoting its connection string, a failed request quoting a URL with a token
|
|
277
|
+
* in it. Both move text onto someone else's disk, and secrets reach them by
|
|
278
|
+
* accident far more often than by design, so the safe behaviour is the one
|
|
279
|
+
* you get without asking. Set `enabled: false` to turn it off deliberately.
|
|
278
280
|
*/
|
|
279
281
|
redaction?: RedactionOptions;
|
|
280
282
|
/**
|
package/dist/observe.module.js
CHANGED
|
@@ -31,6 +31,7 @@ import { TraceSamplerService } from "./services/trace-sampler.service.js";
|
|
|
31
31
|
import { TracerService } from "./services/tracer.service.js";
|
|
32
32
|
import { assertModuleOptions } from "./utils/assert-module-options.util.js";
|
|
33
33
|
import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
|
|
34
|
+
import { LogRedactor } from "./utils/log-redactor.js";
|
|
34
35
|
/**
|
|
35
36
|
* All three async providers are optional on the options type, but one of them
|
|
36
37
|
* has to be there. Stating that here beats the `undefined` token Nest would
|
|
@@ -143,10 +144,14 @@ export function createObserveModule(options = {}) {
|
|
|
143
144
|
provide: OperationTraceRegistry,
|
|
144
145
|
// The instance already exists (the instrumentation hook below holds
|
|
145
146
|
// it), so this is the one moment the resolved `ObserveOptions` and the
|
|
146
|
-
// registry meet: `spanCollapse`
|
|
147
|
-
// `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
147
|
+
// registry meet: `spanCollapse` and `redaction` are applied here.
|
|
148
|
+
// Optional because `ASSERT_MODULE_OPTIONS` owns the missing-options
|
|
149
|
+
// error.
|
|
148
150
|
useFactory: (observeOptions) => {
|
|
149
151
|
operationTraceRegistry.configureSpanCollapse(resolveSpanCollapseSettings(observeOptions?.spanCollapse));
|
|
152
|
+
operationTraceRegistry.configureRedaction(observeOptions?.redaction?.enabled === false
|
|
153
|
+
? null
|
|
154
|
+
: new LogRedactor(observeOptions?.redaction));
|
|
150
155
|
return operationTraceRegistry;
|
|
151
156
|
},
|
|
152
157
|
inject: [{ token: OBSERVE_OPTIONS, optional: true }],
|
|
@@ -34,3 +34,5 @@ export declare function toResolveInfoLike(operation: Pick<ParsedGraphQLOperation
|
|
|
34
34
|
export declare function parseGraphQLOperation(document: string | undefined): ParsedGraphQLOperation | undefined;
|
|
35
35
|
/** Test seam: the cache is process-wide and would leak between cases. */
|
|
36
36
|
export declare function clearGraphQLOperationCache(): void;
|
|
37
|
+
/** Test seam: what the cache holds is otherwise unobservable from outside. */
|
|
38
|
+
export declare function graphQLOperationCacheSize(): number;
|
|
@@ -19,12 +19,29 @@ const ROOT_TYPE_BY_KEYWORD = {
|
|
|
19
19
|
};
|
|
20
20
|
/**
|
|
21
21
|
* Parsed results are cached: a client sends the same handful of documents over
|
|
22
|
-
* and over, and re-scanning each one per request is pure waste. Bounded
|
|
23
|
-
* the key is attacker-supplied
|
|
24
|
-
*
|
|
22
|
+
* and over, and re-scanning each one per request is pure waste. Bounded in
|
|
23
|
+
* both dimensions because the key is attacker-supplied: the entry count stops
|
|
24
|
+
* a client sending unique documents from growing the map without limit, and
|
|
25
|
+
* the per-entry size stops 512 entries from being 512 multi-megabyte strings.
|
|
26
|
+
* A document past the size cap is still parsed, just not remembered - a
|
|
27
|
+
* client that sends one is not a client whose documents repeat.
|
|
25
28
|
*/
|
|
26
29
|
const CACHE_LIMIT = 512;
|
|
30
|
+
const MAX_CACHEABLE_DOCUMENT_LENGTH = 16 * 1024;
|
|
27
31
|
const cache = new Map();
|
|
32
|
+
/**
|
|
33
|
+
* Cap on the document shape a trace records.
|
|
34
|
+
*
|
|
35
|
+
* `sanitizedDocument` travels as the snapshot's `originalUrl`, and a query is
|
|
36
|
+
* a request body, not a URL: nothing upstream bounds its size the way the
|
|
37
|
+
* HTTP parser bounds a header. Left uncapped, one multi-megabyte document
|
|
38
|
+
* from an unauthenticated client overflows the shared buffer and takes every
|
|
39
|
+
* other trace, metric and log in that batch down with it. Same order of size
|
|
40
|
+
* as the log-entry cap, for the same reason: past this a document is no
|
|
41
|
+
* longer something a reader scans, and the collector indexes it by trigram.
|
|
42
|
+
*/
|
|
43
|
+
const MAX_SANITIZED_DOCUMENT_LENGTH = 8 * 1024;
|
|
44
|
+
const TRUNCATION_SUFFIX = "... [truncated by observe]";
|
|
28
45
|
/**
|
|
29
46
|
* Builds the `GraphQLResolveInfo`-shaped object the `graphql` options receive.
|
|
30
47
|
*
|
|
@@ -61,6 +78,9 @@ export function parseGraphQLOperation(document) {
|
|
|
61
78
|
return cache.get(document);
|
|
62
79
|
}
|
|
63
80
|
const parsed = scan(document);
|
|
81
|
+
if (document.length > MAX_CACHEABLE_DOCUMENT_LENGTH) {
|
|
82
|
+
return parsed;
|
|
83
|
+
}
|
|
64
84
|
if (cache.size >= CACHE_LIMIT) {
|
|
65
85
|
// Oldest entry out. Map iterates in insertion order, so this is the least
|
|
66
86
|
// recently *added* document rather than the least recently used one - close
|
|
@@ -74,6 +94,10 @@ export function parseGraphQLOperation(document) {
|
|
|
74
94
|
export function clearGraphQLOperationCache() {
|
|
75
95
|
cache.clear();
|
|
76
96
|
}
|
|
97
|
+
/** Test seam: what the cache holds is otherwise unobservable from outside. */
|
|
98
|
+
export function graphQLOperationCacheSize() {
|
|
99
|
+
return cache.size;
|
|
100
|
+
}
|
|
77
101
|
function scan(document) {
|
|
78
102
|
const source = stripIgnoredTokens(document);
|
|
79
103
|
const words = [];
|
|
@@ -133,9 +157,16 @@ function toOperation(words, fieldName, source) {
|
|
|
133
157
|
operationName: words[0] ? words[1] : undefined,
|
|
134
158
|
// Whitespace is collapsed only here, at the end: `source` positions have to
|
|
135
159
|
// stay valid while the scan is still reading from it.
|
|
136
|
-
sanitizedDocument: source.replace(/\s+/g, " ").trim(),
|
|
160
|
+
sanitizedDocument: truncate(source.replace(/\s+/g, " ").trim()),
|
|
137
161
|
};
|
|
138
162
|
}
|
|
163
|
+
function truncate(document) {
|
|
164
|
+
if (document.length <= MAX_SANITIZED_DOCUMENT_LENGTH) {
|
|
165
|
+
return document;
|
|
166
|
+
}
|
|
167
|
+
return (document.slice(0, MAX_SANITIZED_DOCUMENT_LENGTH - TRUNCATION_SUFFIX.length) +
|
|
168
|
+
TRUNCATION_SUFFIX);
|
|
169
|
+
}
|
|
139
170
|
/**
|
|
140
171
|
* Reads the first field selected inside a selection set, seeing through an
|
|
141
172
|
* alias: `latest: orders` is a selection of `orders`, and that is the name a
|
|
@@ -6,6 +6,7 @@ import { CreateObserveModuleOptions } from "../interfaces/observe-options.interf
|
|
|
6
6
|
import { OngoingTraceEventNode } from "../interfaces/trace-events.interfaces.js";
|
|
7
7
|
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
8
8
|
import { KeyOf } from "../types/key-of.type.js";
|
|
9
|
+
import { LogRedactor } from "../utils/log-redactor.js";
|
|
9
10
|
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
10
11
|
import { SpanCollapseSettings } from "./collapse-repeated-spans.util.js";
|
|
11
12
|
type TraceId = string;
|
|
@@ -27,6 +28,17 @@ export declare class OperationTraceRegistry {
|
|
|
27
28
|
* registry the module has not (yet) configured still bounds what it ships.
|
|
28
29
|
*/
|
|
29
30
|
private spanCollapse;
|
|
31
|
+
/**
|
|
32
|
+
* Scrubs error messages and stacks before they are attached to a span.
|
|
33
|
+
*
|
|
34
|
+
* On by default, with the same defaults the log forwarder uses, for the
|
|
35
|
+
* same reason: an error is at least as likely a carrier of a secret as a
|
|
36
|
+
* log line - a driver error quoting a DSN with the password in it, a fetch
|
|
37
|
+
* failure quoting a URL with a token in it - and an error payload is shipped
|
|
38
|
+
* whether or not log forwarding is on. Null only when redaction has been
|
|
39
|
+
* switched off explicitly.
|
|
40
|
+
*/
|
|
41
|
+
private redactor;
|
|
30
42
|
constructor(als: AsyncLocalStorage<Map<KeyOf<{
|
|
31
43
|
[CALLER_METADATA_KEY]: string;
|
|
32
44
|
}>, unknown>>, sourceContext?: CreateObserveModuleOptions["sourceContext"]);
|
|
@@ -37,6 +49,12 @@ export declare class OperationTraceRegistry {
|
|
|
37
49
|
* before the DI container so the instrumentation hook can hold it.
|
|
38
50
|
*/
|
|
39
51
|
configureSpanCollapse(settings: SpanCollapseSettings | undefined): void;
|
|
52
|
+
/**
|
|
53
|
+
* Applies the resolved `redaction` options to error payloads, or switches
|
|
54
|
+
* redaction off with `null`. Called by the module alongside
|
|
55
|
+
* `configureSpanCollapse`, for the same reason.
|
|
56
|
+
*/
|
|
57
|
+
configureRedaction(redactor: LogRedactor | null): void;
|
|
40
58
|
/**
|
|
41
59
|
* Builds the error payload attached to a span or snapshot, including the source
|
|
42
60
|
* around each in-app frame when source context is enabled.
|
|
@@ -3,6 +3,7 @@ import { activeSliceRecorder } from "../profiling/span-slice-recorder.js";
|
|
|
3
3
|
import { uuidv7 } from "../utils/uuid-v7.util.js";
|
|
4
4
|
import { TraceSpanDelegate } from "../trace-span.delegate.js";
|
|
5
5
|
import { collectCodeFrames } from "../utils/source-context.util.js";
|
|
6
|
+
import { LogRedactor } from "../utils/log-redactor.js";
|
|
6
7
|
import { CALLER_METADATA_KEY } from "../observe.constants.js";
|
|
7
8
|
import { collapseRepeatedSpans, DEFAULT_SPAN_COLLAPSE, } from "./collapse-repeated-spans.util.js";
|
|
8
9
|
const SNAPSHOT_COMPLETION_TIMEOUT_MS = 1000;
|
|
@@ -37,6 +38,17 @@ export class OperationTraceRegistry {
|
|
|
37
38
|
* registry the module has not (yet) configured still bounds what it ships.
|
|
38
39
|
*/
|
|
39
40
|
spanCollapse = DEFAULT_SPAN_COLLAPSE;
|
|
41
|
+
/**
|
|
42
|
+
* Scrubs error messages and stacks before they are attached to a span.
|
|
43
|
+
*
|
|
44
|
+
* On by default, with the same defaults the log forwarder uses, for the
|
|
45
|
+
* same reason: an error is at least as likely a carrier of a secret as a
|
|
46
|
+
* log line - a driver error quoting a DSN with the password in it, a fetch
|
|
47
|
+
* failure quoting a URL with a token in it - and an error payload is shipped
|
|
48
|
+
* whether or not log forwarding is on. Null only when redaction has been
|
|
49
|
+
* switched off explicitly.
|
|
50
|
+
*/
|
|
51
|
+
redactor = new LogRedactor();
|
|
40
52
|
constructor(als, sourceContext = true) {
|
|
41
53
|
this.als = als;
|
|
42
54
|
this.sourceContext = sourceContext;
|
|
@@ -50,14 +62,33 @@ export class OperationTraceRegistry {
|
|
|
50
62
|
configureSpanCollapse(settings) {
|
|
51
63
|
this.spanCollapse = settings;
|
|
52
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* Applies the resolved `redaction` options to error payloads, or switches
|
|
67
|
+
* redaction off with `null`. Called by the module alongside
|
|
68
|
+
* `configureSpanCollapse`, for the same reason.
|
|
69
|
+
*/
|
|
70
|
+
configureRedaction(redactor) {
|
|
71
|
+
this.redactor = redactor;
|
|
72
|
+
}
|
|
53
73
|
/**
|
|
54
74
|
* Builds the error payload attached to a span or snapshot, including the source
|
|
55
75
|
* around each in-app frame when source context is enabled.
|
|
56
76
|
*/
|
|
57
77
|
toErrorPayload(error) {
|
|
58
|
-
const
|
|
78
|
+
const raw = error instanceof Error
|
|
59
79
|
? { message: error.message, stack: error.stack }
|
|
60
80
|
: { message: String(error), stack: undefined };
|
|
81
|
+
// Redacted here, at the one point every error payload passes through,
|
|
82
|
+
// and before code frames are read: the frames are keyed off the stack's
|
|
83
|
+
// file positions, which the redactor leaves alone.
|
|
84
|
+
const payload = this.redactor
|
|
85
|
+
? {
|
|
86
|
+
message: this.redactor.redactMessage(raw.message),
|
|
87
|
+
stack: raw.stack === undefined
|
|
88
|
+
? undefined
|
|
89
|
+
: this.redactor.redactMessage(raw.stack),
|
|
90
|
+
}
|
|
91
|
+
: raw;
|
|
61
92
|
const result = payload;
|
|
62
93
|
if (typeof error?.constructor === "function") {
|
|
63
94
|
result.cls = error.constructor.name;
|
|
@@ -157,6 +157,14 @@ export function collectCodeFrames(stack, options = {}) {
|
|
|
157
157
|
if (isIgnored(original.file)) {
|
|
158
158
|
continue;
|
|
159
159
|
}
|
|
160
|
+
// And the containment check, when the map's `sources` entry is about
|
|
161
|
+
// to be read from disk rather than taken from `sourcesContent`. The
|
|
162
|
+
// compiled frame passed it; the path the map resolved it to is a
|
|
163
|
+
// different string from a different input, and a map is one more
|
|
164
|
+
// thing on disk that can say `../../../etc/passwd`.
|
|
165
|
+
if (!original.content && !isReadableSourcePath(original.file)) {
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
160
168
|
file = original.file;
|
|
161
169
|
line = original.line;
|
|
162
170
|
// Prefer the map's embedded copy - it is the source this build was
|
package/package.json
CHANGED