@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.cjs CHANGED
@@ -103,7 +103,7 @@ __export(index_exports, {
103
103
  module.exports = __toCommonJS(index_exports);
104
104
 
105
105
  // src/version.ts
106
- var SDK_VERSION = "ts-0.6.3";
106
+ var SDK_VERSION = "ts-0.6.4";
107
107
 
108
108
  // src/events.ts
109
109
  var import_zod = require("zod");
@@ -684,7 +684,7 @@ var DropCounts = class {
684
684
  const lost = [...this.#sinceDelivery].sort(([a], [b]) => a.localeCompare(b));
685
685
  this.#sinceDelivery.clear();
686
686
  this.#lastRecoveryLog = now;
687
- const total = lost.reduce((sum, [, n]) => sum + n, 0);
687
+ const total = lost.reduce((sum2, [, n]) => sum2 + n, 0);
688
688
  warn(`baton: delivering again; ${total} event(s) lost before this: ${lost.map(([r, n]) => `${r} ${n}`).join(", ")}.`);
689
689
  }
690
690
  /** For tests: the counts are one per process. */
@@ -742,12 +742,10 @@ function stderrLine(message) {
742
742
  function isTimerMs(value) {
743
743
  return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
744
744
  }
745
- function shutdownFlushTimeoutOption(given) {
745
+ function timerMsOption(given, name, fallback) {
746
746
  if (isTimerMs(given)) return given;
747
- if (given !== void 0) {
748
- warn(`baton: shutdownFlushTimeoutMs must be from 0 to ${MAX_TIMER_MS} ms; using ${SHUTDOWN_FLUSH_TIMEOUT_MS}.`);
749
- }
750
- return SHUTDOWN_FLUSH_TIMEOUT_MS;
747
+ if (given !== void 0) warn(`baton: ${name} must be from 0 to ${MAX_TIMER_MS} ms; using ${fallback}.`);
748
+ return fallback;
751
749
  }
752
750
  function shutdownBudgetMs(sink) {
753
751
  try {
@@ -844,6 +842,31 @@ var MultiSink = class {
844
842
  throw new AggregateError(errors, "MultiSink fan-out failures");
845
843
  }
846
844
  };
845
+ var BATCH_OPEN = '{"events":[';
846
+ var BATCH_CLOSE = "]}";
847
+ var BATCH_FRAME_BYTES = (BATCH_OPEN + BATCH_CLOSE).length;
848
+ var BATCH_MAX_EVENTS = 100;
849
+ var BATCH_MAX_BYTES = 1048576;
850
+ var FLUSH_INTERVAL_MS = 5e3;
851
+ var RETRY_AFTER_MIN_S = 1;
852
+ var RETRY_AFTER_MAX_S = 60;
853
+ var utf8 = new TextEncoder();
854
+ function utf8Bytes(text) {
855
+ return typeof Buffer === "undefined" ? utf8.encode(text).length : Buffer.byteLength(text, "utf8");
856
+ }
857
+ function sum(values) {
858
+ let total = 0;
859
+ for (const value of values) total += value;
860
+ return total;
861
+ }
862
+ function retryAfterMs(header) {
863
+ const value = header?.trim() ?? "";
864
+ if (!/^\d+$/.test(value)) return null;
865
+ return Math.min(Math.max(Number(value), RETRY_AFTER_MIN_S), RETRY_AFTER_MAX_S) * 1e3;
866
+ }
867
+ function sameBatch(a, b) {
868
+ return a.tenant_id === b.tenant_id && a.vendor_id === b.vendor_id;
869
+ }
847
870
  var CircuitBreaker = class {
848
871
  constructor(threshold, resetMs) {
849
872
  this.threshold = threshold;
@@ -854,8 +877,11 @@ var CircuitBreaker = class {
854
877
  failures = 0;
855
878
  openedAt = null;
856
879
  canRequest() {
857
- if (this.openedAt === null) return true;
858
- return Date.now() - this.openedAt >= this.resetMs;
880
+ return this.msUntilRequest() === 0;
881
+ }
882
+ msUntilRequest() {
883
+ if (this.openedAt === null) return 0;
884
+ return Math.max(this.openedAt + this.resetMs - Date.now(), 0);
859
885
  }
860
886
  recordSuccess() {
861
887
  this.failures = 0;
@@ -871,12 +897,17 @@ var CircuitBreaker = class {
871
897
  var HttpSink = class _HttpSink {
872
898
  url;
873
899
  apiKey;
900
+ /** Waiting events only: a batch being sent is out of it, so the bound
901
+ * never pushes out an event in flight (SPEC §11.2 rule 4). */
874
902
  buffer = [];
903
+ bufferedBytes = 0;
904
+ sendingEvents = 0;
875
905
  bufferSize;
876
906
  requestTimeoutMs;
877
907
  shutdownFlushTimeoutMs;
878
- /** Set when an exit pass ends; cleared once a normal drain empties the
879
- * buffer, which means the process went on. */
908
+ flushIntervalMs;
909
+ /** Set when an exit pass ends; cleared once a normal drain sends
910
+ * everything, which means the process went on. */
880
911
  exitPassRan = false;
881
912
  /** Whether the exit pass warned about every event now buffered. */
882
913
  unsentWarned = false;
@@ -886,7 +917,8 @@ var HttpSink = class _HttpSink {
886
917
  circuit;
887
918
  fetchImpl;
888
919
  overflowWarned = false;
889
- /** Per status, so a new kind of refusal, such as a 401 after a 422, still warns. */
920
+ /** Per status or refusal code, so a new kind of refusal, such as a 401
921
+ * after a 422, still warns. */
890
922
  refusals = /* @__PURE__ */ new Map();
891
923
  /** Aborted once `aclose()` returns: nothing Baton started may keep the
892
924
  * process alive after the vendor closed it. */
@@ -896,6 +928,16 @@ var HttpSink = class _HttpSink {
896
928
  skipWarnedFor = null;
897
929
  closeOnce;
898
930
  drainChain = Promise.resolve();
931
+ queuedDrain = null;
932
+ /** Whether the queued pass sends everything waiting, not only what is due. */
933
+ forceNext = false;
934
+ flushTimer = null;
935
+ /** Set by a failed batch: only the timer, a flush or a close tries again. */
936
+ waitForTimer = false;
937
+ /** Nothing is sent before this `Date.now()`, from a 429's `Retry-After`. */
938
+ retryAt = 0;
939
+ /** Set for the life of the sink by a 404 or 405 on the batch path. */
940
+ batchless = false;
899
941
  exitHooks = null;
900
942
  /** The least time between two of this sink's loss reports. */
901
943
  static reportIntervalMs = 6e4;
@@ -903,13 +945,20 @@ var HttpSink = class _HttpSink {
903
945
  reportedSum = 0;
904
946
  lastReportAt = -Infinity;
905
947
  reportsStopped = false;
906
- reportInFlight = null;
948
+ /** The envelope of a report due to ride the next batch, and when it was set up. */
949
+ pendingReport = null;
950
+ reportSetAt = 0;
907
951
  constructor(url, options) {
908
952
  this.url = url.replace(/\/+$/, "");
909
953
  this.apiKey = options.apiKey;
910
954
  this.bufferSize = options.bufferSize ?? 1e3;
911
955
  this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
912
- this.shutdownFlushTimeoutMs = shutdownFlushTimeoutOption(options.shutdownFlushTimeoutMs);
956
+ this.shutdownFlushTimeoutMs = timerMsOption(
957
+ options.shutdownFlushTimeoutMs,
958
+ "shutdownFlushTimeoutMs",
959
+ SHUTDOWN_FLUSH_TIMEOUT_MS
960
+ );
961
+ this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
913
962
  this.maxRetries = options.maxRetries ?? 3;
914
963
  this.backoffBaseMs = options.backoffBaseMs ?? 100;
915
964
  this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
@@ -939,11 +988,24 @@ var HttpSink = class _HttpSink {
939
988
  get closed() {
940
989
  return this.closing.signal.aborted;
941
990
  }
991
+ get unsent() {
992
+ return this.buffer.length + this.sendingEvents;
993
+ }
994
+ /** Encodes at once, not when the batch is cut, because the byte cap
995
+ * decides when a batch goes. */
942
996
  async write(event) {
943
997
  if (this.closed) throw new SinkClosedError("HttpSink is closed");
944
- this.enqueue(event);
998
+ const json = this.encode(event);
999
+ if (json === null) return;
1000
+ const bytes = utf8Bytes(json);
1001
+ if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {
1002
+ this.refuse(1, { kind: "over 1 MiB", detail: `${bytes} bytes` }, false);
1003
+ return;
1004
+ }
1005
+ this.enqueue({ event, json, bytes, writtenAt: Date.now() });
945
1006
  this.unsentWarned = false;
946
- void this.scheduleDrain();
1007
+ if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
1008
+ else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
947
1009
  this.ensureExitHooksRegistered();
948
1010
  }
949
1011
  flush() {
@@ -965,9 +1027,11 @@ var HttpSink = class _HttpSink {
965
1027
  this.stopReports();
966
1028
  await this.drainWithinBudget("aclose()", ms);
967
1029
  this.closing.abort();
968
- if (this.buffer.length > 0) {
969
- PROCESS_DROPS.add("unsent_at_close", this.buffer.length);
970
- warn(`baton: the sink closed with ${this.buffer.length} event(s) unsent.`);
1030
+ this.clearTimer();
1031
+ const unsent = this.unsent;
1032
+ if (unsent > 0) {
1033
+ PROCESS_DROPS.add("unsent_at_close", unsent);
1034
+ warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
971
1035
  }
972
1036
  this.warnUnloggedRefusals("the sink closed");
973
1037
  if (this.exitHooks) {
@@ -989,11 +1053,11 @@ var HttpSink = class _HttpSink {
989
1053
  }
990
1054
  if (this.skipWarnedFor !== this.stalledDrain) {
991
1055
  this.skipWarnedFor = this.stalledDrain;
992
- warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.buffer.length} event(s) wait to be sent.`);
1056
+ warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
993
1057
  }
994
1058
  return;
995
1059
  }
996
- const settled = this.scheduleDrain().catch(() => void 0);
1060
+ const settled = this.scheduleDrain(true).catch(() => void 0);
997
1061
  if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
998
1062
  if (ms < this.shutdownFlushTimeoutMs) return;
999
1063
  const stalled = this.drainChain.catch(() => void 0);
@@ -1005,12 +1069,13 @@ var HttpSink = class _HttpSink {
1005
1069
  warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
1006
1070
  }
1007
1071
  }
1008
- /** A full buffer may already have pushed `event` out while it was being sent. */
1009
- dequeue(event) {
1010
- if (this.buffer[0] === event) this.buffer.shift();
1072
+ enqueue(waiting) {
1073
+ this.buffer.push(waiting);
1074
+ this.bufferedBytes += waiting.bytes;
1075
+ this.dropOverflow();
1011
1076
  }
1012
- enqueue(event) {
1013
- if (this.buffer.length >= this.bufferSize) {
1077
+ dropOverflow() {
1078
+ while (this.buffer.length > this.bufferSize) {
1014
1079
  PROCESS_DROPS.add("buffer_full");
1015
1080
  if (!this.overflowWarned) {
1016
1081
  warn(
@@ -1018,21 +1083,49 @@ var HttpSink = class _HttpSink {
1018
1083
  );
1019
1084
  this.overflowWarned = true;
1020
1085
  }
1021
- this.buffer.shift();
1086
+ this.bufferedBytes -= this.buffer.shift().bytes;
1022
1087
  }
1023
- this.buffer.push(event);
1024
- }
1025
- /** Serializes every call to `drainLocked` — from `write()`'s background
1026
- * drain and from explicit `flush()` alike — onto one promise chain, so
1027
- * concurrent tool calls (the normal case once the MCP interceptor is
1028
- * wired up) can never run two drains at once racing on `buffer[0]`/
1029
- * `shift()`. Mirrors Python's `asyncio.Lock` around `_drain_locked`. */
1030
- scheduleDrain() {
1031
- this.drainChain = this.drainChain.then(
1032
- () => this.drainLocked(),
1033
- () => this.drainLocked()
1088
+ }
1089
+ batchIsFull() {
1090
+ return this.buffer.length >= BATCH_MAX_EVENTS || BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES;
1091
+ }
1092
+ /** The timer must not keep the vendor's process alive: the exit hooks send
1093
+ * what is left. */
1094
+ armTimer(delayMs) {
1095
+ if (this.flushTimer !== null || this.closed) return;
1096
+ const timer = setTimeout(
1097
+ () => {
1098
+ this.flushTimer = null;
1099
+ this.waitForTimer = false;
1100
+ void this.scheduleDrain(false);
1101
+ },
1102
+ Math.min(Math.max(delayMs, 0), MAX_TIMER_MS)
1034
1103
  );
1035
- return this.drainChain;
1104
+ timer.unref?.();
1105
+ this.flushTimer = timer;
1106
+ }
1107
+ clearTimer() {
1108
+ if (this.flushTimer === null) return;
1109
+ clearTimeout(this.flushTimer);
1110
+ this.flushTimer = null;
1111
+ }
1112
+ /** Runs `drainLocked` after the pass under way, one pass at a time, so two
1113
+ * never send at once or race on the buffer. A pass not yet started is
1114
+ * shared by every caller: one per write would grow without bound while a
1115
+ * slow collector holds a pass. */
1116
+ scheduleDrain(force) {
1117
+ this.forceNext ||= force;
1118
+ if (this.queuedDrain) return this.queuedDrain;
1119
+ const run = () => {
1120
+ this.queuedDrain = null;
1121
+ const forced = this.forceNext;
1122
+ this.forceNext = false;
1123
+ return this.drainLocked(forced);
1124
+ };
1125
+ this.queuedDrain = this.drainChain.then(run, run);
1126
+ this.queuedDrain.catch(() => void 0);
1127
+ this.drainChain = this.queuedDrain;
1128
+ return this.queuedDrain;
1036
1129
  }
1037
1130
  /** Best-effort flush when the process is about to exit without an
1038
1131
  * explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
@@ -1041,18 +1134,18 @@ var HttpSink = class _HttpSink {
1041
1134
  ensureExitHooksRegistered() {
1042
1135
  if (this.exitHooks) return;
1043
1136
  const beforeExit = () => {
1044
- if (this.buffer.length === 0 || this.exitPassRan) {
1137
+ if (this.unsent === 0 || this.exitPassRan) {
1045
1138
  this.warnUnloggedRefusals("process exiting");
1046
1139
  return;
1047
1140
  }
1048
1141
  this.drainChain = this.drainChain.then(
1049
1142
  () => this.exitPass(),
1050
1143
  () => this.exitPass()
1051
- );
1144
+ ).catch(() => void 0);
1052
1145
  };
1053
1146
  const exit = () => {
1054
1147
  try {
1055
- if (this.buffer.length > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1148
+ if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
1056
1149
  this.warnUnloggedRefusals("process exiting", stderrLine);
1057
1150
  } catch {
1058
1151
  }
@@ -1061,35 +1154,22 @@ var HttpSink = class _HttpSink {
1061
1154
  process.on("beforeExit", beforeExit);
1062
1155
  process.on("exit", exit);
1063
1156
  }
1064
- /** One attempt per event, no retry, within `shutdownFlushTimeoutMs` in
1157
+ /** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
1065
1158
  * total (SPEC §11.2); what is left is reported, not sent. */
1066
1159
  async exitPass() {
1067
1160
  const deadline = Date.now() + this.shutdownFlushTimeoutMs;
1068
- while (this.buffer.length > 0 && this.circuit.canRequest()) {
1069
- const timeLeft = deadline - Date.now();
1070
- if (timeLeft <= 0) break;
1071
- const event = this.buffer[0];
1072
- const body = this.encode(event);
1073
- if (body !== null) {
1074
- const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
1075
- if (outcome === "transient_failure") {
1076
- this.circuit.recordFailure();
1077
- break;
1078
- }
1079
- this.circuit.recordSuccess();
1080
- }
1081
- this.dequeue(event);
1161
+ while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
1162
+ const batch = this.takeBatch(false);
1163
+ if (batch === null) break;
1164
+ if (!this.putBack(await this.sendBatch(batch, 0, deadline))) break;
1082
1165
  }
1083
1166
  this.exitPassRan = true;
1084
1167
  this.unsentWarned = true;
1085
- if (this.buffer.length > 0) warn(this.unsentAtExit());
1168
+ if (this.unsent > 0) warn(this.unsentAtExit());
1086
1169
  this.warnUnloggedRefusals("process exiting");
1087
1170
  }
1088
1171
  unsentAtExit() {
1089
- return `baton: process exiting with ${this.buffer.length} unsent event(s).`;
1090
- }
1091
- events_url() {
1092
- return `${this.url}/v0/events`;
1172
+ return `baton: process exiting with ${this.unsent} unsent event(s).`;
1093
1173
  }
1094
1174
  authHeaders() {
1095
1175
  return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
@@ -1099,17 +1179,19 @@ var HttpSink = class _HttpSink {
1099
1179
  if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
1100
1180
  return "transient_failure";
1101
1181
  }
1102
- /** A refused event is otherwise dropped silently, which looks the same from
1103
- * the vendor's process as an accepted one. The collector's own message is
1104
- * logged because it names the field at fault; it is capped and escaped
1182
+ /** Counts `n` refused events and logs them, at most once a minute per
1183
+ * kind. A refused event is otherwise dropped silently, which looks the same
1184
+ * from the vendor's process as an accepted one. The collector's own message
1185
+ * is logged because it names the field at fault; it is capped and escaped
1105
1186
  * because it is a remote server's text landing in the vendor's log. */
1106
- static async logRefusal(response, unlogged) {
1107
- const detail = await _HttpSink.readHead(response).then(
1108
- (text) => escapeForLog(capCodePoints(text, REFUSAL_BODY_MAX_LEN)),
1109
- () => "<unreadable>"
1110
- );
1187
+ refuse(n, { kind, detail }, byCollector = true) {
1188
+ if (n === 0) return;
1189
+ PROCESS_DROPS.add("refused", n);
1190
+ const unlogged = this.refusalToLog(kind, n);
1191
+ if (unlogged === null) return;
1192
+ const what = n === 1 ? "an event and it has" : `${n} events and they have`;
1111
1193
  warn(
1112
- `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.` : "")
1194
+ `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.` : "")
1113
1195
  );
1114
1196
  }
1115
1197
  warnUnloggedRefusals(when, emit2 = warn) {
@@ -1120,16 +1202,16 @@ var HttpSink = class _HttpSink {
1120
1202
  }
1121
1203
  if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
1122
1204
  }
1123
- /** How many refusals with `status` went unlogged before this one, or `null`
1124
- * when this one goes unlogged too. */
1125
- refusalToLog(status) {
1205
+ /** How many refusals of `kind` went unlogged before these `n`, or `null`
1206
+ * when these go unlogged too. */
1207
+ refusalToLog(kind, n) {
1126
1208
  const now = performance.now();
1127
- const seen = this.refusals.get(status);
1209
+ const seen = this.refusals.get(kind);
1128
1210
  if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
1129
- seen.unlogged++;
1211
+ seen.unlogged += n;
1130
1212
  return null;
1131
1213
  }
1132
- this.refusals.set(status, { loggedAt: now, unlogged: 0 });
1214
+ this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
1133
1215
  return seen?.unlogged ?? 0;
1134
1216
  }
1135
1217
  /** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
@@ -1151,87 +1233,205 @@ var HttpSink = class _HttpSink {
1151
1233
  });
1152
1234
  }
1153
1235
  }
1154
- async drainLocked() {
1155
- while (this.buffer.length > 0) {
1156
- if (!this.circuit.canRequest() || this.closing.signal.aborted) return;
1157
- const event = this.buffer[0];
1158
- const outcome = await this.sendWithRetry(event);
1159
- if (outcome === "success" || outcome === "permanent_failure") {
1160
- this.dequeue(event);
1161
- this.circuit.recordSuccess();
1162
- if (outcome === "success") {
1163
- PROCESS_DROPS.logRecovery();
1164
- this.maybeReport(event);
1165
- }
1166
- } else if (outcome === "unencodable") {
1167
- this.dequeue(event);
1168
- } else {
1169
- this.circuit.recordFailure();
1170
- return;
1236
+ /** Sends what is due, one batch at a time; `force` (a flush or close) sends
1237
+ * everything waiting. A report set up before the pass rides along; one set
1238
+ * up by this pass's own delivery waits for the next batch. */
1239
+ async drainLocked(force) {
1240
+ let failed = false;
1241
+ let reportDue = this.pendingReport !== null;
1242
+ while (!this.closed) {
1243
+ if (!this.isDue(force, reportDue)) break;
1244
+ if (!this.circuit.canRequest() || Date.now() < this.retryAt) {
1245
+ failed = true;
1246
+ break;
1171
1247
  }
1248
+ const batch = this.takeBatch(reportDue);
1249
+ if (batch === null) break;
1250
+ if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
1251
+ if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity))) {
1252
+ failed = true;
1253
+ break;
1254
+ }
1255
+ }
1256
+ if (!failed && this.unsent === 0) this.exitPassRan = false;
1257
+ this.waitForTimer = failed;
1258
+ this.clearTimer();
1259
+ if (failed) {
1260
+ const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
1261
+ if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
1262
+ return;
1263
+ }
1264
+ const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
1265
+ if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());
1266
+ }
1267
+ /** A due report makes the next batch due only when it can ride it; the
1268
+ * timer is armed the same way, so a pass that sends nothing never re-arms
1269
+ * it at a time already past. */
1270
+ isDue(force, reportDue) {
1271
+ const now = Date.now();
1272
+ if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;
1273
+ return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0].writtenAt + this.flushIntervalMs <= now);
1274
+ }
1275
+ /** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */
1276
+ reportRidesHead() {
1277
+ const head = this.buffer[0];
1278
+ return this.pendingReport !== null && (head === void 0 || sameBatch(this.pendingReport, head.event));
1279
+ }
1280
+ /** Takes the head of the buffer that fits one batch: one tenant and vendor
1281
+ * (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
1282
+ * event's tenant and vendor takes one of those places; otherwise it is not
1283
+ * built, and waits for a batch it can ride. Without a batch endpoint the same events go one
1284
+ * per request. */
1285
+ takeBatch(withReport) {
1286
+ const batch = [];
1287
+ let bytes = BATCH_FRAME_BYTES - 1;
1288
+ let eventBytes = 0;
1289
+ 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;
1290
+ const report = withReport && this.reportRidesHead() ? this.buildReport() : null;
1291
+ const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
1292
+ const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
1293
+ for (const waiting of this.buffer) {
1294
+ if (!fits(waiting, maxEvents, maxBytes)) break;
1295
+ batch.push(waiting);
1296
+ bytes += 1 + waiting.bytes;
1297
+ eventBytes += waiting.bytes;
1172
1298
  }
1173
- this.exitPassRan = false;
1299
+ this.buffer.splice(0, batch.length);
1300
+ this.bufferedBytes -= eventBytes;
1301
+ this.sendingEvents = batch.length;
1302
+ if (report !== null && fits(report)) {
1303
+ report.alone = batch.length === 0;
1304
+ batch.push(report);
1305
+ }
1306
+ return batch.length > 0 ? batch : null;
1307
+ }
1308
+ /** Puts a kept batch's events back at the head of the buffer; `true` when
1309
+ * there were none. */
1310
+ putBack(kept) {
1311
+ this.sendingEvents = 0;
1312
+ if (this.closed) return kept.length === 0;
1313
+ const events = [];
1314
+ for (const waiting of kept) {
1315
+ if (waiting.reportSum !== void 0) {
1316
+ if (waiting.alone || this.batchless) this.pendingReport = null;
1317
+ continue;
1318
+ }
1319
+ events.push(waiting);
1320
+ this.bufferedBytes += waiting.bytes;
1321
+ }
1322
+ this.buffer.unshift(...events);
1323
+ this.dropOverflow();
1324
+ return kept.length === 0;
1174
1325
  }
1175
- /** Starts a report of this process's loss totals (SPEC §11.4.7) beside the
1176
- * drain and outside the buffer, so it never delays an event and is never
1177
- * counted as one. */
1326
+ /** After a delivery, sets up a report of this process's loss totals (SPEC
1327
+ * §11.4.7) to ride the next batch. It stays outside the buffer, so it never
1328
+ * pushes an event out and is never counted as one. */
1178
1329
  maybeReport({ tenant_id, vendor_id, consent_token }) {
1179
1330
  const now = performance.now();
1180
- if (this.reportsStopped || this.reportInFlight !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1331
+ if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
1181
1332
  return;
1182
1333
  }
1183
- const totals = PROCESS_DROPS.total();
1184
- const sum = Object.values(totals).reduce((a, b) => a + b, 0);
1185
- if (sum === this.reportedSum) return;
1334
+ if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;
1186
1335
  this.lastReportAt = now;
1187
- const abort = new AbortController();
1188
- this.reportInFlight = abort;
1189
- const envelope = { tenant_id, vendor_id, consent_token };
1190
- void this.sendReport(envelope, totals, sum, abort).finally(() => {
1191
- this.reportInFlight = null;
1192
- });
1336
+ this.reportSetAt = Date.now();
1337
+ this.pendingReport = { tenant_id, vendor_id, consent_token };
1193
1338
  }
1194
1339
  stopReports() {
1195
1340
  this.reportsStopped = true;
1196
- this.reportInFlight?.abort();
1341
+ this.pendingReport = null;
1197
1342
  }
1198
- async sendReport(envelope, totals, sum, abort) {
1199
- const timer = setTimeout(() => abort.abort(), this.requestTimeoutMs);
1343
+ buildReport() {
1344
+ if (this.pendingReport === null) return null;
1345
+ const totals = PROCESS_DROPS.total();
1200
1346
  try {
1201
1347
  const report = ClientReportEventSchema.parse({
1202
- ...envelope,
1348
+ ...this.pendingReport,
1203
1349
  session_id: PROCESS_DROPS.instanceId,
1204
1350
  sequence_number: nextClockSequence(),
1205
1351
  captured_at: (/* @__PURE__ */ new Date()).toISOString(),
1206
1352
  payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
1207
1353
  });
1208
- const response = await this.fetchImpl(this.events_url(), {
1209
- method: "POST",
1210
- headers: this.authHeaders(),
1211
- body: JSON.stringify(report),
1212
- signal: abort.signal
1213
- });
1214
- void response.body?.cancel().catch(() => void 0);
1215
- if (response.status === 400 || response.status === 422) this.reportsStopped = true;
1216
- else if (_HttpSink.classifyStatus(response.status) === "success") this.reportedSum = sum;
1354
+ const json = JSON.stringify(report);
1355
+ return { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
1217
1356
  } catch {
1218
- } finally {
1219
- clearTimeout(timer);
1357
+ this.pendingReport = null;
1358
+ return null;
1220
1359
  }
1221
1360
  }
1222
- async sendWithRetry(event) {
1223
- const body = this.encode(event);
1224
- if (body === null) return "unencodable";
1225
- for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1226
- const outcome = await this.postOnce(body, this.requestTimeoutMs);
1227
- if (outcome !== "transient_failure") return outcome;
1228
- if (attempt < this.maxRetries) {
1229
- const backoff = Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs);
1230
- await this.sleepUnlessClosed(backoff);
1231
- if (this.closing.signal.aborted) return "transient_failure";
1361
+ /** Sends one batch, splitting it on 413, until every event in it is
1362
+ * delivered or refused. Returns what a failure kept, to go back in the
1363
+ * buffer. */
1364
+ async sendBatch(batch, retries, deadline) {
1365
+ if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);
1366
+ const batchless = this.batchless;
1367
+ const body = batchless ? batch[0].json : BATCH_OPEN + batch.map((w) => w.json).join(",") + BATCH_CLOSE;
1368
+ for (let attempt = 0; ; attempt++) {
1369
+ const timeLeft = deadline - Date.now();
1370
+ if (timeLeft <= 0) return batch;
1371
+ const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));
1372
+ if (answer.kind === "no_batch_endpoint") {
1373
+ this.batchless = true;
1374
+ warn("baton: the collector has no batch endpoint; sending one event per request.");
1375
+ return this.sendEachAlone(batch, retries, deadline);
1376
+ }
1377
+ if (answer.kind === "too_large") {
1378
+ const half = Math.floor(batch.length / 2);
1379
+ const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);
1380
+ if (kept.length > 0) return [...kept, ...batch.slice(half)];
1381
+ return this.sendBatch(batch.slice(half), retries, deadline);
1382
+ }
1383
+ if (answer.kind === "transient") {
1384
+ if (answer.retryAfterMs !== null) {
1385
+ this.retryAt = Date.now() + answer.retryAfterMs;
1386
+ return batch;
1387
+ }
1388
+ if (attempt < retries && !this.closed) {
1389
+ await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));
1390
+ if (!this.closed) continue;
1391
+ }
1392
+ this.circuit.recordFailure();
1393
+ return batch;
1232
1394
  }
1395
+ this.circuit.recordSuccess();
1396
+ this.settle(batch, answer, batchless);
1397
+ return [];
1398
+ }
1399
+ }
1400
+ async sendEachAlone(batch, retries, deadline) {
1401
+ for (const [i, waiting] of batch.entries()) {
1402
+ if (this.closed) return batch.slice(i);
1403
+ const kept = await this.sendBatch([waiting], retries, deadline);
1404
+ if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];
1405
+ }
1406
+ return [];
1407
+ }
1408
+ /** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */
1409
+ settle(batch, answer, alone) {
1410
+ if (this.closed) return;
1411
+ let lastDelivered = null;
1412
+ const refused = /* @__PURE__ */ new Map();
1413
+ for (const waiting of batch) {
1414
+ if (waiting.reportSum === void 0) this.sendingEvents -= 1;
1415
+ const refusal = answer.kind === "refused" ? answer.refusal : answer.refused.get(waiting.event.event_id);
1416
+ if (waiting.reportSum !== void 0) {
1417
+ this.pendingReport = null;
1418
+ if (refusal === void 0) this.reportedSum = waiting.reportSum;
1419
+ else if (answer.kind === "answered" ? refusal.kind === "payload_malformed" : alone && (answer.status === 400 || answer.status === 422)) {
1420
+ this.reportsStopped = true;
1421
+ }
1422
+ } else if (refusal === void 0) {
1423
+ lastDelivered = waiting.event;
1424
+ } else {
1425
+ const seen = refused.get(refusal.kind);
1426
+ if (seen) seen.n += 1;
1427
+ else refused.set(refusal.kind, { first: refusal, n: 1 });
1428
+ }
1429
+ }
1430
+ for (const { first, n } of refused.values()) this.refuse(n, first);
1431
+ if (lastDelivered !== null) {
1432
+ PROCESS_DROPS.logRecovery();
1433
+ this.maybeReport(lastDelivered);
1233
1434
  }
1234
- return "transient_failure";
1235
1435
  }
1236
1436
  /** `null`, with a warning, for an event `JSON.stringify` rejects. */
1237
1437
  encode(event) {
@@ -1259,37 +1459,73 @@ var HttpSink = class _HttpSink {
1259
1459
  }
1260
1460
  /** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
1261
1461
  * is missing before Node 20.3, and on some later versions it keeps every
1262
- * combined signal alive as long as the long-lived `closing` signal. */
1263
- async postOnce(body, timeoutMs) {
1462
+ * combined signal alive as long as the long-lived `closing` signal. Any body
1463
+ * read is under the same signal, so a stalled body cannot hold the drain. */
1464
+ async post(body, size, batchless, timeoutMs) {
1465
+ if (this.closed) return { kind: "transient", retryAfterMs: null };
1264
1466
  const request = new AbortController();
1265
1467
  const abort = () => request.abort();
1266
1468
  const timer = setTimeout(abort, timeoutMs);
1267
1469
  this.closing.signal.addEventListener("abort", abort);
1268
1470
  try {
1269
- const response = await this.fetchImpl(this.events_url(), {
1471
+ const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
1270
1472
  method: "POST",
1271
1473
  headers: this.authHeaders(),
1272
1474
  body,
1273
- signal: request.signal
1475
+ signal: request.signal,
1476
+ // SPEC §2.5: a redirect is a failure, not followed.
1477
+ redirect: "manual"
1274
1478
  });
1275
- const outcome = _HttpSink.classifyStatus(response.status);
1276
- if (outcome === "permanent_failure") {
1277
- PROCESS_DROPS.add("refused");
1278
- const unlogged = this.refusalToLog(response.status);
1279
- if (unlogged !== null) {
1280
- await _HttpSink.logRefusal(response, unlogged);
1281
- return outcome;
1479
+ const { status } = response;
1480
+ const outcome = _HttpSink.classifyStatus(status);
1481
+ if (outcome === "success") {
1482
+ if (batchless) {
1483
+ void response.body?.cancel().catch(() => void 0);
1484
+ return { kind: "answered", refused: /* @__PURE__ */ new Map() };
1282
1485
  }
1486
+ return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
1283
1487
  }
1284
- void response.body?.cancel().catch(() => void 0);
1285
- return outcome;
1488
+ const other = _HttpSink.otherAnswer(response, size, batchless);
1489
+ if (other !== null) {
1490
+ void response.body?.cancel().catch(() => void 0);
1491
+ return other;
1492
+ }
1493
+ const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
1494
+ return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
1286
1495
  } catch {
1287
- return "transient_failure";
1496
+ return { kind: "transient", retryAfterMs: null };
1288
1497
  } finally {
1289
1498
  clearTimeout(timer);
1290
1499
  this.closing.signal.removeEventListener("abort", abort);
1291
1500
  }
1292
1501
  }
1502
+ /** Every answer but a 2xx and a refusal of the whole batch. */
1503
+ static otherAnswer(response, size, batchless) {
1504
+ const { status } = response;
1505
+ if (status === 413 && size > 1) return { kind: "too_large" };
1506
+ if ((status === 404 || status === 405) && !batchless) return { kind: "no_batch_endpoint" };
1507
+ if (status === 429) return { kind: "transient", retryAfterMs: retryAfterMs(response.headers.get("Retry-After")) };
1508
+ if (_HttpSink.classifyStatus(status) === "transient_failure") return { kind: "transient", retryAfterMs: null };
1509
+ return null;
1510
+ }
1511
+ /** The refused results by `event_id` (SPEC §2.5). An event with no readable
1512
+ * result was delivered. */
1513
+ static refusedIn(text) {
1514
+ const refused = /* @__PURE__ */ new Map();
1515
+ let results;
1516
+ try {
1517
+ results = JSON.parse(text)?.results;
1518
+ } catch {
1519
+ return refused;
1520
+ }
1521
+ if (!Array.isArray(results)) return refused;
1522
+ const str = (value) => typeof value === "string" ? value : "";
1523
+ for (const result of results) {
1524
+ if (result?.status !== "refused" || typeof result.event_id !== "string") continue;
1525
+ refused.set(result.event_id, { kind: str(result.error?.code) || "no code", detail: str(result.error?.message) });
1526
+ }
1527
+ return refused;
1528
+ }
1293
1529
  };
1294
1530
 
1295
1531
  // src/integrations/mcp/withBaton.ts
@@ -2270,7 +2506,7 @@ function resolveBatonConfig(config) {
2270
2506
  validateBatonConfig(identity);
2271
2507
  return {
2272
2508
  ...identity,
2273
- // The origin is scheme + authority; `HttpSink` appends `/v0/events`
2509
+ // The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
2274
2510
  // itself, exactly as it does for an explicitly-constructed sink.
2275
2511
  sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
2276
2512
  };