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
package/dist/index.js CHANGED
@@ -8,6 +8,35 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
8
8
  // src/client.ts
9
9
  import { createHash as createHash2 } from "crypto";
10
10
 
11
+ // src/exporters/retry.ts
12
+ var RETRY_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
13
+ var TOO_LARGE_STATUS = 413;
14
+ var RETRY_BACKOFF_BASE_S = 1;
15
+ var RETRY_BACKOFF_CAP_S = 30;
16
+ var DEFAULT_RETRY_HORIZON_S = 300;
17
+ var DEFAULT_SHUTDOWN_TIMEOUT_S = 10;
18
+ var RETRY_WARN_AFTER_ATTEMPTS = 3;
19
+ var jitter = { fraction: () => Math.random() };
20
+ function backoffDelayS(retryNumber, fraction) {
21
+ const exponent = Math.min(Math.max(retryNumber, 0), 62);
22
+ const ceiling = Math.min(RETRY_BACKOFF_CAP_S, RETRY_BACKOFF_BASE_S * 2 ** exponent);
23
+ return Math.min(Math.max(fraction, 0), 1) * ceiling;
24
+ }
25
+ var SECONDS = /^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$/;
26
+ function parseRetryAfterS(value, nowMs = Date.now()) {
27
+ if (value === null || value === void 0) return null;
28
+ const text = String(value).trim();
29
+ if (text === "") return null;
30
+ if (SECONDS.test(text)) {
31
+ const seconds = Number(text);
32
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds : null;
33
+ }
34
+ if (!/[A-Za-z]/.test(text)) return null;
35
+ const when = Date.parse(text);
36
+ if (!Number.isFinite(when)) return null;
37
+ return Math.max(0, (when - nowMs) / 1e3);
38
+ }
39
+
11
40
  // src/globals.ts
12
41
  import { AsyncLocalStorage } from "async_hooks";
13
42
  var G = globalThis;
@@ -51,9 +80,9 @@ function setDebugFlag(enabled) {
51
80
  var PROVIDER_SPANS = /* @__PURE__ */ Symbol.for("risicare.providerSpans");
52
81
  function usableProviderSpanState(s) {
53
82
  if (!s || typeof s !== "object") return false;
54
- const { version, open, registry } = s;
83
+ const { version, open, registry: registry2 } = s;
55
84
  const o = open;
56
- return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry === void 0 || typeof registry.register === "function");
85
+ return version === 1 && !!o && typeof o.add === "function" && typeof o.delete === "function" && typeof o[Symbol.iterator] === "function" && (registry2 === void 0 || typeof registry2.register === "function");
57
86
  }
58
87
  function getProviderSpanState() {
59
88
  const found = G[PROVIDER_SPANS];
@@ -736,6 +765,31 @@ function warnMaskSlow(spanCount, elapsedMs) {
736
765
  }
737
766
 
738
767
  // src/exporters/batch.ts
768
+ var DECIDED_FAILURES = /* @__PURE__ */ new Set([
769
+ "transport_refused",
770
+ "retry_exhausted",
771
+ "shutdown_residue"
772
+ ]);
773
+ var DECIDED_DROPS = /* @__PURE__ */ new Set([
774
+ "transport_refused",
775
+ "retry_exhausted",
776
+ "shutdown_residue",
777
+ "too_large"
778
+ ]);
779
+ function endMs(span) {
780
+ const end = span?.endTime;
781
+ if (typeof end !== "string") return null;
782
+ const ms = Date.parse(end);
783
+ return Number.isFinite(ms) ? ms : null;
784
+ }
785
+ function oldestEndMs(spans) {
786
+ let oldest = null;
787
+ for (const span of spans) {
788
+ const ms = endMs(span);
789
+ if (ms !== null && (oldest === null || ms < oldest)) oldest = ms;
790
+ }
791
+ return oldest;
792
+ }
739
793
  var DEADLINE = /* @__PURE__ */ Symbol("deadline");
740
794
  async function raceDeadline(p, ms) {
741
795
  let timer;
@@ -760,10 +814,11 @@ async function shutdownExporter(exporter, ms) {
760
814
  }
761
815
  }
762
816
  var SHUTDOWN_RESERVE_MS = 100;
763
- var SHUTDOWN_BUDGET_MS = 5e3;
817
+ var SHUTDOWN_BUDGET_MS = DEFAULT_SHUTDOWN_TIMEOUT_S * 1e3;
818
+ var FLUSH_BUDGET_MS = 5e3;
764
819
  var MAX_TIMEOUT_MS = 2 ** 31 - 1;
765
- function normalizeTimeoutMs(value) {
766
- if (typeof value !== "number" || !Number.isFinite(value)) return SHUTDOWN_BUDGET_MS;
820
+ function normalizeTimeoutMs(value, fallback = FLUSH_BUDGET_MS) {
821
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
767
822
  if (value < 0) return 0;
768
823
  return Math.min(value, MAX_TIMEOUT_MS);
769
824
  }
@@ -908,9 +963,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
908
963
  transport_refused: 0,
909
964
  shutdown_residue: 0,
910
965
  unacknowledged: 0,
911
- quota_exceeded: 0
966
+ quota_exceeded: 0,
967
+ retry_exhausted: 0,
968
+ too_large: 0
912
969
  };
913
970
  exportedSpans = 0;
971
+ /**
972
+ * Export requests (W2-1c): for the SDK's HTTP exporter one for each HTTP request (each retry
973
+ * and each half of a split counts), for another exporter one for each `export()` call.
974
+ */
975
+ attempts = 0;
976
+ /**
977
+ * Spans of a 413 split that `endRetries()` left unsent in the drain of `shutdown()`. They are
978
+ * counted as `shutdown_residue` in their round; the residue WARNING adds them to its
979
+ * in-export number.
980
+ */
981
+ _drainResidue = 0;
914
982
  /**
915
983
  * Spans that the backend acknowledged as REJECTED (the ack's `rejected`). They
916
984
  * are not stored and are not retried. An exporter without an ack adds nothing.
@@ -1023,8 +1091,9 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1023
1091
  * A second call, while the first runs or after it ended, returns the promise
1024
1092
  * of the first one. It does not return before the first drain ends.
1025
1093
  *
1026
- * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
1027
- * the values that are not a finite number.
1094
+ * @param timeoutMs - The budget (default `SHUTDOWN_BUDGET_MS`, 10,000 ms; the client passes
1095
+ * its `shutdownTimeoutS`). See `normalizeTimeoutMs` for the values that are not a finite
1096
+ * number.
1028
1097
  */
1029
1098
  shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
1030
1099
  if (!this._started) return this._closing ?? Promise.resolve();
@@ -1032,9 +1101,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1032
1101
  return this._closing;
1033
1102
  }
1034
1103
  async _shutdown(timeoutMs) {
1035
- timeoutMs = normalizeTimeoutMs(timeoutMs);
1104
+ timeoutMs = normalizeTimeoutMs(timeoutMs, SHUTDOWN_BUDGET_MS);
1036
1105
  this._started = false;
1037
1106
  this._drainOpen = true;
1107
+ this._drainResidue = 0;
1108
+ for (const exporter of this._exporters) {
1109
+ try {
1110
+ exporter.endRetries?.();
1111
+ } catch (e) {
1112
+ debug(`Error ending the retries of ${exporter.name}: ${describeThrown(e)}`);
1113
+ }
1114
+ }
1038
1115
  if (this._timer) {
1039
1116
  clearInterval(this._timer);
1040
1117
  this._timer = null;
@@ -1073,17 +1150,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1073
1150
  }
1074
1151
  }
1075
1152
  }
1076
- const residue = queued + inFlight;
1153
+ const drained = this._drainResidue;
1154
+ this._drainResidue = 0;
1155
+ const counted = queued + inFlight;
1156
+ const unfinished = inFlight + drained;
1157
+ const residue = counted + drained;
1077
1158
  if (residue > 0) {
1078
1159
  this._queue.length = 0;
1079
- this._recordDropped("shutdown_residue", residue);
1160
+ if (counted > 0) this._recordDropped("shutdown_residue", counted);
1080
1161
  if (this._quotaPaused()) {
1081
1162
  warn(
1082
- `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${inFlight} in an export that shutdown() stopped. The monthly event quota is used up and export is paused until the next probe, so these spans could not be sent. A longer shutdown timeout does not help. Upgrade the plan or wait for the quota to reset.`
1163
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${unfinished} in an export that shutdown() stopped. The monthly event quota is used up and export is paused until the next probe, so these spans could not be sent. A longer shutdown timeout does not help. Upgrade the plan or wait for the quota to reset.`
1083
1164
  );
1084
1165
  } else {
1085
1166
  warn(
1086
- `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${inFlight} in an export that shutdown() stopped. ` + (inFlight > 0 ? `The server may have received the ${inFlight} span(s) of the stopped export. ` : "") + `All ${residue} were not confirmed as delivered, and are counted as dropped. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Pass a larger timeout to shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`
1167
+ `shutdown() gave up with ${residue} span(s) (reason=shutdown_residue): ${queued} still queued and ${unfinished} in an export that shutdown() stopped. ` + (inFlight > 0 ? `The server may have received the ${inFlight} span(s) of the stopped export. ` : "") + `All ${residue} were not confirmed as delivered, and are counted as dropped. The ${timeoutMs} ms shutdown budget expired or the transport stopped accepting. Pass a larger timeout to shutdown(timeoutMs), or raise your container's termination grace period, to lose less.`
1087
1168
  );
1088
1169
  }
1089
1170
  }
@@ -1107,8 +1188,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1107
1188
  _enqueue(span, exportAtBatchSize) {
1108
1189
  if (this._queue.length >= this._maxQueueSize) {
1109
1190
  if (this._quotaPaused()) {
1110
- const oldest = this._queue.shift();
1111
- if (oldest !== void 0) this._forgetRetry(oldest.spanId);
1191
+ const oldest2 = this._queue.shift();
1192
+ if (oldest2 !== void 0) this._forgetRetry(oldest2.spanId);
1112
1193
  this._recordDropped("quota_exceeded");
1113
1194
  for (const exporter of this._exporters) {
1114
1195
  try {
@@ -1119,9 +1200,16 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1119
1200
  this._queue.push(span);
1120
1201
  return;
1121
1202
  }
1203
+ const oldest = this._queue.shift();
1204
+ if (oldest !== void 0) {
1205
+ this._forgetRetry(oldest.spanId);
1206
+ this._queue.push(span);
1207
+ }
1122
1208
  this._recordDropped("queue_full");
1123
1209
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
1124
- warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
1210
+ warn(
1211
+ `Span queue full (${this._maxQueueSize}): the oldest queued span is dropped and the new one is kept (reason=queue_full). ${this.droppedSpans} spans dropped so far.`
1212
+ );
1125
1213
  }
1126
1214
  return;
1127
1215
  }
@@ -1220,7 +1308,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1220
1308
  * conservative direction on purpose: a false negative costs a caller one
1221
1309
  * more flush, a false positive is the defect being fixed.
1222
1310
  */
1223
- async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
1311
+ async flush(timeoutMs = FLUSH_BUDGET_MS) {
1224
1312
  timeoutMs = normalizeTimeoutMs(timeoutMs);
1225
1313
  const deadline = Date.now() + timeoutMs;
1226
1314
  const mark = this._lossMark;
@@ -1240,6 +1328,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1240
1328
  while (this._queue.length > 0 || this._flushing) {
1241
1329
  const remaining = deadline - Date.now();
1242
1330
  if (remaining <= 0) return finish(false);
1331
+ if (!this._started && this._closing !== null) {
1332
+ const closed = await raceDeadline(this._closing.catch(() => void 0), remaining);
1333
+ if (closed === DEADLINE) return finish(false);
1334
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
1335
+ return finish(this._queue.length === 0 && !held);
1336
+ }
1243
1337
  if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);
1244
1338
  if (!this._flushing && this._queue.length > 0) {
1245
1339
  const outcome = await raceDeadline(this._exportBatch(), remaining);
@@ -1252,6 +1346,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1252
1346
  return finish(true);
1253
1347
  }
1254
1348
  getMetrics() {
1349
+ const ends = [];
1350
+ const head = endMs(this._queue[0]);
1351
+ if (head !== null) ends.push(head);
1352
+ const flight = this._inFlight;
1353
+ if (flight !== null && !flight.abandoned && flight.oldestEndMs !== null) ends.push(flight.oldestEndMs);
1354
+ const oldestPendingAgeS = ends.length > 0 ? Math.max(0, (Date.now() - Math.min(...ends)) / 1e3) : 0;
1255
1355
  return {
1256
1356
  exportedSpans: this.exportedSpans,
1257
1357
  rejectedSpans: this.rejectedSpans,
@@ -1261,6 +1361,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1261
1361
  // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.
1262
1362
  droppedQuota: this.droppedSpansByReason.quota_exceeded,
1263
1363
  failedExports: this.failedExports,
1364
+ /**
1365
+ * W2-1c: export requests (each retry and each half of a 413 split counts), added when the
1366
+ * export call ends: a batch that still retries is not in it yet.
1367
+ */
1368
+ attempts: this.attempts,
1369
+ /**
1370
+ * W2-1c: the age in seconds of the oldest span that is queued or in an export (its end
1371
+ * time to now). 0 when nothing is pending. It grows during an outage, up to the retry
1372
+ * horizon for the batch in an export.
1373
+ */
1374
+ oldestPendingAgeS,
1264
1375
  maskErrors: this.maskErrors,
1265
1376
  queueSize: this._queue.length,
1266
1377
  queueCapacity: this._maxQueueSize,
@@ -1287,6 +1398,17 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1287
1398
  n -= quota;
1288
1399
  if (n === 0) return;
1289
1400
  }
1401
+ for (const [reason, count] of Object.entries(ack.dropped ?? {})) {
1402
+ if (!DECIDED_DROPS.has(reason) || typeof count !== "number" || !Number.isInteger(count) || count <= 0) {
1403
+ continue;
1404
+ }
1405
+ const take = Math.min(count, n);
1406
+ if (take === 0) continue;
1407
+ this._recordDropped(reason, take);
1408
+ if (reason === "shutdown_residue") this._drainResidue += take;
1409
+ n -= take;
1410
+ }
1411
+ if (n === 0) return;
1290
1412
  const rejected = Math.min(ack.rejected, n);
1291
1413
  const accepted = Math.min(ack.accepted, n - rejected);
1292
1414
  const unacknowledged = n - accepted - rejected;
@@ -1314,13 +1436,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1314
1436
  return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : void 0;
1315
1437
  }
1316
1438
  /**
1317
- * The HTTP requests that the failed round for `batch` really sent (issue #57). `undefined`
1318
- * when the exporter that delivers does not state it, so that the WARNING keeps its "up to"
1319
- * text. NaN when the exporter has no record of the round.
1439
+ * The HTTP requests that `exporter`'s `export()` call for `batch` really sent (issue #57,
1440
+ * W2-1c). `undefined` when the exporter does not state it. NaN when it has no record of the
1441
+ * call, or the read threw.
1320
1442
  */
1321
- _requestsSent(batch) {
1322
- const exporter = this._soleDeliverer();
1323
- if (exporter === void 0 || typeof exporter.takeAttempts !== "function") return void 0;
1443
+ _takeAttempts(exporter, batch) {
1444
+ if (typeof exporter.takeAttempts !== "function") return void 0;
1324
1445
  try {
1325
1446
  const n = exporter.takeAttempts(batch);
1326
1447
  return typeof n === "number" && Number.isFinite(n) && n >= 0 ? n : Number.NaN;
@@ -1329,6 +1450,45 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1329
1450
  return Number.NaN;
1330
1451
  }
1331
1452
  }
1453
+ /**
1454
+ * The drop reason of `exporter`'s failed `export()` call for `batch` (W2-1c), or `null`: the
1455
+ * exporter does not classify its failure, and the batch gets the bounded re-queue.
1456
+ */
1457
+ _takeDropReason(exporter, batch) {
1458
+ if (typeof exporter.takeDropReason !== "function") return null;
1459
+ try {
1460
+ const reason = exporter.takeDropReason(batch);
1461
+ return typeof reason === "string" && DECIDED_FAILURES.has(reason) ? reason : null;
1462
+ } catch (e) {
1463
+ debug(`takeDropReason of ${exporter.name} failed: ${describeThrown(e)}`);
1464
+ return null;
1465
+ }
1466
+ }
1467
+ /**
1468
+ * A failed batch whose fate the exporter decided (`takeDropReason`, W2-1c).
1469
+ *
1470
+ * `transport_refused` and `retry_exhausted`: every span is dropped with that reason at once,
1471
+ * and COUNTED. A re-queue would only send it to the same answer, or past the retry horizon.
1472
+ * `shutdown_residue`: `endRetries()` ended the retries in the drain of `shutdown()`. The
1473
+ * batch goes back to the head of the queue, uncounted, and `shutdown()` counts it with the
1474
+ * queue in its one residue WARNING.
1475
+ */
1476
+ _dropDecided(batch, unserializable, reason) {
1477
+ const spans = batch.filter((span) => !unserializable.has(span));
1478
+ if (reason === "shutdown_residue") {
1479
+ this._queue.unshift(...spans);
1480
+ return;
1481
+ }
1482
+ for (const span of spans) this._forgetRetry(span.spanId);
1483
+ this._recordDropped(reason, spans.length);
1484
+ if (reason !== "transport_refused" || spans.length === 0) return;
1485
+ const now = Date.now();
1486
+ if (now - this._lastRefusalWarnAt <= REFUSAL_WARN_WINDOW_MS) return;
1487
+ this._lastRefusalWarnAt = now;
1488
+ warn(
1489
+ `${spans.length} span(s) DISCARDED (reason=transport_refused): the endpoint gave an answer that a retry cannot change, so the batch was sent once. ${this.droppedSpansByReason.transport_refused} span(s) discarded this way so far in this process. This data is gone; check the apiKey and the endpoint.`
1490
+ );
1491
+ }
1332
1492
  /** End the retry tracking of one span (retry-map drain sites 1 and 2 of 3, and the queue drop). */
1333
1493
  _forgetRetry(spanId) {
1334
1494
  this._retryCounts.delete(spanId);
@@ -1366,7 +1526,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1366
1526
  }
1367
1527
  const batch = this._queue.splice(0, take);
1368
1528
  if (batch.length === 0) return 0 /* Empty */;
1369
- flight = { spans: batch, size: batch.length, abandoned: false };
1529
+ flight = { spans: batch, size: batch.length, abandoned: false, oldestEndMs: oldestEndMs(batch) };
1370
1530
  this._inFlight = flight;
1371
1531
  if (!this._traceContent) {
1372
1532
  const stripped = stripContentBatch(batch);
@@ -1383,12 +1543,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1383
1543
  let batchExported = false;
1384
1544
  const anyDelivers = this._exporters.some((e) => e.countsAsDelivery !== false);
1385
1545
  const unserializable = /* @__PURE__ */ new Set();
1546
+ let failReason = null;
1547
+ let failedDecider = false;
1548
+ const sole = this._soleDeliverer();
1549
+ let sent;
1386
1550
  for (const exporter of this._exporters) {
1387
1551
  const decides = !anyDelivers || exporter.countsAsDelivery !== false;
1388
1552
  try {
1389
1553
  const result = await exporter.export(batch);
1390
1554
  if (flight.abandoned) return 2 /* Failed */;
1391
1555
  if (!decides) continue;
1556
+ if (exporter.countsAsDelivery !== false) {
1557
+ const requests = this._takeAttempts(exporter, batch);
1558
+ this.attempts += requests !== void 0 && Number.isFinite(requests) ? requests : 1;
1559
+ if (exporter === sole) sent = requests;
1560
+ }
1392
1561
  for (const span of exporter.takeUnserializable?.(batch) ?? []) unserializable.add(span);
1393
1562
  if (result === "success" /* SUCCESS */) {
1394
1563
  const ack = exporter.takeAck?.(batch) ?? null;
@@ -1401,18 +1570,26 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
1401
1570
  }
1402
1571
  } else {
1403
1572
  this.failedExports++;
1573
+ if (!failedDecider && exporter.countsAsDelivery !== false) {
1574
+ failedDecider = true;
1575
+ failReason = this._takeDropReason(exporter, batch);
1576
+ }
1404
1577
  }
1405
1578
  } catch (e) {
1406
1579
  if (flight.abandoned) return 2 /* Failed */;
1407
1580
  if (!decides) continue;
1581
+ if (exporter.countsAsDelivery !== false) this.attempts++;
1408
1582
  this.failedExports++;
1409
1583
  debug(`Export to ${exporter.name} failed: ${describeThrown(e)}`);
1410
1584
  }
1411
1585
  }
1412
1586
  if (unserializable.size > 0) this._recordDropped("unacknowledged", unserializable.size);
1587
+ if (!batchExported && failReason !== null) {
1588
+ this._dropDecided(batch, unserializable, failReason);
1589
+ return 2 /* Failed */;
1590
+ }
1413
1591
  if (!batchExported) {
1414
1592
  let dropped = 0;
1415
- const sent = this._requestsSent(batch);
1416
1593
  const droppedRequests = [];
1417
1594
  const retryable = batch.filter((span) => {
1418
1595
  if (unserializable.has(span)) return false;
@@ -1528,6 +1705,12 @@ function resolveConfig(config) {
1528
1705
  const batchSize = validatePositiveInt("batchSize", batchSizeRaw, DEFAULT_BATCH_SIZE, 1, 1e4);
1529
1706
  const batchTimeoutMs = validatePositiveInt("batchTimeoutMs", batchTimeoutMsRaw, 1e3, 1, 6e5);
1530
1707
  const maxQueueSize = validatePositiveInt("maxQueueSize", maxQueueSizeRaw, 1e4, 1, 1e6);
1708
+ const retryHorizonS = validateSeconds("retryHorizonS", config?.retryHorizonS, DEFAULT_RETRY_HORIZON_S);
1709
+ const shutdownTimeoutS = validateSeconds(
1710
+ "shutdownTimeoutS",
1711
+ config?.shutdownTimeoutS,
1712
+ DEFAULT_SHUTDOWN_TIMEOUT_S
1713
+ );
1531
1714
  let enabled;
1532
1715
  const tracingEnv = config?.enabled === void 0 ? tracingFromEnv(env.RISICARE_TRACING) : void 0;
1533
1716
  if (config?.enabled !== void 0) {
@@ -1552,6 +1735,8 @@ function resolveConfig(config) {
1552
1735
  batchSize,
1553
1736
  batchTimeoutMs,
1554
1737
  maxQueueSize,
1738
+ retryHorizonS,
1739
+ shutdownTimeoutS,
1555
1740
  debug: debug2,
1556
1741
  compress,
1557
1742
  fixRuntime,
@@ -1614,6 +1799,14 @@ function validateSampleRate(value) {
1614
1799
  );
1615
1800
  return 1;
1616
1801
  }
1802
+ function validateSeconds(name, value, defaultValue) {
1803
+ if (value === void 0) return defaultValue;
1804
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
1805
+ warn(
1806
+ `Risicare: ${name}=${String(value)} is not a finite number of seconds of 0 or more; using the default, ${defaultValue} s.`
1807
+ );
1808
+ return defaultValue;
1809
+ }
1617
1810
  function validatePositiveInt(name, value, defaultValue, min, max) {
1618
1811
  let n;
1619
1812
  if (typeof value === "number") {
@@ -1648,6 +1841,178 @@ function validatePositiveInt(name, value, defaultValue, min, max) {
1648
1841
  return Math.floor(n);
1649
1842
  }
1650
1843
 
1844
+ // src/context/storage.ts
1845
+ function storage() {
1846
+ return getContextStorage();
1847
+ }
1848
+ function getContext() {
1849
+ return storage().getStore() ?? {};
1850
+ }
1851
+ function hasContextScope() {
1852
+ return storage().getStore() !== void 0;
1853
+ }
1854
+ function runWithContext(overrides, fn) {
1855
+ const parent = getContext();
1856
+ const merged = { ...parent, ...overrides };
1857
+ return storage().run(merged, fn);
1858
+ }
1859
+ function getCurrentSession() {
1860
+ return getContext().session;
1861
+ }
1862
+ function getCurrentAgent() {
1863
+ return getContext().agent;
1864
+ }
1865
+ function getCurrentSpan() {
1866
+ return getContext().span;
1867
+ }
1868
+ function getCurrentPhase() {
1869
+ return getContext().phase;
1870
+ }
1871
+ function getCurrentSessionId() {
1872
+ return getContext().session?.sessionId;
1873
+ }
1874
+ function getCurrentAgentId() {
1875
+ return getContext().agent?.agentId;
1876
+ }
1877
+ function getCurrentTraceId() {
1878
+ return getContext().span?.traceId;
1879
+ }
1880
+ function getCurrentSpanId() {
1881
+ return getContext().span?.spanId;
1882
+ }
1883
+ function getCurrentContext() {
1884
+ const ctx = getContext();
1885
+ return {
1886
+ session: ctx.session ? {
1887
+ sessionId: ctx.session.sessionId,
1888
+ userId: ctx.session.userId,
1889
+ ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
1890
+ ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
1891
+ ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
1892
+ } : null,
1893
+ agent: ctx.agent ? {
1894
+ agentId: ctx.agent.agentId,
1895
+ agentName: ctx.agent.agentName,
1896
+ agentRole: ctx.agent.agentRole,
1897
+ agentType: ctx.agent.agentType,
1898
+ ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
1899
+ ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
1900
+ ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
1901
+ } : null,
1902
+ span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
1903
+ phase: ctx.phase ?? null
1904
+ };
1905
+ }
1906
+
1907
+ // src/identity.ts
1908
+ var USER_ATTRIBUTE = "user.id";
1909
+ var SESSION_ATTRIBUTE = "session.id";
1910
+ var RELEASE_ATTRIBUTE = "risicare.release";
1911
+ var TAGS_ATTRIBUTE = "tag.tags";
1912
+ var MAX_TRACES = 1e4;
1913
+ var REGISTRY = /* @__PURE__ */ Symbol.for("risicare.identity");
1914
+ function registry() {
1915
+ const g = globalThis;
1916
+ let r = g[REGISTRY];
1917
+ if (r === void 0) {
1918
+ r = { traces: /* @__PURE__ */ new Map(), warned: /* @__PURE__ */ new Set() };
1919
+ g[REGISTRY] = r;
1920
+ }
1921
+ return r;
1922
+ }
1923
+ function warnOnce(helper, text) {
1924
+ const r = registry();
1925
+ if (r.warned.has(helper)) return;
1926
+ r.warned.add(helper);
1927
+ warn(`Risicare: ${helper}() ${text} Nothing was set.`);
1928
+ }
1929
+ function asText(helper, value) {
1930
+ let text;
1931
+ if (typeof value === "string") text = value.trim();
1932
+ else if (typeof value === "number" && Number.isInteger(value)) text = String(value);
1933
+ else {
1934
+ warnOnce(helper, `takes a non-empty string; it got ${value === null ? "null" : typeof value}.`);
1935
+ return null;
1936
+ }
1937
+ if (text === "") {
1938
+ warnOnce(helper, "takes a non-empty string; it got an empty one.");
1939
+ return null;
1940
+ }
1941
+ return text;
1942
+ }
1943
+ function mergeTags(old, add) {
1944
+ const merged = Array.isArray(old) ? old.filter((t) => typeof t === "string") : [];
1945
+ for (const tag of add) if (!merged.includes(tag)) merged.push(tag);
1946
+ return merged;
1947
+ }
1948
+ function set(helper, key, value) {
1949
+ const span = getCurrentSpan();
1950
+ const traceId = span?.traceId;
1951
+ if (span === void 0 || typeof traceId !== "string" || traceId === "") {
1952
+ warnOnce(
1953
+ helper,
1954
+ "was called outside a span, so there is no current trace. Call it inside a span (startSpan(), a decorated function), or use withSession() for a value that must apply before the first span."
1955
+ );
1956
+ return false;
1957
+ }
1958
+ const r = registry();
1959
+ const values = r.traces.get(traceId) ?? {};
1960
+ r.traces.delete(traceId);
1961
+ values[key] = key === TAGS_ATTRIBUTE ? mergeTags(values[key], value) : value;
1962
+ r.traces.set(traceId, values);
1963
+ while (r.traces.size > MAX_TRACES) {
1964
+ const oldest = r.traces.keys().next().value;
1965
+ r.traces.delete(oldest);
1966
+ }
1967
+ span.setAttribute(key, key === TAGS_ATTRIBUTE ? mergeTags(span.attributes[key], value) : value);
1968
+ return true;
1969
+ }
1970
+ function setUser(userId) {
1971
+ const text = asText("setUser", userId);
1972
+ return text !== null && set("setUser", USER_ATTRIBUTE, text);
1973
+ }
1974
+ function setSession(sessionId) {
1975
+ const text = asText("setSession", sessionId);
1976
+ return text !== null && set("setSession", SESSION_ATTRIBUTE, text);
1977
+ }
1978
+ function setRelease(version) {
1979
+ const text = asText("setRelease", version);
1980
+ return text !== null && set("setRelease", RELEASE_ATTRIBUTE, text);
1981
+ }
1982
+ function addTags(tags) {
1983
+ if (!Array.isArray(tags)) {
1984
+ warnOnce("addTags", `takes an array of strings; it got ${tags === null ? "null" : typeof tags}.`);
1985
+ return false;
1986
+ }
1987
+ const clean = [];
1988
+ for (const tag of tags) {
1989
+ const text = typeof tag === "string" ? tag.trim() : "";
1990
+ if (text === "") {
1991
+ warnOnce("addTags", "takes non-empty strings; it got another item, left out.");
1992
+ continue;
1993
+ }
1994
+ if (!clean.includes(text)) clean.push(text);
1995
+ }
1996
+ if (clean.length === 0) return false;
1997
+ return set("addTags", TAGS_ATTRIBUTE, clean);
1998
+ }
1999
+ function applyIdentity(span) {
2000
+ const r = registry();
2001
+ if (r.traces.size === 0) return;
2002
+ const values = r.traces.get(span.traceId);
2003
+ if (values === void 0) return;
2004
+ const attributes = span.attributes;
2005
+ for (const [key, value] of Object.entries(values)) {
2006
+ if (key === TAGS_ATTRIBUTE) {
2007
+ if (!(key in attributes) || Array.isArray(attributes[key])) {
2008
+ attributes[key] = mergeTags(attributes[key], value);
2009
+ }
2010
+ } else if (!(key in attributes)) {
2011
+ attributes[key] = value;
2012
+ }
2013
+ }
2014
+ }
2015
+
1651
2016
  // src/ids.ts
1652
2017
  import { randomBytes } from "crypto";
1653
2018
  var HEX_REGEX_32 = /^[0-9a-f]{32}$/;
@@ -2472,69 +2837,6 @@ function classifyError(error) {
2472
2837
  return CANONICAL_ERROR_CODES.has(GENERIC_FALLBACK) ? GENERIC_FALLBACK : "";
2473
2838
  }
2474
2839
 
2475
- // src/context/storage.ts
2476
- function storage() {
2477
- return getContextStorage();
2478
- }
2479
- function getContext() {
2480
- return storage().getStore() ?? {};
2481
- }
2482
- function hasContextScope() {
2483
- return storage().getStore() !== void 0;
2484
- }
2485
- function runWithContext(overrides, fn) {
2486
- const parent = getContext();
2487
- const merged = { ...parent, ...overrides };
2488
- return storage().run(merged, fn);
2489
- }
2490
- function getCurrentSession() {
2491
- return getContext().session;
2492
- }
2493
- function getCurrentAgent() {
2494
- return getContext().agent;
2495
- }
2496
- function getCurrentSpan() {
2497
- return getContext().span;
2498
- }
2499
- function getCurrentPhase() {
2500
- return getContext().phase;
2501
- }
2502
- function getCurrentSessionId() {
2503
- return getContext().session?.sessionId;
2504
- }
2505
- function getCurrentAgentId() {
2506
- return getContext().agent?.agentId;
2507
- }
2508
- function getCurrentTraceId() {
2509
- return getContext().span?.traceId;
2510
- }
2511
- function getCurrentSpanId() {
2512
- return getContext().span?.spanId;
2513
- }
2514
- function getCurrentContext() {
2515
- const ctx = getContext();
2516
- return {
2517
- session: ctx.session ? {
2518
- sessionId: ctx.session.sessionId,
2519
- userId: ctx.session.userId,
2520
- ...ctx.session.parentSessionId !== void 0 ? { parentSessionId: ctx.session.parentSessionId } : {},
2521
- ...ctx.session.turnNumber !== void 0 ? { turnNumber: ctx.session.turnNumber } : {},
2522
- ...ctx.session.metadata !== void 0 ? { metadata: ctx.session.metadata } : {}
2523
- } : null,
2524
- agent: ctx.agent ? {
2525
- agentId: ctx.agent.agentId,
2526
- agentName: ctx.agent.agentName,
2527
- agentRole: ctx.agent.agentRole,
2528
- agentType: ctx.agent.agentType,
2529
- ...ctx.agent.parentAgentId !== void 0 ? { parentAgentId: ctx.agent.parentAgentId } : {},
2530
- ...ctx.agent.version !== void 0 ? { version: ctx.agent.version } : {},
2531
- ...ctx.agent.metadata !== void 0 ? { metadata: ctx.agent.metadata } : {}
2532
- } : null,
2533
- span: ctx.span ? { spanId: ctx.span.spanId, traceId: ctx.span.traceId } : null,
2534
- phase: ctx.phase ?? null
2535
- };
2536
- }
2537
-
2538
2840
  // src/tracer.ts
2539
2841
  function attachErrorCode(span, error) {
2540
2842
  try {
@@ -2555,7 +2857,11 @@ var Tracer = class {
2555
2857
  _serviceName;
2556
2858
  _serviceVersion;
2557
2859
  constructor(config) {
2558
- this._onSpanEnd = config.onSpanEnd;
2860
+ const onSpanEnd = config.onSpanEnd;
2861
+ this._onSpanEnd = (span) => {
2862
+ applyIdentity(span);
2863
+ onSpanEnd(span);
2864
+ };
2559
2865
  this._sampleRate = config.sampleRate ?? 1;
2560
2866
  this._enabled = config.enabled ?? true;
2561
2867
  this._traceContent = config.traceContent ?? false;
@@ -2716,7 +3022,7 @@ function markCancel(span, error) {
2716
3022
  }
2717
3023
 
2718
3024
  // src/version.ts
2719
- var SDK_VERSION = "0.10.0";
3025
+ var SDK_VERSION = "0.11.0";
2720
3026
 
2721
3027
  // src/exporters/quota.ts
2722
3028
  var QUOTA_REASON = "monthly_quota_exceeded";
@@ -2824,12 +3130,18 @@ var QuotaPause = class {
2824
3130
 
2825
3131
  // src/exporters/http.ts
2826
3132
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
2827
- var RETRY_AFTER_CEILING_MS = 1e4;
2828
- var REFUSAL_BACKOFF_BASE_MS = 1e3;
2829
- var REFUSAL_NO_HINT = -1;
2830
3133
  var MISROUTE_WARN_WINDOW_MS = 3e5;
2831
3134
  var AUTH_REFUSAL_STATUSES = /* @__PURE__ */ new Set([401, 403]);
2832
3135
  var FAILURE_WARN_WINDOW_MS = 3e5;
3136
+ var MAX_TIMER_MS = 2 ** 31 - 1;
3137
+ function validHorizonS(value) {
3138
+ if (value === void 0) return DEFAULT_RETRY_HORIZON_S;
3139
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
3140
+ warn(
3141
+ `Risicare: retryHorizonS=${String(value)} is not a finite number of 0 or more; using the default, ${DEFAULT_RETRY_HORIZON_S} s.`
3142
+ );
3143
+ return DEFAULT_RETRY_HORIZON_S;
3144
+ }
2833
3145
  var HttpExporter = class {
2834
3146
  name = "http";
2835
3147
  _endpoint;
@@ -2839,20 +3151,28 @@ var HttpExporter = class {
2839
3151
  _timeoutMs;
2840
3152
  _maxRetries;
2841
3153
  _compress;
3154
+ _retryHorizonS;
3155
+ /** Total HTTP requests that this exporter sent (each retry and each half of a split counts). */
3156
+ attempts = 0;
2842
3157
  // Circuit breaker (CON-201 / B-16). Threshold and cooldown sized for
2843
- // a "30-second prod restart" scenario: with default 1s batch flush a
2844
- // 5-failure threshold opens the circuit ~5s into an outage and the 60s
2845
- // cooldown gives the gateway time to come back before the half-open
2846
- // probe fires. Lower numbers (was 3@30s) tripped on transient blips.
3158
+ // a "30-second prod restart" scenario. Since W2-1c only answers that a retry
3159
+ // cannot change move it (see the block above).
2847
3160
  _consecutiveFailures = 0;
2848
3161
  _lastMisrouteWarnAt = -Infinity;
2849
3162
  _lastFailureWarnAt = -Infinity;
3163
+ _lastExhaustedWarnAt = -Infinity;
3164
+ /** "log once" (W2-1c): the WARNING for a `too_large` drop is written one time. */
3165
+ _tooLargeWarned = false;
2850
3166
  /**
2851
3167
  * The kind of failure that the last outage WARNING named ('auth', 'http', 'none',
2852
3168
  * 'unknown'). `null` after a success. A new kind in the same outage writes one more
2853
3169
  * WARNING, also inside the window.
2854
3170
  */
2855
3171
  _failureKind = null;
3172
+ /** `endRetries()` was called, and `shutdown()` has not run since. */
3173
+ _noWait = false;
3174
+ /** The wake-ups of the backoff waits in progress. `endRetries()` calls each one. */
3175
+ _waits = /* @__PURE__ */ new Set();
2856
3176
  /** The endpoint as a log line may show it: no userinfo, no query (see `safeUrl`). */
2857
3177
  _safeEndpoint;
2858
3178
  /** The endpoint holds userinfo. `fetch` refuses such a URL. */
@@ -2863,6 +3183,8 @@ var HttpExporter = class {
2863
3183
  _acks = /* @__PURE__ */ new WeakMap();
2864
3184
  /** The requests that each finished call sent, by its batch. Read once by `takeAttempts(spans)`. */
2865
3185
  _requests = /* @__PURE__ */ new WeakMap();
3186
+ /** The drop reason of each failed call, by its batch. Read once by `takeDropReason(spans)`. */
3187
+ _dropReasons = /* @__PURE__ */ new WeakMap();
2866
3188
  /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
2867
3189
  noteQuotaDrop(count = 1) {
2868
3190
  this._quota.addDrops(count);
@@ -2887,8 +3209,16 @@ var HttpExporter = class {
2887
3209
  this._projectId = options.projectId;
2888
3210
  this._environment = options.environment;
2889
3211
  this._timeoutMs = options.timeoutMs ?? 5e3;
2890
- this._maxRetries = options.maxRetries ?? 3;
3212
+ let maxRetries = options.maxRetries;
3213
+ if (maxRetries !== void 0 && !(Number.isInteger(maxRetries) && maxRetries >= 1)) {
3214
+ warn(
3215
+ `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).`
3216
+ );
3217
+ maxRetries = void 0;
3218
+ }
3219
+ this._maxRetries = maxRetries;
2891
3220
  this._compress = options.compress ?? false;
3221
+ this._retryHorizonS = validHorizonS(options.retryHorizonS);
2892
3222
  this._safeEndpoint = safeUrl(this._endpoint);
2893
3223
  this._endpointHasCredentials = hasCredentials(this._endpoint);
2894
3224
  }
@@ -2910,16 +3240,18 @@ var HttpExporter = class {
2910
3240
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")]() {
2911
3241
  return `HttpExporter { endpoint: '${this._safeEndpoint}' }`;
2912
3242
  }
2913
- /** The most requests that one `export()` call sends (`maxRetries`). */
3243
+ /**
3244
+ * The most attempts for one request body (`maxRetries`). `undefined` when no count is set:
3245
+ * the retry horizon is the limit.
3246
+ */
2914
3247
  get attemptsPerExport() {
2915
3248
  return this._maxRetries;
2916
3249
  }
2917
3250
  /**
2918
3251
  * Returns the number of HTTP requests that the `export()` call for `spans` sent, and clears
2919
- * it. This is the number that was sent, not the most that the call may send
2920
- * (`attemptsPerExport`): a 401 or 403 stops the loop after one request, and an open circuit
2921
- * breaker sends none. Returns `null` when no call is on record for `spans`. The answer is
2922
- * kept per batch, as `takeAck` keeps the ack.
3252
+ * it. Each retry and each half of a 413 split counts one; a call that the open circuit
3253
+ * breaker or the quota pause stops sends none. Returns `null` when no call is on record for
3254
+ * `spans`. The answer is kept per batch, as `takeAck` keeps the ack.
2923
3255
  */
2924
3256
  takeAttempts(spans) {
2925
3257
  const n = this._requests.get(spans) ?? null;
@@ -2936,6 +3268,12 @@ var HttpExporter = class {
2936
3268
  this._acks.delete(spans);
2937
3269
  return ack;
2938
3270
  }
3271
+ /** Returns why the `export()` call for `spans` failed (W2-1c), and clears it. See `SpanExporter`. */
3272
+ takeDropReason(spans) {
3273
+ const reason = this._dropReasons.get(spans) ?? null;
3274
+ this._dropReasons.delete(spans);
3275
+ return reason;
3276
+ }
2939
3277
  /** Returns the spans of `spans` that could not be serialized and were not sent, and clears them. */
2940
3278
  takeUnserializable(spans) {
2941
3279
  const bad = this._unserializable.get(spans) ?? [];
@@ -2944,7 +3282,7 @@ var HttpExporter = class {
2944
3282
  }
2945
3283
  /**
2946
3284
  * Cancel the `export()` call for `spans` (all calls when `spans` is not given): its
2947
- * request, its retries and its backoff sleep. The batch processor calls it when
3285
+ * request, its retries and its backoff wait. The batch processor calls it when
2948
3286
  * `shutdown()` abandons the batch, so that the call does not keep the process alive. The
2949
3287
  * cancelled call returns FAILURE, changes no counter (the circuit breaker included) and
2950
3288
  * logs no WARNING.
@@ -2954,24 +3292,39 @@ var HttpExporter = class {
2954
3292
  else for (const call of this._calls.values()) call.cancel.abort();
2955
3293
  }
2956
3294
  /**
2957
- * Send one batch. The limits are the request timeout and `maxRetries`.
3295
+ * End the retry waits of this exporter until its next `shutdown()`. The batch processor
3296
+ * calls it when `shutdown()` starts. A call that waits for a retry makes one more attempt
3297
+ * at once. An attempt that fails after this is not retried: the call fails with the drop
3298
+ * reason `shutdown_residue`. So a drain against a dead endpoint costs one attempt for each
3299
+ * batch, not the shutdown budget.
3300
+ */
3301
+ endRetries() {
3302
+ this._noWait = true;
3303
+ for (const wake of [...this._waits]) wake();
3304
+ }
3305
+ /**
3306
+ * Send one batch, with the W2-1c retry policy (see the block above the class).
3307
+ *
3308
+ * Resolves SUCCESS when the backend accounted for the batch: `takeAck` has the counts (and
3309
+ * the spans that a 413 split dropped, in `dropped`). Resolves FAILURE when no span was
3310
+ * accounted for: `takeDropReason` then says why, and the batch processor drops the batch
3311
+ * with that reason.
2958
3312
  *
2959
3313
  * ⚠ NO CALLER BUDGET. `flush(timeoutMs)` only stops WAITING at its deadline; it never
2960
- * cuts a request that is already sent. A short flush budget that cut the request made a
2961
- * healthy, slow server look like a failure: the span used a retry, the breaker moved, and
2962
- * the server stored the same spans again. Only `abort()` stops the call, and only
3314
+ * cuts a request that is already sent. Only `abort()` stops the call, and only
2963
3315
  * `shutdown()` calls it.
2964
3316
  */
2965
3317
  async export(spans) {
2966
3318
  if (spans.length === 0) return "success" /* SUCCESS */;
2967
3319
  const call = {
2968
3320
  cancel: new AbortController(),
2969
- refusalAfterMs: null,
3321
+ retryAfterS: null,
2970
3322
  misroute: null,
2971
3323
  noRetry: false,
2972
3324
  status: null,
2973
3325
  error: null,
2974
- attempts: 0
3326
+ attempts: 0,
3327
+ ack: null
2975
3328
  };
2976
3329
  this._calls.set(spans, call);
2977
3330
  try {
@@ -3008,83 +3361,236 @@ var HttpExporter = class {
3008
3361
  );
3009
3362
  }
3010
3363
  if (parts.length === 0) return "success" /* SUCCESS */;
3011
- const payload = `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
3012
- const now = Date.now();
3013
- let isHalfOpen = false;
3014
- if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
3015
- if (now < this._circuitOpenUntil) {
3016
- return "failure" /* FAILURE */;
3364
+ if (this._consecutiveFailures >= this._circuitBreakerThreshold && Date.now() < this._circuitOpenUntil) {
3365
+ this._dropReasons.set(spans, "transport_refused");
3366
+ return "failure" /* FAILURE */;
3367
+ }
3368
+ const out = { delivered: [], dropped: {}, failed: [], cancelled: false };
3369
+ const start = performance.now();
3370
+ await this._deliver(parts, start, call, out, true);
3371
+ if (cancelled.aborted || out.cancelled) {
3372
+ this._acks.delete(spans);
3373
+ return "failure" /* FAILURE */;
3374
+ }
3375
+ return this._finish(spans, out, call.attempts);
3376
+ }
3377
+ /** The request body for `parts` (the serialized spans of one part of a batch). */
3378
+ _payload(parts) {
3379
+ return `{"spans":[${parts.join(",")}]` + (this._projectId ? `,"projectId":${JSON.stringify(this._projectId)}` : "") + (this._environment ? `,"environment":${JSON.stringify(this._environment)}` : "") + "}";
3380
+ }
3381
+ /**
3382
+ * Send one part of a batch with the retry policy, and record its outcome in `out`.
3383
+ * `maySplit` is true only for the whole batch: a 413 splits it in two one time. A half
3384
+ * that gets 413 again is dropped as `too_large`.
3385
+ */
3386
+ async _deliver(parts, start, call, out, maySplit) {
3387
+ const n = parts.length;
3388
+ if (!maySplit && this._quota.paused()) {
3389
+ out.delivered.push({ n, ack: { accepted: 0, rejected: 0, quotaDropped: n } });
3390
+ return;
3391
+ }
3392
+ const result = await this._sendWithRetries(this._payload(parts), n, start, call);
3393
+ if (result.kind === "delivered") {
3394
+ out.delivered.push({ n, ack: result.ack });
3395
+ } else if (result.kind === "too_large") {
3396
+ if (maySplit && n > 1) {
3397
+ const mid = Math.ceil(n / 2);
3398
+ debug(`Ingest answered HTTP 413 for ${n} span(s): sending two halves of ${mid} and ${n - mid}`);
3399
+ await this._deliver(parts.slice(0, mid), start, call, out, false);
3400
+ if (!out.cancelled) await this._deliver(parts.slice(mid), start, call, out, false);
3401
+ } else {
3402
+ out.dropped.too_large = (out.dropped.too_large ?? 0) + n;
3017
3403
  }
3018
- isHalfOpen = true;
3404
+ } else if (result.kind === "cancelled") {
3405
+ out.cancelled = true;
3406
+ } else {
3407
+ out.failed.push({ n, reason: result.kind, answer: result.answer });
3019
3408
  }
3020
- const maxAttempts = isHalfOpen ? 1 : this._maxRetries;
3021
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
3022
- call.refusalAfterMs = null;
3409
+ }
3410
+ /** Send one request body until it is delivered or the policy stops. */
3411
+ async _sendWithRetries(body, spansSent, start, call) {
3412
+ const cancelled = call.cancel.signal;
3413
+ let retryNumber = 0;
3414
+ let attemptsHere = 0;
3415
+ for (; ; ) {
3416
+ if (cancelled.aborted) return { kind: "cancelled" };
3417
+ call.retryAfterS = null;
3023
3418
  call.misroute = null;
3024
3419
  call.noRetry = false;
3025
3420
  call.status = null;
3026
3421
  call.error = null;
3422
+ call.ack = null;
3027
3423
  call.attempts++;
3028
- const result = await this._sendRequest(payload, parts.length, call, spans);
3029
- if (cancelled.aborted) {
3030
- this._acks.delete(spans);
3031
- return "failure" /* FAILURE */;
3032
- }
3033
- if (result === "success" /* SUCCESS */) {
3034
- this._consecutiveFailures = 0;
3035
- this._failureKind = null;
3036
- return result;
3424
+ attemptsHere++;
3425
+ this.attempts++;
3426
+ const result = await this._sendRequest(body, spansSent, call);
3427
+ if (cancelled.aborted) return { kind: "cancelled" };
3428
+ if (result === "success" /* SUCCESS */) return { kind: "delivered", ack: call.ack };
3429
+ if (call.status === TOO_LARGE_STATUS) return { kind: "too_large" };
3430
+ const answer = {
3431
+ status: call.status,
3432
+ error: call.error,
3433
+ misroute: call.misroute,
3434
+ zeroAck: call.noRetry,
3435
+ sent: spansSent
3436
+ };
3437
+ if (!this._retryable(call)) return { kind: "transport_refused", answer };
3438
+ if (attemptsHere === RETRY_WARN_AFTER_ATTEMPTS) this._warnOutage(answer, true);
3439
+ if (this._noWait) return { kind: "shutdown_residue", answer };
3440
+ if (this._maxRetries !== void 0 && attemptsHere >= this._maxRetries) {
3441
+ return { kind: "retry_exhausted", answer };
3037
3442
  }
3038
- if (call.misroute !== null || call.noRetry) break;
3039
- if (call.status !== null && AUTH_REFUSAL_STATUSES.has(call.status)) break;
3040
- if (attempt < maxAttempts - 1) {
3041
- const refusal = call.refusalAfterMs;
3042
- const delay = refusal === null ? 100 * Math.pow(2, attempt) : refusal === REFUSAL_NO_HINT ? REFUSAL_BACKOFF_BASE_MS * Math.pow(2, attempt) : refusal;
3043
- await sleep(delay, cancelled);
3044
- if (cancelled.aborted) return "failure" /* FAILURE */;
3443
+ const remainingS = this._retryHorizonS - (performance.now() - start) / 1e3;
3444
+ if (remainingS <= 0) return { kind: "retry_exhausted", answer };
3445
+ const hint = call.retryAfterS;
3446
+ const waitS = hint !== null && hint > 0 ? hint : backoffDelayS(retryNumber, jitter.fraction());
3447
+ const delayS = Math.min(waitS, remainingS);
3448
+ retryNumber++;
3449
+ debug(
3450
+ `Ingest attempt ${attemptsHere} failed (${answer.status ?? answer.error ?? "unknown"}); next attempt in ${delayS.toFixed(2)} s (${Math.round(remainingS)} s of the horizon left)`
3451
+ );
3452
+ await this._retryWait(delayS * 1e3, cancelled);
3453
+ }
3454
+ }
3455
+ /** True when the answer of the last attempt of `call` can change on a retry. */
3456
+ _retryable(call) {
3457
+ if (call.misroute !== null || call.noRetry) return false;
3458
+ if (call.status !== null) return RETRY_STATUSES.has(call.status);
3459
+ if (this._endpointHasCredentials) return false;
3460
+ return call.error !== null;
3461
+ }
3462
+ /**
3463
+ * Wait `ms` before the next attempt. `abort()` and `endRetries()` end the wait at once. The
3464
+ * timer does not keep the process alive: when nothing else runs, `beforeExit` starts the
3465
+ * SDK's `shutdown()`, which ends the wait.
3466
+ */
3467
+ _retryWait(ms, signal) {
3468
+ return new Promise((resolve) => {
3469
+ if (signal.aborted || this._noWait || ms <= 0) return resolve();
3470
+ const done = () => {
3471
+ clearTimeout(timer);
3472
+ signal.removeEventListener("abort", done);
3473
+ this._waits.delete(done);
3474
+ resolve();
3475
+ };
3476
+ const timer = setTimeout(done, Math.min(ms, MAX_TIMER_MS));
3477
+ timer.unref?.();
3478
+ signal.addEventListener("abort", done, { once: true });
3479
+ this._waits.add(done);
3480
+ });
3481
+ }
3482
+ /** Turn the outcome of the parts of one batch into the result of `export()`. */
3483
+ _finish(spans, out, attempts) {
3484
+ const reasons = new Set(out.failed.map((f) => f.reason));
3485
+ if (out.delivered.length === 0 && Object.keys(out.dropped).length === 0 && reasons.size === 1) {
3486
+ const reason = out.failed[0].reason;
3487
+ const nFailed = out.failed.reduce((sum, f) => sum + f.n, 0);
3488
+ this._dropReasons.set(spans, reason);
3489
+ return this._fail(reason, out.failed[out.failed.length - 1].answer, nFailed, attempts);
3490
+ }
3491
+ let ack;
3492
+ if (out.delivered.length === 1 && Object.keys(out.dropped).length === 0 && out.failed.length === 0) {
3493
+ ack = out.delivered[0].ack;
3494
+ } else {
3495
+ let accepted = 0;
3496
+ let rejected = 0;
3497
+ let quotaDropped = 0;
3498
+ for (const part of out.delivered) {
3499
+ accepted += part.ack !== null ? part.ack.accepted : part.n;
3500
+ rejected += part.ack !== null ? part.ack.rejected : 0;
3501
+ quotaDropped += part.ack?.quotaDropped ?? 0;
3045
3502
  }
3503
+ const dropped = { ...out.dropped };
3504
+ for (const f of out.failed) dropped[f.reason] = (dropped[f.reason] ?? 0) + f.n;
3505
+ ack = { accepted, rejected };
3506
+ if (quotaDropped > 0) ack.quotaDropped = quotaDropped;
3507
+ if (Object.keys(dropped).length > 0) ack.dropped = dropped;
3046
3508
  }
3047
- if (call.refusalAfterMs !== null) {
3048
- warn(
3049
- `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.`
3050
- );
3509
+ if (ack !== null) this._acks.set(spans, ack);
3510
+ this._consecutiveFailures = 0;
3511
+ this._failureKind = null;
3512
+ const tooLarge = out.dropped.too_large ?? 0;
3513
+ if (tooLarge > 0) this._warnTooLarge(tooLarge);
3514
+ for (const f of out.failed) {
3515
+ if (f.reason === "retry_exhausted") this._warnExhausted(f.n, attempts, f.answer);
3516
+ }
3517
+ return "success" /* SUCCESS */;
3518
+ }
3519
+ /** End a call in which no span was accounted for. Always returns FAILURE. */
3520
+ _fail(reason, answer, nSpans, attempts) {
3521
+ if (reason === "shutdown_residue") {
3522
+ debug(`Export ended by shutdown after ${attempts} attempt(s)`);
3051
3523
  return "failure" /* FAILURE */;
3052
3524
  }
3053
- const misroute = call.misroute;
3054
- if (misroute !== null && Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
3055
- this._lastMisrouteWarnAt = Date.now();
3056
- warn(
3057
- `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.`
3058
- );
3525
+ if (reason === "retry_exhausted") {
3526
+ if (answer.status === null || !CAPACITY_REFUSAL_STATUSES.has(answer.status)) this._stepBreaker();
3527
+ this._warnOutage(answer, true);
3528
+ this._warnExhausted(nSpans, attempts, answer);
3529
+ return "failure" /* FAILURE */;
3059
3530
  }
3531
+ this._stepBreaker();
3532
+ this._warnOutage(answer, false);
3533
+ return "failure" /* FAILURE */;
3534
+ }
3535
+ /** Count one failed call toward the circuit breaker. */
3536
+ _stepBreaker() {
3060
3537
  this._consecutiveFailures++;
3061
- if (misroute === null && !call.noRetry) {
3062
- const status = call.status;
3063
- const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : call.error !== null ? "none" : "unknown";
3064
- let write = false;
3065
- if (this._consecutiveFailures === 1 || this._failureKind === null) {
3066
- if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
3067
- this._lastFailureWarnAt = Date.now();
3068
- write = true;
3069
- }
3070
- this._failureKind = kind;
3071
- } else if (kind !== this._failureKind) {
3072
- this._failureKind = kind;
3073
- write = true;
3074
- }
3075
- if (write) this._warnOutage(kind, status, call.error);
3076
- }
3077
3538
  if (this._consecutiveFailures >= this._circuitBreakerThreshold) {
3078
3539
  this._circuitOpenUntil = Date.now() + this._circuitBreakerCooldownMs;
3079
3540
  warn(
3080
3541
  `HTTP exporter circuit breaker opened after ${this._consecutiveFailures} failures. Cooldown: ${this._circuitBreakerCooldownMs / 1e3}s`
3081
3542
  );
3082
3543
  }
3083
- return "failure" /* FAILURE */;
3084
3544
  }
3085
- /** The outage WARNING for one kind of failure. */
3086
- _warnOutage(kind, status, error) {
3545
+ /**
3546
+ * The outage WARNING: at the first failure of an outage, and when its kind changes. At most
3547
+ * one in the window for the first failure; a misroute has its own WARNING, at most one in
3548
+ * the window. `retrying` is true for a retryable answer (written after
3549
+ * `RETRY_WARN_AFTER_ATTEMPTS` failed attempts of one batch, or when its retries end before
3550
+ * that), false for an answer that a retry cannot change (one attempt). The WARNING names the last HTTP status, or the error
3551
+ * code when there was no answer. It never names the key or the response body, and names
3552
+ * the API key as a cause only for a 401 or 403. An ack of 0 and 0 has its WARNING from
3553
+ * `checkAck`.
3554
+ */
3555
+ _warnOutage(answer, retrying) {
3556
+ if (answer.misroute !== null) {
3557
+ if (Date.now() - this._lastMisrouteWarnAt > MISROUTE_WARN_WINDOW_MS) {
3558
+ this._lastMisrouteWarnAt = Date.now();
3559
+ warn(
3560
+ `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.`
3561
+ );
3562
+ }
3563
+ return;
3564
+ }
3565
+ if (answer.zeroAck) return;
3566
+ const status = answer.status;
3567
+ const kind = status !== null && AUTH_REFUSAL_STATUSES.has(status) ? "auth" : status !== null ? "http" : answer.error !== null ? "none" : "unknown";
3568
+ let write = false;
3569
+ if (this._failureKind === null || !retrying && this._consecutiveFailures === 1) {
3570
+ if (Date.now() - this._lastFailureWarnAt > FAILURE_WARN_WINDOW_MS) {
3571
+ this._lastFailureWarnAt = Date.now();
3572
+ write = true;
3573
+ }
3574
+ this._failureKind = kind;
3575
+ } else if (kind !== this._failureKind) {
3576
+ this._failureKind = kind;
3577
+ write = true;
3578
+ }
3579
+ if (!write) return;
3087
3580
  const where = `Risicare: spans are NOT reaching ${this._safeEndpoint}`;
3581
+ if (retrying) {
3582
+ let limit = `${this._retryHorizonS} s from its first attempt (retryHorizonS)`;
3583
+ if (this._maxRetries !== void 0) limit = `${this._maxRetries} attempt(s) (maxRetries) or ${limit}`;
3584
+ const retryText = `The SDK sends each batch again with a growing wait, for up to ${limit}, and then drops it (reason=retry_exhausted).`;
3585
+ if (kind === "http") {
3586
+ warn(`${where}: it answered HTTP ${status}. ${retryText} Set debug: true to see each attempt.`);
3587
+ } else {
3588
+ warn(
3589
+ `${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.`
3590
+ );
3591
+ }
3592
+ return;
3593
+ }
3088
3594
  const tail = "Tracing continues, but the SDK drops the spans that it cannot send.";
3089
3595
  if (kind === "auth") {
3090
3596
  warn(
@@ -3092,15 +3598,11 @@ var HttpExporter = class {
3092
3598
  );
3093
3599
  } else if (kind === "http") {
3094
3600
  warn(
3095
- `${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.`
3601
+ `${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.`
3096
3602
  );
3097
3603
  } else if (kind === "none" && this._endpointHasCredentials) {
3098
3604
  warn(
3099
- `${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}`
3100
- );
3101
- } else if (kind === "none") {
3102
- warn(
3103
- `${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.`
3605
+ `${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}`
3104
3606
  );
3105
3607
  } else {
3106
3608
  warn(
@@ -3108,33 +3610,38 @@ var HttpExporter = class {
3108
3610
  );
3109
3611
  }
3110
3612
  }
3613
+ /** The WARNING for spans dropped as `retry_exhausted`. At most one in the window. */
3614
+ _warnExhausted(nSpans, attempts, answer) {
3615
+ if (Date.now() - this._lastExhaustedWarnAt <= FAILURE_WARN_WINDOW_MS) return;
3616
+ this._lastExhaustedWarnAt = Date.now();
3617
+ const last = answer.status !== null ? `HTTP ${answer.status}` : `no answer (${answer.error})`;
3618
+ const capacity = answer.status !== null && CAPACITY_REFUSAL_STATUSES.has(answer.status) ? " (over capacity)" : "";
3619
+ 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)`;
3620
+ warn(
3621
+ `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.`
3622
+ );
3623
+ }
3624
+ /** The WARNING for spans dropped as `too_large`. One time for each exporter. */
3625
+ _warnTooLarge(nSpans) {
3626
+ if (this._tooLargeWarned) return;
3627
+ this._tooLargeWarned = true;
3628
+ warn(
3629
+ `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.`
3630
+ );
3631
+ }
3111
3632
  /** Record a MISROUTE for the retry loop and the breaker. Always returns FAILURE. */
3112
3633
  _noteMisroute(call, answer) {
3113
3634
  call.misroute = this._scrub(answer, 300);
3114
3635
  debug(`Ingest misroute: ${call.misroute}`);
3115
3636
  return "failure" /* FAILURE */;
3116
3637
  }
3117
- /**
3118
- * Record a CAPACITY REFUSAL for the retry loop. Returns true if it was one.
3119
- *
3120
- * `Retry-After` is honoured only in its delta-seconds form (RFC 9110 §10.2.3 also permits an
3121
- * HTTP-date); anything else falls back to our own backoff rather than guessing at a date
3122
- * parse.
3123
- */
3124
- _noteRefusal(call, status, retryAfterRaw) {
3125
- if (!CAPACITY_REFUSAL_STATUSES.has(status)) return false;
3126
- let delay = REFUSAL_NO_HINT;
3127
- if (retryAfterRaw) {
3128
- const secs = Number(retryAfterRaw);
3129
- if (Number.isFinite(secs) && secs >= 0) {
3130
- delay = Math.min(secs * 1e3, RETRY_AFTER_CEILING_MS);
3131
- }
3132
- }
3133
- call.refusalAfterMs = delay;
3134
- debug(`Ingest refused for capacity: HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
3135
- return true;
3638
+ /** Record the `Retry-After` wait of a retryable answer for the retry loop. */
3639
+ _noteRetryAfter(call, status, retryAfterRaw) {
3640
+ if (!RETRY_STATUSES.has(status)) return;
3641
+ call.retryAfterS = parseRetryAfterS(retryAfterRaw);
3642
+ debug(`Ingest answered HTTP ${status} (Retry-After=${this._scrub(retryAfterRaw)})`);
3136
3643
  }
3137
- async _sendRequest(body, spansSent, call, spans) {
3644
+ async _sendRequest(body, spansSent, call) {
3138
3645
  const cancelled = call.cancel.signal;
3139
3646
  const timeoutMs = this._timeoutMs;
3140
3647
  const url = `${this._endpoint}/v1/spans`;
@@ -3202,14 +3709,15 @@ var HttpExporter = class {
3202
3709
  } else if (ack.result === "success" /* SUCCESS */) {
3203
3710
  this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
3204
3711
  }
3205
- if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
3712
+ if (ack.result === "success" /* SUCCESS */) call.ack = ack.counts;
3206
3713
  if (ack.final) call.noRetry = true;
3207
3714
  return ack.result;
3208
- } else if (response.status === 408 || response.status === 504) {
3715
+ }
3716
+ this._noteRetryAfter(call, response.status, response.headers?.get?.("Retry-After") ?? null);
3717
+ if (response.status === 408 || response.status === 504) {
3209
3718
  debug(`HTTP export timeout: ${response.status}`);
3210
3719
  return "timeout" /* TIMEOUT */;
3211
3720
  }
3212
- this._noteRefusal(call, response.status, response.headers.get("Retry-After"));
3213
3721
  debug(`HTTP export failed: ${response.status}`);
3214
3722
  return "failure" /* FAILURE */;
3215
3723
  } catch (e) {
@@ -3223,20 +3731,9 @@ var HttpExporter = class {
3223
3731
  }
3224
3732
  }
3225
3733
  shutdown() {
3734
+ this._noWait = false;
3226
3735
  }
3227
3736
  };
3228
- function sleep(ms, signal) {
3229
- return new Promise((resolve) => {
3230
- if (signal?.aborted) return resolve();
3231
- const done = () => {
3232
- clearTimeout(timer);
3233
- signal?.removeEventListener("abort", done);
3234
- resolve();
3235
- };
3236
- const timer = setTimeout(done, ms);
3237
- signal?.addEventListener("abort", done, { once: true });
3238
- });
3239
- }
3240
3737
  function asCount(v) {
3241
3738
  return typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : void 0;
3242
3739
  }
@@ -3735,7 +4232,7 @@ var FixApplier = class {
3735
4232
  const initialDelayMs = cfg.initial_delay_ms ?? cfg.initialDelayMs ?? 1e3;
3736
4233
  const maxDelayMs = cfg.max_delay_ms ?? cfg.maxDelayMs ?? 3e4;
3737
4234
  const exponentialBase = cfg.exponential_base ?? cfg.exponentialBase ?? 2;
3738
- const jitter = cfg.jitter ?? true;
4235
+ const jitter2 = cfg.jitter ?? true;
3739
4236
  const retryOn = cfg.retry_on ?? cfg.retryOn ?? [];
3740
4237
  const result = emptyResult(fix, "retry");
3741
4238
  if (this._config.dryRun) {
@@ -3763,7 +4260,7 @@ var FixApplier = class {
3763
4260
  initialDelayMs * Math.pow(exponentialBase, attempt),
3764
4261
  maxDelayMs
3765
4262
  );
3766
- if (jitter) {
4263
+ if (jitter2) {
3767
4264
  delayMs *= 0.5 + Math.random();
3768
4265
  }
3769
4266
  debug(
@@ -4610,7 +5107,8 @@ var RisicareClient = class {
4610
5107
  apiKey: this.config.apiKey,
4611
5108
  projectId: this.config.projectId || void 0,
4612
5109
  environment: this.config.environment || void 0,
4613
- compress: this.config.compress
5110
+ compress: this.config.compress,
5111
+ retryHorizonS: this.config.retryHorizonS
4614
5112
  });
4615
5113
  }
4616
5114
  this.processor = new BatchSpanProcessor({
@@ -4701,7 +5199,8 @@ var RisicareClient = class {
4701
5199
  }
4702
5200
  this._shutdownHandlers = [];
4703
5201
  endOpenProviderSpans();
4704
- await this.processor.shutdown(timeoutMs);
5202
+ const budgetMs = typeof timeoutMs === "number" && Number.isFinite(timeoutMs) ? timeoutMs : this.config.shutdownTimeoutS * 1e3;
5203
+ await this.processor.shutdown(budgetMs);
4705
5204
  _failWaitingScores(SCORE_DEADLINE_REASON);
4706
5205
  this.isShutdown = true;
4707
5206
  _finalMetrics = this.processor.getMetrics();
@@ -4778,7 +5277,7 @@ var RisicareClient = class {
4778
5277
  const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4779
5278
  const backstop = setTimeout(
4780
5279
  () => process.exit(128 + signum),
4781
- SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
5280
+ this.config.shutdownTimeoutS * 1e3 + BACKSTOP_MARGIN_MS
4782
5281
  );
4783
5282
  backstop.unref();
4784
5283
  this.shutdown().catch(() => {
@@ -4922,10 +5421,14 @@ function getMetrics() {
4922
5421
  transport_refused: 0,
4923
5422
  shutdown_residue: 0,
4924
5423
  unacknowledged: 0,
4925
- quota_exceeded: 0
5424
+ quota_exceeded: 0,
5425
+ retry_exhausted: 0,
5426
+ too_large: 0
4926
5427
  },
4927
5428
  droppedQuota: 0,
4928
5429
  failedExports: 0,
5430
+ attempts: 0,
5431
+ oldestPendingAgeS: 0,
4929
5432
  queueSize: 0,
4930
5433
  queueCapacity: 0,
4931
5434
  queueUtilization: 0,
@@ -4987,40 +5490,111 @@ function refuseScore(message) {
4987
5490
  const client = getClient();
4988
5491
  if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4989
5492
  }
4990
- function score(traceId, name, value, options) {
5493
+ var SCORE_KINDS = ["annotation", "eval", "feedback", "outcome"];
5494
+ var SCORE_NAME_MAX_LEN = 128;
5495
+ var SCORE_STRING_VALUE_MAX_LEN = 256;
5496
+ var SCORE_SESSION_ID_MAX_LEN = 255;
5497
+ var SCORE_COMMENT_MAX_LEN = 4096;
5498
+ var _positionalScoreWarned = false;
5499
+ function warnPositionalScore() {
5500
+ if (_positionalScoreWarned) return;
5501
+ _positionalScoreWarned = true;
5502
+ warn(
5503
+ "Risicare: score(traceId, name, value) with positional arguments is deprecated; this call still sends the score. Use score({ name, value, traceId }). This WARNING is written one time."
5504
+ );
5505
+ }
5506
+ function scoreWireValue(value) {
5507
+ if (typeof value === "boolean") return value;
5508
+ if (typeof value === "number") {
5509
+ if (Number.isFinite(value)) return value;
5510
+ refuseScore(`score: a number value must be finite, not ${value}. The SDK does not send this score.`);
5511
+ return void 0;
5512
+ }
5513
+ if (typeof value === "string") {
5514
+ if (value.length >= 1 && value.length <= SCORE_STRING_VALUE_MAX_LEN) return value;
5515
+ refuseScore(
5516
+ `score: a string value must have 1 to ${SCORE_STRING_VALUE_MAX_LEN} characters, not ${value.length}. The SDK does not send this score.`
5517
+ );
5518
+ return void 0;
5519
+ }
5520
+ refuseScore(
5521
+ `score: the value must be a number, a string or a boolean, not ${value === null ? "null" : typeof value}. The SDK does not send this score.`
5522
+ );
5523
+ return void 0;
5524
+ }
5525
+ function score(first, legacyName, legacyValue, legacyOptions) {
4991
5526
  try {
4992
- const raw = value;
4993
- if (typeof raw === "boolean") value = raw ? 1 : 0;
4994
- if (typeof value !== "number") {
4995
- refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
5527
+ let opts;
5528
+ if (typeof first === "object" && first !== null && arguments.length === 1) {
5529
+ opts = first;
5530
+ } else {
5531
+ warnPositionalScore();
5532
+ opts = {
5533
+ traceId: first,
5534
+ name: legacyName,
5535
+ value: legacyValue,
5536
+ spanId: legacyOptions?.spanId,
5537
+ comment: legacyOptions?.comment
5538
+ };
5539
+ }
5540
+ const { name, traceId, spanId, sessionId } = opts;
5541
+ const kind = opts.kind ?? "annotation";
5542
+ if (typeof name !== "string" || given(name) === void 0) {
5543
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4996
5544
  return;
4997
5545
  }
4998
- if (!Number.isFinite(value) || value < 0 || value > 1) {
4999
- refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
5546
+ if (name.length > SCORE_NAME_MAX_LEN) {
5547
+ refuseScore(
5548
+ `score: name must be at most ${SCORE_NAME_MAX_LEN} characters, not ${name.length}. The SDK does not send this score.`
5549
+ );
5000
5550
  return;
5001
5551
  }
5002
- if (typeof traceId !== "string" || given(traceId) === void 0) {
5552
+ const value = scoreWireValue(opts.value);
5553
+ if (value === void 0) return;
5554
+ if (traceId !== void 0 && (typeof traceId !== "string" || given(traceId) === void 0)) {
5003
5555
  refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
5004
5556
  return;
5005
5557
  }
5006
- if (typeof name !== "string" || given(name) === void 0) {
5007
- refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
5558
+ if (sessionId !== void 0 && (typeof sessionId !== "string" || given(sessionId) === void 0 || sessionId.length > SCORE_SESSION_ID_MAX_LEN)) {
5559
+ refuseScore(
5560
+ `score: sessionId must be a non-empty string of at most ${SCORE_SESSION_ID_MAX_LEN} characters. The SDK does not send this score.`
5561
+ );
5562
+ return;
5563
+ }
5564
+ if (traceId === void 0 && sessionId === void 0) {
5565
+ refuseScore("score: give traceId or sessionId (or both). The SDK does not send this score.");
5566
+ return;
5567
+ }
5568
+ if (spanId && traceId === void 0) {
5569
+ refuseScore("score: spanId needs traceId. The SDK does not send this score.");
5570
+ return;
5571
+ }
5572
+ if (typeof kind !== "string" || !SCORE_KINDS.includes(kind)) {
5573
+ refuseScore(`score: kind must be one of ${SCORE_KINDS.join(", ")}. The SDK does not send this score.`);
5008
5574
  return;
5009
5575
  }
5010
5576
  const client = getClient();
5011
5577
  if (!client?.enabled || !client.config.apiKey) return;
5012
5578
  const endpoint = client.config.apiEndpoint.replace(/\/+$/, "");
5013
5579
  const url = `${endpoint}/v1/scores`;
5014
- let comment = options?.comment;
5580
+ let comment = opts.comment;
5015
5581
  if (comment !== void 0 && client.config.mask) {
5016
5582
  comment = maskText(client.config.mask, SCORE_COMMENT_KEY, comment);
5017
5583
  }
5584
+ if (comment && comment.length > SCORE_COMMENT_MAX_LEN) {
5585
+ refuseScore(
5586
+ `score: comment must be at most ${SCORE_COMMENT_MAX_LEN} characters, not ${comment.length}. The SDK does not send this score.`
5587
+ );
5588
+ return;
5589
+ }
5018
5590
  const body = JSON.stringify({
5019
- trace_id: traceId,
5020
5591
  name,
5021
- score: value,
5592
+ value,
5593
+ kind,
5022
5594
  source: "sdk",
5023
- ...options?.spanId && { span_id: options.spanId },
5595
+ ...traceId !== void 0 && { trace_id: traceId },
5596
+ ...sessionId !== void 0 && { session_id: sessionId },
5597
+ ...spanId && { span_id: spanId },
5024
5598
  ...comment && { comment }
5025
5599
  });
5026
5600
  if (_scoresInFlight >= SCORE_MAX_IN_FLIGHT && _scoreWaiters.length >= SCORE_MAX_WAITING) {
@@ -6237,6 +6811,7 @@ export {
6237
6811
  SpanKind,
6238
6812
  SpanStatus,
6239
6813
  WebhookVerificationError,
6814
+ addTags,
6240
6815
  agent,
6241
6816
  disable,
6242
6817
  enable,
@@ -6268,6 +6843,9 @@ export {
6268
6843
  reportError,
6269
6844
  score,
6270
6845
  session,
6846
+ setRelease,
6847
+ setSession,
6848
+ setUser,
6271
6849
  shutdown,
6272
6850
  shutdownFixRuntime,
6273
6851
  suppressProviderInstrumentation,