jsflow-sdk 1.1.2 → 1.2.0-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +109 -0
- package/README.md +1 -1
- package/jsflow.d.ts +138 -4
- package/jsflow.js +283 -24
- package/package.json +1 -1
- package/sri.json +4 -4
- package/worker.js +682 -53
package/worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// jsflow-sdk 1.1.
|
|
1
|
+
// jsflow-sdk 1.2.0-rc.1. Licence: see LICENSE (https://jsflow.com). Built by client/build.js.
|
|
2
2
|
|
|
3
3
|
// core/header.js
|
|
4
4
|
var VERSION = 2;
|
|
@@ -153,7 +153,7 @@ function articulationPoints(g) {
|
|
|
153
153
|
var NATS = [null, "open", "prc", "sym"];
|
|
154
154
|
var NATCODE = { open: 1, prc: 2, sym: 3 };
|
|
155
155
|
var TLV = { TOKEN: 1, CAPS: 2 };
|
|
156
|
-
var CAPS = { DIAG_ECHO: 1 };
|
|
156
|
+
var CAPS = { DIAG_ECHO: 1, WIDE_WINDOW: 2, STREAM: 4 };
|
|
157
157
|
var HELLO_MIN = 50;
|
|
158
158
|
var HELLO_MAX = 1e4;
|
|
159
159
|
var DEAD_K = 8;
|
|
@@ -319,7 +319,7 @@ function meshNode(opts = {}) {
|
|
|
319
319
|
lsaSeq = lsaSeq + 1 & 65535;
|
|
320
320
|
const live = leaving ? [] : [...nbr].filter(([, n]) => !n.sus);
|
|
321
321
|
const tok = o.e2e?.token() ?? null;
|
|
322
|
-
const tlvs = [...tok ? [[TLV.TOKEN, tok]] : [], [TLV.CAPS, u32(CAPS.DIAG_ECHO)]];
|
|
322
|
+
const tlvs = [...tok ? [[TLV.TOKEN, tok]] : [], [TLV.CAPS, u32(CAPS.DIAG_ECHO | (o.caps ?? 0))]];
|
|
323
323
|
const p = new Uint8Array(8 + 4 * live.length + tlvs.reduce((a, [, x]) => a + 3 + x.length, 0)), v = new DataView(p.buffer);
|
|
324
324
|
v.setUint32(0, inc);
|
|
325
325
|
v.setUint16(4, lsaSeq);
|
|
@@ -709,8 +709,8 @@ function meshNode(opts = {}) {
|
|
|
709
709
|
return env2.restartIn?.(peer, kind, blob);
|
|
710
710
|
}
|
|
711
711
|
if (kind === OFFER) {
|
|
712
|
-
const
|
|
713
|
-
if (m.inc &&
|
|
712
|
+
const known = lsdb.get(peer)?.inc;
|
|
713
|
+
if (m.inc && known && m.inc < known) return env2.metric("olderInc", { peer, inc: m.inc, known });
|
|
714
714
|
if (leaving) return sigSend(peer, REJECT, void 0, cloud, att);
|
|
715
715
|
if (nbr.has(peer)) {
|
|
716
716
|
env2.metric("staleLink", peer);
|
|
@@ -867,7 +867,10 @@ function meshNode(opts = {}) {
|
|
|
867
867
|
}
|
|
868
868
|
function hello() {
|
|
869
869
|
every(o.helloMs, hello);
|
|
870
|
-
if (leaving)
|
|
870
|
+
if (leaving) {
|
|
871
|
+
for (const peer of nbr.keys()) sendBye(peer);
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
871
874
|
const now = env2.now();
|
|
872
875
|
const deadMs = o.deadMs ?? o.missK * o.helloMs;
|
|
873
876
|
for (const [peer, n] of [...nbr]) {
|
|
@@ -916,9 +919,15 @@ function meshNode(opts = {}) {
|
|
|
916
919
|
n.echoTs = v.getUint32(0);
|
|
917
920
|
n.echoAt = env2.now();
|
|
918
921
|
}
|
|
922
|
+
function sendBye(peer) {
|
|
923
|
+
const p = new Uint8Array(4);
|
|
924
|
+
new DataView(p.buffer).setUint32(0, ts10());
|
|
925
|
+
env2.send(peer, P(T.BYE, peer, p, { ttl: 1 }));
|
|
926
|
+
}
|
|
919
927
|
function onBye(peer, h2) {
|
|
920
928
|
const n = nbr.get(peer);
|
|
921
929
|
if (!n || h2.payload.length < 4) return;
|
|
930
|
+
const first = n.byeTs === void 0;
|
|
922
931
|
const ts = new DataView(h2.payload.buffer, h2.payload.byteOffset, 4).getUint32(0), last = n.echoTs ?? 0;
|
|
923
932
|
n.byeTs = ts - last >>> 0 < 1e5 ? ts : last;
|
|
924
933
|
if (!n.sus) {
|
|
@@ -926,7 +935,7 @@ function meshNode(opts = {}) {
|
|
|
926
935
|
routes = null;
|
|
927
936
|
originateSoon();
|
|
928
937
|
}
|
|
929
|
-
env2.metric("bye", peer);
|
|
938
|
+
if (first) env2.metric("bye", peer);
|
|
930
939
|
}
|
|
931
940
|
function down(peer) {
|
|
932
941
|
if (!nbr.delete(peer)) return;
|
|
@@ -1005,6 +1014,7 @@ function meshNode(opts = {}) {
|
|
|
1005
1014
|
reject.delete(peer);
|
|
1006
1015
|
nbr.set(peer, { lastHeard: env2.now(), rtt: null, echoTs: 0, echoAt: 0 });
|
|
1007
1016
|
sendHello(peer, nbr.get(peer));
|
|
1017
|
+
if (leaving) sendBye(peer);
|
|
1008
1018
|
for (const e of lsdb.values()) if (env2.now() - e.at < 2 * o.lsaRefreshMs) env2.send(peer, e.raw);
|
|
1009
1019
|
routes = null;
|
|
1010
1020
|
originateSoon();
|
|
@@ -1024,7 +1034,15 @@ function meshNode(opts = {}) {
|
|
|
1024
1034
|
if (h2.type === T.HELLO) return onHello(from, h2);
|
|
1025
1035
|
if (h2.type === T.BYE) return onBye(from, h2);
|
|
1026
1036
|
const n = nbr.get(from);
|
|
1027
|
-
if (n && n.byeTs === void 0)
|
|
1037
|
+
if (n && n.byeTs === void 0) {
|
|
1038
|
+
n.lastHeard = env2.now();
|
|
1039
|
+
if (n.sus) {
|
|
1040
|
+
n.sus = false;
|
|
1041
|
+
routes = null;
|
|
1042
|
+
originateSoon();
|
|
1043
|
+
env2.metric("unsuspect", from);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1028
1046
|
route(raw, h2, from);
|
|
1029
1047
|
},
|
|
1030
1048
|
// ---- app API used by experiments ----
|
|
@@ -1065,10 +1083,9 @@ function meshNode(opts = {}) {
|
|
|
1065
1083
|
},
|
|
1066
1084
|
// Announced leave (page hiding on a phone): BYE to every neighbour,
|
|
1067
1085
|
// withdraw own links from the map, then stay silent until onWake.
|
|
1086
|
+
// The BYE repeats every hello interval until wake (hello()).
|
|
1068
1087
|
bye() {
|
|
1069
|
-
const
|
|
1070
|
-
new DataView(p.buffer).setUint32(0, ts10());
|
|
1071
|
-
for (const peer of nbr.keys()) env2.send(peer, P(T.BYE, peer, p, { ttl: 1 }));
|
|
1088
|
+
for (const peer of nbr.keys()) sendBye(peer);
|
|
1072
1089
|
leaving = true;
|
|
1073
1090
|
originate();
|
|
1074
1091
|
},
|
|
@@ -1822,6 +1839,8 @@ var B = 16;
|
|
|
1822
1839
|
var E = 32;
|
|
1823
1840
|
var FRAG = MTU - HDR2 - ACKH - 2 * MAX_RANGES - DATAH;
|
|
1824
1841
|
var d32 = (a, b) => a - b >>> 0;
|
|
1842
|
+
var FRAG_COST = 32;
|
|
1843
|
+
var MIN_RTT_MS = 3e4;
|
|
1825
1844
|
function reliable({
|
|
1826
1845
|
inc,
|
|
1827
1846
|
send,
|
|
@@ -1830,6 +1849,8 @@ function reliable({
|
|
|
1830
1849
|
clearTimer,
|
|
1831
1850
|
onMessage,
|
|
1832
1851
|
onGiveUp,
|
|
1852
|
+
onFreed = null,
|
|
1853
|
+
onReset = null,
|
|
1833
1854
|
metric: metric2 = () => {
|
|
1834
1855
|
},
|
|
1835
1856
|
maxMessage = 65536,
|
|
@@ -1842,6 +1863,12 @@ function reliable({
|
|
|
1842
1863
|
initRto = 1e3,
|
|
1843
1864
|
initCwnd = 10,
|
|
1844
1865
|
congestion = true,
|
|
1866
|
+
maxRate = null,
|
|
1867
|
+
wireOverhead = 100,
|
|
1868
|
+
peerWindow = null,
|
|
1869
|
+
narrowWindow = 64,
|
|
1870
|
+
wideAfterMs = 5e3,
|
|
1871
|
+
narrowOn = "delay",
|
|
1845
1872
|
giveUpMs = 3e4,
|
|
1846
1873
|
txIdleMs = 3e4,
|
|
1847
1874
|
rxIdleMs = 6e4,
|
|
@@ -1850,7 +1877,8 @@ function reliable({
|
|
|
1850
1877
|
}) {
|
|
1851
1878
|
if (!(Number.isInteger(inc) && inc > 0 && inc <= 4294967295)) throw new RangeError("reliable: inc must be a 32-bit incarnation > 0");
|
|
1852
1879
|
if (!(W >= 2 && W <= 255)) throw new RangeError("reliable: window must be 2…255 (SACK offsets are 8-bit)");
|
|
1853
|
-
|
|
1880
|
+
const MAXF = Math.ceil(maxMessage / FRAG);
|
|
1881
|
+
if (MAXF > W) throw new RangeError("reliable: a maxMessage message must fit in the window");
|
|
1854
1882
|
if (!(rxIdleMs > giveUpMs && rxIdleMs > txIdleMs)) throw new RangeError("reliable: rxIdleMs must outlast giveUpMs and txIdleMs");
|
|
1855
1883
|
const peers = /* @__PURE__ */ new Map();
|
|
1856
1884
|
const meshInc = /* @__PURE__ */ new Map();
|
|
@@ -1871,10 +1899,10 @@ function reliable({
|
|
|
1871
1899
|
inc: meshInc.get(peer) ?? 0,
|
|
1872
1900
|
tx: null,
|
|
1873
1901
|
rx: null,
|
|
1874
|
-
rtt: { srtt: null, var: 0, min: Infinity, latest: 0 },
|
|
1902
|
+
rtt: { srtt: null, var: 0, min: Infinity, minAt: 0, latest: 0 },
|
|
1875
1903
|
seen: now(),
|
|
1876
1904
|
noticeAt: -Infinity,
|
|
1877
|
-
cc: { cwnd: Math.min(W, initCwnd), ssthresh: Infinity, delivered: 0, roundDel: 0, rDel0: 0, rLost: 0 }
|
|
1905
|
+
cc: { cwnd: Math.min(W, initCwnd), ssthresh: Infinity, delivered: 0, roundDel: 0, rDel0: 0, rLost: 0, lossAt: -Infinity }
|
|
1878
1906
|
});
|
|
1879
1907
|
if (!sweep) sweep = setTimer(sweepMs, onSweep);
|
|
1880
1908
|
return rec;
|
|
@@ -1906,6 +1934,7 @@ function reliable({
|
|
|
1906
1934
|
giveUp(peer, rec, why);
|
|
1907
1935
|
dropRx(rec);
|
|
1908
1936
|
peers.delete(peer);
|
|
1937
|
+
if (why === "reset") onReset?.(peer);
|
|
1909
1938
|
}
|
|
1910
1939
|
function live(peer, rec) {
|
|
1911
1940
|
const tx = rec.tx;
|
|
@@ -1936,7 +1965,7 @@ function reliable({
|
|
|
1936
1965
|
let o = HDR2;
|
|
1937
1966
|
if (ack) {
|
|
1938
1967
|
v.setUint32(o, rx.sid);
|
|
1939
|
-
v.setUint32(o + 4, rx.
|
|
1968
|
+
v.setUint32(o + 4, rx.cum);
|
|
1940
1969
|
v.setUint16(o + 8, Math.min(65535, Math.round(now() - rx.firstAt)));
|
|
1941
1970
|
b[o + 10] = ranges.length;
|
|
1942
1971
|
ranges.forEach(([off, len], i) => {
|
|
@@ -1980,6 +2009,8 @@ function reliable({
|
|
|
1980
2009
|
inflight: /* @__PURE__ */ new Map(),
|
|
1981
2010
|
queue: [],
|
|
1982
2011
|
qBytes: 0,
|
|
2012
|
+
unsent: 0,
|
|
2013
|
+
cost: 0,
|
|
1983
2014
|
msgs: 0,
|
|
1984
2015
|
txn: 0,
|
|
1985
2016
|
rack: { txn: 0, rtt: 0 },
|
|
@@ -1989,47 +2020,103 @@ function reliable({
|
|
|
1989
2020
|
progress: now(),
|
|
1990
2021
|
timer: null,
|
|
1991
2022
|
paceAt: 0,
|
|
1992
|
-
paceTimer: null
|
|
2023
|
+
paceTimer: null,
|
|
2024
|
+
retxQ: []
|
|
1993
2025
|
};
|
|
1994
2026
|
}
|
|
2027
|
+
function rateMs(peer, bytes) {
|
|
2028
|
+
const r = maxRate?.(peer);
|
|
2029
|
+
return r > 0 && r < Infinity ? 1e3 * (HDR2 + DATAH + bytes + wireOverhead) / r : 0;
|
|
2030
|
+
}
|
|
1995
2031
|
function transmit(peer, rec, p) {
|
|
1996
2032
|
const tx = rec.tx;
|
|
1997
|
-
if (p.n)
|
|
2033
|
+
if (p.n) {
|
|
2034
|
+
const r = rateMs(peer, p.bytes.length);
|
|
2035
|
+
if (r) {
|
|
2036
|
+
if (tx.paceAt > now()) {
|
|
2037
|
+
if (!p.queued) {
|
|
2038
|
+
p.queued = true;
|
|
2039
|
+
tx.retxQ.push(p);
|
|
2040
|
+
}
|
|
2041
|
+
paceLater(peer, rec, tx);
|
|
2042
|
+
return false;
|
|
2043
|
+
}
|
|
2044
|
+
tx.paceAt = Math.max(tx.paceAt, now()) + r;
|
|
2045
|
+
}
|
|
2046
|
+
stats.retx++;
|
|
2047
|
+
}
|
|
1998
2048
|
p.sentAt = now();
|
|
1999
2049
|
p.txn = ++tx.txn;
|
|
2000
2050
|
p.n++;
|
|
2001
2051
|
p.del = rec.cc.delivered;
|
|
2002
2052
|
out2(peer, rec, p);
|
|
2053
|
+
return true;
|
|
2054
|
+
}
|
|
2055
|
+
function paceLater(peer, rec, tx) {
|
|
2056
|
+
if (!tx.paceTimer) tx.paceTimer = setTimer(Math.max(1, tx.paceAt - now()), () => {
|
|
2057
|
+
tx.paceTimer = null;
|
|
2058
|
+
if (rec.tx === tx && peers.get(peer) === rec && live(peer, rec)) pump(peer, rec);
|
|
2059
|
+
});
|
|
2003
2060
|
}
|
|
2004
2061
|
function pipe(tx) {
|
|
2005
2062
|
let n = 0;
|
|
2006
2063
|
for (const p of tx.inflight.values()) if (!p.sacked) n++;
|
|
2007
2064
|
return n;
|
|
2008
2065
|
}
|
|
2009
|
-
function
|
|
2066
|
+
function win(peer, rec) {
|
|
2067
|
+
const w = Math.max(2, Math.min(W, peerWindow ? peerWindow(peer) ?? narrowWindow : W));
|
|
2068
|
+
return w <= narrowWindow || now() - rec.cc.lossAt >= wideAfterMs ? w : narrowWindow;
|
|
2069
|
+
}
|
|
2070
|
+
function narrow(peer, rec) {
|
|
2071
|
+
rec.cc.lossAt = now();
|
|
2072
|
+
rec.cc.cwnd = Math.min(rec.cc.cwnd, win(peer, rec));
|
|
2073
|
+
}
|
|
2074
|
+
function lossSeen(peer, rec) {
|
|
2075
|
+
if (narrowOn === "loss") narrow(peer, rec);
|
|
2076
|
+
}
|
|
2077
|
+
function delivered(peer, rec, ps) {
|
|
2010
2078
|
const cc = rec.cc;
|
|
2011
2079
|
let roundEnd = false;
|
|
2012
2080
|
for (const p of ps) {
|
|
2013
2081
|
cc.delivered++;
|
|
2014
2082
|
if (p.del >= cc.roundDel) roundEnd = true;
|
|
2015
2083
|
}
|
|
2016
|
-
cc.cwnd = Math.min(
|
|
2084
|
+
cc.cwnd = Math.min(win(peer, rec), cc.cwnd < cc.ssthresh ? cc.cwnd + ps.length : cc.cwnd + ps.length / cc.cwnd);
|
|
2017
2085
|
if (!roundEnd) return;
|
|
2018
2086
|
const rDel = cc.delivered - cc.rDel0;
|
|
2019
2087
|
if (rDel >= 8 && cc.rLost >= 3 && cc.rLost >= 0.1 * (rDel + cc.rLost)) {
|
|
2020
2088
|
cc.cwnd = Math.max(4, Math.min(cc.cwnd, 0.85 * rDel));
|
|
2021
2089
|
cc.ssthresh = cc.cwnd;
|
|
2022
2090
|
stats.cuts++;
|
|
2091
|
+
cc.lossAt = now();
|
|
2023
2092
|
}
|
|
2024
2093
|
cc.roundDel = cc.rDel0 = cc.delivered;
|
|
2025
2094
|
cc.rLost = 0;
|
|
2026
2095
|
}
|
|
2027
2096
|
function pump(peer, rec) {
|
|
2028
2097
|
const tx = rec.tx, cc = rec.cc, t = now();
|
|
2029
|
-
|
|
2098
|
+
const w = win(peer, rec);
|
|
2099
|
+
let room = (congestion ? Math.floor(Math.min(cc.cwnd, w)) : w) - pipe(tx);
|
|
2030
2100
|
const srtt = rec.rtt.srtt, gap = congestion && srtt ? srtt / ((cc.cwnd < cc.ssthresh ? 2 : 1.2) * cc.cwnd) : 0;
|
|
2031
|
-
|
|
2032
|
-
|
|
2101
|
+
const rg = tx.queue.length ? rateMs(peer, tx.queue[0].bytes.length) : 0;
|
|
2102
|
+
tx.paceAt = Math.max(tx.paceAt, t - 4 * Math.max(gap, rg));
|
|
2103
|
+
while (tx.retxQ.length) {
|
|
2104
|
+
if (tx.paceAt > t) {
|
|
2105
|
+
paceLater(peer, rec, tx);
|
|
2106
|
+
return arm(peer, rec);
|
|
2107
|
+
}
|
|
2108
|
+
const p = tx.retxQ.shift();
|
|
2109
|
+
p.queued = false;
|
|
2110
|
+
if (tx.inflight.get(p.seq) !== p || p.sacked) continue;
|
|
2111
|
+
tx.paceAt = Math.max(tx.paceAt, t) + rateMs(peer, p.bytes.length);
|
|
2112
|
+
stats.retx++;
|
|
2113
|
+
p.sentAt = t;
|
|
2114
|
+
p.txn = ++tx.txn;
|
|
2115
|
+
p.n++;
|
|
2116
|
+
p.del = rec.cc.delivered;
|
|
2117
|
+
out2(peer, rec, p);
|
|
2118
|
+
}
|
|
2119
|
+
while (tx.queue.length && d32(tx.next, tx.una) < w && room-- > 0) {
|
|
2033
2120
|
if (tx.paceAt > t) {
|
|
2034
2121
|
if (!tx.paceTimer) tx.paceTimer = setTimer(Math.max(1, tx.paceAt - t), () => {
|
|
2035
2122
|
tx.paceTimer = null;
|
|
@@ -2037,12 +2124,13 @@ function reliable({
|
|
|
2037
2124
|
});
|
|
2038
2125
|
break;
|
|
2039
2126
|
}
|
|
2040
|
-
tx.paceAt += gap;
|
|
2127
|
+
tx.paceAt += Math.max(gap, rateMs(peer, tx.queue[0].bytes.length));
|
|
2041
2128
|
if (!tx.inflight.size) {
|
|
2042
2129
|
tx.progress = now();
|
|
2043
2130
|
tx.rtoAt = now() + tx.rto;
|
|
2044
2131
|
}
|
|
2045
2132
|
const p = { ...tx.queue.shift(), seq: tx.next, n: 0, sacked: false, sentAt: 0, txn: 0 };
|
|
2133
|
+
tx.unsent -= p.bytes.length;
|
|
2046
2134
|
tx.next = tx.next + 1 >>> 0;
|
|
2047
2135
|
tx.inflight.set(p.seq, p);
|
|
2048
2136
|
transmit(peer, rec, p);
|
|
@@ -2067,20 +2155,28 @@ function reliable({
|
|
|
2067
2155
|
const lost = detectLost(rec);
|
|
2068
2156
|
if (lost.length) {
|
|
2069
2157
|
rec.cc.rLost += lost.length;
|
|
2158
|
+
lossSeen(peer, rec);
|
|
2070
2159
|
for (const p of lost) transmit(peer, rec, p);
|
|
2071
2160
|
return arm(peer, rec);
|
|
2072
2161
|
}
|
|
2073
2162
|
if (now() >= tx.rtoAt) {
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2163
|
+
let probe = null;
|
|
2164
|
+
for (const p of tx.inflight.values()) if (!p.sacked && !p.queued) {
|
|
2165
|
+
probe = p;
|
|
2077
2166
|
break;
|
|
2078
2167
|
}
|
|
2168
|
+
if (!probe || !transmit(peer, rec, probe)) {
|
|
2169
|
+
tx.rtoAt = now() + tx.rto;
|
|
2170
|
+
return arm(peer, rec);
|
|
2171
|
+
}
|
|
2172
|
+
lossSeen(peer, rec);
|
|
2173
|
+
stats.rto++;
|
|
2079
2174
|
if (tx.rto === rtoOf(rec.rtt)) {
|
|
2080
2175
|
const cc = rec.cc;
|
|
2081
2176
|
cc.cwnd = cc.ssthresh = Math.max(4, cc.cwnd / 2);
|
|
2082
2177
|
stats.cuts++;
|
|
2083
2178
|
}
|
|
2179
|
+
narrow(peer, rec);
|
|
2084
2180
|
tx.rto = Math.min(2 * tx.rto, maxRto);
|
|
2085
2181
|
tx.rtoAt = now() + tx.rto;
|
|
2086
2182
|
}
|
|
@@ -2095,6 +2191,7 @@ function reliable({
|
|
|
2095
2191
|
later.push(p.txn);
|
|
2096
2192
|
continue;
|
|
2097
2193
|
}
|
|
2194
|
+
if (p.queued) continue;
|
|
2098
2195
|
if (p.txn >= rk.txn) continue;
|
|
2099
2196
|
let k = 0;
|
|
2100
2197
|
if (!tx.reordered) {
|
|
@@ -2115,7 +2212,10 @@ function reliable({
|
|
|
2115
2212
|
}
|
|
2116
2213
|
function rttSample(rec, tx, raw, ackDelay) {
|
|
2117
2214
|
const r = rec.rtt;
|
|
2118
|
-
r.min
|
|
2215
|
+
if (raw <= r.min || now() - r.minAt > MIN_RTT_MS) {
|
|
2216
|
+
r.min = raw;
|
|
2217
|
+
r.minAt = now();
|
|
2218
|
+
}
|
|
2119
2219
|
const a = raw - ackDelay >= r.min ? raw - ackDelay : raw;
|
|
2120
2220
|
r.latest = a;
|
|
2121
2221
|
if (r.srtt === null) {
|
|
@@ -2154,6 +2254,7 @@ function reliable({
|
|
|
2154
2254
|
if (!p.sacked) got(p);
|
|
2155
2255
|
tx.inflight.delete(s);
|
|
2156
2256
|
tx.qBytes -= p.bytes.length;
|
|
2257
|
+
tx.cost -= Math.max(p.bytes.length, FRAG_COST);
|
|
2157
2258
|
if (p.flags & E) tx.msgs--;
|
|
2158
2259
|
}
|
|
2159
2260
|
tx.una = next;
|
|
@@ -2166,14 +2267,17 @@ function reliable({
|
|
|
2166
2267
|
}
|
|
2167
2268
|
if (newest) {
|
|
2168
2269
|
if (newest.n === 1) rttSample(rec, tx, now() - newest.sentAt, delay);
|
|
2270
|
+
if (narrowOn === "delay" && rec.rtt.srtt > 1.5 * rec.rtt.min + 5 && pipe(tx) > narrowWindow) narrow(peer, rec);
|
|
2169
2271
|
tx.progress = now();
|
|
2170
2272
|
tx.rtoAt = now() + tx.rto;
|
|
2171
2273
|
}
|
|
2172
|
-
if (acked.length) delivered(rec, acked);
|
|
2274
|
+
if (acked.length) delivered(peer, rec, acked);
|
|
2173
2275
|
const lost = detectLost(rec);
|
|
2174
2276
|
rec.cc.rLost += lost.length;
|
|
2277
|
+
if (lost.length) lossSeen(peer, rec);
|
|
2175
2278
|
for (const p of lost) transmit(peer, rec, p);
|
|
2176
2279
|
pump(peer, rec);
|
|
2280
|
+
if (adv && onFreed) onFreed(peer);
|
|
2177
2281
|
}
|
|
2178
2282
|
function onData(peer, rec, sid, seq, una, flags, bytes) {
|
|
2179
2283
|
let rx = rec.rx;
|
|
@@ -2184,33 +2288,33 @@ function reliable({
|
|
|
2184
2288
|
if (rx && sid !== rx.sid && !newer32(sid, rx.sid)) return metric2("reliableOldSession", peer);
|
|
2185
2289
|
if (!rx || sid !== rx.sid) {
|
|
2186
2290
|
dropRx(rec);
|
|
2187
|
-
rx = rec.rx = { sid, next: una, buf: /* @__PURE__ */ new Map(), bytes: 0, heard: 0, pending: 0, firstAt: 0, timer: null };
|
|
2291
|
+
rx = rec.rx = { sid, next: una, cum: una, buf: /* @__PURE__ */ new Map(), bytes: 0, heard: 0, pending: 0, firstAt: 0, timer: null };
|
|
2188
2292
|
}
|
|
2189
2293
|
rx.heard = now();
|
|
2190
|
-
const off = d32(seq, rx.
|
|
2294
|
+
const off = d32(seq, rx.cum);
|
|
2191
2295
|
let now_ = false, stored = false;
|
|
2192
2296
|
if (off >= W) {
|
|
2193
|
-
if (off
|
|
2297
|
+
if (off >= 2147483648) {
|
|
2298
|
+
stats.dup++;
|
|
2299
|
+
now_ = true;
|
|
2300
|
+
} else {
|
|
2194
2301
|
metric2("reliableBeyondWindow", peer);
|
|
2195
2302
|
return;
|
|
2196
2303
|
}
|
|
2197
|
-
stats.dup++;
|
|
2198
|
-
now_ = true;
|
|
2199
2304
|
} else if (rx.buf.has(seq)) {
|
|
2200
2305
|
stats.dup++;
|
|
2201
2306
|
now_ = true;
|
|
2202
2307
|
} else {
|
|
2203
|
-
let first = 0;
|
|
2204
|
-
while (first < W && rx.buf.has(rx.next + first >>> 0)) first++;
|
|
2205
2308
|
let above = false;
|
|
2206
|
-
for (const s of rx.buf.keys()) if (d32(s, rx.
|
|
2309
|
+
for (const s of rx.buf.keys()) if (d32(s, rx.cum) < W && d32(s, rx.cum) > off) {
|
|
2207
2310
|
above = true;
|
|
2208
2311
|
break;
|
|
2209
2312
|
}
|
|
2210
|
-
now_ = off !==
|
|
2313
|
+
now_ = off !== 0 || above;
|
|
2211
2314
|
rx.buf.set(seq, { flags, bytes: bytes.slice() });
|
|
2212
2315
|
rx.bytes += bytes.length;
|
|
2213
2316
|
stored = true;
|
|
2317
|
+
while (rx.buf.has(rx.cum)) rx.cum = rx.cum + 1 >>> 0;
|
|
2214
2318
|
}
|
|
2215
2319
|
if (!rx.pending++) rx.firstAt = now();
|
|
2216
2320
|
if (stored && !deliverReady(peer, rec, rx)) return;
|
|
@@ -2226,18 +2330,19 @@ function reliable({
|
|
|
2226
2330
|
const head = rx.buf.get(rx.next);
|
|
2227
2331
|
if (!head) return true;
|
|
2228
2332
|
let k = 0, size = 0, ok = !!(head.flags & B);
|
|
2229
|
-
for (; ok && k <
|
|
2333
|
+
for (; ok && k < MAXF; k++) {
|
|
2230
2334
|
const f = rx.buf.get(rx.next + k >>> 0);
|
|
2231
2335
|
if (!f) return true;
|
|
2232
2336
|
if (k && f.flags & B) ok = false;
|
|
2233
2337
|
size += f.bytes.length;
|
|
2234
2338
|
if (f.flags & E) break;
|
|
2235
2339
|
}
|
|
2236
|
-
if (!ok || k >=
|
|
2340
|
+
if (!ok || k >= MAXF || size > maxMessage) {
|
|
2237
2341
|
bad("fragments");
|
|
2238
2342
|
rx.bytes -= head.bytes.length;
|
|
2239
2343
|
rx.buf.delete(rx.next);
|
|
2240
2344
|
rx.next = rx.next + 1 >>> 0;
|
|
2345
|
+
if (d32(rx.cum, rx.next) >= 2147483648) rx.cum = rx.next;
|
|
2241
2346
|
continue;
|
|
2242
2347
|
}
|
|
2243
2348
|
const msg = new Uint8Array(size), chan = head.flags & 15;
|
|
@@ -2257,9 +2362,9 @@ function reliable({
|
|
|
2257
2362
|
function sackRanges(rx) {
|
|
2258
2363
|
const r = [];
|
|
2259
2364
|
for (let off = 0; off < W && r.length < MAX_RANGES; off++) {
|
|
2260
|
-
if (!rx.buf.has(rx.
|
|
2365
|
+
if (!rx.buf.has(rx.cum + off >>> 0)) continue;
|
|
2261
2366
|
let len = 1;
|
|
2262
|
-
while (off + len < W && rx.buf.has(rx.
|
|
2367
|
+
while (off + len < W && rx.buf.has(rx.cum + off + len >>> 0)) len++;
|
|
2263
2368
|
r.push([off, len]);
|
|
2264
2369
|
off += len;
|
|
2265
2370
|
}
|
|
@@ -2270,18 +2375,23 @@ function reliable({
|
|
|
2270
2375
|
send(dst, bytes, appChan = 0) {
|
|
2271
2376
|
if (!(bytes instanceof Uint8Array)) throw new TypeError("reliable.send: bytes must be a Uint8Array");
|
|
2272
2377
|
if (bytes.length > maxMessage) throw new RangeError(`reliable.send: ${bytes.length} B > maxMessage ${maxMessage}`);
|
|
2273
|
-
if (!(Number.isInteger(appChan) && appChan >= 0 && appChan <=
|
|
2378
|
+
if (!(Number.isInteger(appChan) && appChan >= 0 && appChan <= 14)) throw new RangeError("reliable.send: appChan must be 0…14");
|
|
2274
2379
|
if (!(Number.isInteger(dst) && dst >= 0 && dst <= 65535)) throw new RangeError("reliable.send: dst must be a 16-bit id");
|
|
2275
2380
|
const rec = record(dst);
|
|
2276
2381
|
if (!rec) return false;
|
|
2277
2382
|
const tx = live(dst, rec) ?? (rec.tx = newTx(rec));
|
|
2278
|
-
|
|
2383
|
+
const nf = Math.max(1, Math.ceil(bytes.length / FRAG));
|
|
2384
|
+
let c = 0;
|
|
2385
|
+
for (let i = 0; i < nf; i++) c += Math.max(Math.min(FRAG, bytes.length - i * FRAG), FRAG_COST);
|
|
2386
|
+
if (tx.cost + c > maxQueueBytes) {
|
|
2279
2387
|
metric2("reliableQueueFull", dst);
|
|
2280
2388
|
return false;
|
|
2281
2389
|
}
|
|
2282
2390
|
const copy = bytes.slice(), n = Math.max(1, Math.ceil(copy.length / FRAG));
|
|
2283
2391
|
for (let i = 0; i < n; i++) tx.queue.push({ bytes: copy.subarray(i * FRAG, (i + 1) * FRAG), flags: appChan | (i === 0 ? B : 0) | (i === n - 1 ? E : 0) });
|
|
2284
2392
|
tx.qBytes += copy.length;
|
|
2393
|
+
tx.unsent += copy.length;
|
|
2394
|
+
tx.cost += c;
|
|
2285
2395
|
tx.msgs++;
|
|
2286
2396
|
pump(dst, rec);
|
|
2287
2397
|
return true;
|
|
@@ -2311,7 +2421,7 @@ function reliable({
|
|
|
2311
2421
|
if (kind & 1) {
|
|
2312
2422
|
if (payload.length < o + DATAH) return bad("data");
|
|
2313
2423
|
const seq = v.getUint32(o + 4), una = v.getUint32(o + 8), flags = payload[o + 12], bytes = payload.subarray(o + DATAH);
|
|
2314
|
-
if (flags & 192 || (flags & 15) >
|
|
2424
|
+
if (flags & 192 || (flags & 15) > 14 || bytes.length > FRAG || d32(seq, una) >= W) return bad("data");
|
|
2315
2425
|
data = { sid: v.getUint32(o), seq, una, flags, bytes };
|
|
2316
2426
|
}
|
|
2317
2427
|
let rec = peers.get(src);
|
|
@@ -2342,8 +2452,13 @@ function reliable({
|
|
|
2342
2452
|
// than the one we talk to: it restarted, so drop the old one's state now
|
|
2343
2453
|
// rather than when our retransmissions (paced by RTO backoff) reach it.
|
|
2344
2454
|
peerIncarnation(peer, pinc) {
|
|
2345
|
-
|
|
2455
|
+
const was = meshInc.get(peer) ?? 0;
|
|
2456
|
+
if (!(pinc <= was)) meshInc.set(peer, pinc);
|
|
2346
2457
|
const rec = peers.get(peer);
|
|
2458
|
+
if (!rec && was && pinc > was) {
|
|
2459
|
+
onReset?.(peer);
|
|
2460
|
+
return;
|
|
2461
|
+
}
|
|
2347
2462
|
if (rec && !rec.inc) {
|
|
2348
2463
|
rec.inc = pinc;
|
|
2349
2464
|
return;
|
|
@@ -2374,6 +2489,11 @@ function reliable({
|
|
|
2374
2489
|
}
|
|
2375
2490
|
return { peers: peers.size, tx, rx, queued, inflight, txBytes, rxPackets, rxBytes, timers, ...stats };
|
|
2376
2491
|
},
|
|
2492
|
+
// bytes queued for a peer and not yet acknowledged; of them, not yet sent: what a new message waits behind
|
|
2493
|
+
// (the stream layer feeds while that is below a low-water mark, so the window stays full)
|
|
2494
|
+
queued: (peer) => peers.get(peer)?.tx?.qBytes ?? 0,
|
|
2495
|
+
unsent: (peer) => peers.get(peer)?.tx?.unsent ?? 0,
|
|
2496
|
+
inc: (peer) => peers.get(peer)?.inc || null,
|
|
2377
2497
|
rtt: (peer) => {
|
|
2378
2498
|
const r = peers.get(peer)?.rtt;
|
|
2379
2499
|
return r && r.srtt !== null ? { srtt: r.srtt, rttvar: r.var, rto: peers.get(peer).tx?.rto } : null;
|
|
@@ -2381,6 +2501,395 @@ function reliable({
|
|
|
2381
2501
|
};
|
|
2382
2502
|
}
|
|
2383
2503
|
|
|
2504
|
+
// core/peer-hold.js
|
|
2505
|
+
function peerHold({ holdMs = 2e3 } = {}) {
|
|
2506
|
+
if (!(holdMs >= 0)) throw new RangeError("peerHold: holdMs must be ≥ 0");
|
|
2507
|
+
const known = /* @__PURE__ */ new Set(), since = /* @__PURE__ */ new Map(), gone = /* @__PURE__ */ new Map();
|
|
2508
|
+
return {
|
|
2509
|
+
gone(peer, now) {
|
|
2510
|
+
gone.set(peer, now);
|
|
2511
|
+
},
|
|
2512
|
+
tick(reachable, now) {
|
|
2513
|
+
const up = [], down = [];
|
|
2514
|
+
for (const p of reachable) {
|
|
2515
|
+
since.delete(p);
|
|
2516
|
+
if (!known.has(p)) {
|
|
2517
|
+
known.add(p);
|
|
2518
|
+
up.push(p);
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
for (const p of known) {
|
|
2522
|
+
if (reachable.has(p)) continue;
|
|
2523
|
+
if (!since.has(p)) since.set(p, now);
|
|
2524
|
+
if (gone.has(p) && now - gone.get(p) < holdMs || now - since.get(p) >= holdMs) down.push(p);
|
|
2525
|
+
}
|
|
2526
|
+
for (const p of down) {
|
|
2527
|
+
known.delete(p);
|
|
2528
|
+
since.delete(p);
|
|
2529
|
+
gone.delete(p);
|
|
2530
|
+
}
|
|
2531
|
+
for (const [p, t] of gone) if (now - t >= holdMs) gone.delete(p);
|
|
2532
|
+
return { up, down };
|
|
2533
|
+
},
|
|
2534
|
+
known: () => new Set(known)
|
|
2535
|
+
};
|
|
2536
|
+
}
|
|
2537
|
+
|
|
2538
|
+
// core/stream.js
|
|
2539
|
+
var STREAM_CHAN = 14;
|
|
2540
|
+
var K = { OPEN: 1, ACCEPT: 2, REFUSE: 3, DATA: 4, END: 5, ABORT: 6, CREDIT: 7, CANCEL: 8 };
|
|
2541
|
+
var enc4 = new TextEncoder();
|
|
2542
|
+
var dec2 = new TextDecoder();
|
|
2543
|
+
var MAX_META = 4096;
|
|
2544
|
+
var MAX_REASON = 200;
|
|
2545
|
+
var cut = (s, n) => {
|
|
2546
|
+
const b = enc4.encode(String(s ?? ""));
|
|
2547
|
+
return b.length <= n ? b : b.subarray(0, n);
|
|
2548
|
+
};
|
|
2549
|
+
var u48 = (v, b, o) => {
|
|
2550
|
+
const d = new DataView(b.buffer, b.byteOffset);
|
|
2551
|
+
d.setUint16(o, Math.floor(v / 2 ** 32));
|
|
2552
|
+
d.setUint32(o + 2, v % 2 ** 32);
|
|
2553
|
+
};
|
|
2554
|
+
var r48 = (b, o) => {
|
|
2555
|
+
const d = new DataView(b.buffer, b.byteOffset, b.byteLength);
|
|
2556
|
+
return d.getUint16(o) * 2 ** 32 + d.getUint32(o + 2);
|
|
2557
|
+
};
|
|
2558
|
+
function streams({
|
|
2559
|
+
send,
|
|
2560
|
+
queued,
|
|
2561
|
+
now,
|
|
2562
|
+
setTimer,
|
|
2563
|
+
clearTimer,
|
|
2564
|
+
onOpen,
|
|
2565
|
+
onAccepted,
|
|
2566
|
+
onCredit,
|
|
2567
|
+
onDone,
|
|
2568
|
+
onPending,
|
|
2569
|
+
onData,
|
|
2570
|
+
onEnd,
|
|
2571
|
+
onError,
|
|
2572
|
+
metric: metric2 = () => {
|
|
2573
|
+
},
|
|
2574
|
+
window: WIN2 = 1 << 20,
|
|
2575
|
+
maxIn = 8,
|
|
2576
|
+
chunk = 16384,
|
|
2577
|
+
lowWater = 64 * 1024,
|
|
2578
|
+
creditMs = 100,
|
|
2579
|
+
openMs = 3e4,
|
|
2580
|
+
maxCtl = 256
|
|
2581
|
+
}) {
|
|
2582
|
+
const out2 = /* @__PURE__ */ new Map(), inn = /* @__PURE__ */ new Map();
|
|
2583
|
+
let ids = 0;
|
|
2584
|
+
const key = (peer, id) => `${peer}:${id}`;
|
|
2585
|
+
function frame(kind, id, extra = 0) {
|
|
2586
|
+
const b = new Uint8Array(5 + extra);
|
|
2587
|
+
b[0] = kind;
|
|
2588
|
+
new DataView(b.buffer).setUint32(1, id);
|
|
2589
|
+
return b;
|
|
2590
|
+
}
|
|
2591
|
+
const ctl = /* @__PURE__ */ new Map();
|
|
2592
|
+
function sendCtl(peer, b) {
|
|
2593
|
+
let q = ctl.get(peer);
|
|
2594
|
+
if (!q?.length && send(peer, b)) return;
|
|
2595
|
+
q ??= ctl.set(peer, []).get(peer);
|
|
2596
|
+
if (q.length >= maxCtl) {
|
|
2597
|
+
if (b[0] === K.REFUSE) return metric2("streamCtlFull", peer);
|
|
2598
|
+
if (b[0] === K.CREDIT) {
|
|
2599
|
+
const i = q.findIndex((x) => x[0] === K.CREDIT && x[1] === b[1] && x[2] === b[2] && x[3] === b[3] && x[4] === b[4]);
|
|
2600
|
+
if (i >= 0) {
|
|
2601
|
+
q[i] = b;
|
|
2602
|
+
return;
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
q.push(b);
|
|
2607
|
+
}
|
|
2608
|
+
function flushCtl(peer) {
|
|
2609
|
+
const q = ctl.get(peer);
|
|
2610
|
+
while (q?.length && send(peer, q[0])) q.shift();
|
|
2611
|
+
if (q && !q.length) ctl.delete(peer);
|
|
2612
|
+
}
|
|
2613
|
+
function pump(peer) {
|
|
2614
|
+
flushCtl(peer);
|
|
2615
|
+
const mine = [...out2.values()].filter((s) => s.peer === peer && s.accepted && !s.failed), was = mine.map((s) => s.pending);
|
|
2616
|
+
try {
|
|
2617
|
+
feed(peer, mine);
|
|
2618
|
+
} finally {
|
|
2619
|
+
mine.forEach((s, i) => {
|
|
2620
|
+
if (s.pending < was[i] && !s.failed) onPending?.(peer, s.id, s.pending);
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
}
|
|
2624
|
+
function feed(peer, mine) {
|
|
2625
|
+
let progress = true;
|
|
2626
|
+
while (progress) {
|
|
2627
|
+
progress = false;
|
|
2628
|
+
for (const s of mine) {
|
|
2629
|
+
if (queued(peer) >= lowWater) return;
|
|
2630
|
+
const room = s.read + WIN2 - s.sent, n = Math.min(chunk, s.buf.length ? s.buf[0].length - s.off : 0, room);
|
|
2631
|
+
if (n > 0) {
|
|
2632
|
+
const b = frame(K.DATA, s.id, n);
|
|
2633
|
+
b.set(s.buf[0].subarray(s.off, s.off + n), 5);
|
|
2634
|
+
if (!send(peer, b)) return;
|
|
2635
|
+
s.sent += n;
|
|
2636
|
+
s.off += n;
|
|
2637
|
+
s.pending -= n;
|
|
2638
|
+
if (s.off === s.buf[0].length) {
|
|
2639
|
+
s.buf.shift();
|
|
2640
|
+
s.off = 0;
|
|
2641
|
+
}
|
|
2642
|
+
progress = true;
|
|
2643
|
+
}
|
|
2644
|
+
if (s.closing && !s.pending && !s.endSent) {
|
|
2645
|
+
const b = frame(K.END, s.id, 6);
|
|
2646
|
+
u48(s.sent, b, 5);
|
|
2647
|
+
if (!send(peer, b)) return;
|
|
2648
|
+
s.endSent = true;
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
function failOut(s, code, reason) {
|
|
2654
|
+
if (s.failed) return;
|
|
2655
|
+
s.failed = true;
|
|
2656
|
+
clearTimer(s.openTimer);
|
|
2657
|
+
out2.delete(key(s.peer, s.id));
|
|
2658
|
+
onError?.(s.peer, s.id, "out", code, { reason, delivered: s.read });
|
|
2659
|
+
}
|
|
2660
|
+
function failIn(s, code, reason) {
|
|
2661
|
+
if (s.failed) return;
|
|
2662
|
+
s.failed = true;
|
|
2663
|
+
clearTimer(s.creditTimer);
|
|
2664
|
+
inn.delete(key(s.peer, s.id));
|
|
2665
|
+
onError?.(s.peer, s.id, "in", code, { reason, delivered: s.read });
|
|
2666
|
+
}
|
|
2667
|
+
function credit(s, force = false) {
|
|
2668
|
+
const fin = s.ended && s.read === s.total;
|
|
2669
|
+
if (s.failed || s.read === s.credited && !fin) return;
|
|
2670
|
+
if (!force && !fin && s.read - s.credited < WIN2 / 4) {
|
|
2671
|
+
if (!s.creditTimer) s.creditTimer = setTimer(creditMs, () => {
|
|
2672
|
+
s.creditTimer = null;
|
|
2673
|
+
credit(s, true);
|
|
2674
|
+
});
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
clearTimer(s.creditTimer);
|
|
2678
|
+
s.creditTimer = null;
|
|
2679
|
+
const b = frame(K.CREDIT, s.id, 6);
|
|
2680
|
+
u48(s.read, b, 5);
|
|
2681
|
+
s.credited = s.read;
|
|
2682
|
+
sendCtl(s.peer, b);
|
|
2683
|
+
if (fin) {
|
|
2684
|
+
inn.delete(key(s.peer, s.id));
|
|
2685
|
+
s.done = true;
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
function cancel(peer, id, reason) {
|
|
2689
|
+
const s = inn.get(key(peer, id));
|
|
2690
|
+
if (!s) return;
|
|
2691
|
+
const r = cut(reason, MAX_REASON), b = frame(K.CANCEL, id, 6 + r.length);
|
|
2692
|
+
u48(s.read, b, 5);
|
|
2693
|
+
b.set(r, 11);
|
|
2694
|
+
s.failed = true;
|
|
2695
|
+
clearTimer(s.creditTimer);
|
|
2696
|
+
inn.delete(key(peer, id));
|
|
2697
|
+
sendCtl(peer, b);
|
|
2698
|
+
}
|
|
2699
|
+
return {
|
|
2700
|
+
// → the new stream's id; data may be written at once and leaves after ACCEPT
|
|
2701
|
+
open(peer, { channel = 0, meta } = {}) {
|
|
2702
|
+
const m = meta === void 0 ? new Uint8Array(0) : enc4.encode(JSON.stringify(meta));
|
|
2703
|
+
if (m.length > MAX_META) throw new RangeError(`stream meta: ${m.length} bytes as JSON > ${MAX_META}`);
|
|
2704
|
+
if (!(Number.isInteger(channel) && channel >= 0 && channel <= 13)) throw new RangeError("stream channel must be 0…13");
|
|
2705
|
+
const id = (ids = ids + 1 >>> 0) || (ids = 1);
|
|
2706
|
+
const s = { peer, id, accepted: false, failed: false, buf: [], off: 0, pending: 0, sent: 0, read: 0, closing: false, endSent: false };
|
|
2707
|
+
out2.set(key(peer, id), s);
|
|
2708
|
+
s.openTimer = setTimer(openMs, () => {
|
|
2709
|
+
if (!s.accepted && !s.failed) failOut(s, "timeout");
|
|
2710
|
+
});
|
|
2711
|
+
const b = frame(K.OPEN, id, 1 + m.length);
|
|
2712
|
+
b[5] = channel;
|
|
2713
|
+
b.set(m, 6);
|
|
2714
|
+
sendCtl(peer, b);
|
|
2715
|
+
return id;
|
|
2716
|
+
},
|
|
2717
|
+
// queue bytes on a stream of ours; → the bytes it holds unsent (the page's write waits while that is high)
|
|
2718
|
+
write(peer, id, bytes) {
|
|
2719
|
+
const s = out2.get(key(peer, id));
|
|
2720
|
+
if (!s || s.closing) return -1;
|
|
2721
|
+
if (bytes.length) {
|
|
2722
|
+
s.buf.push(bytes.slice());
|
|
2723
|
+
s.pending += bytes.length;
|
|
2724
|
+
}
|
|
2725
|
+
if (s.accepted) pump(peer);
|
|
2726
|
+
return s.pending;
|
|
2727
|
+
},
|
|
2728
|
+
pending: (peer, id) => out2.get(key(peer, id))?.pending ?? -1,
|
|
2729
|
+
close(peer, id) {
|
|
2730
|
+
const s = out2.get(key(peer, id));
|
|
2731
|
+
if (!s) return;
|
|
2732
|
+
s.closing = true;
|
|
2733
|
+
if (s.accepted) pump(peer);
|
|
2734
|
+
},
|
|
2735
|
+
abort(peer, id, reason) {
|
|
2736
|
+
const s = out2.get(key(peer, id));
|
|
2737
|
+
if (!s) return;
|
|
2738
|
+
const r = cut(reason, MAX_REASON), b = frame(K.ABORT, id, r.length);
|
|
2739
|
+
b.set(r, 5);
|
|
2740
|
+
s.failed = true;
|
|
2741
|
+
clearTimer(s.openTimer);
|
|
2742
|
+
out2.delete(key(peer, id));
|
|
2743
|
+
sendCtl(peer, b);
|
|
2744
|
+
},
|
|
2745
|
+
// the receiving app took n more bytes of an incoming stream
|
|
2746
|
+
read(peer, id, n) {
|
|
2747
|
+
const s = inn.get(key(peer, id));
|
|
2748
|
+
if (!s) return;
|
|
2749
|
+
s.read += n;
|
|
2750
|
+
credit(s, s.ended && s.read === s.total);
|
|
2751
|
+
},
|
|
2752
|
+
cancel,
|
|
2753
|
+
// the peer's reliable queue has room again
|
|
2754
|
+
freed(peer) {
|
|
2755
|
+
pump(peer);
|
|
2756
|
+
},
|
|
2757
|
+
// every reliable message on STREAM_CHAN from peer
|
|
2758
|
+
onPacket(peer, b) {
|
|
2759
|
+
if (!(b instanceof Uint8Array) || b.length < 5) return metric2("streamBad", "short");
|
|
2760
|
+
const kind = b[0], id = new DataView(b.buffer, b.byteOffset, b.byteLength).getUint32(1), body = b.subarray(5), k = key(peer, id);
|
|
2761
|
+
switch (kind) {
|
|
2762
|
+
case K.OPEN: {
|
|
2763
|
+
if (body.length < 1) return metric2("streamBad", "open");
|
|
2764
|
+
if (inn.has(k)) {
|
|
2765
|
+
metric2("streamReopen", { peer, id });
|
|
2766
|
+
for (const s2 of [...inn.values()]) if (s2.peer === peer) failIn(s2, "peer_restarted");
|
|
2767
|
+
for (const s2 of [...out2.values()]) if (s2.peer === peer) failOut(s2, "peer_restarted");
|
|
2768
|
+
}
|
|
2769
|
+
if ((ctl.get(peer)?.length ?? 0) >= maxCtl) return metric2("streamCtlFull", peer);
|
|
2770
|
+
let meta;
|
|
2771
|
+
try {
|
|
2772
|
+
meta = body.length > 1 ? JSON.parse(dec2.decode(body.subarray(1))) : void 0;
|
|
2773
|
+
} catch {
|
|
2774
|
+
return metric2("streamBad", "meta");
|
|
2775
|
+
}
|
|
2776
|
+
const open2 = [...inn.values()].filter((s2) => s2.peer === peer).length;
|
|
2777
|
+
const s = { peer, id, read: 0, credited: 0, got: 0, ended: false, total: null, failed: false, creditTimer: null };
|
|
2778
|
+
if (open2 >= maxIn || body[0] > 13) {
|
|
2779
|
+
sendCtl(peer, frame(K.REFUSE, id));
|
|
2780
|
+
return metric2("streamRefused", { peer, open: open2 });
|
|
2781
|
+
}
|
|
2782
|
+
inn.set(k, s);
|
|
2783
|
+
let ok = false;
|
|
2784
|
+
try {
|
|
2785
|
+
ok = onOpen?.(peer, id, { channel: body[0], meta }) === true;
|
|
2786
|
+
} catch {
|
|
2787
|
+
}
|
|
2788
|
+
if (!ok) {
|
|
2789
|
+
inn.delete(k);
|
|
2790
|
+
sendCtl(peer, frame(K.REFUSE, id));
|
|
2791
|
+
return;
|
|
2792
|
+
}
|
|
2793
|
+
sendCtl(peer, frame(K.ACCEPT, id));
|
|
2794
|
+
return;
|
|
2795
|
+
}
|
|
2796
|
+
case K.DATA: {
|
|
2797
|
+
const s = inn.get(k);
|
|
2798
|
+
if (!s || s.ended) return;
|
|
2799
|
+
s.got += body.length;
|
|
2800
|
+
if (s.got > s.read + WIN2) {
|
|
2801
|
+
metric2("streamBad", "credit");
|
|
2802
|
+
onError?.(peer, id, "in", "aborted", { reason: "over credit", delivered: s.read });
|
|
2803
|
+
return cancel(peer, id, "over credit");
|
|
2804
|
+
}
|
|
2805
|
+
onData?.(peer, id, body.slice());
|
|
2806
|
+
return;
|
|
2807
|
+
}
|
|
2808
|
+
case K.END: {
|
|
2809
|
+
const s = inn.get(k);
|
|
2810
|
+
if (!s || body.length < 6) return;
|
|
2811
|
+
s.ended = true;
|
|
2812
|
+
s.total = r48(body, 0);
|
|
2813
|
+
if (s.total !== s.got) {
|
|
2814
|
+
metric2("streamBad", "end");
|
|
2815
|
+
onError?.(peer, id, "in", "aborted", { reason: "short", delivered: s.read });
|
|
2816
|
+
return cancel(peer, id, "short");
|
|
2817
|
+
}
|
|
2818
|
+
onEnd?.(peer, id);
|
|
2819
|
+
if (s.read === s.total) credit(s, true);
|
|
2820
|
+
return;
|
|
2821
|
+
}
|
|
2822
|
+
case K.ABORT: {
|
|
2823
|
+
const s = inn.get(k);
|
|
2824
|
+
if (!s) return;
|
|
2825
|
+
const q = ctl.get(peer);
|
|
2826
|
+
if (q) {
|
|
2827
|
+
const i = q.findIndex((x) => x[0] === K.ACCEPT && new DataView(x.buffer, x.byteOffset).getUint32(1) === id);
|
|
2828
|
+
if (i >= 0) q.splice(i, 1);
|
|
2829
|
+
}
|
|
2830
|
+
failIn(s, "aborted", dec2.decode(body));
|
|
2831
|
+
return;
|
|
2832
|
+
}
|
|
2833
|
+
case K.ACCEPT: {
|
|
2834
|
+
const s = out2.get(k);
|
|
2835
|
+
if (!s || s.accepted) return;
|
|
2836
|
+
s.accepted = true;
|
|
2837
|
+
clearTimer(s.openTimer);
|
|
2838
|
+
onAccepted?.(peer, id);
|
|
2839
|
+
pump(peer);
|
|
2840
|
+
return;
|
|
2841
|
+
}
|
|
2842
|
+
case K.REFUSE: {
|
|
2843
|
+
const s = out2.get(k);
|
|
2844
|
+
if (s) failOut(s, "refused");
|
|
2845
|
+
return;
|
|
2846
|
+
}
|
|
2847
|
+
case K.CREDIT: {
|
|
2848
|
+
const s = out2.get(k);
|
|
2849
|
+
if (!s || body.length < 6) return;
|
|
2850
|
+
const r = r48(body, 0);
|
|
2851
|
+
if (r > s.sent || r < s.read) return metric2("streamBad", "credit");
|
|
2852
|
+
s.read = r;
|
|
2853
|
+
onCredit?.(peer, id, r);
|
|
2854
|
+
if (s.endSent && r === s.sent) {
|
|
2855
|
+
out2.delete(k);
|
|
2856
|
+
onDone?.(peer, id);
|
|
2857
|
+
return;
|
|
2858
|
+
}
|
|
2859
|
+
pump(peer);
|
|
2860
|
+
return;
|
|
2861
|
+
}
|
|
2862
|
+
case K.CANCEL: {
|
|
2863
|
+
const s = out2.get(k);
|
|
2864
|
+
if (!s || body.length < 6) return;
|
|
2865
|
+
const r = r48(body, 0);
|
|
2866
|
+
if (r >= s.read && r <= s.sent) s.read = r;
|
|
2867
|
+
failOut(s, "cancelled", dec2.decode(body.subarray(6)));
|
|
2868
|
+
return;
|
|
2869
|
+
}
|
|
2870
|
+
default:
|
|
2871
|
+
return metric2("streamBad", "kind");
|
|
2872
|
+
}
|
|
2873
|
+
},
|
|
2874
|
+
// the reliable layer gave up on this peer, or it restarted, or it left: every stream with it ends
|
|
2875
|
+
peerGone(peer, code) {
|
|
2876
|
+
ctl.delete(peer);
|
|
2877
|
+
for (const s of [...out2.values()]) if (s.peer === peer) failOut(s, code);
|
|
2878
|
+
for (const s of [...inn.values()]) if (s.peer === peer) failIn(s, code);
|
|
2879
|
+
},
|
|
2880
|
+
// the peers we have streams with (the worker times their absence: 30 s unreachable ends them, 'timeout')
|
|
2881
|
+
peers() {
|
|
2882
|
+
const p = /* @__PURE__ */ new Set();
|
|
2883
|
+
for (const s of out2.values()) p.add(s.peer);
|
|
2884
|
+
for (const s of inn.values()) p.add(s.peer);
|
|
2885
|
+
return p;
|
|
2886
|
+
},
|
|
2887
|
+
state() {
|
|
2888
|
+
return { out: out2.size, in: inn.size, ctl: [...ctl.values()].reduce((a, q) => a + q.length, 0) };
|
|
2889
|
+
}
|
|
2890
|
+
};
|
|
2891
|
+
}
|
|
2892
|
+
|
|
2384
2893
|
// client/worker.js
|
|
2385
2894
|
var b64 = (u8) => btoa(String.fromCharCode(...u8));
|
|
2386
2895
|
var unb64 = (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
|
|
@@ -2395,7 +2904,21 @@ var suspended = false;
|
|
|
2395
2904
|
var internals = {};
|
|
2396
2905
|
var pending = [];
|
|
2397
2906
|
var out = (m, t) => self.postMessage(m, t ?? []);
|
|
2398
|
-
var
|
|
2907
|
+
var RELAY_RATE = 425e3;
|
|
2908
|
+
var pacedPeers = /* @__PURE__ */ new Set();
|
|
2909
|
+
var STREAM_HIGH = 256 * 1024;
|
|
2910
|
+
var STREAM_GONE_MS = 3e4;
|
|
2911
|
+
var swait = /* @__PURE__ */ new Map();
|
|
2912
|
+
var goneSince = /* @__PURE__ */ new Map();
|
|
2913
|
+
var st = null;
|
|
2914
|
+
var streamListen = false;
|
|
2915
|
+
var leftAt = /* @__PURE__ */ new Map();
|
|
2916
|
+
var hold = peerHold({ holdMs: 2e3 });
|
|
2917
|
+
var GONE = /* @__PURE__ */ new Set(["bye", "keepaliveDead", "evictedPeer"]);
|
|
2918
|
+
var metric = (name, value) => {
|
|
2919
|
+
if (GONE.has(name) && Number.isInteger(value)) hold.gone(value, Date.now());
|
|
2920
|
+
out({ op: "metric", name, value });
|
|
2921
|
+
};
|
|
2399
2922
|
self.onmessage = (e) => {
|
|
2400
2923
|
const m = e.data;
|
|
2401
2924
|
if (m.op === "keygen") return keygen();
|
|
@@ -2479,6 +3002,7 @@ async function init({ id, inc, key, room, server, near: nr, token, tokenKeys, re
|
|
|
2479
3002
|
helloMs: 250,
|
|
2480
3003
|
suspectK: 2,
|
|
2481
3004
|
deadMs: 2e4,
|
|
3005
|
+
caps: CAPS.WIDE_WINDOW | CAPS.STREAM,
|
|
2482
3006
|
target,
|
|
2483
3007
|
max,
|
|
2484
3008
|
onDeliver: (src, payload, hops, chan, _env, bcast) => {
|
|
@@ -2501,9 +3025,53 @@ async function init({ id, inc, key, room, server, near: nr, token, tokenKeys, re
|
|
|
2501
3025
|
setTimer: env.setTimer,
|
|
2502
3026
|
clearTimer: env.clearTimer,
|
|
2503
3027
|
metric,
|
|
2504
|
-
|
|
2505
|
-
|
|
3028
|
+
maxRate: (peer) => pacedPeers.has(peer) ? RELAY_RATE : null,
|
|
3029
|
+
// 1.2: a window of 255 to a peer whose LSA says it takes one (CAPS.WIDE_WINDOW), else 64; 64 again after a loss
|
|
3030
|
+
window: 255,
|
|
3031
|
+
peerWindow: (peer) => (h.api.lsa(peer)?.caps ?? 0) & CAPS.WIDE_WINDOW ? 255 : 64,
|
|
3032
|
+
onMessage: (src, data, chan) => chan === STREAM_CHAN ? st.onPacket(src, data) : out({ op: "message", from: src, data, chan, broadcast: false, reliable: true }, [data.buffer]),
|
|
3033
|
+
onGiveUp: (peer, n, why) => {
|
|
3034
|
+
st.peerGone(peer, why === "reset" ? "peer_restarted" : "timeout");
|
|
3035
|
+
out({ op: "undelivered", peer, n, why });
|
|
3036
|
+
},
|
|
3037
|
+
onFreed: (peer) => st.freed(peer),
|
|
3038
|
+
onReset: (peer) => st.peerGone(peer, "peer_restarted")
|
|
3039
|
+
});
|
|
3040
|
+
st = streams({
|
|
3041
|
+
send: (d, b) => rel.send(d, b, STREAM_CHAN),
|
|
3042
|
+
queued: (d) => rel.unsent(d),
|
|
3043
|
+
now: env.now,
|
|
3044
|
+
setTimer: env.setTimer,
|
|
3045
|
+
clearTimer: env.clearTimer,
|
|
3046
|
+
metric,
|
|
3047
|
+
onOpen: (peer, id2, info) => {
|
|
3048
|
+
if (!streamListen) return false;
|
|
3049
|
+
out({ op: "sopen", peer, id: id2, channel: info.channel, meta: info.meta });
|
|
3050
|
+
return true;
|
|
3051
|
+
},
|
|
3052
|
+
onAccepted: (peer, id2) => out({ op: "sacc", peer, id: id2 }),
|
|
3053
|
+
onCredit: (peer, id2, read) => out({ op: "scredit", peer, id: id2, read }),
|
|
3054
|
+
onDone: (peer, id2) => out({ op: "sdone", peer, id: id2 }),
|
|
3055
|
+
onPending: (peer, id2, pending2) => {
|
|
3056
|
+
const k = `${peer}:${id2}`, w = swait.get(k);
|
|
3057
|
+
if (w && pending2 < STREAM_HIGH) {
|
|
3058
|
+
swait.delete(k);
|
|
3059
|
+
out({ op: "swrote", mid: w });
|
|
3060
|
+
}
|
|
3061
|
+
},
|
|
3062
|
+
onData: (peer, id2, data) => out({ op: "sdata", peer, id: id2, data }, [data.buffer]),
|
|
3063
|
+
onEnd: (peer, id2) => out({ op: "sfin", peer, id: id2 }),
|
|
3064
|
+
onError: (peer, id2, side, code, { reason, delivered }) => {
|
|
3065
|
+
const k = `${peer}:${id2}`, w = swait.get(k);
|
|
3066
|
+
swait.delete(k);
|
|
3067
|
+
out({ op: "serr", peer, id: id2, side, code, reason, delivered, mid: w });
|
|
3068
|
+
}
|
|
2506
3069
|
});
|
|
3070
|
+
const linkDown = h.onLinkDown;
|
|
3071
|
+
h.onLinkDown = (peer, why) => {
|
|
3072
|
+
if (why === "closed") hold.gone(peer, Date.now());
|
|
3073
|
+
linkDown(peer, why);
|
|
3074
|
+
};
|
|
2507
3075
|
env.attach(h);
|
|
2508
3076
|
h.start();
|
|
2509
3077
|
out({ op: "state", s: "joining" });
|
|
@@ -2558,15 +3126,35 @@ async function init({ id, inc, key, room, server, near: nr, token, tokenKeys, re
|
|
|
2558
3126
|
}, 3e4);
|
|
2559
3127
|
pending.splice(0).forEach(handle);
|
|
2560
3128
|
}
|
|
2561
|
-
var known = /* @__PURE__ */ new Set();
|
|
2562
3129
|
var holding = false;
|
|
2563
3130
|
var connected = false;
|
|
2564
3131
|
function peerWatch() {
|
|
2565
3132
|
if (stopped) return;
|
|
2566
|
-
const now =
|
|
2567
|
-
for (const p of
|
|
2568
|
-
|
|
2569
|
-
|
|
3133
|
+
const t = Date.now(), table = h.api.table().dist;
|
|
3134
|
+
for (const [p, l] of leftAt) if (t - l.at > 1e4 || !table.has(p) && l.reported || (h.api.lsa(p)?.inc ?? 0) > l.inc) leftAt.delete(p);
|
|
3135
|
+
const now = new Set([...table.keys()].filter((x) => x !== env.id && !leftAt.has(x)));
|
|
3136
|
+
const { up, down } = hold.tick(now, t);
|
|
3137
|
+
if (st) {
|
|
3138
|
+
const live = st.peers();
|
|
3139
|
+
for (const p of [...goneSince.keys()]) if (!live.has(p)) goneSince.delete(p);
|
|
3140
|
+
}
|
|
3141
|
+
if (st) for (const p of st.peers()) {
|
|
3142
|
+
if (now.has(p)) {
|
|
3143
|
+
goneSince.delete(p);
|
|
3144
|
+
continue;
|
|
3145
|
+
}
|
|
3146
|
+
if (!goneSince.has(p)) goneSince.set(p, t);
|
|
3147
|
+
else if (t - goneSince.get(p) >= STREAM_GONE_MS) {
|
|
3148
|
+
goneSince.delete(p);
|
|
3149
|
+
st.peerGone(p, "timeout");
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
for (const p of up) out({ op: "peer", id: p, up: true });
|
|
3153
|
+
for (const p of down) {
|
|
3154
|
+
const l = leftAt.get(p);
|
|
3155
|
+
if (l) l.reported = true;
|
|
3156
|
+
out({ op: "peer", id: p, up: false, why: l ? "left" : "lost" });
|
|
3157
|
+
}
|
|
2570
3158
|
const c = h.api.live().length > 0;
|
|
2571
3159
|
if (c !== connected && !byeSent) {
|
|
2572
3160
|
connected = c;
|
|
@@ -2595,6 +3183,15 @@ function handle(m) {
|
|
|
2595
3183
|
if (s.type === "signal") env.cloudIn(s.from, s.kind, unb64(s.blob));
|
|
2596
3184
|
else if (s.type === "superseded") h.onSuperseded(s.inc);
|
|
2597
3185
|
else if (s.type === "evict") h.api.notice(unb64(s.notice));
|
|
3186
|
+
else if (s.type === "left") {
|
|
3187
|
+
const known = h.api.lsa(s.id)?.inc ?? rel?.inc(s.id) ?? null;
|
|
3188
|
+
if (!(known > s.inc)) {
|
|
3189
|
+
leftAt.set(s.id, { at: Date.now(), inc: s.inc });
|
|
3190
|
+
hold.gone(s.id, Date.now());
|
|
3191
|
+
st?.peerGone(s.id, "left");
|
|
3192
|
+
peerWatch();
|
|
3193
|
+
}
|
|
3194
|
+
}
|
|
2598
3195
|
return;
|
|
2599
3196
|
}
|
|
2600
3197
|
case "send":
|
|
@@ -2605,6 +3202,34 @@ function handle(m) {
|
|
|
2605
3202
|
return h.api.ping(m.to, (r) => out({ op: "pong", mid: m.mid, r: r && { rtt: r.rtt, hops: r.hops, clock: r.wall } }));
|
|
2606
3203
|
case "reliable":
|
|
2607
3204
|
return out({ op: "queued", mid: m.mid, ok: rel.send(m.to, m.data, m.chan) });
|
|
3205
|
+
// 1.2 streams: the page's openStream() and 'stream' listener
|
|
3206
|
+
case "slisten":
|
|
3207
|
+
streamListen = !!m.on;
|
|
3208
|
+
return;
|
|
3209
|
+
case "sopen": {
|
|
3210
|
+
if (!h.api.table().dist.has(m.to)) return out({ op: "sopened", mid: m.mid, err: "unreachable" });
|
|
3211
|
+
if (!((h.api.lsa(m.to)?.caps ?? 0) & CAPS.STREAM)) return out({ op: "sopened", mid: m.mid, err: "unsupported" });
|
|
3212
|
+
try {
|
|
3213
|
+
return out({ op: "sopened", mid: m.mid, id: st.open(m.to, { channel: m.chan, meta: m.meta }) });
|
|
3214
|
+
} catch (e) {
|
|
3215
|
+
return out({ op: "sopened", mid: m.mid, err: "bad", message: String(e?.message ?? e) });
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
case "swrite": {
|
|
3219
|
+
const p = st.write(m.peer, m.id, m.data);
|
|
3220
|
+
if (p < 0) return out({ op: "swrote", mid: m.mid, gone: true });
|
|
3221
|
+
if (p < STREAM_HIGH) return out({ op: "swrote", mid: m.mid });
|
|
3222
|
+
swait.set(`${m.peer}:${m.id}`, m.mid);
|
|
3223
|
+
return;
|
|
3224
|
+
}
|
|
3225
|
+
case "sclose":
|
|
3226
|
+
return st.close(m.peer, m.id);
|
|
3227
|
+
case "sabort":
|
|
3228
|
+
return st.abort(m.peer, m.id, m.reason);
|
|
3229
|
+
case "sread":
|
|
3230
|
+
return st.read(m.peer, m.id, m.n);
|
|
3231
|
+
case "scancel":
|
|
3232
|
+
return st.cancel(m.peer, m.id, m.reason);
|
|
2608
3233
|
case "leave": {
|
|
2609
3234
|
h.api.bye();
|
|
2610
3235
|
env.closeAll();
|
|
@@ -2627,6 +3252,10 @@ function handle(m) {
|
|
|
2627
3252
|
if (away > WAKE_MS || byeSent || m.manual) wake(m.manual ? 1e9 : byeSent ? away : frozen);
|
|
2628
3253
|
return;
|
|
2629
3254
|
}
|
|
3255
|
+
case "pace":
|
|
3256
|
+
if (m.on) pacedPeers.add(m.peer);
|
|
3257
|
+
else pacedPeers.delete(m.peer);
|
|
3258
|
+
return metric("relayPaced", { peer: m.peer, on: !!m.on });
|
|
2630
3259
|
default:
|
|
2631
3260
|
env.fromMain(m);
|
|
2632
3261
|
}
|