risicare 0.8.0 → 0.9.1

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 (72) hide show
  1. package/README.md +98 -21
  2. package/dist/frameworks/instructor.cjs +144 -2
  3. package/dist/frameworks/instructor.cjs.map +1 -1
  4. package/dist/frameworks/instructor.js +144 -2
  5. package/dist/frameworks/instructor.js.map +1 -1
  6. package/dist/frameworks/langchain.cjs +144 -2
  7. package/dist/frameworks/langchain.cjs.map +1 -1
  8. package/dist/frameworks/langchain.js +144 -2
  9. package/dist/frameworks/langchain.js.map +1 -1
  10. package/dist/frameworks/langgraph.cjs +144 -2
  11. package/dist/frameworks/langgraph.cjs.map +1 -1
  12. package/dist/frameworks/langgraph.js +144 -2
  13. package/dist/frameworks/langgraph.js.map +1 -1
  14. package/dist/frameworks/llamaindex.cjs +144 -2
  15. package/dist/frameworks/llamaindex.cjs.map +1 -1
  16. package/dist/frameworks/llamaindex.js +144 -2
  17. package/dist/frameworks/llamaindex.js.map +1 -1
  18. package/dist/index.cjs +329 -67
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +29 -9
  21. package/dist/index.d.ts +29 -9
  22. package/dist/index.js +329 -67
  23. package/dist/index.js.map +1 -1
  24. package/dist/providers/anthropic/index.cjs +144 -2
  25. package/dist/providers/anthropic/index.cjs.map +1 -1
  26. package/dist/providers/anthropic/index.js +144 -2
  27. package/dist/providers/anthropic/index.js.map +1 -1
  28. package/dist/providers/bedrock/index.cjs +144 -2
  29. package/dist/providers/bedrock/index.cjs.map +1 -1
  30. package/dist/providers/bedrock/index.js +144 -2
  31. package/dist/providers/bedrock/index.js.map +1 -1
  32. package/dist/providers/cerebras/index.cjs +144 -2
  33. package/dist/providers/cerebras/index.cjs.map +1 -1
  34. package/dist/providers/cerebras/index.js +144 -2
  35. package/dist/providers/cerebras/index.js.map +1 -1
  36. package/dist/providers/cohere/index.cjs +144 -2
  37. package/dist/providers/cohere/index.cjs.map +1 -1
  38. package/dist/providers/cohere/index.js +144 -2
  39. package/dist/providers/cohere/index.js.map +1 -1
  40. package/dist/providers/google/index.cjs +144 -2
  41. package/dist/providers/google/index.cjs.map +1 -1
  42. package/dist/providers/google/index.js +144 -2
  43. package/dist/providers/google/index.js.map +1 -1
  44. package/dist/providers/groq/index.cjs +144 -2
  45. package/dist/providers/groq/index.cjs.map +1 -1
  46. package/dist/providers/groq/index.js +144 -2
  47. package/dist/providers/groq/index.js.map +1 -1
  48. package/dist/providers/huggingface/index.cjs +144 -2
  49. package/dist/providers/huggingface/index.cjs.map +1 -1
  50. package/dist/providers/huggingface/index.js +144 -2
  51. package/dist/providers/huggingface/index.js.map +1 -1
  52. package/dist/providers/mistral/index.cjs +144 -2
  53. package/dist/providers/mistral/index.cjs.map +1 -1
  54. package/dist/providers/mistral/index.js +144 -2
  55. package/dist/providers/mistral/index.js.map +1 -1
  56. package/dist/providers/ollama/index.cjs +144 -2
  57. package/dist/providers/ollama/index.cjs.map +1 -1
  58. package/dist/providers/ollama/index.js +144 -2
  59. package/dist/providers/ollama/index.js.map +1 -1
  60. package/dist/providers/openai/index.cjs +144 -2
  61. package/dist/providers/openai/index.cjs.map +1 -1
  62. package/dist/providers/openai/index.js +144 -2
  63. package/dist/providers/openai/index.js.map +1 -1
  64. package/dist/providers/together/index.cjs +144 -2
  65. package/dist/providers/together/index.cjs.map +1 -1
  66. package/dist/providers/together/index.js +144 -2
  67. package/dist/providers/together/index.js.map +1 -1
  68. package/dist/providers/vercel-ai/index.cjs +144 -2
  69. package/dist/providers/vercel-ai/index.cjs.map +1 -1
  70. package/dist/providers/vercel-ai/index.js +144 -2
  71. package/dist/providers/vercel-ai/index.js.map +1 -1
  72. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -172,6 +172,10 @@ function warn(msg) {
172
172
  process.stderr.write(`[risicare] WARNING: ${msg}
173
173
  `);
174
174
  }
175
+ function info(msg) {
176
+ process.stderr.write(`[risicare] INFO: ${msg}
177
+ `);
178
+ }
175
179
 
176
180
  // src/utils/text.ts
177
181
  function cutCodePoints(text, max) {
@@ -627,6 +631,18 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
627
631
  _started = false;
628
632
  _flushing = false;
629
633
  _inFlight = null;
634
+ /**
635
+ * The `shutdown()` that runs, or ran. A second `shutdown()` returns it, and a
636
+ * `flush()` that comes while it runs waits for it (inside its own deadline).
637
+ */
638
+ _closing = null;
639
+ /**
640
+ * True from the start of the drain of `shutdown()` until its loop ends and the
641
+ * residue is counted (no `await` between those two points). A span that ends
642
+ * in this time joins the drain. After it, the processor can take no span.
643
+ */
644
+ _drainOpen = false;
645
+ _lateSpanWarned = false;
630
646
  _beforeExitHandler = null;
631
647
  // Retry tracking for failed batches (Audit #5)
632
648
  _retryCounts = /* @__PURE__ */ new Map();
@@ -660,7 +676,8 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
660
676
  queue_full: 0,
661
677
  transport_refused: 0,
662
678
  shutdown_residue: 0,
663
- unacknowledged: 0
679
+ unacknowledged: 0,
680
+ quota_exceeded: 0
664
681
  };
665
682
  exportedSpans = 0;
666
683
  /**
@@ -772,13 +789,21 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
772
789
  * Limit: the abort does not stop a TLS handshake that stalls. Measured, such a
773
790
  * handshake kept the process alive about 10 s after `shutdown()` returned.
774
791
  *
792
+ * A second call, while the first runs or after it ended, returns the promise
793
+ * of the first one. It does not return before the first drain ends.
794
+ *
775
795
  * @param timeoutMs - The budget (default 5000). See `normalizeTimeoutMs` for
776
796
  * the values that are not a finite number.
777
797
  */
778
- async shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
779
- if (!this._started) return;
798
+ shutdown(timeoutMs = SHUTDOWN_BUDGET_MS) {
799
+ if (!this._started) return this._closing ?? Promise.resolve();
800
+ this._closing = this._shutdown(timeoutMs);
801
+ return this._closing;
802
+ }
803
+ async _shutdown(timeoutMs) {
780
804
  timeoutMs = normalizeTimeoutMs(timeoutMs);
781
805
  this._started = false;
806
+ this._drainOpen = true;
782
807
  if (this._timer) {
783
808
  clearInterval(this._timer);
784
809
  this._timer = null;
@@ -803,6 +828,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
803
828
  break;
804
829
  }
805
830
  }
831
+ this._drainOpen = false;
806
832
  const queued = this._queue.length;
807
833
  const flight = this._inFlight;
808
834
  const inFlight = flight !== null && !flight.abandoned ? flight.size : 0;
@@ -820,9 +846,15 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
820
846
  if (residue > 0) {
821
847
  this._queue.length = 0;
822
848
  this._recordDropped("shutdown_residue", residue);
823
- warn(
824
- `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.`
825
- );
849
+ if (this._quotaPaused()) {
850
+ warn(
851
+ `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.`
852
+ );
853
+ } else {
854
+ warn(
855
+ `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.`
856
+ );
857
+ }
826
858
  }
827
859
  for (const exporter of this._exporters) {
828
860
  await shutdownExporter(exporter, Math.max(0, shutdownDeadline - Date.now()));
@@ -833,8 +865,28 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
833
865
  );
834
866
  }
835
867
  onSpanEnd(span) {
836
- if (!this._started) return;
868
+ if (!this._started) {
869
+ if (this._drainOpen) this._enqueue(span, false);
870
+ else if (this._closing !== null) this._lateSpan();
871
+ return;
872
+ }
873
+ this._enqueue(span, true);
874
+ }
875
+ _enqueue(span, exportAtBatchSize) {
837
876
  if (this._queue.length >= this._maxQueueSize) {
877
+ if (this._quotaPaused()) {
878
+ const oldest = this._queue.shift();
879
+ if (oldest !== void 0) this._retryCounts.delete(oldest.spanId);
880
+ this._recordDropped("quota_exceeded");
881
+ for (const exporter of this._exporters) {
882
+ try {
883
+ exporter.noteQuotaDrop?.(1);
884
+ } catch {
885
+ }
886
+ }
887
+ this._queue.push(span);
888
+ return;
889
+ }
838
890
  this._recordDropped("queue_full");
839
891
  if (this.droppedSpans === 1 || this.droppedSpans % 1e3 === 0) {
840
892
  warn(`Span queue full (${this._maxQueueSize}). ${this.droppedSpans} spans dropped so far.`);
@@ -842,10 +894,35 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
842
894
  return;
843
895
  }
844
896
  this._queue.push(span);
845
- if (this._queue.length >= this._batchSize) {
897
+ if (exportAtBatchSize && this._queue.length >= this._batchSize) {
846
898
  void this._exportBatch();
847
899
  }
848
900
  }
901
+ /**
902
+ * True when every exporter that delivers is paused for the monthly quota (S-1). An exporter
903
+ * says so with `quotaPaused()`. A custom exporter has none: not paused.
904
+ */
905
+ _quotaPaused() {
906
+ const deciders = this._exporters.filter((e) => e.countsAsDelivery !== false);
907
+ if (deciders.length === 0) return false;
908
+ for (const exporter of deciders) {
909
+ try {
910
+ if (exporter.quotaPaused?.() !== true) return false;
911
+ } catch {
912
+ return false;
913
+ }
914
+ }
915
+ return true;
916
+ }
917
+ /** A span that ended after the drain ended: counted, with one WARNING for the first. */
918
+ _lateSpan() {
919
+ this._recordDropped("shutdown_residue");
920
+ if (this._lateSpanWarned) return;
921
+ this._lateSpanWarned = true;
922
+ warn(
923
+ "a span ended after shutdown() had stopped taking spans (reason=shutdown_residue). It was not delivered, and it is counted as dropped. Later spans of this kind are counted without a WARNING."
924
+ );
925
+ }
849
926
  /**
850
927
  * Flush pending spans.
851
928
  *
@@ -875,12 +952,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
875
952
  * loss. The flush after that answers `true` when nothing new was lost.
876
953
  *
877
954
  * Returns `false` in these cases:
878
- * (a) the deadline expires with spans still queued or in flight;
955
+ * (a) the deadline expires with spans still queued or in flight, or while a
956
+ * `shutdown()` that it waits for still runs;
879
957
  * (b) a span was discarded since the previous flush returned: queue full,
880
- * breaker refusal, retry exhaustion, or an ack that did not account
881
- * for it or a span that could not be serialized (`unacknowledged`);
882
- * (c) the backend rejected a span since the previous flush returned;
883
- * (d) it is called after `shutdown()`, and the shutdown residue was not 0.
958
+ * breaker refusal, retry exhaustion, spans that `shutdown()` left
959
+ * (`shutdown_residue`), or an ack that did not account for it or a span
960
+ * that could not be serialized (`unacknowledged`);
961
+ * (c) the backend rejected a span since the previous flush returned.
962
+ *
963
+ * A `flush()` that comes while a `shutdown()` runs (the SDK's own drain at
964
+ * SIGTERM or SIGINT, or a `shutdown()` that nobody awaited) waits for that
965
+ * shutdown, inside its OWN deadline, and then answers from the final tally with
966
+ * the same loss mark. After `shutdown()` it answers from the final tally in the
967
+ * same way. Through 0.8.0 both answered from the empty queue: true in 0 ms,
968
+ * with the batch in flight, and true after a rejection or a `transport_refused`
969
+ * drop. A loss that `shutdown()` counts (also `shutdown_residue`) makes ONE
970
+ * `flush()` false, as every other loss does.
884
971
  *
885
972
  * The deadline is a hard wall-clock bound on the WAIT. At the deadline
886
973
  * `flush()` returns `false`. Through 0.7.1 the deadline was checked only
@@ -903,9 +990,6 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
903
990
  */
904
991
  async flush(timeoutMs = SHUTDOWN_BUDGET_MS) {
905
992
  timeoutMs = normalizeTimeoutMs(timeoutMs);
906
- if (!this._started) {
907
- return this._queue.length === 0 && this.droppedSpansByReason.shutdown_residue === 0;
908
- }
909
993
  const deadline = Date.now() + timeoutMs;
910
994
  const mark = this._lossMark;
911
995
  const finish = (settled) => {
@@ -913,12 +997,22 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
913
997
  this._lossMark = Math.max(this._lossMark, lost);
914
998
  return settled && lost === mark;
915
999
  };
1000
+ if (!this._started) {
1001
+ if (this._closing !== null) {
1002
+ const closed = await raceDeadline(this._closing.catch(() => void 0), timeoutMs);
1003
+ if (closed === DEADLINE) return finish(false);
1004
+ }
1005
+ const held = this._inFlight !== null && !this._inFlight.abandoned;
1006
+ return finish(this._queue.length === 0 && !held);
1007
+ }
916
1008
  while (this._queue.length > 0 || this._flushing) {
917
1009
  const remaining = deadline - Date.now();
918
1010
  if (remaining <= 0) return finish(false);
1011
+ if (!this._flushing && this._queue.length > 0 && this._quotaPaused()) return finish(false);
919
1012
  if (!this._flushing && this._queue.length > 0) {
920
1013
  const outcome = await raceDeadline(this._exportBatch(), remaining);
921
1014
  if (outcome === DEADLINE) return finish(false);
1015
+ if (outcome === 4 /* Paused */) await new Promise((r) => setTimeout(r, 20));
922
1016
  } else {
923
1017
  await new Promise((r) => setTimeout(r, 1));
924
1018
  }
@@ -931,6 +1025,9 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
931
1025
  rejectedSpans: this.rejectedSpans,
932
1026
  droppedSpans: this.droppedSpans,
933
1027
  droppedSpansByReason: { ...this.droppedSpansByReason },
1028
+ // Spans dropped because the monthly event quota is used up (S-1). The same number as
1029
+ // `droppedSpansByReason.quota_exceeded`, for a reader that wants one key.
1030
+ droppedQuota: this.droppedSpansByReason.quota_exceeded,
934
1031
  failedExports: this.failedExports,
935
1032
  maskErrors: this.maskErrors,
936
1033
  queueSize: this._queue.length,
@@ -952,6 +1049,12 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
952
1049
  this.exportedSpans += n;
953
1050
  return;
954
1051
  }
1052
+ const quota = Math.min(Math.max(ack.quotaDropped ?? 0, 0), n);
1053
+ if (quota > 0) {
1054
+ this._recordDropped("quota_exceeded", quota);
1055
+ n -= quota;
1056
+ if (n === 0) return;
1057
+ }
955
1058
  const rejected = Math.min(ack.rejected, n);
956
1059
  const accepted = Math.min(ack.accepted, n - rejected);
957
1060
  const unacknowledged = n - accepted - rejected;
@@ -986,6 +1089,7 @@ var BatchSpanProcessor = class _BatchSpanProcessor {
986
1089
  async _exportBatch() {
987
1090
  if (this._flushing) return 3 /* Busy */;
988
1091
  if (this._queue.length === 0) return 0 /* Empty */;
1092
+ if (this._quotaPaused()) return 4 /* Paused */;
989
1093
  this._flushing = true;
990
1094
  let flight = null;
991
1095
  try {
@@ -1117,7 +1221,7 @@ function resolveEndpoints(endpointOption, apiEndpointOption, envEndpoint, envApi
1117
1221
  }
1118
1222
  function resolveConfig(config) {
1119
1223
  const env = process.env;
1120
- const apiKey = config?.apiKey ?? env.RISICARE_API_KEY;
1224
+ const apiKey = keyText(config?.apiKey) || keyText(env.RISICARE_API_KEY) || void 0;
1121
1225
  const { endpoint, apiEndpoint } = resolveEndpoints(
1122
1226
  config?.endpoint,
1123
1227
  config?.apiEndpoint,
@@ -1159,6 +1263,7 @@ function resolveConfig(config) {
1159
1263
  } else {
1160
1264
  enabled = !!apiKey;
1161
1265
  }
1266
+ if (!apiKey) enabled = false;
1162
1267
  return hideKeyFromInspect({
1163
1268
  apiKey: apiKey ?? "",
1164
1269
  endpoint,
@@ -1209,6 +1314,14 @@ function tracingFromEnv(value) {
1209
1314
  );
1210
1315
  return false;
1211
1316
  }
1317
+ function keyText(value) {
1318
+ return typeof value === "string" ? value.trim() : "";
1319
+ }
1320
+ function tracingTurnedOff(config) {
1321
+ if (config?.enabled !== void 0) return config.enabled === false;
1322
+ const v = (process.env.RISICARE_TRACING ?? "").trim().toLowerCase();
1323
+ return v !== "" && !TRACING_ON.has(v);
1324
+ }
1212
1325
  function parseNumericEnv(value, defaultValue) {
1213
1326
  if (value === void 0) return defaultValue;
1214
1327
  const n = Number(value);
@@ -2329,7 +2442,111 @@ function markCancel(span, error) {
2329
2442
  }
2330
2443
 
2331
2444
  // src/version.ts
2332
- var SDK_VERSION = "0.8.0";
2445
+ var SDK_VERSION = "0.9.1";
2446
+
2447
+ // src/exporters/quota.ts
2448
+ var QUOTA_REASON = "monthly_quota_exceeded";
2449
+ var QUOTA_HEADER = "X-Risicare-Quota";
2450
+ var QUOTA_HEADER_VALUE = "exceeded";
2451
+ var DEFAULT_RETRY_AFTER_S = 300;
2452
+ var MIN_RETRY_AFTER_S = 1;
2453
+ var MAX_RETRY_AFTER_S = 3600;
2454
+ var QUOTA_WARN_WINDOW_MS = 36e5;
2455
+ var MAX_RESETS_AT_CHARS = 40;
2456
+ function asPositiveCount(v) {
2457
+ if (typeof v === "number") return Number.isFinite(v) && v > 0;
2458
+ if (typeof v === "string" && /^[0-9]+$/.test(v)) return Number(v) > 0;
2459
+ return false;
2460
+ }
2461
+ function boundedRetryAfter(value) {
2462
+ let n;
2463
+ if (typeof value === "number") n = value;
2464
+ else if (typeof value === "string" && value.trim() !== "") n = Number(value);
2465
+ else return DEFAULT_RETRY_AFTER_S;
2466
+ if (!Number.isFinite(n)) return DEFAULT_RETRY_AFTER_S;
2467
+ return Math.min(Math.max(n, MIN_RETRY_AFTER_S), MAX_RETRY_AFTER_S);
2468
+ }
2469
+ function boundedResetsAt(value) {
2470
+ if (typeof value !== "string" || value.length === 0) return null;
2471
+ const cut = value.slice(0, MAX_RESETS_AT_CHARS);
2472
+ return /^[ -~]*$/.test(cut) ? cut : null;
2473
+ }
2474
+ function headerSaysExceeded(headers) {
2475
+ try {
2476
+ const value = headers?.get?.(QUOTA_HEADER);
2477
+ return typeof value === "string" && value.trim().toLowerCase() === QUOTA_HEADER_VALUE;
2478
+ } catch {
2479
+ return false;
2480
+ }
2481
+ }
2482
+ function parseJsonDiscard(payload, headers) {
2483
+ const body = payload !== null && typeof payload === "object" && !Array.isArray(payload) ? payload : {};
2484
+ const stored = (asPositiveCount(body.accepted) || asPositiveCount(body.spansAccepted)) === true;
2485
+ if (body.reason === QUOTA_REASON || headerSaysExceeded(headers) && !stored) {
2486
+ return {
2487
+ retryAfterS: boundedRetryAfter(body.retryAfterSeconds),
2488
+ resetsAt: boundedResetsAt(body.resetsAt)
2489
+ };
2490
+ }
2491
+ return null;
2492
+ }
2493
+ var EPISODE_END_ACCEPTS = 3;
2494
+ var QuotaPause = class {
2495
+ constructor(now = () => performance.now()) {
2496
+ this.now = now;
2497
+ }
2498
+ _until = -Infinity;
2499
+ _inEpisode = false;
2500
+ _accepts = 0;
2501
+ _lastWarn = -Infinity;
2502
+ _lastInfo = -Infinity;
2503
+ /**
2504
+ * Spans dropped since the last WARNING: the full queue's (`addDrops`) and the batches that a
2505
+ * probe lost while the WARNING was held back. The WARNING carries the number.
2506
+ */
2507
+ _drops = 0;
2508
+ addDrops(count) {
2509
+ this._drops += count;
2510
+ }
2511
+ paused() {
2512
+ return this.now() < this._until;
2513
+ }
2514
+ remainingS() {
2515
+ return Math.max(0, (this._until - this.now()) / 1e3);
2516
+ }
2517
+ enter(discard, where, dropped) {
2518
+ const t = this.now();
2519
+ this._until = t + discard.retryAfterS * 1e3;
2520
+ this._inEpisode = true;
2521
+ this._accepts = 0;
2522
+ if (t - this._lastWarn >= QUOTA_WARN_WINDOW_MS) {
2523
+ this._lastWarn = t;
2524
+ const since = this._drops;
2525
+ this._drops = 0;
2526
+ warn(
2527
+ `Risicare: the monthly event quota is used up (monthly_quota_exceeded). ${where} discarded ${dropped} span(s) and will discard new ones until the quota resets (resetsAt=${discard.resetsAt ?? "unknown"}) or the plan changes. The SDK pauses export and sends one batch again in ${Math.round(discard.retryAfterS)} s. Spans that end in the meantime wait in the queue. When it is full the oldest spans are dropped (the most recent are kept) and counted as quota_exceeded in droppedSpansByReason; a batch that is discarded again is dropped and counted the same way. This is not an error and the SDK does not retry the batch. At most one such WARNING an hour.` + (since > 0 ? ` Spans dropped for the quota since the last WARNING: ${since}.` : "")
2528
+ );
2529
+ } else {
2530
+ this._drops += dropped;
2531
+ debug(`Quota discard again: ${dropped} span(s); paused for ${Math.round(discard.retryAfterS)} s`);
2532
+ }
2533
+ }
2534
+ accepted(where) {
2535
+ if (!this._inEpisode) return;
2536
+ this._accepts++;
2537
+ if (this._accepts < EPISODE_END_ACCEPTS) return;
2538
+ this._inEpisode = false;
2539
+ this._accepts = 0;
2540
+ this._until = -Infinity;
2541
+ const t = this.now();
2542
+ if (t - this._lastInfo >= QUOTA_WARN_WINDOW_MS) {
2543
+ this._lastInfo = t;
2544
+ info(`Risicare: ${where} accepts spans again; the export pause for the quota has ended.`);
2545
+ } else {
2546
+ debug("Quota pause ended (INFO already written this hour)");
2547
+ }
2548
+ }
2549
+ };
2333
2550
 
2334
2551
  // src/exporters/http.ts
2335
2552
  var CAPACITY_REFUSAL_STATUSES = /* @__PURE__ */ new Set([429, 503]);
@@ -2370,8 +2587,21 @@ var HttpExporter = class {
2370
2587
  _calls = /* @__PURE__ */ new Map();
2371
2588
  /** The ack of each finished call, by its batch. Read once by `takeAck(spans)`. */
2372
2589
  _acks = /* @__PURE__ */ new WeakMap();
2590
+ /** The batch processor dropped span(s) from a full queue in the quota pause (S-1). */
2591
+ noteQuotaDrop(count = 1) {
2592
+ this._quota.addDrops(count);
2593
+ }
2594
+ /** True while the exporter is paused for the monthly event quota (S-1). */
2595
+ quotaPaused() {
2596
+ return this._quota.paused();
2597
+ }
2373
2598
  /** The spans of each finished call that could not be serialized, by its batch. */
2374
2599
  _unserializable = /* @__PURE__ */ new WeakMap();
2600
+ /**
2601
+ * S-1: the paused state after a monthly-quota discard (see `quota.ts`). A discard is not a
2602
+ * failure: it does not touch the circuit breaker.
2603
+ */
2604
+ _quota = new QuotaPause();
2375
2605
  _circuitOpenUntil = 0;
2376
2606
  _circuitBreakerThreshold = 5;
2377
2607
  _circuitBreakerCooldownMs = 6e4;
@@ -2463,6 +2693,13 @@ var HttpExporter = class {
2463
2693
  }
2464
2694
  async _export(spans, call) {
2465
2695
  const cancelled = call.cancel.signal;
2696
+ if (this._quota.paused()) {
2697
+ debug(
2698
+ `Export skipped: monthly quota pause, ${Math.round(this._quota.remainingS())} s left; ${spans.length} span(s) dropped`
2699
+ );
2700
+ this._acks.set(spans, { accepted: 0, rejected: 0, quotaDropped: spans.length });
2701
+ return "success" /* SUCCESS */;
2702
+ }
2466
2703
  const parts = [];
2467
2704
  const bad = [];
2468
2705
  let errorClass = "";
@@ -2671,6 +2908,11 @@ var HttpExporter = class {
2671
2908
  `HTTP ${response.status} and a body that is not a Risicare ack (content-type: ${response.headers?.get?.("Content-Type") || "none"})`
2672
2909
  );
2673
2910
  }
2911
+ if (ack.quota !== void 0) {
2912
+ this._quota.enter(ack.quota, `The ingest endpoint ${this._safeEndpoint}`, spansSent);
2913
+ } else if (ack.result === "success" /* SUCCESS */) {
2914
+ this._quota.accepted(`the ingest endpoint ${this._safeEndpoint}`);
2915
+ }
2674
2916
  if (ack.result === "success" /* SUCCESS */) this._acks.set(spans, ack.counts);
2675
2917
  if (ack.final) call.noRetry = true;
2676
2918
  return ack.result;
@@ -2737,7 +2979,16 @@ async function checkAck(response, spansSent, scrub) {
2737
2979
  try {
2738
2980
  payload = await response.json();
2739
2981
  } catch {
2740
- return null;
2982
+ payload = void 0;
2983
+ }
2984
+ const discard = parseJsonDiscard(payload, response.headers);
2985
+ if (discard !== null) {
2986
+ return {
2987
+ result: "success" /* SUCCESS */,
2988
+ counts: { accepted: 0, rejected: 0, quotaDropped: spansSent },
2989
+ final: false,
2990
+ quota: discard
2991
+ };
2741
2992
  }
2742
2993
  if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
2743
2994
  return null;
@@ -2767,27 +3018,6 @@ async function checkAck(response, spansSent, scrub) {
2767
3018
  return { result: "success" /* SUCCESS */, counts, final: false };
2768
3019
  }
2769
3020
 
2770
- // src/exporters/console.ts
2771
- var ConsoleExporter = class {
2772
- name = "console";
2773
- /**
2774
- * It only shows spans locally, so its success is not a delivery. When another
2775
- * exporter is present, the batch processor ignores this exporter's result.
2776
- */
2777
- countsAsDelivery = false;
2778
- export(spans) {
2779
- for (const span of spans) {
2780
- const payload = span.toPayload();
2781
- const line = JSON.stringify(payload);
2782
- process.stderr.write(`[risicare] ${line}
2783
- `);
2784
- }
2785
- return "success" /* SUCCESS */;
2786
- }
2787
- shutdown() {
2788
- }
2789
- };
2790
-
2791
3021
  // src/utils/stream-proxy.ts
2792
3022
  function endOpenProviderSpans() {
2793
3023
  let open;
@@ -3980,6 +4210,8 @@ var TERMINATING_SIGNALS = [
3980
4210
  ];
3981
4211
  var BACKSTOP_MARGIN_MS = 500;
3982
4212
  var _finalMetrics;
4213
+ var _finalProcessor;
4214
+ var _finalActive = false;
3983
4215
  var SCORE_TIMEOUT_MS = 2e3;
3984
4216
  var _pendingScores = /* @__PURE__ */ new Set();
3985
4217
  var _failedScores = 0;
@@ -4060,6 +4292,13 @@ var RisicareClient = class {
4060
4292
  * this flag `getMetrics()` would keep reporting `"running"` over a processor
4061
4293
  * that has already been torn down. */
4062
4294
  isShutdown = false;
4295
+ /**
4296
+ * Tracing was on at `init()` or since `enable()`. A client that never was
4297
+ * (no key, or tracing off) accepted nothing, and delivered nothing: its
4298
+ * `flush()` is false. `disable()` does not clear it: spans that were accepted
4299
+ * before keep their answer.
4300
+ */
4301
+ _activated = false;
4063
4302
  _shutdownPromise;
4064
4303
  _shutdownHandlers = [];
4065
4304
  constructor(config) {
@@ -4070,16 +4309,13 @@ var RisicareClient = class {
4070
4309
  'the API key does not look like a Risicare key: it should start with "rsk-", "rski_" or "rsks_". Tracing continues with this key.'
4071
4310
  );
4072
4311
  }
4073
- const tracingSetExplicitly = config?.enabled !== void 0 || (process.env.RISICARE_TRACING ?? "").trim() !== "";
4074
- if (!this.config.apiKey && !this.config.enabled && !tracingSetExplicitly) {
4312
+ if (!this.config.apiKey && !tracingTurnedOff(config)) {
4075
4313
  warn(
4076
- "Risicare found no API key. Tracing is off and the SDK sends no span. Pass apiKey to init() or set RISICARE_API_KEY."
4314
+ "Risicare found no API key. Nothing is sent to Risicare: tracing is off, no span is created, and flush() returns false. Set the RISICARE_API_KEY environment variable, or pass apiKey to init()."
4077
4315
  );
4078
4316
  }
4079
4317
  let exporter;
4080
- if (this.config.debug && !this.config.apiKey) {
4081
- exporter = new ConsoleExporter();
4082
- } else if (this.config.apiKey) {
4318
+ if (this.config.apiKey) {
4083
4319
  exporter = new HttpExporter({
4084
4320
  endpoint: this.config.endpoint,
4085
4321
  apiKey: this.config.apiKey,
@@ -4087,16 +4323,6 @@ var RisicareClient = class {
4087
4323
  environment: this.config.environment || void 0,
4088
4324
  compress: this.config.compress
4089
4325
  });
4090
- } else {
4091
- exporter = void 0;
4092
- if (this.config.enabled) {
4093
- try {
4094
- console.warn(
4095
- `[risicare] tracing is enabled but NO API key is configured \u2014 spans are created and then DROPPED, not sent to ${this.config.endpoint}. Pass apiKey to init() (or set the RISICARE_API_KEY env var). Span data is NOT written to the console: it would be unredacted. Pass debug:true if you want console output for local development.`
4096
- );
4097
- } catch {
4098
- }
4099
- }
4100
4326
  }
4101
4327
  this.processor = new BatchSpanProcessor({
4102
4328
  exporters: exporter ? [exporter] : [],
@@ -4127,6 +4353,7 @@ var RisicareClient = class {
4127
4353
  serviceName: this.config.serviceName,
4128
4354
  serviceVersion: this.config.serviceVersion
4129
4355
  });
4356
+ this._activated = this.tracer.enabled;
4130
4357
  this.processor.start();
4131
4358
  if (this.config.apiKey && this.config.enabled && this.config.fixRuntime) {
4132
4359
  try {
@@ -4165,7 +4392,12 @@ var RisicareClient = class {
4165
4392
  return this.tracer.enabled;
4166
4393
  }
4167
4394
  set enabled(value) {
4395
+ if (value && !this.config.apiKey) {
4396
+ debug("enable() ignored: no API key is configured, so tracing stays off");
4397
+ return;
4398
+ }
4168
4399
  this.tracer.enabled = value;
4400
+ if (value) this._activated = true;
4169
4401
  }
4170
4402
  // Audit #6: Promise-based shutdown dedup (fixes TOCTOU race condition)
4171
4403
  async shutdown(timeoutMs) {
@@ -4184,6 +4416,8 @@ var RisicareClient = class {
4184
4416
  _failWaitingScores(SCORE_DEADLINE_REASON);
4185
4417
  this.isShutdown = true;
4186
4418
  _finalMetrics = this.processor.getMetrics();
4419
+ _finalProcessor = this.processor;
4420
+ _finalActive = this._activated;
4187
4421
  }
4188
4422
  /**
4189
4423
  * Flush pending spans.
@@ -4197,6 +4431,7 @@ var RisicareClient = class {
4197
4431
  * *discarded*.
4198
4432
  */
4199
4433
  async flush(timeoutMs) {
4434
+ if (!this._activated) return false;
4200
4435
  return this.processor.flush(timeoutMs);
4201
4436
  }
4202
4437
  /**
@@ -4223,6 +4458,19 @@ var RisicareClient = class {
4223
4458
  * * **A prior listener exists.** The application took ownership before the
4224
4459
  * SDK loaded. We drain and RETURN; termination was never ours to decide,
4225
4460
  * and forcing it would cut off the app's own graceful shutdown.
4461
+ * * **A listener that the application adds after `init()`.** Node calls ours
4462
+ * first. The question is asked when OUR listener starts, at signal time:
4463
+ * is there another listener for this signal? If there is, it owns
4464
+ * termination as well: when the drain ends we do not raise the signal
4465
+ * again, and we do not arm the fail-safe exit. Its listener runs once and
4466
+ * decides the exit, in the same way as when it was registered before
4467
+ * `init()`. Through 0.8.0 the re-raise ran it a second time, and the
4468
+ * fail-safe ended the process with code 143, 100 ms later.
4469
+ * * **A listener that the application adds DURING the drain.** There was none
4470
+ * at signal time, so the 0.8.0 rule holds: after the drain we raise the
4471
+ * signal again, and that listener runs on it, and the process ends (fail-safe
4472
+ * after 100 ms if it does not). A count taken after the drain would have
4473
+ * counted that listener, and nothing would have run or ended the process.
4226
4474
  *
4227
4475
  * ⚠ `beforeExit` is deliberately NOT in that logic. It is not a signal and
4228
4476
  * carries no termination the SDK could displace — the loop has already
@@ -4238,6 +4486,7 @@ var RisicareClient = class {
4238
4486
  for (const [signal, signum] of TERMINATING_SIGNALS) {
4239
4487
  const weDisplacedDefault = process.listenerCount(signal) === 0;
4240
4488
  const handler = () => {
4489
+ const othersAtSignal = process.listeners(signal).filter((l) => l !== handler).length;
4241
4490
  const backstop = setTimeout(
4242
4491
  () => process.exit(128 + signum),
4243
4492
  SHUTDOWN_BUDGET_MS + BACKSTOP_MARGIN_MS
@@ -4247,6 +4496,7 @@ var RisicareClient = class {
4247
4496
  }).finally(() => {
4248
4497
  clearTimeout(backstop);
4249
4498
  if (!weDisplacedDefault) return;
4499
+ if (othersAtSignal > 0) return;
4250
4500
  try {
4251
4501
  process.kill(process.pid, signal);
4252
4502
  } catch {
@@ -4295,6 +4545,8 @@ function init(config) {
4295
4545
  return;
4296
4546
  }
4297
4547
  _finalMetrics = void 0;
4548
+ _finalProcessor = void 0;
4549
+ _finalActive = false;
4298
4550
  _resetScoreFailures();
4299
4551
  const client = new RisicareClient(config);
4300
4552
  setClient(client);
@@ -4317,10 +4569,12 @@ async function flush(timeoutMs) {
4317
4569
  const scoreMark = _failedScoresFlushMark;
4318
4570
  const client = getClient();
4319
4571
  let spansOk;
4320
- if (!client) {
4321
- spansOk = (_finalMetrics?.droppedSpansByReason.shutdown_residue ?? 0) === 0;
4322
- } else {
4572
+ if (client) {
4323
4573
  spansOk = await client.flush(timeoutMs);
4574
+ } else if (_finalProcessor) {
4575
+ spansOk = _finalActive && await _finalProcessor.flush(timeoutMs);
4576
+ } else {
4577
+ spansOk = false;
4324
4578
  }
4325
4579
  const scoresDone = await _waitForPendingScores(deadline - Date.now());
4326
4580
  if (!scoresDone) _failWaitingScores(SCORE_DEADLINE_REASON);
@@ -4339,7 +4593,7 @@ function disable() {
4339
4593
  }
4340
4594
  function isEnabled() {
4341
4595
  const client = getClient();
4342
- return client?.enabled ?? false;
4596
+ return client !== void 0 && !client.isShutdown && client.enabled;
4343
4597
  }
4344
4598
  function getTracer2() {
4345
4599
  return getTracer();
@@ -4358,10 +4612,11 @@ function getMetrics() {
4358
4612
  };
4359
4613
  }
4360
4614
  if (_finalMetrics) {
4615
+ const tally = _finalProcessor?.getMetrics() ?? _finalMetrics;
4361
4616
  return {
4362
- ..._finalMetrics,
4617
+ ...tally,
4363
4618
  failedScores: _failedScores,
4364
- droppedSpansByReason: { ..._finalMetrics.droppedSpansByReason },
4619
+ droppedSpansByReason: { ...tally.droppedSpansByReason },
4365
4620
  sdkState: "shutdown"
4366
4621
  };
4367
4622
  }
@@ -4374,8 +4629,10 @@ function getMetrics() {
4374
4629
  queue_full: 0,
4375
4630
  transport_refused: 0,
4376
4631
  shutdown_residue: 0,
4377
- unacknowledged: 0
4632
+ unacknowledged: 0,
4633
+ quota_exceeded: 0
4378
4634
  },
4635
+ droppedQuota: 0,
4379
4636
  failedExports: 0,
4380
4637
  queueSize: 0,
4381
4638
  queueCapacity: 0,
@@ -4433,24 +4690,29 @@ function reportError(error, options) {
4433
4690
  debug("reportError failed");
4434
4691
  }
4435
4692
  }
4693
+ function refuseScore(message) {
4694
+ warn(message);
4695
+ const client = getClient();
4696
+ if (client && !client.isShutdown && client.enabled && client.config.apiKey) _failedScores += 1;
4697
+ }
4436
4698
  function score(traceId, name, value, options) {
4437
4699
  try {
4438
4700
  const raw = value;
4439
4701
  if (typeof raw === "boolean") value = raw ? 1 : 0;
4440
4702
  if (typeof value !== "number") {
4441
- warn(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4703
+ refuseScore(`score: the value must be a number, not ${typeof raw}. The SDK does not send this score.`);
4442
4704
  return;
4443
4705
  }
4444
4706
  if (!Number.isFinite(value) || value < 0 || value > 1) {
4445
- warn(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4707
+ refuseScore(`score: the value must be in [0.0, 1.0], not ${value}. The SDK does not send this score.`);
4446
4708
  return;
4447
4709
  }
4448
4710
  if (typeof traceId !== "string" || given(traceId) === void 0) {
4449
- warn("score: traceId must be a non-empty string. The SDK does not send this score.");
4711
+ refuseScore("score: traceId must be a non-empty string. The SDK does not send this score.");
4450
4712
  return;
4451
4713
  }
4452
4714
  if (typeof name !== "string" || given(name) === void 0) {
4453
- warn("score: name must be a non-empty string. The SDK does not send this score.");
4715
+ refuseScore("score: name must be a non-empty string. The SDK does not send this score.");
4454
4716
  return;
4455
4717
  }
4456
4718
  const client = getClient();