@isoloop/bus 0.1.0-next.10 → 0.1.0-next.11

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