@isoloop/bus 0.0.0 → 0.1.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1921 @@
1
+ import { t as toIssues } from "./standard-schema-DnJtEmJw.js";
2
+ import { SYSTEM_TOPICS, isIsolateToBus, isSystemTopic, matchAny, topicConfigOf } from "@isoloop/protocol";
3
+ import { CodecError, decode, encode } from "@isoloop/codec";
4
+ // src/topic.ts
5
+ /** Default `maxRecordBytes`: 256 KiB (design §6.1). */
6
+ const DEFAULT_MAX_RECORD_BYTES = 262144;
7
+ /** Defines a topic. Types come from the schemas. */
8
+ function topic(name, def) {
9
+ return Object.freeze({
10
+ ...def,
11
+ name
12
+ });
13
+ }
14
+ const UNCHECKED_VENDOR = "isoloop/unchecked";
15
+ /**
16
+ * A Standard Schema that accepts any value unchanged and only carries the type
17
+ * (ADR 0003, decision 2). Tools list topics that use it.
18
+ */
19
+ function unchecked() {
20
+ return { "~standard": {
21
+ version: 1,
22
+ vendor: UNCHECKED_VENDOR,
23
+ validate: (value) => ({ value })
24
+ } };
25
+ }
26
+ /** True if the schema came from `unchecked()`. */
27
+ function isUnchecked(schema) {
28
+ return schema["~standard"].vendor === UNCHECKED_VENDOR;
29
+ }
30
+ /** A contracts list that can't be built: duplicate or reserved names, or a bad definition. */
31
+ var ContractsError = class extends Error {
32
+ code;
33
+ /** The topics at fault. */
34
+ topics;
35
+ constructor(code, message, topics) {
36
+ super(message);
37
+ this.name = "ContractsError";
38
+ this.code = code;
39
+ this.topics = topics;
40
+ }
41
+ };
42
+ const RETENTION_KINDS = /* @__PURE__ */ new Set([
43
+ "last-n",
44
+ "time",
45
+ "compacted"
46
+ ]);
47
+ const isRecord = (x) => typeof x === "object" && x !== null;
48
+ const isSchema = (x) => isRecord(x) && isRecord(x["~standard"]) && typeof x["~standard"]["validate"] === "function";
49
+ const positiveInt = (n) => typeof n === "number" && Number.isInteger(n) && n > 0;
50
+ function problemOf(t) {
51
+ if (typeof t.name !== "string" || t.name === "") return "has no name";
52
+ if (!isSchema(t.schema)) return "has no Standard Schema";
53
+ if (t.reply !== void 0 && !isSchema(t.reply)) return "has a reply that is not a Standard Schema";
54
+ const r = t.retention;
55
+ if (!r || !RETENTION_KINDS.has(r.kind)) return "has no valid retention";
56
+ if (r.kind === "last-n" && !positiveInt(r.n)) return "needs a positive integer `n`";
57
+ if (r.kind === "time" && !positiveInt(r.ms)) return "needs a positive integer `ms`";
58
+ if (t.maxRecordBytes !== void 0 && !positiveInt(t.maxRecordBytes)) return "needs a positive integer `maxRecordBytes`";
59
+ if (t.durability !== void 0 && t.durability !== "memory" && t.durability !== "persistent") return "has a durability other than 'memory' or 'persistent'";
60
+ if (t.seed !== void 0) {
61
+ const s = t.seed;
62
+ if (!isRecord(s) || !isRecord(s.from) || typeof s.from.name !== "string") return "has a seed without a `from` topic";
63
+ if (typeof s.map !== "function") return "has a seed without a `map` function";
64
+ if (s.follow !== void 0 && typeof s.follow !== "boolean") return "has a seed whose `follow` is not a boolean";
65
+ if (s.from.name === t.name) return "seeds from itself";
66
+ }
67
+ }
68
+ /**
69
+ * Builds the contracts list. Rejects duplicate names and `isoloop.*` topics,
70
+ * which belong to the kernel (ADR 0003, decisions 4 and 6).
71
+ */
72
+ function contracts(...topics) {
73
+ const reserved = topics.filter((t) => isSystemTopic(t.name)).map((t) => t.name);
74
+ if (reserved.length > 0) throw new ContractsError("reserved_topic", `isoloop.* topics belong to the kernel: ${reserved.join(", ")}`, reserved);
75
+ for (const t of topics) {
76
+ const problem = problemOf(t);
77
+ if (problem) throw new ContractsError("contracts_invalid", `topic ${t.name} ${problem}`, [t.name]);
78
+ }
79
+ const byName = /* @__PURE__ */ new Map();
80
+ const dupes = /* @__PURE__ */ new Set();
81
+ for (const t of topics) {
82
+ if (byName.has(t.name)) dupes.add(t.name);
83
+ byName.set(t.name, t);
84
+ }
85
+ if (dupes.size > 0) {
86
+ const names = [...dupes];
87
+ throw new ContractsError("contracts_invalid", `duplicate topic names: ${names.join(", ")}`, names);
88
+ }
89
+ const cycle = seedCycle(byName);
90
+ if (cycle) throw new ContractsError("contracts_invalid", `seeds form a cycle: ${cycle.join(" → ")}`, cycle);
91
+ return Object.freeze({
92
+ "~isoloop": "contracts",
93
+ topics: Object.freeze([...topics]),
94
+ get: (name) => byName.get(name)
95
+ });
96
+ }
97
+ /** A chain of seeds that comes back to where it started, if there is one. */
98
+ function seedCycle(byName) {
99
+ for (const start of byName.values()) {
100
+ const path = [start.name];
101
+ let at = start.seed?.from;
102
+ while (at !== void 0) {
103
+ if (at.name === start.name) return [...path, at.name];
104
+ if (path.includes(at.name)) break;
105
+ path.push(at.name);
106
+ at = (byName.get(at.name) ?? at).seed?.from;
107
+ }
108
+ }
109
+ }
110
+ /** True for a value built by `contracts()`, from any copy of this package. */
111
+ function isContracts(x) {
112
+ return isRecord(x) && x["~isoloop"] === "contracts";
113
+ }
114
+ /** The structured-cloneable part of a topic, sent at `boot` for the contracts check (ADR 0003, decision 5). */
115
+ function topicConfig(t) {
116
+ return topicConfigOf(t);
117
+ }
118
+ // src/engine/memory-storage.ts
119
+ /** Storage that keeps nothing. Every topic behaves as `memory`. */
120
+ var MemoryStorage = class {
121
+ kind = "memory";
122
+ open() {
123
+ return Promise.resolve({
124
+ topics: [],
125
+ offsets: {}
126
+ });
127
+ }
128
+ appendBatch(_topic, _encoded) {}
129
+ flush() {
130
+ return Promise.resolve();
131
+ }
132
+ saveOffsets(_offsets) {}
133
+ dropBelow(_topic, _tail) {}
134
+ rewrite(_topic, _keep) {
135
+ return Promise.resolve();
136
+ }
137
+ readSegment(_topic, _fromOffset) {
138
+ return Promise.resolve([]);
139
+ }
140
+ bytes(_topic) {
141
+ return Promise.resolve(0);
142
+ }
143
+ deleteTopic(_topic) {
144
+ return Promise.resolve(false);
145
+ }
146
+ quarantineNewest() {
147
+ return Promise.resolve([]);
148
+ }
149
+ };
150
+ /**
151
+ * Engines call this from `createTopic`: the durability a topic actually gets.
152
+ * A `persistent` topic on storage that keeps nothing (no OPFS, or another tab
153
+ * holds it) behaves as `memory`; the kernel reports that as
154
+ * `bus:durability-degraded` (ADR 0007, decision 6).
155
+ */
156
+ function effectiveDurability(cfg, storage) {
157
+ if (cfg.durability !== "persistent") return "memory";
158
+ return storage.kind === "memory" ? "memory" : "persistent";
159
+ }
160
+ const OFFSET = 8;
161
+ const TABLE = (() => {
162
+ const t = /* @__PURE__ */ new Uint32Array(256);
163
+ for (let n = 0; n < 256; n++) {
164
+ let c = n;
165
+ for (let k = 0; k < 8; k++) c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
166
+ t[n] = c >>> 0;
167
+ }
168
+ return t;
169
+ })();
170
+ /** CRC-32 (IEEE 802.3, as in zip and PNG). */
171
+ function crc32(bytes, start = 0, end = bytes.length) {
172
+ let c = 4294967295;
173
+ for (let i = start; i < end; i++) c = (TABLE[(c ^ (bytes[i] ?? 0)) & 255] ?? 0) ^ c >>> 8;
174
+ return (c ^ 4294967295) >>> 0;
175
+ }
176
+ /** A frame: `number` in the header, `value` encoded after it. */
177
+ function pack(number, value) {
178
+ const body = encode(value);
179
+ const out = new Uint8Array(16 + body.length);
180
+ const view = new DataView(out.buffer);
181
+ view.setUint32(0, OFFSET + body.length, true);
182
+ view.setFloat64(8, number, true);
183
+ out.set(body, 16);
184
+ view.setUint32(4, crc32(out, 8), true);
185
+ return out;
186
+ }
187
+ /** The value of a frame written by `pack`. */
188
+ function unpack(frame) {
189
+ return decode(frame.subarray(16));
190
+ }
191
+ /** Encodes a record as one frame. Throws the codec's `not_encodable`. */
192
+ function encodeFrame(rec) {
193
+ const fields = [
194
+ rec.ts,
195
+ rec.producer,
196
+ rec.value,
197
+ rec.key,
198
+ rec.req,
199
+ rec.epoch,
200
+ rec.seq
201
+ ];
202
+ while (fields.length > 3 && fields.at(-1) === void 0) fields.pop();
203
+ return pack(rec.offset, fields);
204
+ }
205
+ /** The offset in a frame's header. */
206
+ function frameOffset(frame) {
207
+ return new DataView(frame.buffer, frame.byteOffset).getFloat64(8, true);
208
+ }
209
+ const isList = (x) => Array.isArray(x);
210
+ const isReq = (x) => typeof x === "object" && x !== null && typeof Reflect.get(x, "from") === "string" && typeof Reflect.get(x, "id") === "string";
211
+ /** Decodes one frame written by `encodeFrame`. */
212
+ function decodeFrame(frame) {
213
+ const offset = frameOffset(frame);
214
+ const fields = unpack(frame);
215
+ const [ts, producer, value, key, req, epoch, seq] = isList(fields) ? fields : [];
216
+ if (typeof ts !== "number" || typeof producer !== "string") throw new Error(`frame at offset ${offset} is not a record`);
217
+ const rec = {
218
+ offset,
219
+ value,
220
+ ts,
221
+ producer
222
+ };
223
+ if (typeof key === "string") rec.key = key;
224
+ if (isReq(req)) rec.req = req;
225
+ if (typeof epoch === "number") rec.epoch = epoch;
226
+ if (typeof seq === "number") rec.seq = seq;
227
+ return rec;
228
+ }
229
+ /** Pages of evicted records kept per engine, newest last. */
230
+ const PAGES = 8;
231
+ /** A compacted topic compacts itself once this share of its records is superseded… */
232
+ const DIRTY_RATIO = .5;
233
+ /** …and at least this many are. */
234
+ const DIRTY_MIN = 1024;
235
+ /**
236
+ * The TypeScript `LogEngine` (design §6.2). Each topic is an array of
237
+ * fixed-size chunks, so dropping old records frees a whole chunk at a time:
238
+ * O(1) per chunk. Compacted topics keep a key → latest-offset index.
239
+ */
240
+ var TsEngine = class {
241
+ name = "ts";
242
+ #topics = /* @__PURE__ */ new Map();
243
+ #now;
244
+ #storage;
245
+ #size;
246
+ #dirtyMin;
247
+ #residentBytes;
248
+ #pages = [];
249
+ #paging = /* @__PURE__ */ new Map();
250
+ /** While restoring, records are read back from disk: don't compact it under the read. */
251
+ #restoring = false;
252
+ constructor(opts = {}) {
253
+ this.#now = opts.now ?? Date.now;
254
+ this.#size = opts.chunkSize ?? 4096;
255
+ this.#dirtyMin = opts.dirtyMin ?? DIRTY_MIN;
256
+ this.#residentBytes = opts.residentBytes ?? 8388608;
257
+ this.#storage = opts.storage ?? new MemoryStorage();
258
+ }
259
+ #topic(name) {
260
+ const t = this.#topics.get(name);
261
+ if (!t) throw new Error(`unknown topic ${name}`);
262
+ return t;
263
+ }
264
+ createTopic(cfg) {
265
+ if (this.#topics.has(cfg.name)) throw new Error(`topic ${cfg.name} exists`);
266
+ const durable = effectiveDurability(cfg, this.#storage) === "persistent";
267
+ this.#topics.set(cfg.name, {
268
+ durable,
269
+ dropped: 0,
270
+ diskDirty: 0,
271
+ evictedTo: 0,
272
+ chunkBytes: [],
273
+ residentBytes: 0,
274
+ evicted: [],
275
+ appended: /* @__PURE__ */ new Map(),
276
+ cfg,
277
+ base: 0,
278
+ chunks: [],
279
+ head: 0,
280
+ tail: 0,
281
+ live: 0,
282
+ keys: cfg.retention.kind === "compacted" ? /* @__PURE__ */ new Map() : void 0,
283
+ dirty: 0,
284
+ commits: /* @__PURE__ */ new Map()
285
+ });
286
+ }
287
+ append(topic, rec, id) {
288
+ const t = this.#topic(topic);
289
+ const frame = t.durable ? encodeFrame({
290
+ ...rec,
291
+ ...id,
292
+ offset: t.head
293
+ }) : void 0;
294
+ if (frame) this.#storage.appendBatch(topic, [frame]);
295
+ if (t.durable && id) remember(t, rec.producer, id, t.head);
296
+ return this.#place(t, rec, t.head, frame?.length ?? 0);
297
+ }
298
+ appended(topic, producer, id) {
299
+ const a = this.#topics.get(topic)?.appended.get(producer);
300
+ return a?.epoch === id.epoch ? a.seqs.get(id.seq) : void 0;
301
+ }
302
+ /**
303
+ * Rebuilds durable topics from what the storage found on open (M2b task 7):
304
+ * every stored record, in order and at its own offset, with retention
305
+ * applied as if it had just been appended, and the committed offsets.
306
+ * Call after `createTopic`, before any append. Returns each restored
307
+ * topic's head.
308
+ */
309
+ async restore(state) {
310
+ const restored = [];
311
+ this.#restoring = true;
312
+ try {
313
+ await this.#restoreTopics(state, restored);
314
+ } finally {
315
+ this.#restoring = false;
316
+ }
317
+ for (const { topic } of restored) {
318
+ const t = this.#topic(topic);
319
+ if (t.keys) this.#compactKeys(t);
320
+ }
321
+ return restored;
322
+ }
323
+ async #restoreTopics(state, restored) {
324
+ for (const { topic, tail, head } of state.topics) {
325
+ const t = this.#topics.get(topic);
326
+ if (!t?.durable) continue;
327
+ if (t.head !== 0) throw new Error(`${topic} isn't empty`);
328
+ t.head = t.tail = t.dropped = tail;
329
+ t.base = Math.floor(tail / this.#size);
330
+ let from = tail;
331
+ while (from < head) {
332
+ const frames = await this.#storage.readSegment(topic, from);
333
+ if (frames.length === 0) break;
334
+ for (const f of frames) {
335
+ const { offset, epoch, seq, ...rec } = decodeFrame(f);
336
+ if (epoch !== void 0 && seq !== void 0) remember(t, rec.producer, {
337
+ epoch,
338
+ seq
339
+ }, offset);
340
+ this.#place(t, rec, offset, f.length);
341
+ from = offset + 1;
342
+ }
343
+ }
344
+ t.head = Math.max(t.head, head);
345
+ for (const [consumer, offset] of Object.entries(state.offsets[topic] ?? {})) t.commits.set(consumer, offset);
346
+ restored.push({
347
+ topic,
348
+ head: t.head
349
+ });
350
+ }
351
+ }
352
+ /** Stores a record at `offset` (≥ head; a gap is left as dropped slots) and applies retention. */
353
+ #place(t, rec, at, bytes) {
354
+ t.head = at + 1;
355
+ const offset = at;
356
+ const ci = Math.floor(offset / this.#size);
357
+ if (t.chunks.length === 0) {
358
+ t.base = ci;
359
+ t.chunkBytes = [];
360
+ }
361
+ let chunk = t.chunks[ci - t.base];
362
+ if (chunk === void 0 || chunk === null) {
363
+ chunk = [];
364
+ t.chunks[ci - t.base] = chunk;
365
+ }
366
+ chunk[offset % this.#size] = {
367
+ ...rec,
368
+ offset
369
+ };
370
+ t.live++;
371
+ if (t.durable) {
372
+ t.chunkBytes[ci - t.base] = (t.chunkBytes[ci - t.base] ?? 0) + bytes;
373
+ t.residentBytes += bytes;
374
+ if (t.residentBytes > this.#residentBytes) this.#evict(t);
375
+ }
376
+ const r = t.cfg.retention;
377
+ if (r.kind === "last-n") {
378
+ if (t.live > r.n) this.#dropBelow(t, t.head - r.n);
379
+ } else if (t.keys && rec.key !== void 0) {
380
+ const prev = t.keys.get(rec.key);
381
+ t.keys.set(rec.key, offset);
382
+ if (prev !== void 0 && t.durable) t.diskDirty++;
383
+ if (prev !== void 0 && prev >= t.tail && prev < t.evictedTo) t.live--;
384
+ else if (prev !== void 0 && prev >= t.tail) {
385
+ t.dirty++;
386
+ if (t.dirty >= this.#dirtyMin && t.dirty >= t.live * DIRTY_RATIO) this.#compactKeys(t);
387
+ }
388
+ }
389
+ return offset;
390
+ }
391
+ read(topic, fromOffset, max) {
392
+ const t = this.#topic(topic);
393
+ const out = [];
394
+ let o = Math.max(fromOffset, t.tail);
395
+ while (o < t.evictedTo && out.length < max) {
396
+ const page = this.#pageAt(t, o);
397
+ if (!page) return out;
398
+ for (const rec of page.records) {
399
+ if (out.length >= max) return out;
400
+ if (rec.offset >= o && this.#retained(t, rec)) out.push(rec);
401
+ }
402
+ o = page.to;
403
+ }
404
+ o = Math.max(o, t.evictedTo);
405
+ while (o < t.head && out.length < max) {
406
+ const ci = Math.floor(o / this.#size);
407
+ const chunk = t.chunks[ci - t.base];
408
+ const end = Math.min((ci + 1) * this.#size, t.head);
409
+ if (!chunk) {
410
+ o = end;
411
+ continue;
412
+ }
413
+ for (; o < end && out.length < max; o++) {
414
+ const rec = chunk[o % this.#size];
415
+ if (rec) out.push(rec);
416
+ }
417
+ }
418
+ return out;
419
+ }
420
+ head(topic) {
421
+ return this.#topic(topic).head;
422
+ }
423
+ readable(topic, fromOffset) {
424
+ return this.#unpaged(this.#topic(topic), fromOffset) === void 0;
425
+ }
426
+ /**
427
+ * Where a read from `from` would stop for want of a page: the first evicted
428
+ * offset no page covers, before any retained record. `undefined` when the
429
+ * read can answer.
430
+ */
431
+ #unpaged(t, from) {
432
+ let o = Math.max(from, t.tail);
433
+ while (o < t.evictedTo && o < t.head) {
434
+ const page = this.#pageAt(t, o);
435
+ if (!page) return o;
436
+ const at = o;
437
+ if (page.records.some((r) => r.offset >= at && this.#retained(t, r))) return void 0;
438
+ o = page.to;
439
+ }
440
+ }
441
+ page(topic, fromOffset) {
442
+ const t = this.#topic(topic);
443
+ const o = this.#unpaged(t, fromOffset);
444
+ if (o === void 0) return Promise.resolve();
445
+ const key = `${topic}\u0000${o}`;
446
+ let p = this.#paging.get(key);
447
+ if (!p) {
448
+ p = this.#readPage(t, o).finally(() => this.#paging.delete(key));
449
+ this.#paging.set(key, p);
450
+ }
451
+ return p;
452
+ }
453
+ /**
454
+ * Reads the segment holding `from` back from disk, and the ones after it
455
+ * until one holds a retained record, up to where eviction ends: a page
456
+ * always answers a read, so paging never goes round in circles.
457
+ */
458
+ async #readPage(t, from) {
459
+ await this.#storage.flush();
460
+ const records = [];
461
+ let o = from;
462
+ while (o < t.evictedTo && records.length === 0) {
463
+ const frames = await this.#storage.readSegment(t.cfg.name, o);
464
+ if (frames.length === 0) break;
465
+ for (const f of frames) {
466
+ const { epoch: _e, seq: _s, ...rec } = decodeFrame(f);
467
+ if (rec.offset >= t.evictedTo) break;
468
+ if (this.#retained(t, rec)) records.push(rec);
469
+ o = rec.offset + 1;
470
+ }
471
+ if (frameOffset(frames.at(-1) ?? /* @__PURE__ */ new Uint8Array(16)) >= t.evictedTo) break;
472
+ }
473
+ const to = records.length > 0 ? o : t.evictedTo;
474
+ this.#pages.push({
475
+ topic: t.cfg.name,
476
+ from,
477
+ to,
478
+ records
479
+ });
480
+ if (this.#pages.length > PAGES) this.#pages.shift();
481
+ }
482
+ #pageAt(t, offset) {
483
+ return this.#pages.find((p) => p.topic === t.cfg.name && p.from <= offset && offset < p.to);
484
+ }
485
+ /** Whether a record read back from disk is still retained in the log. */
486
+ #retained(t, rec) {
487
+ if (rec.offset < t.tail) return false;
488
+ return !t.keys || rec.key === void 0 || t.keys.get(rec.key) === rec.offset;
489
+ }
490
+ /**
491
+ * Evicts the oldest chunks until the topic fits `residentBytes` again
492
+ * (M2b task 11). Every record of a durable topic is on disk, or in the
493
+ * storage's buffer until the next commit; `page` reads them back.
494
+ */
495
+ #evict(t) {
496
+ while (t.residentBytes > this.#residentBytes && t.chunks.length > 1) {
497
+ const chunk = t.chunks.shift();
498
+ t.residentBytes -= t.chunkBytes.shift() ?? 0;
499
+ t.base++;
500
+ t.evictedTo = t.base * this.#size;
501
+ let count = 0;
502
+ let maxTs = -Infinity;
503
+ for (const rec of chunk ?? []) {
504
+ if (!rec || rec.offset < t.tail) continue;
505
+ count++;
506
+ maxTs = Math.max(maxTs, rec.ts);
507
+ }
508
+ if (count > 0) t.evicted.push({
509
+ end: t.evictedTo,
510
+ count,
511
+ maxTs
512
+ });
513
+ }
514
+ }
515
+ /** Lowest offset held in memory; below it, records are on disk only. For tests and metrics. */
516
+ resident(topic) {
517
+ const t = this.#topic(topic);
518
+ return Math.max(t.tail, t.evictedTo);
519
+ }
520
+ tail(topic) {
521
+ return this.#topic(topic).tail;
522
+ }
523
+ commit(topic, consumer, offset) {
524
+ const t = this.#topic(topic);
525
+ t.commits.set(consumer, offset);
526
+ if (t.durable) this.#storage.saveOffsets({ [topic]: Object.fromEntries(t.commits) });
527
+ }
528
+ committed(topic, consumer) {
529
+ return this.#topic(topic).commits.get(consumer);
530
+ }
531
+ durable(topic) {
532
+ return this.#topic(topic).durable;
533
+ }
534
+ flush(o) {
535
+ return this.#storage.flush(o);
536
+ }
537
+ compact(topic) {
538
+ const t = this.#topic(topic);
539
+ const r = t.cfg.retention;
540
+ if (r.kind === "time") this.#expire(t, this.#now() - r.ms);
541
+ else if (r.kind === "compacted") this.#compactKeys(t);
542
+ }
543
+ /** Drops every record below `offset` (last-n). */
544
+ #dropBelow(t, offset) {
545
+ if (offset <= t.tail) return;
546
+ const from = t.tail;
547
+ t.live -= this.#countLive(t, from, offset);
548
+ t.tail = offset;
549
+ this.#freeChunks(t);
550
+ this.#clearBelowTail(t, from);
551
+ }
552
+ /** Records in `[from, to)` still held. Last-n topics have no holes, so this is `to - from` there. */
553
+ #countLive(t, from, to) {
554
+ if (t.cfg.retention.kind === "last-n") return to - from;
555
+ let n = 0;
556
+ for (let o = from; o < to; o++) if (this.#at(t, o)) n++;
557
+ return n;
558
+ }
559
+ /** Drops records from the tail while the oldest is older than `cutoff` (time). */
560
+ #expire(t, cutoff) {
561
+ const from = t.tail;
562
+ let o = t.tail;
563
+ while (o < t.evictedTo) {
564
+ const s = t.evicted[0];
565
+ if (!s) {
566
+ o = t.evictedTo;
567
+ break;
568
+ }
569
+ if (s.maxTs >= cutoff) {
570
+ t.tail = o;
571
+ this.#freeChunks(t);
572
+ this.#clearBelowTail(t, from);
573
+ return;
574
+ }
575
+ t.live -= s.count;
576
+ t.evicted.shift();
577
+ o = s.end;
578
+ }
579
+ while (o < t.head) {
580
+ const rec = this.#at(t, o);
581
+ if (rec && rec.ts >= cutoff) break;
582
+ if (rec) t.live--;
583
+ o = rec || this.#chunkOf(t, o) ? o + 1 : (Math.floor(o / this.#size) + 1) * this.#size;
584
+ }
585
+ t.tail = Math.min(o, t.head);
586
+ this.#freeChunks(t);
587
+ this.#clearBelowTail(t, from);
588
+ }
589
+ /**
590
+ * Clears the slots in `[from, tail)` that are still in a held chunk:
591
+ * `#freeChunks` frees whole chunks only, so without this a slow topic keeps
592
+ * its expired records referenced until the chunk holding its tail fills,
593
+ * minutes at a few records a second (plant memory investigation, #162).
594
+ * Each record is cleared once, as the tail passes it.
595
+ */
596
+ #clearBelowTail(t, from) {
597
+ for (let o = Math.max(from, t.base * this.#size); o < t.tail; o++) {
598
+ const chunk = this.#chunkOf(t, o);
599
+ if (chunk) chunk[o % this.#size] = void 0;
600
+ }
601
+ }
602
+ /** Drops records superseded by a later record with the same key; keyless records stay. */
603
+ #compactKeys(t) {
604
+ const keys = t.keys;
605
+ if (!keys) return;
606
+ for (let ci = 0; ci < t.chunks.length; ci++) {
607
+ const chunk = t.chunks[ci];
608
+ if (!chunk) continue;
609
+ let kept = 0;
610
+ for (let s = 0; s < chunk.length; s++) {
611
+ const rec = chunk[s];
612
+ if (!rec) continue;
613
+ if (rec.offset < t.tail || rec.key !== void 0 && keys.get(rec.key) !== rec.offset) {
614
+ chunk[s] = void 0;
615
+ if (rec.offset >= t.tail) t.live--;
616
+ } else kept++;
617
+ }
618
+ if (kept === 0) {
619
+ t.chunks[ci] = null;
620
+ t.residentBytes -= t.chunkBytes[ci] ?? 0;
621
+ t.chunkBytes[ci] = 0;
622
+ }
623
+ }
624
+ t.dirty = 0;
625
+ 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;
626
+ t.tail = Math.min(t.tail, t.head);
627
+ this.#freeChunks(t);
628
+ this.#compactDisk(t);
629
+ }
630
+ /**
631
+ * Compaction on disk (M2b task 10), once at least half of what the disk
632
+ * holds for the topic is superseded: the same rule as in memory.
633
+ */
634
+ #compactDisk(t) {
635
+ if (!t.durable || this.#restoring || t.diskDirty < this.#dirtyMin || t.diskDirty < t.live) return;
636
+ t.diskDirty = 0;
637
+ const keys = t.keys;
638
+ const keep = (offset, key) => offset >= t.tail && (key === void 0 || keys?.get(key) === offset);
639
+ this.#storage.rewrite(t.cfg.name, keep).catch((e) => {
640
+ console.warn(`[isoloop] compacting ${t.cfg.name} on disk failed`, e);
641
+ });
642
+ }
643
+ #chunkOf(t, offset) {
644
+ return t.chunks[Math.floor(offset / this.#size) - t.base];
645
+ }
646
+ #at(t, offset) {
647
+ return this.#chunkOf(t, offset)?.[offset % this.#size];
648
+ }
649
+ /** Frees whole chunks below the tail, and on disk the segments below it. */
650
+ #freeChunks(t) {
651
+ if (t.durable && t.tail > t.dropped) {
652
+ t.dropped = t.tail;
653
+ this.#storage.dropBelow(t.cfg.name, t.tail);
654
+ }
655
+ while ((t.evicted[0]?.end ?? Infinity) <= t.tail) t.evicted.shift();
656
+ const keep = Math.floor(t.tail / this.#size);
657
+ const drop = Math.min(keep - t.base, t.chunks.length);
658
+ if (drop > 0) {
659
+ t.chunks.splice(0, drop);
660
+ for (const b of t.chunkBytes.splice(0, drop)) t.residentBytes -= b;
661
+ t.base += drop;
662
+ }
663
+ if (t.chunks.length === 0) {
664
+ t.base = Math.floor(t.head / this.#size);
665
+ t.chunkBytes = [];
666
+ t.residentBytes = 0;
667
+ }
668
+ if (t.evictedTo > 0) t.evictedTo = Math.max(t.evictedTo, t.base * this.#size);
669
+ }
670
+ /** Chunks held for a topic, for tests and metrics. */
671
+ chunkCount(topic) {
672
+ return this.#topic(topic).chunks.length;
673
+ }
674
+ /** Records held in memory for a topic, for tests and metrics. */
675
+ heldCount(topic) {
676
+ let n = 0;
677
+ for (const chunk of this.#topic(topic).chunks) for (const r of chunk ?? []) if (r) n++;
678
+ return n;
679
+ }
680
+ };
681
+ /** Notes that `producer` appended `id` at `offset`; a new epoch forgets the old one's. */
682
+ function remember(t, producer, id, offset) {
683
+ let a = t.appended.get(producer);
684
+ if (a?.epoch !== id.epoch) {
685
+ a = {
686
+ epoch: id.epoch,
687
+ seqs: /* @__PURE__ */ new Map()
688
+ };
689
+ t.appended.set(producer, a);
690
+ }
691
+ a.seqs.set(id.seq, offset);
692
+ if (a.seqs.size > 1e3) {
693
+ const oldest = a.seqs.keys().next();
694
+ if (!oldest.done) a.seqs.delete(oldest.value);
695
+ }
696
+ }
697
+ // src/size.ts
698
+ /**
699
+ * A rough structured size of a value in bytes, for `maxRecordBytes` (design
700
+ * §6.1). Strings count two bytes per UTF-16 unit, numbers eight, object keys
701
+ * like strings, plus a little per entry. Cycles count once. Cheap rather than
702
+ * exact: it only has to tell a 1 KiB record from a 1 MiB one.
703
+ */
704
+ function estimateSize(value, limit = Infinity) {
705
+ const seen = /* @__PURE__ */ new Set();
706
+ const stack = [value];
707
+ let size = 0;
708
+ while (stack.length > 0 && size <= limit) {
709
+ const v = stack.pop();
710
+ switch (typeof v) {
711
+ case "string":
712
+ size += 2 * v.length + 4;
713
+ continue;
714
+ case "number":
715
+ case "bigint":
716
+ size += 8;
717
+ continue;
718
+ case "boolean":
719
+ case "undefined":
720
+ size += 1;
721
+ continue;
722
+ case "symbol":
723
+ case "function": continue;
724
+ }
725
+ if (v === null) {
726
+ size += 1;
727
+ continue;
728
+ }
729
+ if (seen.has(v)) continue;
730
+ seen.add(v);
731
+ if (ArrayBuffer.isView(v)) size += v.byteLength + 8;
732
+ else if (v instanceof ArrayBuffer) size += v.byteLength + 8;
733
+ else if (Array.isArray(v)) {
734
+ size += 8 + v.length;
735
+ for (const x of v) stack.push(x);
736
+ } else if (v instanceof Map) {
737
+ size += 8;
738
+ for (const [k, x] of v) stack.push(k, x);
739
+ } else if (v instanceof Set) {
740
+ size += 8;
741
+ for (const x of v) stack.push(x);
742
+ } else {
743
+ size += 8;
744
+ for (const [k, x] of Object.entries(v)) {
745
+ size += 2 * k.length + 4;
746
+ stack.push(x);
747
+ }
748
+ }
749
+ }
750
+ return size;
751
+ }
752
+ /**
753
+ * Seed progress, kept as committed offsets of reserved consumers on the
754
+ * seeding topic. Offsets are written after the records of the same group
755
+ * commit, so the progress never points past what is on disk (ADR 0003,
756
+ * decision 18: exactly once).
757
+ */
758
+ const SEED_FROM = "isoloop:seed:from";
759
+ /** The seeding topic's head when `SEED_FROM` was saved. */
760
+ const SEED_HEAD = "isoloop:seed:head";
761
+ /** Set when the seed ended: the source's head then. */
762
+ const SEED_DONE = "isoloop:seed:done";
763
+ /** How many source records were rejected, all runs together. */
764
+ const SEED_REJECTED = "isoloop:seed:rejected";
765
+ /** One per rejected source offset; its value is the offset. */
766
+ const SEED_REJECTED_AT = "isoloop:seed:rejected:";
767
+ /** Whether a seed into `to` started on this device and hasn't ended. */
768
+ function seedPending(engine, to) {
769
+ return engine.committed(to, "isoloop:seed:from") !== void 0 && !seedDone(engine, to);
770
+ }
771
+ function seedDone(engine, to) {
772
+ return engine.committed(to, SEED_DONE) !== void 0;
773
+ }
774
+ /**
775
+ * Topics with a seed, sources before the topics that seed from them, so a
776
+ * chain (v3 from v2 from v1) runs in order. `contracts()` has already refused
777
+ * unknown sources and cycles.
778
+ */
779
+ function seedOrder(topics) {
780
+ const byName = new Map(topics.map((t) => [t.name, t]));
781
+ const out = [];
782
+ const seen = /* @__PURE__ */ new Set();
783
+ const visit = (t) => {
784
+ if (seen.has(t.name)) return;
785
+ seen.add(t.name);
786
+ const from = t.seed && byName.get(t.seed.from.name);
787
+ if (from) visit(from);
788
+ if (t.seed) out.push(t);
789
+ };
790
+ for (const t of topics) visit(t);
791
+ return out;
792
+ }
793
+ const issue = (message) => [{
794
+ message,
795
+ path: []
796
+ }];
797
+ /** Runs `map`; a throw or a returned promise rejects the record. */
798
+ function mapRecord(map, rec) {
799
+ let mapped;
800
+ try {
801
+ mapped = map(rec.value, rec);
802
+ } catch (e) {
803
+ return {
804
+ ok: false,
805
+ code: "invalid",
806
+ issues: issue(`map threw: ${String(e)}`)
807
+ };
808
+ }
809
+ if (mapped instanceof Promise) {
810
+ mapped.catch(() => {});
811
+ return {
812
+ ok: false,
813
+ code: "seed_async",
814
+ issues: issue("map returned a promise")
815
+ };
816
+ }
817
+ return {
818
+ ok: true,
819
+ value: mapped
820
+ };
821
+ }
822
+ /**
823
+ * Copies `from`'s records into `to` until it reaches `from`'s head, keeping
824
+ * each record's `ts`, `producer` and `key`, and saving progress with every
825
+ * batch. A seed cut short resumes after the last saved source offset; records
826
+ * it appended after that save are recognised and not appended again, since
827
+ * `map` and the schema are pure. Records `map` or `to`'s schema rejects are
828
+ * skipped, reported and recorded. Yields between batches, so other topics
829
+ * carry on.
830
+ */
831
+ async function copySeed(c) {
832
+ const { engine, to, from } = c;
833
+ const last = engine.committed(to, SEED_FROM);
834
+ let offset = Math.max(last === void 0 ? 0 : last + 1, engine.tail(from));
835
+ let skip = engine.head(to) - (engine.committed(to, "isoloop:seed:head") ?? 0);
836
+ let rejected = engine.committed(to, "isoloop:seed:rejected") ?? 0;
837
+ while (offset < engine.head(from)) {
838
+ if (!engine.readable(from, offset)) await engine.page(from, offset);
839
+ const batch = engine.read(from, offset, 256);
840
+ const end = batch.at(-1);
841
+ if (!end) break;
842
+ for (const rec of batch) {
843
+ const mapped = mapRecord(c.map, rec);
844
+ const verdict = mapped.ok ? await c.accept(mapped.value) : mapped;
845
+ if (!verdict.ok) {
846
+ const at = `${SEED_REJECTED_AT}${rec.offset}`;
847
+ if (engine.committed(to, at) === void 0) {
848
+ engine.commit(to, at, rec.offset);
849
+ rejected++;
850
+ }
851
+ c.onReject?.(rec.offset, verdict);
852
+ continue;
853
+ }
854
+ if (skip > 0) {
855
+ skip--;
856
+ continue;
857
+ }
858
+ let out = {
859
+ value: verdict.value,
860
+ ts: rec.ts,
861
+ producer: rec.producer
862
+ };
863
+ if (rec.key !== void 0) out = {
864
+ ...out,
865
+ key: rec.key
866
+ };
867
+ engine.append(to, out);
868
+ }
869
+ offset = end.offset + 1;
870
+ engine.commit(to, SEED_REJECTED, rejected);
871
+ engine.commit(to, SEED_FROM, end.offset);
872
+ engine.commit(to, SEED_HEAD, engine.head(to));
873
+ await new Promise((r) => setTimeout(r, 0));
874
+ }
875
+ engine.commit(to, SEED_REJECTED, rejected);
876
+ engine.commit(to, SEED_DONE, engine.head(from));
877
+ return {
878
+ copied: engine.head(to),
879
+ rejected
880
+ };
881
+ }
882
+ // src/broker.ts
883
+ const fail = (code, message, extra) => ({
884
+ ok: false,
885
+ error: {
886
+ code,
887
+ message,
888
+ ...extra
889
+ }
890
+ });
891
+ const isStartPosition = (x) => x === "latest" || x === "earliest" || x === "committed";
892
+ const hasTopic = (p) => typeof p === "object" && p !== null && "topic" in p && typeof p.topic === "string";
893
+ const isOffset = (x) => typeof x === "number" && Number.isInteger(x) && x >= 0;
894
+ /** A commit's `seq`: a non-negative integer, 0 before any delivery is settled whole. */
895
+ const isSeq = isOffset;
896
+ /** FNV-1a: a small, stable string hash for key → group member. */
897
+ function hash(s) {
898
+ let h = 2166136261;
899
+ for (let i = 0; i < s.length; i++) {
900
+ h ^= s.charCodeAt(i);
901
+ h = Math.imul(h, 16777619);
902
+ }
903
+ return h >>> 0;
904
+ }
905
+ const reqKey = (topic, offset) => `${topic}\u0000${offset}`;
906
+ /** A message's `(epoch, seq)`, when it carries both as numbers. */
907
+ function publishId(p) {
908
+ const { epoch, seq } = p;
909
+ return typeof epoch === "number" && typeof seq === "number" ? {
910
+ epoch,
911
+ seq
912
+ } : void 0;
913
+ }
914
+ /** Producer id for records the host publishes through `kernel.publish`. */
915
+ const HOST_PRODUCER = "host";
916
+ /** Producer id for records the kernel publishes to system topics. */
917
+ const KERNEL_PRODUCER = "kernel";
918
+ /** Requests are forgotten after this long when the caller gives no timeout. */
919
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
920
+ /**
921
+ * The bus core (design §6.3): runs the publish pipeline, keeps subscriptions
922
+ * and consumer groups, delivers from the log under credit, and routes
923
+ * request replies. Knows nothing about workers; the bus worker entry wires
924
+ * ports to it.
925
+ */
926
+ var Broker = class {
927
+ #engine;
928
+ #now;
929
+ #dev;
930
+ #batch;
931
+ #inboxLimit;
932
+ #timers;
933
+ #durable;
934
+ #storageFull = false;
935
+ #topics = /* @__PURE__ */ new Map();
936
+ #conns = /* @__PURE__ */ new Map();
937
+ #groups = /* @__PURE__ */ new Map();
938
+ #requests = /* @__PURE__ */ new Map();
939
+ /** Consumers whose offsets were dropped by `detach { keepOffsets: false }`, per topic. */
940
+ #forgotten = /* @__PURE__ */ new Set();
941
+ #rejected = {};
942
+ /** Suspended isolates by topic: who to wake when a record arrives there. */
943
+ #sleepers = /* @__PURE__ */ new Map();
944
+ #onWake;
945
+ #onSeed;
946
+ /** Seed sources the contracts don't list: in the engine, so seeds can read them, but not open to isolates. */
947
+ #sources = /* @__PURE__ */ new Set();
948
+ #followReports = /* @__PURE__ */ new Map();
949
+ #dropped = 0;
950
+ constructor(opts) {
951
+ this.#engine = opts.engine;
952
+ this.#now = opts.now ?? Date.now;
953
+ this.#dev = opts.dev ?? false;
954
+ this.#batch = opts.batchSize ?? 64;
955
+ this.#inboxLimit = opts.inboxLimit ?? 1e3;
956
+ this.#timers = opts.timers ?? { set: (fn, ms) => void setTimeout(fn, ms) };
957
+ this.#durable = opts.durable ?? ((topic) => this.#engine.durable(topic));
958
+ this.#onWake = opts.onWake ?? (() => {});
959
+ this.#onSeed = opts.onSeed ?? (() => {});
960
+ for (const def of [...opts.systemTopics ?? SYSTEM_TOPICS, ...opts.contracts.topics]) {
961
+ this.#engine.createTopic(topicConfig(def));
962
+ this.#topics.set(def.name, {
963
+ def,
964
+ maxBytes: def.maxRecordBytes ?? 262144,
965
+ queue: [],
966
+ seeding: void 0,
967
+ records: 0,
968
+ bytes: 0
969
+ });
970
+ }
971
+ for (const def of opts.contracts.topics) {
972
+ const from = def.seed?.from;
973
+ if (!from || this.#topics.has(from.name) || this.#sources.has(from.name)) continue;
974
+ this.#engine.createTopic(topicConfig(from));
975
+ this.#sources.add(from.name);
976
+ }
977
+ }
978
+ #sleep(topic, isolateId) {
979
+ let set = this.#sleepers.get(topic);
980
+ if (!set) this.#sleepers.set(topic, set = /* @__PURE__ */ new Set());
981
+ set.add(isolateId);
982
+ }
983
+ #unsleep(isolateId) {
984
+ for (const set of this.#sleepers.values()) set.delete(isolateId);
985
+ }
986
+ /** Wakes every isolate sleeping on `topic`, once. */
987
+ #wake(topic) {
988
+ const set = this.#sleepers.get(topic);
989
+ if (!set || set.size === 0) return;
990
+ for (const id of set) {
991
+ this.#unsleep(id);
992
+ this.#onWake(id, topic);
993
+ }
994
+ }
995
+ /** Messages dropped as malformed or unknown (design §3: dropped and counted). */
996
+ get dropped() {
997
+ return this.#dropped;
998
+ }
999
+ /** Counters for the 1 s metrics sample. */
1000
+ stats() {
1001
+ const subscriptions = [];
1002
+ const groups = /* @__PURE__ */ new Set();
1003
+ for (const conn of this.#conns.values()) for (const sub of conn.subs.values()) {
1004
+ const head = this.#engine.head(sub.topic);
1005
+ const g = sub.group;
1006
+ if (g) {
1007
+ if (groups.has(g)) continue;
1008
+ groups.add(g);
1009
+ const credit = g.members.reduce((n, m) => n + m.credit, 0);
1010
+ subscriptions.push({
1011
+ consumer: g.consumer,
1012
+ topic: g.topic,
1013
+ lag: head - g.cursor,
1014
+ credit
1015
+ });
1016
+ continue;
1017
+ }
1018
+ subscriptions.push({
1019
+ consumer: conn.isolateId,
1020
+ topic: sub.topic,
1021
+ lag: head - sub.cursor,
1022
+ credit: sub.credit
1023
+ });
1024
+ }
1025
+ return {
1026
+ topics: [...this.#topics].map(([topic, t]) => ({
1027
+ topic,
1028
+ records: t.records,
1029
+ bytes: t.bytes
1030
+ })),
1031
+ subscriptions,
1032
+ rejected: { ...this.#rejected }
1033
+ };
1034
+ }
1035
+ /**
1036
+ * The origin's storage is full (M2b task 14): publishes to persistent
1037
+ * topics reject with `quota_exceeded`, memory topics carry on.
1038
+ */
1039
+ setStorageFull(full) {
1040
+ this.#storageFull = full;
1041
+ }
1042
+ /**
1043
+ * Writes what persistent topics have pending at once: the page is freezing
1044
+ * or going away (ADR 0001, what the browser still controls).
1045
+ */
1046
+ flush() {
1047
+ return this.#engine.flush({ now: true });
1048
+ }
1049
+ /**
1050
+ * Starts every declared seed whose topic is empty and whose source has
1051
+ * records, or is seeding itself (ADR 0003, decision 18). The topics are
1052
+ * marked seeding before this returns, so call it before any connection is
1053
+ * attached. Resolves when every seed has ended. The bus worker calls it
1054
+ * only when it holds the files: elsewhere persistent topics start empty.
1055
+ */
1056
+ seed() {
1057
+ const runs = /* @__PURE__ */ new Map();
1058
+ for (const def of seedOrder([...this.#topics.values()].map((t) => t.def))) {
1059
+ const topic = this.#topics.get(def.name);
1060
+ const seed = def.seed;
1061
+ if (!topic || !seed) continue;
1062
+ const from = seed.from.name;
1063
+ const before = runs.get(from);
1064
+ const hasData = this.#engine.head(from) > this.#engine.tail(from);
1065
+ if (seedDone(this.#engine, def.name)) continue;
1066
+ if (!seedPending(this.#engine, def.name)) {
1067
+ if (this.#engine.head(def.name) > 0 || !hasData && !before) continue;
1068
+ }
1069
+ topic.seeding = [];
1070
+ const run = (before ?? Promise.resolve()).then(() => copySeed({
1071
+ engine: this.#engine,
1072
+ to: def.name,
1073
+ from,
1074
+ map: seed.map,
1075
+ accept: (value) => {
1076
+ const v = validate(def.schema, value);
1077
+ const verdict = (r) => {
1078
+ const c = this.#check(def.name, r, def.durability === "persistent");
1079
+ if (c.ok) return {
1080
+ ok: true,
1081
+ value: c.value
1082
+ };
1083
+ return {
1084
+ ok: false,
1085
+ code: c.error.code,
1086
+ issues: c.error.issues ?? [{
1087
+ message: c.error.message,
1088
+ path: []
1089
+ }]
1090
+ };
1091
+ };
1092
+ return v instanceof Promise ? v.then(verdict) : verdict(v);
1093
+ },
1094
+ onReject: this.#seedReporter(def.name, from)
1095
+ })).then((r) => {
1096
+ this.#onSeed({
1097
+ kind: "seeded",
1098
+ topic: def.name,
1099
+ ...r
1100
+ });
1101
+ this.#open(def.name, topic);
1102
+ }, (e) => {
1103
+ console.warn(`[isoloop] seeding ${def.name} from ${from} failed`, e);
1104
+ this.#open(def.name, topic);
1105
+ });
1106
+ runs.set(def.name, run);
1107
+ }
1108
+ return Promise.all(runs.values()).then(() => {});
1109
+ }
1110
+ /**
1111
+ * `follow` (ADR 0003, decision 18): a record appended to a seed source goes
1112
+ * on, through `map` and the topic's schema, to each topic that follows it
1113
+ * and isn't seeding (a seed in progress copies it itself).
1114
+ */
1115
+ #follow(source, rec) {
1116
+ for (const topic of this.#topics.values()) {
1117
+ const seed = topic.def.seed;
1118
+ if (!seed?.follow || seed.from.name !== source || topic.seeding) continue;
1119
+ const name = topic.def.name;
1120
+ let report = this.#followReports.get(name);
1121
+ if (!report) this.#followReports.set(name, report = this.#seedReporter(name, source));
1122
+ const rejected = report;
1123
+ const mapped = mapRecord(seed.map, rec);
1124
+ if (!mapped.ok) {
1125
+ rejected(rec.offset, mapped);
1126
+ continue;
1127
+ }
1128
+ const pending = {
1129
+ bytes: 0,
1130
+ producer: rec.producer,
1131
+ key: rec.key,
1132
+ req: void 0,
1133
+ ts: rec.ts,
1134
+ done: false,
1135
+ result: void 0,
1136
+ settle: (r) => {
1137
+ if (!r.ok) {
1138
+ const issues = r.error.issues ?? [{
1139
+ message: r.error.message,
1140
+ path: []
1141
+ }];
1142
+ rejected(rec.offset, {
1143
+ ok: false,
1144
+ code: r.error.code,
1145
+ issues
1146
+ });
1147
+ }
1148
+ }
1149
+ };
1150
+ this.#enqueue(name, topic, pending, validate(topic.def.schema, mapped.value));
1151
+ }
1152
+ }
1153
+ /**
1154
+ * Why `kernel.dropTopic(name)` may not delete `name`, if it may not (ADR
1155
+ * 0003, decision 19): the contracts list it, a declared seed that reads it
1156
+ * hasn't ended, or seed records rejected from it are recorded and `force`
1157
+ * isn't set.
1158
+ */
1159
+ dropRefusal(name, force) {
1160
+ if (this.#topics.has(name)) return fail("invalid", `${name} is in the contracts`);
1161
+ for (const t of this.#topics.values()) {
1162
+ if (t.def.seed?.from.name !== name) continue;
1163
+ if (!seedDone(this.#engine, t.def.name)) return fail("seed_pending", `${t.def.name} still seeds from ${name}`);
1164
+ 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`);
1165
+ }
1166
+ }
1167
+ /** Persistent topics a declared seed reads that the contracts don't list. */
1168
+ get seedSources() {
1169
+ return [...this.#sources];
1170
+ }
1171
+ /** Reports rejected seed records, at most `SEED_REPORTS_PER_SEC` a second. */
1172
+ #seedReporter(topic, from) {
1173
+ let windowStart = -Infinity;
1174
+ let sent = 0;
1175
+ return (offset, v) => {
1176
+ const now = this.#now();
1177
+ if (now - windowStart >= 1e3) {
1178
+ windowStart = now;
1179
+ sent = 0;
1180
+ }
1181
+ if (sent >= 10) return;
1182
+ sent++;
1183
+ this.#onSeed({
1184
+ kind: "rejected",
1185
+ topic,
1186
+ from,
1187
+ offset,
1188
+ code: v.code,
1189
+ issues: v.issues
1190
+ });
1191
+ };
1192
+ }
1193
+ /** A seed ended: the topic takes its waiting publishes, then its waiting subscribes. */
1194
+ #open(name, topic) {
1195
+ const held = topic.seeding ?? [];
1196
+ topic.seeding = void 0;
1197
+ this.#drain(name, topic);
1198
+ for (const h of held) {
1199
+ if (this.#conns.get(h.conn.isolateId) !== h.conn) continue;
1200
+ h.reply(this.#subscribe(h.conn, name, h.from, h.group));
1201
+ }
1202
+ if (this.#engine.durable(name)) this.#engine.flush();
1203
+ }
1204
+ /** Retention pass over every topic (`time` and `compacted`); the bus worker runs it every second. */
1205
+ compact() {
1206
+ for (const name of this.#topics.keys()) this.#engine.compact(name);
1207
+ }
1208
+ /**
1209
+ * Connects an isolate. A second attach for the same id replaces the first.
1210
+ * With `reattach`, the isolate was connected to a bus that restarted: its
1211
+ * first subscribe to each memory topic is answered with `reset` (ADR 0007).
1212
+ */
1213
+ attach(isolateId, grants, port, opts = {}) {
1214
+ this.detach(isolateId, true);
1215
+ const conn = {
1216
+ isolateId,
1217
+ grants,
1218
+ port,
1219
+ subs: /* @__PURE__ */ new Map(),
1220
+ reset: opts.reattach ? /* @__PURE__ */ new Set() : void 0
1221
+ };
1222
+ this.#conns.set(isolateId, conn);
1223
+ port.onMessage((msg) => {
1224
+ if (this.#conns.get(isolateId) === conn) this.#receive(conn, msg);
1225
+ });
1226
+ }
1227
+ /**
1228
+ * Disconnects an isolate, drops its subscriptions and leaves its groups,
1229
+ * which rebalance. With `keepOffsets` its commits stay, so a restart with
1230
+ * `from: 'committed'` resumes (I6). Replies to its pending requests are dropped.
1231
+ */
1232
+ detach(isolateId, keepOffsets, opts = {}) {
1233
+ if (!opts.wake) this.#unsleep(isolateId);
1234
+ const conn = this.#conns.get(isolateId);
1235
+ if (!conn) return;
1236
+ this.#conns.delete(isolateId);
1237
+ for (const sub of conn.subs.values()) {
1238
+ const g = sub.group;
1239
+ if (opts.wake && (!g || g.members.length === 1)) this.#sleep(sub.topic, isolateId);
1240
+ this.#leave(sub);
1241
+ }
1242
+ conn.subs.clear();
1243
+ if (!keepOffsets) for (const name of this.#topics.keys()) this.#forgotten.add(`${name}\u0000${isolateId}`);
1244
+ conn.port.close();
1245
+ }
1246
+ /**
1247
+ * Publishes for the host (`kernel.publish`) or the kernel (system topics).
1248
+ * The host can't publish system topics; the kernel can only publish them.
1249
+ */
1250
+ publish(from, topic, key, value, id) {
1251
+ return new Promise((resolve) => this.#publish(from, topic, key, value, void 0, resolve, id));
1252
+ }
1253
+ #receive(conn, msg) {
1254
+ if (!isIsolateToBus(msg) || msg.t !== "commits" && !hasTopic(msg.p)) {
1255
+ this.#dropped++;
1256
+ return;
1257
+ }
1258
+ const reply = (r) => {
1259
+ if (msg.id !== void 0) conn.port.post({
1260
+ v: 1,
1261
+ t: "result",
1262
+ re: msg.id,
1263
+ p: r
1264
+ });
1265
+ };
1266
+ this.#handle(conn, msg, reply);
1267
+ }
1268
+ #handle(conn, msg, reply) {
1269
+ const self = {
1270
+ kind: "isolate",
1271
+ isolateId: conn.isolateId
1272
+ };
1273
+ switch (msg.t) {
1274
+ case "publish": {
1275
+ const key = msg.p.key;
1276
+ if (key !== void 0 && typeof key !== "string") {
1277
+ reply(fail("invalid", "key must be a string"));
1278
+ return;
1279
+ }
1280
+ this.#publish(self, msg.p.topic, key, msg.p.value, void 0, reply, publishId(msg.p));
1281
+ return;
1282
+ }
1283
+ case "request": {
1284
+ const { id } = msg;
1285
+ const key = msg.p.key;
1286
+ const timeoutMs = msg.p.timeoutMs;
1287
+ if (id === void 0) {
1288
+ this.#dropped++;
1289
+ return;
1290
+ }
1291
+ if (key !== void 0 && typeof key !== "string") {
1292
+ reply(fail("invalid", "key must be a string"));
1293
+ return;
1294
+ }
1295
+ const ms = typeof timeoutMs === "number" && timeoutMs > 0 ? timeoutMs : DEFAULT_REQUEST_TIMEOUT_MS;
1296
+ const onFail = (r) => {
1297
+ if (!r.ok) reply(r);
1298
+ };
1299
+ this.#publish(self, msg.p.topic, key, msg.p.value, {
1300
+ from: conn,
1301
+ id,
1302
+ timeoutMs: ms
1303
+ }, onFail, publishId(msg.p));
1304
+ return;
1305
+ }
1306
+ case "reply":
1307
+ this.#reply(conn, msg.p.topic, msg.p.offset, msg.p.value, reply);
1308
+ return;
1309
+ case "subscribe": {
1310
+ const held = this.#topics.get(msg.p.topic)?.seeding;
1311
+ if (held && (isSystemTopic(msg.p.topic) || matchAny(conn.grants.subscribe, msg.p.topic))) {
1312
+ held.push({
1313
+ conn,
1314
+ from: msg.p.from,
1315
+ group: msg.p.group,
1316
+ reply
1317
+ });
1318
+ return;
1319
+ }
1320
+ reply(this.#subscribe(conn, msg.p.topic, msg.p.from, msg.p.group));
1321
+ return;
1322
+ }
1323
+ case "unsubscribe": {
1324
+ const held = this.#topics.get(msg.p.topic)?.seeding;
1325
+ if (held) for (let i = held.length - 1; i >= 0; i--) {
1326
+ const h = held[i];
1327
+ if (h?.conn !== conn) continue;
1328
+ held.splice(i, 1);
1329
+ h.reply(fail("invalid", "unsubscribed before the seed ended"));
1330
+ }
1331
+ const sub = conn.subs.get(msg.p.topic);
1332
+ if (sub) this.#leave(sub);
1333
+ conn.subs.delete(msg.p.topic);
1334
+ reply({
1335
+ ok: true,
1336
+ value: null
1337
+ });
1338
+ return;
1339
+ }
1340
+ case "commits": {
1341
+ const offsets = msg.p.offsets;
1342
+ if (!Array.isArray(offsets)) {
1343
+ reply(fail("invalid", "commits needs an offsets array"));
1344
+ return;
1345
+ }
1346
+ let first = {
1347
+ ok: true,
1348
+ value: null
1349
+ };
1350
+ for (const e of offsets) {
1351
+ 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");
1352
+ if (!r.ok && first.ok) first = r;
1353
+ }
1354
+ reply(first);
1355
+ return;
1356
+ }
1357
+ default: {
1358
+ const never = msg;
1359
+ this.#dropped++;
1360
+ return never;
1361
+ }
1362
+ }
1363
+ }
1364
+ #publish(from, name, key, value, req, done, id) {
1365
+ const settle = (r) => {
1366
+ if (!r.ok) this.#rejected[r.error.code] = (this.#rejected[r.error.code] ?? 0) + 1;
1367
+ done(r);
1368
+ };
1369
+ const system = isSystemTopic(name);
1370
+ if (from.kind === "kernel" ? !system : system) {
1371
+ settle(fail("forbidden", `${from.kind} may not publish to ${name}`));
1372
+ return;
1373
+ }
1374
+ if (from.kind === "isolate") {
1375
+ const conn = this.#conns.get(from.isolateId);
1376
+ if (!conn || !matchAny(conn.grants.publish, name)) {
1377
+ settle(fail("forbidden", `no publish grant for ${name}`));
1378
+ return;
1379
+ }
1380
+ }
1381
+ const topic = this.#topics.get(name);
1382
+ if (!topic) {
1383
+ settle(fail("unknown_topic", `unknown topic ${name}`));
1384
+ return;
1385
+ }
1386
+ if (req && !topic.def.reply) {
1387
+ settle(fail("not_requestable", `${name} has no reply schema`));
1388
+ return;
1389
+ }
1390
+ const bytes = estimateSize(value, topic.maxBytes);
1391
+ if (bytes > topic.maxBytes) {
1392
+ settle(fail("too_large", `record is over ${topic.maxBytes} bytes`));
1393
+ return;
1394
+ }
1395
+ const pending = {
1396
+ bytes,
1397
+ producer: from.kind === "isolate" ? from.isolateId : from.kind === "host" ? HOST_PRODUCER : KERNEL_PRODUCER,
1398
+ key,
1399
+ req,
1400
+ ...id ? { id } : {},
1401
+ done: false,
1402
+ result: void 0,
1403
+ settle
1404
+ };
1405
+ this.#enqueue(name, topic, pending, validate(topic.def.schema, value));
1406
+ }
1407
+ /** Appends `pending` once its validation is done and everything ahead of it on the topic is. */
1408
+ #enqueue(name, topic, pending, result) {
1409
+ if (!(result instanceof Promise) && topic.queue.length === 0 && !topic.seeding) {
1410
+ pending.result = result;
1411
+ this.#finish(name, topic, pending);
1412
+ return;
1413
+ }
1414
+ topic.queue.push(pending);
1415
+ Promise.resolve(result).then((r) => {
1416
+ pending.result = r;
1417
+ pending.done = true;
1418
+ this.#drain(name, topic);
1419
+ });
1420
+ }
1421
+ /** Finishes queued publishes in order, stopping at the first still validating. */
1422
+ #drain(name, topic) {
1423
+ if (topic.seeding) return;
1424
+ while (topic.queue[0]?.done) {
1425
+ const next = topic.queue.shift();
1426
+ if (next) this.#finish(name, topic, next);
1427
+ }
1428
+ }
1429
+ #finish(name, topic, p) {
1430
+ if (p.id && this.#engine.durable(name)) {
1431
+ const prior = this.#engine.appended(name, p.producer, p.id);
1432
+ if (prior !== void 0) {
1433
+ if (p.req) this.#openRequest(name, prior, p.req);
1434
+ this.#ackDurable(name, prior, p);
1435
+ return;
1436
+ }
1437
+ }
1438
+ const checked = this.#check(name, p.result, topic.def.durability === "persistent");
1439
+ if (!checked.ok) {
1440
+ p.settle(checked);
1441
+ return;
1442
+ }
1443
+ if (this.#storageFull && this.#engine.durable(name)) {
1444
+ p.settle(fail("quota_exceeded", `${name}: the origin's storage is full`));
1445
+ return;
1446
+ }
1447
+ let rec = {
1448
+ value: checked.value,
1449
+ ts: p.ts ?? this.#now(),
1450
+ producer: p.producer
1451
+ };
1452
+ if (p.key !== void 0) rec = {
1453
+ ...rec,
1454
+ key: p.key
1455
+ };
1456
+ if (p.req) rec = {
1457
+ ...rec,
1458
+ req: {
1459
+ from: p.req.from.isolateId,
1460
+ id: p.req.id
1461
+ }
1462
+ };
1463
+ const offset = this.#engine.append(name, rec, p.id);
1464
+ topic.records++;
1465
+ topic.bytes += p.bytes;
1466
+ if (p.req) this.#openRequest(name, offset, p.req);
1467
+ if (this.#engine.durable(name)) this.#ackDurable(name, offset, p);
1468
+ else p.settle({
1469
+ ok: true,
1470
+ value: { offset }
1471
+ });
1472
+ this.#fanOut(name);
1473
+ this.#wake(name);
1474
+ this.#follow(name, {
1475
+ ...rec,
1476
+ offset
1477
+ });
1478
+ }
1479
+ /**
1480
+ * Turns a schema result into the value to store, or the error to send. A
1481
+ * persistent topic's value must also encode (ADR 0007, consequences).
1482
+ */
1483
+ #check(name, r, persistent = false) {
1484
+ if (!r || "thrown" in r) {
1485
+ const thrown = r ? String(r.thrown) : "no result";
1486
+ return fail("invalid", `schema threw: ${thrown}`, { issues: [{
1487
+ message: thrown,
1488
+ path: []
1489
+ }] });
1490
+ }
1491
+ if (r.issues) return fail("invalid", `invalid value for ${name}`, { issues: toIssues(r.issues) });
1492
+ if (persistent) try {
1493
+ encode(r.value);
1494
+ } catch (e) {
1495
+ if (e instanceof CodecError) return fail("not_encodable", `${name}: ${e.message}`);
1496
+ throw e;
1497
+ }
1498
+ else if (this.#dev) try {
1499
+ structuredClone(r.value);
1500
+ } catch (e) {
1501
+ return fail("not_encodable", `schema output can't be cloned: ${String(e)}`);
1502
+ }
1503
+ return {
1504
+ ok: true,
1505
+ value: r.value
1506
+ };
1507
+ }
1508
+ /** Acknowledged once its batch is on disk (ADR 0007, decision 2). */
1509
+ #ackDurable(name, offset, p) {
1510
+ this.#engine.flush().then(() => p.settle({
1511
+ ok: true,
1512
+ value: { offset }
1513
+ }), (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)}`)));
1514
+ }
1515
+ #openRequest(topic, offset, req) {
1516
+ const key = reqKey(topic, offset);
1517
+ this.#timers.set(() => this.#requests.delete(key), req.timeoutMs);
1518
+ this.#requests.set(key, {
1519
+ caller: req.from,
1520
+ id: req.id,
1521
+ recipients: /* @__PURE__ */ new Set(),
1522
+ done: false
1523
+ });
1524
+ }
1525
+ #reply(conn, name, offset, value, settle) {
1526
+ const topic = this.#topics.get(name);
1527
+ if (!topic) return settle(fail("unknown_topic", `unknown topic ${name}`));
1528
+ const schema = topic.def.reply;
1529
+ if (!schema) return settle(fail("not_requestable", `${name} has no reply schema`));
1530
+ if (!isOffset(offset)) return settle(fail("invalid", "offset must be a non-negative integer"));
1531
+ const req = this.#requests.get(reqKey(name, offset));
1532
+ if (!req) {
1533
+ const rec = this.#engine.read(name, offset, 1)[0];
1534
+ return settle(rec?.offset === offset && rec.req ? fail("timeout", `request ${name}@${offset} has expired`) : fail("invalid", `${name}@${offset} is not a request`));
1535
+ }
1536
+ if (!req.recipients.has(conn.isolateId)) return settle(fail("forbidden", `request ${name}@${offset} was not delivered to you`));
1537
+ if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
1538
+ if (estimateSize(value, topic.maxBytes) > topic.maxBytes) return settle(fail("too_large", `reply is over ${topic.maxBytes} bytes`));
1539
+ const answer = (r) => {
1540
+ if (req.done) return settle(fail("already_replied", `request ${name}@${offset} has an answer`));
1541
+ req.done = true;
1542
+ const checked = this.#check(name, r);
1543
+ const callerAlive = this.#conns.get(req.caller.isolateId) === req.caller;
1544
+ if (!checked.ok) {
1545
+ settle(checked);
1546
+ if (callerAlive) {
1547
+ const issues = checked.error.issues;
1548
+ this.#post(req.caller, req.id, fail("reply_invalid", `invalid reply on ${name}`, issues ? { issues } : {}));
1549
+ }
1550
+ return;
1551
+ }
1552
+ if (callerAlive) this.#post(req.caller, req.id, checked);
1553
+ settle({
1554
+ ok: true,
1555
+ value: { delivered: callerAlive }
1556
+ });
1557
+ };
1558
+ const result = validate(schema, value);
1559
+ if (result instanceof Promise) result.then(answer);
1560
+ else answer(result);
1561
+ }
1562
+ #post(conn, re, r) {
1563
+ conn.port.post({
1564
+ v: 1,
1565
+ t: "result",
1566
+ re,
1567
+ p: r
1568
+ });
1569
+ }
1570
+ #subscribe(conn, name, from, group) {
1571
+ if (!isStartPosition(from)) return fail("invalid", "from must be latest, earliest or committed");
1572
+ if (group !== void 0 && (typeof group !== "string" || group === "")) return fail("invalid", "group must be a non-empty string");
1573
+ if (!isSystemTopic(name) && !matchAny(conn.grants.subscribe, name)) return fail("forbidden", `no subscribe grant for ${name}`);
1574
+ if (!this.#topics.has(name)) return fail("unknown_topic", `unknown topic ${name}`);
1575
+ if (conn.reset && !conn.reset.has(name) && !this.#durable(name)) {
1576
+ conn.reset.add(name);
1577
+ conn.port.post({
1578
+ v: 1,
1579
+ t: "reset",
1580
+ p: {
1581
+ topic: name,
1582
+ reason: "bus_restart"
1583
+ }
1584
+ });
1585
+ }
1586
+ const consumer = group === void 0 ? conn.isolateId : `group:${group}`;
1587
+ const start = conn.reset && this.#durable(name) && this.#committed(name, consumer) !== void 0 ? "committed" : from;
1588
+ const old = conn.subs.get(name);
1589
+ if (old) this.#leave(old);
1590
+ const sub = {
1591
+ conn,
1592
+ topic: name,
1593
+ group: void 0,
1594
+ cursor: 0,
1595
+ credit: this.#inboxLimit,
1596
+ unacked: [],
1597
+ seq: 0,
1598
+ scheduled: false
1599
+ };
1600
+ conn.subs.set(name, sub);
1601
+ if (group === void 0) {
1602
+ sub.cursor = this.#start(name, conn.isolateId, start);
1603
+ this.#schedule(sub);
1604
+ return {
1605
+ ok: true,
1606
+ value: { from: sub.cursor }
1607
+ };
1608
+ }
1609
+ return {
1610
+ ok: true,
1611
+ value: {
1612
+ from: this.#join(sub, group, start).cursor,
1613
+ group
1614
+ }
1615
+ };
1616
+ }
1617
+ /**
1618
+ * Adds a member to a group. A group with no members starts after its
1619
+ * committed offset when it has one, whatever `from` says, and at `from`
1620
+ * only before its first commit (ADR 0016, point 14). A member joining a
1621
+ * group that has members takes records from where the group is.
1622
+ */
1623
+ #join(sub, name, from) {
1624
+ const id = `${sub.topic}\u0000${name}`;
1625
+ let g = this.#groups.get(id);
1626
+ if (!g) {
1627
+ const consumer = `group:${name}`;
1628
+ const committed = this.#committed(sub.topic, consumer) !== void 0;
1629
+ g = {
1630
+ topic: sub.topic,
1631
+ name,
1632
+ consumer,
1633
+ cursor: this.#start(sub.topic, consumer, committed ? "committed" : from),
1634
+ members: [],
1635
+ rr: 0,
1636
+ unacked: [],
1637
+ redeliver: [],
1638
+ scheduled: false
1639
+ };
1640
+ this.#groups.set(id, g);
1641
+ }
1642
+ sub.group = g;
1643
+ g.members.push(sub);
1644
+ g.members.sort((a, b) => a.conn.isolateId < b.conn.isolateId ? -1 : 1);
1645
+ this.#scheduleGroup(g);
1646
+ return g;
1647
+ }
1648
+ /** Ends a subscription. A group member's uncommitted records go to the others. */
1649
+ #leave(sub) {
1650
+ const g = sub.group;
1651
+ if (!g) return;
1652
+ sub.group = void 0;
1653
+ g.members = g.members.filter((m) => m !== sub);
1654
+ if (g.members.length === 0) {
1655
+ this.#groups.delete(`${g.topic}\u0000${g.name}`);
1656
+ return;
1657
+ }
1658
+ for (const u of g.unacked) if (u.member === sub) {
1659
+ u.member = void 0;
1660
+ g.redeliver.push(u.offset);
1661
+ }
1662
+ g.redeliver.sort((a, b) => a - b);
1663
+ this.#scheduleGroup(g);
1664
+ }
1665
+ /** `latest` → head, `earliest` → tail, `committed` → committed + 1, else earliest. */
1666
+ #start(name, consumer, from) {
1667
+ if (from === "latest") return this.#engine.head(name);
1668
+ if (from === "committed") {
1669
+ const c = this.#committed(name, consumer);
1670
+ if (c !== void 0) return c + 1;
1671
+ }
1672
+ return this.#engine.tail(name);
1673
+ }
1674
+ #committed(name, consumer) {
1675
+ if (this.#forgotten.has(`${name}\u0000${consumer}`)) return void 0;
1676
+ return this.#engine.committed(name, consumer);
1677
+ }
1678
+ /**
1679
+ * A commit covers the records delivered up to `offset`. In a group it also
1680
+ * needs their delivery's `seq` at or below `seq`: a record redelivered to
1681
+ * this member after the deliveries the commit settled has a higher one,
1682
+ * whatever its offset (ADR 0016, point 12). An own subscription's
1683
+ * deliveries are in order, so the offset alone decides there.
1684
+ */
1685
+ #commit(conn, name, offset, seq) {
1686
+ const sub = conn.subs.get(name);
1687
+ if (!sub) return fail("forbidden", `not subscribed to ${name}`);
1688
+ if (!isOffset(offset)) return fail("invalid", "offset must be a non-negative integer");
1689
+ if (!isSeq(seq)) return fail("invalid", "seq must be a non-negative integer");
1690
+ if (offset >= this.#engine.head(name)) return fail("invalid", `offset ${offset} is not in ${name} yet`);
1691
+ const g = sub.group;
1692
+ const covers = (d) => d.offset <= offset && (!g || d.seq <= seq);
1693
+ const before = sub.unacked.length;
1694
+ if (g) sub.unacked = sub.unacked.filter((d) => !covers(d));
1695
+ else while (sub.unacked[0] && covers(sub.unacked[0])) sub.unacked.shift();
1696
+ const freed = before - sub.unacked.length;
1697
+ sub.credit += freed;
1698
+ if (g) {
1699
+ g.unacked = g.unacked.filter((u) => !(u.member === sub && covers(u)));
1700
+ const upTo = (g.unacked[0]?.offset ?? g.cursor) - 1;
1701
+ if (upTo > (this.#engine.committed(name, g.consumer) ?? -1)) this.#engine.commit(name, g.consumer, upTo);
1702
+ if (freed > 0) this.#scheduleGroup(g);
1703
+ } else {
1704
+ this.#forgotten.delete(`${name}\u0000${conn.isolateId}`);
1705
+ this.#engine.commit(name, conn.isolateId, offset);
1706
+ if (freed > 0) this.#schedule(sub);
1707
+ }
1708
+ return {
1709
+ ok: true,
1710
+ value: null
1711
+ };
1712
+ }
1713
+ #fanOut(name) {
1714
+ for (const conn of this.#conns.values()) {
1715
+ const sub = conn.subs.get(name);
1716
+ if (!sub) continue;
1717
+ if (sub.group) this.#scheduleGroup(sub.group);
1718
+ else this.#schedule(sub);
1719
+ }
1720
+ }
1721
+ /**
1722
+ * Queues one pump per subscription per microtask, so records published in
1723
+ * the same task go out together.
1724
+ */
1725
+ #schedule(sub) {
1726
+ if (sub.scheduled) return;
1727
+ sub.scheduled = true;
1728
+ queueMicrotask(() => {
1729
+ sub.scheduled = false;
1730
+ if (this.#conns.get(sub.conn.isolateId) === sub.conn && sub.conn.subs.get(sub.topic) === sub) this.#pump(sub);
1731
+ });
1732
+ }
1733
+ /**
1734
+ * Reads evicted records back from disk (M2b task 11), then calls `then`
1735
+ * to pump again. A page that fails is retried by the next pump: the next
1736
+ * publish or commit.
1737
+ */
1738
+ #pageIn(topic, offset, then) {
1739
+ this.#engine.page(topic, offset).then(then, (e) => {
1740
+ console.warn(`[isoloop] reading ${topic}@${offset} back from disk failed`, e);
1741
+ });
1742
+ }
1743
+ #scheduleGroup(g) {
1744
+ if (g.scheduled) return;
1745
+ g.scheduled = true;
1746
+ queueMicrotask(() => {
1747
+ g.scheduled = false;
1748
+ if (this.#groups.get(`${g.topic}\u0000${g.name}`) === g) this.#pumpGroup(g);
1749
+ });
1750
+ }
1751
+ /** Expired records between the cursor and the tail, as a gap. Compaction is not a gap. */
1752
+ #gap(topic, cursor) {
1753
+ const tail = this.#engine.tail(topic);
1754
+ if (cursor >= tail) return void 0;
1755
+ if (this.#topics.get(topic)?.def.retention.kind === "compacted") return void 0;
1756
+ return {
1757
+ from: cursor,
1758
+ to: tail - 1
1759
+ };
1760
+ }
1761
+ /** Sends one `deliver`, numbered with the subscription's next `seq`, and returns it. */
1762
+ #deliver(sub, records, gap) {
1763
+ const seq = ++sub.seq;
1764
+ for (const r of records) {
1765
+ sub.unacked.push({
1766
+ offset: r.offset,
1767
+ seq
1768
+ });
1769
+ if (r.req) this.#requests.get(reqKey(sub.topic, r.offset))?.recipients.add(sub.conn.isolateId);
1770
+ }
1771
+ sub.credit -= records.length;
1772
+ sub.conn.port.post({
1773
+ v: 1,
1774
+ t: "deliver",
1775
+ p: gap ? {
1776
+ topic: sub.topic,
1777
+ records,
1778
+ gap,
1779
+ seq
1780
+ } : {
1781
+ topic: sub.topic,
1782
+ records,
1783
+ seq
1784
+ }
1785
+ });
1786
+ return seq;
1787
+ }
1788
+ /**
1789
+ * Delivers from the cursor while there is credit, in batches. At 0 credit
1790
+ * the subscription is paused: nothing is queued, only the cursor is kept,
1791
+ * and a commit resumes it from the log. Records that expired meanwhile are
1792
+ * reported as `gap`.
1793
+ */
1794
+ #pump(sub) {
1795
+ if (sub.credit <= 0) return;
1796
+ let gap = this.#gap(sub.topic, sub.cursor);
1797
+ if (gap) sub.cursor = gap.to + 1;
1798
+ const head = this.#engine.head(sub.topic);
1799
+ while (sub.credit > 0 && sub.cursor < head) {
1800
+ if (!this.#engine.readable(sub.topic, sub.cursor)) {
1801
+ this.#pageIn(sub.topic, sub.cursor, () => this.#schedule(sub));
1802
+ break;
1803
+ }
1804
+ const records = this.#engine.read(sub.topic, sub.cursor, Math.min(this.#batch, sub.credit));
1805
+ const last = records.at(-1);
1806
+ if (!last) {
1807
+ sub.cursor = head;
1808
+ break;
1809
+ }
1810
+ sub.cursor = last.offset + 1;
1811
+ this.#deliver(sub, records, gap);
1812
+ gap = void 0;
1813
+ }
1814
+ if (gap) this.#deliver(sub, [], gap);
1815
+ }
1816
+ /** The member a record goes to: by key hash, or round-robin when keyless. */
1817
+ #owner(g, rec) {
1818
+ const n = g.members.length;
1819
+ return g.members[rec.key === void 0 ? g.rr % n : hash(rec.key) % n];
1820
+ }
1821
+ /**
1822
+ * Hands records to group members: first those a departed member left
1823
+ * uncommitted, then new ones from the group cursor. If a record's member is
1824
+ * out of credit the group waits for it, which keeps per-key order.
1825
+ */
1826
+ #pumpGroup(g) {
1827
+ if (g.members.length === 0) return;
1828
+ const batches = /* @__PURE__ */ new Map();
1829
+ const flush = (m) => {
1830
+ const b = batches.get(m);
1831
+ batches.delete(m);
1832
+ if (!b || b.records.length === 0) return;
1833
+ const seq = this.#deliver(m, b.records);
1834
+ for (const e of b.entries) e.seq = seq;
1835
+ };
1836
+ /** Credit left once the records batched for it go out. */
1837
+ const room = (m) => m ? m.credit - (batches.get(m)?.records.length ?? 0) : 0;
1838
+ const give = (m, rec, entry) => {
1839
+ const b = batches.get(m) ?? {
1840
+ records: [],
1841
+ entries: []
1842
+ };
1843
+ b.records.push(rec);
1844
+ if (entry) b.entries.push(entry);
1845
+ batches.set(m, b);
1846
+ if (rec.key === void 0) g.rr++;
1847
+ if (b.records.length >= this.#batch) flush(m);
1848
+ };
1849
+ const gap = this.#gap(g.topic, g.cursor);
1850
+ if (gap) {
1851
+ g.cursor = gap.to + 1;
1852
+ for (const m of g.members) this.#deliver(m, [], gap);
1853
+ }
1854
+ const tail = this.#engine.tail(g.topic);
1855
+ let blocked = false;
1856
+ while (g.redeliver.length > 0) {
1857
+ const offset = g.redeliver[0] ?? 0;
1858
+ if (offset >= tail && !this.#engine.readable(g.topic, offset)) {
1859
+ this.#pageIn(g.topic, offset, () => this.#scheduleGroup(g));
1860
+ blocked = true;
1861
+ break;
1862
+ }
1863
+ const rec = offset >= tail ? this.#engine.read(g.topic, offset, 1)[0] : void 0;
1864
+ if (rec?.offset !== offset) {
1865
+ g.redeliver.shift();
1866
+ g.unacked = g.unacked.filter((u) => u.offset !== offset);
1867
+ continue;
1868
+ }
1869
+ const m = this.#owner(g, rec);
1870
+ if (!m || room(m) <= 0) {
1871
+ blocked = true;
1872
+ break;
1873
+ }
1874
+ g.redeliver.shift();
1875
+ const entry = g.unacked.find((u) => u.offset === offset);
1876
+ if (entry) entry.member = m;
1877
+ give(m, rec, entry);
1878
+ }
1879
+ const head = this.#engine.head(g.topic);
1880
+ let more = !blocked;
1881
+ while (more && g.cursor < head) {
1882
+ if (!this.#engine.readable(g.topic, g.cursor)) {
1883
+ this.#pageIn(g.topic, g.cursor, () => this.#scheduleGroup(g));
1884
+ break;
1885
+ }
1886
+ const records = this.#engine.read(g.topic, g.cursor, this.#batch);
1887
+ if (records.length === 0) {
1888
+ g.cursor = head;
1889
+ break;
1890
+ }
1891
+ for (const rec of records) {
1892
+ const m = this.#owner(g, rec);
1893
+ if (!m || room(m) <= 0) {
1894
+ more = false;
1895
+ break;
1896
+ }
1897
+ const entry = {
1898
+ offset: rec.offset,
1899
+ member: m,
1900
+ seq: 0
1901
+ };
1902
+ g.unacked.push(entry);
1903
+ give(m, rec, entry);
1904
+ g.cursor = rec.offset + 1;
1905
+ }
1906
+ }
1907
+ for (const m of batches.keys()) flush(m);
1908
+ }
1909
+ };
1910
+ /** Runs a Standard Schema, turning a throw or a rejection into a result. */
1911
+ function validate(schema, value) {
1912
+ let r;
1913
+ try {
1914
+ r = schema["~standard"].validate(value);
1915
+ } catch (thrown) {
1916
+ return { thrown };
1917
+ }
1918
+ if (!(r instanceof Promise)) return r;
1919
+ return r.then((x) => x, (thrown) => ({ thrown }));
1920
+ }
1921
+ export { Broker, ContractsError, DEFAULT_MAX_RECORD_BYTES, DEFAULT_REQUEST_TIMEOUT_MS, HOST_PRODUCER, KERNEL_PRODUCER, MemoryStorage, TsEngine, contracts, effectiveDurability, estimateSize, isContracts, isUnchecked, publishId, toIssues, topic, topicConfig, unchecked };