@goodtiming/baton-sdk 0.6.2 → 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/README.md +1 -1
- package/dist/index.cjs +495 -217
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +99 -34
- package/dist/index.d.ts +99 -34
- package/dist/index.js +494 -217
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// src/version.ts
|
|
2
|
-
var SDK_VERSION = "ts-0.6.
|
|
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((
|
|
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. */
|
|
@@ -608,10 +608,24 @@ function nextClockSequence() {
|
|
|
608
608
|
// src/sinks.ts
|
|
609
609
|
var REFUSAL_BODY_MAX_LEN = 500;
|
|
610
610
|
var REFUSAL_LOG_MS = 6e4;
|
|
611
|
+
var SinkClosedError = class extends Error {
|
|
612
|
+
name = "SinkClosedError";
|
|
613
|
+
};
|
|
614
|
+
function isSinkClosed(err) {
|
|
615
|
+
return err instanceof Error && err.name === "SinkClosedError";
|
|
616
|
+
}
|
|
617
|
+
var warnedClosed = /* @__PURE__ */ new WeakSet();
|
|
618
|
+
function droppedAfterClose(sink) {
|
|
619
|
+
PROCESS_DROPS.add("after_close");
|
|
620
|
+
if (warnedClosed.has(sink)) return;
|
|
621
|
+
warnedClosed.add(sink);
|
|
622
|
+
warn("baton: the sink is closed; further events are dropped.");
|
|
623
|
+
}
|
|
611
624
|
async function safeWrite(sink, event) {
|
|
612
625
|
try {
|
|
613
626
|
await sink.write(event);
|
|
614
627
|
} catch (err) {
|
|
628
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
615
629
|
PROCESS_DROPS.add("write_failed");
|
|
616
630
|
process.stderr.write(`baton: sink.write failed; event dropped, tool call continues: ${printable(err)}
|
|
617
631
|
`);
|
|
@@ -624,12 +638,10 @@ function stderrLine(message) {
|
|
|
624
638
|
function isTimerMs(value) {
|
|
625
639
|
return typeof value === "number" && value >= 0 && value <= MAX_TIMER_MS;
|
|
626
640
|
}
|
|
627
|
-
function
|
|
641
|
+
function timerMsOption(given, name, fallback) {
|
|
628
642
|
if (isTimerMs(given)) return given;
|
|
629
|
-
if (given !== void 0) {
|
|
630
|
-
|
|
631
|
-
}
|
|
632
|
-
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;
|
|
633
645
|
}
|
|
634
646
|
function shutdownBudgetMs(sink) {
|
|
635
647
|
try {
|
|
@@ -664,7 +676,7 @@ var StdoutSink = class {
|
|
|
664
676
|
this.stream = options.stream ?? process.stderr;
|
|
665
677
|
}
|
|
666
678
|
async write(event) {
|
|
667
|
-
if (this.closed) throw new
|
|
679
|
+
if (this.closed) throw new SinkClosedError("StdoutSink is closed");
|
|
668
680
|
this.stream.write(JSON.stringify(event) + "\n");
|
|
669
681
|
}
|
|
670
682
|
async flush() {
|
|
@@ -681,7 +693,7 @@ var FileSink = class {
|
|
|
681
693
|
fd = null;
|
|
682
694
|
closed = false;
|
|
683
695
|
async write(event) {
|
|
684
|
-
if (this.closed) throw new
|
|
696
|
+
if (this.closed) throw new SinkClosedError("FileSink is closed");
|
|
685
697
|
this.fd ??= openSync(this.path, "a");
|
|
686
698
|
writeSync(this.fd, JSON.stringify(event) + "\n");
|
|
687
699
|
}
|
|
@@ -719,11 +731,38 @@ var MultiSink = class {
|
|
|
719
731
|
}
|
|
720
732
|
async fanOut(op) {
|
|
721
733
|
const results = await Promise.allSettled(this.sinks.map(async (sink) => op(sink)));
|
|
722
|
-
|
|
723
|
-
if (errors.length
|
|
724
|
-
if (errors.length
|
|
734
|
+
let errors = results.flatMap((r) => r.status === "rejected" ? [r.reason] : []);
|
|
735
|
+
if (errors.length < results.length) errors = errors.filter((e) => !isSinkClosed(e));
|
|
736
|
+
if (errors.length === 0) return;
|
|
737
|
+
if (errors.length === 1 || errors.every(isSinkClosed)) throw errors[0];
|
|
738
|
+
throw new AggregateError(errors, "MultiSink fan-out failures");
|
|
725
739
|
}
|
|
726
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
|
+
}
|
|
727
766
|
var CircuitBreaker = class {
|
|
728
767
|
constructor(threshold, resetMs) {
|
|
729
768
|
this.threshold = threshold;
|
|
@@ -734,8 +773,11 @@ var CircuitBreaker = class {
|
|
|
734
773
|
failures = 0;
|
|
735
774
|
openedAt = null;
|
|
736
775
|
canRequest() {
|
|
737
|
-
|
|
738
|
-
|
|
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);
|
|
739
781
|
}
|
|
740
782
|
recordSuccess() {
|
|
741
783
|
this.failures = 0;
|
|
@@ -751,12 +793,17 @@ var CircuitBreaker = class {
|
|
|
751
793
|
var HttpSink = class _HttpSink {
|
|
752
794
|
url;
|
|
753
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). */
|
|
754
798
|
buffer = [];
|
|
799
|
+
bufferedBytes = 0;
|
|
800
|
+
sendingEvents = 0;
|
|
755
801
|
bufferSize;
|
|
756
802
|
requestTimeoutMs;
|
|
757
803
|
shutdownFlushTimeoutMs;
|
|
758
|
-
|
|
759
|
-
|
|
804
|
+
flushIntervalMs;
|
|
805
|
+
/** Set when an exit pass ends; cleared once a normal drain sends
|
|
806
|
+
* everything, which means the process went on. */
|
|
760
807
|
exitPassRan = false;
|
|
761
808
|
/** Whether the exit pass warned about every event now buffered. */
|
|
762
809
|
unsentWarned = false;
|
|
@@ -766,7 +813,8 @@ var HttpSink = class _HttpSink {
|
|
|
766
813
|
circuit;
|
|
767
814
|
fetchImpl;
|
|
768
815
|
overflowWarned = false;
|
|
769
|
-
/** Per status, so a new kind of refusal, such as a 401
|
|
816
|
+
/** Per status or refusal code, so a new kind of refusal, such as a 401
|
|
817
|
+
* after a 422, still warns. */
|
|
770
818
|
refusals = /* @__PURE__ */ new Map();
|
|
771
819
|
/** Aborted once `aclose()` returns: nothing Baton started may keep the
|
|
772
820
|
* process alive after the vendor closed it. */
|
|
@@ -776,6 +824,16 @@ var HttpSink = class _HttpSink {
|
|
|
776
824
|
skipWarnedFor = null;
|
|
777
825
|
closeOnce;
|
|
778
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;
|
|
779
837
|
exitHooks = null;
|
|
780
838
|
/** The least time between two of this sink's loss reports. */
|
|
781
839
|
static reportIntervalMs = 6e4;
|
|
@@ -783,13 +841,20 @@ var HttpSink = class _HttpSink {
|
|
|
783
841
|
reportedSum = 0;
|
|
784
842
|
lastReportAt = -Infinity;
|
|
785
843
|
reportsStopped = false;
|
|
786
|
-
|
|
844
|
+
/** The envelope of a report due to ride the next batch, and when it was set up. */
|
|
845
|
+
pendingReport = null;
|
|
846
|
+
reportSetAt = 0;
|
|
787
847
|
constructor(url, options) {
|
|
788
848
|
this.url = url.replace(/\/+$/, "");
|
|
789
849
|
this.apiKey = options.apiKey;
|
|
790
850
|
this.bufferSize = options.bufferSize ?? 1e3;
|
|
791
851
|
this.requestTimeoutMs = options.requestTimeoutMs ?? 1e3;
|
|
792
|
-
this.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);
|
|
793
858
|
this.maxRetries = options.maxRetries ?? 3;
|
|
794
859
|
this.backoffBaseMs = options.backoffBaseMs ?? 100;
|
|
795
860
|
this.backoffMaxMs = options.backoffMaxMs ?? 5e3;
|
|
@@ -819,11 +884,24 @@ var HttpSink = class _HttpSink {
|
|
|
819
884
|
get closed() {
|
|
820
885
|
return this.closing.signal.aborted;
|
|
821
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. */
|
|
822
892
|
async write(event) {
|
|
823
|
-
if (this.closed) throw new
|
|
824
|
-
this.
|
|
893
|
+
if (this.closed) throw new SinkClosedError("HttpSink is closed");
|
|
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() });
|
|
825
902
|
this.unsentWarned = false;
|
|
826
|
-
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());
|
|
827
905
|
this.ensureExitHooksRegistered();
|
|
828
906
|
}
|
|
829
907
|
flush() {
|
|
@@ -845,9 +923,11 @@ var HttpSink = class _HttpSink {
|
|
|
845
923
|
this.stopReports();
|
|
846
924
|
await this.drainWithinBudget("aclose()", ms);
|
|
847
925
|
this.closing.abort();
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
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.`);
|
|
851
931
|
}
|
|
852
932
|
this.warnUnloggedRefusals("the sink closed");
|
|
853
933
|
if (this.exitHooks) {
|
|
@@ -869,11 +949,11 @@ var HttpSink = class _HttpSink {
|
|
|
869
949
|
}
|
|
870
950
|
if (this.skipWarnedFor !== this.stalledDrain) {
|
|
871
951
|
this.skipWarnedFor = this.stalledDrain;
|
|
872
|
-
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.
|
|
952
|
+
warn(`baton: flush() skipped: an earlier drain is still stuck; ${this.unsent} event(s) wait to be sent.`);
|
|
873
953
|
}
|
|
874
954
|
return;
|
|
875
955
|
}
|
|
876
|
-
const settled = this.scheduleDrain().catch(() => void 0);
|
|
956
|
+
const settled = this.scheduleDrain(true).catch(() => void 0);
|
|
877
957
|
if (await raceDeadline(settled, ms) !== TIMED_OUT) return;
|
|
878
958
|
if (ms < this.shutdownFlushTimeoutMs) return;
|
|
879
959
|
const stalled = this.drainChain.catch(() => void 0);
|
|
@@ -885,12 +965,13 @@ var HttpSink = class _HttpSink {
|
|
|
885
965
|
warn(`baton: flush() took over ${ms} ms; it goes on in the background.`);
|
|
886
966
|
}
|
|
887
967
|
}
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
968
|
+
enqueue(waiting) {
|
|
969
|
+
this.buffer.push(waiting);
|
|
970
|
+
this.bufferedBytes += waiting.bytes;
|
|
971
|
+
this.dropOverflow();
|
|
891
972
|
}
|
|
892
|
-
|
|
893
|
-
|
|
973
|
+
dropOverflow() {
|
|
974
|
+
while (this.buffer.length > this.bufferSize) {
|
|
894
975
|
PROCESS_DROPS.add("buffer_full");
|
|
895
976
|
if (!this.overflowWarned) {
|
|
896
977
|
warn(
|
|
@@ -898,21 +979,49 @@ var HttpSink = class _HttpSink {
|
|
|
898
979
|
);
|
|
899
980
|
this.overflowWarned = true;
|
|
900
981
|
}
|
|
901
|
-
this.buffer.shift();
|
|
982
|
+
this.bufferedBytes -= this.buffer.shift().bytes;
|
|
902
983
|
}
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
*
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
() =>
|
|
913
|
-
|
|
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)
|
|
914
999
|
);
|
|
915
|
-
|
|
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;
|
|
916
1025
|
}
|
|
917
1026
|
/** Best-effort flush when the process is about to exit without an
|
|
918
1027
|
* explicit `aclose()`. SIGKILL, or SIGTERM with no installed handler, skip
|
|
@@ -921,18 +1030,18 @@ var HttpSink = class _HttpSink {
|
|
|
921
1030
|
ensureExitHooksRegistered() {
|
|
922
1031
|
if (this.exitHooks) return;
|
|
923
1032
|
const beforeExit = () => {
|
|
924
|
-
if (this.
|
|
1033
|
+
if (this.unsent === 0 || this.exitPassRan) {
|
|
925
1034
|
this.warnUnloggedRefusals("process exiting");
|
|
926
1035
|
return;
|
|
927
1036
|
}
|
|
928
1037
|
this.drainChain = this.drainChain.then(
|
|
929
1038
|
() => this.exitPass(),
|
|
930
1039
|
() => this.exitPass()
|
|
931
|
-
);
|
|
1040
|
+
).catch(() => void 0);
|
|
932
1041
|
};
|
|
933
1042
|
const exit = () => {
|
|
934
1043
|
try {
|
|
935
|
-
if (this.
|
|
1044
|
+
if (this.unsent > 0 && !this.unsentWarned) stderrLine(this.unsentAtExit());
|
|
936
1045
|
this.warnUnloggedRefusals("process exiting", stderrLine);
|
|
937
1046
|
} catch {
|
|
938
1047
|
}
|
|
@@ -941,35 +1050,22 @@ var HttpSink = class _HttpSink {
|
|
|
941
1050
|
process.on("beforeExit", beforeExit);
|
|
942
1051
|
process.on("exit", exit);
|
|
943
1052
|
}
|
|
944
|
-
/** One attempt per
|
|
1053
|
+
/** One attempt per batch, no retry, within `shutdownFlushTimeoutMs` in
|
|
945
1054
|
* total (SPEC §11.2); what is left is reported, not sent. */
|
|
946
1055
|
async exitPass() {
|
|
947
1056
|
const deadline = Date.now() + this.shutdownFlushTimeoutMs;
|
|
948
|
-
while (this.
|
|
949
|
-
const
|
|
950
|
-
if (
|
|
951
|
-
|
|
952
|
-
const body = this.encode(event);
|
|
953
|
-
if (body !== null) {
|
|
954
|
-
const outcome = await this.postOnce(body, Math.min(this.requestTimeoutMs, timeLeft));
|
|
955
|
-
if (outcome === "transient_failure") {
|
|
956
|
-
this.circuit.recordFailure();
|
|
957
|
-
break;
|
|
958
|
-
}
|
|
959
|
-
this.circuit.recordSuccess();
|
|
960
|
-
}
|
|
961
|
-
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;
|
|
962
1061
|
}
|
|
963
1062
|
this.exitPassRan = true;
|
|
964
1063
|
this.unsentWarned = true;
|
|
965
|
-
if (this.
|
|
1064
|
+
if (this.unsent > 0) warn(this.unsentAtExit());
|
|
966
1065
|
this.warnUnloggedRefusals("process exiting");
|
|
967
1066
|
}
|
|
968
1067
|
unsentAtExit() {
|
|
969
|
-
return `baton: process exiting with ${this.
|
|
970
|
-
}
|
|
971
|
-
events_url() {
|
|
972
|
-
return `${this.url}/v0/events`;
|
|
1068
|
+
return `baton: process exiting with ${this.unsent} unsent event(s).`;
|
|
973
1069
|
}
|
|
974
1070
|
authHeaders() {
|
|
975
1071
|
return { Authorization: `Bearer ${this.apiKey}`, "Content-Type": "application/json" };
|
|
@@ -979,17 +1075,19 @@ var HttpSink = class _HttpSink {
|
|
|
979
1075
|
if (status >= 400 && status < 500 && status !== 429) return "permanent_failure";
|
|
980
1076
|
return "transient_failure";
|
|
981
1077
|
}
|
|
982
|
-
/**
|
|
983
|
-
*
|
|
984
|
-
*
|
|
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
|
|
985
1082
|
* because it is a remote server's text landing in the vendor's log. */
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
);
|
|
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`;
|
|
991
1089
|
warn(
|
|
992
|
-
`baton: collector REFUSED
|
|
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.` : "")
|
|
993
1091
|
);
|
|
994
1092
|
}
|
|
995
1093
|
warnUnloggedRefusals(when, emit2 = warn) {
|
|
@@ -1000,16 +1098,16 @@ var HttpSink = class _HttpSink {
|
|
|
1000
1098
|
}
|
|
1001
1099
|
if (total > 0) emit2(`baton: ${when}; ${total} more event(s) refused since the last such warning.`);
|
|
1002
1100
|
}
|
|
1003
|
-
/** How many refusals
|
|
1004
|
-
* when
|
|
1005
|
-
refusalToLog(
|
|
1101
|
+
/** How many refusals of `kind` went unlogged before these `n`, or `null`
|
|
1102
|
+
* when these go unlogged too. */
|
|
1103
|
+
refusalToLog(kind, n) {
|
|
1006
1104
|
const now = performance.now();
|
|
1007
|
-
const seen = this.refusals.get(
|
|
1105
|
+
const seen = this.refusals.get(kind);
|
|
1008
1106
|
if (seen !== void 0 && now - seen.loggedAt < REFUSAL_LOG_MS) {
|
|
1009
|
-
seen.unlogged
|
|
1107
|
+
seen.unlogged += n;
|
|
1010
1108
|
return null;
|
|
1011
1109
|
}
|
|
1012
|
-
this.refusals.set(
|
|
1110
|
+
this.refusals.set(kind, { loggedAt: now, unlogged: 0 });
|
|
1013
1111
|
return seen?.unlogged ?? 0;
|
|
1014
1112
|
}
|
|
1015
1113
|
/** Enough of the body for `REFUSAL_BODY_MAX_LEN` code points; the rest is
|
|
@@ -1031,87 +1129,205 @@ var HttpSink = class _HttpSink {
|
|
|
1031
1129
|
});
|
|
1032
1130
|
}
|
|
1033
1131
|
}
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
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;
|
|
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;
|
|
1194
|
+
}
|
|
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;
|
|
1051
1214
|
}
|
|
1215
|
+
events.push(waiting);
|
|
1216
|
+
this.bufferedBytes += waiting.bytes;
|
|
1052
1217
|
}
|
|
1053
|
-
this.
|
|
1218
|
+
this.buffer.unshift(...events);
|
|
1219
|
+
this.dropOverflow();
|
|
1220
|
+
return kept.length === 0;
|
|
1054
1221
|
}
|
|
1055
|
-
/**
|
|
1056
|
-
*
|
|
1057
|
-
* 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. */
|
|
1058
1225
|
maybeReport({ tenant_id, vendor_id, consent_token }) {
|
|
1059
1226
|
const now = performance.now();
|
|
1060
|
-
if (this.reportsStopped || this.
|
|
1227
|
+
if (this.reportsStopped || this.pendingReport !== null || now - this.lastReportAt < _HttpSink.reportIntervalMs) {
|
|
1061
1228
|
return;
|
|
1062
1229
|
}
|
|
1063
|
-
|
|
1064
|
-
const sum = Object.values(totals).reduce((a, b) => a + b, 0);
|
|
1065
|
-
if (sum === this.reportedSum) return;
|
|
1230
|
+
if (sum(Object.values(PROCESS_DROPS.total())) === this.reportedSum) return;
|
|
1066
1231
|
this.lastReportAt = now;
|
|
1067
|
-
|
|
1068
|
-
this.
|
|
1069
|
-
const envelope = { tenant_id, vendor_id, consent_token };
|
|
1070
|
-
void this.sendReport(envelope, totals, sum, abort).finally(() => {
|
|
1071
|
-
this.reportInFlight = null;
|
|
1072
|
-
});
|
|
1232
|
+
this.reportSetAt = Date.now();
|
|
1233
|
+
this.pendingReport = { tenant_id, vendor_id, consent_token };
|
|
1073
1234
|
}
|
|
1074
1235
|
stopReports() {
|
|
1075
1236
|
this.reportsStopped = true;
|
|
1076
|
-
this.
|
|
1237
|
+
this.pendingReport = null;
|
|
1077
1238
|
}
|
|
1078
|
-
|
|
1079
|
-
|
|
1239
|
+
buildReport() {
|
|
1240
|
+
if (this.pendingReport === null) return null;
|
|
1241
|
+
const totals = PROCESS_DROPS.total();
|
|
1080
1242
|
try {
|
|
1081
1243
|
const report = ClientReportEventSchema.parse({
|
|
1082
|
-
...
|
|
1244
|
+
...this.pendingReport,
|
|
1083
1245
|
session_id: PROCESS_DROPS.instanceId,
|
|
1084
1246
|
sequence_number: nextClockSequence(),
|
|
1085
1247
|
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1086
1248
|
payload: { instance_id: PROCESS_DROPS.instanceId, dropped: totals }
|
|
1087
1249
|
});
|
|
1088
|
-
const
|
|
1089
|
-
|
|
1090
|
-
headers: this.authHeaders(),
|
|
1091
|
-
body: JSON.stringify(report),
|
|
1092
|
-
signal: abort.signal
|
|
1093
|
-
});
|
|
1094
|
-
void response.body?.cancel().catch(() => void 0);
|
|
1095
|
-
if (response.status === 400 || response.status === 422) this.reportsStopped = true;
|
|
1096
|
-
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)) };
|
|
1097
1252
|
} catch {
|
|
1098
|
-
|
|
1099
|
-
|
|
1253
|
+
this.pendingReport = null;
|
|
1254
|
+
return null;
|
|
1100
1255
|
}
|
|
1101
1256
|
}
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
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);
|
|
1112
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;
|
|
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);
|
|
1113
1330
|
}
|
|
1114
|
-
return "transient_failure";
|
|
1115
1331
|
}
|
|
1116
1332
|
/** `null`, with a warning, for an event `JSON.stringify` rejects. */
|
|
1117
1333
|
encode(event) {
|
|
@@ -1139,37 +1355,73 @@ var HttpSink = class _HttpSink {
|
|
|
1139
1355
|
}
|
|
1140
1356
|
/** Aborted by the timeout or by `aclose()`. Built by hand: `AbortSignal.any`
|
|
1141
1357
|
* is missing before Node 20.3, and on some later versions it keeps every
|
|
1142
|
-
* combined signal alive as long as the long-lived `closing` signal.
|
|
1143
|
-
|
|
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 };
|
|
1144
1362
|
const request = new AbortController();
|
|
1145
1363
|
const abort = () => request.abort();
|
|
1146
1364
|
const timer = setTimeout(abort, timeoutMs);
|
|
1147
1365
|
this.closing.signal.addEventListener("abort", abort);
|
|
1148
1366
|
try {
|
|
1149
|
-
const response = await this.fetchImpl(this.
|
|
1367
|
+
const response = await this.fetchImpl(batchless ? `${this.url}/v0/events` : `${this.url}/v0/events/batch`, {
|
|
1150
1368
|
method: "POST",
|
|
1151
1369
|
headers: this.authHeaders(),
|
|
1152
1370
|
body,
|
|
1153
|
-
signal: request.signal
|
|
1371
|
+
signal: request.signal,
|
|
1372
|
+
// SPEC §2.5: a redirect is a failure, not followed.
|
|
1373
|
+
redirect: "manual"
|
|
1154
1374
|
});
|
|
1155
|
-
const
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
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() };
|
|
1162
1381
|
}
|
|
1382
|
+
return { kind: "answered", refused: _HttpSink.refusedIn(await response.text()) };
|
|
1383
|
+
}
|
|
1384
|
+
const other = _HttpSink.otherAnswer(response, size, batchless);
|
|
1385
|
+
if (other !== null) {
|
|
1386
|
+
void response.body?.cancel().catch(() => void 0);
|
|
1387
|
+
return other;
|
|
1163
1388
|
}
|
|
1164
|
-
|
|
1165
|
-
return
|
|
1389
|
+
const detail = await _HttpSink.readHead(response).catch(() => "<unreadable>");
|
|
1390
|
+
return { kind: "refused", status, refusal: { kind: `HTTP ${status}`, detail } };
|
|
1166
1391
|
} catch {
|
|
1167
|
-
return "
|
|
1392
|
+
return { kind: "transient", retryAfterMs: null };
|
|
1168
1393
|
} finally {
|
|
1169
1394
|
clearTimeout(timer);
|
|
1170
1395
|
this.closing.signal.removeEventListener("abort", abort);
|
|
1171
1396
|
}
|
|
1172
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
|
+
}
|
|
1173
1425
|
};
|
|
1174
1426
|
|
|
1175
1427
|
// src/integrations/mcp/withBaton.ts
|
|
@@ -2150,7 +2402,7 @@ function resolveBatonConfig(config) {
|
|
|
2150
2402
|
validateBatonConfig(identity);
|
|
2151
2403
|
return {
|
|
2152
2404
|
...identity,
|
|
2153
|
-
// The origin is scheme + authority; `HttpSink` appends `/v0/events`
|
|
2405
|
+
// The origin is scheme + authority; `HttpSink` appends `/v0/events/batch`
|
|
2154
2406
|
// itself, exactly as it does for an explicitly-constructed sink.
|
|
2155
2407
|
sink: new HttpSink(dsn.origin, { apiKey: dsn.key })
|
|
2156
2408
|
};
|
|
@@ -2257,6 +2509,24 @@ var DisabledSink = class {
|
|
|
2257
2509
|
}
|
|
2258
2510
|
};
|
|
2259
2511
|
|
|
2512
|
+
// src/integrations/mcp/inputRequired.ts
|
|
2513
|
+
function isInputRequired(result) {
|
|
2514
|
+
try {
|
|
2515
|
+
return isRecord(result) && result.resultType === "input_required";
|
|
2516
|
+
} catch {
|
|
2517
|
+
return false;
|
|
2518
|
+
}
|
|
2519
|
+
}
|
|
2520
|
+
function resumesPausedCall(extra) {
|
|
2521
|
+
try {
|
|
2522
|
+
const req = extra?.mcpReq;
|
|
2523
|
+
if (req === void 0) return false;
|
|
2524
|
+
return req.inputResponses !== void 0 || req.requestState?.() !== void 0;
|
|
2525
|
+
} catch {
|
|
2526
|
+
return false;
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
|
|
2260
2530
|
// src/integrations/mcp/handle.ts
|
|
2261
2531
|
var BatonHandle = class {
|
|
2262
2532
|
sink;
|
|
@@ -2610,6 +2880,7 @@ async function openCall(ctx, toolName, extra, params, retired, registered = true
|
|
|
2610
2880
|
runtime_meta: scrubbedMeta,
|
|
2611
2881
|
call_id: uuid7()
|
|
2612
2882
|
};
|
|
2883
|
+
if (resumesPausedCall(extra)) return { common, session };
|
|
2613
2884
|
await emit(
|
|
2614
2885
|
ctx.sink,
|
|
2615
2886
|
() => ToolCallStartEventSchema.parse({
|
|
@@ -2641,20 +2912,19 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2641
2912
|
const { common, session } = await openCall(ctx, toolName, extra, params, retired);
|
|
2642
2913
|
const terminate = async (build, replacement) => {
|
|
2643
2914
|
if (!slot) {
|
|
2644
|
-
await emit(ctx.sink, build);
|
|
2915
|
+
if (build !== null) await emit(ctx.sink, build);
|
|
2645
2916
|
return;
|
|
2646
2917
|
}
|
|
2647
2918
|
const earlier = slot.flushTerminal;
|
|
2648
2919
|
if (earlier !== null) await earlier(CLEAN_OUTCOME);
|
|
2649
2920
|
slot.flushTerminal = async (outcome) => {
|
|
2650
|
-
await emit(
|
|
2651
|
-
|
|
2652
|
-
() => replacement !== null && outcome.failed ? replacement(outcome) : build()
|
|
2653
|
-
);
|
|
2921
|
+
if (replacement !== null && outcome.failed) await emit(ctx.sink, () => replacement(outcome));
|
|
2922
|
+
else if (build !== null) await emit(ctx.sink, build);
|
|
2654
2923
|
};
|
|
2655
2924
|
};
|
|
2656
2925
|
const parkFailure = (build) => terminate(build, null);
|
|
2657
2926
|
const parkSuccess = (build, replacement) => terminate(build, replacement);
|
|
2927
|
+
const parkPause = (replacement) => terminate(null, replacement);
|
|
2658
2928
|
const startedAt = performance.now();
|
|
2659
2929
|
let result;
|
|
2660
2930
|
try {
|
|
@@ -2697,6 +2967,59 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2697
2967
|
throw err;
|
|
2698
2968
|
}
|
|
2699
2969
|
const durationMs = Math.round(performance.now() - startedAt);
|
|
2970
|
+
const failedAbove = (outcome, failureKind) => ToolCallErrorEventSchema.parse({
|
|
2971
|
+
...common,
|
|
2972
|
+
sequence_number: ctx.counter.nextFor(session),
|
|
2973
|
+
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2974
|
+
payload: {
|
|
2975
|
+
tool_name: toolName,
|
|
2976
|
+
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2977
|
+
// conversion failure is converted to a returned `isError` inside
|
|
2978
|
+
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2979
|
+
// right there. A pause the SDK rejects on 2026-07-28 raises, so
|
|
2980
|
+
// both lanes are reachable.
|
|
2981
|
+
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2982
|
+
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2983
|
+
// not the outer's. Every other leg means the same thing by this
|
|
2984
|
+
// member, and widening it here for one failure kind would make
|
|
2985
|
+
// `duration_ms` mean two things in one column.
|
|
2986
|
+
duration_ms: durationMs,
|
|
2987
|
+
// Omitted, not null, when undetermined: SPEC §11.4.3 says MUST OMIT.
|
|
2988
|
+
...failureKind === void 0 ? {} : { failure_kind: failureKind },
|
|
2989
|
+
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2990
|
+
// kinds.** The message quotes the value the tool returned
|
|
2991
|
+
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2992
|
+
// result-derived by provenance and goes — which leaves
|
|
2993
|
+
// `failure_kind` as the ONLY surviving signal for an
|
|
2994
|
+
// `output_schema_mismatch` under `"off"`, and is the measurement
|
|
2995
|
+
// that justified putting the member on the wire at all.
|
|
2996
|
+
//
|
|
2997
|
+
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2998
|
+
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2999
|
+
// asks for the envelope that holds the flag and the reason, and
|
|
3000
|
+
// this package's own invariant is that it agrees with the
|
|
3001
|
+
// caller. Recording the rejected output TOO would need a member
|
|
3002
|
+
// nothing on the wire has; the loss is deliberate and worth
|
|
3003
|
+
// knowing when debugging one of these.
|
|
3004
|
+
...resultDerivedFields(
|
|
3005
|
+
ctx.resultCaptureMode,
|
|
3006
|
+
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
3007
|
+
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
3008
|
+
// union is what forces the branch rather than a comment: the
|
|
3009
|
+
// scrubber would answer `undefined` and DROP the key, where the
|
|
3010
|
+
// sibling raise lane a few lines up declares `result: null`
|
|
3011
|
+
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
3012
|
+
// records. One shape for "no result object existed", not two.
|
|
3013
|
+
outcome.raised ? null : outcome.result ?? null,
|
|
3014
|
+
(text) => errorBody(ctx, text),
|
|
3015
|
+
ctx.scrubber
|
|
3016
|
+
)
|
|
3017
|
+
}
|
|
3018
|
+
});
|
|
3019
|
+
if (isInputRequired(result)) {
|
|
3020
|
+
await parkPause(failedAbove);
|
|
3021
|
+
return result;
|
|
3022
|
+
}
|
|
2700
3023
|
if (isErrorResult(result)) {
|
|
2701
3024
|
await parkFailure(
|
|
2702
3025
|
() => ToolCallErrorEventSchema.parse({
|
|
@@ -2739,61 +3062,7 @@ function batonWrap(nameRef, original, ctx) {
|
|
|
2739
3062
|
...endResultFields(ctx.resultCaptureMode, result, ctx.scrubber)
|
|
2740
3063
|
}
|
|
2741
3064
|
}),
|
|
2742
|
-
|
|
2743
|
-
// then the outer seam saw the call fail anyway — so what failed is the
|
|
2744
|
-
// producer's own conversion of the output (SPEC §11.4.3's
|
|
2745
|
-
// `output_schema_mismatch`). Correcting this is the whole point of the
|
|
2746
|
-
// second seam: without it this is a `tool_call_end` for a call the
|
|
2747
|
-
// CALLER saw fail, which is a success the product invented.
|
|
2748
|
-
(outcome) => ToolCallErrorEventSchema.parse({
|
|
2749
|
-
...common,
|
|
2750
|
-
sequence_number: ctx.counter.nextFor(session),
|
|
2751
|
-
captured_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2752
|
-
payload: {
|
|
2753
|
-
tool_name: toolName,
|
|
2754
|
-
// The lane the OUTER came back on, not this one's: on 2.x the
|
|
2755
|
-
// conversion failure is converted to a returned `isError` inside
|
|
2756
|
-
// `tools/call` (`mcp-DXXb3Vv3.mjs:1402`), so `"tool_error"` is
|
|
2757
|
-
// right there. A throw out of the handler is unreachable on
|
|
2758
|
-
// either major today for this lane; spelled anyway, because the
|
|
2759
|
-
// alternative is a crash on the day it stops being.
|
|
2760
|
-
error_type: outcome.raised ? errorTypeOf(outcome.err) : TOOL_ERROR_TYPE,
|
|
2761
|
-
// ⚠ The INNER's measurement — the vendor's handler duration —
|
|
2762
|
-
// not the outer's. Every other leg means the same thing by this
|
|
2763
|
-
// member, and widening it here for one failure kind would make
|
|
2764
|
-
// `duration_ms` mean two things in one column.
|
|
2765
|
-
duration_ms: durationMs,
|
|
2766
|
-
failure_kind: OUTPUT_SCHEMA_MISMATCH,
|
|
2767
|
-
// ⚠ **WITHHELD under `"off"`, unlike the three request-side
|
|
2768
|
-
// kinds.** The message quotes the value the tool returned
|
|
2769
|
-
// ("`'not-an-int'` is not of type `integer`"), so it is
|
|
2770
|
-
// result-derived by provenance and goes — which leaves
|
|
2771
|
-
// `failure_kind` as the ONLY surviving signal for this failure
|
|
2772
|
-
// under `"off"`, and is the measurement that justified putting
|
|
2773
|
-
// the member on the wire at all.
|
|
2774
|
-
//
|
|
2775
|
-
// ⚠ `result` is what the CLIENT received — the SDK's own error
|
|
2776
|
-
// envelope — not the vendor's rejected return value. §11.4.3
|
|
2777
|
-
// asks for the envelope that holds the flag and the reason, and
|
|
2778
|
-
// this package's own invariant is that it agrees with the
|
|
2779
|
-
// caller. Recording the rejected output TOO would need a member
|
|
2780
|
-
// nothing on the wire has; the loss is deliberate and worth
|
|
2781
|
-
// knowing when debugging one of these.
|
|
2782
|
-
...resultDerivedFields(
|
|
2783
|
-
ctx.resultCaptureMode,
|
|
2784
|
-
() => outcome.raised ? messageOf(outcome.err) : errorText(outcome.result),
|
|
2785
|
-
// ⚠ `null` on the `raised` lane, never `undefined`, and the
|
|
2786
|
-
// union is what forces the branch rather than a comment: the
|
|
2787
|
-
// scrubber would answer `undefined` and DROP the key, where the
|
|
2788
|
-
// sibling raise lane a few lines up declares `result: null`
|
|
2789
|
-
// explicitly, for the reason `ToolCallErrorPayloadSchema`
|
|
2790
|
-
// records. One shape for "no result object existed", not two.
|
|
2791
|
-
outcome.raised ? null : outcome.result ?? null,
|
|
2792
|
-
(text) => errorBody(ctx, text),
|
|
2793
|
-
ctx.scrubber
|
|
2794
|
-
)
|
|
2795
|
-
}
|
|
2796
|
-
})
|
|
3065
|
+
(outcome) => failedAbove(outcome, OUTPUT_SCHEMA_MISMATCH)
|
|
2797
3066
|
);
|
|
2798
3067
|
return result;
|
|
2799
3068
|
};
|
|
@@ -2959,11 +3228,12 @@ function installLifecycleSeam(lowLevel, ctx, spec) {
|
|
|
2959
3228
|
})
|
|
2960
3229
|
);
|
|
2961
3230
|
};
|
|
2962
|
-
await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
3231
|
+
if (!resumesPausedCall(extra)) await fire(spec.schemas.start, spec.startParams(requestParams));
|
|
2963
3232
|
const startedAt = performance.now();
|
|
2964
3233
|
const elapsed = () => Math.round(performance.now() - startedAt);
|
|
2965
3234
|
try {
|
|
2966
3235
|
const result = await handler(...args);
|
|
3236
|
+
if (isInputRequired(result)) return result;
|
|
2967
3237
|
await fire(spec.schemas.end, {
|
|
2968
3238
|
...spec.countKey === void 0 ? {} : { count: countOf(result, spec.countKey) },
|
|
2969
3239
|
duration_ms: elapsed()
|
|
@@ -3391,7 +3661,12 @@ function install(server, supplied, resolved, sentSurfaces, warned3) {
|
|
|
3391
3661
|
seam_augmentations: snapshot.seam_augmentations
|
|
3392
3662
|
}
|
|
3393
3663
|
});
|
|
3394
|
-
|
|
3664
|
+
try {
|
|
3665
|
+
await sink.write(event);
|
|
3666
|
+
} catch (err) {
|
|
3667
|
+
if (isSinkClosed(err)) return droppedAfterClose(sink);
|
|
3668
|
+
throw err;
|
|
3669
|
+
}
|
|
3395
3670
|
};
|
|
3396
3671
|
const bustSchemaMemo = (name) => {
|
|
3397
3672
|
const memo = internals._toolInputSchemaJson;
|
|
@@ -3853,6 +4128,7 @@ var Core = class {
|
|
|
3853
4128
|
try {
|
|
3854
4129
|
await this.sink.write(event);
|
|
3855
4130
|
} catch (err) {
|
|
4131
|
+
if (isSinkClosed(err)) return droppedAfterClose(this.sink);
|
|
3856
4132
|
process.stderr.write(`baton: surface snapshot not sent; will retry: ${printable(err)}
|
|
3857
4133
|
`);
|
|
3858
4134
|
this.sentSurfaces.unmark(surface.digest);
|
|
@@ -4208,6 +4484,7 @@ export {
|
|
|
4208
4484
|
ResourceReadStartPayloadSchema,
|
|
4209
4485
|
SDK_VERSION,
|
|
4210
4486
|
Scrubber,
|
|
4487
|
+
SinkClosedError,
|
|
4211
4488
|
StdoutSink,
|
|
4212
4489
|
SurfaceSnapshotEventSchema,
|
|
4213
4490
|
SurfaceSnapshotPayloadSchema,
|