@nestjs/observe 0.3.24 → 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.
Files changed (97) hide show
  1. package/README.md +26 -1
  2. package/dist/agent/detached-observe-worker.js +50 -6
  3. package/dist/agent/observe-agent.shared-buffer.d.ts +44 -0
  4. package/dist/agent/observe-agent.shared-buffer.js +196 -19
  5. package/dist/agent/observe-agent.worker.d.ts +22 -2
  6. package/dist/agent/observe-agent.worker.js +43 -7
  7. package/dist/agent/telemetry-wire-contract.js +7 -1
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +28 -3
  10. package/dist/cli/observe-cli.js +1 -19
  11. package/dist/cli/open-url.d.ts +27 -0
  12. package/dist/cli/open-url.js +63 -0
  13. package/dist/cli/project-files.d.ts +42 -1
  14. package/dist/cli/project-files.js +146 -7
  15. package/dist/cli/project-setup.d.ts +6 -0
  16. package/dist/cli/project-setup.js +14 -1
  17. package/dist/cli/wire-application.js +6 -0
  18. package/dist/custom-metrics/counter.d.ts +13 -2
  19. package/dist/custom-metrics/counter.js +33 -16
  20. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  21. package/dist/custom-metrics/finite-value.util.js +33 -1
  22. package/dist/custom-metrics/gauge.d.ts +2 -0
  23. package/dist/custom-metrics/gauge.js +43 -21
  24. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  25. package/dist/custom-metrics/label-values.util.js +51 -0
  26. package/dist/custom-metrics/summary.d.ts +23 -0
  27. package/dist/custom-metrics/summary.js +73 -2
  28. package/dist/instrument/create-instance-decorator.instrument.js +244 -97
  29. package/dist/interfaces/observe-options.interface.d.ts +3 -1
  30. package/dist/objectives/objectives.registry.js +12 -0
  31. package/dist/observe.module.js +119 -3
  32. package/dist/otlp/otlp-encoders.js +22 -5
  33. package/dist/otlp/otlp-span.mapper.d.ts +4 -3
  34. package/dist/otlp/otlp-span.mapper.js +16 -8
  35. package/dist/otlp/otlp-trace-exporter.service.d.ts +3 -0
  36. package/dist/otlp/otlp-trace-exporter.service.js +71 -6
  37. package/dist/outgoing/http.integration.d.ts +8 -4
  38. package/dist/outgoing/http.integration.js +13 -6
  39. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  40. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  41. package/dist/outgoing/llm/llm-providers.js +72 -22
  42. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  43. package/dist/outgoing/llm/llm-usage.js +72 -25
  44. package/dist/outgoing/mssql.integration.js +16 -2
  45. package/dist/outgoing/mysql2.integration.js +17 -1
  46. package/dist/outgoing/outgoing-observe-agent.service.js +15 -3
  47. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  48. package/dist/outgoing/pg.integration.d.ts +3 -2
  49. package/dist/outgoing/pg.integration.js +39 -11
  50. package/dist/outgoing/sql-statement.util.js +106 -14
  51. package/dist/outgoing/undici.integration.d.ts +13 -0
  52. package/dist/outgoing/undici.integration.js +68 -0
  53. package/dist/protocols/bull-observe-agent.service.js +2 -12
  54. package/dist/protocols/deferred-trace-completion.d.ts +9 -1
  55. package/dist/protocols/deferred-trace-completion.js +36 -6
  56. package/dist/protocols/graphql-observe-agent.service.d.ts +36 -5
  57. package/dist/protocols/graphql-observe-agent.service.js +166 -5
  58. package/dist/protocols/graphql-operation-parser.js +72 -18
  59. package/dist/protocols/http-observe-agent.service.d.ts +43 -9
  60. package/dist/protocols/http-observe-agent.service.js +177 -59
  61. package/dist/protocols/job-trace-runner.d.ts +35 -3
  62. package/dist/protocols/job-trace-runner.js +136 -31
  63. package/dist/protocols/queue-observe-agent.service.js +44 -20
  64. package/dist/protocols/rpc-observe-agent.service.d.ts +50 -8
  65. package/dist/protocols/rpc-observe-agent.service.js +225 -49
  66. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  67. package/dist/protocols/ws-observe-agent.service.js +226 -20
  68. package/dist/services/index.d.ts +1 -1
  69. package/dist/services/index.js +1 -1
  70. package/dist/services/logger-patcher.service.js +3 -4
  71. package/dist/services/operation-trace.registry.d.ts +45 -1
  72. package/dist/services/operation-trace.registry.js +418 -35
  73. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  74. package/dist/services/stdout-forwarder.service.js +288 -51
  75. package/dist/services/tracer.service.d.ts +23 -0
  76. package/dist/services/tracer.service.js +99 -7
  77. package/dist/utils/capture-request.util.d.ts +3 -1
  78. package/dist/utils/capture-request.util.js +100 -12
  79. package/dist/utils/fit-to-length.util.js +33 -10
  80. package/dist/utils/log-line.parser.d.ts +14 -0
  81. package/dist/utils/log-line.parser.js +7 -3
  82. package/dist/utils/log-redactor.d.ts +14 -0
  83. package/dist/utils/log-redactor.js +512 -61
  84. package/dist/utils/operation-state.util.d.ts +39 -0
  85. package/dist/utils/operation-state.util.js +50 -0
  86. package/dist/utils/redact-url-query.d.ts +26 -4
  87. package/dist/utils/redact-url-query.js +184 -32
  88. package/dist/utils/sensitive-keys.d.ts +4 -1
  89. package/dist/utils/sensitive-keys.js +48 -10
  90. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  91. package/dist/utils/shared-hook-slot.util.js +103 -0
  92. package/dist/utils/source-context.util.d.ts +8 -0
  93. package/dist/utils/source-context.util.js +88 -19
  94. package/dist/utils/source-map-resolver.util.js +8 -2
  95. package/dist/utils/trace-context.util.d.ts +20 -0
  96. package/dist/utils/trace-context.util.js +50 -6
  97. package/package.json +4 -1
@@ -13,13 +13,14 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
13
13
  import { Inject, Logger, Module, } from "@nestjs/common";
14
14
  import { DiscoveryModule, DiscoveryService, HttpAdapterHost, MetadataScanner, ModulesContainer, } from "@nestjs/core";
15
15
  import { AsyncLocalStorage } from "async_hooks";
16
+ import { isObservable, Observable } from "rxjs";
16
17
  import { ObserveAgentSharedBuffer } from "./agent/observe-agent.shared-buffer.js";
17
18
  import { ObserveAgentWorker } from "./agent/observe-agent.worker.js";
18
19
  import { ObjectivesRegistry } from "./objectives/objectives.registry.js";
19
20
  import { createInstanceDecorator } from "./instrument/create-instance-decorator.instrument.js";
20
21
  import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
21
22
  import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
22
- import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
23
+ import { HttpObserveAgentService, shareHttpAdapterHooks, } from "./protocols/http-observe-agent.service.js";
23
24
  import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
24
25
  import { OtlpTraceExporter } from "./otlp/otlp-trace-exporter.service.js";
25
26
  import { installLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./outgoing/llm/llm-fetch.integration.js";
@@ -37,6 +38,7 @@ import { StdoutForwarderService } from "./services/stdout-forwarder.service.js";
37
38
  import { TraceSamplerService } from "./services/trace-sampler.service.js";
38
39
  import { TracerService } from "./services/tracer.service.js";
39
40
  import { assertModuleOptions } from "./utils/assert-module-options.util.js";
41
+ import { setAgentHook } from "./utils/shared-hook-slot.util.js";
40
42
  import { defaultTraceIdGenerator } from "./utils/default-trace-id-generator.util.js";
41
43
  import { recordTraceIdGeneratorOrigin } from "./utils/trace-id-generator-origin.util.js";
42
44
  import { OpenTelemetryInteropGate, traceparentToHandOn, } from "./utils/trace-handoff.util.js";
@@ -44,6 +46,7 @@ import { fitServiceVersion, MAX_SERVICE_VERSION_LENGTH, } from "./utils/fit-serv
44
46
  import { fitToLength } from "./utils/fit-to-length.util.js";
45
47
  import { inferServiceVersion } from "./utils/infer-service-version.util.js";
46
48
  import { LogRedactor } from "./utils/log-redactor.js";
49
+ import { liveTraceId } from "./utils/operation-state.util.js";
47
50
  /**
48
51
  * All three async providers are optional on the options type, but one of them
49
52
  * has to be there. Stating that here beats the `undefined` token Nest would
@@ -371,7 +374,12 @@ export function createObserveModule(options = {}) {
371
374
  skipInstrumentation,
372
375
  });
373
376
  return (instance) => {
374
- propagateTraceIdThrough(instance, () => asyncLocalStorage.getStore()?.get(options.traceIdKey), (traceId) => openTelemetryInterop.isOn()
377
+ shareHooksOfHttpAdapter(instance);
378
+ deliverRepliesToTheirCaller(instance, asyncLocalStorage);
379
+ propagateTraceIdThrough(instance,
380
+ // Not a finished operation's, past its grace period: a message a
381
+ // timer it left armed sends is no part of its trace.
382
+ () => liveTraceId(asyncLocalStorage.getStore(), options.traceIdKey), (traceId) => openTelemetryInterop.isOn()
375
383
  ? traceparentToHandOn(asyncLocalStorage.getStore(), traceId)
376
384
  : undefined);
377
385
  return decorate(instance);
@@ -381,6 +389,23 @@ export function createObserveModule(options = {}) {
381
389
  ObserveModule,
382
390
  };
383
391
  }
392
+ /**
393
+ * Shares the HTTP adapter's request and response hooks with the application
394
+ * from the moment Nest creates the `HttpAdapterHost`, ahead of every provider
395
+ * of the application's, so a hook it sets on the adapter runs beside the
396
+ * agent's - see `shareHttpAdapterHooks`.
397
+ */
398
+ function shareHooksOfHttpAdapter(instance) {
399
+ try {
400
+ if (instance instanceof HttpAdapterHost) {
401
+ shareHttpAdapterHooks(instance);
402
+ }
403
+ }
404
+ catch {
405
+ // `instanceof` runs a proxy's prototype trap, which may throw, and Nest
406
+ // 11 does not guard the instance decorator.
407
+ }
408
+ }
384
409
  /**
385
410
  * Makes a microservice client send the current trace id with every packet.
386
411
  *
@@ -399,6 +424,14 @@ export function createObserveModule(options = {}) {
399
424
  * With OpenTelemetry interop on, `traceparentFor` names a W3C `traceparent`
400
425
  * to send beside it, which the receiving agent hands to an OpenTelemetry SDK
401
426
  * in its process - see `traceparentToHandOn`.
427
+ *
428
+ * The hook is the application's to set too - Nest names a tenant and a
429
+ * locale as packet metadata - so the agent's part is set beside it: a
430
+ * dispatch hook the application sets on the client from here on runs first,
431
+ * and the agent's after it, adding the id beside what it wrote and never
432
+ * over an id it chose. Nest hands the same client over again for an alias,
433
+ * which replaces the agent's part rather than nesting it. A hook set in the
434
+ * client's own factory is already in place, and cannot be read.
402
435
  */
403
436
  function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
404
437
  const client = instance;
@@ -412,7 +445,7 @@ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
412
445
  // exclusions deal with it; it is certainly not a microservice client.
413
446
  return;
414
447
  }
415
- client.setOnDispatchHook((packet) => {
448
+ setAgentHook(client, "setOnDispatchHook", (packet) => {
416
449
  const traceId = currentTraceId();
417
450
  if (typeof traceId !== "string") {
418
451
  return;
@@ -429,6 +462,89 @@ function propagateTraceIdThrough(instance, currentTraceId, traceparentFor) {
429
462
  packet.metadata = { ...packet.metadata, traceparent };
430
463
  }
431
464
  }
465
+ }, composeDispatchHook);
466
+ }
467
+ /** The dispatch hook the client is given: the application's, then the agent's. */
468
+ function composeDispatchHook(application, agent) {
469
+ if (!application) {
470
+ return agent;
471
+ }
472
+ return function (packet) {
473
+ application.call(this, packet);
474
+ agent.call(this, packet);
475
+ };
476
+ }
477
+ /**
478
+ * Makes what a microservice client's call emits arrive in the async context
479
+ * of the caller that subscribed to it.
480
+ *
481
+ * A client's replies come from events of its connection, and Node runs those
482
+ * in the async context the connection was opened in: a `ClientProxy`
483
+ * connects on first use, in the request that used it first, and grpc-js
484
+ * starts the calls made while its channel connects from the first one's
485
+ * attempt. Whatever a later caller chained onto its reply - a log line, a
486
+ * span, the next call's packet - read that request's store, and carried its
487
+ * trace id, for as long as the connection lived.
488
+ *
489
+ * Only what the client hands out is wrapped: the `Observable` of
490
+ * `ClientProxy#send`, and of each method a `ClientGrpc#getService` service
491
+ * has. Matched by shape, as the optional peer is never imported here; an
492
+ * instance that cannot be inspected or written to is left as it is.
493
+ */
494
+ function deliverRepliesToTheirCaller(instance, asyncLocalStorage) {
495
+ const client = instance;
496
+ const inCaller = (replies) => isObservable(replies)
497
+ ? inSubscriberContext(replies, asyncLocalStorage)
498
+ : replies;
499
+ try {
500
+ const { send, getService } = client ?? {};
501
+ if (typeof getService === "function" &&
502
+ typeof client.getClientByServiceName === "function") {
503
+ client.getService = function (...args) {
504
+ const service = getService.apply(this, args);
505
+ if (typeof service === "object" && service !== null) {
506
+ const methods = service;
507
+ for (const name of Object.keys(methods)) {
508
+ const method = methods[name];
509
+ if (typeof method === "function") {
510
+ methods[name] = function (...callArgs) {
511
+ return inCaller(method.apply(this, callArgs));
512
+ };
513
+ }
514
+ }
515
+ }
516
+ return service;
517
+ };
518
+ }
519
+ else if (typeof send === "function" &&
520
+ typeof client.emit === "function" &&
521
+ typeof client.connect === "function" &&
522
+ typeof client.close === "function" &&
523
+ typeof client.dispatchEvent === "function") {
524
+ client.send = function (...args) {
525
+ return inCaller(send.apply(this, args));
526
+ };
527
+ }
528
+ }
529
+ catch {
530
+ // A provider that throws on inspection, or cannot be written to, is not
531
+ // a client this can help - the decorator's own exclusions deal with it.
532
+ }
533
+ }
534
+ /**
535
+ * `source`, with each value, error and completion delivered in the store the
536
+ * subscriber subscribed in. The store is re-entered rather than every async
537
+ * context with it: the agent's own is what its trace id is read from, and a
538
+ * reply whose context is already that store pays nothing more.
539
+ */
540
+ function inSubscriberContext(source, asyncLocalStorage) {
541
+ return new Observable((subscriber) => {
542
+ const store = asyncLocalStorage.getStore();
543
+ return source.subscribe({
544
+ next: (value) => asyncLocalStorage.run(store, () => subscriber.next(value)),
545
+ error: (error) => asyncLocalStorage.run(store, () => subscriber.error(error)),
546
+ complete: () => asyncLocalStorage.run(store, () => subscriber.complete()),
547
+ });
432
548
  });
433
549
  }
434
550
  /**
@@ -22,13 +22,25 @@ export function encodeOtlpJson(resource, scope, spans) {
22
22
  ],
23
23
  });
24
24
  }
25
+ /**
26
+ * A string as a protobuf `string` field holds it, which is what the JSON
27
+ * encoding stands for. Half a surrogate pair names no character:
28
+ * `JSON.stringify` writes it as a `\ud83d` escape, and a receiver that reads
29
+ * JSON strings strictly refuses the whole request for it - every span of the
30
+ * batch, whoever's request put it there. It becomes U+FFFD, which is what
31
+ * the protobuf encoding's UTF-8 makes of it. With the `u` flag a whole pair
32
+ * is one character, outside the class.
33
+ */
34
+ function jsonText(value) {
35
+ return value.replace(/[\ud800-\udfff]/gu, "\ufffd");
36
+ }
25
37
  function jsonSpan(span) {
26
38
  return {
27
39
  traceId: span.traceId,
28
40
  spanId: span.spanId,
29
41
  ...(span.parentSpanId ? { parentSpanId: span.parentSpanId } : {}),
30
42
  ...(span.traceState ? { traceState: span.traceState } : {}),
31
- name: span.name,
43
+ name: jsonText(span.name),
32
44
  kind: span.kind,
33
45
  startTimeUnixNano: span.startTimeUnixNano.toString(),
34
46
  endTimeUnixNano: span.endTimeUnixNano.toString(),
@@ -37,23 +49,28 @@ function jsonSpan(span) {
37
49
  ? { droppedAttributesCount: span.droppedAttributesCount }
38
50
  : {}),
39
51
  ...(span.events.length > 0 ? { events: span.events.map(jsonEvent) } : {}),
40
- ...(span.status ? { status: span.status } : {}),
52
+ ...(span.status ? { status: jsonStatus(span.status) } : {}),
41
53
  flags: span.flags,
42
54
  };
43
55
  }
56
+ function jsonStatus({ code, message }) {
57
+ return message === undefined
58
+ ? { code }
59
+ : { code, message: jsonText(message) };
60
+ }
44
61
  function jsonEvent(event) {
45
62
  return {
46
63
  timeUnixNano: event.timeUnixNano.toString(),
47
- name: event.name,
64
+ name: jsonText(event.name),
48
65
  attributes: event.attributes.map(jsonKeyValue),
49
66
  };
50
67
  }
51
68
  function jsonKeyValue({ key, value }) {
52
- return { key, value: jsonAnyValue(value) };
69
+ return { key: jsonText(key), value: jsonAnyValue(value) };
53
70
  }
54
71
  function jsonAnyValue(value) {
55
72
  if (typeof value === "string") {
56
- return { stringValue: value };
73
+ return { stringValue: jsonText(value) };
57
74
  }
58
75
  if (typeof value === "boolean") {
59
76
  return { boolValue: value };
@@ -59,10 +59,11 @@ export declare function requestSnapshotSpans(snapshot: RequestSnapshot, context:
59
59
  * A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
60
60
  * - INTERNAL for a scheduled one, which nothing sent - and its tree under
61
61
  * it. A job reports under the trace id of the operation that enqueued it,
62
- * so it lands in that trace; nothing records which span enqueued it, so it
63
- * has no parent there. Without `withTree`, the run's span alone.
62
+ * so it lands in that trace, and under the span that enqueued it when it was
63
+ * handed on with a `traceparent` - see `handedOnTraceContext`. Without
64
+ * `withTree`, the run's span alone.
64
65
  */
65
- export declare function jobSnapshotSpans(snapshot: JobSnapshot, withTree?: boolean): OtlpSpan[];
66
+ export declare function jobSnapshotSpans(snapshot: JobSnapshot, context: TraceContext | undefined, withTree?: boolean): OtlpSpan[];
66
67
  /**
67
68
  * Attributes from a flat record, in its order, without the keys that hold
68
69
  * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
@@ -115,11 +115,12 @@ export function requestSnapshotSpans(snapshot, context, withTree = true) {
115
115
  * A queue job or a scheduled run as OTLP spans: a CONSUMER span for the run
116
116
  * - INTERNAL for a scheduled one, which nothing sent - and its tree under
117
117
  * it. A job reports under the trace id of the operation that enqueued it,
118
- * so it lands in that trace; nothing records which span enqueued it, so it
119
- * has no parent there. Without `withTree`, the run's span alone.
118
+ * so it lands in that trace, and under the span that enqueued it when it was
119
+ * handed on with a `traceparent` - see `handedOnTraceContext`. Without
120
+ * `withTree`, the run's span alone.
120
121
  */
121
- export function jobSnapshotSpans(snapshot, withTree = true) {
122
- const traceId = w3cTraceIdOf(snapshot.traceId);
122
+ export function jobSnapshotSpans(snapshot, context, withTree = true) {
123
+ const traceId = context?.traceId ?? w3cTraceIdOf(snapshot.traceId);
123
124
  const startNs = epochNanos(snapshot.calledAt);
124
125
  const scheduled = SCHEDULER_QUEUES.has(snapshot.queueName);
125
126
  const tags = {
@@ -141,6 +142,9 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
141
142
  const run = {
142
143
  traceId,
143
144
  spanId: randomSpanId(),
145
+ ...(context
146
+ ? { parentSpanId: context.parentSpanId, traceState: context.traceState }
147
+ : {}),
144
148
  name: `${snapshot.queueName} ${snapshot.name}`,
145
149
  kind: scheduled ? SpanKind.INTERNAL : SpanKind.CONSUMER,
146
150
  startTimeUnixNano: startNs,
@@ -148,7 +152,7 @@ export function jobSnapshotSpans(snapshot, withTree = true) {
148
152
  ...toAttributes(tags),
149
153
  events: [],
150
154
  ...(failed ? { status: errorStatus(snapshot.error) } : {}),
151
- flags: LOCAL_PARENT_FLAGS,
155
+ flags: context ? REMOTE_PARENT_FLAGS : LOCAL_PARENT_FLAGS,
152
156
  };
153
157
  const spans = [run];
154
158
  for (const node of withTree ? snapshot.traces ?? [] : []) {
@@ -198,10 +202,14 @@ function appendNodeSpans(spans, node, traceId, parentSpanId, operationStartNs) {
198
202
  traceId,
199
203
  spanId: complete.spanId ? w3cSpanIdOf(complete.spanId) : randomSpanId(),
200
204
  parentSpanId,
201
- name: complete.name ??
202
- (client
205
+ // A manual span's name is whatever `createSpan` was given. Held to a
206
+ // string, as `toAttributes` holds the tags: anything else would fail
207
+ // the encoding, and with it the whole batch of every request's spans.
208
+ name: typeof complete.name === "string"
209
+ ? complete.name
210
+ : client
203
211
  ? complete.methodKey
204
- : `${complete.className}.${complete.methodKey}`),
212
+ : `${complete.className}.${complete.methodKey}`,
205
213
  kind: client ? SpanKind.CLIENT : SpanKind.INTERNAL,
206
214
  startTimeUnixNano: startNs,
207
215
  endTimeUnixNano: endNs,
@@ -86,6 +86,9 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
86
86
  /**
87
87
  * Queues a finished job's spans - its own span, and with `withTree` the
88
88
  * spans under it. Never throws into the caller.
89
+ *
90
+ * Left out, as a request is, when the trace it was handed on in is one an
91
+ * OpenTelemetry SDK in this process sampled out.
89
92
  */
90
93
  exportJobSnapshot(snapshot: JobSnapshot, withTree?: boolean): void;
91
94
  /**
@@ -57,6 +57,22 @@ const RETRY_MAX_MS = 60_000;
57
57
  const RETRY_AFTER_MAX_MS = 5 * 60_000;
58
58
  /** How long an idle connection to the receiver is kept for the next batch. */
59
59
  const KEEP_ALIVE_IDLE_MS = 30_000;
60
+ /**
61
+ * The most of a receiver's reply that is read. Only its first 300 characters
62
+ * are ever shown, and it is held and decoded on the application's thread:
63
+ * past this, the reading stops and the connection goes with it, and the
64
+ * status is acted on as it stands.
65
+ */
66
+ const MAX_REPLY_BYTES = 64 * 1024;
67
+ /**
68
+ * The most interim (1xx) replies one export sits through. Nothing it sends
69
+ * asks for one, and each is parsed on the application's thread: how many of
70
+ * them that thread works through is not the receiver's to choose. A proxy's
71
+ * few ahead of the answer still pass.
72
+ */
73
+ const MAX_INTERIM_REPLIES = 8;
74
+ /** The longest a timer runs; a longer delay would fire at once instead. */
75
+ const MAX_TIMER_MS = 2 ** 31 - 1;
60
76
  /**
61
77
  * Exports what the agent records as OpenTelemetry traces, over OTLP/HTTP, to
62
78
  * whatever receiver `otlp` names - a collector, Jaeger, Tempo, Honeycomb, a
@@ -210,13 +226,20 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
210
226
  /**
211
227
  * Queues a finished job's spans - its own span, and with `withTree` the
212
228
  * spans under it. Never throws into the caller.
229
+ *
230
+ * Left out, as a request is, when the trace it was handed on in is one an
231
+ * OpenTelemetry SDK in this process sampled out.
213
232
  */
214
233
  exportJobSnapshot(snapshot, withTree = true) {
215
234
  if (!this.settings) {
216
235
  return;
217
236
  }
218
237
  try {
219
- this.enqueue(jobSnapshotSpans(snapshot, withTree));
238
+ const context = this.operationTraceRegistry.traceContextOf(snapshot);
239
+ if (context && !context.sampled) {
240
+ return;
241
+ }
242
+ this.enqueue(jobSnapshotSpans(snapshot, context, withTree));
220
243
  }
221
244
  catch (error) {
222
245
  this.reportMappingFailure(error);
@@ -400,9 +423,8 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
400
423
  },
401
424
  }, (response) => {
402
425
  const chunks = [];
403
- response.on("data", (chunk) => chunks.push(chunk));
404
- response.on("error", reject);
405
- response.on("end", () => {
426
+ let received = 0;
427
+ const settle = () => {
406
428
  const retryAfter = response.headers["retry-after"];
407
429
  resolve({
408
430
  status: response.statusCode ?? 0,
@@ -410,12 +432,55 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
410
432
  ? retryAfter[0]
411
433
  : retryAfter,
412
434
  contentType: response.headers["content-type"],
413
- body: Buffer.concat(chunks).toString("utf8"),
435
+ body: Buffer.concat(chunks, Math.min(received, MAX_REPLY_BYTES)).toString("utf8"),
414
436
  });
437
+ // A reply that ends before the batch has been written leaves a
438
+ // socket that is never pooled, timed out or closed again.
439
+ if (!request.writableFinished) {
440
+ request.destroy();
441
+ }
442
+ };
443
+ response.on("data", (chunk) => {
444
+ if (received >= MAX_REPLY_BYTES) {
445
+ return;
446
+ }
447
+ chunks.push(chunk);
448
+ received += chunk.length;
449
+ if (received >= MAX_REPLY_BYTES) {
450
+ response.destroy();
451
+ settle();
452
+ }
415
453
  });
454
+ response.on("error", reject);
455
+ response.on("end", settle);
416
456
  });
417
457
  request.on("error", reject);
418
- request.setTimeout(settings.timeoutMs, () => request.destroy(Object.assign(new Error(`no answer within ${settings.timeoutMs} ms`), { code: "ETIMEDOUT" })));
458
+ // A 101 with `Connection: Upgrade` is no response to Node: it emits
459
+ // only this, and destroys the socket without an error. Unheard, the
460
+ // export would never settle and every later one would wait behind it.
461
+ // No upgrade was asked for: it is a status like any other refusal.
462
+ request.on("upgrade", (response, socket) => {
463
+ socket.destroy();
464
+ resolve({
465
+ status: response.statusCode ?? 101,
466
+ retryAfter: undefined,
467
+ contentType: undefined,
468
+ body: "",
469
+ });
470
+ });
471
+ // A limit on the export as a whole, which is what `timeoutMillis` is.
472
+ // `request.setTimeout` measures silence on the socket instead and
473
+ // starts over with every byte: a receiver that went on writing -
474
+ // interim replies, a body a byte at a time - would hold this export,
475
+ // and every one queued behind it, open for as long as it liked.
476
+ const deadline = setTimeout(() => request.destroy(Object.assign(new Error(`no answer within ${settings.timeoutMs} ms`), { code: "ETIMEDOUT" })), Math.min(settings.timeoutMs, MAX_TIMER_MS));
477
+ request.on("close", () => clearTimeout(deadline));
478
+ let interimReplies = 0;
479
+ request.on("information", () => {
480
+ if (++interimReplies > MAX_INTERIM_REPLIES) {
481
+ request.destroy(new Error(`it sent more than ${MAX_INTERIM_REPLIES} interim (1xx) replies`));
482
+ }
483
+ });
419
484
  request.end(body);
420
485
  });
421
486
  }
@@ -45,12 +45,14 @@ export interface OutgoingTrace {
45
45
  /**
46
46
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
47
47
  * own: `undici` - which is also what the global `fetch` runs on - and the
48
- * `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
49
- * so there is no HTTP client to keep up with.
48
+ * `node:http` client that axios, got and most SDKs sit on. No HTTP client is
49
+ * patched, so there is none to keep up with.
50
50
  *
51
51
  * The handlers run synchronously inside the call that makes the request, which
52
52
  * is what puts the span under the right parent; the span is then carried to
53
- * the completion events on the request object itself.
53
+ * the completion events on the request object itself. An undici request a
54
+ * pool queued, or a redirect it follows, is created later, from a socket's
55
+ * events: `patchUndiciDispatch` puts it back in its caller's context first.
54
56
  *
55
57
  * Returns the function that removes every subscription.
56
58
  */
@@ -65,4 +67,6 @@ getRedactor?: () => LogRedactor | null,
65
67
  * `traceContext` not off, while the agent reports to NestJS Observe (see
66
68
  * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
67
69
  */
68
- traceContextOn?: () => boolean): () => void;
70
+ traceContextOn?: () => boolean,
71
+ /** `http.queryParamsObfuscateRegex`, global: held to every recorded URL. */
72
+ obfuscateUrl?: RegExp): () => void;
@@ -10,12 +10,14 @@ const TRACESTATE_HEADER = "tracestate";
10
10
  /**
11
11
  * Spans for outbound HTTP, from the diagnostics channels Node publishes on its
12
12
  * own: `undici` - which is also what the global `fetch` runs on - and the
13
- * `node:http` client that axios, got and most SDKs sit on. Nothing is patched,
14
- * so there is no HTTP client to keep up with.
13
+ * `node:http` client that axios, got and most SDKs sit on. No HTTP client is
14
+ * patched, so there is none to keep up with.
15
15
  *
16
16
  * The handlers run synchronously inside the call that makes the request, which
17
17
  * is what puts the span under the right parent; the span is then carried to
18
- * the completion events on the request object itself.
18
+ * the completion events on the request object itself. An undici request a
19
+ * pool queued, or a redirect it follows, is created later, from a socket's
20
+ * events: `patchUndiciDispatch` puts it back in its caller's context first.
19
21
  *
20
22
  * Returns the function that removes every subscription.
21
23
  */
@@ -30,7 +32,9 @@ getRedactor = () => null,
30
32
  * `traceContext` not off, while the agent reports to NestJS Observe (see
31
33
  * `ObserveAgentSharedBuffer.isReporting`). Off unless given.
32
34
  */
33
- traceContextOn = () => false) {
35
+ traceContextOn = () => false,
36
+ /** `http.queryParamsObfuscateRegex`, global: held to every recorded URL. */
37
+ obfuscateUrl) {
34
38
  const spans = new WeakMap();
35
39
  /**
36
40
  * Span ids minted for a `node:http` request at `created`, where its
@@ -67,7 +71,7 @@ traceContextOn = () => false) {
67
71
  }
68
72
  const span = recorder.open("http", `${method} ${host}`, {
69
73
  "http.method": method,
70
- "http.url": redactUrlQuery(url, getRedactor()),
74
+ "http.url": redactUrlQuery(url, getRedactor(), obfuscateUrl),
71
75
  }, presetSpanId);
72
76
  if (span) {
73
77
  spans.set(request, span);
@@ -101,8 +105,11 @@ traceContextOn = () => false) {
101
105
  }
102
106
  if (sendsTraceContext() &&
103
107
  !hasUndiciHeader(request.headers, TRACEPARENT_HEADER)) {
108
+ // Sampled when the operation is recorded, as for node:http, not when
109
+ // this call got a span: one that opened as many spans as it may is
110
+ // still recorded, and its callee must not drop the trace.
104
111
  const span = spans.get(request);
105
- const headers = traceContextHeaders(trace, span?.spanId, span !== undefined);
112
+ const headers = traceContextHeaders(trace, span?.spanId, recorder.isRecording());
106
113
  request.addHeader(TRACEPARENT_HEADER, headers.traceparent);
107
114
  if (headers.tracestate &&
108
115
  !hasUndiciHeader(request.headers, TRACESTATE_HEADER)) {
@@ -104,6 +104,21 @@ export function activateLlmFetchObserver(recorder, options = {}) {
104
104
  }
105
105
  };
106
106
  }
107
+ /**
108
+ * Cancels a provider's stream once the stream handed to the caller in its
109
+ * place can no longer be read. undici does this for an unread response it
110
+ * created, but not for one whose body is locked, as the provider's is once
111
+ * it is read through here: a reply the application drops would otherwise
112
+ * hold its socket, its buffered body and its span for good.
113
+ */
114
+ const abandonedBodies = new FinalizationRegistry((release) => {
115
+ try {
116
+ release();
117
+ }
118
+ catch {
119
+ /* thrown from here it would be an uncaught exception in the host */
120
+ }
121
+ });
107
122
  async function observeCall(original, input, init, call) {
108
123
  const startedAt = performance.now();
109
124
  const holder = {};
@@ -150,6 +165,8 @@ async function observeCall(original, input, init, call) {
150
165
  return;
151
166
  }
152
167
  tagged = true;
168
+ // Read to its end, failed or cancelled: nothing is left to release.
169
+ abandonedBodies.unregister(holder);
153
170
  let usage = {};
154
171
  try {
155
172
  usage = reader.finish();
@@ -164,6 +181,21 @@ async function observeCall(original, input, init, call) {
164
181
  // go on generating - and billing - a completion nobody reads.
165
182
  const source = response.body.getReader();
166
183
  const body = new ReadableStream({
184
+ start(controller) {
185
+ // Failed between two reads - the call's signal aborted, the
186
+ // connection reset: the caller hears of it now, as from plain
187
+ // `fetch`, not at a read that may never come. A stream piped on
188
+ // (`Readable.fromWeb`) stops reading while its buffer is full and
189
+ // waits on `closed` to hang up. A normal end or a cancel fulfils
190
+ // `closed`, and `error` does nothing to a stream already done.
191
+ // Held weakly: `source` is reachable from `abandonedBodies`, and so
192
+ // is what waits on it - a strong hold here would keep `body` alive.
193
+ const handle = new WeakRef(controller);
194
+ source.closed.catch((error) => {
195
+ finish();
196
+ handle.deref()?.error(error);
197
+ });
198
+ },
167
199
  async pull(controller) {
168
200
  let chunk;
169
201
  try {
@@ -192,7 +224,36 @@ async function observeCall(original, input, init, call) {
192
224
  return source.cancel(reason);
193
225
  },
194
226
  }, { highWaterMark: 0 });
195
- return rewrap(response, body);
227
+ let wrapped;
228
+ try {
229
+ wrapped = rewrap(response, body);
230
+ }
231
+ catch {
232
+ // The `Response` constructor refuses what `fetch` takes off the wire: a
233
+ // status past 599, a reason phrase with a control character or past
234
+ // Latin-1. The caller gets the reply as it came, tagged without its
235
+ // usage. Nothing has been read from it - `pull` runs on demand - so its
236
+ // body is whole once the lock is given back. Tagged first: giving the
237
+ // lock back rejects `closed`, which `start` above would act on.
238
+ tagged = true;
239
+ source.releaseLock();
240
+ tag({}, stream);
241
+ return response;
242
+ }
243
+ // Watching `body`, not the response: a caller that keeps only the body,
244
+ // or a clone, can still read it. Nothing registered may reach `body`, or
245
+ // it would never be collected.
246
+ abandonedBodies.register(body, () => {
247
+ try {
248
+ finish();
249
+ }
250
+ finally {
251
+ source
252
+ .cancel("Response object has been garbage collected")
253
+ .catch(() => undefined);
254
+ }
255
+ }, holder);
256
+ return wrapped;
196
257
  }
197
258
  /** The same response, reading through `body`. */
198
259
  function rewrap(response, body) {
@@ -8,13 +8,25 @@
8
8
  */
9
9
  /** The provider a call to `host` goes to, or undefined when it is not one. */
10
10
  export declare function llmProviderForHost(host: string, extraHosts?: ReadonlySet<string>): string | undefined;
11
+ /**
12
+ * The `model` of the outermost object of a JSON document, or of as much of
13
+ * one as `text` holds - and nothing for text that does not open with `{`.
14
+ *
15
+ * A scan rather than `JSON.parse`, which a cut-off document would fail, and
16
+ * rather than a search for `"model":`, which finds that key at any depth: a
17
+ * tool call's input, a tool result or a JSON-mode completion can carry one,
18
+ * and what it holds is the prompt's, not the model's. Strings are skipped
19
+ * whole, so a brace or a key inside one counts for nothing. Linear, and done
20
+ * at the first `model` key of the outermost object - where clients put it.
21
+ */
22
+ export declare function topLevelModel(text: string): string | undefined;
11
23
  /**
12
24
  * The model a JSON request body names, read from its first 64 KB.
13
25
  *
14
- * A pattern rather than `JSON.parse`: the body is the application's prompt,
15
- * often far larger than the one field wanted, and every client puts `model`
16
- * near the top. Bodies that are streams or forms are not read at all - reading
17
- * them would consume what the request is about to send.
26
+ * Read with `topLevelModel`: the body is the application's prompt, often far
27
+ * larger than the one field wanted, and every client puts `model` near the
28
+ * top. Bodies that are streams or forms are not read at all - reading them
29
+ * would consume what the request is about to send.
18
30
  */
19
31
  export declare function modelFromRequestBody(body: unknown): string | undefined;
20
32
  /**