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