@nestjs/observe 0.3.25 → 0.3.26
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 +17 -0
- package/dist/agent/detached-observe-worker.js +50 -6
- package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
- package/dist/agent/observe-agent.shared-buffer.js +196 -19
- package/dist/agent/observe-agent.worker.d.ts +22 -2
- package/dist/agent/observe-agent.worker.js +43 -7
- package/dist/agent/telemetry-wire-contract.js +7 -1
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +28 -3
- package/dist/cli/observe-cli.js +1 -19
- package/dist/cli/open-url.d.ts +27 -0
- package/dist/cli/open-url.js +63 -0
- package/dist/cli/project-files.d.ts +42 -1
- package/dist/cli/project-files.js +146 -7
- package/dist/cli/project-setup.d.ts +6 -0
- package/dist/cli/project-setup.js +14 -1
- package/dist/cli/wire-application.js +6 -0
- package/dist/custom-metrics/counter.d.ts +13 -2
- package/dist/custom-metrics/counter.js +33 -16
- package/dist/custom-metrics/finite-value.util.d.ts +14 -0
- package/dist/custom-metrics/finite-value.util.js +33 -1
- package/dist/custom-metrics/gauge.d.ts +2 -0
- package/dist/custom-metrics/gauge.js +41 -17
- package/dist/custom-metrics/label-values.util.d.ts +37 -0
- package/dist/custom-metrics/label-values.util.js +51 -0
- package/dist/custom-metrics/summary.d.ts +23 -0
- package/dist/custom-metrics/summary.js +73 -2
- package/dist/instrument/create-instance-decorator.instrument.js +158 -96
- package/dist/interfaces/observe-options.interface.d.ts +3 -1
- package/dist/objectives/objectives.registry.js +12 -0
- package/dist/observe.module.js +119 -3
- package/dist/otlp/otlp-encoders.js +22 -5
- package/dist/otlp/otlp-span.mapper.js +7 -3
- package/dist/otlp/otlp-trace-exporter.service.js +63 -5
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +13 -6
- package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
- package/dist/outgoing/llm/llm-providers.d.ts +16 -4
- package/dist/outgoing/llm/llm-providers.js +72 -22
- package/dist/outgoing/llm/llm-usage.d.ts +11 -6
- package/dist/outgoing/llm/llm-usage.js +72 -25
- package/dist/outgoing/mssql.integration.js +16 -2
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
- package/dist/outgoing/outgoing-span.recorder.js +17 -3
- package/dist/outgoing/pg.integration.d.ts +3 -2
- package/dist/outgoing/pg.integration.js +39 -11
- package/dist/outgoing/sql-statement.util.js +106 -14
- package/dist/outgoing/undici.integration.d.ts +13 -0
- package/dist/outgoing/undici.integration.js +68 -0
- package/dist/protocols/bull-observe-agent.service.js +2 -12
- package/dist/protocols/deferred-trace-completion.d.ts +9 -1
- package/dist/protocols/deferred-trace-completion.js +36 -6
- package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
- package/dist/protocols/graphql-observe-agent.service.js +166 -5
- package/dist/protocols/graphql-operation-parser.js +72 -18
- package/dist/protocols/http-observe-agent.service.d.ts +43 -9
- package/dist/protocols/http-observe-agent.service.js +177 -59
- package/dist/protocols/job-trace-runner.d.ts +35 -3
- package/dist/protocols/job-trace-runner.js +126 -29
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
- package/dist/protocols/rpc-observe-agent.service.js +187 -47
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +226 -20
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +3 -4
- package/dist/services/operation-trace.registry.d.ts +45 -1
- package/dist/services/operation-trace.registry.js +418 -35
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +288 -51
- package/dist/services/tracer.service.d.ts +23 -0
- package/dist/services/tracer.service.js +91 -5
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +100 -12
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +14 -0
- package/dist/utils/log-line.parser.js +7 -3
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +512 -61
- package/dist/utils/operation-state.util.d.ts +39 -0
- package/dist/utils/operation-state.util.js +50 -0
- package/dist/utils/redact-url-query.d.ts +26 -4
- package/dist/utils/redact-url-query.js +184 -32
- package/dist/utils/sensitive-keys.d.ts +4 -1
- package/dist/utils/sensitive-keys.js +48 -10
- package/dist/utils/shared-hook-slot.util.d.ts +48 -0
- package/dist/utils/shared-hook-slot.util.js +103 -0
- package/dist/utils/source-context.util.d.ts +8 -0
- package/dist/utils/source-context.util.js +88 -24
- package/dist/utils/source-map-resolver.util.js +8 -2
- package/dist/utils/trace-context.util.js +21 -6
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -379,6 +379,13 @@ children, `s` spanId and `so` startOffset. A collector that does not know the
|
|
|
379
379
|
tag stores it like any other and attributes the node as one call of its class
|
|
380
380
|
rather than as the number it carries.
|
|
381
381
|
|
|
382
|
+
Collapsing bounds what is shipped, not what is held while the operation runs,
|
|
383
|
+
so one operation opens at most 10,000 spans, manual ones included. Calls past
|
|
384
|
+
that run as they would untraced, and the operation's `observe.unrecordedSpans`
|
|
385
|
+
tag says how many there were. A handler that calls a provider once per element
|
|
386
|
+
of a list it was sent would otherwise let the sender decide how much memory
|
|
387
|
+
the agent holds.
|
|
388
|
+
|
|
382
389
|
## Skipping spans for expected outcomes
|
|
383
390
|
|
|
384
391
|
Nest applications answer "not found", "not allowed" and "invalid input" by
|
|
@@ -429,6 +436,16 @@ Once the module and the instrument are in place, the agent reports, with no furt
|
|
|
429
436
|
|
|
430
437
|
Query and outbound-HTTP spans are not billed as events. Turn them off with `outgoing: false`, or one side with `outgoing: { database: false }` / `outgoing: { http: false }`.
|
|
431
438
|
|
|
439
|
+
### Hooks your application sets too
|
|
440
|
+
|
|
441
|
+
Several of the places the agent hooks into hold one hook each: GraphQL's `ResolverDecoratorHost` request hooks, the HTTP adapter's `setOnRequestHook`, `setOnResponseHook` and `setOnRouteTriggered`, a microservice server's processing hooks, a `ClientProxy`'s `setOnDispatchHook`, and `@nestjs/bullmq`'s `ProcessorDecoratorService.prototype.decorate`. They are yours to use as well: the agent runs its part beside your hook, whichever is set first, and a getter such as `getOnRequestStartHook()` hands back your own. Three cannot be shared, because the hook is set before Nest hands the object over and nothing can read it back, so the agent's replaces it:
|
|
442
|
+
|
|
443
|
+
- a request or response hook set on an adapter you build yourself, before `NestFactory.create()`;
|
|
444
|
+
- a processing hook set on a server you pass as `strategy`, before `createMicroservice()` or `connectMicroservice()`;
|
|
445
|
+
- a dispatch hook set in a client's own `useFactory`, or in the constructor of a `customClass` client.
|
|
446
|
+
|
|
447
|
+
Set those after instead: on `app.getHttpAdapter()` before `listen()`, on `app.getTransportServer()`, or on the injected client from a provider.
|
|
448
|
+
|
|
432
449
|
## Capturing failed and slow requests
|
|
433
450
|
|
|
434
451
|
The inputs behind a failing request are usually the fastest way to reproduce it. The agent keeps them only for the requests worth it - never for ordinary traffic:
|
|
@@ -257,11 +257,25 @@ describeRefusal) => {
|
|
|
257
257
|
*/
|
|
258
258
|
const REQUEST_TIMEOUT_MS = 15_000;
|
|
259
259
|
/**
|
|
260
|
-
*
|
|
260
|
+
* The most of a reply that is read.
|
|
261
|
+
*
|
|
262
|
+
* Collector replies are a few hundred bytes; the rest is room for a proxy's
|
|
263
|
+
* error page, of which 500 characters are ever shown. The reply is held,
|
|
264
|
+
* decoded and parsed in the application's process, so without a limit its
|
|
265
|
+
* size - and many times that once parsed - would be the sender's to choose,
|
|
266
|
+
* up to a heap out of memory that ends the whole process. Past the limit
|
|
267
|
+
* the reading stops and the connection goes with it. The status still
|
|
268
|
+
* counts: the collector did answer, and a body cut short does not parse as
|
|
269
|
+
* JSON, which every reader below already treats as no body at all.
|
|
270
|
+
*/
|
|
271
|
+
const MAX_REPLY_BYTES = 64 * 1024;
|
|
272
|
+
/**
|
|
273
|
+
* One POST, with the reply read before it resolves - to the end, or as far
|
|
274
|
+
* as `MAX_REPLY_BYTES`.
|
|
261
275
|
*
|
|
262
276
|
* Read whatever the status: a reply left unread keeps its socket busy, and
|
|
263
277
|
* the next batch opens another connection - the 401/403 path never read
|
|
264
|
-
* its body under `fetch`.
|
|
278
|
+
* its body under `fetch`.
|
|
265
279
|
*
|
|
266
280
|
* A transport failure rejects with the failure as `cause`, the shape the
|
|
267
281
|
* reporting below reads (ECONNREFUSED and friends on `err.cause.code`), and
|
|
@@ -274,10 +288,9 @@ describeRefusal) => {
|
|
|
274
288
|
headers: { ...headers, "Content-Length": body.length },
|
|
275
289
|
}, (res) => {
|
|
276
290
|
const chunks = [];
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
const text = Buffer.concat(chunks).toString("utf8");
|
|
291
|
+
let received = 0;
|
|
292
|
+
const settle = () => {
|
|
293
|
+
const text = Buffer.concat(chunks, Math.min(received, MAX_REPLY_BYTES)).toString("utf8");
|
|
281
294
|
const status = res.statusCode ?? 0;
|
|
282
295
|
resolve({
|
|
283
296
|
ok: status >= 200 && status < 300,
|
|
@@ -295,11 +308,42 @@ describeRefusal) => {
|
|
|
295
308
|
text: async () => text,
|
|
296
309
|
json: async () => JSON.parse(text),
|
|
297
310
|
});
|
|
311
|
+
// A reply can end while the batch is still being written - a
|
|
312
|
+
// collector or proxy answering off the head and reading no
|
|
313
|
+
// further. The send is decided; the socket would never be
|
|
314
|
+
// pooled, timed out or closed again, one more for every flush.
|
|
315
|
+
if (!req.writableFinished) {
|
|
316
|
+
req.destroy();
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
res.on("data", (chunk) => {
|
|
320
|
+
if (received >= MAX_REPLY_BYTES) {
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
chunks.push(chunk);
|
|
324
|
+
received += chunk.length;
|
|
325
|
+
if (received >= MAX_REPLY_BYTES) {
|
|
326
|
+
res.destroy();
|
|
327
|
+
settle();
|
|
328
|
+
}
|
|
298
329
|
});
|
|
330
|
+
res.on("error", (err) => reject(new Error("collector reply failed", { cause: err })));
|
|
331
|
+
res.on("end", settle);
|
|
299
332
|
});
|
|
300
333
|
req.on("error", (err) => reject(Object.assign(new Error("request to the collector failed", { cause: err }), {
|
|
301
334
|
reusedSocket: req.reusedSocket,
|
|
302
335
|
})));
|
|
336
|
+
// A 101 with `Connection: Upgrade` is no response to Node: it emits
|
|
337
|
+
// only this, and destroys the socket without an error. Unheard, the
|
|
338
|
+
// send would never settle, and the worker would end with the lock
|
|
339
|
+
// still held. No upgrade was asked for, so it fails like any other
|
|
340
|
+
// transport failure.
|
|
341
|
+
req.on("upgrade", (res, socket) => {
|
|
342
|
+
socket.destroy();
|
|
343
|
+
reject(new Error("request to the collector failed", {
|
|
344
|
+
cause: new Error(`it answered ${res.statusCode} to a request that asked for no upgrade`),
|
|
345
|
+
}));
|
|
346
|
+
});
|
|
303
347
|
req.setTimeout(REQUEST_TIMEOUT_MS, () => req.destroy(Object.assign(new Error(`no answer within ${REQUEST_TIMEOUT_MS / 1000} s`), { code: "ETIMEDOUT" })));
|
|
304
348
|
req.end(body);
|
|
305
349
|
});
|
|
@@ -56,6 +56,8 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
56
56
|
private readonly encoder;
|
|
57
57
|
private readonly logger;
|
|
58
58
|
private _mainThreadBuffer;
|
|
59
|
+
/** See `reportUnencodableMetric`. */
|
|
60
|
+
private hasReportedUnencodableMetric;
|
|
59
61
|
/**
|
|
60
62
|
* Log lines that did not fit the current batch, oldest first. Survives
|
|
61
63
|
* `resetMainThreadBuffer` on purpose - it is the queue the batches are drawn
|
|
@@ -68,6 +70,8 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
68
70
|
* window can be closed once the payload is actually written.
|
|
69
71
|
*/
|
|
70
72
|
private readonly _awaitingFlushAck;
|
|
73
|
+
/** Metrics changed in the current buffer, encoded as it is written. */
|
|
74
|
+
private readonly _metricsToEncode;
|
|
71
75
|
get sharedBuffer(): SharedArrayBuffer;
|
|
72
76
|
constructor(options: ObserveModuleOptionsWithDefaults, objectivesRegistry?: ObjectivesRegistry | undefined, otlpTraceExporter?: OtlpTraceExporter | undefined);
|
|
73
77
|
insertRequestSnapshot(snapshot: RequestSnapshot): void;
|
|
@@ -273,6 +277,18 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
273
277
|
releaseLock(): void;
|
|
274
278
|
addNodeRuntimeMetrics(runtimeMetrics: NodeRuntimeMetrics | undefined): void;
|
|
275
279
|
upsertCustomMetric(metric: Counter<any> | Gauge<any> | Summary<any>): void;
|
|
280
|
+
/**
|
|
281
|
+
* Encodes every metric changed in the window into the batch's `custom`
|
|
282
|
+
* section, once each.
|
|
283
|
+
*
|
|
284
|
+
* At most `MAX_BATCH_ITEMS` entries: the collector refuses a batch with
|
|
285
|
+
* more, and everything else of the window with it. A metric left out is
|
|
286
|
+
* not marked as delivered, so a counter's increase or a summary's window
|
|
287
|
+
* rides the next batch the metric changes in.
|
|
288
|
+
*/
|
|
289
|
+
private placeChangedMetrics;
|
|
290
|
+
/** Once for the process: the same metric fails the same way every window. */
|
|
291
|
+
private reportUnencodableMetric;
|
|
276
292
|
/**
|
|
277
293
|
* Buffers log entries, filling the current batch first and holding the rest
|
|
278
294
|
* back for later batches. Oversized lines are truncated on the way in.
|
|
@@ -311,6 +327,34 @@ export declare class ObserveAgentSharedBuffer {
|
|
|
311
327
|
drainPendingLogs(maxLogs?: number): void;
|
|
312
328
|
private truncateLogText;
|
|
313
329
|
encodeAndWrite(): void;
|
|
330
|
+
/**
|
|
331
|
+
* The batch as the bytes written to the shared slot, which they have to fit.
|
|
332
|
+
*
|
|
333
|
+
* `maxTracesPerBatch` bounds how many operations a batch holds, not how
|
|
334
|
+
* large each is, and parts of one are as long as a client made them - a
|
|
335
|
+
* URL, the text of an error. One entry can also hold what `JSON.stringify`
|
|
336
|
+
* refuses: a tag of a type nothing checked at run time. Either way the whole
|
|
337
|
+
* batch was thrown away, with every other request, job, log line and metric
|
|
338
|
+
* of the window. Such a batch is now sent without the entries that keep it
|
|
339
|
+
* from being written, so they cost only themselves.
|
|
340
|
+
*
|
|
341
|
+
* A batch that fits is serialised once, as before; only one that does not
|
|
342
|
+
* has its entries measured.
|
|
343
|
+
*/
|
|
344
|
+
private encodeToFit;
|
|
345
|
+
/**
|
|
346
|
+
* The batch as bytes; nothing when it comes to more than `capacity`, and
|
|
347
|
+
* what `JSON.stringify` threw when it cannot be serialised at all.
|
|
348
|
+
*/
|
|
349
|
+
private encodeWithin;
|
|
350
|
+
/**
|
|
351
|
+
* Takes request snapshots, job snapshots and log entries out of the batch -
|
|
352
|
+
* any that cannot be serialised, then the largest - until what is left
|
|
353
|
+
* comes to at most `capacity` bytes, and returns how many went. Metrics are
|
|
354
|
+
* left in: a metric's window closes once the batch is written, so one taken
|
|
355
|
+
* out here would be lost rather than carried to the next.
|
|
356
|
+
*/
|
|
357
|
+
private dropEntriesToFit;
|
|
314
358
|
resetMainThreadBuffer(): void;
|
|
315
359
|
private createEmptyPayload;
|
|
316
360
|
}
|
|
@@ -59,6 +59,15 @@ const TRUNCATION_SUFFIX = "... [truncated by observe]";
|
|
|
59
59
|
const MAX_PENDING_LOGS = 2000;
|
|
60
60
|
/** Declarations one batch carries at most - the collector's own limit. */
|
|
61
61
|
const MAX_OBJECTIVES_PER_BATCH = 100;
|
|
62
|
+
/**
|
|
63
|
+
* What a metric is told apart by in a batch: its type and the name as sent,
|
|
64
|
+
* which the encoder cuts to what the collector accepts. Matched on the
|
|
65
|
+
* metric's own name, two metrics whose names are cut alike would be two
|
|
66
|
+
* entries of one name.
|
|
67
|
+
*/
|
|
68
|
+
function sentMetricKey(encoded) {
|
|
69
|
+
return `${encoded.t}:${encoded.n}`;
|
|
70
|
+
}
|
|
62
71
|
let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSharedBuffer {
|
|
63
72
|
options;
|
|
64
73
|
objectivesRegistry;
|
|
@@ -69,6 +78,8 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
69
78
|
encoder = new TextEncoder();
|
|
70
79
|
logger = new Logger(ObserveAgentSharedBuffer_1.name);
|
|
71
80
|
_mainThreadBuffer = null;
|
|
81
|
+
/** See `reportUnencodableMetric`. */
|
|
82
|
+
hasReportedUnencodableMetric = false;
|
|
72
83
|
/**
|
|
73
84
|
* Log lines that did not fit the current batch, oldest first. Survives
|
|
74
85
|
* `resetMainThreadBuffer` on purpose - it is the queue the batches are drawn
|
|
@@ -81,6 +92,8 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
81
92
|
* window can be closed once the payload is actually written.
|
|
82
93
|
*/
|
|
83
94
|
_awaitingFlushAck = new Set();
|
|
95
|
+
/** Metrics changed in the current buffer, encoded as it is written. */
|
|
96
|
+
_metricsToEncode = new Set();
|
|
84
97
|
get sharedBuffer() {
|
|
85
98
|
return this._sharedBuffer;
|
|
86
99
|
}
|
|
@@ -97,7 +110,9 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
97
110
|
// over a single miss, so fall back to the transport's URL, and drop the
|
|
98
111
|
// snapshot when even that is absent rather than poison the batch it would
|
|
99
112
|
// ride in. The URL is folded to a route-like path first, or every query
|
|
100
|
-
// string and id would be a route of its own
|
|
113
|
+
// string and id would be a route of its own. `originalUrl` keeps its ids;
|
|
114
|
+
// its query string the registry has already cut, as nothing that named
|
|
115
|
+
// the request said what it holds.
|
|
101
116
|
snapshot.operationId ??= fallbackOperationId(snapshot.attributes?.originalUrl);
|
|
102
117
|
// A full grant exports ahead of everything below that can leave the
|
|
103
118
|
// snapshot out: the collector's limits and its answers about this
|
|
@@ -531,21 +546,76 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
531
546
|
if (metric instanceof Counter || metric instanceof Summary) {
|
|
532
547
|
this._awaitingFlushAck.add(metric);
|
|
533
548
|
}
|
|
534
|
-
//
|
|
535
|
-
//
|
|
536
|
-
//
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
549
|
+
// Encoded when the batch is written, not on every change: a metric is
|
|
550
|
+
// changed on the request path, and encoding one reads all of it - a
|
|
551
|
+
// summary sorts its sample once per quantile, a counter or gauge at its
|
|
552
|
+
// series cap copies a thousand series - so encoding on every change cost
|
|
553
|
+
// the main thread more the fuller the window got, for an entry the next
|
|
554
|
+
// change replaced.
|
|
555
|
+
this._metricsToEncode.add(metric);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Encodes every metric changed in the window into the batch's `custom`
|
|
559
|
+
* section, once each.
|
|
560
|
+
*
|
|
561
|
+
* At most `MAX_BATCH_ITEMS` entries: the collector refuses a batch with
|
|
562
|
+
* more, and everything else of the window with it. A metric left out is
|
|
563
|
+
* not marked as delivered, so a counter's increase or a summary's window
|
|
564
|
+
* rides the next batch the metric changes in.
|
|
565
|
+
*/
|
|
566
|
+
placeChangedMetrics() {
|
|
567
|
+
const custom = this._mainThreadBuffer?.custom;
|
|
568
|
+
if (!custom) {
|
|
569
|
+
return;
|
|
544
570
|
}
|
|
545
|
-
|
|
546
|
-
|
|
571
|
+
const placed = new Map();
|
|
572
|
+
custom.forEach((encoded, index) => placed.set(sentMetricKey(encoded), index));
|
|
573
|
+
for (const metric of this._metricsToEncode) {
|
|
574
|
+
let encoded;
|
|
575
|
+
try {
|
|
576
|
+
encoded = CustomMetricsEncoder.encode(metric);
|
|
577
|
+
}
|
|
578
|
+
catch (error) {
|
|
579
|
+
// One metric the encoder cannot read - a label name that is not a
|
|
580
|
+
// string at run time - is left out rather than costing the batch,
|
|
581
|
+
// and is not marked as delivered.
|
|
582
|
+
if (metric instanceof Counter || metric instanceof Summary) {
|
|
583
|
+
this._awaitingFlushAck.delete(metric);
|
|
584
|
+
}
|
|
585
|
+
this.reportUnencodableMetric(metric, error);
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
const key = sentMetricKey(encoded);
|
|
589
|
+
const existing = placed.get(key);
|
|
590
|
+
if (existing !== undefined) {
|
|
591
|
+
custom[existing] = { ...custom[existing], ...encoded };
|
|
592
|
+
}
|
|
593
|
+
else if (custom.length < MAX_BATCH_ITEMS) {
|
|
594
|
+
placed.set(key, custom.length);
|
|
595
|
+
custom.push(encoded);
|
|
596
|
+
}
|
|
597
|
+
else if (metric instanceof Counter || metric instanceof Summary) {
|
|
598
|
+
this._awaitingFlushAck.delete(metric);
|
|
599
|
+
}
|
|
547
600
|
}
|
|
548
601
|
}
|
|
602
|
+
/** Once for the process: the same metric fails the same way every window. */
|
|
603
|
+
reportUnencodableMetric(metric, error) {
|
|
604
|
+
if (this.hasReportedUnencodableMetric) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
this.hasReportedUnencodableMetric = true;
|
|
608
|
+
let reason;
|
|
609
|
+
try {
|
|
610
|
+
reason = error instanceof Error ? error.message : String(error);
|
|
611
|
+
}
|
|
612
|
+
catch {
|
|
613
|
+
reason = "an unprintable error";
|
|
614
|
+
}
|
|
615
|
+
// Typed as a string, and as unchecked at run time as what failed.
|
|
616
|
+
const name = metric.name;
|
|
617
|
+
this.logger.warn(`Custom metric "${typeof name === "string" ? name.slice(0, 100) : typeof name}" could not be encoded and is left out of the batch. Later metrics that cannot be encoded are not reported: ${reason}`);
|
|
618
|
+
}
|
|
549
619
|
/**
|
|
550
620
|
* Buffers log entries, filling the current batch first and holding the rest
|
|
551
621
|
* back for later batches. Oversized lines are truncated on the way in.
|
|
@@ -629,19 +699,16 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
629
699
|
}
|
|
630
700
|
encodeAndWrite() {
|
|
631
701
|
this.withholdLogs();
|
|
702
|
+
this.placeChangedMetrics();
|
|
703
|
+
this._metricsToEncode.clear();
|
|
632
704
|
if (this.options.debug) {
|
|
633
705
|
if (this._mainThreadBuffer?.snapshots) {
|
|
634
706
|
this.logger.debug(`Encoding and writing ${this._mainThreadBuffer.snapshots.length} snapshots to shared buffer.`);
|
|
635
707
|
this.logger.debug(`Operations in shared buffer: ${this._mainThreadBuffer.snapshots.map((s) => s.op)}`);
|
|
636
708
|
}
|
|
637
709
|
}
|
|
638
|
-
const
|
|
639
|
-
const jsonBytes = this.encoder.encode(json);
|
|
710
|
+
const jsonBytes = this.encodeToFit();
|
|
640
711
|
const jsonLength = jsonBytes.length;
|
|
641
|
-
if (jsonLength > SHARED_BUFFER_SIZE - 8) {
|
|
642
|
-
// 8 bytes reserved for the lock and length
|
|
643
|
-
throw new Error("Payload too large for shared buffer");
|
|
644
|
-
}
|
|
645
712
|
// Offset 4 for the lock value
|
|
646
713
|
const view = new DataView(this._sharedBuffer, 4, 4);
|
|
647
714
|
// Store the length of the JSON data
|
|
@@ -658,8 +725,118 @@ let ObserveAgentSharedBuffer = ObserveAgentSharedBuffer_1 = class ObserveAgentSh
|
|
|
658
725
|
}
|
|
659
726
|
this._awaitingFlushAck.clear();
|
|
660
727
|
}
|
|
728
|
+
/**
|
|
729
|
+
* The batch as the bytes written to the shared slot, which they have to fit.
|
|
730
|
+
*
|
|
731
|
+
* `maxTracesPerBatch` bounds how many operations a batch holds, not how
|
|
732
|
+
* large each is, and parts of one are as long as a client made them - a
|
|
733
|
+
* URL, the text of an error. One entry can also hold what `JSON.stringify`
|
|
734
|
+
* refuses: a tag of a type nothing checked at run time. Either way the whole
|
|
735
|
+
* batch was thrown away, with every other request, job, log line and metric
|
|
736
|
+
* of the window. Such a batch is now sent without the entries that keep it
|
|
737
|
+
* from being written, so they cost only themselves.
|
|
738
|
+
*
|
|
739
|
+
* A batch that fits is serialised once, as before; only one that does not
|
|
740
|
+
* has its entries measured.
|
|
741
|
+
*/
|
|
742
|
+
encodeToFit() {
|
|
743
|
+
// 8 bytes reserved for the lock and length
|
|
744
|
+
const capacity = SHARED_BUFFER_SIZE - 8;
|
|
745
|
+
const whole = this.encodeWithin(capacity);
|
|
746
|
+
if (whole instanceof Uint8Array) {
|
|
747
|
+
return whole;
|
|
748
|
+
}
|
|
749
|
+
const dropped = this.dropEntriesToFit(capacity);
|
|
750
|
+
const fitted = this.encodeWithin(capacity);
|
|
751
|
+
if (!(fitted instanceof Uint8Array)) {
|
|
752
|
+
// What is left is in a section no entry can be taken out of.
|
|
753
|
+
throw fitted ?? new Error("Payload too large for shared buffer");
|
|
754
|
+
}
|
|
755
|
+
this.logger.warn(`A telemetry batch could not be written whole - it came to more than the ${capacity} bytes one flush carries, or held a value that cannot be serialised - and was sent without ${dropped} of its entries: any that cannot be serialised, then the largest.`);
|
|
756
|
+
return fitted;
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* The batch as bytes; nothing when it comes to more than `capacity`, and
|
|
760
|
+
* what `JSON.stringify` threw when it cannot be serialised at all.
|
|
761
|
+
*/
|
|
762
|
+
encodeWithin(capacity) {
|
|
763
|
+
let json;
|
|
764
|
+
try {
|
|
765
|
+
json = JSON.stringify(this._mainThreadBuffer);
|
|
766
|
+
}
|
|
767
|
+
catch (error) {
|
|
768
|
+
return error instanceof Error ? error : new Error(String(error));
|
|
769
|
+
}
|
|
770
|
+
// Each character is a byte at least, so a longer one is known not to fit.
|
|
771
|
+
if (json.length > capacity) {
|
|
772
|
+
return undefined;
|
|
773
|
+
}
|
|
774
|
+
const bytes = this.encoder.encode(json);
|
|
775
|
+
return bytes.length > capacity ? undefined : bytes;
|
|
776
|
+
}
|
|
777
|
+
/**
|
|
778
|
+
* Takes request snapshots, job snapshots and log entries out of the batch -
|
|
779
|
+
* any that cannot be serialised, then the largest - until what is left
|
|
780
|
+
* comes to at most `capacity` bytes, and returns how many went. Metrics are
|
|
781
|
+
* left in: a metric's window closes once the batch is written, so one taken
|
|
782
|
+
* out here would be lost rather than carried to the next.
|
|
783
|
+
*/
|
|
784
|
+
dropEntriesToFit(capacity) {
|
|
785
|
+
const batch = this._mainThreadBuffer;
|
|
786
|
+
if (!batch) {
|
|
787
|
+
return 0;
|
|
788
|
+
}
|
|
789
|
+
const dropped = new Set();
|
|
790
|
+
const sized = [];
|
|
791
|
+
for (const entry of [
|
|
792
|
+
...batch.snapshots,
|
|
793
|
+
...(batch.jobs ?? []),
|
|
794
|
+
...(batch.logs ?? []),
|
|
795
|
+
]) {
|
|
796
|
+
try {
|
|
797
|
+
// One more for the comma that follows it.
|
|
798
|
+
sized.push({
|
|
799
|
+
entry,
|
|
800
|
+
bytes: Buffer.byteLength(JSON.stringify(entry)) + 1,
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
catch {
|
|
804
|
+
dropped.add(entry);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
sized.sort((a, b) => b.bytes - a.bytes);
|
|
808
|
+
let total = 0;
|
|
809
|
+
try {
|
|
810
|
+
total = Buffer.byteLength(JSON.stringify({ ...batch, snapshots: [], jobs: [], logs: [] }));
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
// Left to the encode that follows, which reports it.
|
|
814
|
+
}
|
|
815
|
+
for (const { bytes } of sized) {
|
|
816
|
+
total += bytes;
|
|
817
|
+
}
|
|
818
|
+
for (const { entry, bytes } of sized) {
|
|
819
|
+
if (total <= capacity) {
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
822
|
+
dropped.add(entry);
|
|
823
|
+
total -= bytes;
|
|
824
|
+
}
|
|
825
|
+
if (dropped.size > 0) {
|
|
826
|
+
const kept = (entry) => !dropped.has(entry);
|
|
827
|
+
batch.snapshots = batch.snapshots.filter(kept);
|
|
828
|
+
if (batch.jobs) {
|
|
829
|
+
batch.jobs = batch.jobs.filter(kept);
|
|
830
|
+
}
|
|
831
|
+
if (batch.logs) {
|
|
832
|
+
batch.logs = batch.logs.filter(kept);
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
return dropped.size;
|
|
836
|
+
}
|
|
661
837
|
resetMainThreadBuffer() {
|
|
662
838
|
this._mainThreadBuffer = null;
|
|
839
|
+
this._metricsToEncode.clear();
|
|
663
840
|
this.withheldSnapshots = 0;
|
|
664
841
|
this.withheldJobs = 0;
|
|
665
842
|
}
|
|
@@ -121,9 +121,15 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
121
121
|
*/
|
|
122
122
|
private takeFinalRuntimeSample;
|
|
123
123
|
/**
|
|
124
|
-
* The runtime-metrics window between the last
|
|
124
|
+
* The runtime-metrics window between the last sample and now - scheduled
|
|
125
|
+
* or final - and whether it was taken.
|
|
126
|
+
*
|
|
127
|
+
* Never throws. Sampling reads `/proc` and the like, and fails when the
|
|
128
|
+
* process has no file descriptor to spare (`EMFILE`), which a flood of idle
|
|
129
|
+
* connections can arrange: out of a timer, that would be an uncaught
|
|
130
|
+
* exception in the host, and the end of it.
|
|
125
131
|
*/
|
|
126
|
-
private
|
|
132
|
+
private addRuntimeMetrics;
|
|
127
133
|
/**
|
|
128
134
|
* Whether `enabled: false` switched the agent off - whatever the
|
|
129
135
|
* credentials, and whichever collector `endpoint` names.
|
|
@@ -146,6 +152,20 @@ export declare class ObserveAgentWorker implements OnModuleInit, OnApplicationSh
|
|
|
146
152
|
initializeWorker(): void;
|
|
147
153
|
/** The worker's messages, errors, and the restart when it dies. */
|
|
148
154
|
private watchWorker;
|
|
155
|
+
/**
|
|
156
|
+
* Frees the shared slot when the worker died holding it.
|
|
157
|
+
*
|
|
158
|
+
* A worker that dies mid-send - an uncaught exception, an out-of-memory -
|
|
159
|
+
* never reaches the `finally` that lets go of the lock, and its successor,
|
|
160
|
+
* started on the same buffer, could never take it: every later flush would
|
|
161
|
+
* be skipped for the life of the process. The main thread holds the lock
|
|
162
|
+
* only inside one synchronous `flush`, so a lock still held when the exit
|
|
163
|
+
* is handled can only be the dead worker's. Its batch is dropped, as on
|
|
164
|
+
* every failed send, so a batch that ends the worker cannot end the next
|
|
165
|
+
* one too. A slot that is not locked is left alone: its batch is still
|
|
166
|
+
* waiting, and goes to the next worker.
|
|
167
|
+
*/
|
|
168
|
+
private reclaimSlotOfStoppedWorker;
|
|
149
169
|
handleMessage(msg: string): void;
|
|
150
170
|
/**
|
|
151
171
|
* Whether OpenTelemetry interop was last said to be on - see
|
|
@@ -176,8 +176,12 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
176
176
|
}
|
|
177
177
|
this.lastRuntimeSampleAt = Date.now();
|
|
178
178
|
this.runtimeMetricsInterval = setInterval(() => {
|
|
179
|
-
|
|
180
|
-
|
|
179
|
+
// Moved on only by a sample that was taken: one that could not be
|
|
180
|
+
// leaves its window open, and the next sample - or the final one -
|
|
181
|
+
// covers it.
|
|
182
|
+
if (this.addRuntimeMetrics()) {
|
|
183
|
+
this.lastRuntimeSampleAt = Date.now();
|
|
184
|
+
}
|
|
181
185
|
}, interval);
|
|
182
186
|
if (this.options.debug) {
|
|
183
187
|
this.logger.debug(`Collecting runtime metrics every ${interval}ms.`);
|
|
@@ -389,7 +393,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
389
393
|
// window since the previous one, so taking this earlier could
|
|
390
394
|
// replace an unsent sample and lose its window.
|
|
391
395
|
sampleRuntimeMetrics = false;
|
|
392
|
-
this.
|
|
396
|
+
this.addRuntimeMetrics();
|
|
393
397
|
continue;
|
|
394
398
|
}
|
|
395
399
|
}
|
|
@@ -424,20 +428,28 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
424
428
|
if (this.observeAgentSharedBuffer.hasRuntimeMetrics()) {
|
|
425
429
|
return true;
|
|
426
430
|
}
|
|
427
|
-
this.
|
|
431
|
+
this.addRuntimeMetrics();
|
|
428
432
|
return false;
|
|
429
433
|
}
|
|
430
434
|
/**
|
|
431
|
-
* The runtime-metrics window between the last
|
|
435
|
+
* The runtime-metrics window between the last sample and now - scheduled
|
|
436
|
+
* or final - and whether it was taken.
|
|
437
|
+
*
|
|
438
|
+
* Never throws. Sampling reads `/proc` and the like, and fails when the
|
|
439
|
+
* process has no file descriptor to spare (`EMFILE`), which a flood of idle
|
|
440
|
+
* connections can arrange: out of a timer, that would be an uncaught
|
|
441
|
+
* exception in the host, and the end of it.
|
|
432
442
|
*/
|
|
433
|
-
|
|
443
|
+
addRuntimeMetrics() {
|
|
434
444
|
try {
|
|
435
445
|
this.observeAgentSharedBuffer.addNodeRuntimeMetrics(this.nodeRuntimeMetricsService.collectNodeRuntimeMetrics());
|
|
446
|
+
return true;
|
|
436
447
|
}
|
|
437
448
|
catch (error) {
|
|
438
449
|
if (this.options.debug) {
|
|
439
|
-
this.logger.debug(`Could not collect
|
|
450
|
+
this.logger.debug(`Could not collect runtime metrics: ${String(error)}`);
|
|
440
451
|
}
|
|
452
|
+
return false;
|
|
441
453
|
}
|
|
442
454
|
}
|
|
443
455
|
/**
|
|
@@ -518,6 +530,7 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
518
530
|
// Whatever comes next, this worker gets nothing in any more: a
|
|
519
531
|
// restarted one has to get a batch in again first.
|
|
520
532
|
this.observeAgentSharedBuffer.recordStopped();
|
|
533
|
+
this.reclaimSlotOfStoppedWorker();
|
|
521
534
|
this.reportOpenTelemetryInterop("stopped");
|
|
522
535
|
if (code !== 0) {
|
|
523
536
|
this.logger.error(`Worker stopped with exit code ${code}. Restarting worker...`);
|
|
@@ -528,6 +541,29 @@ let ObserveAgentWorker = ObserveAgentWorker_1 = class ObserveAgentWorker {
|
|
|
528
541
|
}
|
|
529
542
|
});
|
|
530
543
|
}
|
|
544
|
+
/**
|
|
545
|
+
* Frees the shared slot when the worker died holding it.
|
|
546
|
+
*
|
|
547
|
+
* A worker that dies mid-send - an uncaught exception, an out-of-memory -
|
|
548
|
+
* never reaches the `finally` that lets go of the lock, and its successor,
|
|
549
|
+
* started on the same buffer, could never take it: every later flush would
|
|
550
|
+
* be skipped for the life of the process. The main thread holds the lock
|
|
551
|
+
* only inside one synchronous `flush`, so a lock still held when the exit
|
|
552
|
+
* is handled can only be the dead worker's. Its batch is dropped, as on
|
|
553
|
+
* every failed send, so a batch that ends the worker cannot end the next
|
|
554
|
+
* one too. A slot that is not locked is left alone: its batch is still
|
|
555
|
+
* waiting, and goes to the next worker.
|
|
556
|
+
*/
|
|
557
|
+
reclaimSlotOfStoppedWorker() {
|
|
558
|
+
const buffer = this.observeAgentSharedBuffer;
|
|
559
|
+
if (!buffer.isBufferLocked()) {
|
|
560
|
+
return;
|
|
561
|
+
}
|
|
562
|
+
// The batch's length, after the lock word - what the worker zeroes
|
|
563
|
+
// before it lets go.
|
|
564
|
+
new DataView(buffer.sharedBuffer, 4, 4).setUint32(0, 0);
|
|
565
|
+
buffer.releaseLock();
|
|
566
|
+
}
|
|
531
567
|
handleMessage(msg) {
|
|
532
568
|
const pausedUntil = parsePausedMessage(msg);
|
|
533
569
|
if (pausedUntil !== null) {
|
|
@@ -462,7 +462,13 @@ export function createTelemetrySanitizer(shapes) {
|
|
|
462
462
|
}
|
|
463
463
|
else if (key in value) {
|
|
464
464
|
// Explicit nulls fail the API's type checks even on optional
|
|
465
|
-
// fields; absent keys do not.
|
|
465
|
+
// fields; absent keys do not. Reported like every other removal:
|
|
466
|
+
// a repair that is not is a batch dropped rather than re-sent -
|
|
467
|
+
// and a non-finite number reaches here as the `null` that
|
|
468
|
+
// `JSON.stringify` made of it. `undefined` never reached the wire.
|
|
469
|
+
if (value[key] === null) {
|
|
470
|
+
problems.push(`${fieldPath}: null, removed`);
|
|
471
|
+
}
|
|
466
472
|
delete value[key];
|
|
467
473
|
}
|
|
468
474
|
continue;
|
package/dist/cli/agent-notes.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { isProjectFile } from "./project-files.js";
|
|
4
|
+
/** What would take a path out of its backticks in the notes. */
|
|
5
|
+
// eslint-disable-next-line no-control-regex -- control characters are what it finds.
|
|
6
|
+
const UNQUOTABLE = /[`\u0000-\u001f\u007f\u0085\u2028\u2029]/;
|
|
3
7
|
/** The file coding agents read for a repository's working notes. */
|
|
4
8
|
export const AGENTS_FILE = "AGENTS.md";
|
|
5
9
|
/**
|
|
@@ -52,14 +56,18 @@ export function pendingAgentNotes(cwd) {
|
|
|
52
56
|
return existsSync(path) ? readFileSync(path, "utf8") : undefined;
|
|
53
57
|
};
|
|
54
58
|
const changes = [];
|
|
55
|
-
|
|
59
|
+
// A file that leads out of the project - a link to anywhere the person
|
|
60
|
+
// can write - is not the project's notes, and is left alone.
|
|
61
|
+
const agents = isProjectFile(cwd, AGENTS_FILE) ? read(AGENTS_FILE) : null;
|
|
56
62
|
if (agents === undefined) {
|
|
57
63
|
changes.push({ file: AGENTS_FILE, created: true });
|
|
58
64
|
}
|
|
59
|
-
else if (!agents.includes(AGENT_NOTES_HEADING)) {
|
|
65
|
+
else if (agents !== null && !agents.includes(AGENT_NOTES_HEADING)) {
|
|
60
66
|
changes.push({ file: AGENTS_FILE, created: false });
|
|
61
67
|
}
|
|
62
|
-
const claude =
|
|
68
|
+
const claude = isProjectFile(cwd, CLAUDE_FILE)
|
|
69
|
+
? read(CLAUDE_FILE)
|
|
70
|
+
: undefined;
|
|
63
71
|
if (claude !== undefined &&
|
|
64
72
|
!claude.includes(AGENT_NOTES_HEADING) &&
|
|
65
73
|
!claude.includes(`@${AGENTS_FILE}`)) {
|
|
@@ -74,7 +82,11 @@ export function pendingAgentNotes(cwd) {
|
|
|
74
82
|
*/
|
|
75
83
|
export function writeAgentNotes(cwd, rootModule) {
|
|
76
84
|
const changes = pendingAgentNotes(cwd);
|
|
77
|
-
|
|
85
|
+
// Quoted only when the path cannot leave its quotes: a directory name is
|
|
86
|
+
// the project's to choose, and a backtick or a line break in it would
|
|
87
|
+
// put text of its own into the notes.
|
|
88
|
+
const quotable = rootModule !== undefined && !UNQUOTABLE.test(rootModule);
|
|
89
|
+
const notes = agentNotes(quotable ? `\`${rootModule}\`` : undefined);
|
|
78
90
|
for (const change of changes) {
|
|
79
91
|
const path = join(cwd, change.file);
|
|
80
92
|
if (change.created) {
|