@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.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.
Files changed (55) hide show
  1. package/AGENTS.md +4 -3
  2. package/dist/index.d.ts +170 -9
  3. package/dist/index.js +5398 -2968
  4. package/dist/rows-worker.d.ts +1 -0
  5. package/dist/rows-worker.js +2731 -0
  6. package/dist/sqlite-open.js +1 -1
  7. package/dist/sqlite-worker.js +1 -1
  8. package/dist/types.d.ts +131 -13
  9. package/package.json +9 -4
  10. package/scripts/check-worker-entries.mjs +15 -2
  11. package/skills/sp00ky-core/SKILL.md +2 -0
  12. package/src/client/bucket-handle.ts +21 -1
  13. package/src/client/eager-paint.test.ts +82 -0
  14. package/src/client/services.ts +4 -1
  15. package/src/client/sp00ky-client.test.ts +143 -1
  16. package/src/client/sp00ky-client.ts +158 -19
  17. package/src/index.ts +9 -0
  18. package/src/kernel/effects.ts +12 -2
  19. package/src/kernel/interpreter.test.ts +17 -0
  20. package/src/kernel/interpreter.ts +5 -2
  21. package/src/modules/channel/hub.test.ts +223 -0
  22. package/src/modules/channel/hub.ts +355 -0
  23. package/src/modules/channel/index.ts +358 -14
  24. package/src/modules/channel/room.test.ts +340 -0
  25. package/src/modules/channel/room.ts +367 -0
  26. package/src/modules/channel/rooms.fixture.ts +383 -0
  27. package/src/modules/channel/share.test.ts +535 -0
  28. package/src/modules/channel/webrtc.ts +2 -2
  29. package/src/modules/devtools/storage-info.ts +4 -3
  30. package/src/query/materialize.saga.test.ts +16 -0
  31. package/src/query/materialize.saga.ts +7 -26
  32. package/src/query/materialize.ts +79 -3
  33. package/src/query/register.saga.test.ts +61 -0
  34. package/src/query/register.saga.ts +39 -2
  35. package/src/services/database/cache-engine.ts +17 -3
  36. package/src/services/database/engine-factory.ts +7 -0
  37. package/src/services/database/index.ts +1 -0
  38. package/src/services/database/rows-cache-engine.test.ts +1584 -0
  39. package/src/services/database/rows-cache-engine.ts +1203 -0
  40. package/src/services/database/rows-exec.integration.test.ts +589 -0
  41. package/src/services/database/rows-exec.ts +1027 -0
  42. package/src/services/database/rows-prewarm.ts +251 -0
  43. package/src/services/database/rows-store.test.ts +635 -0
  44. package/src/services/database/rows-store.ts +1208 -0
  45. package/src/services/database/rows-transport.fixture.ts +151 -0
  46. package/src/services/database/rows-worker.ts +607 -0
  47. package/src/services/database/rows-yield.test.ts +141 -0
  48. package/src/services/database/rows-yield.ts +92 -0
  49. package/src/services/database/sqlite-cache-engine.test.ts +22 -1
  50. package/src/services/database/sqlite-cache-engine.ts +55 -34
  51. package/src/services/database/sqlite-transport.ts +7 -5
  52. package/src/services/tabs/support.ts +6 -4
  53. package/src/types.ts +41 -6
  54. package/tsdown.config.ts +42 -1
  55. package/vitest.config.ts +4 -0
@@ -0,0 +1,1208 @@
1
+ /**
2
+ * The row store: sp00ky's own storage engine for the local cache.
3
+ *
4
+ * One append-only file per bucket, read and written through a synchronous
5
+ * random-access handle (an OPFS `FileSystemSyncAccessHandle` in a worker, a
6
+ * byte array in tests and in memory mode). It stores what the client keeps,
7
+ * rows addressed by `(table, id)` with a version, and nothing a general
8
+ * database needs beyond that: no SQL, no pages, no B-tree.
9
+ *
10
+ * # Layout
11
+ *
12
+ * ```text
13
+ * 0 superblock slot 0 two slots written alternately; the valid one
14
+ * 256 superblock slot 1 with the higher seq wins, so a torn write of
15
+ * one never loses the other
16
+ * 4096 extents [u32 type][u32 len][u32 hash][u32 0] payload,
17
+ * padded to 8 bytes
18
+ * ```
19
+ *
20
+ * Three kinds of extent:
21
+ * - a **batch**: the records of one atomic write. A batch counts only when it
22
+ * lies whole inside the file and its hash matches, which is what makes a
23
+ * multi-row write all-or-nothing without a journal;
24
+ * - a **table block**: one table's index, sorted by id, as flat typed arrays;
25
+ * - a **directory**: where every table's block lies.
26
+ *
27
+ * The superblock names the latest directory and the offset it covers. Opening
28
+ * the store reads the superblock and the directory, then replays the batches
29
+ * written after that offset: the cost follows the writes since the last
30
+ * checkpoint, never the size of the store. A table's block is read on first
31
+ * touch, in one read, and used in place: its arrays are views on the bytes,
32
+ * so nothing is parsed per row.
33
+ *
34
+ * # Index
35
+ *
36
+ * Per table, an immutable sorted run plus a map of the writes since it was
37
+ * built. A point read checks the map, then binary-searches the run. Ordered
38
+ * reads fold the map into a new run first. A checkpoint appends the folded
39
+ * runs and a directory and flips the superblock.
40
+ *
41
+ * # Bodies
42
+ *
43
+ * A body is opaque bytes to this module. The client stores JSON text, because
44
+ * the engine's native parser outruns any decoder written in JavaScript; see
45
+ * `rows-exec.ts`.
46
+ *
47
+ * # Trust
48
+ *
49
+ * The log is the truth and the index is a cache of it: a missing, torn or
50
+ * mismatching index is rebuilt by scanning the log. A torn tail is cut off at
51
+ * the last whole batch. Space freed by updates and deletes comes back through
52
+ * {@link RowStore.compact}, which copies the live rows into the second file
53
+ * and switches over with one superblock write.
54
+ */
55
+
56
+ /** Synchronous random-access file. */
57
+ export interface SyncFile {
58
+ read(buffer: Uint8Array, at: number): number;
59
+ write(buffer: Uint8Array, at: number): number;
60
+ size(): number;
61
+ truncate(size: number): void;
62
+ flush(): void;
63
+ close(): void;
64
+ }
65
+
66
+ /** Opens the store's two files by name. `b` is only asked for when needed. */
67
+ export interface StoreIo {
68
+ open(name: 'a' | 'b'): Promise<SyncFile> | SyncFile;
69
+ }
70
+
71
+ /** Where one row's body lies, and what the index knows without reading it. */
72
+ export interface Entry {
73
+ off: number;
74
+ len: number;
75
+ rv: number;
76
+ flags: number;
77
+ }
78
+
79
+ export type StoreOp =
80
+ | { t: 'put'; table: string; id: string; rv: number; flags: number; body: Uint8Array }
81
+ | { t: 'del'; table: string; id: string }
82
+ | { t: 'clear'; table: string };
83
+
84
+ /** A table's rows in id order: parallel arrays, plus the ids as one heap. */
85
+ export interface Run {
86
+ n: number;
87
+ off: Float64Array;
88
+ rv: Float64Array;
89
+ len: Uint32Array;
90
+ idEnd: Uint32Array;
91
+ flags: Uint8Array;
92
+ heap: Uint8Array;
93
+ /** The bytes the arrays are views on; what a checkpoint writes. */
94
+ buf: Uint8Array;
95
+ /** Sum of the body lengths. */
96
+ live: number;
97
+ /** Row positions ordered by file offset, built on first scan. */
98
+ byOff?: Uint32Array;
99
+ }
100
+
101
+ export interface StoreStats {
102
+ file: 'a' | 'b';
103
+ fileBytes: number;
104
+ liveBytes: number;
105
+ indexBytes: number;
106
+ garbageBytes: number;
107
+ tailBytes: number;
108
+ /** Records the next open would replay. */
109
+ tailOps: number;
110
+ tables: number;
111
+ rebuilt: boolean;
112
+ }
113
+
114
+ /** The OPFS directory that holds a bucket's two files. */
115
+ export const bucketDirName = (bucketId: string): string =>
116
+ `sp00ky-rows-${bucketId.replace(/[^A-Za-z0-9_.-]/g, '_')}`;
117
+
118
+ /** Body holds `{"__u8": base64}` tags the reader has to turn back into bytes. */
119
+ export const FLAG_U8 = 1;
120
+ /** Body is raw bytes, not JSON. */
121
+ export const FLAG_RAW = 2;
122
+
123
+ const MAGIC = 0x524b5053; // "SPKR"
124
+ const VERSION = 1;
125
+ const SB_SIZE = 256;
126
+ const SB_USED = 64;
127
+ const HEADER_END = 4096;
128
+ const XH = 16;
129
+ /** How much of the tail a replay reads at once. */
130
+ const REPLAY_CHUNK = 1 << 20;
131
+ const X_BATCH = 1;
132
+ const X_BLOCK = 2;
133
+ const X_DIR = 3;
134
+ const R_PUT = 1;
135
+ const R_DEL = 2;
136
+ const R_CLEAR = 3;
137
+ const R_TABLE = 4;
138
+ const ACTIVE = 1;
139
+ const MOVED = 2;
140
+ /** Bytes per row in a block, besides its id. */
141
+ const ROW_BYTES = 25;
142
+ /** Bytes a put record adds around its id and body. */
143
+ const RECORD_BYTES = 18;
144
+ const MAX_ID_BYTES = 0xffff;
145
+ const COMPACT_CHUNK = 4 << 20;
146
+ /** A batch buffer larger than this is dropped after the write instead of kept. */
147
+ const SCRATCH_KEEP = 8 << 20;
148
+
149
+ const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
150
+ const encoder = new TextEncoder();
151
+ const decoder = new TextDecoder();
152
+ const align8 = (n: number): number => (n + 7) & ~7;
153
+
154
+ /**
155
+ * 32-bit hash of a byte range. Not cryptographic: it tells a whole write from
156
+ * a torn one. Reads a word at a time where the bytes allow it.
157
+ */
158
+ export function hash32(buf: Uint8Array, start = 0, end = buf.length): number {
159
+ let h = (0x9e3779b1 ^ (end - start)) | 0;
160
+ let i = start;
161
+ const words = (end - start) >>> 2;
162
+ if (LITTLE_ENDIAN && ((buf.byteOffset + start) & 3) === 0) {
163
+ const w = new Uint32Array(buf.buffer, buf.byteOffset + start, words);
164
+ for (let k = 0; k < words; k++) {
165
+ h = Math.imul(h ^ w[k], 0x85ebca6b);
166
+ h = (h << 13) | (h >>> 19);
167
+ }
168
+ i = start + words * 4;
169
+ } else {
170
+ for (const stop = start + words * 4; i < stop; i += 4) {
171
+ const x = buf[i] | (buf[i + 1] << 8) | (buf[i + 2] << 16) | (buf[i + 3] << 24);
172
+ h = Math.imul(h ^ x, 0x85ebca6b);
173
+ h = (h << 13) | (h >>> 19);
174
+ }
175
+ }
176
+ for (; i < end; i++) {
177
+ h = Math.imul(h ^ buf[i], 0xc2b2ae35);
178
+ h = (h << 7) | (h >>> 25);
179
+ }
180
+ h ^= h >>> 16;
181
+ h = Math.imul(h, 0x85ebca6b);
182
+ h ^= h >>> 13;
183
+ h = Math.imul(h, 0xc2b2ae35);
184
+ h ^= h >>> 16;
185
+ return h >>> 0;
186
+ }
187
+
188
+ /** Order of two byte ranges, as `memcmp` then length. */
189
+ function cmpBytes(
190
+ a: Uint8Array,
191
+ aStart: number,
192
+ aEnd: number,
193
+ b: Uint8Array,
194
+ bStart: number,
195
+ bEnd: number
196
+ ): number {
197
+ const n = Math.min(aEnd - aStart, bEnd - bStart);
198
+ for (let i = 0; i < n; i++) {
199
+ const d = a[aStart + i] - b[bStart + i];
200
+ if (d !== 0) return d;
201
+ }
202
+ return aEnd - aStart - (bEnd - bStart);
203
+ }
204
+
205
+ /**
206
+ * Order of two strings by code point, which is the order of their UTF-8
207
+ * bytes. JavaScript's own comparison is by UTF-16 unit and puts a surrogate
208
+ * pair below U+E000, where UTF-8 puts it above.
209
+ */
210
+ export function cmpText(a: string, b: string): number {
211
+ if (a === b) return 0;
212
+ const n = Math.min(a.length, b.length);
213
+ for (let i = 0; i < n; i++) {
214
+ let x = a.charCodeAt(i);
215
+ let y = b.charCodeAt(i);
216
+ if (x === y) continue;
217
+ if (x >= 0xd800 && y >= 0xd800) {
218
+ x = x >= 0xe000 ? x - 0x800 : x + 0x2000;
219
+ y = y >= 0xe000 ? y - 0x800 : y + 0x2000;
220
+ }
221
+ return x - y;
222
+ }
223
+ return a.length - b.length;
224
+ }
225
+
226
+ // oxlint-disable-next-line no-control-regex
227
+ const NON_ASCII = /[^\x00-\x7f]/;
228
+
229
+ function emptyRun(): Run {
230
+ return runFromBuffer(new Uint8Array(0), 0, 0, 0);
231
+ }
232
+
233
+ function runFromBuffer(buf: Uint8Array, n: number, heapLen: number, live: number): Run {
234
+ const b = buf.buffer;
235
+ const o = buf.byteOffset;
236
+ return {
237
+ n,
238
+ off: new Float64Array(b, o, n),
239
+ rv: new Float64Array(b, o + 8 * n, n),
240
+ len: new Uint32Array(b, o + 16 * n, n),
241
+ idEnd: new Uint32Array(b, o + 20 * n, n),
242
+ flags: new Uint8Array(b, o + 24 * n, n),
243
+ heap: new Uint8Array(b, o + ROW_BYTES * n, heapLen),
244
+ buf,
245
+ live,
246
+ };
247
+ }
248
+
249
+ const idStart = (run: Run, i: number): number => (i === 0 ? 0 : run.idEnd[i - 1]);
250
+
251
+ /** The id of row `i` of a run. */
252
+ export function runId(run: Run, i: number): string {
253
+ return decoder.decode(run.heap.subarray(idStart(run, i), run.idEnd[i]));
254
+ }
255
+
256
+ let probe = new Uint8Array(256);
257
+
258
+ /** UTF-8 of `id` in the shared probe buffer; returns its length. */
259
+ function encodeProbe(id: string): number {
260
+ if (probe.length < id.length * 3) probe = new Uint8Array(id.length * 3);
261
+ return encoder.encodeInto(id, probe).written;
262
+ }
263
+
264
+ function runFind(run: Run, id: string): number {
265
+ if (run.n === 0) return -1;
266
+ const len = encodeProbe(id);
267
+ let lo = 0;
268
+ let hi = run.n - 1;
269
+ while (lo <= hi) {
270
+ const mid = (lo + hi) >>> 1;
271
+ const c = cmpBytes(run.heap, idStart(run, mid), run.idEnd[mid], probe, 0, len);
272
+ if (c === 0) return mid;
273
+ if (c < 0) lo = mid + 1;
274
+ else hi = mid - 1;
275
+ }
276
+ return -1;
277
+ }
278
+
279
+ /** First row of `run`, at or after `from`, whose id is not below `key`. */
280
+ function lowerBound(run: Run, from: number, key: Uint8Array, keyLen: number): number {
281
+ let lo = from;
282
+ let hi = run.n;
283
+ while (lo < hi) {
284
+ const mid = (lo + hi) >>> 1;
285
+ if (cmpBytes(run.heap, idStart(run, mid), run.idEnd[mid], key, 0, keyLen) < 0) lo = mid + 1;
286
+ else hi = mid;
287
+ }
288
+ return lo;
289
+ }
290
+
291
+ /**
292
+ * `base` with `delta` applied: overrides replace, `null` removes. The rows
293
+ * between two changed ids are copied as one block, so folding a handful of
294
+ * writes into a large table costs a few searches and a memcpy, not a walk.
295
+ */
296
+ function mergeRun(base: Run, delta: Map<string, Entry | null>): Run {
297
+ const keys = [...delta.keys()];
298
+ let ascii = true;
299
+ let chars = 0;
300
+ for (const k of keys) {
301
+ chars += k.length;
302
+ if (ascii && NON_ASCII.test(k)) ascii = false;
303
+ }
304
+ if (ascii) keys.sort();
305
+ else keys.sort(cmpText);
306
+
307
+ const upper = base.n + keys.length;
308
+ const off = new Float64Array(upper);
309
+ const rv = new Float64Array(upper);
310
+ const len = new Uint32Array(upper);
311
+ const idEnd = new Uint32Array(upper);
312
+ const flags = new Uint8Array(upper);
313
+ const heap = new Uint8Array(base.heap.length + chars * 3);
314
+ let n = 0;
315
+ let h = 0;
316
+ let live = base.live;
317
+ let i = 0;
318
+ /** Copy base rows `[i, to)` to the output. */
319
+ const copy = (to: number): void => {
320
+ if (to <= i) return;
321
+ const count = to - i;
322
+ const s = idStart(base, i);
323
+ const e = base.idEnd[to - 1];
324
+ off.set(base.off.subarray(i, to), n);
325
+ rv.set(base.rv.subarray(i, to), n);
326
+ len.set(base.len.subarray(i, to), n);
327
+ flags.set(base.flags.subarray(i, to), n);
328
+ heap.set(base.heap.subarray(s, e), h);
329
+ const shift = h - s;
330
+ for (let k = 0; k < count; k++) idEnd[n + k] = base.idEnd[i + k] + shift;
331
+ n += count;
332
+ h += e - s;
333
+ i = to;
334
+ };
335
+ for (const key of keys) {
336
+ const keyLen = encodeProbe(key);
337
+ copy(lowerBound(base, i, probe, keyLen));
338
+ if (i < base.n && cmpBytes(base.heap, idStart(base, i), base.idEnd[i], probe, 0, keyLen) === 0) {
339
+ live -= base.len[i];
340
+ i++;
341
+ }
342
+ const entry = delta.get(key);
343
+ if (!entry) continue;
344
+ heap.set(probe.subarray(0, keyLen), h);
345
+ h += keyLen;
346
+ off[n] = entry.off;
347
+ rv[n] = entry.rv;
348
+ len[n] = entry.len;
349
+ flags[n] = entry.flags;
350
+ idEnd[n] = h;
351
+ live += entry.len;
352
+ n++;
353
+ }
354
+ copy(base.n);
355
+
356
+ const buf = new Uint8Array(new ArrayBuffer(ROW_BYTES * n + h));
357
+ const run = runFromBuffer(buf, n, h, live);
358
+ run.off.set(off.subarray(0, n));
359
+ run.rv.set(rv.subarray(0, n));
360
+ run.len.set(len.subarray(0, n));
361
+ run.idEnd.set(idEnd.subarray(0, n));
362
+ run.flags.set(flags.subarray(0, n));
363
+ run.heap.set(heap.subarray(0, h));
364
+ return run;
365
+ }
366
+
367
+ interface Block {
368
+ off: number;
369
+ len: number;
370
+ n: number;
371
+ heap: number;
372
+ sum: number;
373
+ live: number;
374
+ }
375
+
376
+ interface Table {
377
+ name: string;
378
+ tid: number;
379
+ /** The persisted run, when there is one. */
380
+ block: Block | null;
381
+ /** The loaded run; `null` until the table is first read. */
382
+ run: Run | null;
383
+ /** Writes since `run` was built. */
384
+ delta: Map<string, Entry | null>;
385
+ /** `run` is newer than `block`. */
386
+ unsaved: boolean;
387
+ }
388
+
389
+ interface Superblock {
390
+ seq: number;
391
+ state: number;
392
+ dirOff: number;
393
+ dirLen: number;
394
+ dirSum: number;
395
+ covered: number;
396
+ gen: number;
397
+ }
398
+
399
+ function readSuperblock(file: SyncFile): Superblock | null {
400
+ if (file.size() < SB_SIZE) return null;
401
+ const buf = new Uint8Array(SB_SIZE * 2);
402
+ file.read(buf, 0);
403
+ let best: Superblock | null = null;
404
+ for (let slot = 0; slot < 2; slot++) {
405
+ const view = new DataView(buf.buffer, slot * SB_SIZE, SB_USED);
406
+ if (view.getUint32(0, true) !== MAGIC || view.getUint32(4, true) !== VERSION) continue;
407
+ if (view.getUint32(60, true) !== hash32(buf, slot * SB_SIZE, slot * SB_SIZE + 60)) continue;
408
+ // Index blocks are raw typed arrays: only the byte order they were written in reads them.
409
+ if ((view.getUint32(20, true) === 1) !== LITTLE_ENDIAN) continue;
410
+ const sb: Superblock = {
411
+ seq: view.getFloat64(8, true),
412
+ state: view.getUint32(16, true),
413
+ dirOff: view.getFloat64(24, true),
414
+ dirLen: view.getUint32(32, true),
415
+ dirSum: view.getUint32(36, true),
416
+ covered: view.getFloat64(40, true),
417
+ gen: view.getFloat64(48, true),
418
+ };
419
+ if (!best || sb.seq > best.seq) best = sb;
420
+ }
421
+ return best;
422
+ }
423
+
424
+ function writeSuperblock(file: SyncFile, sb: Superblock): void {
425
+ const buf = new Uint8Array(SB_SIZE);
426
+ const view = new DataView(buf.buffer);
427
+ view.setUint32(0, MAGIC, true);
428
+ view.setUint32(4, VERSION, true);
429
+ view.setFloat64(8, sb.seq, true);
430
+ view.setUint32(16, sb.state, true);
431
+ view.setUint32(20, LITTLE_ENDIAN ? 1 : 0, true);
432
+ view.setFloat64(24, sb.dirOff, true);
433
+ view.setUint32(32, sb.dirLen, true);
434
+ view.setUint32(36, sb.dirSum, true);
435
+ view.setFloat64(40, sb.covered, true);
436
+ view.setFloat64(48, sb.gen, true);
437
+ view.setUint32(60, hash32(buf, 0, 60), true);
438
+ file.write(buf, (sb.seq % 2) * SB_SIZE);
439
+ }
440
+
441
+ const EMPTY_SUPERBLOCK: Superblock = { seq: 0, state: ACTIVE, dirOff: 0, dirLen: 0, dirSum: 0, covered: HEADER_END, gen: 0 };
442
+
443
+ /** An index block whose bytes are not the ones a checkpoint wrote. */
444
+ class IndexMismatch extends Error {
445
+ constructor(table: string) {
446
+ super(`rows: index block of ${table} does not match its hash`);
447
+ this.name = 'IndexMismatch';
448
+ }
449
+ }
450
+
451
+ export class RowStore {
452
+ private tables = new Map<string, Table>();
453
+ private byTid = new Map<number, Table>();
454
+ private nextTid = 1;
455
+ private scratch = new Uint8Array(64 << 10);
456
+ private dirBytes = 0;
457
+ private tailOps = 0;
458
+ private needsFlush = false;
459
+ private rebuilt = false;
460
+ private closed = false;
461
+ /**
462
+ * A reader: a second view of a store another `RowStore` is writing through
463
+ * handles of its own (a follower tab reading the leader's file). It never
464
+ * writes a byte. See {@link refresh}.
465
+ */
466
+ private reader = false;
467
+ /** Generation of the superblock a reader's index came from; `null` when it found none. */
468
+ private readGen: number | null = null;
469
+
470
+ private constructor(
471
+ private io: StoreIo,
472
+ private file: SyncFile,
473
+ private name: 'a' | 'b',
474
+ private other: SyncFile | null,
475
+ private sb: Superblock,
476
+ /** End of the last whole extent: where the next one goes. */
477
+ private end: number
478
+ ) {}
479
+
480
+ // ---- open ----------------------------------------------------------------
481
+
482
+ static async open(io: StoreIo, opts: { reader?: boolean } = {}): Promise<RowStore> {
483
+ if (opts.reader) {
484
+ // Both files, for good: which of them is live changes under a reader,
485
+ // and it finds out in the middle of a synchronous read.
486
+ const store = new RowStore(io, await io.open('a'), 'a', await io.open('b'), EMPTY_SUPERBLOCK, HEADER_END);
487
+ store.reader = true;
488
+ store.reload();
489
+ return store;
490
+ }
491
+ const a = await io.open('a');
492
+ let file = a;
493
+ let name: 'a' | 'b' = 'a';
494
+ let other: SyncFile | null = null;
495
+ let sb = readSuperblock(a);
496
+ if (!sb || sb.state !== ACTIVE) {
497
+ // Either a new store, or a compaction moved the rows to `b`.
498
+ const b = await io.open('b');
499
+ const sbB = readSuperblock(b);
500
+ if (sbB && sbB.state === ACTIVE) {
501
+ file = b;
502
+ name = 'b';
503
+ other = a;
504
+ sb = sbB;
505
+ } else {
506
+ other = b;
507
+ // No file claims to be live. Take whichever still holds extents and
508
+ // rebuild from them; a store that never held any starts empty.
509
+ if (a.size() <= HEADER_END && b.size() > HEADER_END) {
510
+ file = b;
511
+ name = 'b';
512
+ other = a;
513
+ }
514
+ sb = null;
515
+ }
516
+ }
517
+ const fresh = sb === null;
518
+ const store = new RowStore(
519
+ io,
520
+ file,
521
+ name,
522
+ other,
523
+ sb ?? EMPTY_SUPERBLOCK,
524
+ HEADER_END
525
+ );
526
+ if (fresh || !store.loadDirectory()) store.resetIndex();
527
+ store.replay(store.sb.covered);
528
+ if (fresh) store.commitSuperblock(0, 0, 0, store.sb.covered);
529
+ return store;
530
+ }
531
+
532
+ /** Read the directory the superblock names. False when it cannot be trusted. */
533
+ private loadDirectory(): boolean {
534
+ const { dirOff, dirLen, dirSum, covered } = this.sb;
535
+ if (covered > Math.max(this.file.size(), HEADER_END)) return false;
536
+ if (dirOff === 0) return true;
537
+ if (dirOff + dirLen > this.file.size()) return false;
538
+ const buf = new Uint8Array(dirLen);
539
+ this.file.read(buf, dirOff);
540
+ if (hash32(buf) !== dirSum) return false;
541
+ let dir: { nextTid: number; tables: (Block & { name: string; tid: number })[] };
542
+ try {
543
+ dir = JSON.parse(decoder.decode(buf));
544
+ } catch {
545
+ return false;
546
+ }
547
+ this.nextTid = dir.nextTid;
548
+ this.dirBytes = dirLen + XH;
549
+ for (const t of dir.tables) {
550
+ const table: Table = {
551
+ name: t.name,
552
+ tid: t.tid,
553
+ block: t.n > 0 ? { off: t.off, len: t.len, n: t.n, heap: t.heap, sum: t.sum, live: t.live } : null,
554
+ run: null,
555
+ delta: new Map(),
556
+ unsaved: false,
557
+ };
558
+ this.tables.set(t.name, table);
559
+ this.byTid.set(t.tid, table);
560
+ }
561
+ return true;
562
+ }
563
+
564
+ /** Forget the index; the next replay starts from the first extent. */
565
+ private resetIndex(): void {
566
+ this.tables.clear();
567
+ this.byTid.clear();
568
+ this.nextTid = 1;
569
+ this.dirBytes = 0;
570
+ this.tailOps = 0;
571
+ this.rebuilt = this.file.size() > HEADER_END;
572
+ this.sb = { ...this.sb, dirOff: 0, dirLen: 0, dirSum: 0, covered: HEADER_END };
573
+ }
574
+
575
+ /** Apply every whole batch from `from` on, and cut the file after the last. */
576
+ private replay(from: number): void {
577
+ const size = this.file.size();
578
+ let pos = from;
579
+ // The tail is read in large pieces, not a header and a payload at a time:
580
+ // a tail of a few hundred small batches is then a handful of reads, where
581
+ // two reads per batch made it most of what an open cost.
582
+ let chunk = new Uint8Array(0);
583
+ let base = 0;
584
+ let have = 0;
585
+ /** Bytes `[at, at + len)` of the file, from the piece in hand when it covers them. */
586
+ const bytes = (at: number, len: number): Uint8Array => {
587
+ if (at < base || at + len > base + have) {
588
+ const want = Math.min(size - at, Math.max(len, REPLAY_CHUNK));
589
+ if (chunk.length < want) chunk = new Uint8Array(new ArrayBuffer(want));
590
+ this.file.read(chunk.subarray(0, want), at);
591
+ base = at;
592
+ have = want;
593
+ }
594
+ return chunk.subarray(at - base, at - base + len);
595
+ };
596
+ while (pos + XH <= size) {
597
+ const head = bytes(pos, XH);
598
+ const headView = new DataView(head.buffer, head.byteOffset, XH);
599
+ const type = headView.getUint32(0, true);
600
+ const len = headView.getUint32(4, true);
601
+ const sum = headView.getUint32(8, true);
602
+ if (type < X_BATCH || type > X_DIR || pos + XH + len > size) break;
603
+ if (type === X_BATCH) {
604
+ const payload = bytes(pos + XH, len);
605
+ if (hash32(payload) !== sum) break;
606
+ this.applyBatch(payload, pos + XH);
607
+ }
608
+ pos = align8(pos + XH + len);
609
+ }
610
+ this.end = pos;
611
+ // What follows the last whole batch is a write that died halfway, for the
612
+ // writer. For a reader it is one still being made: leave it, look again later.
613
+ if (!this.reader && size > this.end) this.file.truncate(this.end);
614
+ }
615
+
616
+ // ---- reading beside a writer ----------------------------------------------
617
+ //
618
+ // The file is a log: a writer only appends to it, so everything a reader has
619
+ // seen stays where it is, and catching up is replaying what was appended.
620
+ // Two things do move bytes. A checkpoint rewrites a superblock slot (a
621
+ // reader carries on: its own index already holds what the new one says).
622
+ // A compaction copies the live rows to the other file, marks this one MOVED
623
+ // and then empties it, in that order, so a reader that read from the old
624
+ // file checks the superblock AFTER its read: still ACTIVE and of the same
625
+ // generation, and every byte it read was in place ({@link current}).
626
+
627
+ /** Take in what the writer did since the last look. A reader calls this before it answers. */
628
+ refresh(): void {
629
+ if (!this.reader || this.closed) return;
630
+ if (!this.current() || this.end > this.file.size()) this.reload();
631
+ else this.replay(this.end);
632
+ }
633
+
634
+ /** Whether the file this reader reads is still the one being written. Checked after a read, it vouches for it. */
635
+ current(): boolean {
636
+ if (!this.reader) return true;
637
+ const sb = readSuperblock(this.file);
638
+ if (!sb) return this.readGen === null && this.file.size() <= HEADER_END;
639
+ return sb.state === ACTIVE && sb.gen === this.readGen;
640
+ }
641
+
642
+ /** Start over from whichever file is live now. */
643
+ private reload(): void {
644
+ const a = this.name === 'a' ? this.file : this.other!;
645
+ const b = this.name === 'a' ? this.other! : this.file;
646
+ const sbA = readSuperblock(a);
647
+ const sbB = sbA?.state === ACTIVE ? null : readSuperblock(b);
648
+ let name: 'a' | 'b' = 'a';
649
+ let sb: Superblock | null = null;
650
+ if (sbA?.state === ACTIVE) sb = sbA;
651
+ else if (sbB?.state === ACTIVE) {
652
+ name = 'b';
653
+ sb = sbB;
654
+ } else if (a.size() <= HEADER_END && b.size() > HEADER_END) name = 'b';
655
+ this.name = name;
656
+ this.file = name === 'a' ? a : b;
657
+ this.other = name === 'a' ? b : a;
658
+ this.sb = sb ?? EMPTY_SUPERBLOCK;
659
+ this.readGen = sb ? sb.gen : null;
660
+ this.end = HEADER_END;
661
+ this.tables.clear();
662
+ this.byTid.clear();
663
+ this.nextTid = 1;
664
+ this.dirBytes = 0;
665
+ this.tailOps = 0;
666
+ if (sb === null || !this.loadDirectory()) this.resetIndex();
667
+ this.replay(this.sb.covered);
668
+ }
669
+
670
+ private mustWrite(): void {
671
+ if (this.reader) throw new Error('rows: this store only reads');
672
+ }
673
+
674
+ private applyBatch(buf: Uint8Array, fileOff: number): void {
675
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
676
+ let p = 0;
677
+ while (p < buf.length) {
678
+ this.tailOps++;
679
+ const kind = buf[p];
680
+ const flags = buf[p + 1];
681
+ const tid = view.getUint16(p + 2, true);
682
+ if (kind === R_TABLE) {
683
+ const nameLen = view.getUint16(p + 4, true);
684
+ const name = decoder.decode(buf.subarray(p + 6, p + 6 + nameLen));
685
+ if (!this.byTid.has(tid)) this.addTable(name, tid);
686
+ p += 6 + nameLen;
687
+ continue;
688
+ }
689
+ const table = this.byTid.get(tid);
690
+ if (!table) throw new Error(`rows: batch names unknown table ${tid}`);
691
+ if (kind === R_CLEAR) {
692
+ this.clearTable(table);
693
+ p += 4;
694
+ continue;
695
+ }
696
+ const idLen = view.getUint16(p + 4, true);
697
+ const id = decoder.decode(buf.subarray(p + 6, p + 6 + idLen));
698
+ p += 6 + idLen;
699
+ if (kind === R_DEL) {
700
+ table.delta.set(id, null);
701
+ continue;
702
+ }
703
+ if (kind !== R_PUT) throw new Error(`rows: unknown record kind ${kind}`);
704
+ const rv = view.getFloat64(p, true);
705
+ const len = view.getUint32(p + 8, true);
706
+ table.delta.set(id, { off: fileOff + p + 12, len, rv, flags });
707
+ p += 12 + len;
708
+ }
709
+ }
710
+
711
+ private addTable(name: string, tid: number): Table {
712
+ const table: Table = { name, tid, block: null, run: null, delta: new Map(), unsaved: false };
713
+ this.tables.set(name, table);
714
+ this.byTid.set(tid, table);
715
+ if (tid >= this.nextTid) this.nextTid = tid + 1;
716
+ return table;
717
+ }
718
+
719
+ private clearTable(table: Table): void {
720
+ table.delta.clear();
721
+ table.unsaved = table.unsaved || table.block !== null;
722
+ table.block = null;
723
+ table.run = emptyRun();
724
+ }
725
+
726
+ // ---- reads ---------------------------------------------------------------
727
+
728
+ /** The table's run, read from its block on first use. */
729
+ private loadRun(table: Table): Run {
730
+ if (table.run) return table.run;
731
+ const block = table.block;
732
+ if (!block) return (table.run = emptyRun());
733
+ const buf = new Uint8Array(new ArrayBuffer(block.len));
734
+ this.file.read(buf, block.off);
735
+ if (hash32(buf) !== block.sum) throw new IndexMismatch(table.name);
736
+ return (table.run = runFromBuffer(buf, block.n, block.heap, block.live));
737
+ }
738
+
739
+ /**
740
+ * Run `fn`; when it finds an index block that does not match what was
741
+ * written, rebuild the index from the log and run it again. The log still
742
+ * holds every row, so the answer is the same, only later.
743
+ */
744
+ private trusted<T>(fn: () => T): T {
745
+ try {
746
+ return fn();
747
+ } catch (error) {
748
+ if (!(error instanceof IndexMismatch)) throw error;
749
+ if (this.reader) {
750
+ // Not damage: the block lay in a file a compaction has emptied since.
751
+ this.reload();
752
+ return fn();
753
+ }
754
+ this.resetIndex();
755
+ this.rebuilt = true;
756
+ this.replay(HEADER_END);
757
+ return fn();
758
+ }
759
+ }
760
+
761
+ /** The table's rows in id order, with every write folded in. */
762
+ ordered(name: string): Run {
763
+ return this.trusted(() => {
764
+ const table = this.tables.get(name);
765
+ if (!table) return emptyRun();
766
+ const run = this.loadRun(table);
767
+ if (table.delta.size === 0) return run;
768
+ table.run = mergeRun(run, table.delta);
769
+ table.delta.clear();
770
+ table.unsaved = true;
771
+ return table.run;
772
+ });
773
+ }
774
+
775
+ find(name: string, id: string): Entry | null {
776
+ return this.trusted(() => {
777
+ const table = this.tables.get(name);
778
+ if (!table) return null;
779
+ const pending = table.delta.get(id);
780
+ if (pending !== undefined) return pending;
781
+ const run = this.loadRun(table);
782
+ const i = runFind(run, id);
783
+ return i < 0 ? null : { off: run.off[i], len: run.len[i], rv: run.rv[i], flags: run.flags[i] };
784
+ });
785
+ }
786
+
787
+ /** Read `len` bytes at `off` into `into`, starting at `at`. */
788
+ readInto(off: number, len: number, into: Uint8Array, at: number): void {
789
+ this.file.read(into.subarray(at, at + len), off);
790
+ }
791
+
792
+ get(name: string, id: string): { body: Uint8Array; entry: Entry } | null {
793
+ const entry = this.find(name, id);
794
+ if (!entry) return null;
795
+ const body = new Uint8Array(entry.len);
796
+ this.file.read(body, entry.off);
797
+ return { body, entry };
798
+ }
799
+
800
+ count(name: string): number {
801
+ return this.ordered(name).n;
802
+ }
803
+
804
+ /**
805
+ * The ids of a table that start with `prefix`, in order, with the prefix cut
806
+ * off. Ids are sorted, so this is one search and a walk over the matches:
807
+ * what makes a table of `value\0id` keys work as a secondary index.
808
+ */
809
+ prefix(name: string, prefix: string): string[] {
810
+ const run = this.ordered(name);
811
+ const len = encodeProbe(prefix);
812
+ const key = probe.slice(0, len);
813
+ const out: string[] = [];
814
+ for (let i = lowerBound(run, 0, key, len); i < run.n; i++) {
815
+ const s = idStart(run, i);
816
+ const e = run.idEnd[i];
817
+ if (e - s < len || cmpBytes(run.heap, s, s + len, key, 0, len) !== 0) break;
818
+ out.push(decoder.decode(run.heap.subarray(s + len, e)));
819
+ }
820
+ return out;
821
+ }
822
+
823
+ /** `(id, version)` of every row, from the index alone. */
824
+ versions(name: string): [string, number][] {
825
+ const run = this.ordered(name);
826
+ const out: [string, number][] = [];
827
+ for (let i = 0; i < run.n; i++) out.push([runId(run, i), run.rv[i]]);
828
+ return out;
829
+ }
830
+
831
+ tableNames(): string[] {
832
+ return [...this.tables.keys()].sort();
833
+ }
834
+
835
+ // ---- writes --------------------------------------------------------------
836
+
837
+ private table(name: string): { table: Table; isNew: boolean } {
838
+ const existing = this.tables.get(name);
839
+ if (existing) return { table: existing, isNew: false };
840
+ return { table: this.addTable(name, this.nextTid), isNew: true };
841
+ }
842
+
843
+ /**
844
+ * Apply `ops` as one atomic batch. `sync` flushes before returning; without
845
+ * it the bytes are with the operating system (they survive the tab, not a
846
+ * power cut) until the next {@link flush}.
847
+ */
848
+ write(ops: StoreOp[], sync = false): void {
849
+ this.mustWrite();
850
+ if (this.closed) throw new Error('rows: store is closed');
851
+ if (ops.length === 0) return;
852
+ let bound = XH + 8;
853
+ for (const op of ops) {
854
+ bound += 12 + op.table.length * 3;
855
+ if (op.t !== 'clear') bound += op.id.length * 3 + 6;
856
+ if (op.t === 'put') bound += op.body.length + 12;
857
+ }
858
+ if (this.scratch.length < bound) this.scratch = new Uint8Array(Math.max(bound, this.scratch.length * 2));
859
+ const buf = this.scratch;
860
+ const view = new DataView(buf.buffer);
861
+ let p = XH;
862
+ const applied: (() => void)[] = [];
863
+ const created: Table[] = [];
864
+ const base = this.end;
865
+ for (const op of ops) {
866
+ const { table, isNew } = this.table(op.table);
867
+ if (isNew) {
868
+ created.push(table);
869
+ buf[p] = R_TABLE;
870
+ buf[p + 1] = 0;
871
+ view.setUint16(p + 2, table.tid, true);
872
+ const written = encoder.encodeInto(table.name, buf.subarray(p + 6)).written;
873
+ view.setUint16(p + 4, written, true);
874
+ p += 6 + written;
875
+ }
876
+ if (op.t === 'clear') {
877
+ buf[p] = R_CLEAR;
878
+ buf[p + 1] = 0;
879
+ view.setUint16(p + 2, table.tid, true);
880
+ p += 4;
881
+ applied.push(() => this.clearTable(table));
882
+ continue;
883
+ }
884
+ const idLen = encoder.encodeInto(op.id, buf.subarray(p + 6)).written;
885
+ if (idLen > MAX_ID_BYTES) throw new Error('rows: id longer than 65535 bytes');
886
+ view.setUint16(p + 2, table.tid, true);
887
+ view.setUint16(p + 4, idLen, true);
888
+ if (op.t === 'del') {
889
+ buf[p] = R_DEL;
890
+ buf[p + 1] = 0;
891
+ p += 6 + idLen;
892
+ const id = op.id;
893
+ applied.push(() => table.delta.set(id, null));
894
+ continue;
895
+ }
896
+ buf[p] = R_PUT;
897
+ buf[p + 1] = op.flags;
898
+ p += 6 + idLen;
899
+ view.setFloat64(p, op.rv, true);
900
+ view.setUint32(p + 8, op.body.length, true);
901
+ buf.set(op.body, p + 12);
902
+ const entry: Entry = { off: base + p + 12, len: op.body.length, rv: op.rv, flags: op.flags };
903
+ const id = op.id;
904
+ applied.push(() => table.delta.set(id, entry));
905
+ p += 12 + op.body.length;
906
+ }
907
+ try {
908
+ this.appendExtent(X_BATCH, buf, p);
909
+ } catch (error) {
910
+ // Nothing was appended (a full disk, a lost handle): the tables this
911
+ // batch would have introduced were never named in the log.
912
+ for (const table of created) {
913
+ this.tables.delete(table.name);
914
+ this.byTid.delete(table.tid);
915
+ }
916
+ if (created.length > 0) this.nextTid = Math.min(...created.map((t) => t.tid));
917
+ throw error;
918
+ }
919
+ // The index moves only once the bytes are in the file.
920
+ for (const apply of applied) apply();
921
+ this.tailOps += ops.length;
922
+ if (this.scratch.length > SCRATCH_KEEP) this.scratch = new Uint8Array(64 << 10);
923
+ this.needsFlush = true;
924
+ if (sync) this.flush();
925
+ }
926
+
927
+ /**
928
+ * Frame `buf[XH..p)` as one extent and append it. `buf` must leave its first
929
+ * `XH` bytes free and have room for the padding.
930
+ */
931
+ private appendExtent(type: number, buf: Uint8Array, p: number): number {
932
+ const len = p - XH;
933
+ const total = align8(p);
934
+ buf.fill(0, p, total);
935
+ const view = new DataView(buf.buffer, buf.byteOffset, XH);
936
+ view.setUint32(0, type, true);
937
+ view.setUint32(4, len, true);
938
+ view.setUint32(8, hash32(buf, XH, p), true);
939
+ view.setUint32(12, 0, true);
940
+ this.file.write(buf.subarray(0, total), this.end);
941
+ const at = this.end + XH;
942
+ this.end += total;
943
+ return at;
944
+ }
945
+
946
+ flush(): void {
947
+ if (!this.needsFlush || this.reader) return;
948
+ this.file.flush();
949
+ this.needsFlush = false;
950
+ }
951
+
952
+ // ---- checkpoint ----------------------------------------------------------
953
+
954
+ /** Bytes of batches the next open would have to replay. */
955
+ get tailBytes(): number {
956
+ return this.end - this.sb.covered;
957
+ }
958
+
959
+ /**
960
+ * Persist the index: append the run of every table written since the last
961
+ * checkpoint, then a directory, then flip the superblock. Returns false when
962
+ * there was nothing to persist.
963
+ */
964
+ checkpoint(): boolean {
965
+ return this.trusted(() => this.checkpointOnce());
966
+ }
967
+
968
+ private checkpointOnce(): boolean {
969
+ if (this.closed || this.reader) return false;
970
+ let dirty = this.end > this.sb.covered;
971
+ for (const table of this.tables.values()) dirty = dirty || table.delta.size > 0 || table.unsaved;
972
+ if (!dirty) return false;
973
+ for (const table of this.tables.values()) {
974
+ if (table.delta.size === 0 && !table.unsaved) continue;
975
+ const run = this.ordered(table.name);
976
+ table.block = run.n > 0 ? this.appendBlock(run) : null;
977
+ table.unsaved = false;
978
+ }
979
+ const { dirOff, dirLen, dirSum } = this.appendDirectory();
980
+ this.file.flush();
981
+ this.commitSuperblock(dirOff, dirLen, dirSum, this.end);
982
+ return true;
983
+ }
984
+
985
+ private appendBlock(run: Run): Block {
986
+ const head = new Uint8Array(XH);
987
+ const view = new DataView(head.buffer);
988
+ const sum = hash32(run.buf);
989
+ view.setUint32(0, X_BLOCK, true);
990
+ view.setUint32(4, run.buf.length, true);
991
+ view.setUint32(8, sum, true);
992
+ this.file.write(head, this.end);
993
+ const off = this.end + XH;
994
+ this.file.write(run.buf, off);
995
+ this.end = align8(off + run.buf.length);
996
+ // Leave no hole behind a block whose length is not a multiple of 8.
997
+ if (this.file.size() < this.end) this.file.truncate(this.end);
998
+ return { off, len: run.buf.length, n: run.n, heap: run.heap.length, sum, live: run.live };
999
+ }
1000
+
1001
+ private appendDirectory(): { dirOff: number; dirLen: number; dirSum: number } {
1002
+ const tables = [...this.tables.values()].map((t) => ({
1003
+ name: t.name,
1004
+ tid: t.tid,
1005
+ ...(t.block ?? { off: 0, len: 0, n: 0, heap: 0, sum: 0, live: 0 }),
1006
+ }));
1007
+ const body = encoder.encode(JSON.stringify({ nextTid: this.nextTid, tables }));
1008
+ const buf = new Uint8Array(align8(XH + body.length));
1009
+ buf.set(body, XH);
1010
+ const dirOff = this.appendExtent(X_DIR, buf, XH + body.length);
1011
+ this.dirBytes = body.length + XH;
1012
+ return { dirOff, dirLen: body.length, dirSum: hash32(body) };
1013
+ }
1014
+
1015
+ private commitSuperblock(dirOff: number, dirLen: number, dirSum: number, covered: number): void {
1016
+ this.sb = { ...this.sb, seq: this.sb.seq + 1, state: ACTIVE, dirOff, dirLen, dirSum, covered };
1017
+ writeSuperblock(this.file, this.sb);
1018
+ this.file.flush();
1019
+ this.needsFlush = false;
1020
+ if (covered === this.end) this.tailOps = 0;
1021
+ }
1022
+
1023
+ // ---- compaction ----------------------------------------------------------
1024
+
1025
+ stats(): StoreStats {
1026
+ let liveBytes = 0;
1027
+ let indexBytes = this.dirBytes;
1028
+ for (const table of this.tables.values()) {
1029
+ const block = table.block;
1030
+ // A live row costs its body plus its record header and id in the log.
1031
+ const run = table.run;
1032
+ if (run) liveBytes += run.live + RECORD_BYTES * run.n + run.heap.length;
1033
+ else if (block) liveBytes += block.live + RECORD_BYTES * block.n + block.heap;
1034
+ if (block) indexBytes += block.len + XH;
1035
+ }
1036
+ const fileBytes = this.end;
1037
+ return {
1038
+ file: this.name,
1039
+ fileBytes,
1040
+ liveBytes,
1041
+ indexBytes,
1042
+ garbageBytes: Math.max(0, fileBytes - HEADER_END - liveBytes - indexBytes),
1043
+ tailBytes: this.tailBytes,
1044
+ tailOps: this.tailOps,
1045
+ tables: this.tables.size,
1046
+ rebuilt: this.rebuilt,
1047
+ };
1048
+ }
1049
+
1050
+ /**
1051
+ * Copy every live row into the other file, in id order, and switch to it.
1052
+ * The switch is one superblock write in the old file; a crash before it
1053
+ * leaves the old file as it was, a crash after it finds the new one whole.
1054
+ */
1055
+ async compact(): Promise<void> {
1056
+ this.mustWrite();
1057
+ if (this.closed) throw new Error('rows: store is closed');
1058
+ // Load every run up front, so a mismatching block is rebuilt before any byte is copied.
1059
+ for (const name of [...this.tables.keys()]) this.ordered(name);
1060
+ const src = this.file;
1061
+ const dst = this.other ?? (await this.io.open(this.name === 'a' ? 'b' : 'a'));
1062
+ dst.truncate(0);
1063
+
1064
+ const next = new RowStore(
1065
+ this.io,
1066
+ dst,
1067
+ this.name === 'a' ? 'b' : 'a',
1068
+ src,
1069
+ { seq: 0, state: ACTIVE, dirOff: 0, dirLen: 0, dirSum: 0, covered: HEADER_END, gen: this.sb.gen + 1 },
1070
+ HEADER_END
1071
+ );
1072
+ const chunk = new Uint8Array(COMPACT_CHUNK + XH + 8);
1073
+ const view = new DataView(chunk.buffer);
1074
+ for (const table of this.tables.values()) {
1075
+ const run = this.ordered(table.name);
1076
+ const copy = next.addTable(table.name, table.tid);
1077
+ const moved = new Uint8Array(new ArrayBuffer(run.buf.length));
1078
+ moved.set(run.buf);
1079
+ const out = runFromBuffer(moved, run.n, run.heap.length, run.live);
1080
+ let p = XH;
1081
+ let first = 0;
1082
+ const emit = (): void => {
1083
+ if (p === XH) return;
1084
+ const at = next.appendExtent(X_BATCH, chunk, p);
1085
+ // Offsets were recorded relative to the chunk; make them absolute.
1086
+ for (let k = first; k < pending; k++) out.off[k] += at - XH;
1087
+ first = pending;
1088
+ p = XH;
1089
+ };
1090
+ let pending = 0;
1091
+ // The table's name travels with its rows, so a scan of this file alone can rebuild it.
1092
+ chunk[p] = R_TABLE;
1093
+ chunk[p + 1] = 0;
1094
+ view.setUint16(p + 2, table.tid, true);
1095
+ const nameLen = encoder.encodeInto(table.name, chunk.subarray(p + 6)).written;
1096
+ view.setUint16(p + 4, nameLen, true);
1097
+ p += 6 + nameLen;
1098
+ for (let i = 0; i < run.n; i++) {
1099
+ const s = idStart(run, i);
1100
+ const idLen = run.idEnd[i] - s;
1101
+ const size = RECORD_BYTES + idLen + run.len[i];
1102
+ if (size > COMPACT_CHUNK) throw new Error('rows: row larger than a compaction chunk');
1103
+ if (p + size > COMPACT_CHUNK + XH) emit();
1104
+ chunk[p] = R_PUT;
1105
+ chunk[p + 1] = run.flags[i];
1106
+ view.setUint16(p + 2, table.tid, true);
1107
+ view.setUint16(p + 4, idLen, true);
1108
+ chunk.set(run.heap.subarray(s, s + idLen), p + 6);
1109
+ p += 6 + idLen;
1110
+ view.setFloat64(p, run.rv[i], true);
1111
+ view.setUint32(p + 8, run.len[i], true);
1112
+ src.read(chunk.subarray(p + 12, p + 12 + run.len[i]), run.off[i]);
1113
+ out.off[i] = p + 12;
1114
+ p += 12 + run.len[i];
1115
+ pending = i + 1;
1116
+ }
1117
+ emit();
1118
+ copy.run = out;
1119
+ copy.block = out.n > 0 ? next.appendBlock(out) : null;
1120
+ }
1121
+ next.nextTid = this.nextTid;
1122
+ const { dirOff, dirLen, dirSum } = next.appendDirectory();
1123
+ dst.flush();
1124
+ next.commitSuperblock(dirOff, dirLen, dirSum, next.end);
1125
+
1126
+ // The commit: from here on an open finds `dst`.
1127
+ writeSuperblock(src, { ...this.sb, seq: this.sb.seq + 1, state: MOVED });
1128
+ src.flush();
1129
+ src.truncate(HEADER_END);
1130
+
1131
+ this.file = dst;
1132
+ this.other = src;
1133
+ this.name = next.name;
1134
+ this.sb = next.sb;
1135
+ this.end = next.end;
1136
+ this.tables = next.tables;
1137
+ this.byTid = next.byTid;
1138
+ this.dirBytes = next.dirBytes;
1139
+ this.tailOps = 0;
1140
+ this.needsFlush = false;
1141
+ }
1142
+
1143
+ close(): void {
1144
+ if (this.closed) return;
1145
+ this.flush();
1146
+ this.closed = true;
1147
+ this.file.close();
1148
+ this.other?.close();
1149
+ }
1150
+ }
1151
+
1152
+ /** A {@link SyncFile} held in memory: tests, and the store's memory mode. */
1153
+ export class MemoryFile implements SyncFile {
1154
+ private bytes = new Uint8Array(64 << 10);
1155
+ private length = 0;
1156
+ flushes = 0;
1157
+
1158
+ read(buffer: Uint8Array, at: number): number {
1159
+ const n = Math.max(0, Math.min(buffer.length, this.length - at));
1160
+ if (n > 0) buffer.set(this.bytes.subarray(at, at + n));
1161
+ if (n < buffer.length) buffer.fill(0, n);
1162
+ return n;
1163
+ }
1164
+
1165
+ write(buffer: Uint8Array, at: number): number {
1166
+ const end = at + buffer.length;
1167
+ if (end > this.bytes.length) {
1168
+ const grown = new Uint8Array(Math.max(end, this.bytes.length * 2));
1169
+ grown.set(this.bytes.subarray(0, this.length));
1170
+ this.bytes = grown;
1171
+ }
1172
+ if (at > this.length) this.bytes.fill(0, this.length, at);
1173
+ this.bytes.set(buffer, at);
1174
+ if (end > this.length) this.length = end;
1175
+ return buffer.length;
1176
+ }
1177
+
1178
+ size(): number {
1179
+ return this.length;
1180
+ }
1181
+
1182
+ truncate(size: number): void {
1183
+ if (size > this.bytes.length) {
1184
+ const grown = new Uint8Array(size);
1185
+ grown.set(this.bytes.subarray(0, this.length));
1186
+ this.bytes = grown;
1187
+ }
1188
+ if (size > this.length) this.bytes.fill(0, this.length, size);
1189
+ this.length = size;
1190
+ }
1191
+
1192
+ flush(): void {
1193
+ this.flushes++;
1194
+ }
1195
+
1196
+ close(): void {}
1197
+
1198
+ /** The file's bytes, for tests that damage them. */
1199
+ snapshot(): Uint8Array {
1200
+ return this.bytes.slice(0, this.length);
1201
+ }
1202
+
1203
+ static from(bytes: Uint8Array): MemoryFile {
1204
+ const file = new MemoryFile();
1205
+ file.write(bytes, 0);
1206
+ return file;
1207
+ }
1208
+ }