@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,1203 @@
1
+ import type { QueryPlan, WhereNode } from '@spooky-sync/query-builder';
2
+ import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
3
+ import type { StorageHealth } from '../../types';
4
+ import type { Id, OrderBy, RelationFetch, Row, SnapshotMeta, StoredSnapshot } from './cache-engine';
5
+ import { stableKey } from './relation-resolver';
6
+ import { fromBase64, serializeMergeRow, serializeRow } from './sqlite-plan-sql';
7
+ import { COLUMNS_ROW_ID, planColumnReset } from './sqlite-column-reset';
8
+ import {
9
+ SNAPSHOT_TABLE,
10
+ SqliteCacheEngine,
11
+ normalizePlanForClone,
12
+ normalizeWhereForClone,
13
+ toCloneSafe,
14
+ } from './sqlite-cache-engine';
15
+ import { WorkerSqliteTransport, type SqliteTransport } from './sqlite-transport';
16
+ import { tableOf, type SqlOp } from './surql-translate';
17
+ import { ROWS_PROTOCOL, ROWS_READER_OPS, parseRowBytes, type WireOp } from './rows-exec';
18
+ import { FLAG_RAW, FLAG_U8, bucketDirName, type StoreStats } from './rows-store';
19
+ import {
20
+ ROWS_AHEAD_OPS,
21
+ ROWS_PREWARM_KEY,
22
+ ReadAhead,
23
+ aheadKey,
24
+ jsonSafe,
25
+ takePrewarmed,
26
+ type PrewarmRecord,
27
+ } from './rows-prewarm';
28
+
29
+ export { ROWS_PREWARM_KEY, ROWS_PREWARM_SNIPPET, prewarmRows } from './rows-prewarm';
30
+
31
+ /**
32
+ * Tables whose rows exist nowhere else: writes the user made that the server
33
+ * has not confirmed. A batch that touches one is flushed to disk before the
34
+ * write resolves. Everything else is a copy of server state and is flushed a
35
+ * moment later, in the worker's own time: losing it to a power cut costs a
36
+ * refetch, not a user's work.
37
+ */
38
+ export const ROWS_DURABLE_TABLES: ReadonlySet<string> = new Set([
39
+ '_00_pending_mutations',
40
+ '_00_pending_writes',
41
+ '_00_failed_mutations',
42
+ '_00_crdt_local',
43
+ ]);
44
+
45
+ const SCHEMA_TABLE = '_00_schema';
46
+
47
+ /** How long after connecting a read counts as one the app makes at startup. */
48
+ const PAINT_CAPTURE_MS = 3000;
49
+
50
+ // What the next page load asks the worker ahead of the app (see `rows-prewarm.ts`).
51
+ // Bounded: the answers wait in the page's memory until the app asks or writes.
52
+ const AHEAD_MAX_READS = 24;
53
+ const AHEAD_MAX_REPLY_BYTES = 512 << 10;
54
+ const AHEAD_MAX_TOTAL_BYTES = 2 << 20;
55
+ const AHEAD_MAX_REQUEST_CHARS = 32_000;
56
+ /** How long a read waits for an answer that was asked ahead before asking again itself. */
57
+ const AHEAD_WAIT_MS = 250;
58
+ /** How long a follower's own reader may take over one read before the leader is asked instead. */
59
+ const READER_OP_TIMEOUT_MS = 2000;
60
+
61
+ /** A timer nothing should wait for (a Node process, a test run). */
62
+ function background<T>(timer: T): T {
63
+ (timer as { unref?: () => void }).unref?.();
64
+ return timer;
65
+ }
66
+
67
+ /** Worker ops that leave the store as it was: none of them makes an answer read ahead stale. */
68
+ const ROWS_READ_OPS: ReadonlySet<string> = new Set([
69
+ 'select',
70
+ 'by-ids',
71
+ 'get',
72
+ 'relation',
73
+ 'select-table',
74
+ 'count',
75
+ 'versions',
76
+ 'tables',
77
+ 'blob-get',
78
+ 'diag',
79
+ 'warm',
80
+ ]);
81
+ const PAINT_MAX_KEYS = 64;
82
+ const PAINT_MAX_ENTRY_CHARS = 256_000;
83
+ const PAINT_FLUSH_MS = 1500;
84
+ /** What a kept read starts with: this layout. A copy that starts otherwise is another release's, and is not read. */
85
+ const PAINT_FORMAT = '2';
86
+
87
+ interface PaintEntry {
88
+ tables: string[];
89
+ /** {@link PAINT_FORMAT}, the header (see {@link paintHead}), a newline, then the rows as JSON text. */
90
+ text: string;
91
+ dirty: boolean;
92
+ }
93
+
94
+ /** A table and its mark (see {@link PaintCache}) at the time a read of it was kept. */
95
+ type PaintMark = [table: string, mark: string | null];
96
+
97
+ /** A kept read's header: whether it holds bytes to revive, the marks it was read under, and where its rows start. */
98
+ function paintHead(text: string): { u8: boolean; marks: PaintMark[]; body: number } | null {
99
+ if (text[0] !== PAINT_FORMAT) return null;
100
+ const end = text.indexOf('\n');
101
+ if (end < 0) return null;
102
+ try {
103
+ const [u8, marks] = JSON.parse(text.slice(1, end)) as [number, PaintMark[]];
104
+ return Array.isArray(marks) ? { u8: u8 === 1, marks, body: end + 1 } : null;
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+
110
+ function hashKey(text: string): string {
111
+ let a = 0x811c9dc5;
112
+ let b = 0x01000193;
113
+ for (let i = 0; i < text.length; i++) {
114
+ const c = text.charCodeAt(i);
115
+ a = Math.imul(a ^ c, 0x01000193);
116
+ b = Math.imul(b + c, 0x85ebca6b) ^ (b >>> 13);
117
+ }
118
+ return (a >>> 0).toString(36) + (b >>> 0).toString(36);
119
+ }
120
+
121
+ /**
122
+ * The rows the app read at startup last time, kept in localStorage: the one
123
+ * place a page can read synchronously, before a worker exists or a file is
124
+ * open. {@link RowsCacheEngine.peekByIds} and `peekSelect` answer from it in
125
+ * a fraction of a millisecond, so a screen can paint what it showed before
126
+ * while the store opens.
127
+ *
128
+ * What it holds is a copy, and the contract says so: a peek is something to
129
+ * paint from, the read that follows is the answer.
130
+ *
131
+ * Several tabs keep copies in the same place and write to the same store
132
+ * (shared tabs), so a copy says what it was read under. Every table has a
133
+ * mark in localStorage, and a tab that writes to a table leaves a new one
134
+ * there, once before the write is sent and once after the store has taken it.
135
+ * A copy carries the marks its tables had when it was read and is handed out
136
+ * only while they still stand, whichever tab wrote. The same marks tell a tab
137
+ * that a read of its own was overtaken by another tab's write (see
138
+ * {@link stamp}). What is left is a tab that dies between a write and its
139
+ * second mark, a write given up on (its deadline passed) that the store takes
140
+ * after all, and a browser that dies before a mark reaches the disk: the read
141
+ * that follows the peek then corrects the screen a moment later.
142
+ *
143
+ * A tab that is alone in the store (no shared tabs) leaves no marks: nobody
144
+ * else writes to it, and dropping its own copies as it writes is enough.
145
+ */
146
+ export class PaintCache {
147
+ private entries = new Map<string, PaintEntry>();
148
+ /** Reads this session made at startup: the ones worth keeping a copy of, whenever they run again. */
149
+ private known = new Set<string>();
150
+ /** table -> keys, for the entries of earlier sessions and of other tabs too. */
151
+ private byTable: Map<string, Set<string>> | null = null;
152
+ /** table -> writes this tab knows of: its own, and another tab's each time the table's mark was found moved. */
153
+ private writes = new Map<string, number>();
154
+ /** table -> its mark as this tab last read it. */
155
+ private seen = new Map<string, string | null>();
156
+ /** table -> the mark this tab last left there. */
157
+ private mine = new Map<string, string>();
158
+ private readonly tab = Math.random().toString(36).slice(2, 10);
159
+ private marked = 0;
160
+ /** Moves with the bucket, so a read sent under one is never kept under the next. */
161
+ private era = 0;
162
+ private timer: ReturnType<typeof setTimeout> | null = null;
163
+ private bucket = '';
164
+ private since = 0;
165
+
166
+ /** `shared`: other tabs write to the same store, so writes are marked for them. */
167
+ constructor(
168
+ private maxChars: number,
169
+ private shared = true
170
+ ) {
171
+ if (typeof addEventListener === 'function') {
172
+ // localStorage is synchronous, so the last state can still be saved as the page goes.
173
+ addEventListener('pagehide', () => this.flush());
174
+ }
175
+ }
176
+
177
+ /** The bucket about to be opened: peeks answer from it until `start` says which one it is. */
178
+ expect(bucket: string): void {
179
+ if (!this.bucket) this.bucket = bucket;
180
+ }
181
+
182
+ /** A new session on `bucket`: reads from now on are startup reads for a while. */
183
+ start(bucket: string): void {
184
+ if (bucket !== this.bucket) {
185
+ this.flush();
186
+ this.forget();
187
+ }
188
+ this.bucket = bucket;
189
+ this.since = Date.now();
190
+ }
191
+
192
+ /**
193
+ * {@link start} for a tab that is handed its store more than once (shared
194
+ * tabs: a new role over the same bucket). Only the first hand-over of a
195
+ * bucket starts a session; what the tab reads after a later one is not what
196
+ * it reads at startup.
197
+ */
198
+ adopt(bucket: string): void {
199
+ if (bucket !== this.bucket || this.since === 0) this.start(bucket);
200
+ }
201
+
202
+ /** The store turned out to live in memory: nothing read from it is worth showing next time. */
203
+ stop(): void {
204
+ if (this.timer) clearTimeout(this.timer);
205
+ this.timer = null;
206
+ this.forget();
207
+ this.bucket = '';
208
+ this.since = 0;
209
+ }
210
+
211
+ private forget(): void {
212
+ this.entries.clear();
213
+ this.known.clear();
214
+ this.byTable = null;
215
+ this.seen.clear();
216
+ this.mine.clear();
217
+ this.era++;
218
+ }
219
+
220
+ private name(key: string): string {
221
+ return `sp00ky.paint.${this.bucket}.${key}`;
222
+ }
223
+
224
+ /** Where `table`'s mark is kept. A key is a hash and has no dot, so the two never meet. */
225
+ private markName(table: string): string {
226
+ return `sp00ky.paint.${this.bucket}.t.${table}`;
227
+ }
228
+
229
+ private index(): Map<string, Set<string>> {
230
+ if (this.byTable) return this.byTable;
231
+ this.byTable = new Map();
232
+ this.readIndex();
233
+ return this.byTable;
234
+ }
235
+
236
+ /** Take in the keys kept by earlier sessions, and by other tabs since this one last looked. */
237
+ private readIndex(): void {
238
+ try {
239
+ const saved = JSON.parse(localStorage.getItem(`sp00ky.paint.${this.bucket}`) ?? '{}') as Record<string, string[]>;
240
+ for (const [key, tables] of Object.entries(saved)) if (Array.isArray(tables)) this.link(key, tables);
241
+ } catch {
242
+ /* an unreadable index only means nothing gets dropped that is not there */
243
+ }
244
+ }
245
+
246
+ private link(key: string, tables: string[]): void {
247
+ const index = this.index();
248
+ for (const table of tables) {
249
+ let keys = index.get(table);
250
+ if (!keys) index.set(table, (keys = new Set()));
251
+ keys.add(key);
252
+ }
253
+ }
254
+
255
+ /**
256
+ * Read `table`'s mark. One that moved, and not to what this tab left there,
257
+ * is another tab's write.
258
+ */
259
+ private look(table: string): void {
260
+ let now: string | null = null;
261
+ try {
262
+ now = localStorage.getItem(this.markName(table));
263
+ } catch {
264
+ /* no storage: no other tab to hear from */
265
+ }
266
+ if (now === (this.seen.get(table) ?? null)) return;
267
+ this.seen.set(table, now);
268
+ if (now !== this.mine.get(table)) this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
269
+ }
270
+
271
+ /** Leave a new mark on `table`: every copy read under the old one is void, in every tab. */
272
+ private leave(table: string): void {
273
+ if (!this.shared) return;
274
+ // Another tab's write is counted before its mark is covered.
275
+ this.look(table);
276
+ let mark: string | null = `${this.tab}.${++this.marked}`;
277
+ try {
278
+ try {
279
+ localStorage.setItem(this.markName(table), mark);
280
+ } catch {
281
+ // No room for it. The copies are what fills the room and what the mark
282
+ // protects: without them it fits, and there is nothing left to go stale.
283
+ this.empty();
284
+ localStorage.setItem(this.markName(table), mark);
285
+ }
286
+ } catch {
287
+ // Still none (the storage is someone else's, or gone). Taking the old mark away says as much.
288
+ mark = null;
289
+ try {
290
+ localStorage.removeItem(this.markName(table));
291
+ } catch {
292
+ /* no storage: no other tab reads it either */
293
+ }
294
+ }
295
+ if (mark === null) this.mine.delete(table);
296
+ else this.mine.set(table, mark);
297
+ this.seen.set(table, mark);
298
+ }
299
+
300
+ /** Every copy kept for this bucket, by any tab, whether the index knows it or not. Marks stay. */
301
+ private copies(): string[] {
302
+ const prefix = `sp00ky.paint.${this.bucket}.`;
303
+ const out: string[] = [];
304
+ for (let i = 0; i < localStorage.length; i++) {
305
+ const name = localStorage.key(i);
306
+ if (name !== null && name.startsWith(prefix) && !name.startsWith(prefix + 't.')) out.push(name.slice(prefix.length));
307
+ }
308
+ return out;
309
+ }
310
+
311
+ /** Let go of every copy of this bucket, this tab's and the others'. */
312
+ private empty(): void {
313
+ this.entries.clear();
314
+ this.byTable = new Map();
315
+ try {
316
+ for (const key of this.copies()) localStorage.removeItem(this.name(key));
317
+ localStorage.removeItem(`sp00ky.paint.${this.bucket}`);
318
+ } catch {
319
+ /* no storage */
320
+ }
321
+ }
322
+
323
+ /** Whether no tab has written to these tables since they were read. Throws without storage. */
324
+ private holds(marks: PaintMark[]): boolean {
325
+ for (const [table, mark] of marks) if (localStorage.getItem(this.markName(table)) !== mark) return false;
326
+ return true;
327
+ }
328
+
329
+ get(key: string, revive: (b64: string) => Uint8Array): Row[] | null {
330
+ if (!this.bucket) return null;
331
+ try {
332
+ // This tab's own copy first. When that one no longer stands, another tab may have kept a newer one.
333
+ const own = this.entries.get(key)?.text;
334
+ for (const text of own ? [own, null] : [null]) {
335
+ const kept = text ?? localStorage.getItem(this.name(key));
336
+ const head = kept ? paintHead(kept) : null;
337
+ if (!kept || !head || !this.holds(head.marks)) continue;
338
+ const rows = kept.slice(head.body);
339
+ if (!head.u8) return JSON.parse(rows) as Row[];
340
+ return JSON.parse(rows, (_k, v) =>
341
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
342
+ ) as Row[];
343
+ }
344
+ return null;
345
+ } catch {
346
+ return null;
347
+ }
348
+ }
349
+
350
+ /**
351
+ * What is known of the writes to `tables`: taken when a read is sent,
352
+ * checked when it answers. It moves with every write this tab sends and
353
+ * with every write of another tab that this one has seen the mark of.
354
+ */
355
+ stamp(tables: string[]): string {
356
+ if (!this.bucket) return '';
357
+ let n = 0;
358
+ for (const table of tables) {
359
+ this.look(table);
360
+ n += this.writes.get(table) ?? 0;
361
+ }
362
+ return `${this.era}.${n}`;
363
+ }
364
+
365
+ /**
366
+ * A read just answered: keep its text if it is a startup read, or one kept
367
+ * before. `sentAt` is {@link stamp} from when it was sent; a write to its
368
+ * tables since then means the answer may already be old, and it is let go.
369
+ */
370
+ note(key: string, tables: string[], rows: string, u8: boolean, sentAt: string): void {
371
+ if (!this.bucket || sentAt !== this.stamp(tables)) return;
372
+ if (!this.known.has(key)) {
373
+ if (Date.now() - this.since > PAINT_CAPTURE_MS || this.known.size >= PAINT_MAX_KEYS) return;
374
+ this.known.add(key);
375
+ }
376
+ if (rows.length > PAINT_MAX_ENTRY_CHARS) return;
377
+ // `stamp` has just read every one of these marks.
378
+ const head = JSON.stringify([u8 ? 1 : 0, tables.map((table): PaintMark => [table, this.seen.get(table) ?? null])]);
379
+ this.entries.set(key, { tables, text: `${PAINT_FORMAT}${head}\n${rows}`, dirty: true });
380
+ this.link(key, tables);
381
+ this.timer ??= setTimeout(() => this.flush(), PAINT_FLUSH_MS);
382
+ }
383
+
384
+ /**
385
+ * This tab writes to `tables`: what was read from them is no longer what
386
+ * they hold. Called as the write is sent, and again with `done` once the
387
+ * store has answered it. The first call drops this tab's copies and fails
388
+ * its reads still on their way. The second only leaves a new mark: a tab
389
+ * that read between the two (it saw the first mark, the store had not yet
390
+ * taken the write) holds a copy that mark makes void, while this tab's own
391
+ * reads, queued behind its write and answered after it, are kept.
392
+ */
393
+ touch(tables: Iterable<string>, done = false): void {
394
+ if (!this.bucket) return;
395
+ const index = done ? null : this.index();
396
+ for (const table of tables) {
397
+ this.leave(table);
398
+ if (!index) continue;
399
+ this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
400
+ const keys = index.get(table);
401
+ if (!keys || keys.size === 0) continue;
402
+ for (const key of keys) {
403
+ this.entries.delete(key);
404
+ try {
405
+ localStorage.removeItem(this.name(key));
406
+ } catch {
407
+ /* ignore */
408
+ }
409
+ }
410
+ keys.clear();
411
+ }
412
+ }
413
+
414
+ /**
415
+ * Write what changed, newest reads first, up to the budget, and clear out
416
+ * what no longer stands: the budget is one for all tabs of the bucket.
417
+ */
418
+ flush(): void {
419
+ if (this.timer) clearTimeout(this.timer);
420
+ this.timer = null;
421
+ if (!this.bucket) return;
422
+ const known = this.byTable !== null;
423
+ const index = this.index();
424
+ if (known) this.readIndex();
425
+ try {
426
+ let used = 0;
427
+ const kept: Record<string, string[]> = {};
428
+ for (const [key, entry] of [...this.entries].reverse()) {
429
+ // Written to by another tab since: whatever sits under the key now is judged below.
430
+ if (!this.holds(paintHead(entry.text)?.marks ?? [])) {
431
+ this.entries.delete(key);
432
+ continue;
433
+ }
434
+ if (used + entry.text.length > this.maxChars) {
435
+ this.entries.delete(key);
436
+ localStorage.removeItem(this.name(key));
437
+ for (const keys of index.values()) keys.delete(key);
438
+ continue;
439
+ }
440
+ if (entry.dirty) {
441
+ try {
442
+ localStorage.setItem(this.name(key), entry.text);
443
+ entry.dirty = false;
444
+ } catch {
445
+ // No room for this one. It must not cost the others their place in the index.
446
+ this.entries.delete(key);
447
+ localStorage.removeItem(this.name(key));
448
+ for (const keys of index.values()) keys.delete(key);
449
+ continue;
450
+ }
451
+ }
452
+ used += entry.text.length;
453
+ kept[key] = entry.tables;
454
+ }
455
+ // Copies this tab does not hold: other tabs', earlier sessions' that this
456
+ // one never read again, and any the index lost track of (two tabs saving
457
+ // at once), which nothing else would ever let go of.
458
+ const others = new Set<string>();
459
+ for (const keys of index.values()) for (const key of keys) if (!(key in kept)) others.add(key);
460
+ // Without marks nothing says whether such a stray is still true: it goes.
461
+ const strays = new Set<string>();
462
+ for (const key of this.copies()) {
463
+ if (key in kept || others.has(key)) continue;
464
+ if (this.shared) others.add(key);
465
+ else strays.add(key);
466
+ }
467
+ for (const key of strays) localStorage.removeItem(this.name(key));
468
+ for (const key of others) {
469
+ const text = localStorage.getItem(this.name(key));
470
+ const head = text ? paintHead(text) : null;
471
+ if (!text || !head || !this.holds(head.marks) || used + text.length > this.maxChars) {
472
+ if (text) localStorage.removeItem(this.name(key));
473
+ for (const keys of index.values()) keys.delete(key);
474
+ continue;
475
+ }
476
+ used += text.length;
477
+ const tables = head.marks.map((mark) => mark[0]);
478
+ kept[key] = tables;
479
+ this.link(key, tables);
480
+ }
481
+ localStorage.setItem(`sp00ky.paint.${this.bucket}`, JSON.stringify(kept));
482
+ } catch {
483
+ // Out of quota, or no storage: painting from the cache is a bonus, not a need.
484
+ }
485
+ }
486
+
487
+ /** Forget everything kept for `bucket`. */
488
+ static drop(bucket: string): void {
489
+ try {
490
+ const prefix = `sp00ky.paint.${bucket}`;
491
+ const mine: string[] = [];
492
+ for (let i = 0; i < localStorage.length; i++) {
493
+ const key = localStorage.key(i);
494
+ if (key !== null && (key === prefix || key.startsWith(prefix + '.'))) mine.push(key);
495
+ }
496
+ for (const key of mine) localStorage.removeItem(key);
497
+ } catch {
498
+ /* ignore */
499
+ }
500
+ }
501
+ }
502
+
503
+ /** Every table a plan reads: its own and its relations'. */
504
+ function tablesOf(plan: QueryPlan): string[] {
505
+ const out = new Set<string>([plan.table]);
506
+ const walk = (relations: QueryPlan['relations']): void => {
507
+ for (const relation of relations ?? []) {
508
+ out.add(relation.table);
509
+ walk(relation.relations);
510
+ }
511
+ };
512
+ walk(plan.relations);
513
+ return [...out];
514
+ }
515
+
516
+ const encoder = new TextEncoder();
517
+ const decoder = new TextDecoder();
518
+
519
+ type RowsReply = { buf: ArrayBuffer | null; u8?: boolean };
520
+
521
+ const byIdsKey = (table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): string =>
522
+ hashKey('i' + JSON.stringify([table, ids.map(stableKey), opts?.select ?? null, opts?.orderBy ?? null]));
523
+
524
+ function parseRowText(text: string, u8: boolean): Row[] {
525
+ if (!u8) return JSON.parse(text) as Row[];
526
+ return JSON.parse(text, (_k, v) =>
527
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? fromBase64((v as { __u8: string }).__u8) : v
528
+ ) as Row[];
529
+ }
530
+ type OpenReply = { persisted: boolean; opfsError?: string; proto?: number; workerUrl?: string };
531
+
532
+ /** One write, with the table and key already resolved. */
533
+ export type WriteItem =
534
+ | { kind: 'upsert'; table: string; key: string; data: Row; mode: 'replace' | 'merge' }
535
+ | { kind: 'delete'; table: string; key: string }
536
+ | { kind: 'clear'; table: string };
537
+
538
+ /** The writes of a translated statement list; the table is the id's own. */
539
+ function itemsOf(ops: SqlOp[]): WriteItem[] {
540
+ const items: WriteItem[] = [];
541
+ for (const op of ops) {
542
+ if (op.kind === 'noop') continue;
543
+ if (op.kind === 'deleteAll') items.push({ kind: 'clear', table: op.table });
544
+ else if (op.kind === 'delete') items.push({ kind: 'delete', table: tableOf(op.id), key: stableKey(op.id) });
545
+ else if (op.kind === 'upsert') {
546
+ items.push({ kind: 'upsert', table: tableOf(op.id), key: stableKey(op.id), data: op.data, mode: op.mode });
547
+ } else throw new Error(`RowsCacheEngine: ${op.kind} is not a write`);
548
+ }
549
+ return items;
550
+ }
551
+
552
+ /**
553
+ * Serialize a batch of writes for the worker: every row's JSON text in one
554
+ * buffer, which is transferred, and one small tuple per op saying where its
555
+ * text lies. The text is what `SqliteCacheEngine` stores, byte for byte.
556
+ */
557
+ export function packWrites(items: WriteItem[]): { wire: WireOp[]; buf: ArrayBuffer | null; sync: boolean } {
558
+ const wire: WireOp[] = [];
559
+ let bytes = new Uint8Array(0);
560
+ let at = 0;
561
+ let sync = false;
562
+ const append = (text: string): [off: number, len: number] => {
563
+ // `encodeInto` needs room for the worst case, three bytes per UTF-16 unit.
564
+ const need = at + text.length * 3;
565
+ if (bytes.length < need) {
566
+ const grown = new Uint8Array(Math.max(need, bytes.length * 2, 1024));
567
+ grown.set(bytes.subarray(0, at));
568
+ bytes = grown;
569
+ }
570
+ const written = encoder.encodeInto(text, bytes.subarray(at)).written;
571
+ const off = at;
572
+ at += written;
573
+ return [off, written];
574
+ };
575
+ for (const op of items) {
576
+ const table = op.table;
577
+ if (ROWS_DURABLE_TABLES.has(table)) sync = true;
578
+ if (op.kind === 'clear') {
579
+ wire.push(['clear', table]);
580
+ continue;
581
+ }
582
+ const key = op.key;
583
+ if (op.kind === 'delete') {
584
+ wire.push(['del', table, key]);
585
+ continue;
586
+ }
587
+ const row: Row = { ...op.data, id: key };
588
+ const rv = Number(row._00_rv) || 0;
589
+ if (op.mode === 'replace') {
590
+ const text = serializeRow(row);
591
+ const [off, len] = append(text);
592
+ wire.push(['put', table, key, rv, text.includes('"__u8"') ? FLAG_U8 : 0, off, len]);
593
+ continue;
594
+ }
595
+ const { insert, patch } = serializeMergeRow(row);
596
+ const [off, len] = append(insert);
597
+ // The patch differs from the row only when a field is being cleared.
598
+ const [patchOff, patchLen] = patch === insert ? [0, 0] : append(patch);
599
+ wire.push(['merge', table, key, rv, insert.includes('"__u8"') ? FLAG_U8 : 0, off, len, patchOff, patchLen]);
600
+ }
601
+ return { wire, buf: at > 0 ? (bytes.buffer as ArrayBuffer) : null, sync };
602
+ }
603
+
604
+ /**
605
+ * Local cache backend on sp00ky's own row store (`rows-store.ts`), in a
606
+ * dedicated Worker (`rows-worker.ts`) on OPFS.
607
+ *
608
+ * It answers every verb the way {@link SqliteCacheEngine} does (same stored
609
+ * JSON, same filter and ordering rules, checked against real SQLite in
610
+ * `rows-exec.integration.test.ts`), so an app can switch between the two with
611
+ * `localEngine` alone. What differs is underneath: no SQL is rendered, rows
612
+ * cross the worker boundary as JSON text in a transferred buffer and are
613
+ * parsed once, on the side that reads them.
614
+ *
615
+ * It extends the SQLite engine for everything that is about the worker rather
616
+ * than about SQL: the serialized op queue, epoch fencing, bucket switches, the
617
+ * shared-tabs roles, the SurrealQL-vocabulary shim. Every method that renders
618
+ * SQL there is replaced here by a message to the row worker.
619
+ */
620
+ export class RowsCacheEngine extends SqliteCacheEngine {
621
+ override readonly engineKind = 'rows' as const;
622
+ /** The transport in use wraps a worker `prewarmRows` started. */
623
+ private adopted = false;
624
+ /** Drops what the adopted worker read ahead of the app, while any of it is still held. */
625
+ private forgetAhead: (() => void) | null = null;
626
+ /** Last-seen startup reads, for {@link peekByIds} / {@link peekSelect}. Off for a memory store. */
627
+ private paint: PaintCache | null =
628
+ this.useOpfs && this.config.paintCache !== false && typeof localStorage !== 'undefined' ? new PaintCache(1_000_000, this.shared) : null;
629
+
630
+ protected override createTransport(): SqliteTransport {
631
+ const pre = takePrewarmed();
632
+ if (pre?.failed) pre.worker.terminate();
633
+ this.adopted = pre !== null && !pre.failed;
634
+ const transport = new WorkerSqliteTransport(
635
+ this.logger,
636
+ this.adopted
637
+ ? () => pre!.worker
638
+ : // Same shape as the SQLite worker's URL: `.ts` for bundlers that build
639
+ // from source, rewritten to `./rows-worker.js` in the published build.
640
+ (this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' })))
641
+ );
642
+ // What the worker was asked ahead of the app, for as long as it holds true.
643
+ let ahead = this.adopted ? new ReadAhead(pre!, AHEAD_WAIT_MS) : null;
644
+ const forget = (): void => {
645
+ ahead?.drop();
646
+ ahead = null;
647
+ };
648
+ this.forgetAhead = forget;
649
+ if (ahead) background(setTimeout(forget, PAINT_CAPTURE_MS));
650
+ let opens = 0;
651
+ // Every open is checked: a worker from another release must not be talked to.
652
+ const call = transport.call.bind(transport);
653
+ transport.call = async <T>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> => {
654
+ if (type === 'open') {
655
+ // The prewarm's work stands only for the first open, of the store it
656
+ // was started on. Under a role's lock too (a shared-tabs leader): the
657
+ // worker keeps the store it has open, and until a follower's port is
658
+ // handed to it (`exposeClientPort`) nobody else writes through it.
659
+ const asked = payload as { dbName: string; useOpfs: boolean; workerLockName?: string; share?: boolean };
660
+ // A leader whose followers read the file themselves opens it for sharing.
661
+ if (asked.workerLockName && asked.useOpfs && this.config.followerReads === 'direct') {
662
+ asked.share = true;
663
+ }
664
+ const mine = ahead !== null && opens++ === 0 && asked.useOpfs && asked.dbName === pre!.bucket;
665
+ const answered = pre?.opened as (OpenReply & { ok?: boolean }) | undefined;
666
+ if (pre) pre.opened = undefined;
667
+ if (!mine) forget();
668
+ else if (answered?.persisted && !asked.workerLockName && !this.shared) {
669
+ // The worker answered this very open already: no need to ask again.
670
+ // Never with shared tabs: there the open is also what takes the
671
+ // role's lock, and what tells the worker that its store, which it
672
+ // would give up to another tab's leader, has an owner.
673
+ this.opened(transport, asked, answered);
674
+ return answered as T;
675
+ }
676
+ } else if (ahead && ROWS_AHEAD_OPS.has(type)) {
677
+ const early = ahead.take(type, payload);
678
+ const got = early ? await early : null;
679
+ if (got) {
680
+ const { id: _id, ok: _ok, error: _error, ...rest } = got;
681
+ return rest as T;
682
+ }
683
+ } else if (!ROWS_READ_OPS.has(type)) forget();
684
+ const reply = await call<T>(type, payload, transfer);
685
+ if (type === 'open') this.opened(transport, payload as { dbName: string; useOpfs: boolean }, reply as OpenReply);
686
+ return reply;
687
+ };
688
+ return transport;
689
+ }
690
+
691
+ private opened(transport: SqliteTransport, asked: { dbName: string; useOpfs: boolean }, reply: OpenReply): void {
692
+ if (reply.proto !== ROWS_PROTOCOL) {
693
+ transport.close('row worker speaks another protocol');
694
+ throw new Error(`RowsCacheEngine: worker protocol ${String(reply.proto)}, expected ${ROWS_PROTOCOL}`);
695
+ }
696
+ // Leave the next page load what it needs to start this worker ahead of the app.
697
+ try {
698
+ if (asked.useOpfs && reply.persisted && reply.workerUrl) {
699
+ const old = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
700
+ const record: PrewarmRecord = { url: reply.workerUrl, bucket: asked.dbName };
701
+ // The reads to ask ahead belong to a bucket: another user's are not kept.
702
+ if (old?.bucket === asked.dbName && Array.isArray(old.reads)) record.reads = old.reads;
703
+ localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify(record));
704
+ }
705
+ } catch {
706
+ // No localStorage (a worker, a locked-down page): nothing to prewarm from.
707
+ }
708
+ }
709
+
710
+ /**
711
+ * A prewarmed worker is a guess. When it turns out wrong (it failed to
712
+ * load, or it is another release's), drop it and connect again with a
713
+ * worker of our own.
714
+ */
715
+ override async connect(bucketId: string): Promise<void> {
716
+ // Known before the worker answers, so a peek can be asked for right away.
717
+ this.bucketId = bucketId;
718
+ this.paint?.start(bucketId);
719
+ try {
720
+ await super.connect(bucketId);
721
+ this.sessionBegan();
722
+ } catch (error) {
723
+ if (!this.adopted) throw error;
724
+ this.adopted = false;
725
+ try {
726
+ localStorage.removeItem(ROWS_PREWARM_KEY);
727
+ } catch {
728
+ /* ignore */
729
+ }
730
+ this.logger.warn(
731
+ { error, Category: 'sp00ky-client::RowsCacheEngine::connect' },
732
+ 'Prewarmed row worker was unusable; starting a fresh one'
733
+ );
734
+ await this.close();
735
+ await super.connect(bucketId);
736
+ this.sessionBegan();
737
+ }
738
+ }
739
+
740
+ override async switchBucket(bucketId: string): Promise<void> {
741
+ this.dropReader('bucket switch');
742
+ await super.switchBucket(bucketId);
743
+ this.paint?.start(bucketId);
744
+ this.sessionBegan();
745
+ }
746
+
747
+ /**
748
+ * The store is open. One that fell back to memory keeps no copies: its rows
749
+ * are gone with the tab, and it must not write over what a tab with the
750
+ * real store has kept.
751
+ */
752
+ private sessionBegan(): void {
753
+ if (this.useOpfs && this.storageHealth.status !== 'persistent') {
754
+ this.paint?.stop();
755
+ return;
756
+ }
757
+ this.beginStartupReads();
758
+ }
759
+
760
+ /** A follower reads through the leader's worker; one started ahead for this tab is not needed. */
761
+ override async adoptAttached(
762
+ dbPort: MessagePort,
763
+ snapshot: { bucketId: string; storageHealth: StorageHealth },
764
+ onPortDead: (reason: string) => void
765
+ ): Promise<void> {
766
+ takePrewarmed()?.worker.terminate();
767
+ this.dropReader('attaching to a leader');
768
+ const durable = this.useOpfs && snapshot.storageHealth.status === 'persistent';
769
+ // Before the port is in use, as in `connect`: a peek needs no store.
770
+ if (durable) this.paint?.adopt(snapshot.bucketId);
771
+ await super.adoptAttached(dbPort, snapshot, onPortDead);
772
+ this.sessionBegan();
773
+ if (this.config.followerReads === 'direct' && durable) await this.startReader(snapshot.bucketId);
774
+ }
775
+
776
+ // ---- a follower's own reader ------------------------------------------------
777
+ // With `followerReads: 'direct'` a follower answers its reads from a worker
778
+ // of its own, on a reader of the store's file (`RowStore` reader mode). The
779
+ // reader is an optimization and nothing depends on it: when it cannot be
780
+ // had, or fails, the read goes to the leader as it would have.
781
+
782
+ /** The follower's reader worker, while this engine follows and has one. */
783
+ private reader: SqliteTransport | null = null;
784
+
785
+ private async startReader(bucketId: string): Promise<void> {
786
+ let transport: SqliteTransport | null = null;
787
+ // Every change of role bumps the epoch: the same epoch later means still this follower.
788
+ const asFollower = this.epoch;
789
+ try {
790
+ transport = new WorkerSqliteTransport(
791
+ this.logger,
792
+ this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' }))
793
+ );
794
+ const reply = await transport.call<OpenReply>('open', {
795
+ dbName: bucketId,
796
+ useOpfs: true,
797
+ reader: true,
798
+ openOptions: { maxAttempts: 2, disallowMemoryFallback: true },
799
+ });
800
+ if (reply.proto !== ROWS_PROTOCOL || !reply.persisted) throw new Error('reader worker is not this release\'s');
801
+ // The role may have moved on while the worker started.
802
+ if (this.epoch !== asFollower || this.bucketId !== bucketId) throw new Error('no longer a follower of this store');
803
+ this.reader = transport;
804
+ } catch (error) {
805
+ transport?.close('reader unavailable');
806
+ this.logger.info(
807
+ { error: String(error), Category: 'sp00ky-client::RowsCacheEngine::reader' },
808
+ 'No direct reads for this follower tab; it reads through the leader'
809
+ );
810
+ }
811
+ }
812
+
813
+ private dropReader(reason: string): void {
814
+ const reader = this.reader;
815
+ this.reader = null;
816
+ reader?.close(reason);
817
+ }
818
+
819
+ /** True while this follower answers its reads from the store's file itself. */
820
+ get readsDirectly(): boolean {
821
+ return this.reader !== null;
822
+ }
823
+
824
+ protected override rawCall<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
825
+ const reader = this.reader;
826
+ if (!reader || !ROWS_READER_OPS.has(type)) return super.rawCall<T>(type, payload, transfer);
827
+ let timer: ReturnType<typeof setTimeout> | undefined;
828
+ const late = new Promise<never>((_resolve, reject) => {
829
+ timer = setTimeout(() => reject(new Error('reader timed out')), READER_OP_TIMEOUT_MS);
830
+ });
831
+ return Promise.race([reader.call<T>(type, payload), late])
832
+ .catch((error: unknown) => {
833
+ if (this.reader === reader) {
834
+ this.dropReader('read failed');
835
+ this.logger.warn(
836
+ { error: String(error), type, Category: 'sp00ky-client::RowsCacheEngine::reader' },
837
+ 'Direct read failed; this tab reads through the leader from here on'
838
+ );
839
+ }
840
+ return super.rawCall<T>(type, payload, transfer);
841
+ })
842
+ .finally(() => clearTimeout(timer));
843
+ }
844
+
845
+ /**
846
+ * A leader's store is this tab's own worker, as alone: one started ahead of
847
+ * the app is adopted (`createTransport`), and replaced when it turns out to
848
+ * be another release's.
849
+ */
850
+ override async adoptOwner(...args: Parameters<SqliteCacheEngine['adoptOwner']>): ReturnType<SqliteCacheEngine['adoptOwner']> {
851
+ this.dropReader('becoming the leader');
852
+ this.paint?.adopt(args[0]);
853
+ let health: StorageHealth;
854
+ try {
855
+ health = await super.adoptOwner(...args);
856
+ } catch (error) {
857
+ // Only when the worker itself is the trouble: a lock or a file that
858
+ // cannot be had would fail a second worker the same way.
859
+ if (!this.adopted || !String(error).includes('worker protocol')) throw error;
860
+ this.adopted = false;
861
+ try {
862
+ localStorage.removeItem(ROWS_PREWARM_KEY);
863
+ } catch {
864
+ /* ignore */
865
+ }
866
+ this.logger.warn(
867
+ { error, Category: 'sp00ky-client::RowsCacheEngine::adoptOwner' },
868
+ 'Prewarmed row worker was unusable; starting a fresh one'
869
+ );
870
+ health = await super.adoptOwner(...args);
871
+ }
872
+ this.sessionBegan();
873
+ return health;
874
+ }
875
+
876
+ /** Another tab is about to write through this worker: what it read ahead of the app no longer stands. */
877
+ override async exposeClientPort(clientId: string, port: MessagePort): Promise<void> {
878
+ this.forgetAhead?.();
879
+ return super.exposeClientPort(clientId, port);
880
+ }
881
+
882
+ override async releaseOwnership(): Promise<void> {
883
+ this.dropReader('releasing the store');
884
+ return super.releaseOwnership();
885
+ }
886
+
887
+ override onLeaderLost(reason: string): void {
888
+ // The file is still there and still whole, but writes have nowhere to go:
889
+ // read through the next leader, with a reader started against it.
890
+ this.dropReader('leader lost');
891
+ super.onLeaderLost(reason);
892
+ }
893
+
894
+ override async close(): Promise<void> {
895
+ this.dropReader('engine closed');
896
+ return super.close();
897
+ }
898
+
899
+ /** Tables need no creating: a table is the rows written to it. */
900
+ protected override async ensureTable(): Promise<void> {}
901
+
902
+ // ---- read ahead -----------------------------------------------------------
903
+ // The reads of a session's first seconds are saved, and the next page load's
904
+ // prewarm asks them again before the app exists (`rows-prewarm.ts`).
905
+
906
+ private startupReads: Map<string, [string, unknown]> | null = null;
907
+ private startupBytes = 0;
908
+ private startupUntil = 0;
909
+ private startupTimer: ReturnType<typeof setTimeout> | null = null;
910
+ private startupHooked = false;
911
+ /** The bucket whose startup reads were last begun. */
912
+ private startupBucket: string | null = null;
913
+
914
+ private beginStartupReads(): void {
915
+ if (!this.useOpfs || typeof localStorage === 'undefined') return;
916
+ // With shared tabs a tab is handed its store again with every change of
917
+ // role. Only the first time is a session's start.
918
+ if (this.shared && this.startupBucket === this.bucketId) return;
919
+ this.startupBucket = this.bucketId;
920
+ if (!this.startupHooked && typeof addEventListener === 'function') {
921
+ // localStorage is synchronous, so the list can still be saved as the page goes.
922
+ addEventListener('pagehide', () => this.saveStartupReads());
923
+ this.startupHooked = true;
924
+ }
925
+ this.startupReads = new Map();
926
+ this.startupBytes = 0;
927
+ this.startupUntil = performance.now() + PAINT_CAPTURE_MS;
928
+ if (this.startupTimer) clearTimeout(this.startupTimer);
929
+ this.startupTimer = background(setTimeout(() => this.saveStartupReads(), PAINT_CAPTURE_MS + 50));
930
+ }
931
+
932
+ private noteStartupRead(type: string, payload: unknown, replyBytes: number): void {
933
+ const reads = this.startupReads;
934
+ if (!reads || performance.now() > this.startupUntil || !ROWS_AHEAD_OPS.has(type)) return;
935
+ if (reads.size >= AHEAD_MAX_READS || replyBytes > AHEAD_MAX_REPLY_BYTES) return;
936
+ if (this.startupBytes + replyBytes > AHEAD_MAX_TOTAL_BYTES || !jsonSafe(payload)) return;
937
+ const key = aheadKey(type, payload);
938
+ if (key.length > AHEAD_MAX_REQUEST_CHARS || reads.has(key)) return;
939
+ reads.set(key, [type, payload]);
940
+ this.startupBytes += replyBytes;
941
+ }
942
+
943
+ /** Leave this session's startup reads for the next page load. Also runs as the page goes. */
944
+ private saveStartupReads(): void {
945
+ const reads = this.startupReads;
946
+ if (!reads) return;
947
+ try {
948
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
949
+ if (!saved?.url || saved.bucket !== this.bucketId) return;
950
+ localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify({ url: saved.url, bucket: saved.bucket, reads: [...reads.values()] }));
951
+ } catch {
952
+ // No storage, or no room: the next load asks nothing ahead.
953
+ }
954
+ }
955
+
956
+ /** A read that answers rows. `paint` names it for the paint cache, when it is worth keeping. */
957
+ private async rows(type: string, payload: unknown, paint?: { key: string; tables: string[] }): Promise<Row[]> {
958
+ const sentAt = paint && this.paint ? this.paint.stamp(paint.tables) : '';
959
+ const reply = await this.call<RowsReply>(type, payload);
960
+ this.noteStartupRead(type, payload, reply.buf?.byteLength ?? 0);
961
+ if (!reply.buf) return [];
962
+ const text = decoder.decode(new Uint8Array(reply.buf));
963
+ if (paint) this.paint?.note(paint.key, paint.tables, text, reply.u8 === true, sentAt);
964
+ return parseRowText(text, reply.u8 === true);
965
+ }
966
+
967
+ // ---- reads ---------------------------------------------------------------
968
+
969
+ private selectPayload(plan: QueryPlan, params: Record<string, unknown>): { plan: QueryPlan; params: Record<string, unknown> } {
970
+ // Class instances (RecordId) do not survive structured clone; see the
971
+ // SQLite engine's `select` for why the KEYS of `params` must all stay.
972
+ const normParams: Record<string, unknown> = {};
973
+ for (const [k, v] of Object.entries(params)) normParams[k] = toCloneSafe(v);
974
+ return { plan: normalizePlanForClone(plan), params: normParams };
975
+ }
976
+
977
+ /**
978
+ * The paint cache's name for a select. A caller that reads the same thing
979
+ * again and again under changing arguments (a query whose id set moves)
980
+ * names it itself with `paintKey`, so the copy kept is always its latest
981
+ * answer; without one a read is told apart by its plan and parameters.
982
+ */
983
+ private selectKey(payload: unknown, opts?: { paintKey?: string }): string {
984
+ return opts?.paintKey === undefined ? hashKey('s' + JSON.stringify(payload)) : hashKey('q' + opts.paintKey);
985
+ }
986
+
987
+ override async select(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Promise<Row[]> {
988
+ const payload = this.selectPayload(plan, params);
989
+ return this.rows('select', payload, this.paint ? { key: this.selectKey(payload, opts), tables: tablesOf(plan) } : undefined);
990
+ }
991
+
992
+ /**
993
+ * What `select(plan, params)` answered the last time the app asked at
994
+ * startup, synchronously, or `null`. Available as soon as `connect` was
995
+ * CALLED (or a role was handed over, or `expectBucket` said which bucket):
996
+ * it reads localStorage, not the store. Paint from it, then run the real
997
+ * `select`, which is the answer. A copy is not handed out once any tab has
998
+ * written to a table it read (see {@link PaintCache}).
999
+ */
1000
+ peekSelect(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Row[] | null {
1001
+ if (!this.paint) return null;
1002
+ // A named read needs no payload to find its copy.
1003
+ const payload = opts?.paintKey === undefined ? this.selectPayload(plan, params) : null;
1004
+ return this.paint.get(this.selectKey(payload, opts), fromBase64);
1005
+ }
1006
+
1007
+ /** See `LocalStore.expectBucket`. */
1008
+ expectBucket(bucketId: string): void {
1009
+ this.paint?.expect(bucketId);
1010
+ }
1011
+
1012
+ /** {@link peekSelect} for `selectByIds`. */
1013
+ peekByIds(table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): Row[] | null {
1014
+ return this.paint?.get(byIdsKey(table, ids, opts), fromBase64) ?? null;
1015
+ }
1016
+
1017
+ override async fetchRelation(req: RelationFetch): Promise<Row[]> {
1018
+ return this.rows('relation', {
1019
+ table: req.table,
1020
+ matchField: req.matchField,
1021
+ keys: req.keys.map(stableKey),
1022
+ where: normalizeWhereForClone(req.where),
1023
+ orderBy: req.orderBy,
1024
+ select: req.select,
1025
+ });
1026
+ }
1027
+
1028
+ override async selectByIds(
1029
+ table: string,
1030
+ ids: Id[],
1031
+ opts?: { select?: string[]; orderBy?: OrderBy }
1032
+ ): Promise<Row[]> {
1033
+ if (ids.length === 0) return [];
1034
+ return this.rows(
1035
+ 'by-ids',
1036
+ { table, ids: ids.map(stableKey), select: opts?.select, orderBy: opts?.orderBy },
1037
+ this.paint ? { key: byIdsKey(table, ids, opts), tables: [table] } : undefined
1038
+ );
1039
+ }
1040
+
1041
+ override async getById(table: string, id: Id): Promise<Row | null> {
1042
+ return parseRowBytes<Row | null>(await this.call<RowsReply>('get', { table, id: stableKey(id) }), fromBase64);
1043
+ }
1044
+
1045
+ override async scanVersions(tables: string[]): Promise<Record<string, [string, number][]>> {
1046
+ return (await this.call<{ versions: Record<string, [string, number][]> }>('versions', { tables })).versions;
1047
+ }
1048
+
1049
+ /**
1050
+ * See `sqlite-column-reset.ts`. The recorded column sets live in one raw row
1051
+ * of `_00_schema`, which no row read ever returns.
1052
+ */
1053
+ override async resetChangedTables(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]> {
1054
+ const { bytes } = await this.call<{ bytes: ArrayBuffer | null }>('blob-get', { table: SCHEMA_TABLE, key: COLUMNS_ROW_ID });
1055
+ let stored: Record<string, string> | null = null;
1056
+ try {
1057
+ if (bytes) stored = JSON.parse(decoder.decode(new Uint8Array(bytes))) as Record<string, string>;
1058
+ } catch {
1059
+ stored = null;
1060
+ }
1061
+ const tables = await this.listTables();
1062
+ const plan = planColumnReset(stored, fingerprints, new Set(tables), keep);
1063
+ if (plan.statements.length === 0) return plan.changed;
1064
+ this.paint?.touch(plan.changed);
1065
+ try {
1066
+ if (plan.changed.length > 0) await this.call('reset-versions', { tables: plan.changed, keep: [...keep] });
1067
+ } finally {
1068
+ this.paint?.touch(plan.changed, true);
1069
+ }
1070
+ // Recorded last: a tab that dies between the two redoes the reset, which is harmless.
1071
+ const body = encoder.encode(JSON.stringify(fingerprints));
1072
+ const buf = body.buffer as ArrayBuffer;
1073
+ await this.call(
1074
+ 'write',
1075
+ { ops: [['put', SCHEMA_TABLE, COLUMNS_ROW_ID, 0, FLAG_RAW, 0, body.length]] satisfies WireOp[], buf, sync: false },
1076
+ [buf]
1077
+ );
1078
+ return plan.changed;
1079
+ }
1080
+
1081
+ override async getSnapshot(key: string): Promise<StoredSnapshot | null> {
1082
+ const { bytes, meta } = await this.call<{ bytes: ArrayBuffer | null; meta: string | null }>('blob-get', {
1083
+ table: SNAPSHOT_TABLE,
1084
+ key,
1085
+ });
1086
+ if (!bytes || !meta) return null;
1087
+ try {
1088
+ return { bytes: new Uint8Array(bytes), meta: JSON.parse(meta) as SnapshotMeta };
1089
+ } catch {
1090
+ return null;
1091
+ }
1092
+ }
1093
+
1094
+ override async putSnapshot(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void> {
1095
+ // A copy, so the transfer does not take the caller's buffer away.
1096
+ const buf = bytes.slice().buffer as ArrayBuffer;
1097
+ await this.call('blob-put', { table: SNAPSHOT_TABLE, key, bytes: buf, meta: JSON.stringify(meta) }, [buf]);
1098
+ }
1099
+
1100
+ override async deleteSnapshot(key: string): Promise<void> {
1101
+ await this.call('blob-del', { table: SNAPSHOT_TABLE, key });
1102
+ }
1103
+
1104
+ // ---- writes --------------------------------------------------------------
1105
+
1106
+ override async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
1107
+ await this.write([{ kind: 'upsert', table, key: stableKey(id), data, mode }]);
1108
+ }
1109
+
1110
+ override async delete(table: string, id: Id): Promise<void> {
1111
+ await this.write([{ kind: 'delete', table, key: stableKey(id) }]);
1112
+ }
1113
+
1114
+ /** One message, one atomic batch in the store, however many rows. */
1115
+ private async write(items: WriteItem[]): Promise<void> {
1116
+ const { wire, buf, sync } = packWrites(items);
1117
+ if (wire.length === 0) return;
1118
+ const tables = new Set(items.map((item) => item.table));
1119
+ this.paint?.touch(tables);
1120
+ try {
1121
+ await this.call('write', { ops: wire, buf, sync }, buf ? [buf] : undefined);
1122
+ } finally {
1123
+ // Whether or not it was taken: other tabs are told once more, now that it is over.
1124
+ this.paint?.touch(tables, true);
1125
+ }
1126
+ }
1127
+
1128
+ protected override runWriteBatch(ops: SqlOp[]): Promise<void> {
1129
+ return this.write(itemsOf(ops));
1130
+ }
1131
+
1132
+ protected override async rawSelectTable(
1133
+ table: string,
1134
+ where?: WhereNode[],
1135
+ orderBy?: OrderBy,
1136
+ window?: { limit?: number; start?: number }
1137
+ ): Promise<Row[]> {
1138
+ return this.rows('select-table', {
1139
+ table,
1140
+ where: normalizeWhereForClone(where),
1141
+ orderBy,
1142
+ limit: window?.limit,
1143
+ start: window?.start,
1144
+ });
1145
+ }
1146
+
1147
+ protected override async countRows(table: string, where?: WhereNode[]): Promise<number> {
1148
+ return (await this.call<{ n: number }>('count', { table, where: normalizeWhereForClone(where) })).n;
1149
+ }
1150
+
1151
+ protected override async listTables(): Promise<string[]> {
1152
+ return (await this.call<{ tables: string[] }>('tables')).tables;
1153
+ }
1154
+
1155
+ protected override async deleteAllRows(table: string): Promise<void> {
1156
+ await this.write([{ kind: 'clear', table }]);
1157
+ }
1158
+
1159
+ // ---- housekeeping --------------------------------------------------------
1160
+
1161
+ override async getStorageDiagnostics(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics> {
1162
+ const diag: EngineStorageDiagnostics = {
1163
+ engine: 'rows',
1164
+ bucketId: this.bucketId,
1165
+ useOpfs: this.useOpfs,
1166
+ workerSelectConfigured: true,
1167
+ workerSelectEffective: true,
1168
+ };
1169
+ try {
1170
+ const { stats, tableCounts } = await this.call<{
1171
+ stats: StoreStats;
1172
+ tableCounts?: { table: string; rows: number }[];
1173
+ }>('diag', { tableCounts: opts?.tableCounts === true });
1174
+ diag.dbSizeBytes = stats.fileBytes;
1175
+ diag.freelistBytes = stats.garbageBytes;
1176
+ if (tableCounts) diag.tableCounts = tableCounts.filter((t) => t.table !== SNAPSHOT_TABLE);
1177
+ } catch (e) {
1178
+ diag.error = e instanceof Error ? e.message : String(e);
1179
+ }
1180
+ return diag;
1181
+ }
1182
+
1183
+ /** See `LocalStore.dropBucket`. Fails harmlessly while a worker holds the files. */
1184
+ override async dropBucket(bucketId: string): Promise<void> {
1185
+ if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
1186
+ PaintCache.drop(bucketId);
1187
+ try {
1188
+ // Nothing to start ahead for a store that is gone.
1189
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
1190
+ if (saved?.bucket === bucketId) localStorage.removeItem(ROWS_PREWARM_KEY);
1191
+ } catch {
1192
+ /* no storage */
1193
+ }
1194
+ const storage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
1195
+ if (!storage?.getDirectory) return;
1196
+ const root = await storage.getDirectory();
1197
+ try {
1198
+ await root.removeEntry(bucketDirName(bucketId), { recursive: true });
1199
+ } catch (error) {
1200
+ if ((error as DOMException)?.name !== 'NotFoundError') throw error;
1201
+ }
1202
+ }
1203
+ }