@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.
Files changed (109) hide show
  1. package/README.md +55 -2
  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 +201 -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 +10 -4
  8. package/dist/cli/agent-notes.js +16 -4
  9. package/dist/cli/link.js +51 -4
  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/package-manager.d.ts +6 -0
  14. package/dist/cli/package-manager.js +60 -3
  15. package/dist/cli/project-files.d.ts +62 -1
  16. package/dist/cli/project-files.js +229 -7
  17. package/dist/cli/project-setup.d.ts +6 -0
  18. package/dist/cli/project-setup.js +14 -1
  19. package/dist/cli/wire-application.js +6 -0
  20. package/dist/custom-metrics/counter.d.ts +13 -2
  21. package/dist/custom-metrics/counter.js +33 -16
  22. package/dist/custom-metrics/finite-value.util.d.ts +14 -0
  23. package/dist/custom-metrics/finite-value.util.js +33 -1
  24. package/dist/custom-metrics/gauge.d.ts +2 -0
  25. package/dist/custom-metrics/gauge.js +41 -17
  26. package/dist/custom-metrics/label-values.util.d.ts +37 -0
  27. package/dist/custom-metrics/label-values.util.js +51 -0
  28. package/dist/custom-metrics/summary.d.ts +23 -0
  29. package/dist/custom-metrics/summary.js +90 -12
  30. package/dist/instrument/create-instance-decorator.instrument.js +504 -116
  31. package/dist/instrument/raw-receiver.d.ts +6 -0
  32. package/dist/instrument/raw-receiver.js +32 -0
  33. package/dist/interfaces/observe-options.interface.d.ts +17 -6
  34. package/dist/objectives/objectives.registry.js +12 -0
  35. package/dist/observe.module.js +119 -3
  36. package/dist/otlp/otlp-encoders.js +22 -5
  37. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  38. package/dist/otlp/otlp-span.mapper.js +26 -4
  39. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  40. package/dist/otlp/otlp-trace-exporter.service.js +295 -43
  41. package/dist/outgoing/http.integration.d.ts +8 -4
  42. package/dist/outgoing/http.integration.js +49 -17
  43. package/dist/outgoing/llm/llm-fetch.integration.js +62 -1
  44. package/dist/outgoing/llm/llm-providers.d.ts +16 -4
  45. package/dist/outgoing/llm/llm-providers.js +72 -22
  46. package/dist/outgoing/llm/llm-usage.d.ts +11 -6
  47. package/dist/outgoing/llm/llm-usage.js +72 -25
  48. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  49. package/dist/outgoing/mongodb.integration.js +93 -18
  50. package/dist/outgoing/mssql.integration.js +25 -6
  51. package/dist/outgoing/mysql2.integration.js +17 -1
  52. package/dist/outgoing/outgoing-observe-agent.service.js +20 -4
  53. package/dist/outgoing/outgoing-span.recorder.js +17 -3
  54. package/dist/outgoing/pg.integration.d.ts +3 -2
  55. package/dist/outgoing/pg.integration.js +39 -11
  56. package/dist/outgoing/sql-statement.util.js +139 -21
  57. package/dist/outgoing/undici.integration.d.ts +13 -0
  58. package/dist/outgoing/undici.integration.js +68 -0
  59. package/dist/protocols/bull-observe-agent.service.js +23 -12
  60. package/dist/protocols/deferred-trace-completion.d.ts +17 -3
  61. package/dist/protocols/deferred-trace-completion.js +76 -9
  62. package/dist/protocols/graphql-observe-agent.service.d.ts +97 -6
  63. package/dist/protocols/graphql-observe-agent.service.js +354 -19
  64. package/dist/protocols/graphql-operation-parser.js +111 -26
  65. package/dist/protocols/http-observe-agent.service.d.ts +50 -9
  66. package/dist/protocols/http-observe-agent.service.js +220 -59
  67. package/dist/protocols/job-trace-runner.d.ts +42 -3
  68. package/dist/protocols/job-trace-runner.js +197 -36
  69. package/dist/protocols/queue-observe-agent.service.js +44 -20
  70. package/dist/protocols/rpc-observe-agent.service.d.ts +111 -8
  71. package/dist/protocols/rpc-observe-agent.service.js +332 -56
  72. package/dist/protocols/ws-observe-agent.service.d.ts +55 -5
  73. package/dist/protocols/ws-observe-agent.service.js +227 -21
  74. package/dist/services/index.d.ts +1 -1
  75. package/dist/services/index.js +1 -1
  76. package/dist/services/logger-patcher.service.js +16 -7
  77. package/dist/services/operation-trace.registry.d.ts +58 -1
  78. package/dist/services/operation-trace.registry.js +576 -63
  79. package/dist/services/stdout-forwarder.service.d.ts +69 -0
  80. package/dist/services/stdout-forwarder.service.js +308 -51
  81. package/dist/services/tracer.service.d.ts +39 -11
  82. package/dist/services/tracer.service.js +145 -36
  83. package/dist/utils/capture-request.util.d.ts +3 -1
  84. package/dist/utils/capture-request.util.js +128 -12
  85. package/dist/utils/context-accessor.util.d.ts +16 -0
  86. package/dist/utils/context-accessor.util.js +28 -0
  87. package/dist/utils/default-trace-id-generator.util.js +5 -7
  88. package/dist/utils/error-stack.util.d.ts +13 -0
  89. package/dist/utils/error-stack.util.js +166 -0
  90. package/dist/utils/fit-to-length.util.js +33 -10
  91. package/dist/utils/log-line.parser.d.ts +22 -0
  92. package/dist/utils/log-line.parser.js +20 -7
  93. package/dist/utils/log-redactor.d.ts +14 -0
  94. package/dist/utils/log-redactor.js +690 -65
  95. package/dist/utils/operation-state.util.d.ts +39 -0
  96. package/dist/utils/operation-state.util.js +50 -0
  97. package/dist/utils/redact-url-query.d.ts +37 -4
  98. package/dist/utils/redact-url-query.js +197 -32
  99. package/dist/utils/sensitive-keys.d.ts +4 -1
  100. package/dist/utils/sensitive-keys.js +48 -10
  101. package/dist/utils/shared-hook-slot.util.d.ts +48 -0
  102. package/dist/utils/shared-hook-slot.util.js +103 -0
  103. package/dist/utils/source-context.util.d.ts +14 -0
  104. package/dist/utils/source-context.util.js +142 -43
  105. package/dist/utils/source-map-resolver.util.js +33 -6
  106. package/dist/utils/store-copy.util.d.ts +10 -0
  107. package/dist/utils/store-copy.util.js +43 -0
  108. package/dist/utils/trace-context.util.js +21 -6
  109. package/package.json +2 -2
@@ -0,0 +1,6 @@
1
+ export declare function registerRawReceiver(proxy: object, instance: object): void;
2
+ /**
3
+ * The instance a provider's prototype methods have to be applied to, when
4
+ * that is not the provider itself - `undefined` for anything else.
5
+ */
6
+ export declare function rawReceiverOf(provider: object): object | undefined;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The instance behind each proxy the instance decorator hands out for a class
3
+ * whose methods only the instance itself can be the receiver of: one with
4
+ * private members, or one built on a slot-backed built-in.
5
+ *
6
+ * The proxy runs every method read through it against that instance. A
7
+ * method read anywhere else - off the class prototype - and applied to the
8
+ * proxy gets no such help, and throws on its first `this.#x`. Whoever has to
9
+ * apply one that way asks here for the receiver to use instead.
10
+ *
11
+ * Kept out of the decorator's module, which the package exports in full: the
12
+ * instance behind a proxy is the agent's to hand over, not an application's
13
+ * to look up. Module-level and weak, so a proxy names its instance for as
14
+ * long as the two live, whichever agent made it.
15
+ */
16
+ const rawReceivers = new WeakMap();
17
+ export function registerRawReceiver(proxy, instance) {
18
+ rawReceivers.set(proxy, instance);
19
+ }
20
+ /**
21
+ * The instance a provider's prototype methods have to be applied to, when
22
+ * that is not the provider itself - `undefined` for anything else.
23
+ */
24
+ export function rawReceiverOf(provider) {
25
+ let receiver = rawReceivers.get(provider);
26
+ // A provider handed out a second time (`useExisting`, a factory returning
27
+ // another provider) is a proxy of the first proxy.
28
+ while (receiver !== undefined && rawReceivers.has(receiver)) {
29
+ receiver = rawReceivers.get(receiver);
30
+ }
31
+ return receiver;
32
+ }
@@ -16,7 +16,9 @@ export interface RedactionOptions {
16
16
  * knows about - internal token prefixes, customer identifiers, and so on.
17
17
  *
18
18
  * Patterns are applied with the global flag whether or not you set it, so a
19
- * pattern cannot silently mask just the first occurrence in a line.
19
+ * pattern cannot silently mask just the first occurrence in a line. Each is
20
+ * applied as a copy, so the `lastIndex` of a pattern your own code steps
21
+ * through with `exec()` is never moved.
20
22
  */
21
23
  patterns?: RegExp[];
22
24
  /**
@@ -38,7 +40,8 @@ export interface RedactionOptions {
38
40
  replacement?: string;
39
41
  /**
40
42
  * Whether to apply the built-in patterns - bearer tokens, JWTs, AWS key ids,
41
- * PEM private keys, `key=value` secrets and Luhn-valid card numbers.
43
+ * PEM private keys, `key=value` secrets, the password in a URL
44
+ * (`scheme://user:password@host`) and Luhn-valid card numbers.
42
45
  *
43
46
  * Disable only if you are replacing them wholesale with `patterns`; there is
44
47
  * no supported configuration in which forwarding logs unredacted is a good
@@ -51,7 +54,9 @@ export interface CreateObserveModuleOptions {
51
54
  /**
52
55
  * The trace ID key used to identify the trace in the context.
53
56
  * This key is used to store the trace ID in the context for later retrieval.
54
- * If not provided, the default key 'traceId' will be used.
57
+ * If not provided, the default key 'traceId' will be used. An attribute of
58
+ * the same name returned by a `setAttributes` callback is ignored, with a
59
+ * warning, so a sender cannot choose the trace id.
55
60
  * @default 'traceId'
56
61
  */
57
62
  traceIdKey?: string;
@@ -489,7 +494,9 @@ export interface ObserveOptions {
489
494
  * Applied *in addition to* the built-in redaction, which always masks the
490
495
  * values of well-known sensitive parameters (`token`, `password`, `code`,
491
496
  * `signature`, ...) whether or not this is set. Use it for the parameters
492
- * only your application knows are sensitive.
497
+ * only your application knows are sensitive. It is matched against every
498
+ * URL the agent records: the request's own, a URL in a captured request
499
+ * header (`referer`, ...) and the URL of an outgoing HTTP call.
493
500
  * @default undefined
494
501
  */
495
502
  queryParamsObfuscateRegex?: RegExp;
@@ -574,7 +581,10 @@ export interface ObserveOptions {
574
581
  *
575
582
  * Matching on a field name skips the whole operation the field leads, not
576
583
  * just that field: an operation is measured end to end, so it is traced or
577
- * it is not.
584
+ * it is not. Over HTTP the request's trace is dropped with it, provider and
585
+ * outgoing spans included, unless the request already names an operation
586
+ * of its own; in a batch, the first operation decides for the request.
587
+ * `setAttributes` still runs for an ignored operation.
578
588
  * @example (info) => info.fieldName === 'healthcheck'
579
589
  */
580
590
  ignore?: (info: GraphQLResolveInfoLike) => boolean;
@@ -602,7 +612,8 @@ export interface ObserveOptions {
602
612
  * Only consulted for operations that are *not* already inside an HTTP
603
613
  * trace - a query over HTTP takes its user id from `http.getUserId`, which
604
614
  * sees the whole request. This covers the transports that have no such
605
- * hook, subscriptions over a websocket in particular.
615
+ * hook. Operations Apollo runs over `graphql-ws` are not traced yet, so
616
+ * it is not consulted for those.
606
617
  * @example (context) => context.req?.user?.id
607
618
  * @default undefined
608
619
  */
@@ -31,6 +31,7 @@ const MAX_SPANS_SEARCHED = 200;
31
31
  const MAX_OBJECTIVES_PER_HANDLER = 10;
32
32
  const MAX_HANDLER_LENGTH = 255;
33
33
  const MAX_ROUTE_LENGTH = 255;
34
+ const MAX_METHOD_LENGTH = 10;
34
35
  /** `@nestjs/common`'s METHOD_METADATA - what `@Get()`, `@Post()` and the rest write. */
35
36
  const METHOD_METADATA = "method";
36
37
  /** `@nestjs/common`'s PATH_METADATA and VERSION_METADATA, on the controller and the handler. */
@@ -176,6 +177,17 @@ let ObjectivesRegistry = class ObjectivesRegistry {
176
177
  }
177
178
  return undefined;
178
179
  }
180
+ // Only a handler routed for every method is declared under the request's
181
+ // own, and Node parses one longer than the collector takes: UNSUBSCRIBE.
182
+ // Nothing is stated, so the next request with an ordinary method declares
183
+ // the route as usual.
184
+ if (method !== undefined && method.length > MAX_METHOD_LENGTH) {
185
+ if (!this.refusedRoutes.has(route)) {
186
+ this.refusedRoutes.add(route);
187
+ this.logger.warn(`@Objective on ${handler} not declared for a ${method} request: a method is at most ${MAX_METHOD_LENGTH} characters.`);
188
+ }
189
+ return undefined;
190
+ }
179
191
  const stated = this.statedAt.get(route);
180
192
  if (stated !== undefined && now - stated < RESTATE_EVERY_MS) {
181
193
  return undefined;
@@ -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 };
@@ -67,6 +67,8 @@ export declare function jobSnapshotSpans(snapshot: JobSnapshot, context: TraceCo
67
67
  /**
68
68
  * Attributes from a flat record, in its order, without the keys that hold
69
69
  * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
70
+ * A string longer than `MAX_ATTRIBUTE_VALUE_LENGTH` is cut to a copy of its
71
+ * head that ends in a hash of the whole (see `fitToLength`).
70
72
  */
71
73
  export declare function toAttributes(record: Record<string, OtlpAttributeValue | undefined | null>): {
72
74
  attributes: OtlpAttribute[];
@@ -1,3 +1,4 @@
1
+ import { fitToLength } from "../utils/fit-to-length.util.js";
1
2
  import { randomSpanId, w3cSpanIdOf, w3cTraceIdOf, } from "../utils/trace-context.util.js";
2
3
  /** OTLP's `Span.SpanKind`. */
3
4
  export const SpanKind = {
@@ -24,6 +25,16 @@ const REMOTE_PARENT_FLAGS = LOCAL_PARENT_FLAGS | IS_REMOTE_FLAG;
24
25
  * OpenTelemetry SDKs' default limit.
25
26
  */
26
27
  const MAX_ATTRIBUTES_PER_SPAN = 128;
28
+ /**
29
+ * The most of a string attribute that is exported, as the OpenTelemetry
30
+ * SDKs' `OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT` would cut it.
31
+ *
32
+ * A tag is as long as whatever it was made from, and some are made from
33
+ * what a client sent: an outgoing call's `url.full` with the client's text
34
+ * in its path, a GraphQL document. Uncut, each one waited in the export
35
+ * queue, and in every retry of it, at its full length.
36
+ */
37
+ const MAX_ATTRIBUTE_VALUE_LENGTH = 16 * 1024;
27
38
  /**
28
39
  * The span classes the outgoing integrations open - see
29
40
  * `OutgoingSpanRecorder.open` - which are calls out of the process: CLIENT
@@ -202,10 +213,14 @@ function appendNodeSpans(spans, node, traceId, parentSpanId, operationStartNs) {
202
213
  traceId,
203
214
  spanId: complete.spanId ? w3cSpanIdOf(complete.spanId) : randomSpanId(),
204
215
  parentSpanId,
205
- name: complete.name ??
206
- (client
216
+ // A manual span's name is whatever `createSpan` was given. Held to a
217
+ // string, as `toAttributes` holds the tags: anything else would fail
218
+ // the encoding, and with it the whole batch of every request's spans.
219
+ name: typeof complete.name === "string"
220
+ ? complete.name
221
+ : client
207
222
  ? complete.methodKey
208
- : `${complete.className}.${complete.methodKey}`),
223
+ : `${complete.className}.${complete.methodKey}`,
209
224
  kind: client ? SpanKind.CLIENT : SpanKind.INTERNAL,
210
225
  startTimeUnixNano: startNs,
211
226
  endTimeUnixNano: endNs,
@@ -302,6 +317,8 @@ function errorStatus(error) {
302
317
  /**
303
318
  * Attributes from a flat record, in its order, without the keys that hold
304
319
  * nothing - and at most `MAX_ATTRIBUTES_PER_SPAN` of them, the rest counted.
320
+ * A string longer than `MAX_ATTRIBUTE_VALUE_LENGTH` is cut to a copy of its
321
+ * head that ends in a hash of the whole (see `fitToLength`).
305
322
  */
306
323
  export function toAttributes(record) {
307
324
  const attributes = [];
@@ -321,7 +338,12 @@ export function toAttributes(record) {
321
338
  droppedAttributesCount += 1;
322
339
  continue;
323
340
  }
324
- attributes.push({ key, value });
341
+ attributes.push({
342
+ key,
343
+ value: typeof value === "string"
344
+ ? fitToLength(value, MAX_ATTRIBUTE_VALUE_LENGTH)
345
+ : value,
346
+ });
325
347
  }
326
348
  return { attributes, droppedAttributesCount };
327
349
  }
@@ -36,6 +36,15 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
36
36
  private readonly scope;
37
37
  private readonly agent;
38
38
  private readonly queue;
39
+ /** What `charsOf` counts in `queue`, kept as spans come and go. */
40
+ private queuedChars;
41
+ /**
42
+ * The batches the receiver turned away and that wait for another try,
43
+ * oldest first. Their spans are the first `refusedSpans` of `queue`, in
44
+ * the same order; everything behind them has not been sent yet.
45
+ */
46
+ private readonly refused;
47
+ private refusedSpans;
39
48
  private sending;
40
49
  private flushTimer;
41
50
  private shutdownPromise;
@@ -48,8 +57,6 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
48
57
  /** No export starts before this (epoch ms): a retry is waiting. */
49
58
  private retryNotBefore;
50
59
  private retryDelayMs;
51
- /** Whether the last export failed - the final flush does not retry it. */
52
- private lastSendFailed;
53
60
  /**
54
61
  * What the last failure was, while exports are failing: said once when it
55
62
  * starts or changes, and again when exports recover. Null while healthy.
@@ -98,17 +105,61 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
98
105
  flush(): void;
99
106
  onApplicationShutdown(): Promise<void>;
100
107
  private enqueue;
108
+ /** Whether `spans` can wait in the queue as it stands, within both limits. */
109
+ private fits;
110
+ private queueAtEnd;
111
+ /** Whether what waits fills a batch by either of its limits. */
112
+ private holdsFullBatch;
101
113
  /**
102
- * One export. Resolves whatever happens: a failure is reported and either
103
- * put back for a retry or dropped, never thrown.
114
+ * Takes the next batch off the queue from `start`: as many spans as fit
115
+ * in `MAX_BATCH_SPANS` and `MAX_BATCH_CHARS`, and always at least one, so
116
+ * a span larger than a batch on its own still goes out.
117
+ */
118
+ private takeBatch;
119
+ /**
120
+ * One export - of `retried`, when it is a refused batch going again.
121
+ * Resolves whatever happens: a failure is reported and either put back
122
+ * for a retry or dropped, never thrown.
104
123
  */
105
124
  private send;
106
125
  /**
107
- * Puts a batch back at the front of the queue, if it still fits, and holds
108
- * exports back for the receiver's `Retry-After` or the next backoff step.
126
+ * Sets a batch the receiver turned away aside for a retry, behind the
127
+ * batches refused before it and ahead of everything else, if it still
128
+ * fits; and holds exports back for the receiver's `Retry-After` or the
129
+ * next backoff step. Returns whether it will be retried.
130
+ *
131
+ * A receiver that is away refuses whatever it is sent, but one may also
132
+ * refuse a batch for what is in it - larger than what it passes spans on
133
+ * to takes, say - with the same statuses. Put back at the front and sent
134
+ * again first, as it was, such a batch was refused for as long as the
135
+ * process ran, took in every span queued behind it at each try, and not
136
+ * one trace was exported after it. So later batches now go ahead of it,
137
+ * and once one of them got through it goes again first, a second apart
138
+ * or as long as `Retry-After` asks, and is dropped - counted, and the
139
+ * backoff left as the accepted export reset it - when it has been
140
+ * refused `MAX_REFUSALS_ONCE_OUTLIVED` times more: a receiver that only
141
+ * limits how often it is sent to takes it within those. During an outage
142
+ * nothing gets through, so nothing is dropped before the queue is full;
143
+ * each refused batch goes again once the receiver is back. At shutdown
144
+ * nothing is put back: the drain gives each batch one try.
109
145
  */
110
146
  private retryLater;
111
- /** Clears the failure state after an accepted export, and says so. */
147
+ /**
148
+ * Holds exports back for the receiver's `Retry-After`, or else for
149
+ * `otherwiseMs`.
150
+ *
151
+ * Never sooner than the first backoff step when the receiver asks.
152
+ * `Retry-After` is whole seconds, so no receiver that follows HTTP asks
153
+ * for less; one that answered `0.0000001` had every flush - and the
154
+ * follow-up after each full batch - send the same export again at once,
155
+ * as fast as the application's thread could encode it.
156
+ */
157
+ private holdBack;
158
+ /**
159
+ * Clears the failure state after an accepted export, and says so. Every
160
+ * batch refused before it has now outlived a refusal that may have been
161
+ * the receiver's, and goes again next.
162
+ */
112
163
  private recovered;
113
164
  /**
114
165
  * Says that exports are failing, once when it starts and again only when
@@ -125,8 +176,11 @@ export declare class OtlpTraceExporter implements OnModuleInit, OnApplicationShu
125
176
  * Operations finish their traces a tick after their response, and one
126
177
  * whose spans were still open waits a further second in the registry, so
127
178
  * the drain waits for both before deciding it is done - as the Observe
128
- * worker's final flush does. A receiver that fails the final export is not
129
- * retried: shutdown is not the time to wait out a backoff.
179
+ * worker's final flush does. Each batch still waiting is sent once, with
180
+ * no backoff in between: one the receiver fails is not retried - shutdown
181
+ * is not the time to wait one out - and the drain goes on with the next,
182
+ * so the batch a receiver refuses for what is in it no longer takes every
183
+ * later one with it.
130
184
  */
131
185
  private shutDown;
132
186
  private drain;