@goodtiming/baton-sdk 0.6.3 → 0.6.4

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/version.ts
2
- var SDK_VERSION = "ts-0.6.3";
2
+ var SDK_VERSION = "ts-0.6.4";
3
3
 
4
4
  // src/events.ts
5
5
  import { z } from "zod";
@@ -580,7 +580,7 @@ var DropCounts = class {
580
580
  const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
581
581
  this.#sinceDelivery.clear();
582
582
  this.#lastRecoveryLog = now;
583
- const total = lost.reduce((sum, [, n]) => sum + n, 0);
583
+ const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
584
584
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
585
585
  }
586
586
  /** For tests: the counts are one per process. */
@@ -638,12 +638,10 @@ function stderrLine(message) {
638
638
  function isTimerMs(value) {
639
639
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
640
640
  }
641
- function shutdownFlushTimeoutOption(given) {
641
+ function timerMsOption(given, name, fallback) {
642
642
  if (isTimerMs(given)) return given;
643
- if (given !== void 0) {
644
- warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
645
- }
646
- return SHUTDOWN_FLUSH_TIMEOUT_MS;
643
+ if (given !== void 0) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);
644
+ return fallback;
647
645
  }
648
646
  function shutdownBudgetMs(sink) {
649
647
  try {
@@ -740,6 +738,31 @@ var MultiSink = class {
740
738
  throw new AggregateError(errors, "MultiSink fan-out failures");
741
739
  }
742
740
  };
741
+ var BATCH_OPEN = '{"events":[';
742
+ var BATCH_CLOSE = "]}";
743
+ var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
744
+ var BATCH_MAX_EVENTS = 100;
745
+ var BATCH_MAX_BYTES = 1048576;
746
+ var FLUSH_INTERVAL_MS = 5e3;
747
+ var RETRY_AFTER_MIN_S = 1;
748
+ var RETRY_AFTER_MAX_S = 60;
749
+ var utf8 = new TextEncoder();
750
+ function utf8Bytes(text) {
751
+ return typeof Buffer === "undefined" ? utf8.encode(text).length : Buffer.byteLength(text, "utf8");
752
+ }
753
+ function sum(values) {
754
+ let total = 0;
755
+ for (const value of values) total += value;
756
+ return total;
757
+ }
758
+ function retryAfterMs(header) {
759
+ const value = header?.trim() ?? "";
760
+ if (!/^\d+$/.test(value)) return null;
761
+ return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
762
+ }
763
+ function sameBatch(a, b) {
764
+ return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;
765
+ }
743
766
  var CircuitBreaker = class {
744
767
  constructor(threshold, resetMs) {
745
768
  this.threshold = threshold;
@@ -750,8 +773,11 @@ var CircuitBreaker = class {
750
773
  failures = 0;
751
774
  openedAt = null;
752
775
  canRequest() {
753
- if (this.openedAt === null) return true;
754
- return Date.now() - this.openedAt >= this.resetMs;
776
+ return this.msUntilRequest() === 0;
777
+ }
778
+ msUntilRequest() {
779
+ if (this.openedAt === null) return 0;
780
+ return Math.max(this.openedAt + this.resetMs - Date.now(), 0);
755
781
  }
756
782
  recordSuccess() {
757
783
  this.failures = 0;
@@ -767,12 +793,17 @@ var CircuitBreaker = class {
767
793
  var HttpSink = class _HttpSink {
768
794
  url;
769
795
  apiKey;
796
+ /** Waiting events only: a batch being sent is out of it, so the bound
797
+ * never pushes out an event in flight (SPEC §11.2 rule 4). */
770
798
  buffer = [];
799
+ bufferedBytes = 0;
800
+ sendingEvents = 0;
771
801
  bufferSize;
772
802
  requestTimeoutMs;
773
803
  shutdownFlushTimeoutMs;
774
- /** Set when an exit pass ends; cleared once a normal drain empties the
775
- * buffer, which means the process went on. */
804
+ flushIntervalMs;
805
+ /** Set when an exit pass ends; cleared once a normal drain sends
806
+ * everything, which means the process went on. */
776
807
  exitPassRan = false;
777
808
  /** Whether the exit pass warned about every event now buffered. */
778
809
  unsentWarned = false;
@@ -782,7 +813,8 @@ var HttpSink = class _HttpSink {
782
813
  circuit;
783
814
  fetchImpl;
784
815
  overflowWarned = false;
785
- /** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
816
+ /** Per status or refusal code, so a new kind of refusal, such as a 401
817
+ * after a 422, still warns. */
786
818
  refusals = /* @__PURE__ */ new Map();
787
819
  /** Aborted once `aclose()` returns: nothing Baton started may keep the
788
820
  * process alive after the vendor closed it. */
@@ -792,6 +824,16 @@ var HttpSink = class _HttpSink {
792
824
  skipWarnedFor = null;
793
825
  closeOnce;
794
826
  drainChain = Promise.resolve();
827
+ queuedDrain = null;
828
+ /** Whether the queued pass sends everything waiting, not only what is due. */
829
+ forceNext = false;
830
+ flushTimer = null;
831
+ /** Set by a failed batch: only the timer, a flush or a close tries again. */
832
+ waitForTimer = false;
833
+ /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
834
+ retryAt = 0;
835
+ /** Set for the life of the sink by a 404 or 405 on the batch path. */
836
+ batchless = false;
795
837
  exitHooks = null;
796
838
  /** The least time between two of this sink's loss reports. */
797
839
  static reportIntervalMs = 6e4;
@@ -799,13 +841,20 @@ var HttpSink = class _HttpSink {
799
841
  reportedSum = 0;
800
842
  lastReportAt = -Infinity;
801
843
  reportsStopped = false;
802
- reportInFlight = null;
844
+ /** The envelope of a report due to ride the next batch, and when it was set up. */
845
+ pendingReport = null;
846
+ reportSetAt = 0;
803
847
  constructor(url, options) {
804
848
  this.url = url.replace(/\/+$/, "");
805
849
  this.apiKey = options.apiKey;
806
850
  this.bufferSize = options.bufferSize ?? 1e3;
807
851
  this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
808
- this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
852
+ this.shutdownFlushTimeoutMs = timerMsOption(
853
+ options.shutdownFlushTimeoutMs,
854
+ "shutdownFlushTimeoutMs",
855
+ SHUTDOWN_FLUSH_TIMEOUT_MS
856
+ );
857
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
809
858
  this.maxRetries = options.maxRetries ?? 3;
810
859
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
811
860
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -835,11 +884,24 @@ var HttpSink = class _HttpSink {
835
884
  get closed() {
836
885
  return this.closing.signal.aborted;
837
886
  }
887
+ get unsent() {
888
+ return this.buffer.length + this.sendingEvents;
889
+ }
890
+ /** Encodes at once, not when the batch is cut, because the byte cap
891
+ * decides when a batch goes. */
838
892
  async write(event) {
839
893
  if (this.closed) throw new SinkClosedError("HttpSink is closed");
840
- this.enqueue(event);
894
+ const json = this.encode(event);
895
+ if (json === null) return;
896
+ const bytes = utf8Bytes(json);
897
+ if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {
898
+ this.refuse(1, { kind: "over 1 MiB", detail: `${bytes} bytes` }, false);
899
+ return;
900
+ }
901
+ this.enqueue({ event, json, bytes, writtenAt: Date.now() });
841
902
  this.unsentWarned = false;
842
- void this.scheduleDrain();
903
+ if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
904
+ else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
843
905
  this.ensureExitHooksRegistered();
844
906
  }
845
907
  flush() {
@@ -861,9 +923,11 @@ var HttpSink = class _HttpSink {
861
923
  this.stopReports();
862
924
  await this.drainWithinBudget("aclose()", ms);
863
925
  this.closing.abort();
864
- if (this.buffer.length > 0) {
865
- PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
866
- warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
926
+ this.clearTimer();
927
+ const unsent = this.unsent;
928
+ if (unsent > 0) {
929
+ PROCESS_DROPS.add("unsent_at_close", unsent);
930
+ warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
867
931
  }
868
932
  this.warnUnloggedRefusals("the sink closed");
869
933
  if (this.exitHooks) {
@@ -885,11 +949,11 @@ var HttpSink = class _HttpSink {
885
949
  }
886
950
  if (this.skipWarnedFor !== this.stalledDrain) {
887
951
  this.skipWarnedFor = this.stalledDrain;
888
- warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
952
+ warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
889
953
  }
890
954
  return;
891
955
  }
892
- const settled = this.scheduleDrain().catch(() => void 0);
956
+ const settled = this.scheduleDrain(true).catch(() => void 0);
893
957
  if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
894
958
  if (ms < this.shutdownFlushTimeoutMs) return;
895
959
  const stalled = this.drainChain.catch(() => void 0);
@@ -901,12 +965,13 @@ var HttpSink = class _HttpSink {
901
965
  warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
902
966
  }
903
967
  }
904
- /** A full buffer may already have pushed `event` out while it was being sent. */
905
- dequeue(event) {
906
- if (this.buffer[0] === event) this.buffer.shift();
968
+ enqueue(waiting) {
969
+ this.buffer.push(waiting);
970
+ this.bufferedBytes += waiting.bytes;
971
+ this.dropOverflow();
907
972
  }
908
- enqueue(event) {
909
- if (this.buffer.length >= this.bufferSize) {
973
+ dropOverflow() {
974
+ while (this.buffer.length > this.bufferSize) {
910
975
  PROCESS_DROPS.add("buffer_full");
911
976
  if (!this.overflowWarned) {
912
977
  warn(
@@ -914,21 +979,49 @@ var HttpSink = class _HttpSink {
914
979
  );
915
980
  this.overflowWarned = true;
916
981
  }
917
- this.buffer.shift();
982
+ this.bufferedBytes -= this.buffer.shift().bytes;
918
983
  }
919
- this.buffer.push(event);
920
- }
921
- /** Serializes every call to `drainLocked` — from `write()`'s background
922
- * drain and from explicit `flush()` alike — onto one promise chain, so
923
- * concurrent tool calls (the normal case once the MCP interceptor is
924
- * wired up) can never run two drains at once racing on `buffer[0]`/
925
- * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
926
- scheduleDrain() {
927
- this.drainChain = this.drainChain.then(
928
- () => this.drainLocked(),
929
- () => this.drainLocked()
984
+ }
985
+ batchIsFull() {
986
+ return this.buffer.length >= BATCH_MAX_EVENTS || BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES;
987
+ }
988
+ /** The timer must not keep the vendor's process alive: the exit hooks send
989
+ * what is left. */
990
+ armTimer(delayMs) {
991
+ if (this.flushTimer !== null || this.closed) return;
992
+ const timer = setTimeout(
993
+ () => {
994
+ this.flushTimer = null;
995
+ this.waitForTimer = false;
996
+ void this.scheduleDrain(false);
997
+ },
998
+ Math.min(Math.max(delayMs, 0), MAX_TIMER_MS)
930
999
  );
931
- return this.drainChain;
1000
+ timer.unref?.();
1001
+ this.flushTimer = timer;
1002
+ }
1003
+ clearTimer() {
1004
+ if (this.flushTimer === null) return;
1005
+ clearTimeout(this.flushTimer);
1006
+ this.flushTimer = null;
1007
+ }
1008
+ /** Runs `drainLocked` after the pass under way, one pass at a time, so two
1009
+ * never send at once or race on the buffer. A pass not yet started is
1010
+ * shared by every caller: one per write would grow without bound while a
1011
+ * slow collector holds a pass. */
1012
+ scheduleDrain(force) {
1013
+ this.forceNext ||= force;
1014
+ if (this.queuedDrain) return this.queuedDrain;
1015
+ const run = () => {
1016
+ this.queuedDrain = null;
1017
+ const forced = this.forceNext;
1018
+ this.forceNext = false;
1019
+ return this.drainLocked(forced);
1020
+ };
1021
+ this.queuedDrain = this.drainChain.then(run, run);
1022
+ this.queuedDrain.catch(() => void 0);
1023
+ this.drainChain = this.queuedDrain;
1024
+ return this.queuedDrain;
932
1025
  }
933
1026
  /** Best-effort flush when the process is about to exit without an
934
1027
  * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
@@ -937,18 +1030,18 @@ var HttpSink = class _HttpSink {
937
1030
  ensureExitHooksRegistered() {
938
1031
  if (this.exitHooks) return;
939
1032
  const beforeExit = () => {
940
- if (this.buffer.length === 0 || this.exitPassRan) {
1033
+ if (this.unsent === 0 || this.exitPassRan) {
941
1034
  this.warnUnloggedRefusals("process exiting");
942
1035
  return;
943
1036
  }
944
1037
  this.drainChain = this.drainChain.then(
945
1038
  () => this.exitPass(),
946
1039
  () => this.exitPass()
947
- );
1040
+ ).catch(() => void 0);
948
1041
  };
949
1042
  const exit = () => {
950
1043
  try {
951
- if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1044
+ if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
952
1045
  this.warnUnloggedRefusals("process exiting", stderrLine);
953
1046
  } catch {
954
1047
  }
@@ -957,35 +1050,22 @@ var HttpSink = class _HttpSink {
957
1050
  process.on("beforeExit", beforeExit);
958
1051
  process.on("exit", exit);
959
1052
  }
960
- /** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
1053
+ /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
961
1054
  * total (SPEC §11.2); what is left is reported, not sent. */
962
1055
  async exitPass() {
963
1056
  const deadline = Date.now() + this.shutdownFlushTimeoutMs;
964
- while (this.buffer.length > 0 && this.circuit.canRequest()) {
965
- const timeLeft = deadline - Date.now();
966
- if (timeLeft <= 0) break;
967
- const event = this.buffer[0];
968
- const body = this.encode(event);
969
- if (body !== null) {
970
- const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
971
- if (outcome === "transient_failure") {
972
- this.circuit.recordFailure();
973
- break;
974
- }
975
- this.circuit.recordSuccess();
976
- }
977
- this.dequeue(event);
1057
+ while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
1058
+ const batch = this.takeBatch(false);
1059
+ if (batch === null) break;
1060
+ if (!this.putBack(await this.sendBatch(batch, 0, deadline))) break;
978
1061
  }
979
1062
  this.exitPassRan = true;
980
1063
  this.unsentWarned = true;
981
- if (this.buffer.length > 0) warn(this.unsentAtExit());
1064
+ if (this.unsent > 0) warn(this.unsentAtExit());
982
1065
  this.warnUnloggedRefusals("process exiting");
983
1066
  }
984
1067
  unsentAtExit() {
985
- return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
986
- }
987
- events_url() {
988
- return `${this.url}/v0/events`;
1068
+ return `baton: process exiting with ${this.unsent} unsent event(s).`;
989
1069
  }
990
1070
  authHeaders() {
991
1071
  return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
@@ -995,17 +1075,19 @@ var HttpSink = class _HttpSink {
995
1075
  if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
996
1076
  return "transient_failure";
997
1077
  }
998
- /** A refused event is otherwise dropped silently, which looks the same from
999
- * the vendor's process as an accepted one. The collector's own message is
1000
- * logged because it names the field at fault; it is capped and escaped
1078
+ /** Counts `n` refused events and logs them, at most once a minute per
1079
+ * kind. A refused event is otherwise dropped silently, which looks the same
1080
+ * from the vendor's process as an accepted one. The collector's own message
1081
+ * is logged because it names the field at fault; it is capped and escaped
1001
1082
  * because it is a remote server's text landing in the vendor's log. */
1002
- static async logRefusal(response, unlogged) {
1003
- const detail = await _HttpSink.readHead(response).then(
1004
- (text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
1005
- () => "<unreadable>"
1006
- );
1083
+ refuse(n, { kind, detail }, byCollector = true) {
1084
+ if (n === 0) return;
1085
+ PROCESS_DROPS.add("refused", n);
1086
+ const unlogged = this.refusalToLog(kind, n);
1087
+ if (unlogged === null) return;
1088
+ const what = n === 1 ? "an event and it has" : `${n} events and they have`;
1007
1089
  warn(
1008
- `baton: collector REFUSED an event and it has been dropped (HTTP ${response.status}): ${detail} \u2014 the event is gone; nothing retries a 4xx.` + (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : "")
1090
+ `baton: ${byCollector ? "collector REFUSED" : "REFUSED, unsent,"} ${what} been dropped (${kind}): ${escapeForLog(capCodePoints(detail, REFUSAL_BODY_MAX_LEN))} \u2014 the event is gone; nothing retries a refusal.` + (unlogged > 0 ? ` ${unlogged} more refused since the last such warning.` : "")
1009
1091
  );
1010
1092
  }
1011
1093
  warnUnloggedRefusals(when, emit2 = warn) {
@@ -1016,16 +1098,16 @@ var HttpSink = class _HttpSink {
1016
1098
  }
1017
1099
  if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
1018
1100
  }
1019
- /** How many refusals with `status` went unlogged before this one, or `null`
1020
- * when this one goes unlogged too. */
1021
- refusalToLog(status) {
1101
+ /** How many refusals of `kind` went unlogged before these `n`, or `null`
1102
+ * when these go unlogged too. */
1103
+ refusalToLog(kind, n) {
1022
1104
  const now = performance.now();
1023
- const seen = this.refusals.get(status);
1105
+ const seen = this.refusals.get(kind);
1024
1106
  if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
1025
- seen.unlogged++;
1107
+ seen.unlogged += n;
1026
1108
  return null;
1027
1109
  }
1028
- this.refusals.set(status, { loggedAt: now, unlogged: 0 });
1110
+ this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
1029
1111
  return seen?.unlogged ?? 0;
1030
1112
  }
1031
1113
  /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
@@ -1047,87 +1129,205 @@ var HttpSink = class _HttpSink {
1047
1129
  });
1048
1130
  }
1049
1131
  }
1050
- async drainLocked() {
1051
- while (this.buffer.length > 0) {
1052
- if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
1053
- const event = this.buffer[0];
1054
- const outcome = await this.sendWithRetry(event);
1055
- if (outcome === "success" || outcome === "permanent_failure") {
1056
- this.dequeue(event);
1057
- this.circuit.recordSuccess();
1058
- if (outcome === "success") {
1059
- PROCESS_DROPS.logRecovery();
1060
- this.maybeReport(event);
1061
- }
1062
- } else if (outcome === "unencodable") {
1063
- this.dequeue(event);
1064
- } else {
1065
- this.circuit.recordFailure();
1066
- return;
1132
+ /** Sends what is due, one batch at a time; `force` (a flush or close) sends
1133
+ * everything waiting. A report set up before the pass rides along; one set
1134
+ * up by this pass's own delivery waits for the next batch. */
1135
+ async drainLocked(force) {
1136
+ let failed = false;
1137
+ let reportDue = this.pendingReport !== null;
1138
+ while (!this.closed) {
1139
+ if (!this.isDue(force, reportDue)) break;
1140
+ if (!this.circuit.canRequest() || Date.now() < this.retryAt) {
1141
+ failed = true;
1142
+ break;
1067
1143
  }
1144
+ const batch = this.takeBatch(reportDue);
1145
+ if (batch === null) break;
1146
+ if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
1147
+ if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity))) {
1148
+ failed = true;
1149
+ break;
1150
+ }
1151
+ }
1152
+ if (!failed && this.unsent === 0) this.exitPassRan = false;
1153
+ this.waitForTimer = failed;
1154
+ this.clearTimer();
1155
+ if (failed) {
1156
+ const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1157
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1158
+ return;
1159
+ }
1160
+ const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
1161
+ if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());
1162
+ }
1163
+ /** A due report makes the next batch due only when it can ride it; the
1164
+ * timer is armed the same way, so a pass that sends nothing never re-arms
1165
+ * it at a time already past. */
1166
+ isDue(force, reportDue) {
1167
+ const now = Date.now();
1168
+ if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;
1169
+ return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0].writtenAt + this.flushIntervalMs <= now);
1170
+ }
1171
+ /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */
1172
+ reportRidesHead() {
1173
+ const head = this.buffer[0];
1174
+ return this.pendingReport !== null && (head === void 0 || sameBatch(this.pendingReport, head.event));
1175
+ }
1176
+ /** Takes the head of the buffer that fits one batch: one tenant and vendor
1177
+ * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
1178
+ * event's tenant and vendor takes one of those places; otherwise it is not
1179
+ * built, and waits for a batch it can ride. Without a batch endpoint the same events go one
1180
+ * per request. */
1181
+ takeBatch(withReport) {
1182
+ const batch = [];
1183
+ let bytes = BATCH_FRAME_BYTES - 1;
1184
+ let eventBytes = 0;
1185
+ const fits = (w, maxEvents2 = BATCH_MAX_EVENTS, maxBytes2 = BATCH_MAX_BYTES) => batch.length === 0 || batch.length < maxEvents2 && sameBatch(w.event, batch[0].event) && bytes + 1 + w.bytes <= maxBytes2;
1186
+ const report = withReport && this.reportRidesHead() ? this.buildReport() : null;
1187
+ const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
1188
+ const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
1189
+ for (const waiting of this.buffer) {
1190
+ if (!fits(waiting, maxEvents, maxBytes)) break;
1191
+ batch.push(waiting);
1192
+ bytes += 1 + waiting.bytes;
1193
+ eventBytes += waiting.bytes;
1068
1194
  }
1069
- this.exitPassRan = false;
1195
+ this.buffer.splice(0, batch.length);
1196
+ this.bufferedBytes -= eventBytes;
1197
+ this.sendingEvents = batch.length;
1198
+ if (report !== null && fits(report)) {
1199
+ report.alone = batch.length === 0;
1200
+ batch.push(report);
1201
+ }
1202
+ return batch.length > 0 ? batch : null;
1203
+ }
1204
+ /** Puts a kept batch's events back at the head of the buffer; `true` when
1205
+ * there were none. */
1206
+ putBack(kept) {
1207
+ this.sendingEvents = 0;
1208
+ if (this.closed) return kept.length === 0;
1209
+ const events = [];
1210
+ for (const waiting of kept) {
1211
+ if (waiting.reportSum !== void 0) {
1212
+ if (waiting.alone || this.batchless) this.pendingReport = null;
1213
+ continue;
1214
+ }
1215
+ events.push(waiting);
1216
+ this.bufferedBytes += waiting.bytes;
1217
+ }
1218
+ this.buffer.unshift(...events);
1219
+ this.dropOverflow();
1220
+ return kept.length === 0;
1070
1221
  }
1071
- /** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
1072
- * drain and outside the buffer, so it never delays an event and is never
1073
- * counted as one. */
1222
+ /** After a delivery, sets up a report of this process's loss totals (SPEC
1223
+ * §11.4.7) to ride the next batch. It stays outside the buffer, so it never
1224
+ * pushes an event out and is never counted as one. */
1074
1225
  maybeReport({ tenant_id, vendor_id, consent_token }) {
1075
1226
  const now = performance.now();
1076
- if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1227
+ if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1077
1228
  return;
1078
1229
  }
1079
- const totals = PROCESS_DROPS.total();
1080
- const sum = Object.values(totals).reduce((a, b) => a + b, 0);
1081
- if (sum === this.reportedSum) return;
1230
+ if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;
1082
1231
  this.lastReportAt = now;
1083
- const abort = new AbortController();
1084
- this.reportInFlight = abort;
1085
- const envelope = { tenant_id, vendor_id, consent_token };
1086
- void this.sendReport(envelope, totals, sum, abort).finally(() => {
1087
- this.reportInFlight = null;
1088
- });
1232
+ this.reportSetAt = Date.now();
1233
+ this.pendingReport = { tenant_id, vendor_id, consent_token };
1089
1234
  }
1090
1235
  stopReports() {
1091
1236
  this.reportsStopped = true;
1092
- this.reportInFlight?.abort();
1237
+ this.pendingReport = null;
1093
1238
  }
1094
- async sendReport(envelope, totals, sum, abort) {
1095
- const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
1239
+ buildReport() {
1240
+ if (this.pendingReport === null) return null;
1241
+ const totals = PROCESS_DROPS.total();
1096
1242
  try {
1097
1243
  const report = ClientReportEventSchema.parse({
1098
- ...envelope,
1244
+ ...this.pendingReport,
1099
1245
  session_id: PROCESS_DROPS.instanceId,
1100
1246
  sequence_number: nextClockSequence(),
1101
1247
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1102
1248
  payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1103
1249
  });
1104
- const response = await this.fetchImpl(this.events_url(), {
1105
- method: "POST",
1106
- headers: this.authHeaders(),
1107
- body: JSON.stringify(report),
1108
- signal: abort.signal
1109
- });
1110
- void response.body?.cancel().catch(() => void 0);
1111
- if (response.status === 400 || response.status === 422) this.reportsStopped = true;
1112
- else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
1250
+ const json = JSON.stringify(report);
1251
+ return { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1113
1252
  } catch {
1114
- } finally {
1115
- clearTimeout(timer);
1253
+ this.pendingReport = null;
1254
+ return null;
1116
1255
  }
1117
1256
  }
1118
- async sendWithRetry(event) {
1119
- const body = this.encode(event);
1120
- if (body === null) return "unencodable";
1121
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1122
- const outcome = await this.postOnce(body, this.requestTimeoutMs);
1123
- if (outcome !== "transient_failure") return outcome;
1124
- if (attempt < this.maxRetries) {
1125
- const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
1126
- await this.sleepUnlessClosed(backoff);
1127
- if (this.closing.signal.aborted) return "transient_failure";
1257
+ /** Sends one batch, splitting it on 413, until every event in it is
1258
+ * delivered or refused. Returns what a failure kept, to go back in the
1259
+ * buffer. */
1260
+ async sendBatch(batch, retries, deadline) {
1261
+ if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);
1262
+ const batchless = this.batchless;
1263
+ const body = batchless ? batch[0].json : BATCH_OPEN + batch.map((w) => w.json).join(",") + BATCH_CLOSE;
1264
+ for (let attempt = 0; ; attempt++) {
1265
+ const timeLeft = deadline - Date.now();
1266
+ if (timeLeft <= 0) return batch;
1267
+ const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));
1268
+ if (answer.kind === "no_batch_endpoint") {
1269
+ this.batchless = true;
1270
+ warn("baton: the collector has no batch endpoint; sending one event per request.");
1271
+ return this.sendEachAlone(batch, retries, deadline);
1272
+ }
1273
+ if (answer.kind === "too_large") {
1274
+ const half = Math.floor(batch.length / 2);
1275
+ const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);
1276
+ if (kept.length > 0) return [...kept, ...batch.slice(half)];
1277
+ return this.sendBatch(batch.slice(half), retries, deadline);
1278
+ }
1279
+ if (answer.kind === "transient") {
1280
+ if (answer.retryAfterMs !== null) {
1281
+ this.retryAt = Date.now() + answer.retryAfterMs;
1282
+ return batch;
1283
+ }
1284
+ if (attempt < retries && !this.closed) {
1285
+ await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));
1286
+ if (!this.closed) continue;
1287
+ }
1288
+ this.circuit.recordFailure();
1289
+ return batch;
1128
1290
  }
1291
+ this.circuit.recordSuccess();
1292
+ this.settle(batch, answer, batchless);
1293
+ return [];
1294
+ }
1295
+ }
1296
+ async sendEachAlone(batch, retries, deadline) {
1297
+ for (const [i, waiting] of batch.entries()) {
1298
+ if (this.closed) return batch.slice(i);
1299
+ const kept = await this.sendBatch([waiting], retries, deadline);
1300
+ if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];
1301
+ }
1302
+ return [];
1303
+ }
1304
+ /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */
1305
+ settle(batch, answer, alone) {
1306
+ if (this.closed) return;
1307
+ let lastDelivered = null;
1308
+ const refused = /* @__PURE__ */ new Map();
1309
+ for (const waiting of batch) {
1310
+ if (waiting.reportSum === void 0) this.sendingEvents -= 1;
1311
+ const refusal = answer.kind === "refused" ? answer.refusal : answer.refused.get(waiting.event.event_id);
1312
+ if (waiting.reportSum !== void 0) {
1313
+ this.pendingReport = null;
1314
+ if (refusal === void 0) this.reportedSum = waiting.reportSum;
1315
+ else if (answer.kind === "answered" ? refusal.kind === "payload_malformed" : alone && (answer.status === 400 || answer.status === 422)) {
1316
+ this.reportsStopped = true;
1317
+ }
1318
+ } else if (refusal === void 0) {
1319
+ lastDelivered = waiting.event;
1320
+ } else {
1321
+ const seen = refused.get(refusal.kind);
1322
+ if (seen) seen.n += 1;
1323
+ else refused.set(refusal.kind, { first: refusal, n: 1 });
1324
+ }
1325
+ }
1326
+ for (const { first, n } of refused.values()) this.refuse(n, first);
1327
+ if (lastDelivered !== null) {
1328
+ PROCESS_DROPS.logRecovery();
1329
+ this.maybeReport(lastDelivered);
1129
1330
  }
1130
- return "transient_failure";
1131
1331
  }
1132
1332
  /** `null`, with a warning, for an event `JSON.stringify` rejects. */
1133
1333
  encode(event) {
@@ -1155,37 +1355,73 @@ var HttpSink = class _HttpSink {
1155
1355
  }
1156
1356
  /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
1157
1357
  * is missing before Node 20.3, and on some later versions it keeps every
1158
- * combined signal alive as long as the long-lived `closing` signal. */
1159
- async postOnce(body, timeoutMs) {
1358
+ * combined signal alive as long as the long-lived `closing` signal. Any body
1359
+ * read is under the same signal, so a stalled body cannot hold the drain. */
1360
+ async post(body, size, batchless, timeoutMs) {
1361
+ if (this.closed) return { kind: "transient", retryAfterMs: null };
1160
1362
  const request = new AbortController();
1161
1363
  const abort = () => request.abort();
1162
1364
  const timer = setTimeout(abort, timeoutMs);
1163
1365
  this.closing.signal.addEventListener("abort", abort);
1164
1366
  try {
1165
- const response = await this.fetchImpl(this.events_url(), {
1367
+ const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
1166
1368
  method: "POST",
1167
1369
  headers: this.authHeaders(),
1168
1370
  body,
1169
- signal: request.signal
1371
+ signal: request.signal,
1372
+ // SPEC §2.5: a redirect is a failure, not followed.
1373
+ redirect: "manual"
1170
1374
  });
1171
- const outcome = _HttpSink.classifyStatus(response.status);
1172
- if (outcome === "permanent_failure") {
1173
- PROCESS_DROPS.add("refused");
1174
- const unlogged = this.refusalToLog(response.status);
1175
- if (unlogged !== null) {
1176
- await _HttpSink.logRefusal(response, unlogged);
1177
- return outcome;
1375
+ const { status } = response;
1376
+ const outcome = _HttpSink.classifyStatus(status);
1377
+ if (outcome === "success") {
1378
+ if (batchless) {
1379
+ void response.body?.cancel().catch(() => void 0);
1380
+ return { kind: "answered", refused: /* @__PURE__ */ new Map() };
1178
1381
  }
1382
+ return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
1179
1383
  }
1180
- void response.body?.cancel().catch(() => void 0);
1181
- return outcome;
1384
+ const other = _HttpSink.otherAnswer(response, size, batchless);
1385
+ if (other !== null) {
1386
+ void response.body?.cancel().catch(() => void 0);
1387
+ return other;
1388
+ }
1389
+ const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
1390
+ return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
1182
1391
  } catch {
1183
- return "transient_failure";
1392
+ return { kind: "transient", retryAfterMs: null };
1184
1393
  } finally {
1185
1394
  clearTimeout(timer);
1186
1395
  this.closing.signal.removeEventListener("abort", abort);
1187
1396
  }
1188
1397
  }
1398
+ /** Every answer but a 2xx and a refusal of the whole batch. */
1399
+ static otherAnswer(response, size, batchless) {
1400
+ const { status } = response;
1401
+ if (status === 413 && size > 1) return { kind: "too_large" };
1402
+ if ((status === 404 || status === 405) && !batchless) return { kind: "no_batch_endpoint" };
1403
+ if (status === 429) return { kind: "transient", retryAfterMs: retryAfterMs(response.headers.get("Retry-After")) };
1404
+ if (_HttpSink.classifyStatus(status) === "transient_failure") return { kind: "transient", retryAfterMs: null };
1405
+ return null;
1406
+ }
1407
+ /** The refused results by `event_id` (SPEC §2.5). An event with no readable
1408
+ * result was delivered. */
1409
+ static refusedIn(text) {
1410
+ const refused = /* @__PURE__ */ new Map();
1411
+ let results;
1412
+ try {
1413
+ results = JSON.parse(text)?.results;
1414
+ } catch {
1415
+ return refused;
1416
+ }
1417
+ if (!Array.isArray(results)) return refused;
1418
+ const str = (value) => typeof value === "string" ? value : "";
1419
+ for (const result of results) {
1420
+ if (result?.status !== "refused" || typeof result.event_id !== "string") continue;
1421
+ refused.set(result.event_id, { kind: str(result.error?.code) || "no code", detail: str(result.error?.message) });
1422
+ }
1423
+ return refused;
1424
+ }
1189
1425
  };
1190
1426
 
1191
1427
  // src/integrations/mcp/withBaton.ts
@@ -2166,7 +2402,7 @@ function resolveBatonConfig(config) {
2166
2402
  validateBatonConfig(identity);
2167
2403
  return {
2168
2404
  ...identity,
2169
- // The origin is scheme + authority; `HttpSink` appends `/v0/events`
2405
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2170
2406
  // itself, exactly as it does for an explicitly-constructed sink.
2171
2407
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2172
2408
  };