risicare 0.10.0 → 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 +76 -5
  2. package/README.md +157 -39
  3. package/dist/frameworks/instructor.cjs +338 -117
  4. package/dist/frameworks/instructor.cjs.map +1 -1
  5. package/dist/frameworks/instructor.js +338 -117
  6. package/dist/frameworks/instructor.js.map +1 -1
  7. package/dist/frameworks/langchain.cjs +351 -130
  8. package/dist/frameworks/langchain.cjs.map +1 -1
  9. package/dist/frameworks/langchain.js +351 -130
  10. package/dist/frameworks/langchain.js.map +1 -1
  11. package/dist/frameworks/langgraph.cjs +351 -130
  12. package/dist/frameworks/langgraph.cjs.map +1 -1
  13. package/dist/frameworks/langgraph.js +351 -130
  14. package/dist/frameworks/langgraph.js.map +1 -1
  15. package/dist/frameworks/llamaindex.cjs +351 -130
  16. package/dist/frameworks/llamaindex.cjs.map +1 -1
  17. package/dist/frameworks/llamaindex.js +351 -130
  18. package/dist/frameworks/llamaindex.js.map +1 -1
  19. package/dist/index.cjs +808 -226
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +137 -21
  22. package/dist/index.d.ts +137 -21
  23. package/dist/index.js +804 -226
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic/index.cjs +351 -130
  26. package/dist/providers/anthropic/index.cjs.map +1 -1
  27. package/dist/providers/anthropic/index.js +351 -130
  28. package/dist/providers/anthropic/index.js.map +1 -1
  29. package/dist/providers/bedrock/index.cjs +346 -125
  30. package/dist/providers/bedrock/index.cjs.map +1 -1
  31. package/dist/providers/bedrock/index.js +346 -125
  32. package/dist/providers/bedrock/index.js.map +1 -1
  33. package/dist/providers/cerebras/index.cjs +351 -130
  34. package/dist/providers/cerebras/index.cjs.map +1 -1
  35. package/dist/providers/cerebras/index.js +351 -130
  36. package/dist/providers/cerebras/index.js.map +1 -1
  37. package/dist/providers/cohere/index.cjs +351 -130
  38. package/dist/providers/cohere/index.cjs.map +1 -1
  39. package/dist/providers/cohere/index.js +351 -130
  40. package/dist/providers/cohere/index.js.map +1 -1
  41. package/dist/providers/google/index.cjs +351 -130
  42. package/dist/providers/google/index.cjs.map +1 -1
  43. package/dist/providers/google/index.js +351 -130
  44. package/dist/providers/google/index.js.map +1 -1
  45. package/dist/providers/groq/index.cjs +351 -130
  46. package/dist/providers/groq/index.cjs.map +1 -1
  47. package/dist/providers/groq/index.js +351 -130
  48. package/dist/providers/groq/index.js.map +1 -1
  49. package/dist/providers/huggingface/index.cjs +351 -130
  50. package/dist/providers/huggingface/index.cjs.map +1 -1
  51. package/dist/providers/huggingface/index.js +351 -130
  52. package/dist/providers/huggingface/index.js.map +1 -1
  53. package/dist/providers/mistral/index.cjs +351 -130
  54. package/dist/providers/mistral/index.cjs.map +1 -1
  55. package/dist/providers/mistral/index.js +351 -130
  56. package/dist/providers/mistral/index.js.map +1 -1
  57. package/dist/providers/ollama/index.cjs +351 -130
  58. package/dist/providers/ollama/index.cjs.map +1 -1
  59. package/dist/providers/ollama/index.js +351 -130
  60. package/dist/providers/ollama/index.js.map +1 -1
  61. package/dist/providers/openai/index.cjs +351 -130
  62. package/dist/providers/openai/index.cjs.map +1 -1
  63. package/dist/providers/openai/index.js +351 -130
  64. package/dist/providers/openai/index.js.map +1 -1
  65. package/dist/providers/together/index.cjs +351 -130
  66. package/dist/providers/together/index.cjs.map +1 -1
  67. package/dist/providers/together/index.js +351 -130
  68. package/dist/providers/together/index.js.map +1 -1
  69. package/dist/providers/vercel-ai/index.cjs +351 -130
  70. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  71. package/dist/providers/vercel-ai/index.js +351 -130
  72. package/dist/providers/vercel-ai/index.js.map +1 -1
  73. package/package.json +1 -1
@@ -37,6 +37,35 @@ module.exports = __toCommonJS(instructor_exports);
37
37
  // src/client.ts
38
38
  var import_node_crypto3 = require("crypto");
39
39
 
40
+ // src/exporters/retry.ts
41
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
42
+ var TOO_LARGE_STATUS = 413;
43
+ var RETRY_BACKOFF_BASE_S = 1;
44
+ var RETRY_BACKOFF_CAP_S = 30;
45
+ var DEFAULT_RETRY_HORIZON_S = 300;
46
+ var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
47
+ var RETRY_WARN_AFTER_ATTEMPTS = 3;
48
+ var jitter = { fraction: () => Math.random() };
49
+ function backoffDelayS(retryNumber, fraction) {
50
+ const exponent = Math.min(Math.max(retryNumber, 0), 62);
51
+ const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
52
+ return Math.min(Math.max(fraction, 0), 1) * ceiling;
53
+ }
54
+ var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
55
+ function parseRetryAfterS(value, nowMs = Date.now()) {
56
+ if (value === null || value === void 0) return null;
57
+ const text = String(value).trim();
58
+ if (text === "") return null;
59
+ if (SECONDS.test(text)) {
60
+ const seconds = Number(text);
61
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
62
+ }
63
+ if (!/[A-Za-z]/.test(text)) return null;
64
+ const when = Date.parse(text);
65
+ if (!Number.isFinite(when)) return null;
66
+ return Math.max(0, (when - nowMs) / 1e3);
67
+ }
68
+
40
69
  // src/globals.ts
41
70
  var import_node_async_hooks = require("async_hooks");
42
71
  var G = globalThis;
@@ -177,6 +206,7 @@ var VALUE_RULE_PREFIXES = new Set(
177
206
  );
178
207
 
179
208
  // src/exporters/batch.ts
209
+ var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
180
210
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
181
211
  var MAX_BATCH_BYTES = 8 * 1024 * 1024;
182
212
  var utf8ByteLength = typeof Buffer !== "undefined" && typeof Buffer.byteLength === "function" ? (s) => Buffer.byteLength(s, "utf8") : (s) => s.length * 3;
@@ -312,7 +342,7 @@ var SUPPLEMENTAL_RULES = [
312
342
  ];
313
343
 
314
344
  // src/version.ts
315
- var SDK_VERSION = "0.10.0";
345
+ var SDK_VERSION = "0.11.0";
316
346
 
317
347
  // src/exporters/quota.ts
318
348
  var QUOTA_REASON = "monthly_quota_exceeded";
@@ -420,12 +450,18 @@ var QuotaPause = class {
420
450
 
421
451
  // src/exporters/http.ts
422
452
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
423
- var RETRY_AFTER_CEILING_MS = 1e4;
424
- var REFUSAL_BACKOFF_BASE_MS = 1e3;
425
- var REFUSAL_NO_HINT = -1;
426
453
  var MISROUTE_WARN_WINDOW_MS = 3e5;
427
454
  var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
428
455
  var FAILURE_WARN_WINDOW_MS = 3e5;
456
+ var MAX_TIMER_MS = 2 ** 31 - 1;
457
+ function validHorizonS(value) {
458
+ if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
459
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
460
+ warn(
461
+ `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
462
+ );
463
+ return DEFAULT_RETRY_HORIZON_S;
464
+ }
429
465
  var HttpExporter = class {
430
466
  name = "http";
431
467
  _endpoint;
@@ -435,20 +471,28 @@ var HttpExporter = class {
435
471
  _timeoutMs;
436
472
  _maxRetries;
437
473
  _compress;
474
+ _retryHorizonS;
475
+ /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
476
+ attempts = 0;
438
477
  // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
439
- // a "30-second prod restart" scenario: with default 1s batch flush a
440
- // 5-failure threshold opens the circuit ~5s into an outage and the 60s
441
- // cooldown gives the gateway time to come back before the half-open
442
- // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
478
+ // a "30-second prod restart" scenario. Since W2-1c only answers that a retry
479
+ // cannot change move it (see the block above).
443
480
  _consecutiveFailures = 0;
444
481
  _lastMisrouteWarnAt = -Infinity;
445
482
  _lastFailureWarnAt = -Infinity;
483
+ _lastExhaustedWarnAt = -Infinity;
484
+ /** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
485
+ _tooLargeWarned = false;
446
486
  /**
447
487
  * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
448
488
  * 'unknown'). `null` after a success. A new kind in the same outage writes one more
449
489
  * WARNING, also inside the window.
450
490
  */
451
491
  _failureKind = null;
492
+ /** `endRetries()` was called, and `shutdown()` has not run since. */
493
+ _noWait = false;
494
+ /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
495
+ _waits = /* @__PURE__ */ new Set();
452
496
  /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
453
497
  _safeEndpoint;
454
498
  /** The endpoint holds userinfo. `fetch` refuses such a URL. */
@@ -459,6 +503,8 @@ var HttpExporter = class {
459
503
  _acks = /* @__PURE__ */ new WeakMap();
460
504
  /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
461
505
  _requests = /* @__PURE__ */ new WeakMap();
506
+ /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
507
+ _dropReasons = /* @__PURE__ */ new WeakMap();
462
508
  /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
463
509
  noteQuotaDrop(count = 1) {
464
510
  this._quota.addDrops(count);
@@ -483,8 +529,16 @@ var HttpExporter = class {
483
529
  this._projectId = options.projectId;
484
530
  this._environment = options.environment;
485
531
  this._timeoutMs = options.timeoutMs ?? 5e3;
486
- this._maxRetries = options.maxRetries ?? 3;
532
+ let maxRetries = options.maxRetries;
533
+ if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
534
+ warn(
535
+ `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).`
536
+ );
537
+ maxRetries = void 0;
538
+ }
539
+ this._maxRetries = maxRetries;
487
540
  this._compress = options.compress ?? false;
541
+ this._retryHorizonS = validHorizonS(options.retryHorizonS);
488
542
  this._safeEndpoint = safeUrl(this._endpoint);
489
543
  this._endpointHasCredentials = hasCredentials(this._endpoint);
490
544
  }
@@ -506,16 +560,18 @@ var HttpExporter = class {
506
560
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
507
561
  return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
508
562
  }
509
- /** The most requests that one `export()` call sends (`maxRetries`). */
563
+ /**
564
+ * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
565
+ * the retry horizon is the limit.
566
+ */
510
567
  get attemptsPerExport() {
511
568
  return this._maxRetries;
512
569
  }
513
570
  /**
514
571
  * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
515
- * it. This is the number that was sent, not the most that the call may send
516
- * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit
517
- * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is
518
- * kept per batch, as `takeAck` keeps the ack.
572
+ * it. Each retry and each half of a 413 split counts one; a call that the open circuit
573
+ * breaker or the quota pause stops sends none. Returns `null` when no call is on record for
574
+ * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
519
575
  */
520
576
  takeAttempts(spans) {
521
577
  const n = this._requests.get(spans) ?? null;
@@ -532,6 +588,12 @@ var HttpExporter = class {
532
588
  this._acks.delete(spans);
533
589
  return ack;
534
590
  }
591
+ /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
592
+ takeDropReason(spans) {
593
+ const reason = this._dropReasons.get(spans) ?? null;
594
+ this._dropReasons.delete(spans);
595
+ return reason;
596
+ }
535
597
  /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
536
598
  takeUnserializable(spans) {
537
599
  const bad = this._unserializable.get(spans) ?? [];
@@ -540,7 +602,7 @@ var HttpExporter = class {
540
602
  }
541
603
  /**
542
604
  * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
543
- * request, its retries and its backoff sleep. The batch processor calls it when
605
+ * request, its retries and its backoff wait. The batch processor calls it when
544
606
  * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
545
607
  * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
546
608
  * logs no WARNING.
@@ -550,24 +612,39 @@ var HttpExporter = class {
550
612
  else for (const call of this._calls.values()) call.cancel.abort();
551
613
  }
552
614
  /**
553
- * Send one batch. The limits are the request timeout and `maxRetries`.
615
+ * End the retry waits of this exporter until its next `shutdown()`. The batch processor
616
+ * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
617
+ * at once. An attempt that fails after this is not retried: the call fails with the drop
618
+ * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
619
+ * batch, not the shutdown budget.
620
+ */
621
+ endRetries() {
622
+ this._noWait = true;
623
+ for (const wake of [...this._waits]) wake();
624
+ }
625
+ /**
626
+ * Send one batch, with the W2-1c retry policy (see the block above the class).
627
+ *
628
+ * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
629
+ * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
630
+ * accounted for: `takeDropReason` then says why, and the batch processor drops the batch
631
+ * with that reason.
554
632
  *
555
633
  * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
556
- * cuts a request that is already sent. A short flush budget that cut the request made a
557
- * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
558
- * the server stored the same spans again. Only `abort()` stops the call, and only
634
+ * cuts a request that is already sent. Only `abort()` stops the call, and only
559
635
  * `shutdown()` calls it.
560
636
  */
561
637
  async export(spans) {
562
638
  if (spans.length === 0) return "success" /* SUCCESS */;
563
639
  const call = {
564
640
  cancel: new AbortController(),
565
- refusalAfterMs: null,
641
+ retryAfterS: null,
566
642
  misroute: null,
567
643
  noRetry: false,
568
644
  status: null,
569
645
  error: null,
570
- attempts: 0
646
+ attempts: 0,
647
+ ack: null
571
648
  };
572
649
  this._calls.set(spans, call);
573
650
  try {
@@ -604,83 +681,236 @@ var HttpExporter = class {
604
681
  );
605
682
  }
606
683
  if (parts.length === 0) return "success" /* SUCCESS */;
607
- const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
608
- const now = Date.now();
609
- let isHalfOpen = false;
610
- if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
611
- if (now < this._circuitOpenUntil) {
612
- return "failure" /* FAILURE */;
684
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
685
+ this._dropReasons.set(spans, "transport_refused");
686
+ return "failure" /* FAILURE */;
687
+ }
688
+ const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
689
+ const start = performance.now();
690
+ await this._deliver(parts, start, call, out, true);
691
+ if (cancelled.aborted || out.cancelled) {
692
+ this._acks.delete(spans);
693
+ return "failure" /* FAILURE */;
694
+ }
695
+ return this._finish(spans, out, call.attempts);
696
+ }
697
+ /** The request body for `parts` (the serialized spans of one part of a batch). */
698
+ _payload(parts) {
699
+ return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
700
+ }
701
+ /**
702
+ * Send one part of a batch with the retry policy, and record its outcome in `out`.
703
+ * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
704
+ * that gets 413 again is dropped as `too_large`.
705
+ */
706
+ async _deliver(parts, start, call, out, maySplit) {
707
+ const n = parts.length;
708
+ if (!maySplit && this._quota.paused()) {
709
+ out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
710
+ return;
711
+ }
712
+ const result = await this._sendWithRetries(this._payload(parts), n, start, call);
713
+ if (result.kind === "delivered") {
714
+ out.delivered.push({ n, ack: result.ack });
715
+ } else if (result.kind === "too_large") {
716
+ if (maySplit && n > 1) {
717
+ const mid = Math.ceil(n / 2);
718
+ debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
719
+ await this._deliver(parts.slice(0, mid), start, call, out, false);
720
+ if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
721
+ } else {
722
+ out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
613
723
  }
614
- isHalfOpen = true;
724
+ } else if (result.kind === "cancelled") {
725
+ out.cancelled = true;
726
+ } else {
727
+ out.failed.push({ n, reason: result.kind, answer: result.answer });
615
728
  }
616
- const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
617
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
618
- call.refusalAfterMs = null;
729
+ }
730
+ /** Send one request body until it is delivered or the policy stops. */
731
+ async _sendWithRetries(body, spansSent, start, call) {
732
+ const cancelled = call.cancel.signal;
733
+ let retryNumber = 0;
734
+ let attemptsHere = 0;
735
+ for (; ; ) {
736
+ if (cancelled.aborted) return { kind: "cancelled" };
737
+ call.retryAfterS = null;
619
738
  call.misroute = null;
620
739
  call.noRetry = false;
621
740
  call.status = null;
622
741
  call.error = null;
742
+ call.ack = null;
623
743
  call.attempts++;
624
- const result = await this._sendRequest(payload, parts.length, call, spans);
625
- if (cancelled.aborted) {
626
- this._acks.delete(spans);
627
- return "failure" /* FAILURE */;
744
+ attemptsHere++;
745
+ this.attempts++;
746
+ const result = await this._sendRequest(body, spansSent, call);
747
+ if (cancelled.aborted) return { kind: "cancelled" };
748
+ if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
749
+ if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
750
+ const answer = {
751
+ status: call.status,
752
+ error: call.error,
753
+ misroute: call.misroute,
754
+ zeroAck: call.noRetry,
755
+ sent: spansSent
756
+ };
757
+ if (!this._retryable(call)) return { kind: "transport_refused", answer };
758
+ if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
759
+ if (this._noWait) return { kind: "shutdown_residue", answer };
760
+ if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
761
+ return { kind: "retry_exhausted", answer };
628
762
  }
629
- if (result === "success" /* SUCCESS */) {
630
- this._consecutiveFailures = 0;
631
- this._failureKind = null;
632
- return result;
633
- }
634
- if (call.misroute !== null || call.noRetry) break;
635
- if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
636
- if (attempt < maxAttempts - 1) {
637
- const refusal = call.refusalAfterMs;
638
- const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
639
- await sleep(delay, cancelled);
640
- if (cancelled.aborted) return "failure" /* FAILURE */;
763
+ const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
764
+ if (remainingS <= 0) return { kind: "retry_exhausted", answer };
765
+ const hint = call.retryAfterS;
766
+ const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
767
+ const delayS = Math.min(waitS, remainingS);
768
+ retryNumber++;
769
+ debug(
770
+ `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
771
+ );
772
+ await this._retryWait(delayS * 1e3, cancelled);
773
+ }
774
+ }
775
+ /** True when the answer of the last attempt of `call` can change on a retry. */
776
+ _retryable(call) {
777
+ if (call.misroute !== null || call.noRetry) return false;
778
+ if (call.status !== null) return RETRY_STATUSES.has(call.status);
779
+ if (this._endpointHasCredentials) return false;
780
+ return call.error !== null;
781
+ }
782
+ /**
783
+ * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
784
+ * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
785
+ * SDK's `shutdown()`, which ends the wait.
786
+ */
787
+ _retryWait(ms, signal) {
788
+ return new Promise((resolve) => {
789
+ if (signal.aborted || this._noWait || ms <= 0) return resolve();
790
+ const done = () => {
791
+ clearTimeout(timer);
792
+ signal.removeEventListener("abort", done);
793
+ this._waits.delete(done);
794
+ resolve();
795
+ };
796
+ const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
797
+ timer.unref?.();
798
+ signal.addEventListener("abort", done, { once: true });
799
+ this._waits.add(done);
800
+ });
801
+ }
802
+ /** Turn the outcome of the parts of one batch into the result of `export()`. */
803
+ _finish(spans, out, attempts) {
804
+ const reasons = new Set(out.failed.map((f) => f.reason));
805
+ if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
806
+ const reason = out.failed[0].reason;
807
+ const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
808
+ this._dropReasons.set(spans, reason);
809
+ return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
810
+ }
811
+ let ack;
812
+ if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
813
+ ack = out.delivered[0].ack;
814
+ } else {
815
+ let accepted = 0;
816
+ let rejected = 0;
817
+ let quotaDropped = 0;
818
+ for (const part of out.delivered) {
819
+ accepted += part.ack !== null ? part.ack.accepted : part.n;
820
+ rejected += part.ack !== null ? part.ack.rejected : 0;
821
+ quotaDropped += part.ack?.quotaDropped ?? 0;
641
822
  }
823
+ const dropped = { ...out.dropped };
824
+ for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
825
+ ack = { accepted, rejected };
826
+ if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
827
+ if (Object.keys(dropped).length > 0) ack.dropped = dropped;
642
828
  }
643
- if (call.refusalAfterMs !== null) {
644
- warn(
645
- `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.`
646
- );
829
+ if (ack !== null) this._acks.set(spans, ack);
830
+ this._consecutiveFailures = 0;
831
+ this._failureKind = null;
832
+ const tooLarge = out.dropped.too_large ?? 0;
833
+ if (tooLarge > 0) this._warnTooLarge(tooLarge);
834
+ for (const f of out.failed) {
835
+ if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
836
+ }
837
+ return "success" /* SUCCESS */;
838
+ }
839
+ /** End a call in which no span was accounted for. Always returns FAILURE. */
840
+ _fail(reason, answer, nSpans, attempts) {
841
+ if (reason === "shutdown_residue") {
842
+ debug(`Export ended by shutdown after ${attempts} attempt(s)`);
647
843
  return "failure" /* FAILURE */;
648
844
  }
649
- const misroute = call.misroute;
650
- if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
651
- this._lastMisrouteWarnAt = Date.now();
652
- warn(
653
- `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.`
654
- );
845
+ if (reason === "retry_exhausted") {
846
+ if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
847
+ this._warnOutage(answer, true);
848
+ this._warnExhausted(nSpans, attempts, answer);
849
+ return "failure" /* FAILURE */;
655
850
  }
851
+ this._stepBreaker();
852
+ this._warnOutage(answer, false);
853
+ return "failure" /* FAILURE */;
854
+ }
855
+ /** Count one failed call toward the circuit breaker. */
856
+ _stepBreaker() {
656
857
  this._consecutiveFailures++;
657
- if (misroute === null && !call.noRetry) {
658
- const status = call.status;
659
- const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
660
- let write = false;
661
- if (this._consecutiveFailures === 1 || this._failureKind === null) {
662
- if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
663
- this._lastFailureWarnAt = Date.now();
664
- write = true;
665
- }
666
- this._failureKind = kind;
667
- } else if (kind !== this._failureKind) {
668
- this._failureKind = kind;
669
- write = true;
670
- }
671
- if (write) this._warnOutage(kind, status, call.error);
672
- }
673
858
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
674
859
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
675
860
  warn(
676
861
  `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
677
862
  );
678
863
  }
679
- return "failure" /* FAILURE */;
680
864
  }
681
- /** The outage WARNING for one kind of failure. */
682
- _warnOutage(kind, status, error) {
865
+ /**
866
+ * The outage WARNING: at the first failure of an outage, and when its kind changes. At most
867
+ * one in the window for the first failure; a misroute has its own WARNING, at most one in
868
+ * the window. `retrying` is true for a retryable answer (written after
869
+ * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
870
+ * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
871
+ * code when there was no answer. It never names the key or the response body, and names
872
+ * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
873
+ * `checkAck`.
874
+ */
875
+ _warnOutage(answer, retrying) {
876
+ if (answer.misroute !== null) {
877
+ if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
878
+ this._lastMisrouteWarnAt = Date.now();
879
+ warn(
880
+ `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.`
881
+ );
882
+ }
883
+ return;
884
+ }
885
+ if (answer.zeroAck) return;
886
+ const status = answer.status;
887
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
888
+ let write = false;
889
+ if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
890
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
891
+ this._lastFailureWarnAt = Date.now();
892
+ write = true;
893
+ }
894
+ this._failureKind = kind;
895
+ } else if (kind !== this._failureKind) {
896
+ this._failureKind = kind;
897
+ write = true;
898
+ }
899
+ if (!write) return;
683
900
  const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
901
+ if (retrying) {
902
+ let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
903
+ if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
904
+ const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
905
+ if (kind === "http") {
906
+ warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
907
+ } else {
908
+ warn(
909
+ `${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.`
910
+ );
911
+ }
912
+ return;
913
+ }
684
914
  const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
685
915
  if (kind === "auth") {
686
916
  warn(
@@ -688,15 +918,11 @@ var HttpExporter = class {
688
918
  );
689
919
  } else if (kind === "http") {
690
920
  warn(
691
- `${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.`
921
+ `${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.`
692
922
  );
693
923
  } else if (kind === "none" && this._endpointHasCredentials) {
694
924
  warn(
695
- `${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}`
696
- );
697
- } else if (kind === "none") {
698
- warn(
699
- `${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.`
925
+ `${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}`
700
926
  );
701
927
  } else {
702
928
  warn(
@@ -704,33 +930,38 @@ var HttpExporter = class {
704
930
  );
705
931
  }
706
932
  }
933
+ /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
934
+ _warnExhausted(nSpans, attempts, answer) {
935
+ if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
936
+ this._lastExhaustedWarnAt = Date.now();
937
+ const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
938
+ const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
939
+ 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)`;
940
+ warn(
941
+ `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.`
942
+ );
943
+ }
944
+ /** The WARNING for spans dropped as `too_large`. One time for each exporter. */
945
+ _warnTooLarge(nSpans) {
946
+ if (this._tooLargeWarned) return;
947
+ this._tooLargeWarned = true;
948
+ warn(
949
+ `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.`
950
+ );
951
+ }
707
952
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
708
953
  _noteMisroute(call, answer) {
709
954
  call.misroute = this._scrub(answer, 300);
710
955
  debug(`Ingest misroute: ${call.misroute}`);
711
956
  return "failure" /* FAILURE */;
712
957
  }
713
- /**
714
- * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
715
- *
716
- * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
717
- * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
718
- * parse.
719
- */
720
- _noteRefusal(call, status, retryAfterRaw) {
721
- if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
722
- let delay = REFUSAL_NO_HINT;
723
- if (retryAfterRaw) {
724
- const secs = Number(retryAfterRaw);
725
- if (Number.isFinite(secs) && secs >= 0) {
726
- delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
727
- }
728
- }
729
- call.refusalAfterMs = delay;
730
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
731
- return true;
958
+ /** Record the `Retry-After` wait of a retryable answer for the retry loop. */
959
+ _noteRetryAfter(call, status, retryAfterRaw) {
960
+ if (!RETRY_STATUSES.has(status)) return;
961
+ call.retryAfterS = parseRetryAfterS(retryAfterRaw);
962
+ debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
732
963
  }
733
- async _sendRequest(body, spansSent, call, spans) {
964
+ async _sendRequest(body, spansSent, call) {
734
965
  const cancelled = call.cancel.signal;
735
966
  const timeoutMs = this._timeoutMs;
736
967
  const url = `${this._endpoint}/v1/spans`;
@@ -798,14 +1029,15 @@ var HttpExporter = class {
798
1029
  } else if (ack.result === "success" /* SUCCESS */) {
799
1030
  this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
800
1031
  }
801
- if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
1032
+ if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
802
1033
  if (ack.final) call.noRetry = true;
803
1034
  return ack.result;
804
- } else if (response.status === 408 || response.status === 504) {
1035
+ }
1036
+ this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
1037
+ if (response.status === 408 || response.status === 504) {
805
1038
  debug(`HTTP export timeout: ${response.status}`);
806
1039
  return "timeout" /* TIMEOUT */;
807
1040
  }
808
- this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
809
1041
  debug(`HTTP export failed: ${response.status}`);
810
1042
  return "failure" /* FAILURE */;
811
1043
  } catch (e) {
@@ -819,20 +1051,9 @@ var HttpExporter = class {
819
1051
  }
820
1052
  }
821
1053
  shutdown() {
1054
+ this._noWait = false;
822
1055
  }
823
1056
  };
824
- function sleep(ms, signal) {
825
- return new Promise((resolve) => {
826
- if (signal?.aborted) return resolve();
827
- const done = () => {
828
- clearTimeout(timer);
829
- signal?.removeEventListener("abort", done);
830
- resolve();
831
- };
832
- const timer = setTimeout(done, ms);
833
- signal?.addEventListener("abort", done, { once: true });
834
- });
835
- }
836
1057
  function asCount(v) {
837
1058
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
838
1059
  }