@goodtiming/baton-sdk 0.6.3 → 0.6.5
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/README.md +5 -4
- package/dist/index.cjs +474 -195
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +99 -35
- package/dist/index.d.ts +99 -35
- package/dist/index.js +474 -195
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
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.
|
|
106
|
+
var SDK_VERSION = "ts-0.6.5";
|
|
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((
|
|
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
|
|
745
|
+
function timerMsOption(given, name, fallback) {
|
|
746
746
|
if (isTimerMs(given)) return given;
|
|
747
|
-
if (given !== void 0) {
|
|
748
|
-
|
|
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
|
-
|
|
858
|
-
|
|
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
|
-
|
|
879
|
-
|
|
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
|
|
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,21 @@ var HttpSink = class _HttpSink {
|
|
|
903
945
|
reportedSum = 0;
|
|
904
946
|
lastReportAt = -Infinity;
|
|
905
947
|
reportsStopped = false;
|
|
906
|
-
|
|
948
|
+
/** The envelope of a report due to ride the next batch, and when it was set up.
|
|
949
|
+
* `built` is the report once taken: a kept batch resends it unchanged (SPEC §11.4.7). */
|
|
950
|
+
pendingReport = null;
|
|
951
|
+
reportSetAt = 0;
|
|
907
952
|
constructor(url, options) {
|
|
908
953
|
this.url = url.replace(/\/+$/, "");
|
|
909
954
|
this.apiKey = options.apiKey;
|
|
910
955
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
911
956
|
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
912
|
-
this.shutdownFlushTimeoutMs =
|
|
957
|
+
this.shutdownFlushTimeoutMs = timerMsOption(
|
|
958
|
+
options.shutdownFlushTimeoutMs,
|
|
959
|
+
"shutdownFlushTimeoutMs",
|
|
960
|
+
SHUTDOWN_FLUSH_TIMEOUT_MS
|
|
961
|
+
);
|
|
962
|
+
this.flushIntervalMs = timerMsOption(options.flushIntervalMs, "flushIntervalMs", FLUSH_INTERVAL_MS);
|
|
913
963
|
this.maxRetries = options.maxRetries ?? 3;
|
|
914
964
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
915
965
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -939,11 +989,24 @@ var HttpSink = class _HttpSink {
|
|
|
939
989
|
get closed() {
|
|
940
990
|
return this.closing.signal.aborted;
|
|
941
991
|
}
|
|
992
|
+
get unsent() {
|
|
993
|
+
return this.buffer.length + this.sendingEvents;
|
|
994
|
+
}
|
|
995
|
+
/** Encodes at once, not when the batch is cut, because the byte cap
|
|
996
|
+
* decides when a batch goes. */
|
|
942
997
|
async write(event) {
|
|
943
998
|
if (this.closed) throw new SinkClosedError("HttpSink is closed");
|
|
944
|
-
this.
|
|
999
|
+
const json = this.encode(event);
|
|
1000
|
+
if (json === null) return;
|
|
1001
|
+
const bytes = utf8Bytes(json);
|
|
1002
|
+
if (BATCH_FRAME_BYTES + bytes > BATCH_MAX_BYTES) {
|
|
1003
|
+
this.refuse(1, { kind: "over 1 MiB", detail: `${bytes} bytes` }, false);
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
this.enqueue({ event, json, bytes, writtenAt: Date.now() });
|
|
945
1007
|
this.unsentWarned = false;
|
|
946
|
-
void this.scheduleDrain();
|
|
1008
|
+
if (this.batchIsFull() && !this.waitForTimer) void this.scheduleDrain(false);
|
|
1009
|
+
else this.armTimer(this.buffer[0].writtenAt + this.flushIntervalMs - Date.now());
|
|
947
1010
|
this.ensureExitHooksRegistered();
|
|
948
1011
|
}
|
|
949
1012
|
flush() {
|
|
@@ -965,9 +1028,11 @@ var HttpSink = class _HttpSink {
|
|
|
965
1028
|
this.stopReports();
|
|
966
1029
|
await this.drainWithinBudget("aclose()", ms);
|
|
967
1030
|
this.closing.abort();
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
1031
|
+
this.clearTimer();
|
|
1032
|
+
const unsent = this.unsent;
|
|
1033
|
+
if (unsent > 0) {
|
|
1034
|
+
PROCESS_DROPS.add("unsent_at_close", unsent);
|
|
1035
|
+
warn(`baton: the sink closed with ${unsent} event(s) unsent.`);
|
|
971
1036
|
}
|
|
972
1037
|
this.warnUnloggedRefusals("the sink closed");
|
|
973
1038
|
if (this.exitHooks) {
|
|
@@ -989,11 +1054,11 @@ var HttpSink = class _HttpSink {
|
|
|
989
1054
|
}
|
|
990
1055
|
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
991
1056
|
this.skipWarnedFor = this.stalledDrain;
|
|
992
|
-
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.
|
|
1057
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
|
|
993
1058
|
}
|
|
994
1059
|
return;
|
|
995
1060
|
}
|
|
996
|
-
const settled = this.scheduleDrain().catch(() => void 0);
|
|
1061
|
+
const settled = this.scheduleDrain(true).catch(() => void 0);
|
|
997
1062
|
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
998
1063
|
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
999
1064
|
const stalled = this.drainChain.catch(() => void 0);
|
|
@@ -1005,12 +1070,13 @@ var HttpSink = class _HttpSink {
|
|
|
1005
1070
|
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
1006
1071
|
}
|
|
1007
1072
|
}
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1073
|
+
enqueue(waiting) {
|
|
1074
|
+
this.buffer.push(waiting);
|
|
1075
|
+
this.bufferedBytes += waiting.bytes;
|
|
1076
|
+
this.dropOverflow();
|
|
1011
1077
|
}
|
|
1012
|
-
|
|
1013
|
-
|
|
1078
|
+
dropOverflow() {
|
|
1079
|
+
while (this.buffer.length > this.bufferSize) {
|
|
1014
1080
|
PROCESS_DROPS.add("buffer_full");
|
|
1015
1081
|
if (!this.overflowWarned) {
|
|
1016
1082
|
warn(
|
|
@@ -1018,21 +1084,49 @@ var HttpSink = class _HttpSink {
|
|
|
1018
1084
|
);
|
|
1019
1085
|
this.overflowWarned = true;
|
|
1020
1086
|
}
|
|
1021
|
-
this.buffer.shift();
|
|
1087
|
+
this.bufferedBytes -= this.buffer.shift().bytes;
|
|
1022
1088
|
}
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
*
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
() =>
|
|
1033
|
-
|
|
1089
|
+
}
|
|
1090
|
+
batchIsFull() {
|
|
1091
|
+
return this.buffer.length >= BATCH_MAX_EVENTS || BATCH_FRAME_BYTES + this.bufferedBytes + this.buffer.length - 1 > BATCH_MAX_BYTES;
|
|
1092
|
+
}
|
|
1093
|
+
/** The timer must not keep the vendor's process alive: the exit hooks send
|
|
1094
|
+
* what is left. */
|
|
1095
|
+
armTimer(delayMs) {
|
|
1096
|
+
if (this.flushTimer !== null || this.closed) return;
|
|
1097
|
+
const timer = setTimeout(
|
|
1098
|
+
() => {
|
|
1099
|
+
this.flushTimer = null;
|
|
1100
|
+
this.waitForTimer = false;
|
|
1101
|
+
void this.scheduleDrain(false);
|
|
1102
|
+
},
|
|
1103
|
+
Math.min(Math.max(delayMs, 0), MAX_TIMER_MS)
|
|
1034
1104
|
);
|
|
1035
|
-
|
|
1105
|
+
timer.unref?.();
|
|
1106
|
+
this.flushTimer = timer;
|
|
1107
|
+
}
|
|
1108
|
+
clearTimer() {
|
|
1109
|
+
if (this.flushTimer === null) return;
|
|
1110
|
+
clearTimeout(this.flushTimer);
|
|
1111
|
+
this.flushTimer = null;
|
|
1112
|
+
}
|
|
1113
|
+
/** Runs `drainLocked` after the pass under way, one pass at a time, so two
|
|
1114
|
+
* never send at once or race on the buffer. A pass not yet started is
|
|
1115
|
+
* shared by every caller: one per write would grow without bound while a
|
|
1116
|
+
* slow collector holds a pass. */
|
|
1117
|
+
scheduleDrain(force) {
|
|
1118
|
+
this.forceNext ||= force;
|
|
1119
|
+
if (this.queuedDrain) return this.queuedDrain;
|
|
1120
|
+
const run = () => {
|
|
1121
|
+
this.queuedDrain = null;
|
|
1122
|
+
const forced = this.forceNext;
|
|
1123
|
+
this.forceNext = false;
|
|
1124
|
+
return this.drainLocked(forced);
|
|
1125
|
+
};
|
|
1126
|
+
this.queuedDrain = this.drainChain.then(run, run);
|
|
1127
|
+
this.queuedDrain.catch(() => void 0);
|
|
1128
|
+
this.drainChain = this.queuedDrain;
|
|
1129
|
+
return this.queuedDrain;
|
|
1036
1130
|
}
|
|
1037
1131
|
/** Best-effort flush when the process is about to exit without an
|
|
1038
1132
|
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
@@ -1041,18 +1135,18 @@ var HttpSink = class _HttpSink {
|
|
|
1041
1135
|
ensureExitHooksRegistered() {
|
|
1042
1136
|
if (this.exitHooks) return;
|
|
1043
1137
|
const beforeExit = () => {
|
|
1044
|
-
if (this.
|
|
1138
|
+
if (this.unsent === 0 || this.exitPassRan) {
|
|
1045
1139
|
this.warnUnloggedRefusals("process exiting");
|
|
1046
1140
|
return;
|
|
1047
1141
|
}
|
|
1048
1142
|
this.drainChain = this.drainChain.then(
|
|
1049
1143
|
() => this.exitPass(),
|
|
1050
1144
|
() => this.exitPass()
|
|
1051
|
-
);
|
|
1145
|
+
).catch(() => void 0);
|
|
1052
1146
|
};
|
|
1053
1147
|
const exit = () => {
|
|
1054
1148
|
try {
|
|
1055
|
-
if (this.
|
|
1149
|
+
if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
1056
1150
|
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
1057
1151
|
} catch {
|
|
1058
1152
|
}
|
|
@@ -1061,35 +1155,22 @@ var HttpSink = class _HttpSink {
|
|
|
1061
1155
|
process.on("beforeExit", beforeExit);
|
|
1062
1156
|
process.on("exit", exit);
|
|
1063
1157
|
}
|
|
1064
|
-
/** One attempt per
|
|
1158
|
+
/** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
|
|
1065
1159
|
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
1066
1160
|
async exitPass() {
|
|
1067
1161
|
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
1068
|
-
while (this.
|
|
1069
|
-
const
|
|
1070
|
-
if (
|
|
1071
|
-
|
|
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);
|
|
1162
|
+
while (this.circuit.canRequest() && Date.now() >= this.retryAt && Date.now() < deadline) {
|
|
1163
|
+
const batch = this.takeBatch(false);
|
|
1164
|
+
if (batch === null) break;
|
|
1165
|
+
if (!this.putBack(await this.sendBatch(batch, 0, deadline), batch)) break;
|
|
1082
1166
|
}
|
|
1083
1167
|
this.exitPassRan = true;
|
|
1084
1168
|
this.unsentWarned = true;
|
|
1085
|
-
if (this.
|
|
1169
|
+
if (this.unsent > 0) warn(this.unsentAtExit());
|
|
1086
1170
|
this.warnUnloggedRefusals("process exiting");
|
|
1087
1171
|
}
|
|
1088
1172
|
unsentAtExit() {
|
|
1089
|
-
return `baton: process exiting with ${this.
|
|
1090
|
-
}
|
|
1091
|
-
events_url() {
|
|
1092
|
-
return `${this.url}/v0/events`;
|
|
1173
|
+
return `baton: process exiting with ${this.unsent} unsent event(s).`;
|
|
1093
1174
|
}
|
|
1094
1175
|
authHeaders() {
|
|
1095
1176
|
return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
|
|
@@ -1099,17 +1180,19 @@ var HttpSink = class _HttpSink {
|
|
|
1099
1180
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
1100
1181
|
return "transient_failure";
|
|
1101
1182
|
}
|
|
1102
|
-
/**
|
|
1103
|
-
*
|
|
1104
|
-
*
|
|
1183
|
+
/** Counts `n` refused events and logs them, at most once a minute per
|
|
1184
|
+
* kind. A refused event is otherwise dropped silently, which looks the same
|
|
1185
|
+
* from the vendor's process as an accepted one. The collector's own message
|
|
1186
|
+
* is logged because it names the field at fault; it is capped and escaped
|
|
1105
1187
|
* because it is a remote server's text landing in the vendor's log. */
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
);
|
|
1188
|
+
refuse(n, { kind, detail }, byCollector = true) {
|
|
1189
|
+
if (n === 0) return;
|
|
1190
|
+
PROCESS_DROPS.add("refused", n);
|
|
1191
|
+
const unlogged = this.refusalToLog(kind, n);
|
|
1192
|
+
if (unlogged === null) return;
|
|
1193
|
+
const what = n === 1 ? "an event and it has" : `${n} events and they have`;
|
|
1111
1194
|
warn(
|
|
1112
|
-
`baton: collector REFUSED
|
|
1195
|
+
`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
1196
|
);
|
|
1114
1197
|
}
|
|
1115
1198
|
warnUnloggedRefusals(when, emit2 = warn) {
|
|
@@ -1120,16 +1203,16 @@ var HttpSink = class _HttpSink {
|
|
|
1120
1203
|
}
|
|
1121
1204
|
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1122
1205
|
}
|
|
1123
|
-
/** How many refusals
|
|
1124
|
-
* when
|
|
1125
|
-
refusalToLog(
|
|
1206
|
+
/** How many refusals of `kind` went unlogged before these `n`, or `null`
|
|
1207
|
+
* when these go unlogged too. */
|
|
1208
|
+
refusalToLog(kind, n) {
|
|
1126
1209
|
const now = performance.now();
|
|
1127
|
-
const seen = this.refusals.get(
|
|
1210
|
+
const seen = this.refusals.get(kind);
|
|
1128
1211
|
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1129
|
-
seen.unlogged
|
|
1212
|
+
seen.unlogged += n;
|
|
1130
1213
|
return null;
|
|
1131
1214
|
}
|
|
1132
|
-
this.refusals.set(
|
|
1215
|
+
this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
|
|
1133
1216
|
return seen?.unlogged ?? 0;
|
|
1134
1217
|
}
|
|
1135
1218
|
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
@@ -1151,87 +1234,208 @@ var HttpSink = class _HttpSink {
|
|
|
1151
1234
|
});
|
|
1152
1235
|
}
|
|
1153
1236
|
}
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1237
|
+
/** Sends what is due, one batch at a time; `force` (a flush or close) sends
|
|
1238
|
+
* everything waiting. A report set up before the pass rides along; one set
|
|
1239
|
+
* up by this pass's own delivery waits for the next batch. */
|
|
1240
|
+
async drainLocked(force) {
|
|
1241
|
+
let failed = false;
|
|
1242
|
+
let reportDue = this.pendingReport !== null;
|
|
1243
|
+
while (!this.closed) {
|
|
1244
|
+
if (!this.isDue(force, reportDue)) break;
|
|
1245
|
+
if (!this.circuit.canRequest() || Date.now() < this.retryAt) {
|
|
1246
|
+
failed = true;
|
|
1247
|
+
break;
|
|
1248
|
+
}
|
|
1249
|
+
const batch = this.takeBatch(reportDue);
|
|
1250
|
+
if (batch === null) break;
|
|
1251
|
+
if (batch.some((w) => w.reportSum !== void 0)) reportDue = false;
|
|
1252
|
+
if (!this.putBack(await this.sendBatch(batch, this.maxRetries, Infinity), batch)) {
|
|
1253
|
+
failed = true;
|
|
1254
|
+
break;
|
|
1171
1255
|
}
|
|
1172
1256
|
}
|
|
1173
|
-
this.exitPassRan = false;
|
|
1257
|
+
if (!failed && this.unsent === 0) this.exitPassRan = false;
|
|
1258
|
+
this.waitForTimer = failed;
|
|
1259
|
+
this.clearTimer();
|
|
1260
|
+
if (failed) {
|
|
1261
|
+
const waits = [this.flushIntervalMs, this.backoffBaseMs, this.retryAt - Date.now(), this.circuit.msUntilRequest()];
|
|
1262
|
+
if (this.buffer.length > 0 || this.pendingReport !== null) this.armTimer(Math.max(...waits));
|
|
1263
|
+
return;
|
|
1264
|
+
}
|
|
1265
|
+
const next = Math.min(this.buffer[0]?.writtenAt ?? Infinity, this.reportRidesHead() ? this.reportSetAt : Infinity);
|
|
1266
|
+
if (next !== Infinity) this.armTimer(next + this.flushIntervalMs - Date.now());
|
|
1267
|
+
}
|
|
1268
|
+
/** A due report makes the next batch due only when it can ride it; the
|
|
1269
|
+
* timer is armed the same way, so a pass that sends nothing never re-arms
|
|
1270
|
+
* it at a time already past. */
|
|
1271
|
+
isDue(force, reportDue) {
|
|
1272
|
+
const now = Date.now();
|
|
1273
|
+
if (reportDue && this.reportRidesHead() && (force || this.reportSetAt + this.flushIntervalMs <= now)) return true;
|
|
1274
|
+
return this.buffer.length > 0 && (force || this.batchIsFull() || this.buffer[0].writtenAt + this.flushIntervalMs <= now);
|
|
1275
|
+
}
|
|
1276
|
+
/** A pending report can go in the next batch: alone, or with the head event's tenant and vendor. */
|
|
1277
|
+
reportRidesHead() {
|
|
1278
|
+
const head = this.buffer[0];
|
|
1279
|
+
return this.pendingReport !== null && (head === void 0 || sameBatch(this.pendingReport, head.event));
|
|
1280
|
+
}
|
|
1281
|
+
/** Takes the head of the buffer that fits one batch: one tenant and vendor
|
|
1282
|
+
* (SPEC §2.5), at most 100 events and 1 MiB. A due report with the head
|
|
1283
|
+
* event's tenant and vendor takes one of those places, and goes alone when
|
|
1284
|
+
* the head event fits only without it. A report that cannot ride the head
|
|
1285
|
+
* waits for a batch it can ride. Without a batch endpoint the same events
|
|
1286
|
+
* go one per request. */
|
|
1287
|
+
takeBatch(withReport) {
|
|
1288
|
+
const batch = [];
|
|
1289
|
+
let bytes = BATCH_FRAME_BYTES - 1;
|
|
1290
|
+
let eventBytes = 0;
|
|
1291
|
+
const report = withReport && this.reportRidesHead() ? this.pendingReport.built ?? this.buildReport() : null;
|
|
1292
|
+
const maxEvents = BATCH_MAX_EVENTS - (report ? 1 : 0);
|
|
1293
|
+
const maxBytes = BATCH_MAX_BYTES - (report ? 1 + report.bytes : 0);
|
|
1294
|
+
const fits = (w) => bytes + 1 + w.bytes <= maxBytes && (batch.length === 0 || batch.length < maxEvents && sameBatch(w.event, batch[0].event));
|
|
1295
|
+
for (const waiting of this.buffer) {
|
|
1296
|
+
if (!fits(waiting)) break;
|
|
1297
|
+
batch.push(waiting);
|
|
1298
|
+
bytes += 1 + waiting.bytes;
|
|
1299
|
+
eventBytes += waiting.bytes;
|
|
1300
|
+
}
|
|
1301
|
+
this.buffer.splice(0, batch.length);
|
|
1302
|
+
this.bufferedBytes -= eventBytes;
|
|
1303
|
+
this.sendingEvents = batch.length;
|
|
1304
|
+
if (report !== null) batch.push(report);
|
|
1305
|
+
return batch.length > 0 ? batch : null;
|
|
1306
|
+
}
|
|
1307
|
+
/** Puts what a failure `kept` of the batch `taken` back at the head of the
|
|
1308
|
+
* buffer, and keeps its report unless `taken` had no events; `true` when
|
|
1309
|
+
* nothing was kept. */
|
|
1310
|
+
putBack(kept, taken) {
|
|
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 (taken.every((w) => w.reportSum !== void 0) || 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
|
-
/**
|
|
1176
|
-
*
|
|
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.
|
|
1331
|
+
if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1181
1332
|
return;
|
|
1182
1333
|
}
|
|
1183
|
-
|
|
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
|
-
|
|
1188
|
-
this.
|
|
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.
|
|
1341
|
+
this.pendingReport = null;
|
|
1197
1342
|
}
|
|
1198
|
-
|
|
1199
|
-
|
|
1343
|
+
buildReport() {
|
|
1344
|
+
if (this.pendingReport === null) return null;
|
|
1345
|
+
const { tenant_id, vendor_id, consent_token } = this.pendingReport;
|
|
1346
|
+
const totals = PROCESS_DROPS.total();
|
|
1200
1347
|
try {
|
|
1201
1348
|
const report = ClientReportEventSchema.parse({
|
|
1202
|
-
|
|
1349
|
+
tenant_id,
|
|
1350
|
+
vendor_id,
|
|
1351
|
+
consent_token,
|
|
1203
1352
|
session_id: PROCESS_DROPS.instanceId,
|
|
1204
1353
|
sequence_number: nextClockSequence(),
|
|
1205
1354
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1206
1355
|
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1207
1356
|
});
|
|
1208
|
-
const
|
|
1209
|
-
|
|
1210
|
-
|
|
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;
|
|
1357
|
+
const json = JSON.stringify(report);
|
|
1358
|
+
this.pendingReport.built = { event: report, json, bytes: utf8Bytes(json), writtenAt: Date.now(), reportSum: sum(Object.values(totals)) };
|
|
1359
|
+
return this.pendingReport.built;
|
|
1217
1360
|
} catch {
|
|
1218
|
-
|
|
1219
|
-
|
|
1361
|
+
this.pendingReport = null;
|
|
1362
|
+
return null;
|
|
1220
1363
|
}
|
|
1221
1364
|
}
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1365
|
+
/** Sends one batch, splitting it on 413, until every event in it is
|
|
1366
|
+
* delivered or refused. Returns what a failure kept, to go back in the
|
|
1367
|
+
* buffer. */
|
|
1368
|
+
async sendBatch(batch, retries, deadline) {
|
|
1369
|
+
if (this.batchless && batch.length > 1) return this.sendEachAlone(batch, retries, deadline);
|
|
1370
|
+
const batchless = this.batchless;
|
|
1371
|
+
const body = batchless ? batch[0].json : BATCH_OPEN + batch.map((w) => w.json).join(",") + BATCH_CLOSE;
|
|
1372
|
+
for (let attempt = 0; ; attempt++) {
|
|
1373
|
+
const timeLeft = deadline - Date.now();
|
|
1374
|
+
if (timeLeft <= 0) return batch;
|
|
1375
|
+
const answer = await this.post(body, batch.length, batchless, Math.min(this.requestTimeoutMs, timeLeft));
|
|
1376
|
+
if (answer.kind === "no_batch_endpoint") {
|
|
1377
|
+
this.batchless = true;
|
|
1378
|
+
warn("baton: the collector has no batch endpoint; sending one event per request.");
|
|
1379
|
+
return this.sendEachAlone(batch, retries, deadline);
|
|
1380
|
+
}
|
|
1381
|
+
if (answer.kind === "too_large") {
|
|
1382
|
+
const half = Math.floor(batch.length / 2);
|
|
1383
|
+
const kept = await this.sendBatch(batch.slice(0, half), retries, deadline);
|
|
1384
|
+
if (kept.length > 0) return [...kept, ...batch.slice(half)];
|
|
1385
|
+
return this.sendBatch(batch.slice(half), retries, deadline);
|
|
1232
1386
|
}
|
|
1387
|
+
if (answer.kind === "transient") {
|
|
1388
|
+
if (answer.retryAfterMs !== null) {
|
|
1389
|
+
this.retryAt = Date.now() + answer.retryAfterMs;
|
|
1390
|
+
return batch;
|
|
1391
|
+
}
|
|
1392
|
+
if (attempt < retries && !this.closed) {
|
|
1393
|
+
await this.sleepUnlessClosed(Math.min(this.backoffBaseMs * 2 ** attempt, this.backoffMaxMs));
|
|
1394
|
+
if (!this.closed) continue;
|
|
1395
|
+
}
|
|
1396
|
+
this.circuit.recordFailure();
|
|
1397
|
+
return batch;
|
|
1398
|
+
}
|
|
1399
|
+
this.circuit.recordSuccess();
|
|
1400
|
+
this.settle(batch, answer, batchless);
|
|
1401
|
+
return [];
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
async sendEachAlone(batch, retries, deadline) {
|
|
1405
|
+
for (const [i, waiting] of batch.entries()) {
|
|
1406
|
+
if (this.closed) return batch.slice(i);
|
|
1407
|
+
const kept = await this.sendBatch([waiting], retries, deadline);
|
|
1408
|
+
if (kept.length > 0) return [...kept, ...batch.slice(i + 1)];
|
|
1409
|
+
}
|
|
1410
|
+
return [];
|
|
1411
|
+
}
|
|
1412
|
+
/** `alone` is one event per request (SPEC §2.5), so a whole refusal there is that event's own. */
|
|
1413
|
+
settle(batch, answer, alone) {
|
|
1414
|
+
if (this.closed) return;
|
|
1415
|
+
let lastDelivered = null;
|
|
1416
|
+
const refused = /* @__PURE__ */ new Map();
|
|
1417
|
+
for (const waiting of batch) {
|
|
1418
|
+
if (waiting.reportSum === void 0) this.sendingEvents -= 1;
|
|
1419
|
+
const refusal = answer.kind === "refused" ? answer.refusal : answer.refused.get(waiting.event.event_id);
|
|
1420
|
+
if (waiting.reportSum !== void 0) {
|
|
1421
|
+
this.pendingReport = null;
|
|
1422
|
+
if (refusal === void 0) this.reportedSum = waiting.reportSum;
|
|
1423
|
+
else if (answer.kind === "answered" ? refusal.kind === "payload_malformed" : alone && (answer.status === 400 || answer.status === 422)) {
|
|
1424
|
+
this.reportsStopped = true;
|
|
1425
|
+
}
|
|
1426
|
+
} else if (refusal === void 0) {
|
|
1427
|
+
lastDelivered = waiting.event;
|
|
1428
|
+
} else {
|
|
1429
|
+
const seen = refused.get(refusal.kind);
|
|
1430
|
+
if (seen) seen.n += 1;
|
|
1431
|
+
else refused.set(refusal.kind, { first: refusal, n: 1 });
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
for (const { first, n } of refused.values()) this.refuse(n, first);
|
|
1435
|
+
if (lastDelivered !== null) {
|
|
1436
|
+
PROCESS_DROPS.logRecovery();
|
|
1437
|
+
this.maybeReport(lastDelivered);
|
|
1233
1438
|
}
|
|
1234
|
-
return "transient_failure";
|
|
1235
1439
|
}
|
|
1236
1440
|
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1237
1441
|
encode(event) {
|
|
@@ -1259,37 +1463,73 @@ var HttpSink = class _HttpSink {
|
|
|
1259
1463
|
}
|
|
1260
1464
|
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1261
1465
|
* 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
|
-
|
|
1466
|
+
* combined signal alive as long as the long-lived `closing` signal. Any body
|
|
1467
|
+
* read is under the same signal, so a stalled body cannot hold the drain. */
|
|
1468
|
+
async post(body, size, batchless, timeoutMs) {
|
|
1469
|
+
if (this.closed) return { kind: "transient", retryAfterMs: null };
|
|
1264
1470
|
const request = new AbortController();
|
|
1265
1471
|
const abort = () => request.abort();
|
|
1266
1472
|
const timer = setTimeout(abort, timeoutMs);
|
|
1267
1473
|
this.closing.signal.addEventListener("abort", abort);
|
|
1268
1474
|
try {
|
|
1269
|
-
const response = await this.fetchImpl(this.
|
|
1475
|
+
const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
|
|
1270
1476
|
method: "POST",
|
|
1271
1477
|
headers: this.authHeaders(),
|
|
1272
1478
|
body,
|
|
1273
|
-
signal: request.signal
|
|
1479
|
+
signal: request.signal,
|
|
1480
|
+
// SPEC §2.5: a redirect is a failure, not followed.
|
|
1481
|
+
redirect: "manual"
|
|
1274
1482
|
});
|
|
1275
|
-
const
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
return outcome;
|
|
1483
|
+
const { status } = response;
|
|
1484
|
+
const outcome = _HttpSink.classifyStatus(status);
|
|
1485
|
+
if (outcome === "success") {
|
|
1486
|
+
if (batchless) {
|
|
1487
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1488
|
+
return { kind: "answered", refused: /* @__PURE__ */ new Map() };
|
|
1282
1489
|
}
|
|
1490
|
+
return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
|
|
1283
1491
|
}
|
|
1284
|
-
|
|
1285
|
-
|
|
1492
|
+
const other = _HttpSink.otherAnswer(response, size, batchless);
|
|
1493
|
+
if (other !== null) {
|
|
1494
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1495
|
+
return other;
|
|
1496
|
+
}
|
|
1497
|
+
const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
|
|
1498
|
+
return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
|
|
1286
1499
|
} catch {
|
|
1287
|
-
return "
|
|
1500
|
+
return { kind: "transient", retryAfterMs: null };
|
|
1288
1501
|
} finally {
|
|
1289
1502
|
clearTimeout(timer);
|
|
1290
1503
|
this.closing.signal.removeEventListener("abort", abort);
|
|
1291
1504
|
}
|
|
1292
1505
|
}
|
|
1506
|
+
/** Every answer but a 2xx and a refusal of the whole batch. */
|
|
1507
|
+
static otherAnswer(response, size, batchless) {
|
|
1508
|
+
const { status } = response;
|
|
1509
|
+
if (status === 413 && size > 1) return { kind: "too_large" };
|
|
1510
|
+
if ((status === 404 || status === 405) && !batchless) return { kind: "no_batch_endpoint" };
|
|
1511
|
+
if (status === 429) return { kind: "transient", retryAfterMs: retryAfterMs(response.headers.get("Retry-After")) };
|
|
1512
|
+
if (_HttpSink.classifyStatus(status) === "transient_failure") return { kind: "transient", retryAfterMs: null };
|
|
1513
|
+
return null;
|
|
1514
|
+
}
|
|
1515
|
+
/** The refused results by `event_id` (SPEC §2.5). An event with no readable
|
|
1516
|
+
* result was delivered. */
|
|
1517
|
+
static refusedIn(text) {
|
|
1518
|
+
const refused = /* @__PURE__ */ new Map();
|
|
1519
|
+
let results;
|
|
1520
|
+
try {
|
|
1521
|
+
results = JSON.parse(text)?.results;
|
|
1522
|
+
} catch {
|
|
1523
|
+
return refused;
|
|
1524
|
+
}
|
|
1525
|
+
if (!Array.isArray(results)) return refused;
|
|
1526
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
1527
|
+
for (const result of results) {
|
|
1528
|
+
if (result?.status !== "refused" || typeof result.event_id !== "string") continue;
|
|
1529
|
+
refused.set(result.event_id, { kind: str(result.error?.code) || "no code", detail: str(result.error?.message) });
|
|
1530
|
+
}
|
|
1531
|
+
return refused;
|
|
1532
|
+
}
|
|
1293
1533
|
};
|
|
1294
1534
|
|
|
1295
1535
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -2225,6 +2465,18 @@ function resolveTenantId(explicit, vendorId2) {
|
|
|
2225
2465
|
if (fromEnv2) return fromEnv2;
|
|
2226
2466
|
return vendorId2;
|
|
2227
2467
|
}
|
|
2468
|
+
var STAND_IN_VENDOR_ID = "unset";
|
|
2469
|
+
function resolveInstallConfig(config) {
|
|
2470
|
+
const unconfigured = !config.dsn && dsnFromEnvironment() === void 0 && !config.vendorId && !config.tenantId && config.sink === void 0;
|
|
2471
|
+
const resolved = resolveBatonConfig(
|
|
2472
|
+
unconfigured ? {
|
|
2473
|
+
...config,
|
|
2474
|
+
vendorId: STAND_IN_VENDOR_ID,
|
|
2475
|
+
vendorDisplayName: config.vendorDisplayName ?? STAND_IN_VENDOR_ID
|
|
2476
|
+
} : config
|
|
2477
|
+
);
|
|
2478
|
+
return { resolved, unconfigured };
|
|
2479
|
+
}
|
|
2228
2480
|
function resolveBatonConfig(config) {
|
|
2229
2481
|
const dsnString = selectDsn(
|
|
2230
2482
|
config.dsn,
|
|
@@ -2270,7 +2522,7 @@ function resolveBatonConfig(config) {
|
|
|
2270
2522
|
validateBatonConfig(identity);
|
|
2271
2523
|
return {
|
|
2272
2524
|
...identity,
|
|
2273
|
-
// The origin is scheme + authority; `HttpSink` appends `/v0/events`
|
|
2525
|
+
// The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
|
|
2274
2526
|
// itself, exactly as it does for an explicitly-constructed sink.
|
|
2275
2527
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
|
|
2276
2528
|
};
|
|
@@ -2356,11 +2608,12 @@ function captureDisabled() {
|
|
|
2356
2608
|
return null;
|
|
2357
2609
|
}
|
|
2358
2610
|
function logDisabled(switchName, surface) {
|
|
2359
|
-
|
|
2360
|
-
|
|
2361
|
-
|
|
2362
|
-
|
|
2363
|
-
|
|
2611
|
+
warn(
|
|
2612
|
+
`baton: ${switchName} is set, so capture is OFF \u2014 ${surface} installed nothing and will emit no events. Unset it to re-enable.`
|
|
2613
|
+
);
|
|
2614
|
+
}
|
|
2615
|
+
function logUnconfigured(surface) {
|
|
2616
|
+
warn(`baton: no DSN (dsn or BATON_DSN), so ${surface} installed nothing and records nothing`);
|
|
2364
2617
|
}
|
|
2365
2618
|
var DisabledSink = class {
|
|
2366
2619
|
// The parameter is omitted rather than named-and-ignored: a narrower
|
|
@@ -2439,6 +2692,19 @@ var SessionCounter = class {
|
|
|
2439
2692
|
return next;
|
|
2440
2693
|
}
|
|
2441
2694
|
};
|
|
2695
|
+
var ServerCounter = class extends SessionCounter {
|
|
2696
|
+
constructor(shared, ownSessionId) {
|
|
2697
|
+
super();
|
|
2698
|
+
this.shared = shared;
|
|
2699
|
+
this.ownSessionId = ownSessionId;
|
|
2700
|
+
}
|
|
2701
|
+
shared;
|
|
2702
|
+
ownSessionId;
|
|
2703
|
+
ownSequence = 0;
|
|
2704
|
+
next(sessionId) {
|
|
2705
|
+
return sessionId === this.ownSessionId ? ++this.ownSequence : this.shared.next(sessionId);
|
|
2706
|
+
}
|
|
2707
|
+
};
|
|
2442
2708
|
|
|
2443
2709
|
// src/integrations/mcp/zodCompat.ts
|
|
2444
2710
|
var z3rt = __toESM(require("zod/v3"), 1);
|
|
@@ -2656,6 +2922,7 @@ function buildSeamAugmentations(options) {
|
|
|
2656
2922
|
var BATON_WRAPPED = /* @__PURE__ */ Symbol("batonWrapped");
|
|
2657
2923
|
var wired = /* @__PURE__ */ new WeakSet();
|
|
2658
2924
|
var CLEAN_OUTCOME = { failed: false, raised: false, result: void 0 };
|
|
2925
|
+
var INTENT_PARAM_NAMES = [USER_GOAL_PARAM_NAME, ...RETIRED_PARAM_NAMES];
|
|
2659
2926
|
var callSlots = new import_node_async_hooks.AsyncLocalStorage();
|
|
2660
2927
|
var SurfaceState = class {
|
|
2661
2928
|
constructor(serverMeta, sentSurfaces) {
|
|
@@ -2718,14 +2985,14 @@ async function resolveEnvelopeParts(ctx, extra) {
|
|
|
2718
2985
|
const session = await resolveSessionId(ctx.fallbackSessionId, extra);
|
|
2719
2986
|
return { ...session, scrubbedMeta };
|
|
2720
2987
|
}
|
|
2721
|
-
async function openCall(ctx, toolName, extra, params,
|
|
2988
|
+
async function openCall(ctx, toolName, extra, params, stripped, registered = true) {
|
|
2722
2989
|
await maybeEmitSurfaceSnapshot(ctx);
|
|
2723
2990
|
const { scrubbedMeta, ...session } = await resolveEnvelopeParts(ctx, extra);
|
|
2724
2991
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2725
|
-
const rawIntent = extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2992
|
+
const rawIntent = stripped[USER_GOAL_PARAM_NAME] ?? extractGoalParam(params, USER_GOAL_PARAM_NAME, toolName, dispositions, registered);
|
|
2726
2993
|
const scrubbedIntent = scrubOrNull(ctx.scrubber, rawIntent, USER_GOAL_PARAM_NAME);
|
|
2727
2994
|
const [scrubbedExpected = null, scrubbedWorkflow = null] = RETIRED_PARAM_NAMES.map(
|
|
2728
|
-
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber,
|
|
2995
|
+
(name) => dispositions === void 0 || dispositions[name] === "native" ? null : scrubOrNull(ctx.scrubber, stripped[name] ?? popText(params, name), name)
|
|
2729
2996
|
);
|
|
2730
2997
|
const caller = await resolveCaller(
|
|
2731
2998
|
ctx.resolvePrincipal,
|
|
@@ -2775,9 +3042,9 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2775
3042
|
if (slot) slot.innerFired = true;
|
|
2776
3043
|
const extra = callArgs[callArgs.length - 1];
|
|
2777
3044
|
const params = (callArgs.length > 1 ? callArgs[0] : void 0) ?? {};
|
|
2778
|
-
const
|
|
2779
|
-
if (slot) slot.
|
|
2780
|
-
const { common, session } = await openCall(ctx, toolName, extra, params,
|
|
3045
|
+
const stripped = slot?.strippedFor === toolName ? slot.stripped : {};
|
|
3046
|
+
if (slot) slot.strippedFor = null;
|
|
3047
|
+
const { common, session } = await openCall(ctx, toolName, extra, params, stripped);
|
|
2781
3048
|
const terminate = async (build, replacement) => {
|
|
2782
3049
|
if (!slot) {
|
|
2783
3050
|
if (build !== null) await emit(ctx.sink, build);
|
|
@@ -2953,19 +3220,19 @@ function popText(args, paramName) {
|
|
|
2953
3220
|
delete args[paramName];
|
|
2954
3221
|
return typeof raw === "string" && !isBlank(raw) ? raw : null;
|
|
2955
3222
|
}
|
|
2956
|
-
function
|
|
3223
|
+
function stripIntentParams(params, ctx) {
|
|
2957
3224
|
const toolName = params?.name;
|
|
2958
3225
|
const args = params?.arguments;
|
|
2959
3226
|
if (typeof toolName !== "string") return {};
|
|
2960
3227
|
if (toolName === ctx.annotationToolName) return {};
|
|
2961
3228
|
if (typeof args !== "object" || args === null || Array.isArray(args)) return {};
|
|
2962
3229
|
const dispositions = ctx.paramRegistry.get(toolName);
|
|
2963
|
-
const
|
|
2964
|
-
for (const name of
|
|
3230
|
+
const stripped = {};
|
|
3231
|
+
for (const name of INTENT_PARAM_NAMES) {
|
|
2965
3232
|
if (dispositions === void 0 || dispositions[name] === "native" || !(name in args)) continue;
|
|
2966
|
-
|
|
3233
|
+
stripped[name] = popText(args, name);
|
|
2967
3234
|
}
|
|
2968
|
-
return
|
|
3235
|
+
return stripped;
|
|
2969
3236
|
}
|
|
2970
3237
|
async function maybeEmitSurfaceSnapshot(ctx) {
|
|
2971
3238
|
if (!ctx.surfaceState.dirty) return;
|
|
@@ -3001,7 +3268,7 @@ async function maybeEmitSurfaceSnapshot(ctx) {
|
|
|
3001
3268
|
}
|
|
3002
3269
|
function declaredIntentParams(vendorSchema) {
|
|
3003
3270
|
const declared2 = {};
|
|
3004
|
-
for (const name of
|
|
3271
|
+
for (const name of INTENT_PARAM_NAMES) {
|
|
3005
3272
|
if (declaresParam(vendorSchema, name)) declared2[name] = "native";
|
|
3006
3273
|
}
|
|
3007
3274
|
return declared2;
|
|
@@ -3267,10 +3534,12 @@ function installToolsCallSeam(lowLevel, toolEntry, ctx) {
|
|
|
3267
3534
|
TOOLS_CALL_SEAM,
|
|
3268
3535
|
(handler) => async (...args) => {
|
|
3269
3536
|
const request = args[0];
|
|
3537
|
+
const name = request?.params?.name;
|
|
3270
3538
|
const slot = {
|
|
3271
3539
|
innerFired: false,
|
|
3272
3540
|
flushTerminal: null,
|
|
3273
|
-
|
|
3541
|
+
stripped: stripIntentParams(request?.params, ctx),
|
|
3542
|
+
strippedFor: typeof name === "string" ? name : null,
|
|
3274
3543
|
validation: "unseen"
|
|
3275
3544
|
};
|
|
3276
3545
|
let outcome = CLEAN_OUTCOME;
|
|
@@ -3336,7 +3605,7 @@ async function emitRequestSideFailure(outcome, args, slot, toolEntry, ctx) {
|
|
|
3336
3605
|
toolName,
|
|
3337
3606
|
args[1],
|
|
3338
3607
|
params,
|
|
3339
|
-
slot.
|
|
3608
|
+
slot.stripped,
|
|
3340
3609
|
entry != null
|
|
3341
3610
|
);
|
|
3342
3611
|
const failureKind = requestSideFailureKind(entry, slot.validation);
|
|
@@ -3445,23 +3714,13 @@ function withBaton(server, supplied = {}) {
|
|
|
3445
3714
|
const disabledBy = captureDisabled();
|
|
3446
3715
|
if (disabledBy !== null) {
|
|
3447
3716
|
logDisabled(disabledBy, "withBaton");
|
|
3448
|
-
return new
|
|
3449
|
-
// A sink the VENDOR constructed is held rather than dropped, so their
|
|
3450
|
-
// `handle.aclose()` still releases it — we took ownership of that object
|
|
3451
|
-
// the moment they passed it, and the switch does not undo that. Nothing
|
|
3452
|
-
// writes to it: nothing is wrapped.
|
|
3453
|
-
sink: supplied.sink ?? new DisabledSink(),
|
|
3454
|
-
// Empty, and a constant, because when the switch is on nothing was
|
|
3455
|
-
// resolved: inventing a session id would put a real identifier on a
|
|
3456
|
-
// handle whose whole meaning is that no events exist under it.
|
|
3457
|
-
vendorId: "",
|
|
3458
|
-
sessionId: "baton-disabled",
|
|
3459
|
-
annotationToolName: ""
|
|
3460
|
-
});
|
|
3717
|
+
return inertHandle(supplied.sink ?? new DisabledSink(), "baton-disabled");
|
|
3461
3718
|
}
|
|
3462
|
-
const resolved =
|
|
3463
|
-
warnUnusedReportSettings(resolved);
|
|
3464
|
-
|
|
3719
|
+
const { resolved, unconfigured } = resolveInstallConfig(supplied);
|
|
3720
|
+
if (!unconfigured) warnUnusedReportSettings(resolved);
|
|
3721
|
+
const handle = install(server, supplied, resolved, newBatonState(resolved), unconfigured);
|
|
3722
|
+
if (unconfigured) logUnconfigured("withBaton");
|
|
3723
|
+
return handle;
|
|
3465
3724
|
}
|
|
3466
3725
|
function createBaton(supplied = {}) {
|
|
3467
3726
|
const disabledBy = captureDisabled();
|
|
@@ -3475,40 +3734,61 @@ function createBaton(supplied = {}) {
|
|
|
3475
3734
|
aclose: () => boundedSinkCall(unused, "aclose")
|
|
3476
3735
|
};
|
|
3477
3736
|
}
|
|
3478
|
-
const resolved =
|
|
3479
|
-
warnUnusedReportSettings(resolved);
|
|
3737
|
+
const { resolved, unconfigured } = resolveInstallConfig(supplied);
|
|
3480
3738
|
if (resolved.reportMode === "on") deriveAnnotationToolName(resolved.vendorId, supplied.annotationToolName);
|
|
3481
|
-
|
|
3739
|
+
if (unconfigured) logUnconfigured("createBaton");
|
|
3740
|
+
else warnUnusedReportSettings(resolved);
|
|
3741
|
+
const sink = unconfigured ? new DisabledSink() : resolved.sink ?? new StdoutSink();
|
|
3482
3742
|
const config = {
|
|
3483
3743
|
...resolved,
|
|
3484
3744
|
sink,
|
|
3485
3745
|
tenantId: resolveTenantId(resolved.tenantId, resolved.vendorId)
|
|
3486
3746
|
};
|
|
3487
|
-
const
|
|
3488
|
-
const warned3 = /* @__PURE__ */ new Set();
|
|
3747
|
+
const state = newBatonState(resolved);
|
|
3489
3748
|
return {
|
|
3490
3749
|
wrap: (server) => {
|
|
3491
|
-
install(server, supplied, config,
|
|
3750
|
+
install(server, supplied, config, state, unconfigured);
|
|
3492
3751
|
},
|
|
3493
3752
|
flush: () => boundedSinkCall(sink, "flush"),
|
|
3494
3753
|
aclose: () => boundedSinkCall(sink, "aclose")
|
|
3495
3754
|
};
|
|
3496
3755
|
}
|
|
3497
|
-
function
|
|
3756
|
+
function inertHandle(sink, sessionId) {
|
|
3757
|
+
return new BatonHandle({ sink, sessionId, vendorId: "", annotationToolName: "" });
|
|
3758
|
+
}
|
|
3759
|
+
function requireHighLevelServer(server) {
|
|
3760
|
+
const candidate = server;
|
|
3761
|
+
if (typeof candidate?.registerTool !== "function" || typeof candidate.server !== "object" || candidate.server === null) {
|
|
3762
|
+
throw new TypeError(
|
|
3763
|
+
"Baton needs a high-level McpServer (from @modelcontextprotocol/sdk/server/mcp.js or @modelcontextprotocol/server); the low-level Server is not supported."
|
|
3764
|
+
);
|
|
3765
|
+
}
|
|
3766
|
+
}
|
|
3767
|
+
function newBatonState(config) {
|
|
3768
|
+
return {
|
|
3769
|
+
sentSurfaces: new SentSurfaces(),
|
|
3770
|
+
warned: /* @__PURE__ */ new Set(),
|
|
3771
|
+
counter: new SessionCounter(),
|
|
3772
|
+
scrubber: config.scrubber ?? new Scrubber().scrub
|
|
3773
|
+
};
|
|
3774
|
+
}
|
|
3775
|
+
function install(server, supplied, resolved, { sentSurfaces, warned: warned3, counter: sharedCounter, scrubber }, unconfigured) {
|
|
3776
|
+
requireHighLevelServer(server);
|
|
3498
3777
|
const internals = server;
|
|
3499
3778
|
const serverName = usableServerName(() => ({
|
|
3500
3779
|
name: internals.server._serverInfo?.name,
|
|
3501
3780
|
className: internals.constructor.name
|
|
3502
3781
|
}));
|
|
3503
3782
|
const config = resolved.reportMode === "on" ? withServerDisplayName(resolved, supplied, serverName) : resolved;
|
|
3504
|
-
const sink = config.sink ?? new StdoutSink();
|
|
3505
3783
|
const reports = reportsFor(config);
|
|
3506
3784
|
const annotationToolName = reports ? resolveAnnotationToolName(serverName, { ...config, vendorDisplayName: reports.vendorDisplayName }) : "";
|
|
3785
|
+
const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
|
|
3786
|
+
if (unconfigured) return inertHandle(new DisabledSink(), "baton-unconfigured");
|
|
3787
|
+
const sink = config.sink ?? new StdoutSink();
|
|
3507
3788
|
const intentParamMode = config.intentParamMode ?? DEFAULT_INTENT_PARAM_MODE;
|
|
3508
|
-
const counter2 = new SessionCounter();
|
|
3509
3789
|
const fallbackSessionId = `sdk-${uuid7()}`;
|
|
3790
|
+
const counter2 = new ServerCounter(sharedCounter, fallbackSessionId);
|
|
3510
3791
|
const tenantId = resolveTenantId(config.tenantId, config.vendorId);
|
|
3511
|
-
const scrubber = config.scrubber ?? new Scrubber().scrub;
|
|
3512
3792
|
const serverMeta = buildServerMeta(server.server);
|
|
3513
3793
|
const surfaceState = new SurfaceState(serverMeta, sentSurfaces);
|
|
3514
3794
|
const emitSurface = async (sessionId, digest, snapshot) => {
|
|
@@ -3603,7 +3883,6 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
|
3603
3883
|
surfaceState,
|
|
3604
3884
|
emitSurface
|
|
3605
3885
|
};
|
|
3606
|
-
const ours = reports ? buildServerInstructions({ vendorDisplayName: reports.vendorDisplayName, annotationToolName }) : INTENT_INSTRUCTIONS;
|
|
3607
3886
|
internals.server._instructions = withVendorInstructions(
|
|
3608
3887
|
internals.server,
|
|
3609
3888
|
ours,
|