risicare 0.9.2 → 0.11.0

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 (73) hide show
  1. package/CHANGELOG.md +254 -0
  2. package/README.md +194 -58
  3. package/dist/frameworks/instructor.cjs +383 -117
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +383 -117
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +396 -130
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.js +396 -130
  10. package/dist/frameworks/langchain.js.map +1 -1
  11. package/dist/frameworks/langgraph.cjs +396 -130
  12. package/dist/frameworks/langgraph.cjs.map +1 -1
  13. package/dist/frameworks/langgraph.js +396 -130
  14. package/dist/frameworks/langgraph.js.map +1 -1
  15. package/dist/frameworks/llamaindex.cjs +396 -130
  16. package/dist/frameworks/llamaindex.cjs.map +1 -1
  17. package/dist/frameworks/llamaindex.js +396 -130
  18. package/dist/frameworks/llamaindex.js.map +1 -1
  19. package/dist/index.cjs +1136 -240
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +151 -26
  22. package/dist/index.d.ts +151 -26
  23. package/dist/index.js +1132 -240
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic/index.cjs +467 -137
  26. package/dist/providers/anthropic/index.cjs.map +1 -1
  27. package/dist/providers/anthropic/index.js +467 -137
  28. package/dist/providers/anthropic/index.js.map +1 -1
  29. package/dist/providers/bedrock/index.cjs +409 -128
  30. package/dist/providers/bedrock/index.cjs.map +1 -1
  31. package/dist/providers/bedrock/index.js +409 -128
  32. package/dist/providers/bedrock/index.js.map +1 -1
  33. package/dist/providers/cerebras/index.cjs +414 -133
  34. package/dist/providers/cerebras/index.cjs.map +1 -1
  35. package/dist/providers/cerebras/index.js +414 -133
  36. package/dist/providers/cerebras/index.js.map +1 -1
  37. package/dist/providers/cohere/index.cjs +414 -133
  38. package/dist/providers/cohere/index.cjs.map +1 -1
  39. package/dist/providers/cohere/index.js +414 -133
  40. package/dist/providers/cohere/index.js.map +1 -1
  41. package/dist/providers/google/index.cjs +414 -133
  42. package/dist/providers/google/index.cjs.map +1 -1
  43. package/dist/providers/google/index.js +414 -133
  44. package/dist/providers/google/index.js.map +1 -1
  45. package/dist/providers/groq/index.cjs +414 -133
  46. package/dist/providers/groq/index.cjs.map +1 -1
  47. package/dist/providers/groq/index.js +414 -133
  48. package/dist/providers/groq/index.js.map +1 -1
  49. package/dist/providers/huggingface/index.cjs +414 -133
  50. package/dist/providers/huggingface/index.cjs.map +1 -1
  51. package/dist/providers/huggingface/index.js +414 -133
  52. package/dist/providers/huggingface/index.js.map +1 -1
  53. package/dist/providers/mistral/index.cjs +414 -133
  54. package/dist/providers/mistral/index.cjs.map +1 -1
  55. package/dist/providers/mistral/index.js +414 -133
  56. package/dist/providers/mistral/index.js.map +1 -1
  57. package/dist/providers/ollama/index.cjs +414 -133
  58. package/dist/providers/ollama/index.cjs.map +1 -1
  59. package/dist/providers/ollama/index.js +414 -133
  60. package/dist/providers/ollama/index.js.map +1 -1
  61. package/dist/providers/openai/index.cjs +452 -135
  62. package/dist/providers/openai/index.cjs.map +1 -1
  63. package/dist/providers/openai/index.js +452 -135
  64. package/dist/providers/openai/index.js.map +1 -1
  65. package/dist/providers/together/index.cjs +414 -133
  66. package/dist/providers/together/index.cjs.map +1 -1
  67. package/dist/providers/together/index.js +414 -133
  68. package/dist/providers/together/index.js.map +1 -1
  69. package/dist/providers/vercel-ai/index.cjs +398 -132
  70. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  71. package/dist/providers/vercel-ai/index.js +398 -132
  72. package/dist/providers/vercel-ai/index.js.map +1 -1
  73. package/package.json +1 -1
@@ -1,6 +1,35 @@
1
1
  // src/client.ts
2
2
  import { createHash as createHash2 } from "crypto";
3
3
 
4
+ // src/exporters/retry.ts
5
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
6
+ var TOO_LARGE_STATUS = 413;
7
+ var RETRY_BACKOFF_BASE_S = 1;
8
+ var RETRY_BACKOFF_CAP_S = 30;
9
+ var DEFAULT_RETRY_HORIZON_S = 300;
10
+ var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
11
+ var RETRY_WARN_AFTER_ATTEMPTS = 3;
12
+ var jitter = { fraction: () => Math.random() };
13
+ function backoffDelayS(retryNumber, fraction) {
14
+ const exponent = Math.min(Math.max(retryNumber, 0), 62);
15
+ const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
16
+ return Math.min(Math.max(fraction, 0), 1) * ceiling;
17
+ }
18
+ var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
19
+ function parseRetryAfterS(value, nowMs = Date.now()) {
20
+ if (value === null || value === void 0) return null;
21
+ const text = String(value).trim();
22
+ if (text === "") return null;
23
+ if (SECONDS.test(text)) {
24
+ const seconds = Number(text);
25
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
26
+ }
27
+ if (!/[A-Za-z]/.test(text)) return null;
28
+ const when = Date.parse(text);
29
+ if (!Number.isFinite(when)) return null;
30
+ return Math.max(0, (when - nowMs) / 1e3);
31
+ }
32
+
4
33
  // src/globals.ts
5
34
  import { AsyncLocalStorage } from "async_hooks";
6
35
  var G = globalThis;
@@ -95,7 +124,53 @@ function hasCredentials(url) {
95
124
  }
96
125
  }
97
126
 
127
+ // src/masking.ts
128
+ var CONTENT_IN_JSON_OBJECT = /* @__PURE__ */ new Map([
129
+ [
130
+ "llm.invocation_parameters",
131
+ /* @__PURE__ */ new Set([
132
+ "additionalinstructions",
133
+ // OpenAI assistants run
134
+ "chathistory",
135
+ // Cohere
136
+ "contents",
137
+ // Gemini
138
+ "documents",
139
+ // Cohere RAG
140
+ "functions",
141
+ "input",
142
+ "inputtext",
143
+ // Bedrock Titan
144
+ "instructions",
145
+ "message",
146
+ // Cohere
147
+ "messages",
148
+ "preamble",
149
+ // Cohere
150
+ "prediction",
151
+ // OpenAI predicted output
152
+ "prompt",
153
+ "system",
154
+ // Anthropic
155
+ "systeminstruction",
156
+ // Gemini
157
+ "texts",
158
+ // Cohere embed
159
+ "toolconfig",
160
+ // Gemini
161
+ "tools"
162
+ ])
163
+ ]
164
+ ]);
165
+ var VALUE_RULE_PREFIXES = new Set(
166
+ [...CONTENT_IN_JSON_OBJECT.keys()].flatMap((key) => {
167
+ const segments = key.split(".");
168
+ return segments.slice(1).map((_, i) => segments.slice(0, i + 1).join("."));
169
+ })
170
+ );
171
+
98
172
  // src/exporters/batch.ts
173
+ var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
99
174
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
100
175
  var MAX_BATCH_BYTES = 8 * 1024 * 1024;
101
176
  var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
@@ -231,7 +306,7 @@ var SUPPLEMENTAL_RULES = [
231
306
  ];
232
307
 
233
308
  // src/version.ts
234
- var SDK_VERSION = "0.9.2";
309
+ var SDK_VERSION = "0.11.0";
235
310
 
236
311
  // src/exporters/quota.ts
237
312
  var QUOTA_REASON = "monthly_quota_exceeded";
@@ -339,12 +414,18 @@ var QuotaPause = class {
339
414
 
340
415
  // src/exporters/http.ts
341
416
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
342
- var RETRY_AFTER_CEILING_MS = 1e4;
343
- var REFUSAL_BACKOFF_BASE_MS = 1e3;
344
- var REFUSAL_NO_HINT = -1;
345
417
  var MISROUTE_WARN_WINDOW_MS = 3e5;
346
418
  var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
347
419
  var FAILURE_WARN_WINDOW_MS = 3e5;
420
+ var MAX_TIMER_MS = 2 ** 31 - 1;
421
+ function validHorizonS(value) {
422
+ if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
423
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
424
+ warn(
425
+ `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
426
+ );
427
+ return DEFAULT_RETRY_HORIZON_S;
428
+ }
348
429
  var HttpExporter = class {
349
430
  name = "http";
350
431
  _endpoint;
@@ -354,20 +435,28 @@ var HttpExporter = class {
354
435
  _timeoutMs;
355
436
  _maxRetries;
356
437
  _compress;
438
+ _retryHorizonS;
439
+ /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
440
+ attempts = 0;
357
441
  // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
358
- // a "30-second prod restart" scenario: with default 1s batch flush a
359
- // 5-failure threshold opens the circuit ~5s into an outage and the 60s
360
- // cooldown gives the gateway time to come back before the half-open
361
- // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
442
+ // a "30-second prod restart" scenario. Since W2-1c only answers that a retry
443
+ // cannot change move it (see the block above).
362
444
  _consecutiveFailures = 0;
363
445
  _lastMisrouteWarnAt = -Infinity;
364
446
  _lastFailureWarnAt = -Infinity;
447
+ _lastExhaustedWarnAt = -Infinity;
448
+ /** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
449
+ _tooLargeWarned = false;
365
450
  /**
366
451
  * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
367
452
  * 'unknown'). `null` after a success. A new kind in the same outage writes one more
368
453
  * WARNING, also inside the window.
369
454
  */
370
455
  _failureKind = null;
456
+ /** `endRetries()` was called, and `shutdown()` has not run since. */
457
+ _noWait = false;
458
+ /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
459
+ _waits = /* @__PURE__ */ new Set();
371
460
  /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
372
461
  _safeEndpoint;
373
462
  /** The endpoint holds userinfo. `fetch` refuses such a URL. */
@@ -378,6 +467,8 @@ var HttpExporter = class {
378
467
  _acks = /* @__PURE__ */ new WeakMap();
379
468
  /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
380
469
  _requests = /* @__PURE__ */ new WeakMap();
470
+ /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
471
+ _dropReasons = /* @__PURE__ */ new WeakMap();
381
472
  /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
382
473
  noteQuotaDrop(count = 1) {
383
474
  this._quota.addDrops(count);
@@ -402,8 +493,16 @@ var HttpExporter = class {
402
493
  this._projectId = options.projectId;
403
494
  this._environment = options.environment;
404
495
  this._timeoutMs = options.timeoutMs ?? 5e3;
405
- this._maxRetries = options.maxRetries ?? 3;
496
+ let maxRetries = options.maxRetries;
497
+ if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
498
+ warn(
499
+ `Risicare: maxRetries=${String(maxRetries)} is not a whole number of 1 or more; the exporter uses no count limit (the retry horizon is the limit).`
500
+ );
501
+ maxRetries = void 0;
502
+ }
503
+ this._maxRetries = maxRetries;
406
504
  this._compress = options.compress ?? false;
505
+ this._retryHorizonS = validHorizonS(options.retryHorizonS);
407
506
  this._safeEndpoint = safeUrl(this._endpoint);
408
507
  this._endpointHasCredentials = hasCredentials(this._endpoint);
409
508
  }
@@ -425,16 +524,18 @@ var HttpExporter = class {
425
524
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
426
525
  return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
427
526
  }
428
- /** The most requests that one `export()` call sends (`maxRetries`). */
527
+ /**
528
+ * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
529
+ * the retry horizon is the limit.
530
+ */
429
531
  get attemptsPerExport() {
430
532
  return this._maxRetries;
431
533
  }
432
534
  /**
433
535
  * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
434
- * it. This is the number that was sent, not the most that the call may send
435
- * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit
436
- * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is
437
- * kept per batch, as `takeAck` keeps the ack.
536
+ * it. Each retry and each half of a 413 split counts one; a call that the open circuit
537
+ * breaker or the quota pause stops sends none. Returns `null` when no call is on record for
538
+ * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
438
539
  */
439
540
  takeAttempts(spans) {
440
541
  const n = this._requests.get(spans) ?? null;
@@ -451,6 +552,12 @@ var HttpExporter = class {
451
552
  this._acks.delete(spans);
452
553
  return ack;
453
554
  }
555
+ /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
556
+ takeDropReason(spans) {
557
+ const reason = this._dropReasons.get(spans) ?? null;
558
+ this._dropReasons.delete(spans);
559
+ return reason;
560
+ }
454
561
  /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
455
562
  takeUnserializable(spans) {
456
563
  const bad = this._unserializable.get(spans) ?? [];
@@ -459,7 +566,7 @@ var HttpExporter = class {
459
566
  }
460
567
  /**
461
568
  * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
462
- * request, its retries and its backoff sleep. The batch processor calls it when
569
+ * request, its retries and its backoff wait. The batch processor calls it when
463
570
  * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
464
571
  * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
465
572
  * logs no WARNING.
@@ -469,24 +576,39 @@ var HttpExporter = class {
469
576
  else for (const call of this._calls.values()) call.cancel.abort();
470
577
  }
471
578
  /**
472
- * Send one batch. The limits are the request timeout and `maxRetries`.
579
+ * End the retry waits of this exporter until its next `shutdown()`. The batch processor
580
+ * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
581
+ * at once. An attempt that fails after this is not retried: the call fails with the drop
582
+ * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
583
+ * batch, not the shutdown budget.
584
+ */
585
+ endRetries() {
586
+ this._noWait = true;
587
+ for (const wake of [...this._waits]) wake();
588
+ }
589
+ /**
590
+ * Send one batch, with the W2-1c retry policy (see the block above the class).
591
+ *
592
+ * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
593
+ * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
594
+ * accounted for: `takeDropReason` then says why, and the batch processor drops the batch
595
+ * with that reason.
473
596
  *
474
597
  * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
475
- * cuts a request that is already sent. A short flush budget that cut the request made a
476
- * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
477
- * the server stored the same spans again. Only `abort()` stops the call, and only
598
+ * cuts a request that is already sent. Only `abort()` stops the call, and only
478
599
  * `shutdown()` calls it.
479
600
  */
480
601
  async export(spans) {
481
602
  if (spans.length === 0) return "success" /* SUCCESS */;
482
603
  const call = {
483
604
  cancel: new AbortController(),
484
- refusalAfterMs: null,
605
+ retryAfterS: null,
485
606
  misroute: null,
486
607
  noRetry: false,
487
608
  status: null,
488
609
  error: null,
489
- attempts: 0
610
+ attempts: 0,
611
+ ack: null
490
612
  };
491
613
  this._calls.set(spans, call);
492
614
  try {
@@ -523,83 +645,236 @@ var HttpExporter = class {
523
645
  );
524
646
  }
525
647
  if (parts.length === 0) return "success" /* SUCCESS */;
526
- const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
527
- const now = Date.now();
528
- let isHalfOpen = false;
529
- if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
530
- if (now < this._circuitOpenUntil) {
531
- return "failure" /* FAILURE */;
648
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
649
+ this._dropReasons.set(spans, "transport_refused");
650
+ return "failure" /* FAILURE */;
651
+ }
652
+ const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
653
+ const start = performance.now();
654
+ await this._deliver(parts, start, call, out, true);
655
+ if (cancelled.aborted || out.cancelled) {
656
+ this._acks.delete(spans);
657
+ return "failure" /* FAILURE */;
658
+ }
659
+ return this._finish(spans, out, call.attempts);
660
+ }
661
+ /** The request body for `parts` (the serialized spans of one part of a batch). */
662
+ _payload(parts) {
663
+ return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
664
+ }
665
+ /**
666
+ * Send one part of a batch with the retry policy, and record its outcome in `out`.
667
+ * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
668
+ * that gets 413 again is dropped as `too_large`.
669
+ */
670
+ async _deliver(parts, start, call, out, maySplit) {
671
+ const n = parts.length;
672
+ if (!maySplit && this._quota.paused()) {
673
+ out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
674
+ return;
675
+ }
676
+ const result = await this._sendWithRetries(this._payload(parts), n, start, call);
677
+ if (result.kind === "delivered") {
678
+ out.delivered.push({ n, ack: result.ack });
679
+ } else if (result.kind === "too_large") {
680
+ if (maySplit && n > 1) {
681
+ const mid = Math.ceil(n / 2);
682
+ debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
683
+ await this._deliver(parts.slice(0, mid), start, call, out, false);
684
+ if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
685
+ } else {
686
+ out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
532
687
  }
533
- isHalfOpen = true;
688
+ } else if (result.kind === "cancelled") {
689
+ out.cancelled = true;
690
+ } else {
691
+ out.failed.push({ n, reason: result.kind, answer: result.answer });
534
692
  }
535
- const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
536
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
537
- call.refusalAfterMs = null;
693
+ }
694
+ /** Send one request body until it is delivered or the policy stops. */
695
+ async _sendWithRetries(body, spansSent, start, call) {
696
+ const cancelled = call.cancel.signal;
697
+ let retryNumber = 0;
698
+ let attemptsHere = 0;
699
+ for (; ; ) {
700
+ if (cancelled.aborted) return { kind: "cancelled" };
701
+ call.retryAfterS = null;
538
702
  call.misroute = null;
539
703
  call.noRetry = false;
540
704
  call.status = null;
541
705
  call.error = null;
706
+ call.ack = null;
542
707
  call.attempts++;
543
- const result = await this._sendRequest(payload, parts.length, call, spans);
544
- if (cancelled.aborted) {
545
- this._acks.delete(spans);
546
- return "failure" /* FAILURE */;
708
+ attemptsHere++;
709
+ this.attempts++;
710
+ const result = await this._sendRequest(body, spansSent, call);
711
+ if (cancelled.aborted) return { kind: "cancelled" };
712
+ if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
713
+ if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
714
+ const answer = {
715
+ status: call.status,
716
+ error: call.error,
717
+ misroute: call.misroute,
718
+ zeroAck: call.noRetry,
719
+ sent: spansSent
720
+ };
721
+ if (!this._retryable(call)) return { kind: "transport_refused", answer };
722
+ if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
723
+ if (this._noWait) return { kind: "shutdown_residue", answer };
724
+ if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
725
+ return { kind: "retry_exhausted", answer };
547
726
  }
548
- if (result === "success" /* SUCCESS */) {
549
- this._consecutiveFailures = 0;
550
- this._failureKind = null;
551
- return result;
552
- }
553
- if (call.misroute !== null || call.noRetry) break;
554
- if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
555
- if (attempt < maxAttempts - 1) {
556
- const refusal = call.refusalAfterMs;
557
- const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
558
- await sleep(delay, cancelled);
559
- if (cancelled.aborted) return "failure" /* FAILURE */;
727
+ const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
728
+ if (remainingS <= 0) return { kind: "retry_exhausted", answer };
729
+ const hint = call.retryAfterS;
730
+ const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
731
+ const delayS = Math.min(waitS, remainingS);
732
+ retryNumber++;
733
+ debug(
734
+ `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
735
+ );
736
+ await this._retryWait(delayS * 1e3, cancelled);
737
+ }
738
+ }
739
+ /** True when the answer of the last attempt of `call` can change on a retry. */
740
+ _retryable(call) {
741
+ if (call.misroute !== null || call.noRetry) return false;
742
+ if (call.status !== null) return RETRY_STATUSES.has(call.status);
743
+ if (this._endpointHasCredentials) return false;
744
+ return call.error !== null;
745
+ }
746
+ /**
747
+ * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
748
+ * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
749
+ * SDK's `shutdown()`, which ends the wait.
750
+ */
751
+ _retryWait(ms, signal) {
752
+ return new Promise((resolve) => {
753
+ if (signal.aborted || this._noWait || ms <= 0) return resolve();
754
+ const done = () => {
755
+ clearTimeout(timer);
756
+ signal.removeEventListener("abort", done);
757
+ this._waits.delete(done);
758
+ resolve();
759
+ };
760
+ const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
761
+ timer.unref?.();
762
+ signal.addEventListener("abort", done, { once: true });
763
+ this._waits.add(done);
764
+ });
765
+ }
766
+ /** Turn the outcome of the parts of one batch into the result of `export()`. */
767
+ _finish(spans, out, attempts) {
768
+ const reasons = new Set(out.failed.map((f) => f.reason));
769
+ if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
770
+ const reason = out.failed[0].reason;
771
+ const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
772
+ this._dropReasons.set(spans, reason);
773
+ return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
774
+ }
775
+ let ack;
776
+ if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
777
+ ack = out.delivered[0].ack;
778
+ } else {
779
+ let accepted = 0;
780
+ let rejected = 0;
781
+ let quotaDropped = 0;
782
+ for (const part of out.delivered) {
783
+ accepted += part.ack !== null ? part.ack.accepted : part.n;
784
+ rejected += part.ack !== null ? part.ack.rejected : 0;
785
+ quotaDropped += part.ack?.quotaDropped ?? 0;
560
786
  }
787
+ const dropped = { ...out.dropped };
788
+ for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
789
+ ack = { accepted, rejected };
790
+ if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
791
+ if (Object.keys(dropped).length > 0) ack.dropped = dropped;
561
792
  }
562
- if (call.refusalAfterMs !== null) {
563
- warn(
564
- `Risicare: the ingest endpoint refused this batch for capacity (HTTP 429/503) after ${call.attempts} attempt(s). This is a healthy server shedding load, not an outage. This export of the batch failed; the circuit breaker does not count it. Reduce batch size or export rate if it persists.`
565
- );
793
+ if (ack !== null) this._acks.set(spans, ack);
794
+ this._consecutiveFailures = 0;
795
+ this._failureKind = null;
796
+ const tooLarge = out.dropped.too_large ?? 0;
797
+ if (tooLarge > 0) this._warnTooLarge(tooLarge);
798
+ for (const f of out.failed) {
799
+ if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
800
+ }
801
+ return "success" /* SUCCESS */;
802
+ }
803
+ /** End a call in which no span was accounted for. Always returns FAILURE. */
804
+ _fail(reason, answer, nSpans, attempts) {
805
+ if (reason === "shutdown_residue") {
806
+ debug(`Export ended by shutdown after ${attempts} attempt(s)`);
566
807
  return "failure" /* FAILURE */;
567
808
  }
568
- const misroute = call.misroute;
569
- if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
570
- this._lastMisrouteWarnAt = Date.now();
571
- warn(
572
- `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${misroute}. That is not the Risicare ingest gateway, so the endpoint is probably wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK does not follow redirects, and this batch is counted as NOT delivered. Set endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`
573
- );
809
+ if (reason === "retry_exhausted") {
810
+ if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
811
+ this._warnOutage(answer, true);
812
+ this._warnExhausted(nSpans, attempts, answer);
813
+ return "failure" /* FAILURE */;
574
814
  }
815
+ this._stepBreaker();
816
+ this._warnOutage(answer, false);
817
+ return "failure" /* FAILURE */;
818
+ }
819
+ /** Count one failed call toward the circuit breaker. */
820
+ _stepBreaker() {
575
821
  this._consecutiveFailures++;
576
- if (misroute === null && !call.noRetry) {
577
- const status = call.status;
578
- const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
579
- let write = false;
580
- if (this._consecutiveFailures === 1 || this._failureKind === null) {
581
- if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
582
- this._lastFailureWarnAt = Date.now();
583
- write = true;
584
- }
585
- this._failureKind = kind;
586
- } else if (kind !== this._failureKind) {
587
- this._failureKind = kind;
588
- write = true;
589
- }
590
- if (write) this._warnOutage(kind, status, call.error);
591
- }
592
822
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
593
823
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
594
824
  warn(
595
825
  `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
596
826
  );
597
827
  }
598
- return "failure" /* FAILURE */;
599
828
  }
600
- /** The outage WARNING for one kind of failure. */
601
- _warnOutage(kind, status, error) {
829
+ /**
830
+ * The outage WARNING: at the first failure of an outage, and when its kind changes. At most
831
+ * one in the window for the first failure; a misroute has its own WARNING, at most one in
832
+ * the window. `retrying` is true for a retryable answer (written after
833
+ * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
834
+ * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
835
+ * code when there was no answer. It never names the key or the response body, and names
836
+ * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
837
+ * `checkAck`.
838
+ */
839
+ _warnOutage(answer, retrying) {
840
+ if (answer.misroute !== null) {
841
+ if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
842
+ this._lastMisrouteWarnAt = Date.now();
843
+ warn(
844
+ `Risicare: spans are NOT reaching ${this._safeEndpoint}. It answered POST /v1/spans with ${answer.misroute}. That is not the Risicare ingest gateway, so the endpoint is probably wrong (for example the dashboard URL instead of the ingest gateway URL). The SDK does not follow redirects, and this batch is counted as NOT delivered. Set endpoint or RISICARE_ENDPOINT to the ingest gateway URL.`
845
+ );
846
+ }
847
+ return;
848
+ }
849
+ if (answer.zeroAck) return;
850
+ const status = answer.status;
851
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
852
+ let write = false;
853
+ if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
854
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
855
+ this._lastFailureWarnAt = Date.now();
856
+ write = true;
857
+ }
858
+ this._failureKind = kind;
859
+ } else if (kind !== this._failureKind) {
860
+ this._failureKind = kind;
861
+ write = true;
862
+ }
863
+ if (!write) return;
602
864
  const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
865
+ if (retrying) {
866
+ let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
867
+ if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
868
+ const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
869
+ if (kind === "http") {
870
+ warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
871
+ } else {
872
+ warn(
873
+ `${where}: no answer (${answer.error}). The endpoint cannot be reached, or it did not answer in time. ${retryText} Set debug: true to see each attempt.`
874
+ );
875
+ }
876
+ return;
877
+ }
603
878
  const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
604
879
  if (kind === "auth") {
605
880
  warn(
@@ -607,15 +882,11 @@ var HttpExporter = class {
607
882
  );
608
883
  } else if (kind === "http") {
609
884
  warn(
610
- `${where}: it answered HTTP ${status}. The server did not take the batch. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
885
+ `${where}: it answered HTTP ${status}. The server did not take the batch, and a retry cannot change that answer. Check the endpoint and the server. ${tail} Set debug: true to see each attempt.`
611
886
  );
612
887
  } else if (kind === "none" && this._endpointHasCredentials) {
613
888
  warn(
614
- `${where}: no answer (${error}). The endpoint URL holds credentials (a user name or a password before the host), and fetch does not send a request to such a URL. Remove the credentials from the endpoint URL. ${tail}`
615
- );
616
- } else if (kind === "none") {
617
- warn(
618
- `${where}: no answer (${error}). The endpoint cannot be reached, or it did not answer in time. Check the endpoint and the network. ${tail} Set debug: true to see each attempt.`
889
+ `${where}: no answer (${answer.error}). The endpoint URL holds credentials (a user name or a password before the host), and fetch does not send a request to such a URL. Remove the credentials from the endpoint URL. ${tail}`
619
890
  );
620
891
  } else {
621
892
  warn(
@@ -623,33 +894,38 @@ var HttpExporter = class {
623
894
  );
624
895
  }
625
896
  }
897
+ /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
898
+ _warnExhausted(nSpans, attempts, answer) {
899
+ if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
900
+ this._lastExhaustedWarnAt = Date.now();
901
+ const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
902
+ const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
903
+ const limit = this._maxRetries !== void 0 && attempts >= this._maxRetries ? `the maxRetries limit of ${this._maxRetries} attempt(s)` : `the retry horizon of ${this._retryHorizonS} s (retryHorizonS)`;
904
+ warn(
905
+ `Risicare: ${nSpans} span(s) DISCARDED (reason=retry_exhausted): ${this._safeEndpoint} did not take them in ${attempts} attempt(s), and ${limit} is used up. The last answer: ${last}${capacity}. A gateway outage that is longer than the retry horizon loses spans. To wait longer, raise retryHorizonS.`
906
+ );
907
+ }
908
+ /** The WARNING for spans dropped as `too_large`. One time for each exporter. */
909
+ _warnTooLarge(nSpans) {
910
+ if (this._tooLargeWarned) return;
911
+ this._tooLargeWarned = true;
912
+ warn(
913
+ `Risicare: ${nSpans} span(s) DISCARDED (reason=too_large): ${this._safeEndpoint} answered HTTP 413 (the request is too large) for a batch, and again for a half of it after one split. The SDK does not send these spans again. Make the span attributes smaller. This WARNING is written one time; droppedSpansByReason.too_large has the count.`
914
+ );
915
+ }
626
916
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
627
917
  _noteMisroute(call, answer) {
628
918
  call.misroute = this._scrub(answer, 300);
629
919
  debug(`Ingest misroute: ${call.misroute}`);
630
920
  return "failure" /* FAILURE */;
631
921
  }
632
- /**
633
- * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
634
- *
635
- * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
636
- * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
637
- * parse.
638
- */
639
- _noteRefusal(call, status, retryAfterRaw) {
640
- if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
641
- let delay = REFUSAL_NO_HINT;
642
- if (retryAfterRaw) {
643
- const secs = Number(retryAfterRaw);
644
- if (Number.isFinite(secs) && secs >= 0) {
645
- delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
646
- }
647
- }
648
- call.refusalAfterMs = delay;
649
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
650
- return true;
922
+ /** Record the `Retry-After` wait of a retryable answer for the retry loop. */
923
+ _noteRetryAfter(call, status, retryAfterRaw) {
924
+ if (!RETRY_STATUSES.has(status)) return;
925
+ call.retryAfterS = parseRetryAfterS(retryAfterRaw);
926
+ debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
651
927
  }
652
- async _sendRequest(body, spansSent, call, spans) {
928
+ async _sendRequest(body, spansSent, call) {
653
929
  const cancelled = call.cancel.signal;
654
930
  const timeoutMs = this._timeoutMs;
655
931
  const url = `${this._endpoint}/v1/spans`;
@@ -717,14 +993,15 @@ var HttpExporter = class {
717
993
  } else if (ack.result === "success" /* SUCCESS */) {
718
994
  this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
719
995
  }
720
- if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
996
+ if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
721
997
  if (ack.final) call.noRetry = true;
722
998
  return ack.result;
723
- } else if (response.status === 408 || response.status === 504) {
999
+ }
1000
+ this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
1001
+ if (response.status === 408 || response.status === 504) {
724
1002
  debug(`HTTP export timeout: ${response.status}`);
725
1003
  return "timeout" /* TIMEOUT */;
726
1004
  }
727
- this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
728
1005
  debug(`HTTP export failed: ${response.status}`);
729
1006
  return "failure" /* FAILURE */;
730
1007
  } catch (e) {
@@ -738,20 +1015,9 @@ var HttpExporter = class {
738
1015
  }
739
1016
  }
740
1017
  shutdown() {
1018
+ this._noWait = false;
741
1019
  }
742
1020
  };
743
- function sleep(ms, signal) {
744
- return new Promise((resolve) => {
745
- if (signal?.aborted) return resolve();
746
- const done = () => {
747
- clearTimeout(timer);
748
- signal?.removeEventListener("abort", done);
749
- resolve();
750
- };
751
- const timer = setTimeout(done, ms);
752
- signal?.addEventListener("abort", done, { once: true });
753
- });
754
- }
755
1021
  function asCount(v) {
756
1022
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
757
1023
  }