@isoloop/bus 0.0.0 → 0.1.0-next.0
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/LICENSE +21 -0
- package/dist/bus-worker.js +3746 -0
- package/dist/index.d.ts +358 -0
- package/dist/index.js +1921 -0
- package/dist/standard-schema-DnJtEmJw.js +16 -0
- package/dist/testing.d.ts +28 -0
- package/dist/testing.js +98 -0
- package/dist/topic-BQbes-gX.d.ts +127 -0
- package/package.json +40 -6
- package/README.md +0 -3
|
@@ -0,0 +1,3746 @@
|
|
|
1
|
+
// ../protocol/dist/index.js
|
|
2
|
+
/** Protocol version this build speaks (`v`) and the oldest it still accepts (`min`). */
|
|
3
|
+
const PROTOCOL = {
|
|
4
|
+
v: 1,
|
|
5
|
+
min: 1
|
|
6
|
+
};
|
|
7
|
+
const isRecord$1 = (x) => typeof x === "object" && x !== null && !Array.isArray(x);
|
|
8
|
+
const isOptionalString = (x) => x === void 0 || typeof x === "string";
|
|
9
|
+
/**
|
|
10
|
+
* True for a well-formed envelope this build can read: `v` is a supported
|
|
11
|
+
* version, `t` is a string, `id`/`re`/`isolate` are absent or strings, and `p`
|
|
12
|
+
* is present.
|
|
13
|
+
* Says nothing about whether `t` is known; see the per-port guards.
|
|
14
|
+
*/
|
|
15
|
+
function isEnvelope(x) {
|
|
16
|
+
return isRecord$1(x) && x["v"] === PROTOCOL.v && typeof x["t"] === "string" && "p" in x && isOptionalString(x["id"]) && isOptionalString(x["re"]) && isOptionalString(x["isolate"]);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Builds a guard for one port's union from its message types. Each side drops
|
|
20
|
+
* (and counts) envelopes with an unknown `v` or `t` (design §3), so a guard
|
|
21
|
+
* only checks the envelope and the type, not the payload.
|
|
22
|
+
*/
|
|
23
|
+
function envelopeGuard(types) {
|
|
24
|
+
return (x) => isEnvelope(x) && Object.hasOwn(types, x.t);
|
|
25
|
+
}
|
|
26
|
+
/** Topics under this prefix belong to the kernel (ADR 0002). */
|
|
27
|
+
const SYSTEM_TOPIC_PREFIX = "isoloop.";
|
|
28
|
+
function isSystemTopic(topic) {
|
|
29
|
+
return topic.startsWith(SYSTEM_TOPIC_PREFIX);
|
|
30
|
+
}
|
|
31
|
+
const escape = (s) => s.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
|
32
|
+
const compiled = /* @__PURE__ */ new Map();
|
|
33
|
+
/**
|
|
34
|
+
* True if `topic` matches the grant pattern. `*` matches one or more
|
|
35
|
+
* characters, dots included, so `catalog.*` covers `catalog.items.v1` and
|
|
36
|
+
* `cart.*.v1` covers `cart.items.v1`. Without `*` the match is exact.
|
|
37
|
+
*/
|
|
38
|
+
function matchTopic(grant, topic) {
|
|
39
|
+
if (!grant.includes("*")) return grant === topic;
|
|
40
|
+
let re = compiled.get(grant);
|
|
41
|
+
if (!re) {
|
|
42
|
+
re = new RegExp(`^${grant.split("*").map(escape).join(".+")}$`);
|
|
43
|
+
compiled.set(grant, re);
|
|
44
|
+
}
|
|
45
|
+
return re.test(topic);
|
|
46
|
+
}
|
|
47
|
+
/** True if any pattern in the list matches `topic`. */
|
|
48
|
+
function matchAny(patterns, topic) {
|
|
49
|
+
return patterns.some((p) => matchTopic(p, topic));
|
|
50
|
+
}
|
|
51
|
+
const isIsolateToBus = envelopeGuard({
|
|
52
|
+
publish: true,
|
|
53
|
+
subscribe: true,
|
|
54
|
+
unsubscribe: true,
|
|
55
|
+
commits: true,
|
|
56
|
+
request: true,
|
|
57
|
+
reply: true
|
|
58
|
+
});
|
|
59
|
+
const isHostToBus = envelopeGuard({
|
|
60
|
+
boot: true,
|
|
61
|
+
attach: true,
|
|
62
|
+
detach: true,
|
|
63
|
+
publish: true,
|
|
64
|
+
flush: true,
|
|
65
|
+
drop: true
|
|
66
|
+
});
|
|
67
|
+
/** Wraps a hand-written check as a Standard Schema that passes valid values through unchanged. */
|
|
68
|
+
function systemSchema(check) {
|
|
69
|
+
return { "~standard": {
|
|
70
|
+
version: 1,
|
|
71
|
+
vendor: "isoloop",
|
|
72
|
+
validate: (value) => {
|
|
73
|
+
const issues = check(value, []);
|
|
74
|
+
return issues.length === 0 ? { value } : { issues };
|
|
75
|
+
}
|
|
76
|
+
} };
|
|
77
|
+
}
|
|
78
|
+
/** Defines a system topic. The name must start with `isoloop.`. */
|
|
79
|
+
function systemTopic(name, def) {
|
|
80
|
+
if (!isSystemTopic(name)) throw new Error(`system topic names start with isoloop.: ${name}`);
|
|
81
|
+
return Object.freeze({
|
|
82
|
+
...def,
|
|
83
|
+
name
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
87
|
+
const issue$1 = (path, message) => [{
|
|
88
|
+
message,
|
|
89
|
+
path
|
|
90
|
+
}];
|
|
91
|
+
/** Small building blocks for hand-written checks. */
|
|
92
|
+
const checks = {
|
|
93
|
+
string: (v, path) => typeof v === "string" ? [] : issue$1(path, "expected a string"),
|
|
94
|
+
optionalString: (v, path) => v === void 0 || typeof v === "string" ? [] : issue$1(path, "expected a string or nothing"),
|
|
95
|
+
object: (fields) => (v, path) => {
|
|
96
|
+
if (!isObject(v)) return issue$1(path, "expected an object");
|
|
97
|
+
return Object.entries(fields).flatMap(([k, check]) => check(v[k], [...path, k]));
|
|
98
|
+
},
|
|
99
|
+
any: () => []
|
|
100
|
+
};
|
|
101
|
+
const stringOrNull = (v, path) => v === null || typeof v === "string" ? [] : [{
|
|
102
|
+
message: "expected a string or null",
|
|
103
|
+
path
|
|
104
|
+
}];
|
|
105
|
+
/** Every system topic, built into the bus. */
|
|
106
|
+
const SYSTEM_TOPICS = [systemTopic("isoloop.route.v1", {
|
|
107
|
+
schema: systemSchema(checks.object({
|
|
108
|
+
href: checks.string,
|
|
109
|
+
pathname: checks.string,
|
|
110
|
+
path: stringOrNull,
|
|
111
|
+
search: checks.string,
|
|
112
|
+
hash: checks.string,
|
|
113
|
+
state: checks.any
|
|
114
|
+
})),
|
|
115
|
+
retention: { kind: "compacted" }
|
|
116
|
+
})];
|
|
117
|
+
/**
|
|
118
|
+
* The structured-cloneable part of a topic, sent at `boot` and compared with
|
|
119
|
+
* the contracts module's (ADR 0003, decision 5). Host and bus both use this
|
|
120
|
+
* one function, so equal definitions always give equal configs.
|
|
121
|
+
*/
|
|
122
|
+
function topicConfigOf(t) {
|
|
123
|
+
const cfg = {
|
|
124
|
+
name: t.name,
|
|
125
|
+
retention: { ...t.retention },
|
|
126
|
+
requestable: t.reply !== void 0
|
|
127
|
+
};
|
|
128
|
+
if (t.maxRecordBytes !== void 0) cfg.maxRecordBytes = t.maxRecordBytes;
|
|
129
|
+
if (t.durability !== void 0) cfg.durability = t.durability;
|
|
130
|
+
if (t.seed !== void 0) cfg.seed = {
|
|
131
|
+
from: t.seed.from.name,
|
|
132
|
+
follow: t.seed.follow ?? false
|
|
133
|
+
};
|
|
134
|
+
return cfg;
|
|
135
|
+
}
|
|
136
|
+
// ../codec/dist/index.js
|
|
137
|
+
var __defProp = Object.defineProperty;
|
|
138
|
+
var __exportAll = (all, flags) => {
|
|
139
|
+
let target = Object.setPrototypeOf({}, null);
|
|
140
|
+
for (var name in all) __defProp(target, name, {
|
|
141
|
+
get: all[name],
|
|
142
|
+
enumerable: true
|
|
143
|
+
});
|
|
144
|
+
if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
145
|
+
return flags & 2 ? target : Object.preventExtensions(target);
|
|
146
|
+
};
|
|
147
|
+
/** Thrown by `encode` and `decode`. */
|
|
148
|
+
var CodecError = class extends Error {
|
|
149
|
+
code;
|
|
150
|
+
constructor(code, message) {
|
|
151
|
+
super(`${code}: ${message}`);
|
|
152
|
+
this.name = "CodecError";
|
|
153
|
+
this.code = code;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
var format_exports = /* @__PURE__ */ __exportAll({
|
|
157
|
+
ARRAY: () => 200,
|
|
158
|
+
ARRAYBUFFER: () => 207,
|
|
159
|
+
BIGINT: () => 202,
|
|
160
|
+
DATE: () => 204,
|
|
161
|
+
FALSE: () => 194,
|
|
162
|
+
FIXARRAY: () => 160,
|
|
163
|
+
FIXARRAY_MAX: () => 15,
|
|
164
|
+
FIXOBJECT: () => 176,
|
|
165
|
+
FIXOBJECT_MAX: () => 15,
|
|
166
|
+
FIXSTR: () => 128,
|
|
167
|
+
FIXSTR_MAX: () => 31,
|
|
168
|
+
FLOAT64: () => 198,
|
|
169
|
+
MAP: () => 205,
|
|
170
|
+
MAX_DEPTH: () => 512,
|
|
171
|
+
NBIGINT: () => 203,
|
|
172
|
+
NEG_FIXINT: () => 224,
|
|
173
|
+
NINT: () => 197,
|
|
174
|
+
NULL: () => 193,
|
|
175
|
+
OBJECT: () => 201,
|
|
176
|
+
SET: () => 206,
|
|
177
|
+
STR: () => 199,
|
|
178
|
+
TRUE: () => 195,
|
|
179
|
+
UINT: () => 196,
|
|
180
|
+
UNDEFINED: () => 192,
|
|
181
|
+
VIEW: () => 208,
|
|
182
|
+
VIEW_KINDS: () => VIEW_KINDS$2
|
|
183
|
+
});
|
|
184
|
+
/** The kind byte after VIEW is the index in this list. Append only. */
|
|
185
|
+
const VIEW_KINDS$2 = [
|
|
186
|
+
"Int8Array",
|
|
187
|
+
"Uint8Array",
|
|
188
|
+
"Uint8ClampedArray",
|
|
189
|
+
"Int16Array",
|
|
190
|
+
"Uint16Array",
|
|
191
|
+
"Int32Array",
|
|
192
|
+
"Uint32Array",
|
|
193
|
+
"Float32Array",
|
|
194
|
+
"Float64Array",
|
|
195
|
+
"BigInt64Array",
|
|
196
|
+
"BigUint64Array",
|
|
197
|
+
"DataView"
|
|
198
|
+
];
|
|
199
|
+
const { FIXSTR: FIXSTR$1, FIXARRAY: FIXARRAY$1, FIXOBJECT: FIXOBJECT$1, UNDEFINED: UNDEFINED$1, NULL: NULL$1, FALSE: FALSE$1, TRUE: TRUE$1, UINT: UINT$1, NINT: NINT$1, FLOAT64: FLOAT64$1, STR: STR$1, ARRAY: ARRAY$1, OBJECT: OBJECT$1, NEG_FIXINT, FIXSTR_MAX: FIXSTR_MAX$1, MAX_DEPTH: MAX_DEPTH$1, BIGINT: BIGINT$1, NBIGINT: NBIGINT$1, DATE: DATE$1, MAP: MAP$1, SET: SET$1, ARRAYBUFFER: ARRAYBUFFER$1, VIEW: VIEW$1, VIEW_KINDS: VIEW_KINDS$1 } = format_exports;
|
|
200
|
+
const utf8$1 = new TextDecoder("utf-8", { fatal: true });
|
|
201
|
+
let src = /* @__PURE__ */ new Uint8Array(0);
|
|
202
|
+
let pos$1 = 0;
|
|
203
|
+
let end = 0;
|
|
204
|
+
/**
|
|
205
|
+
* Decodes bytes written by `encode`. Throws a `CodecError` with code
|
|
206
|
+
* `malformed` if they're truncated, carry an unknown tag or have bytes left
|
|
207
|
+
* over.
|
|
208
|
+
*/
|
|
209
|
+
function decode(bytes) {
|
|
210
|
+
src = bytes;
|
|
211
|
+
pos$1 = 0;
|
|
212
|
+
end = bytes.length;
|
|
213
|
+
const v = read(0);
|
|
214
|
+
if (pos$1 !== end) throw new CodecError("malformed", "trailing bytes");
|
|
215
|
+
return v;
|
|
216
|
+
}
|
|
217
|
+
const f64 = /* @__PURE__ */ new Float64Array(1);
|
|
218
|
+
const f64b = new Uint8Array(f64.buffer);
|
|
219
|
+
if (!(new Uint8Array(new Uint16Array([1]).buffer)[0] === 1)) throw new Error("@isoloop/codec needs a little-endian platform");
|
|
220
|
+
const truncated = () => new CodecError("malformed", "truncated");
|
|
221
|
+
function byte() {
|
|
222
|
+
if (pos$1 >= end) throw truncated();
|
|
223
|
+
return src[pos$1++] ?? 0;
|
|
224
|
+
}
|
|
225
|
+
function varint$1() {
|
|
226
|
+
let b = byte();
|
|
227
|
+
if (b < 128) return b;
|
|
228
|
+
let n = b & 127;
|
|
229
|
+
for (let shift = 7; shift < 28; shift += 7) {
|
|
230
|
+
b = byte();
|
|
231
|
+
n |= (b & 127) << shift;
|
|
232
|
+
if (b < 128) return n;
|
|
233
|
+
}
|
|
234
|
+
let scale = 268435456;
|
|
235
|
+
for (let i = 4; i < 8; i++) {
|
|
236
|
+
b = byte();
|
|
237
|
+
n += (b & 127) * scale;
|
|
238
|
+
if (b < 128) {
|
|
239
|
+
if (n > Number.MAX_SAFE_INTEGER) break;
|
|
240
|
+
return n;
|
|
241
|
+
}
|
|
242
|
+
scale *= 128;
|
|
243
|
+
}
|
|
244
|
+
throw new CodecError("malformed", "varint out of range");
|
|
245
|
+
}
|
|
246
|
+
function float64() {
|
|
247
|
+
if (pos$1 + 8 > end) throw truncated();
|
|
248
|
+
for (let i = 0; i < 8; i++) f64b[i] = src[pos$1 + i] ?? 0;
|
|
249
|
+
pos$1 += 8;
|
|
250
|
+
return f64[0] ?? 0;
|
|
251
|
+
}
|
|
252
|
+
function read(depth) {
|
|
253
|
+
const tag = byte();
|
|
254
|
+
if (tag < FIXSTR$1) return tag;
|
|
255
|
+
if (tag < FIXARRAY$1) return string$1(tag - FIXSTR$1);
|
|
256
|
+
if (tag < FIXOBJECT$1) return array$1(tag - FIXARRAY$1, depth);
|
|
257
|
+
if (tag < UNDEFINED$1) return object$1(tag - FIXOBJECT$1, depth);
|
|
258
|
+
if (tag >= NEG_FIXINT) return tag - 256;
|
|
259
|
+
switch (tag) {
|
|
260
|
+
case FLOAT64$1: return float64();
|
|
261
|
+
case UNDEFINED$1: return;
|
|
262
|
+
case NULL$1: return null;
|
|
263
|
+
case FALSE$1: return false;
|
|
264
|
+
case TRUE$1: return true;
|
|
265
|
+
case UINT$1: return varint$1();
|
|
266
|
+
case NINT$1: return -varint$1() - 1;
|
|
267
|
+
case STR$1: return string$1(varint$1());
|
|
268
|
+
case ARRAY$1: return array$1(varint$1(), depth);
|
|
269
|
+
case OBJECT$1: return object$1(varint$1(), depth);
|
|
270
|
+
case BIGINT$1: return bigint$1();
|
|
271
|
+
case NBIGINT$1: return -bigint$1();
|
|
272
|
+
case DATE$1: return new Date(float64());
|
|
273
|
+
case MAP$1: return map(varint$1(), depth);
|
|
274
|
+
case SET$1: return set(varint$1(), depth);
|
|
275
|
+
case ARRAYBUFFER$1: return copy(varint$1());
|
|
276
|
+
case VIEW$1: return typed();
|
|
277
|
+
default: throw new CodecError("malformed", `unknown tag 0x${tag.toString(16)}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
function utf8Decode(start, stop) {
|
|
281
|
+
try {
|
|
282
|
+
return utf8$1.decode(src.subarray(start, stop));
|
|
283
|
+
} catch {
|
|
284
|
+
throw new CodecError("malformed", "invalid UTF-8");
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
const SLOTS$1 = 4096;
|
|
288
|
+
const CACHED = 16;
|
|
289
|
+
const slotBytes = new Uint8Array(SLOTS$1 * CACHED);
|
|
290
|
+
const slotLength = new Uint8Array(SLOTS$1);
|
|
291
|
+
const slotString = Array.from({ length: SLOTS$1 }, () => "");
|
|
292
|
+
function string$1(n) {
|
|
293
|
+
const start = pos$1;
|
|
294
|
+
const stop = start + n;
|
|
295
|
+
if (stop > end) throw truncated();
|
|
296
|
+
pos$1 = stop;
|
|
297
|
+
if (n === 0) return "";
|
|
298
|
+
if (n > CACHED) return n > 32 ? utf8Decode(start, stop) : ascii(start, stop);
|
|
299
|
+
let h = n;
|
|
300
|
+
for (let i = start; i < stop; i++) h = Math.imul(h, 31) + (src[i] ?? 0) | 0;
|
|
301
|
+
const slot = (h ^ h >>> 12) & 4095;
|
|
302
|
+
const base = slot * CACHED;
|
|
303
|
+
if (slotLength[slot] === n) {
|
|
304
|
+
let i = 0;
|
|
305
|
+
while (i < n && slotBytes[base + i] === src[start + i]) i++;
|
|
306
|
+
if (i === n) return slotString[slot] ?? "";
|
|
307
|
+
}
|
|
308
|
+
const s = ascii(start, stop);
|
|
309
|
+
slotBytes.set(src.subarray(start, stop), base);
|
|
310
|
+
slotLength[slot] = n;
|
|
311
|
+
slotString[slot] = s;
|
|
312
|
+
return s;
|
|
313
|
+
}
|
|
314
|
+
const fcc = String.fromCharCode;
|
|
315
|
+
/** Up to 32 bytes: by hand when ASCII, which beats TextDecoder's call overhead. */
|
|
316
|
+
function ascii(start, stop) {
|
|
317
|
+
let s = "";
|
|
318
|
+
let i = start;
|
|
319
|
+
for (; i + 4 <= stop; i += 4) {
|
|
320
|
+
const a = src[i] ?? 0;
|
|
321
|
+
const b = src[i + 1] ?? 0;
|
|
322
|
+
const c = src[i + 2] ?? 0;
|
|
323
|
+
const d = src[i + 3] ?? 0;
|
|
324
|
+
if ((a | b | c | d) >= 128) return utf8Decode(start, stop);
|
|
325
|
+
s += fcc(a, b, c, d);
|
|
326
|
+
}
|
|
327
|
+
for (; i < stop; i++) {
|
|
328
|
+
const a = src[i] ?? 0;
|
|
329
|
+
if (a >= 128) return utf8Decode(start, stop);
|
|
330
|
+
s += fcc(a);
|
|
331
|
+
}
|
|
332
|
+
return s;
|
|
333
|
+
}
|
|
334
|
+
function key() {
|
|
335
|
+
const tag = byte();
|
|
336
|
+
if (tag >= FIXSTR$1 && tag <= FIXSTR$1 + FIXSTR_MAX$1) return string$1(tag - FIXSTR$1);
|
|
337
|
+
if (tag === STR$1) return string$1(varint$1());
|
|
338
|
+
throw new CodecError("malformed", "object key is not a string");
|
|
339
|
+
}
|
|
340
|
+
function nest(depth) {
|
|
341
|
+
if (depth >= MAX_DEPTH$1) throw new CodecError("malformed", `nested deeper than ${MAX_DEPTH$1}`);
|
|
342
|
+
return depth + 1;
|
|
343
|
+
}
|
|
344
|
+
function array$1(n, depth) {
|
|
345
|
+
const d = nest(depth);
|
|
346
|
+
if (pos$1 + n > end) throw truncated();
|
|
347
|
+
const a = [];
|
|
348
|
+
for (let i = 0; i < n; i++) a.push(read(d));
|
|
349
|
+
return a;
|
|
350
|
+
}
|
|
351
|
+
function object$1(n, depth) {
|
|
352
|
+
const d = nest(depth);
|
|
353
|
+
if (pos$1 + n * 2 > end) throw truncated();
|
|
354
|
+
const o = {};
|
|
355
|
+
for (let i = 0; i < n; i++) {
|
|
356
|
+
const k = key();
|
|
357
|
+
const v = read(d);
|
|
358
|
+
if (k === "__proto__") Object.defineProperty(o, k, {
|
|
359
|
+
value: v,
|
|
360
|
+
writable: true,
|
|
361
|
+
enumerable: true,
|
|
362
|
+
configurable: true
|
|
363
|
+
});
|
|
364
|
+
else o[k] = v;
|
|
365
|
+
}
|
|
366
|
+
return o;
|
|
367
|
+
}
|
|
368
|
+
/** n bytes, copied into their own ArrayBuffer. */
|
|
369
|
+
function copy(n) {
|
|
370
|
+
if (pos$1 + n > end) throw truncated();
|
|
371
|
+
const out = new ArrayBuffer(n);
|
|
372
|
+
new Uint8Array(out).set(src.subarray(pos$1, pos$1 + n));
|
|
373
|
+
pos$1 += n;
|
|
374
|
+
return out;
|
|
375
|
+
}
|
|
376
|
+
function bigint$1() {
|
|
377
|
+
const n = varint$1();
|
|
378
|
+
if (pos$1 + n > end) throw truncated();
|
|
379
|
+
let v = 0n;
|
|
380
|
+
for (let i = pos$1 + n - 1; i >= pos$1; i--) v = v << 8n | BigInt(src[i] ?? 0);
|
|
381
|
+
pos$1 += n;
|
|
382
|
+
return v;
|
|
383
|
+
}
|
|
384
|
+
function map(n, depth) {
|
|
385
|
+
const d = nest(depth);
|
|
386
|
+
if (pos$1 + n * 2 > end) throw truncated();
|
|
387
|
+
const m = /* @__PURE__ */ new Map();
|
|
388
|
+
for (let i = 0; i < n; i++) {
|
|
389
|
+
const k = read(d);
|
|
390
|
+
m.set(k, read(d));
|
|
391
|
+
}
|
|
392
|
+
return m;
|
|
393
|
+
}
|
|
394
|
+
function set(n, depth) {
|
|
395
|
+
const d = nest(depth);
|
|
396
|
+
if (pos$1 + n > end) throw truncated();
|
|
397
|
+
const s = /* @__PURE__ */ new Set();
|
|
398
|
+
for (let i = 0; i < n; i++) s.add(read(d));
|
|
399
|
+
return s;
|
|
400
|
+
}
|
|
401
|
+
const VIEWS = {
|
|
402
|
+
Int8Array: (b) => new Int8Array(b),
|
|
403
|
+
Uint8Array: (b) => new Uint8Array(b),
|
|
404
|
+
Uint8ClampedArray: (b) => new Uint8ClampedArray(b),
|
|
405
|
+
Int16Array: (b) => new Int16Array(b),
|
|
406
|
+
Uint16Array: (b) => new Uint16Array(b),
|
|
407
|
+
Int32Array: (b) => new Int32Array(b),
|
|
408
|
+
Uint32Array: (b) => new Uint32Array(b),
|
|
409
|
+
Float32Array: (b) => new Float32Array(b),
|
|
410
|
+
Float64Array: (b) => new Float64Array(b),
|
|
411
|
+
BigInt64Array: (b) => new BigInt64Array(b),
|
|
412
|
+
BigUint64Array: (b) => new BigUint64Array(b),
|
|
413
|
+
DataView: (b) => new DataView(b)
|
|
414
|
+
};
|
|
415
|
+
function typed() {
|
|
416
|
+
const kind = VIEW_KINDS$1[byte()];
|
|
417
|
+
if (kind === void 0) throw new CodecError("malformed", "unknown typed array kind");
|
|
418
|
+
const b = copy(varint$1());
|
|
419
|
+
try {
|
|
420
|
+
return VIEWS[kind](b);
|
|
421
|
+
} catch {
|
|
422
|
+
throw new CodecError("malformed", `${kind} byte length ${b.byteLength}`);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
const { FIXSTR, FIXARRAY, FIXOBJECT, UNDEFINED, NULL, FALSE, TRUE, UINT, NINT, FLOAT64, STR, ARRAY, OBJECT, FIXSTR_MAX, FIXARRAY_MAX, FIXOBJECT_MAX, MAX_DEPTH, BIGINT, NBIGINT, DATE, MAP, SET, ARRAYBUFFER, VIEW, VIEW_KINDS } = format_exports;
|
|
426
|
+
const utf8 = new TextEncoder();
|
|
427
|
+
const SLACK = 16;
|
|
428
|
+
const CHUNK$1 = 16384;
|
|
429
|
+
let buf = new Uint8Array(CHUNK$1);
|
|
430
|
+
let view = new DataView(buf.buffer);
|
|
431
|
+
let start = 0;
|
|
432
|
+
let pos = 0;
|
|
433
|
+
/** Makes room for n more bytes (plus SLACK), moving to a new chunk if needed. */
|
|
434
|
+
function room(n) {
|
|
435
|
+
if (pos + n + SLACK <= buf.length) return;
|
|
436
|
+
const used = pos - start;
|
|
437
|
+
let size = CHUNK$1;
|
|
438
|
+
while (size < used + n + SLACK) size *= 2;
|
|
439
|
+
const next = new Uint8Array(size);
|
|
440
|
+
next.set(buf.subarray(start, pos));
|
|
441
|
+
buf = next;
|
|
442
|
+
view = new DataView(next.buffer);
|
|
443
|
+
start = 0;
|
|
444
|
+
pos = used;
|
|
445
|
+
}
|
|
446
|
+
/** Unsigned LEB128, for 0 ≤ n ≤ 2^53 - 1; the caller made room. */
|
|
447
|
+
function varint(n) {
|
|
448
|
+
if (n > 4294967295) {
|
|
449
|
+
const lo = n >>> 0;
|
|
450
|
+
const hi = (n - lo) / 4294967296;
|
|
451
|
+
buf[pos++] = lo & 127 | 128;
|
|
452
|
+
buf[pos++] = lo >>> 7 & 127 | 128;
|
|
453
|
+
buf[pos++] = lo >>> 14 & 127 | 128;
|
|
454
|
+
buf[pos++] = lo >>> 21 & 127 | 128;
|
|
455
|
+
n = lo >>> 28 | hi << 4;
|
|
456
|
+
}
|
|
457
|
+
while (n > 127) {
|
|
458
|
+
buf[pos++] = n & 127 | 128;
|
|
459
|
+
n >>>= 7;
|
|
460
|
+
}
|
|
461
|
+
buf[pos++] = n;
|
|
462
|
+
}
|
|
463
|
+
/** A tag that holds counts up to `max` itself, else the long tag and a varint. */
|
|
464
|
+
function head(fix, max, long, n) {
|
|
465
|
+
if (n <= max) buf[pos++] = fix + n;
|
|
466
|
+
else {
|
|
467
|
+
buf[pos++] = long;
|
|
468
|
+
varint(n);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const varintSize = (n) => {
|
|
472
|
+
let size = 1;
|
|
473
|
+
while (n >= 128) {
|
|
474
|
+
n = Math.floor(n / 128);
|
|
475
|
+
size++;
|
|
476
|
+
}
|
|
477
|
+
return size;
|
|
478
|
+
};
|
|
479
|
+
const isPlainObject = (v) => {
|
|
480
|
+
const proto = Object.getPrototypeOf(v);
|
|
481
|
+
return proto === Object.prototype || proto === null;
|
|
482
|
+
};
|
|
483
|
+
const describe = (v) => {
|
|
484
|
+
if (typeof v === "function") return "a function";
|
|
485
|
+
if (typeof v === "symbol") return "a symbol";
|
|
486
|
+
const ctor = typeof v === "object" && v !== null ? Reflect.get(v, "constructor") : void 0;
|
|
487
|
+
const name = typeof ctor === "function" ? ctor.name : void 0;
|
|
488
|
+
return typeof name === "string" && name !== "" ? `an instance of ${name}` : "an object";
|
|
489
|
+
};
|
|
490
|
+
let busy = false;
|
|
491
|
+
/**
|
|
492
|
+
* Encodes `value` to bytes (`isoloop-codec@1`, see format.ts). Throws a
|
|
493
|
+
* `CodecError` with code `not_encodable` for a function, a symbol, a class
|
|
494
|
+
* instance or a cycle.
|
|
495
|
+
*
|
|
496
|
+
* The result is a view into a chunk shared with other results: copy it, or
|
|
497
|
+
* read it through its `byteOffset`, before transferring its `buffer`.
|
|
498
|
+
*/
|
|
499
|
+
function encode(value) {
|
|
500
|
+
if (busy) {
|
|
501
|
+
const outer = {
|
|
502
|
+
buf,
|
|
503
|
+
view,
|
|
504
|
+
start,
|
|
505
|
+
pos
|
|
506
|
+
};
|
|
507
|
+
buf = /* @__PURE__ */ new Uint8Array(256);
|
|
508
|
+
view = new DataView(buf.buffer);
|
|
509
|
+
start = 0;
|
|
510
|
+
pos = 0;
|
|
511
|
+
try {
|
|
512
|
+
write$1(value, 0);
|
|
513
|
+
return buf.subarray(0, pos);
|
|
514
|
+
} finally {
|
|
515
|
+
({buf, view, start, pos} = outer);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
busy = true;
|
|
519
|
+
start = pos;
|
|
520
|
+
try {
|
|
521
|
+
write$1(value, 0);
|
|
522
|
+
const out = buf.subarray(start, pos);
|
|
523
|
+
start = pos;
|
|
524
|
+
return out;
|
|
525
|
+
} catch (e) {
|
|
526
|
+
pos = start;
|
|
527
|
+
throw e;
|
|
528
|
+
} finally {
|
|
529
|
+
busy = false;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
function write$1(v, depth) {
|
|
533
|
+
if (pos + SLACK > buf.length) room(0);
|
|
534
|
+
switch (typeof v) {
|
|
535
|
+
case "number": return number(v);
|
|
536
|
+
case "string": return string(v);
|
|
537
|
+
case "boolean":
|
|
538
|
+
buf[pos++] = v ? TRUE : FALSE;
|
|
539
|
+
return;
|
|
540
|
+
case "undefined":
|
|
541
|
+
buf[pos++] = UNDEFINED;
|
|
542
|
+
return;
|
|
543
|
+
case "object":
|
|
544
|
+
if (v === null) {
|
|
545
|
+
buf[pos++] = NULL;
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (depth >= MAX_DEPTH) throw new CodecError("not_encodable", `nested deeper than ${MAX_DEPTH}, or a cycle`);
|
|
549
|
+
if (Array.isArray(v)) return array(v, depth + 1);
|
|
550
|
+
if (isPlainObject(v)) return object(v, depth + 1);
|
|
551
|
+
return special(v, depth + 1);
|
|
552
|
+
case "bigint": return bigint(v);
|
|
553
|
+
case "function":
|
|
554
|
+
case "symbol": throw new CodecError("not_encodable", `${describe(v)} can't be encoded`);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
function number(v) {
|
|
558
|
+
if (v >>> 0 === v && (v !== 0 || 1 / v > 0)) {
|
|
559
|
+
if (v < 128) buf[pos++] = v;
|
|
560
|
+
else {
|
|
561
|
+
buf[pos++] = UINT;
|
|
562
|
+
varint(v);
|
|
563
|
+
}
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
if (v !== 0 && ((v | 0) === v || Math.trunc(v) === v && v <= Number.MAX_SAFE_INTEGER && v >= -Number.MAX_SAFE_INTEGER)) {
|
|
567
|
+
if (v >= 0) {
|
|
568
|
+
buf[pos++] = UINT;
|
|
569
|
+
varint(v);
|
|
570
|
+
} else if (v >= -32) buf[pos++] = 256 + v;
|
|
571
|
+
else {
|
|
572
|
+
buf[pos++] = NINT;
|
|
573
|
+
varint(-v - 1);
|
|
574
|
+
}
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
buf[pos] = FLOAT64;
|
|
578
|
+
view.setFloat64(pos + 1, v, true);
|
|
579
|
+
pos += 9;
|
|
580
|
+
}
|
|
581
|
+
function string(s) {
|
|
582
|
+
const n = s.length;
|
|
583
|
+
if (n <= 64) {
|
|
584
|
+
room(n);
|
|
585
|
+
const at = pos;
|
|
586
|
+
if (n <= FIXSTR_MAX) pos += 1;
|
|
587
|
+
else pos += 2;
|
|
588
|
+
let i = 0;
|
|
589
|
+
for (; i < n; i++) {
|
|
590
|
+
const c = s.charCodeAt(i);
|
|
591
|
+
if (c >= 128) break;
|
|
592
|
+
buf[pos++] = c;
|
|
593
|
+
}
|
|
594
|
+
if (i === n) {
|
|
595
|
+
if (n <= FIXSTR_MAX) buf[at] = FIXSTR + n;
|
|
596
|
+
else {
|
|
597
|
+
buf[at] = STR;
|
|
598
|
+
buf[at + 1] = n;
|
|
599
|
+
}
|
|
600
|
+
return;
|
|
601
|
+
}
|
|
602
|
+
pos = at;
|
|
603
|
+
}
|
|
604
|
+
const max = n * 3;
|
|
605
|
+
const gap = 1 + varintSize(max);
|
|
606
|
+
room(gap + max);
|
|
607
|
+
const at = pos;
|
|
608
|
+
const { written } = utf8.encodeInto(s, buf.subarray(at + gap));
|
|
609
|
+
const size = written <= FIXSTR_MAX ? 1 : 1 + varintSize(written);
|
|
610
|
+
if (size !== gap) buf.copyWithin(at + size, at + gap, at + gap + written);
|
|
611
|
+
head(FIXSTR, FIXSTR_MAX, STR, written);
|
|
612
|
+
pos = at + size + written;
|
|
613
|
+
}
|
|
614
|
+
function item(v, depth) {
|
|
615
|
+
if (typeof v === "number") {
|
|
616
|
+
if (pos + SLACK > buf.length) room(0);
|
|
617
|
+
number(v);
|
|
618
|
+
} else if (typeof v === "string") string(v);
|
|
619
|
+
else write$1(v, depth);
|
|
620
|
+
}
|
|
621
|
+
function array(a, depth) {
|
|
622
|
+
head(FIXARRAY, FIXARRAY_MAX, ARRAY, a.length);
|
|
623
|
+
for (let i = 0; i < a.length; i++) item(a[i], depth);
|
|
624
|
+
}
|
|
625
|
+
function object(o, depth) {
|
|
626
|
+
const keys = Object.keys(o);
|
|
627
|
+
head(FIXOBJECT, FIXOBJECT_MAX, OBJECT, keys.length);
|
|
628
|
+
for (const k of keys) {
|
|
629
|
+
string(k);
|
|
630
|
+
item(o[k], depth);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
const viewKind = (v) => {
|
|
634
|
+
const name = Object.prototype.toString.call(v).slice(8, -1);
|
|
635
|
+
return VIEW_KINDS.indexOf(name);
|
|
636
|
+
};
|
|
637
|
+
/** The structured-clone types beyond plain data. */
|
|
638
|
+
function special(v, depth) {
|
|
639
|
+
if (v instanceof Date) {
|
|
640
|
+
buf[pos] = DATE;
|
|
641
|
+
view.setFloat64(pos + 1, v.getTime(), true);
|
|
642
|
+
pos += 9;
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
if (v instanceof Map) {
|
|
646
|
+
head(MAP, -1, MAP, v.size);
|
|
647
|
+
for (const [k, x] of v) {
|
|
648
|
+
item(k, depth);
|
|
649
|
+
item(x, depth);
|
|
650
|
+
}
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
if (v instanceof Set) {
|
|
654
|
+
head(SET, -1, SET, v.size);
|
|
655
|
+
for (const x of v) item(x, depth);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
if (v instanceof ArrayBuffer) return bytes(ARRAYBUFFER, -1, new Uint8Array(v));
|
|
659
|
+
if (ArrayBuffer.isView(v)) {
|
|
660
|
+
const kind = viewKind(v);
|
|
661
|
+
if (kind < 0 || !(v.buffer instanceof ArrayBuffer)) throw new CodecError("not_encodable", `${describe(v)} can't be encoded`);
|
|
662
|
+
return bytes(VIEW, kind, new Uint8Array(v.buffer, v.byteOffset, v.byteLength));
|
|
663
|
+
}
|
|
664
|
+
throw new CodecError("not_encodable", `${describe(v)} can't be encoded`);
|
|
665
|
+
}
|
|
666
|
+
/** A tag, an optional kind byte, a varint length and the bytes. */
|
|
667
|
+
function bytes(tag, kind, b) {
|
|
668
|
+
room(b.length);
|
|
669
|
+
buf[pos++] = tag;
|
|
670
|
+
if (kind >= 0) buf[pos++] = kind;
|
|
671
|
+
varint(b.length);
|
|
672
|
+
buf.set(b, pos);
|
|
673
|
+
pos += b.length;
|
|
674
|
+
}
|
|
675
|
+
function bigint(v) {
|
|
676
|
+
let m = v < 0n ? -v : v;
|
|
677
|
+
const out = [];
|
|
678
|
+
while (m > 0n) {
|
|
679
|
+
out.push(Number(m & 255n));
|
|
680
|
+
m >>= 8n;
|
|
681
|
+
}
|
|
682
|
+
bytes(v < 0n ? NBIGINT : BIGINT, -1, Uint8Array.from(out));
|
|
683
|
+
}
|
|
684
|
+
// src/size.ts
|
|
685
|
+
/**
|
|
686
|
+
* A rough structured size of a value in bytes, for `maxRecordBytes` (design
|
|
687
|
+
* §6.1). Strings count two bytes per UTF-16 unit, numbers eight, object keys
|
|
688
|
+
* like strings, plus a little per entry. Cycles count once. Cheap rather than
|
|
689
|
+
* exact: it only has to tell a 1 KiB record from a 1 MiB one.
|
|
690
|
+
*/
|
|
691
|
+
function estimateSize(value, limit = Infinity) {
|
|
692
|
+
const seen = /* @__PURE__ */ new Set();
|
|
693
|
+
const stack = [value];
|
|
694
|
+
let size = 0;
|
|
695
|
+
while (stack.length > 0 && size <= limit) {
|
|
696
|
+
const v = stack.pop();
|
|
697
|
+
switch (typeof v) {
|
|
698
|
+
case "string":
|
|
699
|
+
size += 2 * v.length + 4;
|
|
700
|
+
continue;
|
|
701
|
+
case "number":
|
|
702
|
+
case "bigint":
|
|
703
|
+
size += 8;
|
|
704
|
+
continue;
|
|
705
|
+
case "boolean":
|
|
706
|
+
case "undefined":
|
|
707
|
+
size += 1;
|
|
708
|
+
continue;
|
|
709
|
+
case "symbol":
|
|
710
|
+
case "function": continue;
|
|
711
|
+
}
|
|
712
|
+
if (v === null) {
|
|
713
|
+
size += 1;
|
|
714
|
+
continue;
|
|
715
|
+
}
|
|
716
|
+
if (seen.has(v)) continue;
|
|
717
|
+
seen.add(v);
|
|
718
|
+
if (ArrayBuffer.isView(v)) size += v.byteLength + 8;
|
|
719
|
+
else if (v instanceof ArrayBuffer) size += v.byteLength + 8;
|
|
720
|
+
else if (Array.isArray(v)) {
|
|
721
|
+
size += 8 + v.length;
|
|
722
|
+
for (const x of v) stack.push(x);
|
|
723
|
+
} else if (v instanceof Map) {
|
|
724
|
+
size += 8;
|
|
725
|
+
for (const [k, x] of v) stack.push(k, x);
|
|
726
|
+
} else if (v instanceof Set) {
|
|
727
|
+
size += 8;
|
|
728
|
+
for (const x of v) stack.push(x);
|
|
729
|
+
} else {
|
|
730
|
+
size += 8;
|
|
731
|
+
for (const [k, x] of Object.entries(v)) {
|
|
732
|
+
size += 2 * k.length + 4;
|
|
733
|
+
stack.push(x);
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return size;
|
|
738
|
+
}
|
|
739
|
+
/**
|
|
740
|
+
* Seed progress, kept as committed offsets of reserved consumers on the
|
|
741
|
+
* seeding topic. Offsets are written after the records of the same group
|
|
742
|
+
* commit, so the progress never points past what is on disk (ADR 0003,
|
|
743
|
+
* decision 18: exactly once).
|
|
744
|
+
*/
|
|
745
|
+
const SEED_FROM = "isoloop:seed:from";
|
|
746
|
+
/** The seeding topic's head when `SEED_FROM` was saved. */
|
|
747
|
+
const SEED_HEAD = "isoloop:seed:head";
|
|
748
|
+
/** Set when the seed ended: the source's head then. */
|
|
749
|
+
const SEED_DONE = "isoloop:seed:done";
|
|
750
|
+
/** How many source records were rejected, all runs together. */
|
|
751
|
+
const SEED_REJECTED = "isoloop:seed:rejected";
|
|
752
|
+
/** One per rejected source offset; its value is the offset. */
|
|
753
|
+
const SEED_REJECTED_AT = "isoloop:seed:rejected:";
|
|
754
|
+
/** Whether a seed into `to` started on this device and hasn't ended. */
|
|
755
|
+
function seedPending(engine, to) {
|
|
756
|
+
return engine.committed(to, "isoloop:seed:from") !== void 0 && !seedDone(engine, to);
|
|
757
|
+
}
|
|
758
|
+
function seedDone(engine, to) {
|
|
759
|
+
return engine.committed(to, SEED_DONE) !== void 0;
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Topics with a seed, sources before the topics that seed from them, so a
|
|
763
|
+
* chain (v3 from v2 from v1) runs in order. `contracts()` has already refused
|
|
764
|
+
* unknown sources and cycles.
|
|
765
|
+
*/
|
|
766
|
+
function seedOrder(topics) {
|
|
767
|
+
const byName = new Map(topics.map((t) => [t.name, t]));
|
|
768
|
+
const out = [];
|
|
769
|
+
const seen = /* @__PURE__ */ new Set();
|
|
770
|
+
const visit = (t) => {
|
|
771
|
+
if (seen.has(t.name)) return;
|
|
772
|
+
seen.add(t.name);
|
|
773
|
+
const from = t.seed && byName.get(t.seed.from.name);
|
|
774
|
+
if (from) visit(from);
|
|
775
|
+
if (t.seed) out.push(t);
|
|
776
|
+
};
|
|
777
|
+
for (const t of topics) visit(t);
|
|
778
|
+
return out;
|
|
779
|
+
}
|
|
780
|
+
const issue = (message) => [{
|
|
781
|
+
message,
|
|
782
|
+
path: []
|
|
783
|
+
}];
|
|
784
|
+
/** Runs `map`; a throw or a returned promise rejects the record. */
|
|
785
|
+
function mapRecord(map, rec) {
|
|
786
|
+
let mapped;
|
|
787
|
+
try {
|
|
788
|
+
mapped = map(rec.value, rec);
|
|
789
|
+
} catch (e) {
|
|
790
|
+
return {
|
|
791
|
+
ok: false,
|
|
792
|
+
code: "invalid",
|
|
793
|
+
issues: issue(`map threw: ${String(e)}`)
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
if (mapped instanceof Promise) {
|
|
797
|
+
mapped.catch(() => {});
|
|
798
|
+
return {
|
|
799
|
+
ok: false,
|
|
800
|
+
code: "seed_async",
|
|
801
|
+
issues: issue("map returned a promise")
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
ok: true,
|
|
806
|
+
value: mapped
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* Copies `from`'s records into `to` until it reaches `from`'s head, keeping
|
|
811
|
+
* each record's `ts`, `producer` and `key`, and saving progress with every
|
|
812
|
+
* batch. A seed cut short resumes after the last saved source offset; records
|
|
813
|
+
* it appended after that save are recognised and not appended again, since
|
|
814
|
+
* `map` and the schema are pure. Records `map` or `to`'s schema rejects are
|
|
815
|
+
* skipped, reported and recorded. Yields between batches, so other topics
|
|
816
|
+
* carry on.
|
|
817
|
+
*/
|
|
818
|
+
async function copySeed(c) {
|
|
819
|
+
const { engine, to, from } = c;
|
|
820
|
+
const last = engine.committed(to, SEED_FROM);
|
|
821
|
+
let offset = Math.max(last === void 0 ? 0 : last + 1, engine.tail(from));
|
|
822
|
+
let skip = engine.head(to) - (engine.committed(to, "isoloop:seed:head") ?? 0);
|
|
823
|
+
let rejected = engine.committed(to, "isoloop:seed:rejected") ?? 0;
|
|
824
|
+
while (offset < engine.head(from)) {
|
|
825
|
+
if (!engine.readable(from, offset)) await engine.page(from, offset);
|
|
826
|
+
const batch = engine.read(from, offset, 256);
|
|
827
|
+
const end = batch.at(-1);
|
|
828
|
+
if (!end) break;
|
|
829
|
+
for (const rec of batch) {
|
|
830
|
+
const mapped = mapRecord(c.map, rec);
|
|
831
|
+
const verdict = mapped.ok ? await c.accept(mapped.value) : mapped;
|
|
832
|
+
if (!verdict.ok) {
|
|
833
|
+
const at = `${SEED_REJECTED_AT}${rec.offset}`;
|
|
834
|
+
if (engine.committed(to, at) === void 0) {
|
|
835
|
+
engine.commit(to, at, rec.offset);
|
|
836
|
+
rejected++;
|
|
837
|
+
}
|
|
838
|
+
c.onReject?.(rec.offset, verdict);
|
|
839
|
+
continue;
|
|
840
|
+
}
|
|
841
|
+
if (skip > 0) {
|
|
842
|
+
skip--;
|
|
843
|
+
continue;
|
|
844
|
+
}
|
|
845
|
+
let out = {
|
|
846
|
+
value: verdict.value,
|
|
847
|
+
ts: rec.ts,
|
|
848
|
+
producer: rec.producer
|
|
849
|
+
};
|
|
850
|
+
if (rec.key !== void 0) out = {
|
|
851
|
+
...out,
|
|
852
|
+
key: rec.key
|
|
853
|
+
};
|
|
854
|
+
engine.append(to, out);
|
|
855
|
+
}
|
|
856
|
+
offset = end.offset + 1;
|
|
857
|
+
engine.commit(to, SEED_REJECTED, rejected);
|
|
858
|
+
engine.commit(to, SEED_FROM, end.offset);
|
|
859
|
+
engine.commit(to, SEED_HEAD, engine.head(to));
|
|
860
|
+
await new Promise((r) => setTimeout(r, 0));
|
|
861
|
+
}
|
|
862
|
+
engine.commit(to, SEED_REJECTED, rejected);
|
|
863
|
+
engine.commit(to, SEED_DONE, engine.head(from));
|
|
864
|
+
return {
|
|
865
|
+
copied: engine.head(to),
|
|
866
|
+
rejected
|
|
867
|
+
};
|
|
868
|
+
}
|
|
869
|
+
// src/standard-schema.ts
|
|
870
|
+
const segmentKey = (s) => typeof s === "object" ? s.key : s;
|
|
871
|
+
/**
|
|
872
|
+
* Maps schema issues to the cloneable `{ message, path }[]` sent with `invalid`
|
|
873
|
+
* (ADR 0003, decision 10). Symbol keys become their description.
|
|
874
|
+
*/
|
|
875
|
+
function toIssues(issues) {
|
|
876
|
+
return issues.map((i) => ({
|
|
877
|
+
message: i.message,
|
|
878
|
+
path: (i.path ?? []).map((s) => {
|
|
879
|
+
const k = segmentKey(s);
|
|
880
|
+
return typeof k === "symbol" ? String(k) : k;
|
|
881
|
+
})
|
|
882
|
+
}));
|
|
883
|
+
}
|
|
884
|
+
const isRecord = (x) => typeof x === "object" && x !== null;
|
|
885
|
+
/** True for a value built by `contracts()`, from any copy of this package. */
|
|
886
|
+
function isContracts(x) {
|
|
887
|
+
return isRecord(x) && x["~isoloop"] === "contracts";
|
|
888
|
+
}
|
|
889
|
+
/** The structured-cloneable part of a topic, sent at `boot` for the contracts check (ADR 0003, decision 5). */
|
|
890
|
+
function topicConfig(t) {
|
|
891
|
+
return topicConfigOf(t);
|
|
892
|
+
}
|
|
893
|
+
// src/broker.ts
|
|
894
|
+
const fail = (code, message, extra) => ({
|
|
895
|
+
ok: false,
|
|
896
|
+
error: {
|
|
897
|
+
code,
|
|
898
|
+
message,
|
|
899
|
+
...extra
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
const isStartPosition = (x) => x === "latest" || x === "earliest" || x === "committed";
|
|
903
|
+
const hasTopic = (p) => typeof p === "object" && p !== null && "topic" in p && typeof p.topic === "string";
|
|
904
|
+
const isOffset = (x) => typeof x === "number" && Number.isInteger(x) && x >= 0;
|
|
905
|
+
/** A commit's `seq`: a non-negative integer, 0 before any delivery is settled whole. */
|
|
906
|
+
const isSeq = isOffset;
|
|
907
|
+
/** FNV-1a: a small, stable string hash for key → group member. */
|
|
908
|
+
function hash(s) {
|
|
909
|
+
let h = 2166136261;
|
|
910
|
+
for (let i = 0; i < s.length; i++) {
|
|
911
|
+
h ^= s.charCodeAt(i);
|
|
912
|
+
h = Math.imul(h, 16777619);
|
|
913
|
+
}
|
|
914
|
+
return h >>> 0;
|
|
915
|
+
}
|
|
916
|
+
const reqKey = (topic, offset) => `${topic}\u0000${offset}`;
|
|
917
|
+
/** A message's `(epoch, seq)`, when it carries both as numbers. */
|
|
918
|
+
function publishId(p) {
|
|
919
|
+
const { epoch, seq } = p;
|
|
920
|
+
return typeof epoch === "number" && typeof seq === "number" ? {
|
|
921
|
+
epoch,
|
|
922
|
+
seq
|
|
923
|
+
} : void 0;
|
|
924
|
+
}
|
|
925
|
+
/** Producer id for records the host publishes through `kernel.publish`. */
|
|
926
|
+
const HOST_PRODUCER = "host";
|
|
927
|
+
/** Producer id for records the kernel publishes to system topics. */
|
|
928
|
+
const KERNEL_PRODUCER = "kernel";
|
|
929
|
+
/** Requests are forgotten after this long when the caller gives no timeout. */
|
|
930
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
|
|
931
|
+
/**
|
|
932
|
+
* The bus core (design §6.3): runs the publish pipeline, keeps subscriptions
|
|
933
|
+
* and consumer groups, delivers from the log under credit, and routes
|
|
934
|
+
* request replies. Knows nothing about workers; the bus worker entry wires
|
|
935
|
+
* ports to it.
|
|
936
|
+
*/
|
|
937
|
+
var Broker = class {
|
|
938
|
+
#engine;
|
|
939
|
+
#now;
|
|
940
|
+
#dev;
|
|
941
|
+
#batch;
|
|
942
|
+
#inboxLimit;
|
|
943
|
+
#timers;
|
|
944
|
+
#durable;
|
|
945
|
+
#storageFull = false;
|
|
946
|
+
#topics = /* @__PURE__ */ new Map();
|
|
947
|
+
#conns = /* @__PURE__ */ new Map();
|
|
948
|
+
#groups = /* @__PURE__ */ new Map();
|
|
949
|
+
#requests = /* @__PURE__ */ new Map();
|
|
950
|
+
/** Consumers whose offsets were dropped by `detach { keepOffsets: false }`, per topic. */
|
|
951
|
+
#forgotten = /* @__PURE__ */ new Set();
|
|
952
|
+
#rejected = {};
|
|
953
|
+
/** Suspended isolates by topic: who to wake when a record arrives there. */
|
|
954
|
+
#sleepers = /* @__PURE__ */ new Map();
|
|
955
|
+
#onWake;
|
|
956
|
+
#onSeed;
|
|
957
|
+
/** Seed sources the contracts don't list: in the engine, so seeds can read them, but not open to isolates. */
|
|
958
|
+
#sources = /* @__PURE__ */ new Set();
|
|
959
|
+
#followReports = /* @__PURE__ */ new Map();
|
|
960
|
+
#dropped = 0;
|
|
961
|
+
constructor(opts) {
|
|
962
|
+
this.#engine = opts.engine;
|
|
963
|
+
this.#now = opts.now ?? Date.now;
|
|
964
|
+
this.#dev = opts.dev ?? false;
|
|
965
|
+
this.#batch = opts.batchSize ?? 64;
|
|
966
|
+
this.#inboxLimit = opts.inboxLimit ?? 1e3;
|
|
967
|
+
this.#timers = opts.timers ?? { set: (fn, ms) => void setTimeout(fn, ms) };
|
|
968
|
+
this.#durable = opts.durable ?? ((topic) => this.#engine.durable(topic));
|
|
969
|
+
this.#onWake = opts.onWake ?? (() => {});
|
|
970
|
+
this.#onSeed = opts.onSeed ?? (() => {});
|
|
971
|
+
for (const def of [...opts.systemTopics ?? SYSTEM_TOPICS, ...opts.contracts.topics]) {
|
|
972
|
+
this.#engine.createTopic(topicConfig(def));
|
|
973
|
+
this.#topics.set(def.name, {
|
|
974
|
+
def,
|
|
975
|
+
maxBytes: def.maxRecordBytes ?? 262144,
|
|
976
|
+
queue: [],
|
|
977
|
+
seeding: void 0,
|
|
978
|
+
records: 0,
|
|
979
|
+
bytes: 0
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
for (const def of opts.contracts.topics) {
|
|
983
|
+
const from = def.seed?.from;
|
|
984
|
+
if (!from || this.#topics.has(from.name) || this.#sources.has(from.name)) continue;
|
|
985
|
+
this.#engine.createTopic(topicConfig(from));
|
|
986
|
+
this.#sources.add(from.name);
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
#sleep(topic, isolateId) {
|
|
990
|
+
let set = this.#sleepers.get(topic);
|
|
991
|
+
if (!set) this.#sleepers.set(topic, set = /* @__PURE__ */ new Set());
|
|
992
|
+
set.add(isolateId);
|
|
993
|
+
}
|
|
994
|
+
#unsleep(isolateId) {
|
|
995
|
+
for (const set of this.#sleepers.values()) set.delete(isolateId);
|
|
996
|
+
}
|
|
997
|
+
/** Wakes every isolate sleeping on `topic`, once. */
|
|
998
|
+
#wake(topic) {
|
|
999
|
+
const set = this.#sleepers.get(topic);
|
|
1000
|
+
if (!set || set.size === 0) return;
|
|
1001
|
+
for (const id of set) {
|
|
1002
|
+
this.#unsleep(id);
|
|
1003
|
+
this.#onWake(id, topic);
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
/** Messages dropped as malformed or unknown (design §3: dropped and counted). */
|
|
1007
|
+
get dropped() {
|
|
1008
|
+
return this.#dropped;
|
|
1009
|
+
}
|
|
1010
|
+
/** Counters for the 1 s metrics sample. */
|
|
1011
|
+
stats() {
|
|
1012
|
+
const subscriptions = [];
|
|
1013
|
+
const groups = /* @__PURE__ */ new Set();
|
|
1014
|
+
for (const conn of this.#conns.values()) for (const sub of conn.subs.values()) {
|
|
1015
|
+
const head = this.#engine.head(sub.topic);
|
|
1016
|
+
const g = sub.group;
|
|
1017
|
+
if (g) {
|
|
1018
|
+
if (groups.has(g)) continue;
|
|
1019
|
+
groups.add(g);
|
|
1020
|
+
const credit = g.members.reduce((n, m) => n + m.credit, 0);
|
|
1021
|
+
subscriptions.push({
|
|
1022
|
+
consumer: g.consumer,
|
|
1023
|
+
topic: g.topic,
|
|
1024
|
+
lag: head - g.cursor,
|
|
1025
|
+
credit
|
|
1026
|
+
});
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
subscriptions.push({
|
|
1030
|
+
consumer: conn.isolateId,
|
|
1031
|
+
topic: sub.topic,
|
|
1032
|
+
lag: head - sub.cursor,
|
|
1033
|
+
credit: sub.credit
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
return {
|
|
1037
|
+
topics: [...this.#topics].map(([topic, t]) => ({
|
|
1038
|
+
topic,
|
|
1039
|
+
records: t.records,
|
|
1040
|
+
bytes: t.bytes
|
|
1041
|
+
})),
|
|
1042
|
+
subscriptions,
|
|
1043
|
+
rejected: { ...this.#rejected }
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* The origin's storage is full (M2b task 14): publishes to persistent
|
|
1048
|
+
* topics reject with `quota_exceeded`, memory topics carry on.
|
|
1049
|
+
*/
|
|
1050
|
+
setStorageFull(full) {
|
|
1051
|
+
this.#storageFull = full;
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Writes what persistent topics have pending at once: the page is freezing
|
|
1055
|
+
* or going away (ADR 0001, what the browser still controls).
|
|
1056
|
+
*/
|
|
1057
|
+
flush() {
|
|
1058
|
+
return this.#engine.flush({ now: true });
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Starts every declared seed whose topic is empty and whose source has
|
|
1062
|
+
* records, or is seeding itself (ADR 0003, decision 18). The topics are
|
|
1063
|
+
* marked seeding before this returns, so call it before any connection is
|
|
1064
|
+
* attached. Resolves when every seed has ended. The bus worker calls it
|
|
1065
|
+
* only when it holds the files: elsewhere persistent topics start empty.
|
|
1066
|
+
*/
|
|
1067
|
+
seed() {
|
|
1068
|
+
const runs = /* @__PURE__ */ new Map();
|
|
1069
|
+
for (const def of seedOrder([...this.#topics.values()].map((t) => t.def))) {
|
|
1070
|
+
const topic = this.#topics.get(def.name);
|
|
1071
|
+
const seed = def.seed;
|
|
1072
|
+
if (!topic || !seed) continue;
|
|
1073
|
+
const from = seed.from.name;
|
|
1074
|
+
const before = runs.get(from);
|
|
1075
|
+
const hasData = this.#engine.head(from) > this.#engine.tail(from);
|
|
1076
|
+
if (seedDone(this.#engine, def.name)) continue;
|
|
1077
|
+
if (!seedPending(this.#engine, def.name)) {
|
|
1078
|
+
if (this.#engine.head(def.name) > 0 || !hasData && !before) continue;
|
|
1079
|
+
}
|
|
1080
|
+
topic.seeding = [];
|
|
1081
|
+
const run = (before ?? Promise.resolve()).then(() => copySeed({
|
|
1082
|
+
engine: this.#engine,
|
|
1083
|
+
to: def.name,
|
|
1084
|
+
from,
|
|
1085
|
+
map: seed.map,
|
|
1086
|
+
accept: (value) => {
|
|
1087
|
+
const v = validate(def.schema, value);
|
|
1088
|
+
const verdict = (r) => {
|
|
1089
|
+
const c = this.#check(def.name, r, def.durability === "persistent");
|
|
1090
|
+
if (c.ok) return {
|
|
1091
|
+
ok: true,
|
|
1092
|
+
value: c.value
|
|
1093
|
+
};
|
|
1094
|
+
return {
|
|
1095
|
+
ok: false,
|
|
1096
|
+
code: c.error.code,
|
|
1097
|
+
issues: c.error.issues ?? [{
|
|
1098
|
+
message: c.error.message,
|
|
1099
|
+
path: []
|
|
1100
|
+
}]
|
|
1101
|
+
};
|
|
1102
|
+
};
|
|
1103
|
+
return v instanceof Promise ? v.then(verdict) : verdict(v);
|
|
1104
|
+
},
|
|
1105
|
+
onReject: this.#seedReporter(def.name, from)
|
|
1106
|
+
})).then((r) => {
|
|
1107
|
+
this.#onSeed({
|
|
1108
|
+
kind: "seeded",
|
|
1109
|
+
topic: def.name,
|
|
1110
|
+
...r
|
|
1111
|
+
});
|
|
1112
|
+
this.#open(def.name, topic);
|
|
1113
|
+
}, (e) => {
|
|
1114
|
+
console.warn(`[isoloop] seeding ${def.name} from ${from} failed`, e);
|
|
1115
|
+
this.#open(def.name, topic);
|
|
1116
|
+
});
|
|
1117
|
+
runs.set(def.name, run);
|
|
1118
|
+
}
|
|
1119
|
+
return Promise.all(runs.values()).then(() => {});
|
|
1120
|
+
}
|
|
1121
|
+
/**
|
|
1122
|
+
* `follow` (ADR 0003, decision 18): a record appended to a seed source goes
|
|
1123
|
+
* on, through `map` and the topic's schema, to each topic that follows it
|
|
1124
|
+
* and isn't seeding (a seed in progress copies it itself).
|
|
1125
|
+
*/
|
|
1126
|
+
#follow(source, rec) {
|
|
1127
|
+
for (const topic of this.#topics.values()) {
|
|
1128
|
+
const seed = topic.def.seed;
|
|
1129
|
+
if (!seed?.follow || seed.from.name !== source || topic.seeding) continue;
|
|
1130
|
+
const name = topic.def.name;
|
|
1131
|
+
let report = this.#followReports.get(name);
|
|
1132
|
+
if (!report) this.#followReports.set(name, report = this.#seedReporter(name, source));
|
|
1133
|
+
const rejected = report;
|
|
1134
|
+
const mapped = mapRecord(seed.map, rec);
|
|
1135
|
+
if (!mapped.ok) {
|
|
1136
|
+
rejected(rec.offset, mapped);
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
const pending = {
|
|
1140
|
+
bytes: 0,
|
|
1141
|
+
producer: rec.producer,
|
|
1142
|
+
key: rec.key,
|
|
1143
|
+
req: void 0,
|
|
1144
|
+
ts: rec.ts,
|
|
1145
|
+
done: false,
|
|
1146
|
+
result: void 0,
|
|
1147
|
+
settle: (r) => {
|
|
1148
|
+
if (!r.ok) {
|
|
1149
|
+
const issues = r.error.issues ?? [{
|
|
1150
|
+
message: r.error.message,
|
|
1151
|
+
path: []
|
|
1152
|
+
}];
|
|
1153
|
+
rejected(rec.offset, {
|
|
1154
|
+
ok: false,
|
|
1155
|
+
code: r.error.code,
|
|
1156
|
+
issues
|
|
1157
|
+
});
|
|
1158
|
+
}
|
|
1159
|
+
}
|
|
1160
|
+
};
|
|
1161
|
+
this.#enqueue(name, topic, pending, validate(topic.def.schema, mapped.value));
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* Why `kernel.dropTopic(name)` may not delete `name`, if it may not (ADR
|
|
1166
|
+
* 0003, decision 19): the contracts list it, a declared seed that reads it
|
|
1167
|
+
* hasn't ended, or seed records rejected from it are recorded and `force`
|
|
1168
|
+
* isn't set.
|
|
1169
|
+
*/
|
|
1170
|
+
dropRefusal(name, force) {
|
|
1171
|
+
if (this.#topics.has(name)) return fail("invalid", `${name} is in the contracts`);
|
|
1172
|
+
for (const t of this.#topics.values()) {
|
|
1173
|
+
if (t.def.seed?.from.name !== name) continue;
|
|
1174
|
+
if (!seedDone(this.#engine, t.def.name)) return fail("seed_pending", `${t.def.name} still seeds from ${name}`);
|
|
1175
|
+
if (!force && (this.#engine.committed(t.def.name, "isoloop:seed:rejected") ?? 0) > 0) return fail("invalid", `${t.def.name} has rejected seed records from ${name}; pass { force: true } to drop them`);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
/** Persistent topics a declared seed reads that the contracts don't list. */
|
|
1179
|
+
get seedSources() {
|
|
1180
|
+
return [...this.#sources];
|
|
1181
|
+
}
|
|
1182
|
+
/** Reports rejected seed records, at most `SEED_REPORTS_PER_SEC` a second. */
|
|
1183
|
+
#seedReporter(topic, from) {
|
|
1184
|
+
let windowStart = -Infinity;
|
|
1185
|
+
let sent = 0;
|
|
1186
|
+
return (offset, v) => {
|
|
1187
|
+
const now = this.#now();
|
|
1188
|
+
if (now - windowStart >= 1e3) {
|
|
1189
|
+
windowStart = now;
|
|
1190
|
+
sent = 0;
|
|
1191
|
+
}
|
|
1192
|
+
if (sent >= 10) return;
|
|
1193
|
+
sent++;
|
|
1194
|
+
this.#onSeed({
|
|
1195
|
+
kind: "rejected",
|
|
1196
|
+
topic,
|
|
1197
|
+
from,
|
|
1198
|
+
offset,
|
|
1199
|
+
code: v.code,
|
|
1200
|
+
issues: v.issues
|
|
1201
|
+
});
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
/** A seed ended: the topic takes its waiting publishes, then its waiting subscribes. */
|
|
1205
|
+
#open(name, topic) {
|
|
1206
|
+
const held = topic.seeding ?? [];
|
|
1207
|
+
topic.seeding = void 0;
|
|
1208
|
+
this.#drain(name, topic);
|
|
1209
|
+
for (const h of held) {
|
|
1210
|
+
if (this.#conns.get(h.conn.isolateId) !== h.conn) continue;
|
|
1211
|
+
h.reply(this.#subscribe(h.conn, name, h.from, h.group));
|
|
1212
|
+
}
|
|
1213
|
+
if (this.#engine.durable(name)) this.#engine.flush();
|
|
1214
|
+
}
|
|
1215
|
+
/** Retention pass over every topic (`time` and `compacted`); the bus worker runs it every second. */
|
|
1216
|
+
compact() {
|
|
1217
|
+
for (const name of this.#topics.keys()) this.#engine.compact(name);
|
|
1218
|
+
}
|
|
1219
|
+
/**
|
|
1220
|
+
* Connects an isolate. A second attach for the same id replaces the first.
|
|
1221
|
+
* With `reattach`, the isolate was connected to a bus that restarted: its
|
|
1222
|
+
* first subscribe to each memory topic is answered with `reset` (ADR 0007).
|
|
1223
|
+
*/
|
|
1224
|
+
attach(isolateId, grants, port, opts = {}) {
|
|
1225
|
+
this.detach(isolateId, true);
|
|
1226
|
+
const conn = {
|
|
1227
|
+
isolateId,
|
|
1228
|
+
grants,
|
|
1229
|
+
port,
|
|
1230
|
+
subs: /* @__PURE__ */ new Map(),
|
|
1231
|
+
reset: opts.reattach ? /* @__PURE__ */ new Set() : void 0
|
|
1232
|
+
};
|
|
1233
|
+
this.#conns.set(isolateId, conn);
|
|
1234
|
+
port.onMessage((msg) => {
|
|
1235
|
+
if (this.#conns.get(isolateId) === conn) this.#receive(conn, msg);
|
|
1236
|
+
});
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Disconnects an isolate, drops its subscriptions and leaves its groups,
|
|
1240
|
+
* which rebalance. With `keepOffsets` its commits stay, so a restart with
|
|
1241
|
+
* `from: 'committed'` resumes (I6). Replies to its pending requests are dropped.
|
|
1242
|
+
*/
|
|
1243
|
+
detach(isolateId, keepOffsets, opts = {}) {
|
|
1244
|
+
if (!opts.wake) this.#unsleep(isolateId);
|
|
1245
|
+
const conn = this.#conns.get(isolateId);
|
|
1246
|
+
if (!conn) return;
|
|
1247
|
+
this.#conns.delete(isolateId);
|
|
1248
|
+
for (const sub of conn.subs.values()) {
|
|
1249
|
+
const g = sub.group;
|
|
1250
|
+
if (opts.wake && (!g || g.members.length === 1)) this.#sleep(sub.topic, isolateId);
|
|
1251
|
+
this.#leave(sub);
|
|
1252
|
+
}
|
|
1253
|
+
conn.subs.clear();
|
|
1254
|
+
if (!keepOffsets) for (const name of this.#topics.keys()) this.#forgotten.add(`${name}\u0000${isolateId}`);
|
|
1255
|
+
conn.port.close();
|
|
1256
|
+
}
|
|
1257
|
+
/**
|
|
1258
|
+
* Publishes for the host (`kernel.publish`) or the kernel (system topics).
|
|
1259
|
+
* The host can't publish system topics; the kernel can only publish them.
|
|
1260
|
+
*/
|
|
1261
|
+
publish(from, topic, key, value, id) {
|
|
1262
|
+
return new Promise((resolve) => this.#publish(from, topic, key, value, void 0, resolve, id));
|
|
1263
|
+
}
|
|
1264
|
+
#receive(conn, msg) {
|
|
1265
|
+
if (!isIsolateToBus(msg) || msg.t !== "commits" && !hasTopic(msg.p)) {
|
|
1266
|
+
this.#dropped++;
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
const reply = (r) => {
|
|
1270
|
+
if (msg.id !== void 0) conn.port.post({
|
|
1271
|
+
v: 1,
|
|
1272
|
+
t: "result",
|
|
1273
|
+
re: msg.id,
|
|
1274
|
+
p: r
|
|
1275
|
+
});
|
|
1276
|
+
};
|
|
1277
|
+
this.#handle(conn, msg, reply);
|
|
1278
|
+
}
|
|
1279
|
+
#handle(conn, msg, reply) {
|
|
1280
|
+
const self = {
|
|
1281
|
+
kind: "isolate",
|
|
1282
|
+
isolateId: conn.isolateId
|
|
1283
|
+
};
|
|
1284
|
+
switch (msg.t) {
|
|
1285
|
+
case "publish": {
|
|
1286
|
+
const key = msg.p.key;
|
|
1287
|
+
if (key !== void 0 && typeof key !== "string") {
|
|
1288
|
+
reply(fail("invalid", "key must be a string"));
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
this.#publish(self, msg.p.topic, key, msg.p.value, void 0, reply, publishId(msg.p));
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
case "request": {
|
|
1295
|
+
const { id } = msg;
|
|
1296
|
+
const key = msg.p.key;
|
|
1297
|
+
const timeoutMs = msg.p.timeoutMs;
|
|
1298
|
+
if (id === void 0) {
|
|
1299
|
+
this.#dropped++;
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
if (key !== void 0 && typeof key !== "string") {
|
|
1303
|
+
reply(fail("invalid", "key must be a string"));
|
|
1304
|
+
return;
|
|
1305
|
+
}
|
|
1306
|
+
const ms = typeof timeoutMs === "number" && timeoutMs > 0 ? timeoutMs : DEFAULT_REQUEST_TIMEOUT_MS;
|
|
1307
|
+
const onFail = (r) => {
|
|
1308
|
+
if (!r.ok) reply(r);
|
|
1309
|
+
};
|
|
1310
|
+
this.#publish(self, msg.p.topic, key, msg.p.value, {
|
|
1311
|
+
from: conn,
|
|
1312
|
+
id,
|
|
1313
|
+
timeoutMs: ms
|
|
1314
|
+
}, onFail, publishId(msg.p));
|
|
1315
|
+
return;
|
|
1316
|
+
}
|
|
1317
|
+
case "reply":
|
|
1318
|
+
this.#reply(conn, msg.p.topic, msg.p.offset, msg.p.value, reply);
|
|
1319
|
+
return;
|
|
1320
|
+
case "subscribe": {
|
|
1321
|
+
const held = this.#topics.get(msg.p.topic)?.seeding;
|
|
1322
|
+
if (held && (isSystemTopic(msg.p.topic) || matchAny(conn.grants.subscribe, msg.p.topic))) {
|
|
1323
|
+
held.push({
|
|
1324
|
+
conn,
|
|
1325
|
+
from: msg.p.from,
|
|
1326
|
+
group: msg.p.group,
|
|
1327
|
+
reply
|
|
1328
|
+
});
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
reply(this.#subscribe(conn, msg.p.topic, msg.p.from, msg.p.group));
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
case "unsubscribe": {
|
|
1335
|
+
const held = this.#topics.get(msg.p.topic)?.seeding;
|
|
1336
|
+
if (held) for (let i = held.length - 1; i >= 0; i--) {
|
|
1337
|
+
const h = held[i];
|
|
1338
|
+
if (h?.conn !== conn) continue;
|
|
1339
|
+
held.splice(i, 1);
|
|
1340
|
+
h.reply(fail("invalid", "unsubscribed before the seed ended"));
|
|
1341
|
+
}
|
|
1342
|
+
const sub = conn.subs.get(msg.p.topic);
|
|
1343
|
+
if (sub) this.#leave(sub);
|
|
1344
|
+
conn.subs.delete(msg.p.topic);
|
|
1345
|
+
reply({
|
|
1346
|
+
ok: true,
|
|
1347
|
+
value: null
|
|
1348
|
+
});
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
case "commits": {
|
|
1352
|
+
const offsets = msg.p.offsets;
|
|
1353
|
+
if (!Array.isArray(offsets)) {
|
|
1354
|
+
reply(fail("invalid", "commits needs an offsets array"));
|
|
1355
|
+
return;
|
|
1356
|
+
}
|
|
1357
|
+
let first = {
|
|
1358
|
+
ok: true,
|
|
1359
|
+
value: null
|
|
1360
|
+
};
|
|
1361
|
+
for (const e of offsets) {
|
|
1362
|
+
const r = typeof e === "object" && e !== null && "topic" in e && typeof e.topic === "string" ? this.#commit(conn, e.topic, "offset" in e ? e.offset : void 0, "seq" in e ? e.seq : void 0) : fail("invalid", "each commit needs a topic, an offset and a seq");
|
|
1363
|
+
if (!r.ok && first.ok) first = r;
|
|
1364
|
+
}
|
|
1365
|
+
reply(first);
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
default: {
|
|
1369
|
+
const never = msg;
|
|
1370
|
+
this.#dropped++;
|
|
1371
|
+
return never;
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
#publish(from, name, key, value, req, done, id) {
|
|
1376
|
+
const settle = (r) => {
|
|
1377
|
+
if (!r.ok) this.#rejected[r.error.code] = (this.#rejected[r.error.code] ?? 0) + 1;
|
|
1378
|
+
done(r);
|
|
1379
|
+
};
|
|
1380
|
+
const system = isSystemTopic(name);
|
|
1381
|
+
if (from.kind === "kernel" ? !system : system) {
|
|
1382
|
+
settle(fail("forbidden", `${from.kind} may not publish to ${name}`));
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
if (from.kind === "isolate") {
|
|
1386
|
+
const conn = this.#conns.get(from.isolateId);
|
|
1387
|
+
if (!conn || !matchAny(conn.grants.publish, name)) {
|
|
1388
|
+
settle(fail("forbidden", `no publish grant for ${name}`));
|
|
1389
|
+
return;
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
const topic = this.#topics.get(name);
|
|
1393
|
+
if (!topic) {
|
|
1394
|
+
settle(fail("unknown_topic", `unknown topic ${name}`));
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
if (req && !topic.def.reply) {
|
|
1398
|
+
settle(fail("not_requestable", `${name} has no reply schema`));
|
|
1399
|
+
return;
|
|
1400
|
+
}
|
|
1401
|
+
const bytes = estimateSize(value, topic.maxBytes);
|
|
1402
|
+
if (bytes > topic.maxBytes) {
|
|
1403
|
+
settle(fail("too_large", `record is over ${topic.maxBytes} bytes`));
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
const pending = {
|
|
1407
|
+
bytes,
|
|
1408
|
+
producer: from.kind === "isolate" ? from.isolateId : from.kind === "host" ? HOST_PRODUCER : KERNEL_PRODUCER,
|
|
1409
|
+
key,
|
|
1410
|
+
req,
|
|
1411
|
+
...id ? { id } : {},
|
|
1412
|
+
done: false,
|
|
1413
|
+
result: void 0,
|
|
1414
|
+
settle
|
|
1415
|
+
};
|
|
1416
|
+
this.#enqueue(name, topic, pending, validate(topic.def.schema, value));
|
|
1417
|
+
}
|
|
1418
|
+
/** Appends `pending` once its validation is done and everything ahead of it on the topic is. */
|
|
1419
|
+
#enqueue(name, topic, pending, result) {
|
|
1420
|
+
if (!(result instanceof Promise) && topic.queue.length === 0 && !topic.seeding) {
|
|
1421
|
+
pending.result = result;
|
|
1422
|
+
this.#finish(name, topic, pending);
|
|
1423
|
+
return;
|
|
1424
|
+
}
|
|
1425
|
+
topic.queue.push(pending);
|
|
1426
|
+
Promise.resolve(result).then((r) => {
|
|
1427
|
+
pending.result = r;
|
|
1428
|
+
pending.done = true;
|
|
1429
|
+
this.#drain(name, topic);
|
|
1430
|
+
});
|
|
1431
|
+
}
|
|
1432
|
+
/** Finishes queued publishes in order, stopping at the first still validating. */
|
|
1433
|
+
#drain(name, topic) {
|
|
1434
|
+
if (topic.seeding) return;
|
|
1435
|
+
while (topic.queue[0]?.done) {
|
|
1436
|
+
const next = topic.queue.shift();
|
|
1437
|
+
if (next) this.#finish(name, topic, next);
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
#finish(name, topic, p) {
|
|
1441
|
+
if (p.id && this.#engine.durable(name)) {
|
|
1442
|
+
const prior = this.#engine.appended(name, p.producer, p.id);
|
|
1443
|
+
if (prior !== void 0) {
|
|
1444
|
+
if (p.req) this.#openRequest(name, prior, p.req);
|
|
1445
|
+
this.#ackDurable(name, prior, p);
|
|
1446
|
+
return;
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
const checked = this.#check(name, p.result, topic.def.durability === "persistent");
|
|
1450
|
+
if (!checked.ok) {
|
|
1451
|
+
p.settle(checked);
|
|
1452
|
+
return;
|
|
1453
|
+
}
|
|
1454
|
+
if (this.#storageFull && this.#engine.durable(name)) {
|
|
1455
|
+
p.settle(fail("quota_exceeded", `${name}: the origin's storage is full`));
|
|
1456
|
+
return;
|
|
1457
|
+
}
|
|
1458
|
+
let rec = {
|
|
1459
|
+
value: checked.value,
|
|
1460
|
+
ts: p.ts ?? this.#now(),
|
|
1461
|
+
producer: p.producer
|
|
1462
|
+
};
|
|
1463
|
+
if (p.key !== void 0) rec = {
|
|
1464
|
+
...rec,
|
|
1465
|
+
key: p.key
|
|
1466
|
+
};
|
|
1467
|
+
if (p.req) rec = {
|
|
1468
|
+
...rec,
|
|
1469
|
+
req: {
|
|
1470
|
+
from: p.req.from.isolateId,
|
|
1471
|
+
id: p.req.id
|
|
1472
|
+
}
|
|
1473
|
+
};
|
|
1474
|
+
const offset = this.#engine.append(name, rec, p.id);
|
|
1475
|
+
topic.records++;
|
|
1476
|
+
topic.bytes += p.bytes;
|
|
1477
|
+
if (p.req) this.#openRequest(name, offset, p.req);
|
|
1478
|
+
if (this.#engine.durable(name)) this.#ackDurable(name, offset, p);
|
|
1479
|
+
else p.settle({
|
|
1480
|
+
ok: true,
|
|
1481
|
+
value: { offset }
|
|
1482
|
+
});
|
|
1483
|
+
this.#fanOut(name);
|
|
1484
|
+
this.#wake(name);
|
|
1485
|
+
this.#follow(name, {
|
|
1486
|
+
...rec,
|
|
1487
|
+
offset
|
|
1488
|
+
});
|
|
1489
|
+
}
|
|
1490
|
+
/**
|
|
1491
|
+
* Turns a schema result into the value to store, or the error to send. A
|
|
1492
|
+
* persistent topic's value must also encode (ADR 0007, consequences).
|
|
1493
|
+
*/
|
|
1494
|
+
#check(name, r, persistent = false) {
|
|
1495
|
+
if (!r || "thrown" in r) {
|
|
1496
|
+
const thrown = r ? String(r.thrown) : "no result";
|
|
1497
|
+
return fail("invalid", `schema threw: ${thrown}`, { issues: [{
|
|
1498
|
+
message: thrown,
|
|
1499
|
+
path: []
|
|
1500
|
+
}] });
|
|
1501
|
+
}
|
|
1502
|
+
if (r.issues) return fail("invalid", `invalid value for ${name}`, { issues: toIssues(r.issues) });
|
|
1503
|
+
if (persistent) try {
|
|
1504
|
+
encode(r.value);
|
|
1505
|
+
} catch (e) {
|
|
1506
|
+
if (e instanceof CodecError) return fail("not_encodable", `${name}: ${e.message}`);
|
|
1507
|
+
throw e;
|
|
1508
|
+
}
|
|
1509
|
+
else if (this.#dev) try {
|
|
1510
|
+
structuredClone(r.value);
|
|
1511
|
+
} catch (e) {
|
|
1512
|
+
return fail("not_encodable", `schema output can't be cloned: ${String(e)}`);
|
|
1513
|
+
}
|
|
1514
|
+
return {
|
|
1515
|
+
ok: true,
|
|
1516
|
+
value: r.value
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
/** Acknowledged once its batch is on disk (ADR 0007, decision 2). */
|
|
1520
|
+
#ackDurable(name, offset, p) {
|
|
1521
|
+
this.#engine.flush().then(() => p.settle({
|
|
1522
|
+
ok: true,
|
|
1523
|
+
value: { offset }
|
|
1524
|
+
}), (e) => p.settle(e instanceof DOMException && e.name === "QuotaExceededError" ? fail("quota_exceeded", `${name}: the origin's storage is full`) : fail("bus_unavailable", `${name}: write failed: ${String(e)}`)));
|
|
1525
|
+
}
|
|
1526
|
+
#openRequest(topic, offset, req) {
|
|
1527
|
+
const key = reqKey(topic, offset);
|
|
1528
|
+
this.#timers.set(() => this.#requests.delete(key), req.timeoutMs);
|
|
1529
|
+
this.#requests.set(key, {
|
|
1530
|
+
caller: req.from,
|
|
1531
|
+
id: req.id,
|
|
1532
|
+
recipients: /* @__PURE__ */ new Set(),
|
|
1533
|
+
done: false
|
|
1534
|
+
});
|
|
1535
|
+
}
|
|
1536
|
+
#reply(conn, name, offset, value, settle) {
|
|
1537
|
+
const topic = this.#topics.get(name);
|
|
1538
|
+
if (!topic) return settle(fail("unknown_topic", `unknown topic ${name}`));
|
|
1539
|
+
const schema = topic.def.reply;
|
|
1540
|
+
if (!schema) return settle(fail("not_requestable", `${name} has no reply schema`));
|
|
1541
|
+
if (!isOffset(offset)) return settle(fail("invalid", "offset must be a non-negative integer"));
|
|
1542
|
+
const req = this.#requests.get(reqKey(name, offset));
|
|
1543
|
+
if (!req) {
|
|
1544
|
+
const rec = this.#engine.read(name, offset, 1)[0];
|
|
1545
|
+
return settle(rec?.offset === offset && rec.req ? fail("timeout", `request ${name}@${offset} has expired`) : fail("invalid", `${name}@${offset} is not a request`));
|
|
1546
|
+
}
|
|
1547
|
+
if (!req.recipients.has(conn.isolateId)) return settle(fail("forbidden", `request ${name}@${offset} was not delivered to you`));
|
|
1548
|
+
if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
|
|
1549
|
+
if (estimateSize(value, topic.maxBytes) > topic.maxBytes) return settle(fail("too_large", `reply is over ${topic.maxBytes} bytes`));
|
|
1550
|
+
const answer = (r) => {
|
|
1551
|
+
if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
|
|
1552
|
+
req.done = true;
|
|
1553
|
+
const checked = this.#check(name, r);
|
|
1554
|
+
const callerAlive = this.#conns.get(req.caller.isolateId) === req.caller;
|
|
1555
|
+
if (!checked.ok) {
|
|
1556
|
+
settle(checked);
|
|
1557
|
+
if (callerAlive) {
|
|
1558
|
+
const issues = checked.error.issues;
|
|
1559
|
+
this.#post(req.caller, req.id, fail("reply_invalid", `invalid reply on ${name}`, issues ? { issues } : {}));
|
|
1560
|
+
}
|
|
1561
|
+
return;
|
|
1562
|
+
}
|
|
1563
|
+
if (callerAlive) this.#post(req.caller, req.id, checked);
|
|
1564
|
+
settle({
|
|
1565
|
+
ok: true,
|
|
1566
|
+
value: { delivered: callerAlive }
|
|
1567
|
+
});
|
|
1568
|
+
};
|
|
1569
|
+
const result = validate(schema, value);
|
|
1570
|
+
if (result instanceof Promise) result.then(answer);
|
|
1571
|
+
else answer(result);
|
|
1572
|
+
}
|
|
1573
|
+
#post(conn, re, r) {
|
|
1574
|
+
conn.port.post({
|
|
1575
|
+
v: 1,
|
|
1576
|
+
t: "result",
|
|
1577
|
+
re,
|
|
1578
|
+
p: r
|
|
1579
|
+
});
|
|
1580
|
+
}
|
|
1581
|
+
#subscribe(conn, name, from, group) {
|
|
1582
|
+
if (!isStartPosition(from)) return fail("invalid", "from must be latest, earliest or committed");
|
|
1583
|
+
if (group !== void 0 && (typeof group !== "string" || group === "")) return fail("invalid", "group must be a non-empty string");
|
|
1584
|
+
if (!isSystemTopic(name) && !matchAny(conn.grants.subscribe, name)) return fail("forbidden", `no subscribe grant for ${name}`);
|
|
1585
|
+
if (!this.#topics.has(name)) return fail("unknown_topic", `unknown topic ${name}`);
|
|
1586
|
+
if (conn.reset && !conn.reset.has(name) && !this.#durable(name)) {
|
|
1587
|
+
conn.reset.add(name);
|
|
1588
|
+
conn.port.post({
|
|
1589
|
+
v: 1,
|
|
1590
|
+
t: "reset",
|
|
1591
|
+
p: {
|
|
1592
|
+
topic: name,
|
|
1593
|
+
reason: "bus_restart"
|
|
1594
|
+
}
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
const consumer = group === void 0 ? conn.isolateId : `group:${group}`;
|
|
1598
|
+
const start = conn.reset && this.#durable(name) && this.#committed(name, consumer) !== void 0 ? "committed" : from;
|
|
1599
|
+
const old = conn.subs.get(name);
|
|
1600
|
+
if (old) this.#leave(old);
|
|
1601
|
+
const sub = {
|
|
1602
|
+
conn,
|
|
1603
|
+
topic: name,
|
|
1604
|
+
group: void 0,
|
|
1605
|
+
cursor: 0,
|
|
1606
|
+
credit: this.#inboxLimit,
|
|
1607
|
+
unacked: [],
|
|
1608
|
+
seq: 0,
|
|
1609
|
+
scheduled: false
|
|
1610
|
+
};
|
|
1611
|
+
conn.subs.set(name, sub);
|
|
1612
|
+
if (group === void 0) {
|
|
1613
|
+
sub.cursor = this.#start(name, conn.isolateId, start);
|
|
1614
|
+
this.#schedule(sub);
|
|
1615
|
+
return {
|
|
1616
|
+
ok: true,
|
|
1617
|
+
value: { from: sub.cursor }
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
return {
|
|
1621
|
+
ok: true,
|
|
1622
|
+
value: {
|
|
1623
|
+
from: this.#join(sub, group, start).cursor,
|
|
1624
|
+
group
|
|
1625
|
+
}
|
|
1626
|
+
};
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Adds a member to a group. A group with no members starts after its
|
|
1630
|
+
* committed offset when it has one, whatever `from` says, and at `from`
|
|
1631
|
+
* only before its first commit (ADR 0016, point 14). A member joining a
|
|
1632
|
+
* group that has members takes records from where the group is.
|
|
1633
|
+
*/
|
|
1634
|
+
#join(sub, name, from) {
|
|
1635
|
+
const id = `${sub.topic}\u0000${name}`;
|
|
1636
|
+
let g = this.#groups.get(id);
|
|
1637
|
+
if (!g) {
|
|
1638
|
+
const consumer = `group:${name}`;
|
|
1639
|
+
const committed = this.#committed(sub.topic, consumer) !== void 0;
|
|
1640
|
+
g = {
|
|
1641
|
+
topic: sub.topic,
|
|
1642
|
+
name,
|
|
1643
|
+
consumer,
|
|
1644
|
+
cursor: this.#start(sub.topic, consumer, committed ? "committed" : from),
|
|
1645
|
+
members: [],
|
|
1646
|
+
rr: 0,
|
|
1647
|
+
unacked: [],
|
|
1648
|
+
redeliver: [],
|
|
1649
|
+
scheduled: false
|
|
1650
|
+
};
|
|
1651
|
+
this.#groups.set(id, g);
|
|
1652
|
+
}
|
|
1653
|
+
sub.group = g;
|
|
1654
|
+
g.members.push(sub);
|
|
1655
|
+
g.members.sort((a, b) => a.conn.isolateId < b.conn.isolateId ? -1 : 1);
|
|
1656
|
+
this.#scheduleGroup(g);
|
|
1657
|
+
return g;
|
|
1658
|
+
}
|
|
1659
|
+
/** Ends a subscription. A group member's uncommitted records go to the others. */
|
|
1660
|
+
#leave(sub) {
|
|
1661
|
+
const g = sub.group;
|
|
1662
|
+
if (!g) return;
|
|
1663
|
+
sub.group = void 0;
|
|
1664
|
+
g.members = g.members.filter((m) => m !== sub);
|
|
1665
|
+
if (g.members.length === 0) {
|
|
1666
|
+
this.#groups.delete(`${g.topic}\u0000${g.name}`);
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
for (const u of g.unacked) if (u.member === sub) {
|
|
1670
|
+
u.member = void 0;
|
|
1671
|
+
g.redeliver.push(u.offset);
|
|
1672
|
+
}
|
|
1673
|
+
g.redeliver.sort((a, b) => a - b);
|
|
1674
|
+
this.#scheduleGroup(g);
|
|
1675
|
+
}
|
|
1676
|
+
/** `latest` → head, `earliest` → tail, `committed` → committed + 1, else earliest. */
|
|
1677
|
+
#start(name, consumer, from) {
|
|
1678
|
+
if (from === "latest") return this.#engine.head(name);
|
|
1679
|
+
if (from === "committed") {
|
|
1680
|
+
const c = this.#committed(name, consumer);
|
|
1681
|
+
if (c !== void 0) return c + 1;
|
|
1682
|
+
}
|
|
1683
|
+
return this.#engine.tail(name);
|
|
1684
|
+
}
|
|
1685
|
+
#committed(name, consumer) {
|
|
1686
|
+
if (this.#forgotten.has(`${name}\u0000${consumer}`)) return void 0;
|
|
1687
|
+
return this.#engine.committed(name, consumer);
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* A commit covers the records delivered up to `offset`. In a group it also
|
|
1691
|
+
* needs their delivery's `seq` at or below `seq`: a record redelivered to
|
|
1692
|
+
* this member after the deliveries the commit settled has a higher one,
|
|
1693
|
+
* whatever its offset (ADR 0016, point 12). An own subscription's
|
|
1694
|
+
* deliveries are in order, so the offset alone decides there.
|
|
1695
|
+
*/
|
|
1696
|
+
#commit(conn, name, offset, seq) {
|
|
1697
|
+
const sub = conn.subs.get(name);
|
|
1698
|
+
if (!sub) return fail("forbidden", `not subscribed to ${name}`);
|
|
1699
|
+
if (!isOffset(offset)) return fail("invalid", "offset must be a non-negative integer");
|
|
1700
|
+
if (!isSeq(seq)) return fail("invalid", "seq must be a non-negative integer");
|
|
1701
|
+
if (offset >= this.#engine.head(name)) return fail("invalid", `offset ${offset} is not in ${name} yet`);
|
|
1702
|
+
const g = sub.group;
|
|
1703
|
+
const covers = (d) => d.offset <= offset && (!g || d.seq <= seq);
|
|
1704
|
+
const before = sub.unacked.length;
|
|
1705
|
+
if (g) sub.unacked = sub.unacked.filter((d) => !covers(d));
|
|
1706
|
+
else while (sub.unacked[0] && covers(sub.unacked[0])) sub.unacked.shift();
|
|
1707
|
+
const freed = before - sub.unacked.length;
|
|
1708
|
+
sub.credit += freed;
|
|
1709
|
+
if (g) {
|
|
1710
|
+
g.unacked = g.unacked.filter((u) => !(u.member === sub && covers(u)));
|
|
1711
|
+
const upTo = (g.unacked[0]?.offset ?? g.cursor) - 1;
|
|
1712
|
+
if (upTo > (this.#engine.committed(name, g.consumer) ?? -1)) this.#engine.commit(name, g.consumer, upTo);
|
|
1713
|
+
if (freed > 0) this.#scheduleGroup(g);
|
|
1714
|
+
} else {
|
|
1715
|
+
this.#forgotten.delete(`${name}\u0000${conn.isolateId}`);
|
|
1716
|
+
this.#engine.commit(name, conn.isolateId, offset);
|
|
1717
|
+
if (freed > 0) this.#schedule(sub);
|
|
1718
|
+
}
|
|
1719
|
+
return {
|
|
1720
|
+
ok: true,
|
|
1721
|
+
value: null
|
|
1722
|
+
};
|
|
1723
|
+
}
|
|
1724
|
+
#fanOut(name) {
|
|
1725
|
+
for (const conn of this.#conns.values()) {
|
|
1726
|
+
const sub = conn.subs.get(name);
|
|
1727
|
+
if (!sub) continue;
|
|
1728
|
+
if (sub.group) this.#scheduleGroup(sub.group);
|
|
1729
|
+
else this.#schedule(sub);
|
|
1730
|
+
}
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Queues one pump per subscription per microtask, so records published in
|
|
1734
|
+
* the same task go out together.
|
|
1735
|
+
*/
|
|
1736
|
+
#schedule(sub) {
|
|
1737
|
+
if (sub.scheduled) return;
|
|
1738
|
+
sub.scheduled = true;
|
|
1739
|
+
queueMicrotask(() => {
|
|
1740
|
+
sub.scheduled = false;
|
|
1741
|
+
if (this.#conns.get(sub.conn.isolateId) === sub.conn && sub.conn.subs.get(sub.topic) === sub) this.#pump(sub);
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
/**
|
|
1745
|
+
* Reads evicted records back from disk (M2b task 11), then calls `then`
|
|
1746
|
+
* to pump again. A page that fails is retried by the next pump: the next
|
|
1747
|
+
* publish or commit.
|
|
1748
|
+
*/
|
|
1749
|
+
#pageIn(topic, offset, then) {
|
|
1750
|
+
this.#engine.page(topic, offset).then(then, (e) => {
|
|
1751
|
+
console.warn(`[isoloop] reading ${topic}@${offset} back from disk failed`, e);
|
|
1752
|
+
});
|
|
1753
|
+
}
|
|
1754
|
+
#scheduleGroup(g) {
|
|
1755
|
+
if (g.scheduled) return;
|
|
1756
|
+
g.scheduled = true;
|
|
1757
|
+
queueMicrotask(() => {
|
|
1758
|
+
g.scheduled = false;
|
|
1759
|
+
if (this.#groups.get(`${g.topic}\u0000${g.name}`) === g) this.#pumpGroup(g);
|
|
1760
|
+
});
|
|
1761
|
+
}
|
|
1762
|
+
/** Expired records between the cursor and the tail, as a gap. Compaction is not a gap. */
|
|
1763
|
+
#gap(topic, cursor) {
|
|
1764
|
+
const tail = this.#engine.tail(topic);
|
|
1765
|
+
if (cursor >= tail) return void 0;
|
|
1766
|
+
if (this.#topics.get(topic)?.def.retention.kind === "compacted") return void 0;
|
|
1767
|
+
return {
|
|
1768
|
+
from: cursor,
|
|
1769
|
+
to: tail - 1
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
/** Sends one `deliver`, numbered with the subscription's next `seq`, and returns it. */
|
|
1773
|
+
#deliver(sub, records, gap) {
|
|
1774
|
+
const seq = ++sub.seq;
|
|
1775
|
+
for (const r of records) {
|
|
1776
|
+
sub.unacked.push({
|
|
1777
|
+
offset: r.offset,
|
|
1778
|
+
seq
|
|
1779
|
+
});
|
|
1780
|
+
if (r.req) this.#requests.get(reqKey(sub.topic, r.offset))?.recipients.add(sub.conn.isolateId);
|
|
1781
|
+
}
|
|
1782
|
+
sub.credit -= records.length;
|
|
1783
|
+
sub.conn.port.post({
|
|
1784
|
+
v: 1,
|
|
1785
|
+
t: "deliver",
|
|
1786
|
+
p: gap ? {
|
|
1787
|
+
topic: sub.topic,
|
|
1788
|
+
records,
|
|
1789
|
+
gap,
|
|
1790
|
+
seq
|
|
1791
|
+
} : {
|
|
1792
|
+
topic: sub.topic,
|
|
1793
|
+
records,
|
|
1794
|
+
seq
|
|
1795
|
+
}
|
|
1796
|
+
});
|
|
1797
|
+
return seq;
|
|
1798
|
+
}
|
|
1799
|
+
/**
|
|
1800
|
+
* Delivers from the cursor while there is credit, in batches. At 0 credit
|
|
1801
|
+
* the subscription is paused: nothing is queued, only the cursor is kept,
|
|
1802
|
+
* and a commit resumes it from the log. Records that expired meanwhile are
|
|
1803
|
+
* reported as `gap`.
|
|
1804
|
+
*/
|
|
1805
|
+
#pump(sub) {
|
|
1806
|
+
if (sub.credit <= 0) return;
|
|
1807
|
+
let gap = this.#gap(sub.topic, sub.cursor);
|
|
1808
|
+
if (gap) sub.cursor = gap.to + 1;
|
|
1809
|
+
const head = this.#engine.head(sub.topic);
|
|
1810
|
+
while (sub.credit > 0 && sub.cursor < head) {
|
|
1811
|
+
if (!this.#engine.readable(sub.topic, sub.cursor)) {
|
|
1812
|
+
this.#pageIn(sub.topic, sub.cursor, () => this.#schedule(sub));
|
|
1813
|
+
break;
|
|
1814
|
+
}
|
|
1815
|
+
const records = this.#engine.read(sub.topic, sub.cursor, Math.min(this.#batch, sub.credit));
|
|
1816
|
+
const last = records.at(-1);
|
|
1817
|
+
if (!last) {
|
|
1818
|
+
sub.cursor = head;
|
|
1819
|
+
break;
|
|
1820
|
+
}
|
|
1821
|
+
sub.cursor = last.offset + 1;
|
|
1822
|
+
this.#deliver(sub, records, gap);
|
|
1823
|
+
gap = void 0;
|
|
1824
|
+
}
|
|
1825
|
+
if (gap) this.#deliver(sub, [], gap);
|
|
1826
|
+
}
|
|
1827
|
+
/** The member a record goes to: by key hash, or round-robin when keyless. */
|
|
1828
|
+
#owner(g, rec) {
|
|
1829
|
+
const n = g.members.length;
|
|
1830
|
+
return g.members[rec.key === void 0 ? g.rr % n : hash(rec.key) % n];
|
|
1831
|
+
}
|
|
1832
|
+
/**
|
|
1833
|
+
* Hands records to group members: first those a departed member left
|
|
1834
|
+
* uncommitted, then new ones from the group cursor. If a record's member is
|
|
1835
|
+
* out of credit the group waits for it, which keeps per-key order.
|
|
1836
|
+
*/
|
|
1837
|
+
#pumpGroup(g) {
|
|
1838
|
+
if (g.members.length === 0) return;
|
|
1839
|
+
const batches = /* @__PURE__ */ new Map();
|
|
1840
|
+
const flush = (m) => {
|
|
1841
|
+
const b = batches.get(m);
|
|
1842
|
+
batches.delete(m);
|
|
1843
|
+
if (!b || b.records.length === 0) return;
|
|
1844
|
+
const seq = this.#deliver(m, b.records);
|
|
1845
|
+
for (const e of b.entries) e.seq = seq;
|
|
1846
|
+
};
|
|
1847
|
+
/** Credit left once the records batched for it go out. */
|
|
1848
|
+
const room = (m) => m ? m.credit - (batches.get(m)?.records.length ?? 0) : 0;
|
|
1849
|
+
const give = (m, rec, entry) => {
|
|
1850
|
+
const b = batches.get(m) ?? {
|
|
1851
|
+
records: [],
|
|
1852
|
+
entries: []
|
|
1853
|
+
};
|
|
1854
|
+
b.records.push(rec);
|
|
1855
|
+
if (entry) b.entries.push(entry);
|
|
1856
|
+
batches.set(m, b);
|
|
1857
|
+
if (rec.key === void 0) g.rr++;
|
|
1858
|
+
if (b.records.length >= this.#batch) flush(m);
|
|
1859
|
+
};
|
|
1860
|
+
const gap = this.#gap(g.topic, g.cursor);
|
|
1861
|
+
if (gap) {
|
|
1862
|
+
g.cursor = gap.to + 1;
|
|
1863
|
+
for (const m of g.members) this.#deliver(m, [], gap);
|
|
1864
|
+
}
|
|
1865
|
+
const tail = this.#engine.tail(g.topic);
|
|
1866
|
+
let blocked = false;
|
|
1867
|
+
while (g.redeliver.length > 0) {
|
|
1868
|
+
const offset = g.redeliver[0] ?? 0;
|
|
1869
|
+
if (offset >= tail && !this.#engine.readable(g.topic, offset)) {
|
|
1870
|
+
this.#pageIn(g.topic, offset, () => this.#scheduleGroup(g));
|
|
1871
|
+
blocked = true;
|
|
1872
|
+
break;
|
|
1873
|
+
}
|
|
1874
|
+
const rec = offset >= tail ? this.#engine.read(g.topic, offset, 1)[0] : void 0;
|
|
1875
|
+
if (rec?.offset !== offset) {
|
|
1876
|
+
g.redeliver.shift();
|
|
1877
|
+
g.unacked = g.unacked.filter((u) => u.offset !== offset);
|
|
1878
|
+
continue;
|
|
1879
|
+
}
|
|
1880
|
+
const m = this.#owner(g, rec);
|
|
1881
|
+
if (!m || room(m) <= 0) {
|
|
1882
|
+
blocked = true;
|
|
1883
|
+
break;
|
|
1884
|
+
}
|
|
1885
|
+
g.redeliver.shift();
|
|
1886
|
+
const entry = g.unacked.find((u) => u.offset === offset);
|
|
1887
|
+
if (entry) entry.member = m;
|
|
1888
|
+
give(m, rec, entry);
|
|
1889
|
+
}
|
|
1890
|
+
const head = this.#engine.head(g.topic);
|
|
1891
|
+
let more = !blocked;
|
|
1892
|
+
while (more && g.cursor < head) {
|
|
1893
|
+
if (!this.#engine.readable(g.topic, g.cursor)) {
|
|
1894
|
+
this.#pageIn(g.topic, g.cursor, () => this.#scheduleGroup(g));
|
|
1895
|
+
break;
|
|
1896
|
+
}
|
|
1897
|
+
const records = this.#engine.read(g.topic, g.cursor, this.#batch);
|
|
1898
|
+
if (records.length === 0) {
|
|
1899
|
+
g.cursor = head;
|
|
1900
|
+
break;
|
|
1901
|
+
}
|
|
1902
|
+
for (const rec of records) {
|
|
1903
|
+
const m = this.#owner(g, rec);
|
|
1904
|
+
if (!m || room(m) <= 0) {
|
|
1905
|
+
more = false;
|
|
1906
|
+
break;
|
|
1907
|
+
}
|
|
1908
|
+
const entry = {
|
|
1909
|
+
offset: rec.offset,
|
|
1910
|
+
member: m,
|
|
1911
|
+
seq: 0
|
|
1912
|
+
};
|
|
1913
|
+
g.unacked.push(entry);
|
|
1914
|
+
give(m, rec, entry);
|
|
1915
|
+
g.cursor = rec.offset + 1;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
for (const m of batches.keys()) flush(m);
|
|
1919
|
+
}
|
|
1920
|
+
};
|
|
1921
|
+
/** Runs a Standard Schema, turning a throw or a rejection into a result. */
|
|
1922
|
+
function validate(schema, value) {
|
|
1923
|
+
let r;
|
|
1924
|
+
try {
|
|
1925
|
+
r = schema["~standard"].validate(value);
|
|
1926
|
+
} catch (thrown) {
|
|
1927
|
+
return { thrown };
|
|
1928
|
+
}
|
|
1929
|
+
if (!(r instanceof Promise)) return r;
|
|
1930
|
+
return r.then((x) => x, (thrown) => ({ thrown }));
|
|
1931
|
+
}
|
|
1932
|
+
// src/engine/memory-storage.ts
|
|
1933
|
+
/** Storage that keeps nothing. Every topic behaves as `memory`. */
|
|
1934
|
+
var MemoryStorage = class {
|
|
1935
|
+
kind = "memory";
|
|
1936
|
+
open() {
|
|
1937
|
+
return Promise.resolve({
|
|
1938
|
+
topics: [],
|
|
1939
|
+
offsets: {}
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
appendBatch(_topic, _encoded) {}
|
|
1943
|
+
flush() {
|
|
1944
|
+
return Promise.resolve();
|
|
1945
|
+
}
|
|
1946
|
+
saveOffsets(_offsets) {}
|
|
1947
|
+
dropBelow(_topic, _tail) {}
|
|
1948
|
+
rewrite(_topic, _keep) {
|
|
1949
|
+
return Promise.resolve();
|
|
1950
|
+
}
|
|
1951
|
+
readSegment(_topic, _fromOffset) {
|
|
1952
|
+
return Promise.resolve([]);
|
|
1953
|
+
}
|
|
1954
|
+
bytes(_topic) {
|
|
1955
|
+
return Promise.resolve(0);
|
|
1956
|
+
}
|
|
1957
|
+
deleteTopic(_topic) {
|
|
1958
|
+
return Promise.resolve(false);
|
|
1959
|
+
}
|
|
1960
|
+
quarantineNewest() {
|
|
1961
|
+
return Promise.resolve([]);
|
|
1962
|
+
}
|
|
1963
|
+
};
|
|
1964
|
+
/**
|
|
1965
|
+
* Engines call this from `createTopic`: the durability a topic actually gets.
|
|
1966
|
+
* A `persistent` topic on storage that keeps nothing (no OPFS, or another tab
|
|
1967
|
+
* holds it) behaves as `memory`; the kernel reports that as
|
|
1968
|
+
* `bus:durability-degraded` (ADR 0007, decision 6).
|
|
1969
|
+
*/
|
|
1970
|
+
function effectiveDurability(cfg, storage) {
|
|
1971
|
+
if (cfg.durability !== "persistent") return "memory";
|
|
1972
|
+
return storage.kind === "memory" ? "memory" : "persistent";
|
|
1973
|
+
}
|
|
1974
|
+
const OFFSET = 8;
|
|
1975
|
+
const TABLE = (() => {
|
|
1976
|
+
const t = /* @__PURE__ */ new Uint32Array(256);
|
|
1977
|
+
for (let n = 0; n < 256; n++) {
|
|
1978
|
+
let c = n;
|
|
1979
|
+
for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
1980
|
+
t[n] = c >>> 0;
|
|
1981
|
+
}
|
|
1982
|
+
return t;
|
|
1983
|
+
})();
|
|
1984
|
+
/** CRC-32 (IEEE 802.3, as in zip and PNG). */
|
|
1985
|
+
function crc32(bytes, start = 0, end = bytes.length) {
|
|
1986
|
+
let c = 4294967295;
|
|
1987
|
+
for (let i = start; i < end; i++) c = (TABLE[(c ^ (bytes[i] ?? 0)) & 255] ?? 0) ^ c >>> 8;
|
|
1988
|
+
return (c ^ 4294967295) >>> 0;
|
|
1989
|
+
}
|
|
1990
|
+
/** A frame: `number` in the header, `value` encoded after it. */
|
|
1991
|
+
function pack(number, value) {
|
|
1992
|
+
const body = encode(value);
|
|
1993
|
+
const out = new Uint8Array(16 + body.length);
|
|
1994
|
+
const view = new DataView(out.buffer);
|
|
1995
|
+
view.setUint32(0, OFFSET + body.length, true);
|
|
1996
|
+
view.setFloat64(8, number, true);
|
|
1997
|
+
out.set(body, 16);
|
|
1998
|
+
view.setUint32(4, crc32(out, 8), true);
|
|
1999
|
+
return out;
|
|
2000
|
+
}
|
|
2001
|
+
/** The value of a frame written by `pack`. */
|
|
2002
|
+
function unpack(frame) {
|
|
2003
|
+
return decode(frame.subarray(16));
|
|
2004
|
+
}
|
|
2005
|
+
/** Encodes a record as one frame. Throws the codec's `not_encodable`. */
|
|
2006
|
+
function encodeFrame(rec) {
|
|
2007
|
+
const fields = [
|
|
2008
|
+
rec.ts,
|
|
2009
|
+
rec.producer,
|
|
2010
|
+
rec.value,
|
|
2011
|
+
rec.key,
|
|
2012
|
+
rec.req,
|
|
2013
|
+
rec.epoch,
|
|
2014
|
+
rec.seq
|
|
2015
|
+
];
|
|
2016
|
+
while (fields.length > 3 && fields.at(-1) === void 0) fields.pop();
|
|
2017
|
+
return pack(rec.offset, fields);
|
|
2018
|
+
}
|
|
2019
|
+
/** The offset in a frame's header. */
|
|
2020
|
+
function frameOffset(frame) {
|
|
2021
|
+
return new DataView(frame.buffer, frame.byteOffset).getFloat64(8, true);
|
|
2022
|
+
}
|
|
2023
|
+
/** Splits bytes into frames, stopping at the first torn or corrupt one. */
|
|
2024
|
+
function scanFrames(bytes) {
|
|
2025
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
2026
|
+
const frames = [];
|
|
2027
|
+
let at = 0;
|
|
2028
|
+
while (at + 8 <= bytes.length) {
|
|
2029
|
+
const length = view.getUint32(at, true);
|
|
2030
|
+
const end = at + 8 + length;
|
|
2031
|
+
if (length < OFFSET || end > bytes.length) break;
|
|
2032
|
+
if (crc32(bytes, at + 8, end) !== view.getUint32(at + 4, true)) break;
|
|
2033
|
+
frames.push(bytes.subarray(at, end));
|
|
2034
|
+
at = end;
|
|
2035
|
+
}
|
|
2036
|
+
return {
|
|
2037
|
+
frames,
|
|
2038
|
+
valid: at
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
const isList = (x) => Array.isArray(x);
|
|
2042
|
+
const isReq = (x) => typeof x === "object" && x !== null && typeof Reflect.get(x, "from") === "string" && typeof Reflect.get(x, "id") === "string";
|
|
2043
|
+
/** Decodes one frame written by `encodeFrame`. */
|
|
2044
|
+
function decodeFrame(frame) {
|
|
2045
|
+
const offset = frameOffset(frame);
|
|
2046
|
+
const fields = unpack(frame);
|
|
2047
|
+
const [ts, producer, value, key, req, epoch, seq] = isList(fields) ? fields : [];
|
|
2048
|
+
if (typeof ts !== "number" || typeof producer !== "string") throw new Error(`frame at offset ${offset} is not a record`);
|
|
2049
|
+
const rec = {
|
|
2050
|
+
offset,
|
|
2051
|
+
value,
|
|
2052
|
+
ts,
|
|
2053
|
+
producer
|
|
2054
|
+
};
|
|
2055
|
+
if (typeof key === "string") rec.key = key;
|
|
2056
|
+
if (isReq(req)) rec.req = req;
|
|
2057
|
+
if (typeof epoch === "number") rec.epoch = epoch;
|
|
2058
|
+
if (typeof seq === "number") rec.seq = seq;
|
|
2059
|
+
return rec;
|
|
2060
|
+
}
|
|
2061
|
+
/** Pages of evicted records kept per engine, newest last. */
|
|
2062
|
+
const PAGES = 8;
|
|
2063
|
+
/** A compacted topic compacts itself once this share of its records is superseded… */
|
|
2064
|
+
const DIRTY_RATIO = .5;
|
|
2065
|
+
/** …and at least this many are. */
|
|
2066
|
+
const DIRTY_MIN = 1024;
|
|
2067
|
+
/**
|
|
2068
|
+
* The TypeScript `LogEngine` (design §6.2). Each topic is an array of
|
|
2069
|
+
* fixed-size chunks, so dropping old records frees a whole chunk at a time:
|
|
2070
|
+
* O(1) per chunk. Compacted topics keep a key → latest-offset index.
|
|
2071
|
+
*/
|
|
2072
|
+
var TsEngine = class {
|
|
2073
|
+
name = "ts";
|
|
2074
|
+
#topics = /* @__PURE__ */ new Map();
|
|
2075
|
+
#now;
|
|
2076
|
+
#storage;
|
|
2077
|
+
#size;
|
|
2078
|
+
#dirtyMin;
|
|
2079
|
+
#residentBytes;
|
|
2080
|
+
#pages = [];
|
|
2081
|
+
#paging = /* @__PURE__ */ new Map();
|
|
2082
|
+
/** While restoring, records are read back from disk: don't compact it under the read. */
|
|
2083
|
+
#restoring = false;
|
|
2084
|
+
constructor(opts = {}) {
|
|
2085
|
+
this.#now = opts.now ?? Date.now;
|
|
2086
|
+
this.#size = opts.chunkSize ?? 4096;
|
|
2087
|
+
this.#dirtyMin = opts.dirtyMin ?? DIRTY_MIN;
|
|
2088
|
+
this.#residentBytes = opts.residentBytes ?? 8388608;
|
|
2089
|
+
this.#storage = opts.storage ?? new MemoryStorage();
|
|
2090
|
+
}
|
|
2091
|
+
#topic(name) {
|
|
2092
|
+
const t = this.#topics.get(name);
|
|
2093
|
+
if (!t) throw new Error(`unknown topic ${name}`);
|
|
2094
|
+
return t;
|
|
2095
|
+
}
|
|
2096
|
+
createTopic(cfg) {
|
|
2097
|
+
if (this.#topics.has(cfg.name)) throw new Error(`topic ${cfg.name} exists`);
|
|
2098
|
+
const durable = effectiveDurability(cfg, this.#storage) === "persistent";
|
|
2099
|
+
this.#topics.set(cfg.name, {
|
|
2100
|
+
durable,
|
|
2101
|
+
dropped: 0,
|
|
2102
|
+
diskDirty: 0,
|
|
2103
|
+
evictedTo: 0,
|
|
2104
|
+
chunkBytes: [],
|
|
2105
|
+
residentBytes: 0,
|
|
2106
|
+
evicted: [],
|
|
2107
|
+
appended: /* @__PURE__ */ new Map(),
|
|
2108
|
+
cfg,
|
|
2109
|
+
base: 0,
|
|
2110
|
+
chunks: [],
|
|
2111
|
+
head: 0,
|
|
2112
|
+
tail: 0,
|
|
2113
|
+
live: 0,
|
|
2114
|
+
keys: cfg.retention.kind === "compacted" ? /* @__PURE__ */ new Map() : void 0,
|
|
2115
|
+
dirty: 0,
|
|
2116
|
+
commits: /* @__PURE__ */ new Map()
|
|
2117
|
+
});
|
|
2118
|
+
}
|
|
2119
|
+
append(topic, rec, id) {
|
|
2120
|
+
const t = this.#topic(topic);
|
|
2121
|
+
const frame = t.durable ? encodeFrame({
|
|
2122
|
+
...rec,
|
|
2123
|
+
...id,
|
|
2124
|
+
offset: t.head
|
|
2125
|
+
}) : void 0;
|
|
2126
|
+
if (frame) this.#storage.appendBatch(topic, [frame]);
|
|
2127
|
+
if (t.durable && id) remember(t, rec.producer, id, t.head);
|
|
2128
|
+
return this.#place(t, rec, t.head, frame?.length ?? 0);
|
|
2129
|
+
}
|
|
2130
|
+
appended(topic, producer, id) {
|
|
2131
|
+
const a = this.#topics.get(topic)?.appended.get(producer);
|
|
2132
|
+
return a?.epoch === id.epoch ? a.seqs.get(id.seq) : void 0;
|
|
2133
|
+
}
|
|
2134
|
+
/**
|
|
2135
|
+
* Rebuilds durable topics from what the storage found on open (M2b task 7):
|
|
2136
|
+
* every stored record, in order and at its own offset, with retention
|
|
2137
|
+
* applied as if it had just been appended, and the committed offsets.
|
|
2138
|
+
* Call after `createTopic`, before any append. Returns each restored
|
|
2139
|
+
* topic's head.
|
|
2140
|
+
*/
|
|
2141
|
+
async restore(state) {
|
|
2142
|
+
const restored = [];
|
|
2143
|
+
this.#restoring = true;
|
|
2144
|
+
try {
|
|
2145
|
+
await this.#restoreTopics(state, restored);
|
|
2146
|
+
} finally {
|
|
2147
|
+
this.#restoring = false;
|
|
2148
|
+
}
|
|
2149
|
+
for (const { topic } of restored) {
|
|
2150
|
+
const t = this.#topic(topic);
|
|
2151
|
+
if (t.keys) this.#compactKeys(t);
|
|
2152
|
+
}
|
|
2153
|
+
return restored;
|
|
2154
|
+
}
|
|
2155
|
+
async #restoreTopics(state, restored) {
|
|
2156
|
+
for (const { topic, tail, head } of state.topics) {
|
|
2157
|
+
const t = this.#topics.get(topic);
|
|
2158
|
+
if (!t?.durable) continue;
|
|
2159
|
+
if (t.head !== 0) throw new Error(`${topic} isn't empty`);
|
|
2160
|
+
t.head = t.tail = t.dropped = tail;
|
|
2161
|
+
t.base = Math.floor(tail / this.#size);
|
|
2162
|
+
let from = tail;
|
|
2163
|
+
while (from < head) {
|
|
2164
|
+
const frames = await this.#storage.readSegment(topic, from);
|
|
2165
|
+
if (frames.length === 0) break;
|
|
2166
|
+
for (const f of frames) {
|
|
2167
|
+
const { offset, epoch, seq, ...rec } = decodeFrame(f);
|
|
2168
|
+
if (epoch !== void 0 && seq !== void 0) remember(t, rec.producer, {
|
|
2169
|
+
epoch,
|
|
2170
|
+
seq
|
|
2171
|
+
}, offset);
|
|
2172
|
+
this.#place(t, rec, offset, f.length);
|
|
2173
|
+
from = offset + 1;
|
|
2174
|
+
}
|
|
2175
|
+
}
|
|
2176
|
+
t.head = Math.max(t.head, head);
|
|
2177
|
+
for (const [consumer, offset] of Object.entries(state.offsets[topic] ?? {})) t.commits.set(consumer, offset);
|
|
2178
|
+
restored.push({
|
|
2179
|
+
topic,
|
|
2180
|
+
head: t.head
|
|
2181
|
+
});
|
|
2182
|
+
}
|
|
2183
|
+
}
|
|
2184
|
+
/** Stores a record at `offset` (≥ head; a gap is left as dropped slots) and applies retention. */
|
|
2185
|
+
#place(t, rec, at, bytes) {
|
|
2186
|
+
t.head = at + 1;
|
|
2187
|
+
const offset = at;
|
|
2188
|
+
const ci = Math.floor(offset / this.#size);
|
|
2189
|
+
if (t.chunks.length === 0) {
|
|
2190
|
+
t.base = ci;
|
|
2191
|
+
t.chunkBytes = [];
|
|
2192
|
+
}
|
|
2193
|
+
let chunk = t.chunks[ci - t.base];
|
|
2194
|
+
if (chunk === void 0 || chunk === null) {
|
|
2195
|
+
chunk = [];
|
|
2196
|
+
t.chunks[ci - t.base] = chunk;
|
|
2197
|
+
}
|
|
2198
|
+
chunk[offset % this.#size] = {
|
|
2199
|
+
...rec,
|
|
2200
|
+
offset
|
|
2201
|
+
};
|
|
2202
|
+
t.live++;
|
|
2203
|
+
if (t.durable) {
|
|
2204
|
+
t.chunkBytes[ci - t.base] = (t.chunkBytes[ci - t.base] ?? 0) + bytes;
|
|
2205
|
+
t.residentBytes += bytes;
|
|
2206
|
+
if (t.residentBytes > this.#residentBytes) this.#evict(t);
|
|
2207
|
+
}
|
|
2208
|
+
const r = t.cfg.retention;
|
|
2209
|
+
if (r.kind === "last-n") {
|
|
2210
|
+
if (t.live > r.n) this.#dropBelow(t, t.head - r.n);
|
|
2211
|
+
} else if (t.keys && rec.key !== void 0) {
|
|
2212
|
+
const prev = t.keys.get(rec.key);
|
|
2213
|
+
t.keys.set(rec.key, offset);
|
|
2214
|
+
if (prev !== void 0 && t.durable) t.diskDirty++;
|
|
2215
|
+
if (prev !== void 0 && prev >= t.tail && prev < t.evictedTo) t.live--;
|
|
2216
|
+
else if (prev !== void 0 && prev >= t.tail) {
|
|
2217
|
+
t.dirty++;
|
|
2218
|
+
if (t.dirty >= this.#dirtyMin && t.dirty >= t.live * DIRTY_RATIO) this.#compactKeys(t);
|
|
2219
|
+
}
|
|
2220
|
+
}
|
|
2221
|
+
return offset;
|
|
2222
|
+
}
|
|
2223
|
+
read(topic, fromOffset, max) {
|
|
2224
|
+
const t = this.#topic(topic);
|
|
2225
|
+
const out = [];
|
|
2226
|
+
let o = Math.max(fromOffset, t.tail);
|
|
2227
|
+
while (o < t.evictedTo && out.length < max) {
|
|
2228
|
+
const page = this.#pageAt(t, o);
|
|
2229
|
+
if (!page) return out;
|
|
2230
|
+
for (const rec of page.records) {
|
|
2231
|
+
if (out.length >= max) return out;
|
|
2232
|
+
if (rec.offset >= o && this.#retained(t, rec)) out.push(rec);
|
|
2233
|
+
}
|
|
2234
|
+
o = page.to;
|
|
2235
|
+
}
|
|
2236
|
+
o = Math.max(o, t.evictedTo);
|
|
2237
|
+
while (o < t.head && out.length < max) {
|
|
2238
|
+
const ci = Math.floor(o / this.#size);
|
|
2239
|
+
const chunk = t.chunks[ci - t.base];
|
|
2240
|
+
const end = Math.min((ci + 1) * this.#size, t.head);
|
|
2241
|
+
if (!chunk) {
|
|
2242
|
+
o = end;
|
|
2243
|
+
continue;
|
|
2244
|
+
}
|
|
2245
|
+
for (; o < end && out.length < max; o++) {
|
|
2246
|
+
const rec = chunk[o % this.#size];
|
|
2247
|
+
if (rec) out.push(rec);
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
return out;
|
|
2251
|
+
}
|
|
2252
|
+
head(topic) {
|
|
2253
|
+
return this.#topic(topic).head;
|
|
2254
|
+
}
|
|
2255
|
+
readable(topic, fromOffset) {
|
|
2256
|
+
return this.#unpaged(this.#topic(topic), fromOffset) === void 0;
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* Where a read from `from` would stop for want of a page: the first evicted
|
|
2260
|
+
* offset no page covers, before any retained record. `undefined` when the
|
|
2261
|
+
* read can answer.
|
|
2262
|
+
*/
|
|
2263
|
+
#unpaged(t, from) {
|
|
2264
|
+
let o = Math.max(from, t.tail);
|
|
2265
|
+
while (o < t.evictedTo && o < t.head) {
|
|
2266
|
+
const page = this.#pageAt(t, o);
|
|
2267
|
+
if (!page) return o;
|
|
2268
|
+
const at = o;
|
|
2269
|
+
if (page.records.some((r) => r.offset >= at && this.#retained(t, r))) return void 0;
|
|
2270
|
+
o = page.to;
|
|
2271
|
+
}
|
|
2272
|
+
}
|
|
2273
|
+
page(topic, fromOffset) {
|
|
2274
|
+
const t = this.#topic(topic);
|
|
2275
|
+
const o = this.#unpaged(t, fromOffset);
|
|
2276
|
+
if (o === void 0) return Promise.resolve();
|
|
2277
|
+
const key = `${topic}\u0000${o}`;
|
|
2278
|
+
let p = this.#paging.get(key);
|
|
2279
|
+
if (!p) {
|
|
2280
|
+
p = this.#readPage(t, o).finally(() => this.#paging.delete(key));
|
|
2281
|
+
this.#paging.set(key, p);
|
|
2282
|
+
}
|
|
2283
|
+
return p;
|
|
2284
|
+
}
|
|
2285
|
+
/**
|
|
2286
|
+
* Reads the segment holding `from` back from disk, and the ones after it
|
|
2287
|
+
* until one holds a retained record, up to where eviction ends: a page
|
|
2288
|
+
* always answers a read, so paging never goes round in circles.
|
|
2289
|
+
*/
|
|
2290
|
+
async #readPage(t, from) {
|
|
2291
|
+
await this.#storage.flush();
|
|
2292
|
+
const records = [];
|
|
2293
|
+
let o = from;
|
|
2294
|
+
while (o < t.evictedTo && records.length === 0) {
|
|
2295
|
+
const frames = await this.#storage.readSegment(t.cfg.name, o);
|
|
2296
|
+
if (frames.length === 0) break;
|
|
2297
|
+
for (const f of frames) {
|
|
2298
|
+
const { epoch: _e, seq: _s, ...rec } = decodeFrame(f);
|
|
2299
|
+
if (rec.offset >= t.evictedTo) break;
|
|
2300
|
+
if (this.#retained(t, rec)) records.push(rec);
|
|
2301
|
+
o = rec.offset + 1;
|
|
2302
|
+
}
|
|
2303
|
+
if (frameOffset(frames.at(-1) ?? /* @__PURE__ */ new Uint8Array(16)) >= t.evictedTo) break;
|
|
2304
|
+
}
|
|
2305
|
+
const to = records.length > 0 ? o : t.evictedTo;
|
|
2306
|
+
this.#pages.push({
|
|
2307
|
+
topic: t.cfg.name,
|
|
2308
|
+
from,
|
|
2309
|
+
to,
|
|
2310
|
+
records
|
|
2311
|
+
});
|
|
2312
|
+
if (this.#pages.length > PAGES) this.#pages.shift();
|
|
2313
|
+
}
|
|
2314
|
+
#pageAt(t, offset) {
|
|
2315
|
+
return this.#pages.find((p) => p.topic === t.cfg.name && p.from <= offset && offset < p.to);
|
|
2316
|
+
}
|
|
2317
|
+
/** Whether a record read back from disk is still retained in the log. */
|
|
2318
|
+
#retained(t, rec) {
|
|
2319
|
+
if (rec.offset < t.tail) return false;
|
|
2320
|
+
return !t.keys || rec.key === void 0 || t.keys.get(rec.key) === rec.offset;
|
|
2321
|
+
}
|
|
2322
|
+
/**
|
|
2323
|
+
* Evicts the oldest chunks until the topic fits `residentBytes` again
|
|
2324
|
+
* (M2b task 11). Every record of a durable topic is on disk, or in the
|
|
2325
|
+
* storage's buffer until the next commit; `page` reads them back.
|
|
2326
|
+
*/
|
|
2327
|
+
#evict(t) {
|
|
2328
|
+
while (t.residentBytes > this.#residentBytes && t.chunks.length > 1) {
|
|
2329
|
+
const chunk = t.chunks.shift();
|
|
2330
|
+
t.residentBytes -= t.chunkBytes.shift() ?? 0;
|
|
2331
|
+
t.base++;
|
|
2332
|
+
t.evictedTo = t.base * this.#size;
|
|
2333
|
+
let count = 0;
|
|
2334
|
+
let maxTs = -Infinity;
|
|
2335
|
+
for (const rec of chunk ?? []) {
|
|
2336
|
+
if (!rec || rec.offset < t.tail) continue;
|
|
2337
|
+
count++;
|
|
2338
|
+
maxTs = Math.max(maxTs, rec.ts);
|
|
2339
|
+
}
|
|
2340
|
+
if (count > 0) t.evicted.push({
|
|
2341
|
+
end: t.evictedTo,
|
|
2342
|
+
count,
|
|
2343
|
+
maxTs
|
|
2344
|
+
});
|
|
2345
|
+
}
|
|
2346
|
+
}
|
|
2347
|
+
/** Lowest offset held in memory; below it, records are on disk only. For tests and metrics. */
|
|
2348
|
+
resident(topic) {
|
|
2349
|
+
const t = this.#topic(topic);
|
|
2350
|
+
return Math.max(t.tail, t.evictedTo);
|
|
2351
|
+
}
|
|
2352
|
+
tail(topic) {
|
|
2353
|
+
return this.#topic(topic).tail;
|
|
2354
|
+
}
|
|
2355
|
+
commit(topic, consumer, offset) {
|
|
2356
|
+
const t = this.#topic(topic);
|
|
2357
|
+
t.commits.set(consumer, offset);
|
|
2358
|
+
if (t.durable) this.#storage.saveOffsets({ [topic]: Object.fromEntries(t.commits) });
|
|
2359
|
+
}
|
|
2360
|
+
committed(topic, consumer) {
|
|
2361
|
+
return this.#topic(topic).commits.get(consumer);
|
|
2362
|
+
}
|
|
2363
|
+
durable(topic) {
|
|
2364
|
+
return this.#topic(topic).durable;
|
|
2365
|
+
}
|
|
2366
|
+
flush(o) {
|
|
2367
|
+
return this.#storage.flush(o);
|
|
2368
|
+
}
|
|
2369
|
+
compact(topic) {
|
|
2370
|
+
const t = this.#topic(topic);
|
|
2371
|
+
const r = t.cfg.retention;
|
|
2372
|
+
if (r.kind === "time") this.#expire(t, this.#now() - r.ms);
|
|
2373
|
+
else if (r.kind === "compacted") this.#compactKeys(t);
|
|
2374
|
+
}
|
|
2375
|
+
/** Drops every record below `offset` (last-n). */
|
|
2376
|
+
#dropBelow(t, offset) {
|
|
2377
|
+
if (offset <= t.tail) return;
|
|
2378
|
+
const from = t.tail;
|
|
2379
|
+
t.live -= this.#countLive(t, from, offset);
|
|
2380
|
+
t.tail = offset;
|
|
2381
|
+
this.#freeChunks(t);
|
|
2382
|
+
this.#clearBelowTail(t, from);
|
|
2383
|
+
}
|
|
2384
|
+
/** Records in `[from, to)` still held. Last-n topics have no holes, so this is `to - from` there. */
|
|
2385
|
+
#countLive(t, from, to) {
|
|
2386
|
+
if (t.cfg.retention.kind === "last-n") return to - from;
|
|
2387
|
+
let n = 0;
|
|
2388
|
+
for (let o = from; o < to; o++) if (this.#at(t, o)) n++;
|
|
2389
|
+
return n;
|
|
2390
|
+
}
|
|
2391
|
+
/** Drops records from the tail while the oldest is older than `cutoff` (time). */
|
|
2392
|
+
#expire(t, cutoff) {
|
|
2393
|
+
const from = t.tail;
|
|
2394
|
+
let o = t.tail;
|
|
2395
|
+
while (o < t.evictedTo) {
|
|
2396
|
+
const s = t.evicted[0];
|
|
2397
|
+
if (!s) {
|
|
2398
|
+
o = t.evictedTo;
|
|
2399
|
+
break;
|
|
2400
|
+
}
|
|
2401
|
+
if (s.maxTs >= cutoff) {
|
|
2402
|
+
t.tail = o;
|
|
2403
|
+
this.#freeChunks(t);
|
|
2404
|
+
this.#clearBelowTail(t, from);
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
t.live -= s.count;
|
|
2408
|
+
t.evicted.shift();
|
|
2409
|
+
o = s.end;
|
|
2410
|
+
}
|
|
2411
|
+
while (o < t.head) {
|
|
2412
|
+
const rec = this.#at(t, o);
|
|
2413
|
+
if (rec && rec.ts >= cutoff) break;
|
|
2414
|
+
if (rec) t.live--;
|
|
2415
|
+
o = rec || this.#chunkOf(t, o) ? o + 1 : (Math.floor(o / this.#size) + 1) * this.#size;
|
|
2416
|
+
}
|
|
2417
|
+
t.tail = Math.min(o, t.head);
|
|
2418
|
+
this.#freeChunks(t);
|
|
2419
|
+
this.#clearBelowTail(t, from);
|
|
2420
|
+
}
|
|
2421
|
+
/**
|
|
2422
|
+
* Clears the slots in `[from, tail)` that are still in a held chunk:
|
|
2423
|
+
* `#freeChunks` frees whole chunks only, so without this a slow topic keeps
|
|
2424
|
+
* its expired records referenced until the chunk holding its tail fills,
|
|
2425
|
+
* minutes at a few records a second (plant memory investigation, #162).
|
|
2426
|
+
* Each record is cleared once, as the tail passes it.
|
|
2427
|
+
*/
|
|
2428
|
+
#clearBelowTail(t, from) {
|
|
2429
|
+
for (let o = Math.max(from, t.base * this.#size); o < t.tail; o++) {
|
|
2430
|
+
const chunk = this.#chunkOf(t, o);
|
|
2431
|
+
if (chunk) chunk[o % this.#size] = void 0;
|
|
2432
|
+
}
|
|
2433
|
+
}
|
|
2434
|
+
/** Drops records superseded by a later record with the same key; keyless records stay. */
|
|
2435
|
+
#compactKeys(t) {
|
|
2436
|
+
const keys = t.keys;
|
|
2437
|
+
if (!keys) return;
|
|
2438
|
+
for (let ci = 0; ci < t.chunks.length; ci++) {
|
|
2439
|
+
const chunk = t.chunks[ci];
|
|
2440
|
+
if (!chunk) continue;
|
|
2441
|
+
let kept = 0;
|
|
2442
|
+
for (let s = 0; s < chunk.length; s++) {
|
|
2443
|
+
const rec = chunk[s];
|
|
2444
|
+
if (!rec) continue;
|
|
2445
|
+
if (rec.offset < t.tail || rec.key !== void 0 && keys.get(rec.key) !== rec.offset) {
|
|
2446
|
+
chunk[s] = void 0;
|
|
2447
|
+
if (rec.offset >= t.tail) t.live--;
|
|
2448
|
+
} else kept++;
|
|
2449
|
+
}
|
|
2450
|
+
if (kept === 0) {
|
|
2451
|
+
t.chunks[ci] = null;
|
|
2452
|
+
t.residentBytes -= t.chunkBytes[ci] ?? 0;
|
|
2453
|
+
t.chunkBytes[ci] = 0;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
t.dirty = 0;
|
|
2457
|
+
while (t.tail < t.head && t.tail >= t.evictedTo && !this.#at(t, t.tail)) t.tail = this.#chunkOf(t, t.tail) ? t.tail + 1 : (Math.floor(t.tail / this.#size) + 1) * this.#size;
|
|
2458
|
+
t.tail = Math.min(t.tail, t.head);
|
|
2459
|
+
this.#freeChunks(t);
|
|
2460
|
+
this.#compactDisk(t);
|
|
2461
|
+
}
|
|
2462
|
+
/**
|
|
2463
|
+
* Compaction on disk (M2b task 10), once at least half of what the disk
|
|
2464
|
+
* holds for the topic is superseded: the same rule as in memory.
|
|
2465
|
+
*/
|
|
2466
|
+
#compactDisk(t) {
|
|
2467
|
+
if (!t.durable || this.#restoring || t.diskDirty < this.#dirtyMin || t.diskDirty < t.live) return;
|
|
2468
|
+
t.diskDirty = 0;
|
|
2469
|
+
const keys = t.keys;
|
|
2470
|
+
const keep = (offset, key) => offset >= t.tail && (key === void 0 || keys?.get(key) === offset);
|
|
2471
|
+
this.#storage.rewrite(t.cfg.name, keep).catch((e) => {
|
|
2472
|
+
console.warn(`[isoloop] compacting ${t.cfg.name} on disk failed`, e);
|
|
2473
|
+
});
|
|
2474
|
+
}
|
|
2475
|
+
#chunkOf(t, offset) {
|
|
2476
|
+
return t.chunks[Math.floor(offset / this.#size) - t.base];
|
|
2477
|
+
}
|
|
2478
|
+
#at(t, offset) {
|
|
2479
|
+
return this.#chunkOf(t, offset)?.[offset % this.#size];
|
|
2480
|
+
}
|
|
2481
|
+
/** Frees whole chunks below the tail, and on disk the segments below it. */
|
|
2482
|
+
#freeChunks(t) {
|
|
2483
|
+
if (t.durable && t.tail > t.dropped) {
|
|
2484
|
+
t.dropped = t.tail;
|
|
2485
|
+
this.#storage.dropBelow(t.cfg.name, t.tail);
|
|
2486
|
+
}
|
|
2487
|
+
while ((t.evicted[0]?.end ?? Infinity) <= t.tail) t.evicted.shift();
|
|
2488
|
+
const keep = Math.floor(t.tail / this.#size);
|
|
2489
|
+
const drop = Math.min(keep - t.base, t.chunks.length);
|
|
2490
|
+
if (drop > 0) {
|
|
2491
|
+
t.chunks.splice(0, drop);
|
|
2492
|
+
for (const b of t.chunkBytes.splice(0, drop)) t.residentBytes -= b;
|
|
2493
|
+
t.base += drop;
|
|
2494
|
+
}
|
|
2495
|
+
if (t.chunks.length === 0) {
|
|
2496
|
+
t.base = Math.floor(t.head / this.#size);
|
|
2497
|
+
t.chunkBytes = [];
|
|
2498
|
+
t.residentBytes = 0;
|
|
2499
|
+
}
|
|
2500
|
+
if (t.evictedTo > 0) t.evictedTo = Math.max(t.evictedTo, t.base * this.#size);
|
|
2501
|
+
}
|
|
2502
|
+
/** Chunks held for a topic, for tests and metrics. */
|
|
2503
|
+
chunkCount(topic) {
|
|
2504
|
+
return this.#topic(topic).chunks.length;
|
|
2505
|
+
}
|
|
2506
|
+
/** Records held in memory for a topic, for tests and metrics. */
|
|
2507
|
+
heldCount(topic) {
|
|
2508
|
+
let n = 0;
|
|
2509
|
+
for (const chunk of this.#topic(topic).chunks) for (const r of chunk ?? []) if (r) n++;
|
|
2510
|
+
return n;
|
|
2511
|
+
}
|
|
2512
|
+
};
|
|
2513
|
+
/** Notes that `producer` appended `id` at `offset`; a new epoch forgets the old one's. */
|
|
2514
|
+
function remember(t, producer, id, offset) {
|
|
2515
|
+
let a = t.appended.get(producer);
|
|
2516
|
+
if (a?.epoch !== id.epoch) {
|
|
2517
|
+
a = {
|
|
2518
|
+
epoch: id.epoch,
|
|
2519
|
+
seqs: /* @__PURE__ */ new Map()
|
|
2520
|
+
};
|
|
2521
|
+
t.appended.set(producer, a);
|
|
2522
|
+
}
|
|
2523
|
+
a.seqs.set(id.seq, offset);
|
|
2524
|
+
if (a.seqs.size > 1e3) {
|
|
2525
|
+
const oldest = a.seqs.keys().next();
|
|
2526
|
+
if (!oldest.done) a.seqs.delete(oldest.value);
|
|
2527
|
+
}
|
|
2528
|
+
}
|
|
2529
|
+
// src/storage/lock.ts
|
|
2530
|
+
/** The Web Lock the bus worker holding the origin's OPFS files keeps (ADR 0007, decision 6). */
|
|
2531
|
+
const BUS_LOCK = "isoloop-bus";
|
|
2532
|
+
/**
|
|
2533
|
+
* Takes the `isoloop-bus` Web Lock and holds it until this worker ends, so
|
|
2534
|
+
* only one tab writes the files. Resolves whether it got it: at once when
|
|
2535
|
+
* `waitMs` is 0, else after up to `waitMs` (a restarting bus waits for the
|
|
2536
|
+
* one it replaces to let go). Without Web Locks it reports `true`: opening
|
|
2537
|
+
* the files then decides.
|
|
2538
|
+
*/
|
|
2539
|
+
function takeBusLock(waitMs) {
|
|
2540
|
+
const locks = typeof navigator === "undefined" ? void 0 : navigator.locks;
|
|
2541
|
+
if (!locks) return Promise.resolve(true);
|
|
2542
|
+
return new Promise((resolve) => {
|
|
2543
|
+
const held = (lock) => {
|
|
2544
|
+
if (!lock) {
|
|
2545
|
+
resolve(false);
|
|
2546
|
+
return;
|
|
2547
|
+
}
|
|
2548
|
+
resolve(true);
|
|
2549
|
+
return new Promise(() => {});
|
|
2550
|
+
};
|
|
2551
|
+
(waitMs > 0 ? locks.request(BUS_LOCK, { signal: AbortSignal.timeout(waitMs) }, held) : locks.request(BUS_LOCK, { ifAvailable: true }, held)).catch(() => resolve(false));
|
|
2552
|
+
});
|
|
2553
|
+
}
|
|
2554
|
+
// src/storage/handle.ts
|
|
2555
|
+
/** How long to keep trying a file another worker still holds. */
|
|
2556
|
+
const HELD_MS = 3e3;
|
|
2557
|
+
const RETRY_MS = 25;
|
|
2558
|
+
/**
|
|
2559
|
+
* `createSyncAccessHandle`, retried while the file is still held. Sync
|
|
2560
|
+
* access handles are exclusive, and a bus worker that was just terminated
|
|
2561
|
+
* (a crash, a restart) lets go of its files a moment after the new one
|
|
2562
|
+
* starts, so the new one waits for them rather than fail.
|
|
2563
|
+
*/
|
|
2564
|
+
async function syncHandle(file) {
|
|
2565
|
+
const until = Date.now() + HELD_MS;
|
|
2566
|
+
for (;;) try {
|
|
2567
|
+
return await file.createSyncAccessHandle();
|
|
2568
|
+
} catch (e) {
|
|
2569
|
+
if (!(e instanceof DOMException && e.name === "NoModificationAllowedError") || Date.now() >= until) throw e;
|
|
2570
|
+
await new Promise((r) => setTimeout(r, RETRY_MS));
|
|
2571
|
+
}
|
|
2572
|
+
}
|
|
2573
|
+
// src/storage/recover.ts
|
|
2574
|
+
/** Whether an intact frame starts at `at`, or the bytes end there. */
|
|
2575
|
+
function intactAt(bytes, view, at) {
|
|
2576
|
+
if (at === bytes.length) return true;
|
|
2577
|
+
if (at + 8 > bytes.length) return false;
|
|
2578
|
+
const end = at + 8 + view.getUint32(at, true);
|
|
2579
|
+
return end <= bytes.length && crc32(bytes, at + 8, end) === view.getUint32(at + 4, true);
|
|
2580
|
+
}
|
|
2581
|
+
/**
|
|
2582
|
+
* Recovery's scan of one segment (M2b task 7). Like `scanFrames`, but a frame
|
|
2583
|
+
* that fails its CRC in the middle of a segment (a flipped byte) is skipped
|
|
2584
|
+
* when an intact frame follows where its length says it ends, so the records
|
|
2585
|
+
* after it are kept. A frame that can't be stepped over, because it runs past
|
|
2586
|
+
* the end or what follows isn't a frame either, ends the scan: everything from
|
|
2587
|
+
* there is a torn tail.
|
|
2588
|
+
*/
|
|
2589
|
+
function scanSegment(bytes) {
|
|
2590
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
2591
|
+
const frames = [];
|
|
2592
|
+
let at = 0;
|
|
2593
|
+
let valid = 0;
|
|
2594
|
+
let skipped = 0;
|
|
2595
|
+
while (at + 8 <= bytes.length) {
|
|
2596
|
+
const length = view.getUint32(at, true);
|
|
2597
|
+
const end = at + 8 + length;
|
|
2598
|
+
if (length < 8 || end > bytes.length) break;
|
|
2599
|
+
if (crc32(bytes, at + 8, end) === view.getUint32(at + 4, true)) {
|
|
2600
|
+
frames.push(bytes.subarray(at, end));
|
|
2601
|
+
valid = end;
|
|
2602
|
+
} else if (end < bytes.length && intactAt(bytes, view, end)) {
|
|
2603
|
+
skipped++;
|
|
2604
|
+
valid = end;
|
|
2605
|
+
} else break;
|
|
2606
|
+
at = end;
|
|
2607
|
+
}
|
|
2608
|
+
return {
|
|
2609
|
+
frames,
|
|
2610
|
+
valid,
|
|
2611
|
+
skipped
|
|
2612
|
+
};
|
|
2613
|
+
}
|
|
2614
|
+
/** The offset after the last intact frame of a scan, or `fallback` when it has none. */
|
|
2615
|
+
function nextOffset(scan, fallback) {
|
|
2616
|
+
const last = scan.frames.at(-1);
|
|
2617
|
+
return last ? frameOffset(last) + 1 : fallback;
|
|
2618
|
+
}
|
|
2619
|
+
// src/storage/safe-mode.ts
|
|
2620
|
+
const SEGMENT$1 = /^(\d{16})(?:\.\d+)?\.seg$/;
|
|
2621
|
+
/**
|
|
2622
|
+
* A segment set aside by safe mode: `<segment>.to-<next offset>.quarantined`.
|
|
2623
|
+
* No longer a segment, still on disk. The name keeps the offset after its
|
|
2624
|
+
* last record, so offsets the segment used are never handed out again (I5).
|
|
2625
|
+
*/
|
|
2626
|
+
const QUARANTINED = /\.to-(\d{16})\.quarantined$/;
|
|
2627
|
+
const quarantinedName = (segment, next) => `${segment}.to-${String(next).padStart(16, "0")}.quarantined`;
|
|
2628
|
+
/** The offset after every segment set aside in a topic's directory; 0 when none is. */
|
|
2629
|
+
function quarantinedHead(names) {
|
|
2630
|
+
let head = 0;
|
|
2631
|
+
for (const name of names) {
|
|
2632
|
+
const m = QUARANTINED.exec(name);
|
|
2633
|
+
if (m?.[1] !== void 0) head = Math.max(head, Number(m[1]));
|
|
2634
|
+
}
|
|
2635
|
+
return head;
|
|
2636
|
+
}
|
|
2637
|
+
async function readWhole(dir, name) {
|
|
2638
|
+
const src = await syncHandle(await dir.getFileHandle(name));
|
|
2639
|
+
try {
|
|
2640
|
+
const bytes = new Uint8Array(src.getSize());
|
|
2641
|
+
src.read(bytes, { at: 0 });
|
|
2642
|
+
return bytes;
|
|
2643
|
+
} finally {
|
|
2644
|
+
src.close();
|
|
2645
|
+
}
|
|
2646
|
+
}
|
|
2647
|
+
async function write(dir, to, bytes) {
|
|
2648
|
+
const dst = await syncHandle(await dir.getFileHandle(to, { create: true }));
|
|
2649
|
+
try {
|
|
2650
|
+
dst.write(bytes, { at: 0 });
|
|
2651
|
+
dst.truncate(bytes.length);
|
|
2652
|
+
dst.flush();
|
|
2653
|
+
} finally {
|
|
2654
|
+
dst.close();
|
|
2655
|
+
}
|
|
2656
|
+
}
|
|
2657
|
+
/**
|
|
2658
|
+
* Safe mode (ADR 0007, decision 5; M2b task 12): sets the newest segment of
|
|
2659
|
+
* every topic under `root` aside, so the bus starts from the one before it.
|
|
2660
|
+
* The segment is copied to its quarantined name and only then removed, so a
|
|
2661
|
+
* crash halfway leaves it in place, and it is never deleted. Returns the
|
|
2662
|
+
* quarantined segments as `<topic>/<name>`.
|
|
2663
|
+
*/
|
|
2664
|
+
async function quarantineNewest(root) {
|
|
2665
|
+
const out = [];
|
|
2666
|
+
for await (const [entry, handle] of root.entries()) {
|
|
2667
|
+
if (handle.kind !== "directory") continue;
|
|
2668
|
+
const dir = await root.getDirectoryHandle(entry);
|
|
2669
|
+
let newest;
|
|
2670
|
+
for await (const name of dir.keys()) {
|
|
2671
|
+
const m = SEGMENT$1.exec(name);
|
|
2672
|
+
if (m?.[1] === void 0) continue;
|
|
2673
|
+
const first = Number(m[1]);
|
|
2674
|
+
if (!newest || first > newest.first) newest = {
|
|
2675
|
+
first,
|
|
2676
|
+
name
|
|
2677
|
+
};
|
|
2678
|
+
}
|
|
2679
|
+
if (!newest) continue;
|
|
2680
|
+
const bytes = await readWhole(dir, newest.name);
|
|
2681
|
+
const next = nextOffset(scanSegment(bytes), newest.first);
|
|
2682
|
+
await write(dir, quarantinedName(newest.name, next), bytes);
|
|
2683
|
+
await dir.removeEntry(newest.name);
|
|
2684
|
+
out.push(`${decodeURIComponent(entry)}/${newest.name}`);
|
|
2685
|
+
}
|
|
2686
|
+
out.sort();
|
|
2687
|
+
return out;
|
|
2688
|
+
}
|
|
2689
|
+
const SEGMENT = /^(\d{16})(?:\.(\d+))?\.seg$/;
|
|
2690
|
+
const BEGIN = "compact.begin";
|
|
2691
|
+
const DONE = "compact.done";
|
|
2692
|
+
const SLOTS = ["offsets.0", "offsets.1"];
|
|
2693
|
+
/** The file isn't there. Any other error (one still held, I/O) is not the same as missing. */
|
|
2694
|
+
const notFound = (e) => e instanceof DOMException && e.name === "NotFoundError";
|
|
2695
|
+
const isCommits = (x) => typeof x === "object" && x !== null && !Array.isArray(x) && Object.values(x).every((v) => typeof v === "number");
|
|
2696
|
+
/** The newest intact slot of a topic: its generation and offsets. */
|
|
2697
|
+
async function readOffsets(dir) {
|
|
2698
|
+
let best = {
|
|
2699
|
+
generation: 0,
|
|
2700
|
+
commits: {}
|
|
2701
|
+
};
|
|
2702
|
+
for (const slot of SLOTS) {
|
|
2703
|
+
let bytes;
|
|
2704
|
+
try {
|
|
2705
|
+
bytes = await readFile(dir, slot);
|
|
2706
|
+
} catch (e) {
|
|
2707
|
+
if (notFound(e)) continue;
|
|
2708
|
+
throw e;
|
|
2709
|
+
}
|
|
2710
|
+
const frame = scanFrames(bytes).frames[0];
|
|
2711
|
+
if (!frame) continue;
|
|
2712
|
+
const generation = frameOffset(frame);
|
|
2713
|
+
const commits = unpack(frame);
|
|
2714
|
+
if (generation > best.generation && isCommits(commits)) best = {
|
|
2715
|
+
generation,
|
|
2716
|
+
commits
|
|
2717
|
+
};
|
|
2718
|
+
}
|
|
2719
|
+
return best;
|
|
2720
|
+
}
|
|
2721
|
+
const segmentName = (first, generation = 0) => `${String(first).padStart(16, "0")}${generation > 0 ? `.${generation}` : ""}.seg`;
|
|
2722
|
+
/** A marker frame: its generation and, for `done`, the segments it replaced. */
|
|
2723
|
+
async function readMarker(dir, name) {
|
|
2724
|
+
let bytes;
|
|
2725
|
+
try {
|
|
2726
|
+
bytes = await readFile(dir, name);
|
|
2727
|
+
} catch (e) {
|
|
2728
|
+
if (notFound(e)) return void 0;
|
|
2729
|
+
throw e;
|
|
2730
|
+
}
|
|
2731
|
+
const frame = scanFrames(bytes).frames[0];
|
|
2732
|
+
if (!frame) return void 0;
|
|
2733
|
+
const value = unpack(frame);
|
|
2734
|
+
const replaced = Array.isArray(value) && value.every((v) => typeof v === "string") ? value : [];
|
|
2735
|
+
return {
|
|
2736
|
+
generation: frameOffset(frame),
|
|
2737
|
+
replaced
|
|
2738
|
+
};
|
|
2739
|
+
}
|
|
2740
|
+
/** Writes a whole small file and flushes it. */
|
|
2741
|
+
async function writeFile(dir, name, bytes) {
|
|
2742
|
+
const handle = await syncHandle(await dir.getFileHandle(name, { create: true }));
|
|
2743
|
+
try {
|
|
2744
|
+
handle.write(bytes, { at: 0 });
|
|
2745
|
+
handle.truncate(bytes.length);
|
|
2746
|
+
handle.flush();
|
|
2747
|
+
} finally {
|
|
2748
|
+
handle.close();
|
|
2749
|
+
}
|
|
2750
|
+
}
|
|
2751
|
+
/** Deletes a file; one already gone is fine. */
|
|
2752
|
+
async function remove(dir, name) {
|
|
2753
|
+
try {
|
|
2754
|
+
await dir.removeEntry(name);
|
|
2755
|
+
} catch (e) {
|
|
2756
|
+
if (!notFound(e)) throw e;
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
/** Topic names may hold characters a file name can't. */
|
|
2760
|
+
const dirName = (topic) => encodeURIComponent(topic);
|
|
2761
|
+
async function defaultRoot() {
|
|
2762
|
+
return (await (await navigator.storage.getDirectory()).getDirectoryHandle("isoloop", { create: true })).getDirectoryHandle("topics", { create: true });
|
|
2763
|
+
}
|
|
2764
|
+
async function names(dir) {
|
|
2765
|
+
const out = [];
|
|
2766
|
+
for await (const name of dir.keys()) out.push(name);
|
|
2767
|
+
return out;
|
|
2768
|
+
}
|
|
2769
|
+
/** Reads a whole file through a sync access handle, closing it after. */
|
|
2770
|
+
async function readFile(dir, name) {
|
|
2771
|
+
const handle = await syncHandle(await dir.getFileHandle(name));
|
|
2772
|
+
try {
|
|
2773
|
+
return readAll(handle);
|
|
2774
|
+
} finally {
|
|
2775
|
+
handle.close();
|
|
2776
|
+
}
|
|
2777
|
+
}
|
|
2778
|
+
function readAll(handle) {
|
|
2779
|
+
const bytes = new Uint8Array(handle.getSize());
|
|
2780
|
+
handle.read(bytes, { at: 0 });
|
|
2781
|
+
return bytes;
|
|
2782
|
+
}
|
|
2783
|
+
/**
|
|
2784
|
+
* Persistent topics in the Origin Private File System (ADR 0007, design §6.2).
|
|
2785
|
+
* One directory per topic, holding segment files of length-prefixed, CRC'd
|
|
2786
|
+
* frames (frame.ts), each named after its first offset. Writes go through
|
|
2787
|
+
* sync access handles, so this runs in a dedicated worker only: the bus
|
|
2788
|
+
* worker.
|
|
2789
|
+
*
|
|
2790
|
+
* `appendBatch` buffers; a group commit writes the buffer every `commitMs` or
|
|
2791
|
+
* every `commitRecords` records, and `flush()` resolves once everything
|
|
2792
|
+
* appended before it is written and flushed to disk.
|
|
2793
|
+
*/
|
|
2794
|
+
var OpfsStorage = class {
|
|
2795
|
+
kind = "opfs";
|
|
2796
|
+
#opts;
|
|
2797
|
+
#onStep;
|
|
2798
|
+
#root;
|
|
2799
|
+
#rootOption;
|
|
2800
|
+
#topics = /* @__PURE__ */ new Map();
|
|
2801
|
+
#pending = /* @__PURE__ */ new Map();
|
|
2802
|
+
/** Offsets to write at the next commit, per topic: the latest call wins. */
|
|
2803
|
+
#offsets = /* @__PURE__ */ new Map();
|
|
2804
|
+
/** Retention to apply after the next commit's writes, per topic. */
|
|
2805
|
+
#drops = /* @__PURE__ */ new Map();
|
|
2806
|
+
#count = 0;
|
|
2807
|
+
#timer;
|
|
2808
|
+
#waiters = [];
|
|
2809
|
+
/** A failed commit fails every flush after it: the files may be behind memory. */
|
|
2810
|
+
#failed;
|
|
2811
|
+
/** Commits run one at a time, in order: opening a segment is async. */
|
|
2812
|
+
#chain = Promise.resolve();
|
|
2813
|
+
/** Per topic: the compaction running, and the one queued behind it. */
|
|
2814
|
+
#rewrites = /* @__PURE__ */ new Map();
|
|
2815
|
+
#closing = false;
|
|
2816
|
+
constructor(opts = {}) {
|
|
2817
|
+
this.#rootOption = opts.root;
|
|
2818
|
+
this.#onStep = opts.onCompactionStep;
|
|
2819
|
+
this.#opts = {
|
|
2820
|
+
segmentBytes: opts.segmentBytes ?? 4194304,
|
|
2821
|
+
commitMs: opts.commitMs ?? 5,
|
|
2822
|
+
commitRecords: opts.commitRecords ?? 256
|
|
2823
|
+
};
|
|
2824
|
+
}
|
|
2825
|
+
/** Whether this context can use OPFS sync access handles at all. */
|
|
2826
|
+
static available() {
|
|
2827
|
+
return typeof navigator !== "undefined" && typeof navigator.storage?.getDirectory === "function" && typeof FileSystemFileHandle !== "undefined" && "createSyncAccessHandle" in FileSystemFileHandle.prototype;
|
|
2828
|
+
}
|
|
2829
|
+
/**
|
|
2830
|
+
* Recovery (M2b task 7): finds every topic on disk, truncates a torn tail
|
|
2831
|
+
* off each topic's newest segment, and restores committed offsets. A frame
|
|
2832
|
+
* corrupted inside a segment is skipped on every read (recover.ts).
|
|
2833
|
+
*/
|
|
2834
|
+
async open() {
|
|
2835
|
+
const root = this.#root ??= this.#rootOption ?? await defaultRoot();
|
|
2836
|
+
const state = {
|
|
2837
|
+
topics: [],
|
|
2838
|
+
offsets: {}
|
|
2839
|
+
};
|
|
2840
|
+
const found = await Promise.all((await names(root)).map(async (entry) => {
|
|
2841
|
+
const topic = decodeURIComponent(entry);
|
|
2842
|
+
const files = await this.#files(topic);
|
|
2843
|
+
await this.#settleCompaction(files);
|
|
2844
|
+
const saved = await readOffsets(files.dir);
|
|
2845
|
+
files.generation = saved.generation;
|
|
2846
|
+
if (Object.keys(saved.commits).length > 0) state.offsets[topic] = saved.commits;
|
|
2847
|
+
const first = files.segments[0];
|
|
2848
|
+
const last = files.segments.at(-1);
|
|
2849
|
+
const floor = files.quarantined;
|
|
2850
|
+
if (first === void 0 || last === void 0) return floor > 0 ? {
|
|
2851
|
+
topic,
|
|
2852
|
+
tail: floor,
|
|
2853
|
+
head: floor
|
|
2854
|
+
} : void 0;
|
|
2855
|
+
const head = Math.max(floor, await this.#recoverNewest(files, last));
|
|
2856
|
+
return {
|
|
2857
|
+
topic,
|
|
2858
|
+
tail: first.first,
|
|
2859
|
+
head
|
|
2860
|
+
};
|
|
2861
|
+
}));
|
|
2862
|
+
for (const t of found) if (t) state.topics.push(t);
|
|
2863
|
+
state.topics.sort((a, b) => a.topic < b.topic ? -1 : 1);
|
|
2864
|
+
return state;
|
|
2865
|
+
}
|
|
2866
|
+
/** Truncates the newest segment after its last intact frame; returns the head. */
|
|
2867
|
+
async #recoverNewest(files, seg) {
|
|
2868
|
+
const handle = await syncHandle(await files.dir.getFileHandle(seg.name));
|
|
2869
|
+
try {
|
|
2870
|
+
const bytes = readAll(handle);
|
|
2871
|
+
const scan = scanSegment(bytes);
|
|
2872
|
+
if (scan.valid < bytes.length) {
|
|
2873
|
+
handle.truncate(scan.valid);
|
|
2874
|
+
handle.flush();
|
|
2875
|
+
}
|
|
2876
|
+
return nextOffset(scan, seg.first);
|
|
2877
|
+
} finally {
|
|
2878
|
+
handle.close();
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
async #files(topic) {
|
|
2882
|
+
const known = this.#topics.get(topic);
|
|
2883
|
+
if (known) return known;
|
|
2884
|
+
const dir = await (this.#root ??= this.#rootOption ?? await defaultRoot()).getDirectoryHandle(dirName(topic), { create: true });
|
|
2885
|
+
const segments = [];
|
|
2886
|
+
let compactions = 0;
|
|
2887
|
+
const all = await names(dir);
|
|
2888
|
+
for (const name of all) {
|
|
2889
|
+
const m = SEGMENT.exec(name);
|
|
2890
|
+
if (m?.[1] === void 0) continue;
|
|
2891
|
+
segments.push({
|
|
2892
|
+
first: Number(m[1]),
|
|
2893
|
+
name
|
|
2894
|
+
});
|
|
2895
|
+
compactions = Math.max(compactions, Number(m[2] ?? 0));
|
|
2896
|
+
}
|
|
2897
|
+
segments.sort((a, b) => a.first - b.first);
|
|
2898
|
+
const files = {
|
|
2899
|
+
dir,
|
|
2900
|
+
generation: 0,
|
|
2901
|
+
segments,
|
|
2902
|
+
active: void 0,
|
|
2903
|
+
compactions,
|
|
2904
|
+
deferredDrop: void 0,
|
|
2905
|
+
quarantined: quarantinedHead(all)
|
|
2906
|
+
};
|
|
2907
|
+
this.#topics.set(topic, files);
|
|
2908
|
+
return files;
|
|
2909
|
+
}
|
|
2910
|
+
appendBatch(topic, encoded) {
|
|
2911
|
+
let list = this.#pending.get(topic);
|
|
2912
|
+
if (!list) {
|
|
2913
|
+
list = [];
|
|
2914
|
+
this.#pending.set(topic, list);
|
|
2915
|
+
}
|
|
2916
|
+
for (const frame of encoded) list.push(frame);
|
|
2917
|
+
this.#count += encoded.length;
|
|
2918
|
+
if (this.#count >= this.#opts.commitRecords) this.#commitSoon(0);
|
|
2919
|
+
else this.#commitSoon(this.#opts.commitMs);
|
|
2920
|
+
}
|
|
2921
|
+
flush(o = {}) {
|
|
2922
|
+
if (this.#failed !== void 0) return Promise.reject(this.#failed);
|
|
2923
|
+
if (o.now && (this.#count > 0 || this.#offsets.size > 0 || this.#drops.size > 0)) this.#commitSoon(0);
|
|
2924
|
+
if (this.#count === 0 && this.#offsets.size === 0 && this.#drops.size === 0) return this.#chain.then(() => {
|
|
2925
|
+
if (this.#failed !== void 0) throw this.#failed;
|
|
2926
|
+
});
|
|
2927
|
+
return new Promise((resolve, reject) => this.#waiters.push({
|
|
2928
|
+
resolve,
|
|
2929
|
+
reject
|
|
2930
|
+
}));
|
|
2931
|
+
}
|
|
2932
|
+
#commitSoon(ms) {
|
|
2933
|
+
if (this.#timer !== void 0) {
|
|
2934
|
+
if (ms > 0) return;
|
|
2935
|
+
clearTimeout(this.#timer);
|
|
2936
|
+
}
|
|
2937
|
+
this.#timer = setTimeout(() => {
|
|
2938
|
+
this.#timer = void 0;
|
|
2939
|
+
this.#commit();
|
|
2940
|
+
}, ms);
|
|
2941
|
+
}
|
|
2942
|
+
/** Takes the pending batch and queues its write behind any commit still running. */
|
|
2943
|
+
#commit() {
|
|
2944
|
+
const batch = [...this.#pending];
|
|
2945
|
+
const offsets = [...this.#offsets];
|
|
2946
|
+
const drops = [...this.#drops];
|
|
2947
|
+
const waiters = this.#waiters;
|
|
2948
|
+
this.#pending.clear();
|
|
2949
|
+
this.#offsets.clear();
|
|
2950
|
+
this.#drops.clear();
|
|
2951
|
+
this.#count = 0;
|
|
2952
|
+
this.#waiters = [];
|
|
2953
|
+
this.#chain = this.#chain.then(() => this.#run(batch, offsets, drops, waiters));
|
|
2954
|
+
return this.#chain;
|
|
2955
|
+
}
|
|
2956
|
+
async #run(batch, offsets, drops, waiters) {
|
|
2957
|
+
try {
|
|
2958
|
+
if (this.#failed !== void 0) throw this.#failed;
|
|
2959
|
+
for (const [topic, frames] of batch) {
|
|
2960
|
+
const files = this.#topics.get(topic) ?? await this.#files(topic);
|
|
2961
|
+
await this.#write(files, frames);
|
|
2962
|
+
}
|
|
2963
|
+
for (const [topic, commits] of offsets) {
|
|
2964
|
+
const files = this.#topics.get(topic) ?? await this.#files(topic);
|
|
2965
|
+
await this.#writeOffsets(files, commits);
|
|
2966
|
+
}
|
|
2967
|
+
for (const [topic, tail] of drops) {
|
|
2968
|
+
const files = this.#topics.get(topic) ?? await this.#files(topic);
|
|
2969
|
+
if (this.#rewrites.has(topic)) {
|
|
2970
|
+
files.deferredDrop = Math.max(tail, files.deferredDrop ?? 0);
|
|
2971
|
+
continue;
|
|
2972
|
+
}
|
|
2973
|
+
await this.#drop(files, tail);
|
|
2974
|
+
}
|
|
2975
|
+
for (const w of waiters) w.resolve();
|
|
2976
|
+
} catch (e) {
|
|
2977
|
+
const err = e instanceof Error ? e : new Error(String(e));
|
|
2978
|
+
this.#failed = err;
|
|
2979
|
+
for (const w of waiters) w.reject(err);
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
/** Writes frames to a topic's segments, rolling over at `segmentBytes`. */
|
|
2983
|
+
async #write(files, frames) {
|
|
2984
|
+
let i = 0;
|
|
2985
|
+
while (i < frames.length) {
|
|
2986
|
+
const first = frames[i] ?? /* @__PURE__ */ new Uint8Array();
|
|
2987
|
+
let active = files.active;
|
|
2988
|
+
if (!active || active.size > 0 && active.size + first.length > this.#opts.segmentBytes) active = await this.#roll(files, frameOffset(first));
|
|
2989
|
+
let bytes = 0;
|
|
2990
|
+
let j = i;
|
|
2991
|
+
while (j < frames.length) {
|
|
2992
|
+
const len = frames[j]?.length ?? 0;
|
|
2993
|
+
if (j > i && active.size + bytes + len > this.#opts.segmentBytes) break;
|
|
2994
|
+
bytes += len;
|
|
2995
|
+
j++;
|
|
2996
|
+
}
|
|
2997
|
+
const chunk = new Uint8Array(bytes);
|
|
2998
|
+
let at = 0;
|
|
2999
|
+
for (let k = i; k < j; k++) {
|
|
3000
|
+
const f = frames[k] ?? /* @__PURE__ */ new Uint8Array();
|
|
3001
|
+
chunk.set(f, at);
|
|
3002
|
+
at += f.length;
|
|
3003
|
+
}
|
|
3004
|
+
const written = active.handle.write(chunk, { at: active.size });
|
|
3005
|
+
if (written !== bytes) throw new Error(`short write: ${written} of ${bytes} bytes`);
|
|
3006
|
+
active.size += bytes;
|
|
3007
|
+
active.handle.flush();
|
|
3008
|
+
i = j;
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
3011
|
+
async #roll(files, first) {
|
|
3012
|
+
if (files.active) {
|
|
3013
|
+
files.active.handle.flush();
|
|
3014
|
+
files.active.handle.close();
|
|
3015
|
+
}
|
|
3016
|
+
const name = segmentName(first);
|
|
3017
|
+
const handle = await syncHandle(await files.dir.getFileHandle(name, { create: true }));
|
|
3018
|
+
const active = {
|
|
3019
|
+
name,
|
|
3020
|
+
handle,
|
|
3021
|
+
size: handle.getSize()
|
|
3022
|
+
};
|
|
3023
|
+
files.active = active;
|
|
3024
|
+
files.segments.push({
|
|
3025
|
+
first,
|
|
3026
|
+
name
|
|
3027
|
+
});
|
|
3028
|
+
return active;
|
|
3029
|
+
}
|
|
3030
|
+
saveOffsets(offsets) {
|
|
3031
|
+
for (const [topic, commits] of Object.entries(offsets)) this.#offsets.set(topic, { ...commits });
|
|
3032
|
+
this.#commitSoon(this.#opts.commitMs);
|
|
3033
|
+
}
|
|
3034
|
+
/** Writes the next generation to the slot not holding the newest one. */
|
|
3035
|
+
async #writeOffsets(files, commits) {
|
|
3036
|
+
const generation = files.generation + 1;
|
|
3037
|
+
const slot = SLOTS[generation % 2] ?? SLOTS[0];
|
|
3038
|
+
await writeFile(files.dir, slot, pack(generation, commits));
|
|
3039
|
+
files.generation = generation;
|
|
3040
|
+
}
|
|
3041
|
+
dropBelow(topic, tail) {
|
|
3042
|
+
this.#drops.set(topic, Math.max(tail, this.#drops.get(topic) ?? 0));
|
|
3043
|
+
this.#commitSoon(this.#opts.commitMs);
|
|
3044
|
+
}
|
|
3045
|
+
/** Deletes a topic's segments whose records all sit below `tail`. */
|
|
3046
|
+
async #drop(files, tail) {
|
|
3047
|
+
let n = 0;
|
|
3048
|
+
while (n + 1 < files.segments.length && (files.segments[n + 1]?.first ?? 0) <= tail) n++;
|
|
3049
|
+
for (const seg of files.segments.splice(0, n)) await remove(files.dir, seg.name);
|
|
3050
|
+
}
|
|
3051
|
+
/**
|
|
3052
|
+
* Compaction on disk (M2b task 10): rewrites a topic's sealed segments,
|
|
3053
|
+
* keeping the records `keep` accepts, and swaps the output in. The newest
|
|
3054
|
+
* segment, which appends go to, is left alone, so appends during a
|
|
3055
|
+
* compaction land after it. Runs in the background one segment at a time,
|
|
3056
|
+
* each step queued with the commits, so a commit waits for one segment at
|
|
3057
|
+
* most. A call while one runs queues one more run, with the latest `keep`.
|
|
3058
|
+
*/
|
|
3059
|
+
rewrite(topic, keep) {
|
|
3060
|
+
const state = this.#rewrites.get(topic);
|
|
3061
|
+
if (state?.queued) {
|
|
3062
|
+
state.queued.keep = keep;
|
|
3063
|
+
return state.queued.promise;
|
|
3064
|
+
}
|
|
3065
|
+
if (state) {
|
|
3066
|
+
const queued = {
|
|
3067
|
+
keep,
|
|
3068
|
+
promise: state.running.then(() => {
|
|
3069
|
+
const s = this.#rewrites.get(topic);
|
|
3070
|
+
const next = s?.queued?.keep ?? keep;
|
|
3071
|
+
if (s) {
|
|
3072
|
+
s.queued = void 0;
|
|
3073
|
+
s.running = this.#compact(topic, next);
|
|
3074
|
+
}
|
|
3075
|
+
return s?.running;
|
|
3076
|
+
})
|
|
3077
|
+
};
|
|
3078
|
+
state.queued = queued;
|
|
3079
|
+
return queued.promise;
|
|
3080
|
+
}
|
|
3081
|
+
const running = this.#compact(topic, keep);
|
|
3082
|
+
this.#rewrites.set(topic, { running });
|
|
3083
|
+
return running;
|
|
3084
|
+
}
|
|
3085
|
+
/** The topic's compaction, if one is running or queued; resolves when it ends. */
|
|
3086
|
+
compacting(topic) {
|
|
3087
|
+
const state = this.#rewrites.get(topic);
|
|
3088
|
+
return (state?.queued?.promise ?? state?.running ?? Promise.resolve()).then(() => {});
|
|
3089
|
+
}
|
|
3090
|
+
/** Runs `fn` in the commit chain, between commits. */
|
|
3091
|
+
#step(fn) {
|
|
3092
|
+
return new Promise((resolve, reject) => {
|
|
3093
|
+
this.#chain = this.#chain.then(() => fn().then(resolve, reject));
|
|
3094
|
+
});
|
|
3095
|
+
}
|
|
3096
|
+
async #compact(topic, keep) {
|
|
3097
|
+
try {
|
|
3098
|
+
await this.#compactOnce(topic, keep);
|
|
3099
|
+
} finally {
|
|
3100
|
+
const state = this.#rewrites.get(topic);
|
|
3101
|
+
if (state && !state.queued) this.#rewrites.delete(topic);
|
|
3102
|
+
}
|
|
3103
|
+
}
|
|
3104
|
+
async #compactOnce(topic, keep) {
|
|
3105
|
+
const files = await this.#files(topic);
|
|
3106
|
+
await this.flush();
|
|
3107
|
+
await this.#step(() => this.#settleCompaction(files));
|
|
3108
|
+
const inputs = files.segments.slice(0, -1);
|
|
3109
|
+
if (inputs.length === 0) return;
|
|
3110
|
+
const generation = files.compactions + 1;
|
|
3111
|
+
const replaced = [];
|
|
3112
|
+
const outputs = [];
|
|
3113
|
+
let out;
|
|
3114
|
+
const closeOut = () => {
|
|
3115
|
+
out?.handle.flush();
|
|
3116
|
+
out?.handle.close();
|
|
3117
|
+
out = void 0;
|
|
3118
|
+
};
|
|
3119
|
+
let begun = false;
|
|
3120
|
+
let done = false;
|
|
3121
|
+
try {
|
|
3122
|
+
for (const input of inputs) {
|
|
3123
|
+
if (this.#closing) throw new Error("storage closed");
|
|
3124
|
+
if (await this.#step(async () => {
|
|
3125
|
+
const frames = scanSegment(await readFile(files.dir, input.name)).frames;
|
|
3126
|
+
const kept = frames.filter((f) => {
|
|
3127
|
+
const rec = decodeFrame(f);
|
|
3128
|
+
return keep(rec.offset, rec.key);
|
|
3129
|
+
});
|
|
3130
|
+
if (kept.length === frames.length) {
|
|
3131
|
+
closeOut();
|
|
3132
|
+
return false;
|
|
3133
|
+
}
|
|
3134
|
+
if (!begun) {
|
|
3135
|
+
await writeFile(files.dir, BEGIN, pack(generation, []));
|
|
3136
|
+
files.compactions = generation;
|
|
3137
|
+
begun = true;
|
|
3138
|
+
}
|
|
3139
|
+
replaced.push(input);
|
|
3140
|
+
for (const f of kept) {
|
|
3141
|
+
if (!out || out.size > 0 && out.size + f.length > this.#opts.segmentBytes) {
|
|
3142
|
+
closeOut();
|
|
3143
|
+
const seg = {
|
|
3144
|
+
first: frameOffset(f),
|
|
3145
|
+
name: segmentName(frameOffset(f), generation)
|
|
3146
|
+
};
|
|
3147
|
+
const handle = await syncHandle(await files.dir.getFileHandle(seg.name, { create: true }));
|
|
3148
|
+
out = {
|
|
3149
|
+
name: seg.name,
|
|
3150
|
+
handle,
|
|
3151
|
+
size: 0
|
|
3152
|
+
};
|
|
3153
|
+
outputs.push(seg);
|
|
3154
|
+
}
|
|
3155
|
+
const n = out.handle.write(f, { at: out.size });
|
|
3156
|
+
if (n !== f.length) throw new Error(`short write: ${n} of ${f.length} bytes`);
|
|
3157
|
+
out.size += n;
|
|
3158
|
+
}
|
|
3159
|
+
out?.handle.flush();
|
|
3160
|
+
return true;
|
|
3161
|
+
})) await this.#onStep?.(replaced.length === 1 ? "begin" : "output");
|
|
3162
|
+
}
|
|
3163
|
+
if (!begun) return;
|
|
3164
|
+
await this.#step(() => {
|
|
3165
|
+
closeOut();
|
|
3166
|
+
return Promise.resolve();
|
|
3167
|
+
});
|
|
3168
|
+
await this.flush();
|
|
3169
|
+
await this.#step(async () => {
|
|
3170
|
+
await writeFile(files.dir, DONE, pack(generation, replaced.map((s) => s.name)));
|
|
3171
|
+
done = true;
|
|
3172
|
+
});
|
|
3173
|
+
await this.#onStep?.("done");
|
|
3174
|
+
await this.#step(async () => {
|
|
3175
|
+
const gone = new Set(replaced.map((s) => s.name));
|
|
3176
|
+
const segments = files.segments.filter((s) => !gone.has(s.name));
|
|
3177
|
+
segments.push(...outputs);
|
|
3178
|
+
segments.sort((a, b) => a.first - b.first);
|
|
3179
|
+
files.segments = segments;
|
|
3180
|
+
await this.#settleCompaction(files);
|
|
3181
|
+
if (files.deferredDrop !== void 0) {
|
|
3182
|
+
await this.#drop(files, files.deferredDrop);
|
|
3183
|
+
files.deferredDrop = void 0;
|
|
3184
|
+
}
|
|
3185
|
+
});
|
|
3186
|
+
} catch (e) {
|
|
3187
|
+
if (!done && begun) await this.#step(async () => {
|
|
3188
|
+
closeOut();
|
|
3189
|
+
await this.#settleCompaction(files);
|
|
3190
|
+
}).catch(() => {});
|
|
3191
|
+
throw e;
|
|
3192
|
+
}
|
|
3193
|
+
}
|
|
3194
|
+
/**
|
|
3195
|
+
* Finishes or undoes a compaction from its markers (see BEGIN): with `done`,
|
|
3196
|
+
* deletes the segments it replaced; with only `begin`, deletes its output.
|
|
3197
|
+
*/
|
|
3198
|
+
async #settleCompaction(files) {
|
|
3199
|
+
const done = await readMarker(files.dir, DONE);
|
|
3200
|
+
const begin = done ? void 0 : await readMarker(files.dir, BEGIN);
|
|
3201
|
+
const replaced = new Set(done?.replaced);
|
|
3202
|
+
const suffix = begin ? `.${begin.generation}.seg` : void 0;
|
|
3203
|
+
const drop = (s) => replaced.has(s.name) || suffix !== void 0 && s.name.endsWith(suffix);
|
|
3204
|
+
for (const s of files.segments.filter(drop)) await remove(files.dir, s.name);
|
|
3205
|
+
if (done) for (const name of done.replaced) await remove(files.dir, name);
|
|
3206
|
+
files.segments = files.segments.filter((s) => !drop(s));
|
|
3207
|
+
await remove(files.dir, DONE);
|
|
3208
|
+
await remove(files.dir, BEGIN);
|
|
3209
|
+
}
|
|
3210
|
+
/**
|
|
3211
|
+
* The frames of the segment holding `fromOffset`, from that offset on. When
|
|
3212
|
+
* that segment has none left (its tail was corrupt), the next one's. Empty
|
|
3213
|
+
* past the newest record.
|
|
3214
|
+
*/
|
|
3215
|
+
async readSegment(topic, fromOffset) {
|
|
3216
|
+
const files = await this.#files(topic);
|
|
3217
|
+
return this.#step(() => this.#readFrom(files, fromOffset));
|
|
3218
|
+
}
|
|
3219
|
+
async #readFrom(files, fromOffset) {
|
|
3220
|
+
let i = 0;
|
|
3221
|
+
while (i + 1 < files.segments.length && (files.segments[i + 1]?.first ?? 0) <= fromOffset) i++;
|
|
3222
|
+
for (; i < files.segments.length; i++) {
|
|
3223
|
+
const name = files.segments[i]?.name ?? "";
|
|
3224
|
+
const frames = scanSegment(files.active?.name === name ? readAll(files.active.handle) : await readFile(files.dir, name)).frames.filter((f) => frameOffset(f) >= fromOffset);
|
|
3225
|
+
if (frames.length > 0) return frames;
|
|
3226
|
+
}
|
|
3227
|
+
return [];
|
|
3228
|
+
}
|
|
3229
|
+
/** Safe mode: call before `open`. See safe-mode.ts. */
|
|
3230
|
+
async quarantineNewest() {
|
|
3231
|
+
return quarantineNewest(this.#root ??= this.#rootOption ?? await defaultRoot());
|
|
3232
|
+
}
|
|
3233
|
+
/** Segment files of a topic, oldest first. For tests and metrics. */
|
|
3234
|
+
async segments(topic) {
|
|
3235
|
+
return (await this.#files(topic)).segments.map((s) => s.name);
|
|
3236
|
+
}
|
|
3237
|
+
/** Writes what's pending, then releases every file handle. */
|
|
3238
|
+
async bytes(topic) {
|
|
3239
|
+
const files = this.#topics.get(topic);
|
|
3240
|
+
if (!files) return 0;
|
|
3241
|
+
let total = 0;
|
|
3242
|
+
for (const seg of files.segments) if (files.active?.name === seg.name) total += files.active.handle.getSize();
|
|
3243
|
+
else total += (await (await files.dir.getFileHandle(seg.name)).getFile()).size;
|
|
3244
|
+
return total;
|
|
3245
|
+
}
|
|
3246
|
+
/** Orphaned topics only: nothing may be pending for it (ADR 0003, decision 19). */
|
|
3247
|
+
async deleteTopic(topic) {
|
|
3248
|
+
const files = this.#topics.get(topic);
|
|
3249
|
+
const root = this.#root;
|
|
3250
|
+
if (!files || !root) return false;
|
|
3251
|
+
files.active?.handle.close();
|
|
3252
|
+
files.active = void 0;
|
|
3253
|
+
this.#topics.delete(topic);
|
|
3254
|
+
await root.removeEntry(dirName(topic), { recursive: true });
|
|
3255
|
+
return true;
|
|
3256
|
+
}
|
|
3257
|
+
async close() {
|
|
3258
|
+
this.#closing = true;
|
|
3259
|
+
await Promise.all([...this.#rewrites.values()].map((s) => (s.queued?.promise ?? s.running).catch(() => {})));
|
|
3260
|
+
if (this.#timer !== void 0) {
|
|
3261
|
+
clearTimeout(this.#timer);
|
|
3262
|
+
this.#timer = void 0;
|
|
3263
|
+
}
|
|
3264
|
+
if (this.#count > 0 || this.#offsets.size > 0 || this.#drops.size > 0) this.#commit();
|
|
3265
|
+
await this.#chain;
|
|
3266
|
+
for (const files of this.#topics.values()) {
|
|
3267
|
+
files.active?.handle.close();
|
|
3268
|
+
files.active = void 0;
|
|
3269
|
+
}
|
|
3270
|
+
this.#topics.clear();
|
|
3271
|
+
}
|
|
3272
|
+
};
|
|
3273
|
+
// src/server.ts
|
|
3274
|
+
/** Storage use at or past this share of the quota counts as full (M2b task 14). */
|
|
3275
|
+
const FULL = 1;
|
|
3276
|
+
/** How long a restarting bus waits for the worker it replaces to release the files' lock. */
|
|
3277
|
+
const RESTART_LOCK_WAIT_MS = 2e3;
|
|
3278
|
+
/** How often metrics are sampled and retention runs (design §6.2, §6.3). */
|
|
3279
|
+
const METRICS_MS = 1e3;
|
|
3280
|
+
/** A contracts load failure: deterministic, so the host doesn't retry it (ADR 0003, decision 7). */
|
|
3281
|
+
var BootError = class extends Error {
|
|
3282
|
+
code;
|
|
3283
|
+
constructor(code, message) {
|
|
3284
|
+
super(message);
|
|
3285
|
+
this.code = code;
|
|
3286
|
+
}
|
|
3287
|
+
};
|
|
3288
|
+
const CONTRACT_CODES = /* @__PURE__ */ new Set(["contracts_invalid", "reserved_topic"]);
|
|
3289
|
+
/** A `ContractsError` thrown while the module evaluated, from any copy of this package. */
|
|
3290
|
+
function contractsCode(e) {
|
|
3291
|
+
if (typeof e !== "object" || e === null || !("code" in e)) return void 0;
|
|
3292
|
+
const code = e.code;
|
|
3293
|
+
return typeof code === "string" && CONTRACT_CODES.has(code) ? code : void 0;
|
|
3294
|
+
}
|
|
3295
|
+
/** Topic configs as a canonical string, so key order doesn't matter. */
|
|
3296
|
+
function canonical(cfg) {
|
|
3297
|
+
return JSON.stringify(cfg, (_key, v) => {
|
|
3298
|
+
if (typeof v !== "object" || v === null || Array.isArray(v)) return v;
|
|
3299
|
+
const keys = Object.keys(v);
|
|
3300
|
+
keys.sort();
|
|
3301
|
+
return Object.fromEntries(keys.map((k) => [k, Reflect.get(v, k)]));
|
|
3302
|
+
});
|
|
3303
|
+
}
|
|
3304
|
+
/** Names of topics that differ between the module and the host's list, or exist in only one. */
|
|
3305
|
+
function mismatchedTopics(module, host) {
|
|
3306
|
+
const ours = new Map(module.topics.map((t) => [t.name, canonical(topicConfig(t))]));
|
|
3307
|
+
const theirs = new Map(host.map((t) => [t.name, canonical(t)]));
|
|
3308
|
+
const differ = [.../* @__PURE__ */ new Set([...ours.keys(), ...theirs.keys()])].filter((n) => ours.get(n) !== theirs.get(n));
|
|
3309
|
+
differ.sort();
|
|
3310
|
+
return differ;
|
|
3311
|
+
}
|
|
3312
|
+
/** Imports the contracts module and checks it against the host's list (ADR 0003, decisions 4–7). */
|
|
3313
|
+
async function loadContracts(url, host, importModule) {
|
|
3314
|
+
let mod;
|
|
3315
|
+
try {
|
|
3316
|
+
mod = await importModule(url);
|
|
3317
|
+
} catch (e) {
|
|
3318
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
3319
|
+
const code = contractsCode(e);
|
|
3320
|
+
if (code) throw new BootError(code, message);
|
|
3321
|
+
throw new BootError("contracts_failed", `Could not import contracts from ${url}: ${message}`);
|
|
3322
|
+
}
|
|
3323
|
+
const list = typeof mod === "object" && mod !== null && "default" in mod ? mod.default : void 0;
|
|
3324
|
+
if (!isContracts(list)) throw new BootError("contracts_invalid", `${url} has no contracts() default export (ADR 0003, decision 4)`);
|
|
3325
|
+
const reserved = list.topics.filter((t) => isSystemTopic(t.name)).map((t) => t.name);
|
|
3326
|
+
if (reserved.length > 0) throw new BootError("reserved_topic", `isoloop.* topics belong to the kernel: ${reserved.join(", ")}`);
|
|
3327
|
+
const differ = mismatchedTopics(list, host);
|
|
3328
|
+
if (differ.length > 0) throw new BootError("contracts_mismatch", `The contracts at ${url} differ from the host's for: ${differ.join(", ")}`);
|
|
3329
|
+
return list;
|
|
3330
|
+
}
|
|
3331
|
+
function holdPort(port, limit, reject) {
|
|
3332
|
+
let handler;
|
|
3333
|
+
let buffered = 0;
|
|
3334
|
+
const held = {
|
|
3335
|
+
held: [],
|
|
3336
|
+
post(msg) {
|
|
3337
|
+
port.postMessage(msg);
|
|
3338
|
+
},
|
|
3339
|
+
onMessage(h) {
|
|
3340
|
+
handler = h;
|
|
3341
|
+
for (const msg of held.held.splice(0)) h(msg);
|
|
3342
|
+
},
|
|
3343
|
+
close() {
|
|
3344
|
+
port.close();
|
|
3345
|
+
}
|
|
3346
|
+
};
|
|
3347
|
+
port.addEventListener("message", (e) => {
|
|
3348
|
+
if (handler) {
|
|
3349
|
+
handler(e.data);
|
|
3350
|
+
return;
|
|
3351
|
+
}
|
|
3352
|
+
const msg = e.data;
|
|
3353
|
+
if (isPublishLike(msg)) {
|
|
3354
|
+
if (buffered >= limit) {
|
|
3355
|
+
if (typeof msg.id === "string") reject(port, msg.id);
|
|
3356
|
+
return;
|
|
3357
|
+
}
|
|
3358
|
+
buffered++;
|
|
3359
|
+
}
|
|
3360
|
+
held.held.push(msg);
|
|
3361
|
+
});
|
|
3362
|
+
port.start();
|
|
3363
|
+
return held;
|
|
3364
|
+
}
|
|
3365
|
+
const isPublishLike = (m) => typeof m === "object" && m !== null && "t" in m && (m.t === "publish" || m.t === "request");
|
|
3366
|
+
const unavailable = (what) => ({
|
|
3367
|
+
ok: false,
|
|
3368
|
+
error: {
|
|
3369
|
+
code: "bus_unavailable",
|
|
3370
|
+
message: `${what}: the bus buffer is full while contracts load`
|
|
3371
|
+
}
|
|
3372
|
+
});
|
|
3373
|
+
/** Wires the control port of a bus worker. Call once, with the worker's scope. */
|
|
3374
|
+
function serve(scope, opts = {}) {
|
|
3375
|
+
const limit = opts.inboxLimit ?? 1e3;
|
|
3376
|
+
const importModule = opts.importModule ?? ((url) => import(
|
|
3377
|
+
/* @vite-ignore */
|
|
3378
|
+
url
|
|
3379
|
+
));
|
|
3380
|
+
const now = opts.now ?? (() => performance.now());
|
|
3381
|
+
const post = (msg) => {
|
|
3382
|
+
scope.postMessage(msg);
|
|
3383
|
+
};
|
|
3384
|
+
let booted = false;
|
|
3385
|
+
let failed = false;
|
|
3386
|
+
let broker;
|
|
3387
|
+
/** The storage the broker's engine writes to, once booted. */
|
|
3388
|
+
let currentStorage;
|
|
3389
|
+
/** Control messages that arrived before the broker, replayed in order. */
|
|
3390
|
+
const early = [];
|
|
3391
|
+
/** Ports attached before the broker: they buffer what their isolate sends. */
|
|
3392
|
+
const ports = /* @__PURE__ */ new Map();
|
|
3393
|
+
let earlyPublishes = 0;
|
|
3394
|
+
const fatal = (f) => {
|
|
3395
|
+
failed = true;
|
|
3396
|
+
post({
|
|
3397
|
+
v: 1,
|
|
3398
|
+
t: "error",
|
|
3399
|
+
p: {
|
|
3400
|
+
message: f.message,
|
|
3401
|
+
fatal: true,
|
|
3402
|
+
code: f.code
|
|
3403
|
+
}
|
|
3404
|
+
});
|
|
3405
|
+
for (const p of ports.values()) p.close();
|
|
3406
|
+
ports.clear();
|
|
3407
|
+
early.length = 0;
|
|
3408
|
+
};
|
|
3409
|
+
const control = (msg, b) => {
|
|
3410
|
+
switch (msg.t) {
|
|
3411
|
+
case "boot": return;
|
|
3412
|
+
case "attach": {
|
|
3413
|
+
const port = ports.get(msg.p.isolateId) ?? held(msg.p.port);
|
|
3414
|
+
ports.delete(msg.p.isolateId);
|
|
3415
|
+
b.attach(msg.p.isolateId, msg.p.grants, port, { reattach: msg.p.reattach ?? false });
|
|
3416
|
+
return;
|
|
3417
|
+
}
|
|
3418
|
+
case "detach":
|
|
3419
|
+
b.detach(msg.p.isolateId, msg.p.keepOffsets, { wake: msg.p.wake ?? false });
|
|
3420
|
+
return;
|
|
3421
|
+
case "publish": {
|
|
3422
|
+
const { id } = msg;
|
|
3423
|
+
const from = isSystemTopic(msg.p.topic) ? { kind: "kernel" } : { kind: "host" };
|
|
3424
|
+
b.publish(from, msg.p.topic, msg.p.key, msg.p.value, publishId(msg.p)).then((r) => {
|
|
3425
|
+
if (id !== void 0) post({
|
|
3426
|
+
v: 1,
|
|
3427
|
+
t: "result",
|
|
3428
|
+
re: id,
|
|
3429
|
+
p: r
|
|
3430
|
+
});
|
|
3431
|
+
});
|
|
3432
|
+
return;
|
|
3433
|
+
}
|
|
3434
|
+
case "flush": {
|
|
3435
|
+
const { id } = msg;
|
|
3436
|
+
b.flush().then(() => id !== void 0 && post({
|
|
3437
|
+
v: 1,
|
|
3438
|
+
t: "result",
|
|
3439
|
+
re: id,
|
|
3440
|
+
p: {
|
|
3441
|
+
ok: true,
|
|
3442
|
+
value: null
|
|
3443
|
+
}
|
|
3444
|
+
}), (e) => id !== void 0 && post({
|
|
3445
|
+
v: 1,
|
|
3446
|
+
t: "result",
|
|
3447
|
+
re: id,
|
|
3448
|
+
p: {
|
|
3449
|
+
ok: false,
|
|
3450
|
+
error: {
|
|
3451
|
+
code: "bus_unavailable",
|
|
3452
|
+
message: `flush: write failed: ${String(e)}`
|
|
3453
|
+
}
|
|
3454
|
+
}
|
|
3455
|
+
}));
|
|
3456
|
+
return;
|
|
3457
|
+
}
|
|
3458
|
+
case "drop": {
|
|
3459
|
+
const { id } = msg;
|
|
3460
|
+
const answer = (p) => {
|
|
3461
|
+
if (id !== void 0) post({
|
|
3462
|
+
v: 1,
|
|
3463
|
+
t: "result",
|
|
3464
|
+
re: id,
|
|
3465
|
+
p
|
|
3466
|
+
});
|
|
3467
|
+
};
|
|
3468
|
+
const refusal = b.dropRefusal(msg.p.topic, msg.p.force);
|
|
3469
|
+
if (refusal) return answer(refusal);
|
|
3470
|
+
currentStorage?.deleteTopic(msg.p.topic).then((deleted) => answer(deleted ? {
|
|
3471
|
+
ok: true,
|
|
3472
|
+
value: null
|
|
3473
|
+
} : {
|
|
3474
|
+
ok: false,
|
|
3475
|
+
error: {
|
|
3476
|
+
code: "unknown_topic",
|
|
3477
|
+
message: `no stored topic ${msg.p.topic}`
|
|
3478
|
+
}
|
|
3479
|
+
}), (e) => answer({
|
|
3480
|
+
ok: false,
|
|
3481
|
+
error: {
|
|
3482
|
+
code: "bus_unavailable",
|
|
3483
|
+
message: `drop ${msg.p.topic}: ${String(e)}`
|
|
3484
|
+
}
|
|
3485
|
+
}));
|
|
3486
|
+
return;
|
|
3487
|
+
}
|
|
3488
|
+
default: return msg;
|
|
3489
|
+
}
|
|
3490
|
+
};
|
|
3491
|
+
const held = (port) => holdPort(port, limit, (p, re) => {
|
|
3492
|
+
p.postMessage({
|
|
3493
|
+
v: 1,
|
|
3494
|
+
t: "result",
|
|
3495
|
+
re,
|
|
3496
|
+
p: unavailable("publish")
|
|
3497
|
+
});
|
|
3498
|
+
});
|
|
3499
|
+
/** Before the broker: keep what can wait, hold ports, reject publishes past the limit. */
|
|
3500
|
+
const wait = (msg) => {
|
|
3501
|
+
switch (msg.t) {
|
|
3502
|
+
case "attach":
|
|
3503
|
+
ports.get(msg.p.isolateId)?.close();
|
|
3504
|
+
ports.set(msg.p.isolateId, held(msg.p.port));
|
|
3505
|
+
break;
|
|
3506
|
+
case "detach":
|
|
3507
|
+
ports.get(msg.p.isolateId)?.close();
|
|
3508
|
+
ports.delete(msg.p.isolateId);
|
|
3509
|
+
break;
|
|
3510
|
+
case "publish":
|
|
3511
|
+
if (earlyPublishes >= limit) {
|
|
3512
|
+
if (msg.id !== void 0) post({
|
|
3513
|
+
v: 1,
|
|
3514
|
+
t: "result",
|
|
3515
|
+
re: msg.id,
|
|
3516
|
+
p: unavailable("kernel.publish")
|
|
3517
|
+
});
|
|
3518
|
+
return;
|
|
3519
|
+
}
|
|
3520
|
+
earlyPublishes++;
|
|
3521
|
+
break;
|
|
3522
|
+
case "drop":
|
|
3523
|
+
early.push(msg);
|
|
3524
|
+
return;
|
|
3525
|
+
case "flush":
|
|
3526
|
+
if (msg.id !== void 0) post({
|
|
3527
|
+
v: 1,
|
|
3528
|
+
t: "result",
|
|
3529
|
+
re: msg.id,
|
|
3530
|
+
p: {
|
|
3531
|
+
ok: true,
|
|
3532
|
+
value: null
|
|
3533
|
+
}
|
|
3534
|
+
});
|
|
3535
|
+
return;
|
|
3536
|
+
case "boot": return;
|
|
3537
|
+
}
|
|
3538
|
+
early.push(msg);
|
|
3539
|
+
};
|
|
3540
|
+
const startBeat = (everyMs) => {
|
|
3541
|
+
let last = now();
|
|
3542
|
+
setInterval(() => {
|
|
3543
|
+
const t = now();
|
|
3544
|
+
post({
|
|
3545
|
+
v: 1,
|
|
3546
|
+
t: "beat",
|
|
3547
|
+
p: { lagMs: Math.max(0, t - last - everyMs) }
|
|
3548
|
+
});
|
|
3549
|
+
last = t;
|
|
3550
|
+
}, everyMs);
|
|
3551
|
+
};
|
|
3552
|
+
const startMetrics = (b, kind) => {
|
|
3553
|
+
let prev = b.stats();
|
|
3554
|
+
let at = now();
|
|
3555
|
+
let storage;
|
|
3556
|
+
const estimate = opts.estimate ?? (() => navigator.storage.estimate());
|
|
3557
|
+
/** Reads the origin's storage use: it goes into the next metrics, and tells the broker when it's full. */
|
|
3558
|
+
const sample = () => {
|
|
3559
|
+
if (kind !== "opfs") return;
|
|
3560
|
+
estimate().then((e) => {
|
|
3561
|
+
const usage = e.usage ?? 0;
|
|
3562
|
+
const quota = e.quota ?? 0;
|
|
3563
|
+
storage = {
|
|
3564
|
+
usage,
|
|
3565
|
+
quota
|
|
3566
|
+
};
|
|
3567
|
+
b.setStorageFull(quota > 0 && usage >= quota * FULL);
|
|
3568
|
+
}, () => {});
|
|
3569
|
+
};
|
|
3570
|
+
sample();
|
|
3571
|
+
setInterval(() => {
|
|
3572
|
+
sample();
|
|
3573
|
+
b.compact();
|
|
3574
|
+
const stats = b.stats();
|
|
3575
|
+
const t = now();
|
|
3576
|
+
const secs = Math.max(.001, (t - at) / 1e3);
|
|
3577
|
+
const before = new Map(prev.topics.map((x) => [x.topic, x]));
|
|
3578
|
+
const metrics = {
|
|
3579
|
+
topics: stats.topics.map((x) => ({
|
|
3580
|
+
topic: x.topic,
|
|
3581
|
+
recordsPerSec: (x.records - (before.get(x.topic)?.records ?? 0)) / secs,
|
|
3582
|
+
bytesPerSec: (x.bytes - (before.get(x.topic)?.bytes ?? 0)) / secs
|
|
3583
|
+
})),
|
|
3584
|
+
subscriptions: stats.subscriptions,
|
|
3585
|
+
rejected: stats.rejected,
|
|
3586
|
+
...storage ? { storage } : {}
|
|
3587
|
+
};
|
|
3588
|
+
prev = stats;
|
|
3589
|
+
at = t;
|
|
3590
|
+
post({
|
|
3591
|
+
v: 1,
|
|
3592
|
+
t: "metrics",
|
|
3593
|
+
p: metrics
|
|
3594
|
+
});
|
|
3595
|
+
}, METRICS_MS);
|
|
3596
|
+
};
|
|
3597
|
+
/** An engine and broker on `storage`, with persistent topics restored from `stored`. */
|
|
3598
|
+
const build = async (list, storage, stored, dev) => {
|
|
3599
|
+
const engine = new TsEngine({ storage });
|
|
3600
|
+
return {
|
|
3601
|
+
b: new Broker({
|
|
3602
|
+
contracts: list,
|
|
3603
|
+
engine,
|
|
3604
|
+
dev,
|
|
3605
|
+
onWake: (isolateId, topic) => post({
|
|
3606
|
+
v: 1,
|
|
3607
|
+
t: "wake",
|
|
3608
|
+
p: {
|
|
3609
|
+
isolateId,
|
|
3610
|
+
topic
|
|
3611
|
+
}
|
|
3612
|
+
}),
|
|
3613
|
+
onSeed: (e) => post({
|
|
3614
|
+
v: 1,
|
|
3615
|
+
t: "seed",
|
|
3616
|
+
p: e
|
|
3617
|
+
})
|
|
3618
|
+
}),
|
|
3619
|
+
restored: await engine.restore(stored)
|
|
3620
|
+
};
|
|
3621
|
+
};
|
|
3622
|
+
const boot = async (p) => {
|
|
3623
|
+
startBeat(p.heartbeatMs ?? 100);
|
|
3624
|
+
let list;
|
|
3625
|
+
try {
|
|
3626
|
+
list = await loadContracts(p.contractsUrl, p.topics, importModule);
|
|
3627
|
+
} catch (e) {
|
|
3628
|
+
fatal(e instanceof BootError ? {
|
|
3629
|
+
code: e.code,
|
|
3630
|
+
message: e.message
|
|
3631
|
+
} : {
|
|
3632
|
+
code: "contracts_invalid",
|
|
3633
|
+
message: e instanceof Error ? e.message : String(e)
|
|
3634
|
+
});
|
|
3635
|
+
return;
|
|
3636
|
+
}
|
|
3637
|
+
const dev = p.dev ?? false;
|
|
3638
|
+
const persistent = p.topics.some((t) => t.durability === "persistent");
|
|
3639
|
+
let degraded;
|
|
3640
|
+
let storage;
|
|
3641
|
+
if (opts.storage) storage = opts.storage();
|
|
3642
|
+
else if (!persistent) storage = new MemoryStorage();
|
|
3643
|
+
else if (!OpfsStorage.available()) {
|
|
3644
|
+
storage = new MemoryStorage();
|
|
3645
|
+
degraded = "no-sync-access";
|
|
3646
|
+
} else if (await takeBusLock(p.restart ? RESTART_LOCK_WAIT_MS : 0)) storage = new OpfsStorage();
|
|
3647
|
+
else {
|
|
3648
|
+
storage = new MemoryStorage();
|
|
3649
|
+
degraded = "another-tab";
|
|
3650
|
+
}
|
|
3651
|
+
let quarantined;
|
|
3652
|
+
let stored;
|
|
3653
|
+
try {
|
|
3654
|
+
if (p.safeMode) quarantined = await storage.quarantineNewest();
|
|
3655
|
+
stored = await storage.open();
|
|
3656
|
+
} catch (e) {
|
|
3657
|
+
console.warn("[isoloop] persistent topics are in memory: storage failed to open", e);
|
|
3658
|
+
storage = new MemoryStorage();
|
|
3659
|
+
stored = await storage.open();
|
|
3660
|
+
degraded = "open-failed";
|
|
3661
|
+
}
|
|
3662
|
+
let built;
|
|
3663
|
+
try {
|
|
3664
|
+
built = await build(list, storage, stored, dev);
|
|
3665
|
+
} catch (e) {
|
|
3666
|
+
if (!(e instanceof DOMException)) {
|
|
3667
|
+
const message = e instanceof Error ? e.message : String(e);
|
|
3668
|
+
post({
|
|
3669
|
+
v: 1,
|
|
3670
|
+
t: "error",
|
|
3671
|
+
p: {
|
|
3672
|
+
message: `Restoring persistent topics failed: ${message}`,
|
|
3673
|
+
fatal: true
|
|
3674
|
+
}
|
|
3675
|
+
});
|
|
3676
|
+
return;
|
|
3677
|
+
}
|
|
3678
|
+
console.warn("[isoloop] persistent topics are in memory: reading them back failed", e);
|
|
3679
|
+
storage = new MemoryStorage();
|
|
3680
|
+
built = await build(list, storage, await storage.open(), dev);
|
|
3681
|
+
degraded = "open-failed";
|
|
3682
|
+
}
|
|
3683
|
+
const { b, restored } = built;
|
|
3684
|
+
broker = b;
|
|
3685
|
+
currentStorage = storage;
|
|
3686
|
+
const opened = /* @__PURE__ */ new Set([...list.topics.map((t) => t.name), ...b.seedSources]);
|
|
3687
|
+
const orphanNames = storage.kind === "opfs" ? stored.topics.map((t) => t.topic).filter((n) => !opened.has(n)) : [];
|
|
3688
|
+
const orphaned = orphanNames.length > 0 ? {
|
|
3689
|
+
names: orphanNames,
|
|
3690
|
+
bytes: (await Promise.all(orphanNames.map((n) => storage.bytes(n)))).reduce((a, n) => a + n, 0)
|
|
3691
|
+
} : void 0;
|
|
3692
|
+
if (storage.kind === "opfs") b.seed();
|
|
3693
|
+
post({
|
|
3694
|
+
v: 1,
|
|
3695
|
+
t: "ready",
|
|
3696
|
+
p: {
|
|
3697
|
+
engine: "ts",
|
|
3698
|
+
storage: storage.kind,
|
|
3699
|
+
restored,
|
|
3700
|
+
...quarantined ? { quarantined } : {},
|
|
3701
|
+
...degraded && persistent ? { degraded } : {},
|
|
3702
|
+
...orphaned ? { orphaned } : {}
|
|
3703
|
+
}
|
|
3704
|
+
});
|
|
3705
|
+
for (const msg of early.splice(0)) control(msg, b);
|
|
3706
|
+
startMetrics(b, storage.kind);
|
|
3707
|
+
};
|
|
3708
|
+
scope.addEventListener("message", (e) => {
|
|
3709
|
+
const msg = e.data;
|
|
3710
|
+
if (!isHostToBus(msg) || failed) return;
|
|
3711
|
+
if (msg.t === "boot") {
|
|
3712
|
+
if (booted) return;
|
|
3713
|
+
booted = true;
|
|
3714
|
+
boot(msg.p);
|
|
3715
|
+
return;
|
|
3716
|
+
}
|
|
3717
|
+
if (broker) control(msg, broker);
|
|
3718
|
+
else wait(msg);
|
|
3719
|
+
});
|
|
3720
|
+
}
|
|
3721
|
+
// src/worker.ts
|
|
3722
|
+
const report = (p) => {
|
|
3723
|
+
self.postMessage({
|
|
3724
|
+
v: 1,
|
|
3725
|
+
t: "error",
|
|
3726
|
+
p
|
|
3727
|
+
});
|
|
3728
|
+
};
|
|
3729
|
+
self.addEventListener("error", (e) => {
|
|
3730
|
+
report({
|
|
3731
|
+
message: e.message,
|
|
3732
|
+
fatal: false
|
|
3733
|
+
});
|
|
3734
|
+
});
|
|
3735
|
+
self.addEventListener("unhandledrejection", (e) => {
|
|
3736
|
+
const r = e.reason;
|
|
3737
|
+
report(r instanceof Error && r.stack !== void 0 ? {
|
|
3738
|
+
message: r.message,
|
|
3739
|
+
stack: r.stack,
|
|
3740
|
+
fatal: false
|
|
3741
|
+
} : {
|
|
3742
|
+
message: String(r),
|
|
3743
|
+
fatal: false
|
|
3744
|
+
});
|
|
3745
|
+
});
|
|
3746
|
+
serve(self);
|