@nestjs/observe 0.3.26 → 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 (59) hide show
  1. package/README.md +38 -2
  2. package/dist/agent/observe-agent.shared-buffer.js +5 -0
  3. package/dist/agent/telemetry-wire-contract.js +3 -3
  4. package/dist/cli/link.js +24 -2
  5. package/dist/cli/package-manager.d.ts +6 -0
  6. package/dist/cli/package-manager.js +60 -3
  7. package/dist/cli/project-files.d.ts +25 -5
  8. package/dist/cli/project-files.js +98 -15
  9. package/dist/custom-metrics/summary.js +17 -10
  10. package/dist/instrument/create-instance-decorator.instrument.js +364 -38
  11. package/dist/instrument/raw-receiver.d.ts +6 -0
  12. package/dist/instrument/raw-receiver.js +32 -0
  13. package/dist/interfaces/observe-options.interface.d.ts +14 -5
  14. package/dist/otlp/otlp-span.mapper.d.ts +2 -0
  15. package/dist/otlp/otlp-span.mapper.js +19 -1
  16. package/dist/otlp/otlp-trace-exporter.service.d.ts +63 -9
  17. package/dist/otlp/otlp-trace-exporter.service.js +232 -38
  18. package/dist/outgoing/http.integration.js +36 -11
  19. package/dist/outgoing/mongodb.integration.d.ts +3 -1
  20. package/dist/outgoing/mongodb.integration.js +93 -18
  21. package/dist/outgoing/mssql.integration.js +9 -4
  22. package/dist/outgoing/outgoing-observe-agent.service.js +5 -1
  23. package/dist/outgoing/sql-statement.util.js +36 -10
  24. package/dist/protocols/bull-observe-agent.service.js +21 -0
  25. package/dist/protocols/deferred-trace-completion.d.ts +8 -2
  26. package/dist/protocols/deferred-trace-completion.js +40 -3
  27. package/dist/protocols/graphql-observe-agent.service.d.ts +62 -2
  28. package/dist/protocols/graphql-observe-agent.service.js +188 -14
  29. package/dist/protocols/graphql-operation-parser.js +45 -14
  30. package/dist/protocols/http-observe-agent.service.d.ts +14 -7
  31. package/dist/protocols/http-observe-agent.service.js +57 -14
  32. package/dist/protocols/job-trace-runner.d.ts +7 -0
  33. package/dist/protocols/job-trace-runner.js +72 -8
  34. package/dist/protocols/rpc-observe-agent.service.d.ts +61 -0
  35. package/dist/protocols/rpc-observe-agent.service.js +146 -10
  36. package/dist/protocols/ws-observe-agent.service.js +1 -1
  37. package/dist/services/logger-patcher.service.js +13 -3
  38. package/dist/services/operation-trace.registry.d.ts +13 -0
  39. package/dist/services/operation-trace.registry.js +195 -65
  40. package/dist/services/stdout-forwarder.service.js +22 -2
  41. package/dist/services/tracer.service.d.ts +19 -14
  42. package/dist/services/tracer.service.js +57 -34
  43. package/dist/utils/capture-request.util.js +36 -8
  44. package/dist/utils/context-accessor.util.d.ts +16 -0
  45. package/dist/utils/context-accessor.util.js +28 -0
  46. package/dist/utils/default-trace-id-generator.util.js +5 -7
  47. package/dist/utils/error-stack.util.d.ts +13 -0
  48. package/dist/utils/error-stack.util.js +166 -0
  49. package/dist/utils/log-line.parser.d.ts +8 -0
  50. package/dist/utils/log-line.parser.js +13 -4
  51. package/dist/utils/log-redactor.js +184 -10
  52. package/dist/utils/redact-url-query.d.ts +16 -5
  53. package/dist/utils/redact-url-query.js +20 -7
  54. package/dist/utils/source-context.util.d.ts +6 -0
  55. package/dist/utils/source-context.util.js +68 -33
  56. package/dist/utils/source-map-resolver.util.js +25 -4
  57. package/dist/utils/store-copy.util.d.ts +10 -0
  58. package/dist/utils/store-copy.util.js +43 -0
  59. package/package.json +1 -1
@@ -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
@@ -306,6 +317,8 @@ function errorStatus(error) {
306
317
  /**
307
318
  * Attributes from a flat record, in its order, without the keys that hold
308
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`).
309
322
  */
310
323
  export function toAttributes(record) {
311
324
  const attributes = [];
@@ -325,7 +338,12 @@ export function toAttributes(record) {
325
338
  droppedAttributesCount += 1;
326
339
  continue;
327
340
  }
328
- attributes.push({ key, value });
341
+ attributes.push({
342
+ key,
343
+ value: typeof value === "string"
344
+ ? fitToLength(value, MAX_ATTRIBUTE_VALUE_LENGTH)
345
+ : value,
346
+ });
329
347
  }
330
348
  return { attributes, droppedAttributesCount };
331
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;
@@ -35,12 +35,32 @@ const gzipAsync = promisify(gzip);
35
35
  * must cost telemetry, not memory.
36
36
  */
37
37
  const MAX_QUEUED_SPANS = 10_000;
38
+ /**
39
+ * The most characters waiting to be exported, counted over every string the
40
+ * waiting spans carry (see `charsOf`). Past it, as past `MAX_QUEUED_SPANS`,
41
+ * a finished operation's spans are dropped whole and counted.
42
+ *
43
+ * A count of spans alone does not bound the memory: a span is as large as
44
+ * its tags, its status and its exception event, and some of them are as
45
+ * long as a client made them. Ten thousand spans that each carried a few
46
+ * outgoing calls' URLs with a client's text in them ran the process out of
47
+ * heap while the receiver was down.
48
+ */
49
+ const MAX_QUEUED_CHARS = 32 * 1024 * 1024;
38
50
  /**
39
51
  * The most spans one export carries. A full batch is sent at once rather
40
52
  * than at the next interval, so a busy service exports in step with what it
41
53
  * records instead of building up a backlog between ticks.
42
54
  */
43
55
  const MAX_BATCH_SPANS = 1_000;
56
+ /**
57
+ * The most characters one export carries, counted as for the queue: a batch
58
+ * is full at whichever of the two it reaches first, and holds at least one
59
+ * span. Receivers limit the size of what they take - a collector's request
60
+ * body, the message size of whatever it passes spans on to - and a thousand
61
+ * large spans in one export would be refused whole, every time it is tried.
62
+ */
63
+ const MAX_BATCH_CHARS = 2 * 1024 * 1024;
44
64
  const DEFAULT_FLUSH_INTERVAL_MS = 5_000;
45
65
  const MIN_FLUSH_INTERVAL_MS = 1_000;
46
66
  const DEFAULT_SHUTDOWN_FLUSH_TIMEOUT_MS = 2_000;
@@ -50,6 +70,13 @@ const DEFAULT_SHUTDOWN_FLUSH_TIMEOUT_MS = 2_000;
50
70
  * the credentials, which sending the batch again would not change.
51
71
  */
52
72
  const RETRYABLE_STATUSES = new Set([429, 502, 503, 504]);
73
+ /**
74
+ * How often a refused batch may be refused again once a later export was
75
+ * accepted, before it is dropped: what tells a batch the receiver will
76
+ * never take from one a rate limiter turned away just after letting the
77
+ * export before it through.
78
+ */
79
+ const MAX_REFUSALS_ONCE_OUTLIVED = 3;
53
80
  /** The first wait before an export is retried; it doubles to the ceiling. */
54
81
  const RETRY_BASE_MS = 1_000;
55
82
  const RETRY_MAX_MS = 60_000;
@@ -105,6 +132,15 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
105
132
  scope = { name: "@nestjs/observe", version: "" };
106
133
  agent;
107
134
  queue = [];
135
+ /** What `charsOf` counts in `queue`, kept as spans come and go. */
136
+ queuedChars = 0;
137
+ /**
138
+ * The batches the receiver turned away and that wait for another try,
139
+ * oldest first. Their spans are the first `refusedSpans` of `queue`, in
140
+ * the same order; everything behind them has not been sent yet.
141
+ */
142
+ refused = [];
143
+ refusedSpans = 0;
108
144
  sending = null;
109
145
  flushTimer = null;
110
146
  shutdownPromise = null;
@@ -117,8 +153,6 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
117
153
  /** No export starts before this (epoch ms): a retry is waiting. */
118
154
  retryNotBefore = 0;
119
155
  retryDelayMs = 0;
120
- /** Whether the last export failed - the final flush does not retry it. */
121
- lastSendFailed = false;
122
156
  /**
123
157
  * What the last failure was, while exports are failing: said once when it
124
158
  * starts or changes, and again when exports recover. Null while healthy.
@@ -256,11 +290,30 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
256
290
  Date.now() < this.retryNotBefore) {
257
291
  return;
258
292
  }
259
- const batch = this.queue.splice(0, MAX_BATCH_SPANS);
260
- this.sending = this.send(batch).finally(() => {
293
+ // A batch the receiver turned away goes again once a later one got
294
+ // through, or when nothing later is waiting to go ahead of it; until
295
+ // then, later batches go first.
296
+ const oldest = this.refused[0];
297
+ let batch;
298
+ let retried;
299
+ if (oldest &&
300
+ (oldest.outlived || this.queue.length === this.refusedSpans)) {
301
+ retried = this.refused.shift();
302
+ this.refusedSpans -= retried.spans;
303
+ batch = this.queue.splice(0, retried.spans);
304
+ this.queuedChars -= totalChars(batch);
305
+ }
306
+ else {
307
+ batch = this.takeBatch(this.refusedSpans);
308
+ }
309
+ this.sending = this.send(batch, retried).finally(() => {
261
310
  this.sending = null;
262
- // A backlog left behind a full batch goes straight out after it.
263
- if (this.queue.length >= MAX_BATCH_SPANS && !this.shutdownPromise) {
311
+ if (this.shutdownPromise) {
312
+ return;
313
+ }
314
+ // A backlog left behind a full batch goes straight out after it, as
315
+ // does a refused batch a later one has just outlived.
316
+ if (this.refused[0]?.outlived || this.holdsFullBatch()) {
264
317
  this.flush();
265
318
  }
266
319
  });
@@ -270,26 +323,60 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
270
323
  return this.shutdownPromise;
271
324
  }
272
325
  enqueue(spans) {
273
- if (this.queue.length + spans.length > MAX_QUEUED_SPANS) {
326
+ if (!this.fits(spans)) {
274
327
  this.droppedSpans += spans.length;
275
328
  if (!this.reportedDrop) {
276
329
  this.reportedDrop = true;
277
- this.logger.warn(`OTLP export is falling behind: more than ${MAX_QUEUED_SPANS} spans are waiting for ${this.settings?.url}, so newer traces are dropped until it catches up. Dropped spans are counted and reported when it does.`);
330
+ this.logger.warn(`OTLP export is falling behind: the spans waiting for ${this.settings?.url} have reached the limit of what is held (${MAX_QUEUED_SPANS} spans, or ${MAX_QUEUED_CHARS} characters of text in them), so newer traces are dropped until it catches up. Dropped spans are counted and reported when it does.`);
278
331
  }
279
332
  return;
280
333
  }
334
+ this.queueAtEnd(spans);
335
+ if (this.holdsFullBatch()) {
336
+ this.flush();
337
+ }
338
+ }
339
+ /** Whether `spans` can wait in the queue as it stands, within both limits. */
340
+ fits(spans) {
341
+ return (this.queue.length + spans.length <= MAX_QUEUED_SPANS &&
342
+ this.queuedChars + totalChars(spans) <= MAX_QUEUED_CHARS);
343
+ }
344
+ queueAtEnd(spans) {
281
345
  for (const span of spans) {
282
346
  this.queue.push(span);
283
347
  }
284
- if (this.queue.length >= MAX_BATCH_SPANS) {
285
- this.flush();
348
+ this.queuedChars += totalChars(spans);
349
+ }
350
+ /** Whether what waits fills a batch by either of its limits. */
351
+ holdsFullBatch() {
352
+ return (this.queue.length >= MAX_BATCH_SPANS ||
353
+ this.queuedChars >= MAX_BATCH_CHARS);
354
+ }
355
+ /**
356
+ * Takes the next batch off the queue from `start`: as many spans as fit
357
+ * in `MAX_BATCH_SPANS` and `MAX_BATCH_CHARS`, and always at least one, so
358
+ * a span larger than a batch on its own still goes out.
359
+ */
360
+ takeBatch(start) {
361
+ let count = 0;
362
+ let chars = 0;
363
+ while (start + count < this.queue.length && count < MAX_BATCH_SPANS) {
364
+ const next = charsOf(this.queue[start + count]);
365
+ if (count > 0 && chars + next > MAX_BATCH_CHARS) {
366
+ break;
367
+ }
368
+ chars += next;
369
+ count += 1;
286
370
  }
371
+ this.queuedChars -= chars;
372
+ return this.queue.splice(start, count);
287
373
  }
288
374
  /**
289
- * One export. Resolves whatever happens: a failure is reported and either
290
- * put back for a retry or dropped, never thrown.
375
+ * One export - of `retried`, when it is a refused batch going again.
376
+ * Resolves whatever happens: a failure is reported and either put back
377
+ * for a retry or dropped, never thrown.
291
378
  */
292
- async send(batch) {
379
+ async send(batch, retried) {
293
380
  const settings = this.settings;
294
381
  let body;
295
382
  try {
@@ -301,7 +388,6 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
301
388
  }
302
389
  catch (error) {
303
390
  // Nothing a retry would change: the batch is lost, and said so.
304
- this.lastSendFailed = true;
305
391
  this.reportFailure(`the batch could not be encoded (${String(error)})`, false);
306
392
  return;
307
393
  }
@@ -317,34 +403,80 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
317
403
  return;
318
404
  }
319
405
  const code = error.code;
320
- this.retryLater(batch, undefined);
321
- this.reportFailure(`the receiver could not be reached (${code ?? String(error)})`, true);
406
+ const retrying = this.retryLater(batch, retried, undefined);
407
+ this.reportFailure(`the receiver could not be reached (${code ?? String(error)})`, retrying);
322
408
  return;
323
409
  }
324
410
  if (reply.status >= 200 && reply.status < 300) {
325
411
  this.recovered(batch.length);
326
412
  return;
327
413
  }
328
- const retryable = RETRYABLE_STATUSES.has(reply.status);
329
- if (retryable) {
330
- this.retryLater(batch, reply.retryAfter);
331
- }
332
- else {
333
- this.lastSendFailed = true;
334
- }
414
+ const retrying = RETRYABLE_STATUSES.has(reply.status) &&
415
+ this.retryLater(batch, retried, reply.retryAfter);
335
416
  const detail = reply.body && /json|text/.test(reply.contentType ?? "")
336
417
  ? ` - ${reply.body.slice(0, 300)}`
337
418
  : "";
338
- this.reportFailure(`it answered ${reply.status}${detail}`, retryable);
419
+ this.reportFailure(`it answered ${reply.status}${detail}`, retrying);
339
420
  }
340
421
  /**
341
- * Puts a batch back at the front of the queue, if it still fits, and holds
342
- * exports back for the receiver's `Retry-After` or the next backoff step.
422
+ * Sets a batch the receiver turned away aside for a retry, behind the
423
+ * batches refused before it and ahead of everything else, if it still
424
+ * fits; and holds exports back for the receiver's `Retry-After` or the
425
+ * next backoff step. Returns whether it will be retried.
426
+ *
427
+ * A receiver that is away refuses whatever it is sent, but one may also
428
+ * refuse a batch for what is in it - larger than what it passes spans on
429
+ * to takes, say - with the same statuses. Put back at the front and sent
430
+ * again first, as it was, such a batch was refused for as long as the
431
+ * process ran, took in every span queued behind it at each try, and not
432
+ * one trace was exported after it. So later batches now go ahead of it,
433
+ * and once one of them got through it goes again first, a second apart
434
+ * or as long as `Retry-After` asks, and is dropped - counted, and the
435
+ * backoff left as the accepted export reset it - when it has been
436
+ * refused `MAX_REFUSALS_ONCE_OUTLIVED` times more: a receiver that only
437
+ * limits how often it is sent to takes it within those. During an outage
438
+ * nothing gets through, so nothing is dropped before the queue is full;
439
+ * each refused batch goes again once the receiver is back. At shutdown
440
+ * nothing is put back: the drain gives each batch one try.
343
441
  */
344
- retryLater(batch, retryAfter) {
345
- this.lastSendFailed = true;
346
- if (this.queue.length + batch.length <= MAX_QUEUED_SPANS) {
442
+ retryLater(batch, retried, retryAfter) {
443
+ if (this.shutdownPromise) {
444
+ this.droppedSpans += batch.length;
445
+ return false;
446
+ }
447
+ if (retried?.outlived) {
448
+ // The receiver took an export since this one was first refused: it
449
+ // is not away, so this does not add to the backoff.
450
+ retried.refusalsOnceOutlived += 1;
451
+ if (retried.refusalsOnceOutlived >= MAX_REFUSALS_ONCE_OUTLIVED ||
452
+ !this.fits(batch)) {
453
+ this.droppedSpans += batch.length;
454
+ this.holdBack(retryAfter, 0);
455
+ return false;
456
+ }
347
457
  this.queue.unshift(...batch);
458
+ this.refused.unshift(retried);
459
+ this.refusedSpans += batch.length;
460
+ this.queuedChars += totalChars(batch);
461
+ this.holdBack(retryAfter, RETRY_BASE_MS);
462
+ return true;
463
+ }
464
+ if (this.fits(batch)) {
465
+ const refused = {
466
+ spans: batch.length,
467
+ outlived: false,
468
+ refusalsOnceOutlived: 0,
469
+ };
470
+ if (retried) {
471
+ this.queue.unshift(...batch);
472
+ this.refused.unshift(refused);
473
+ }
474
+ else {
475
+ this.queue.splice(this.refusedSpans, 0, ...batch);
476
+ this.refused.push(refused);
477
+ }
478
+ this.refusedSpans += batch.length;
479
+ this.queuedChars += totalChars(batch);
348
480
  }
349
481
  else {
350
482
  this.droppedSpans += batch.length;
@@ -353,15 +485,35 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
353
485
  this.retryDelayMs === 0
354
486
  ? RETRY_BASE_MS
355
487
  : Math.min(this.retryDelayMs * 2, RETRY_MAX_MS);
488
+ this.holdBack(retryAfter, this.retryDelayMs);
489
+ return true;
490
+ }
491
+ /**
492
+ * Holds exports back for the receiver's `Retry-After`, or else for
493
+ * `otherwiseMs`.
494
+ *
495
+ * Never sooner than the first backoff step when the receiver asks.
496
+ * `Retry-After` is whole seconds, so no receiver that follows HTTP asks
497
+ * for less; one that answered `0.0000001` had every flush - and the
498
+ * follow-up after each full batch - send the same export again at once,
499
+ * as fast as the application's thread could encode it.
500
+ */
501
+ holdBack(retryAfter, otherwiseMs) {
356
502
  const asked = Number(retryAfter);
357
503
  const delay = Number.isFinite(asked) && asked > 0
358
- ? Math.min(asked * 1000, RETRY_AFTER_MAX_MS)
359
- : this.retryDelayMs;
504
+ ? Math.min(Math.max(asked * 1000, RETRY_BASE_MS), RETRY_AFTER_MAX_MS)
505
+ : otherwiseMs;
360
506
  this.retryNotBefore = Date.now() + delay;
361
507
  }
362
- /** Clears the failure state after an accepted export, and says so. */
508
+ /**
509
+ * Clears the failure state after an accepted export, and says so. Every
510
+ * batch refused before it has now outlived a refusal that may have been
511
+ * the receiver's, and goes again next.
512
+ */
363
513
  recovered(exported) {
364
- this.lastSendFailed = false;
514
+ for (const refused of this.refused) {
515
+ refused.outlived = true;
516
+ }
365
517
  this.retryDelayMs = 0;
366
518
  this.retryNotBefore = 0;
367
519
  if (this.failure !== null || this.droppedSpans > 0) {
@@ -491,8 +643,11 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
491
643
  * Operations finish their traces a tick after their response, and one
492
644
  * whose spans were still open waits a further second in the registry, so
493
645
  * the drain waits for both before deciding it is done - as the Observe
494
- * worker's final flush does. A receiver that fails the final export is not
495
- * retried: shutdown is not the time to wait out a backoff.
646
+ * worker's final flush does. Each batch still waiting is sent once, with
647
+ * no backoff in between: one the receiver fails is not retried - shutdown
648
+ * is not the time to wait one out - and the drain goes on with the next,
649
+ * so the batch a receiver refuses for what is in it no longer takes every
650
+ * later one with it.
496
651
  */
497
652
  async shutDown() {
498
653
  if (this.flushTimer) {
@@ -536,9 +691,6 @@ let OtlpTraceExporter = OtlpTraceExporter_1 = class OtlpTraceExporter {
536
691
  sleep(remaining, undefined, { signal: timeout.signal }).catch(() => undefined),
537
692
  ]);
538
693
  timeout.abort();
539
- if (this.lastSendFailed) {
540
- return;
541
- }
542
694
  continue;
543
695
  }
544
696
  if (this.operationTraceRegistry.hasSnapshotsAwaitingCompletion()) {
@@ -560,3 +712,45 @@ OtlpTraceExporter = OtlpTraceExporter_1 = __decorate([
560
712
  AsyncLocalStorage])
561
713
  ], OtlpTraceExporter);
562
714
  export { OtlpTraceExporter };
715
+ /** What `charsOf` has counted, so a span is walked once however often it moves. */
716
+ const countedChars = new WeakMap();
717
+ /**
718
+ * How many characters of text a span carries: its ids and name, its trace
719
+ * state and status message, and the keys and string values of its
720
+ * attributes and its events'. What the queue and a batch are measured in -
721
+ * not the bytes an export takes, which the encoding decides, but what grows
722
+ * with them.
723
+ */
724
+ function charsOf(span) {
725
+ let chars = countedChars.get(span);
726
+ if (chars !== undefined) {
727
+ return chars;
728
+ }
729
+ chars =
730
+ span.traceId.length +
731
+ span.spanId.length +
732
+ (span.parentSpanId?.length ?? 0) +
733
+ (span.traceState?.length ?? 0) +
734
+ span.name.length +
735
+ (span.status?.message?.length ?? 0) +
736
+ attributeChars(span.attributes);
737
+ for (const event of span.events) {
738
+ chars += event.name.length + attributeChars(event.attributes);
739
+ }
740
+ countedChars.set(span, chars);
741
+ return chars;
742
+ }
743
+ function attributeChars(attributes) {
744
+ let chars = 0;
745
+ for (const { key, value } of attributes) {
746
+ chars += key.length + (typeof value === "string" ? value.length : 0);
747
+ }
748
+ return chars;
749
+ }
750
+ function totalChars(spans) {
751
+ let chars = 0;
752
+ for (const span of spans) {
753
+ chars += charsOf(span);
754
+ }
755
+ return chars;
756
+ }
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "async_hooks";
1
2
  import { subscribe, unsubscribe } from "diagnostics_channel";
2
3
  import { openTelemetryWritesTraceparent } from "../utils/opentelemetry.util.js";
3
4
  import { redactUrlQuery } from "../utils/redact-url-query.js";
@@ -41,6 +42,11 @@ obfuscateUrl) {
41
42
  * `traceparent` has to be written, for the span `start` opens later.
42
43
  */
43
44
  const presetSpanIds = new WeakMap();
45
+ /**
46
+ * The async context a `node:http` request was created in, for `start` to
47
+ * open its span in - see `http.client.request.start`.
48
+ */
49
+ const createdIn = new WeakMap();
44
50
  const subscriptions = [];
45
51
  const on = (channel, handler) => {
46
52
  const guarded = (message) => {
@@ -129,6 +135,9 @@ obfuscateUrl) {
129
135
  // runtimes there is simply no propagation for this client; `start` below
130
136
  // fires after the header block is already on its way.
131
137
  on("http.client.request.created", ({ request }) => {
138
+ // Taken for every request, in a trace or not: whichever context
139
+ // `start` fires in is no more this request's when it has none.
140
+ createdIn.set(request, AsyncLocalStorage.snapshot());
132
141
  const { url } = describeNodeRequest(request);
133
142
  const trace = currentTrace();
134
143
  if (!trace || options.ignore?.(url) || !shouldPropagate(url)) {
@@ -152,19 +161,35 @@ obfuscateUrl) {
152
161
  }
153
162
  }
154
163
  });
164
+ // `start` fires once the request is ended, which is not always in the call
165
+ // that made it: a body piped in ends it from the source's `end` event, in
166
+ // the context of whoever opened the source's socket - another request's,
167
+ // for a pooled connection an earlier one opened. So the span opens in the
168
+ // context the request was created in, where `created` fired; on runtimes
169
+ // without that event, where `start` fired.
155
170
  on("http.client.request.start", ({ request }) => {
156
- const { host, url, method } = describeNodeRequest(request);
157
- const presetSpanId = presetSpanIds.get(request);
158
- presetSpanIds.delete(request);
159
- if (!open(request, method, url, host, presetSpanId)) {
160
- return;
171
+ const runInCreated = createdIn.get(request);
172
+ createdIn.delete(request);
173
+ const begin = () => {
174
+ const { host, url, method } = describeNodeRequest(request);
175
+ const presetSpanId = presetSpanIds.get(request);
176
+ presetSpanIds.delete(request);
177
+ if (!open(request, method, url, host, presetSpanId)) {
178
+ return;
179
+ }
180
+ // `close` always fires, with or without a response. An `error`
181
+ // listener would tell more, but adding one changes what an otherwise
182
+ // unhandled request error does to the process.
183
+ request.once?.("close", () => close(request, request.res
184
+ ? undefined
185
+ : new Error("Request closed with no response")));
186
+ };
187
+ if (runInCreated) {
188
+ runInCreated(begin);
189
+ }
190
+ else {
191
+ begin();
161
192
  }
162
- // `close` always fires, with or without a response. An `error` listener
163
- // would tell more, but adding one changes what an otherwise unhandled
164
- // request error does to the process.
165
- request.once?.("close", () => close(request, request.res
166
- ? undefined
167
- : new Error("Request closed with no response")));
168
193
  });
169
194
  on("http.client.request.error", ({ request, error }) => close(request, error));
170
195
  on("http.client.response.finish", ({ request }) => close(request));
@@ -6,7 +6,9 @@ interface MongoConnectionModule {
6
6
  }
7
7
  /**
8
8
  * A command with its values removed: field names and operators stay, since
9
- * they are the query's shape, and every primitive becomes `?`.
9
+ * they are the query's shape, and every primitive becomes `?`. The one value
10
+ * kept is the collection a command names, which is to a command what the
11
+ * table is to a SQL statement.
10
12
  *
11
13
  * Arrays come in two kinds and are told apart by what they hold. A list of
12
14
  * values keeps one element - `$in: [1, 2, 3]` and `$in: [4]` are the same