@nestjs/observe 0.3.25 → 0.3.27
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 +55 -2
- 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 +201 -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 +10 -4
- package/dist/cli/agent-notes.js +16 -4
- package/dist/cli/link.js +51 -4
- 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/package-manager.d.ts +6 -0
- package/dist/cli/package-manager.js +60 -3
- package/dist/cli/project-files.d.ts +62 -1
- package/dist/cli/project-files.js +229 -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 +90 -12
- package/dist/instrument/create-instance-decorator.instrument.js +504 -116
- package/dist/instrument/raw-receiver.d.ts +6 -0
- package/dist/instrument/raw-receiver.js +32 -0
- package/dist/interfaces/observe-options.interface.d.ts +17 -6
- 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.d.ts +2 -0
- package/dist/otlp/otlp-span.mapper.js +26 -4
- package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
- package/dist/otlp/otlp-trace-exporter.service.js +295 -43
- package/dist/outgoing/http.integration.d.ts +8 -4
- package/dist/outgoing/http.integration.js +49 -17
- 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/mongodb.integration.d.ts +3 -1
- package/dist/outgoing/mongodb.integration.js +93 -18
- package/dist/outgoing/mssql.integration.js +25 -6
- package/dist/outgoing/mysql2.integration.js +17 -1
- package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
- 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 +139 -21
- 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 +23 -12
- package/dist/protocols/deferred-trace-completion.d.ts +17 -3
- package/dist/protocols/deferred-trace-completion.js +76 -9
- package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
- package/dist/protocols/graphql-observe-agent.service.js +354 -19
- package/dist/protocols/graphql-operation-parser.js +111 -26
- package/dist/protocols/http-observe-agent.service.d.ts +50 -9
- package/dist/protocols/http-observe-agent.service.js +220 -59
- package/dist/protocols/job-trace-runner.d.ts +42 -3
- package/dist/protocols/job-trace-runner.js +197 -36
- package/dist/protocols/queue-observe-agent.service.js +44 -20
- package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
- package/dist/protocols/rpc-observe-agent.service.js +332 -56
- package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
- package/dist/protocols/ws-observe-agent.service.js +227 -21
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/logger-patcher.service.js +16 -7
- package/dist/services/operation-trace.registry.d.ts +58 -1
- package/dist/services/operation-trace.registry.js +576 -63
- package/dist/services/stdout-forwarder.service.d.ts +69 -0
- package/dist/services/stdout-forwarder.service.js +308 -51
- package/dist/services/tracer.service.d.ts +39 -11
- package/dist/services/tracer.service.js +145 -36
- package/dist/utils/capture-request.util.d.ts +3 -1
- package/dist/utils/capture-request.util.js +128 -12
- package/dist/utils/context-accessor.util.d.ts +16 -0
- package/dist/utils/context-accessor.util.js +28 -0
- package/dist/utils/default-trace-id-generator.util.js +5 -7
- package/dist/utils/error-stack.util.d.ts +13 -0
- package/dist/utils/error-stack.util.js +166 -0
- package/dist/utils/fit-to-length.util.js +33 -10
- package/dist/utils/log-line.parser.d.ts +22 -0
- package/dist/utils/log-line.parser.js +20 -7
- package/dist/utils/log-redactor.d.ts +14 -0
- package/dist/utils/log-redactor.js +690 -65
- 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 +37 -4
- package/dist/utils/redact-url-query.js +197 -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 +14 -0
- package/dist/utils/source-context.util.js +142 -43
- package/dist/utils/source-map-resolver.util.js +33 -6
- package/dist/utils/store-copy.util.d.ts +10 -0
- package/dist/utils/store-copy.util.js +43 -0
- 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,52 @@ 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
|
+
|
|
449
|
+
### The request's async store
|
|
450
|
+
|
|
451
|
+
`ObserveModule` provides its `AsyncLocalStorage` to the whole application, under the `AsyncLocalStorage` class, so request context needs no other package: inject it anywhere. Each request, message, job or operation the agent handles runs with a `Map` of its own as the store, which holds what `setAttributes` returns and the trace id (under `traceIdKey`), and which you can read and write too. `TracerService.getAttribute()` and `setAttribute()` are the typed way in.
|
|
452
|
+
|
|
453
|
+
```ts
|
|
454
|
+
@Injectable()
|
|
455
|
+
export class CurrentTenant {
|
|
456
|
+
constructor(private readonly als: AsyncLocalStorage<Map<string, unknown>>) {}
|
|
457
|
+
|
|
458
|
+
get id() {
|
|
459
|
+
return this.als.getStore()?.get("tenantId") as string | undefined;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
```
|
|
463
|
+
|
|
464
|
+
The store is the agent's, so leave opening it to the agent: calling `run()` or `enterWith()` on it with a store of your own replaces the request's `Map`, and the agent loses the request. For a store of your own - Nest's async-local-storage recipe, say - provide it under a token of your own instead of the `AsyncLocalStorage` class, which would otherwise resolve to either one depending on the order of the imports. `enabled: false` does not change any of this: the store is provided either way.
|
|
465
|
+
|
|
466
|
+
### Guards and the handler they are handed
|
|
467
|
+
|
|
468
|
+
With `instrument: ObserveInstrument`, the controller and gateway methods Nest routes to are the agent's traced stand-ins for your methods, so `context.getHandler()` in a guard or interceptor returns the stand-in, not `MyController.prototype.method`. The stand-in carries the method's name and a copy of its metadata, taken when Nest registers the route. Reading that metadata through `Reflector`, as Nest's documentation does (`SetMetadata`, `Reflector.createDecorator()`), works the same with the agent as without it. Two things do not:
|
|
469
|
+
|
|
470
|
+
- **Looking a handler up by the function itself**: a `WeakMap` or `Map` keyed by the decorated method, or an `===` comparison with it. The stand-in is another function, so the lookup misses.
|
|
471
|
+
- **Metadata defined or changed after the route is registered**, in `onModuleInit` or at run time. The copy predates it.
|
|
472
|
+
|
|
473
|
+
A guard that treats such a miss as "no restriction" lets the request through. Keep what a guard reads on the method as metadata, defined by a decorator, and read it with `Reflector`. Where that is not possible, return `true` from `skipInstrumentation` for that controller or gateway, so it is left as it is.
|
|
474
|
+
|
|
475
|
+
### Scheduled jobs in a process with more than one application
|
|
476
|
+
|
|
477
|
+
`@nestjs/schedule` hands every `@Cron`, `@Interval` and `@Timeout` handler in the process through one shared method, and the agent patches it once: the first application in the process to construct its `ObserveModule` traces the scheduled handlers of every application there. This matters only when one process starts more than one application, or starts one again after `app.close()` - two applications side by side, a bootstrap that runs twice, a test file that does either. A later application's scheduled handlers then run under the first application's agent:
|
|
478
|
+
|
|
479
|
+
- Its `jobs` options (`ignore`, `tags`, `setAttributes`) are not used for them; the first application's are.
|
|
480
|
+
- With a `createObserveModule()` call of its own, the handlers run in the first agent's async context, while the `TracerService` injected into them reads the later application's. So `createSpan()` runs its callback untraced, `activeSpan()` hands back a span that records nothing, `setAttribute()` does nothing, `getAttribute()` returns `undefined` and `captureError()` records nothing. Their runs are not reported.
|
|
481
|
+
- Sharing one `createObserveModule()`, the `observe.ts` above, the handlers work, but their runs are reported through the first application's agent, under its `serviceId`, and not at all once that application has closed.
|
|
482
|
+
|
|
483
|
+
Keep scheduled jobs in one application per process, and construct that application first.
|
|
484
|
+
|
|
432
485
|
## Capturing failed and slow requests
|
|
433
486
|
|
|
434
487
|
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:
|
|
@@ -572,7 +625,7 @@ What a backend receives, for each operation:
|
|
|
572
625
|
- **The same trace ids `traceparent` carries.** A request that arrived with a `traceparent` goes under the caller's span, a queue job or microservice message under the span that handed it on, and a call this service makes names its CLIENT span as the parent the callee sees - so services instrumented with OpenTelemetry, and other services running the agent, assemble into one trace in the backend.
|
|
573
626
|
- **Errors** as span status and an `exception` event, with the class, message and stack the dashboard shows - redacted the same way.
|
|
574
627
|
|
|
575
|
-
What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000 while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
|
|
628
|
+
What is exported is what is recorded: after `tracesSampleRate`, `skipSpans` and `spanCollapse`, and on Free after what NestJS Observe holds back. A request whose caller sampled its trace out (`traceparent` flags `00`) is not exported, as an OpenTelemetry SDK sampling by its parent would leave it out. Spans wait in a queue of at most 10,000, and at most 32 Mi characters of text, while an export is retried (429, 502, 503 and 504, honouring `Retry-After`); past that, whole operations are dropped and counted. An export carries at most 1,000 spans and 2 Mi characters, and a string attribute is cut to 16 KiB. Later batches go ahead of one the receiver turned away, and a batch it turns away three more times once one of them got through is dropped and counted too, so one it will never take does not hold up every trace after it. Exports run on the application's thread, outside its traces, and whatever is queued is exported when the application closes, within `shutdownFlushTimeout`. Traces only, for now: runtime metrics, custom metrics and logs are not exported.
|
|
576
629
|
|
|
577
630
|
## Configuration
|
|
578
631
|
|
|
@@ -602,7 +655,7 @@ Every option, with its default. The [documentation](https://www.observe.nestjs.c
|
|
|
602
655
|
| `openTelemetry` | `false` | Continues and sends W3C `traceparent`, names a request after the W3C trace it is in, and follows an OpenTelemetry SDK running in the same process - see [Observe and OpenTelemetry](#observe-and-opentelemetry). Works only beside reporting to NestJS Observe, and stays on through collector outages. Off, the agent reads and sends `x-request-id` alone. |
|
|
603
656
|
| `http` | | `ignore`, `tags`, `setAttributes`, `getUserId`, `queryParamsObfuscateRegex`, `tracePreflights` and `capture` - see [Capturing failed and slow requests](#capturing-failed-and-slow-requests). |
|
|
604
657
|
| `rpc`, `grpc` | | `ignore`, `tags`, `setAttributes` and `getUserId` for microservice and gRPC handlers. |
|
|
605
|
-
| `graphql` | | The same four, once per GraphQL operation.
|
|
658
|
+
| `graphql` | | The same four, once per GraphQL operation. An operation `ignore` matches over HTTP takes the request's trace with it: nothing it reaches is recorded, nor anything else in a batched request it leads. |
|
|
606
659
|
| `ws` | | The same four, once per gateway message. |
|
|
607
660
|
| `jobs` | | `ignore`, `tags` and `setAttributes` for queue jobs and scheduled handlers. |
|
|
608
661
|
| `debug` | `false` | Logs the SDK's own diagnostics. |
|
|
@@ -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,20 +546,75 @@ 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
|
+
}
|
|
600
|
+
}
|
|
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;
|
|
547
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}`);
|
|
548
618
|
}
|
|
549
619
|
/**
|
|
550
620
|
* Buffers log entries, filling the current batch first and holding the rest
|
|
@@ -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,123 @@ 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();
|
|
840
|
+
// Of the batch just dropped, with the metrics in it. After a write that
|
|
841
|
+
// threw, they stayed, and the next batch written marked them delivered
|
|
842
|
+
// too: a counter's increase and a summary's window were lost unsent. A
|
|
843
|
+
// metric comes back at its next change, with its window still open.
|
|
844
|
+
this._awaitingFlushAck.clear();
|
|
663
845
|
this.withheldSnapshots = 0;
|
|
664
846
|
this.withheldJobs = 0;
|
|
665
847
|
}
|
|
@@ -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) {
|