@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,1584 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import { RecordId } from 'surrealdb';
3
+ import type { QueryPlan } from '@spooky-sync/query-builder';
4
+ import {
5
+ PaintCache,
6
+ RowsCacheEngine,
7
+ ROWS_DURABLE_TABLES,
8
+ ROWS_PREWARM_KEY,
9
+ ROWS_PREWARM_SNIPPET,
10
+ packWrites,
11
+ prewarmRows,
12
+ } from './rows-cache-engine';
13
+ import { createLocalEngine } from './engine-factory';
14
+ import { FakeRowsWorker, inProcessRows, type RowsDisks, type RowsHost } from './rows-transport.fixture';
15
+ import { ROWS_CLIENT_OPS, maintenance } from './rows-exec';
16
+ import type { StoreStats } from './rows-store';
17
+ import { columnFingerprints } from './sqlite-column-reset';
18
+ import { surql } from '../../utils/surql';
19
+ import type { Row } from './cache-engine';
20
+
21
+ const logger = {
22
+ info() {},
23
+ warn() {},
24
+ error() {},
25
+ debug() {},
26
+ trace() {},
27
+ child() {
28
+ return logger;
29
+ },
30
+ } as any;
31
+
32
+ let engine: RowsCacheEngine;
33
+ let host: RowsHost;
34
+
35
+ async function boot(disks?: RowsDisks, bucket = 'user_a'): Promise<void> {
36
+ engine = new RowsCacheEngine({ store: 'indexeddb' } as any, logger, { useOpfs: true });
37
+ host = inProcessRows(engine, disks);
38
+ await engine.connect(bucket);
39
+ }
40
+
41
+ beforeEach(() => boot());
42
+
43
+ describe('RowsCacheEngine: verbs', () => {
44
+ it('is what `localEngine: "rows"` builds', () => {
45
+ const built = createLocalEngine('rows', { store: 'indexeddb' } as any, logger);
46
+ expect(built).toBeInstanceOf(RowsCacheEngine);
47
+ expect(built.engineKind).toBe('rows');
48
+ expect(built.usesSurqlSchema).toBe(false);
49
+ });
50
+
51
+ it('writes, reads, merges and deletes rows', async () => {
52
+ await engine.upsert('game', 'game:a', { title: 'Alpha', moves: 3, _00_rv: 2 }, 'replace');
53
+ await engine.upsert('game', new RecordId('game', 'b'), { title: 'Beta', white: new RecordId('user', '1') }, 'replace');
54
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', title: 'Alpha', moves: 3, _00_rv: 2 });
55
+ // A record link is stored, and read back, as its `table:id` string.
56
+ expect(await engine.getById('game', new RecordId('game', 'b'))).toEqual({ id: 'game:b', title: 'Beta', white: 'user:1' });
57
+ expect(await engine.getById('game', 'game:none')).toBeNull();
58
+
59
+ await engine.upsert('game', 'game:a', { moves: 4, extra: { k: 1 }, title: undefined }, 'merge');
60
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', moves: 4, _00_rv: 2, extra: { k: 1 } });
61
+
62
+ await engine.delete('game', 'game:a');
63
+ expect(await engine.getById('game', 'game:a')).toBeNull();
64
+ expect(await engine.selectByIds('game', ['game:a', 'game:b'])).toEqual([{ id: 'game:b', title: 'Beta', white: 'user:1' }]);
65
+ });
66
+
67
+ it('keeps bytes as bytes', async () => {
68
+ const state = new Uint8Array([1, 2, 3, 254, 255]);
69
+ await engine.upsert('doc', 'doc:1', { state, sdk: state.slice().buffer, n: 1 }, 'replace');
70
+ const row = (await engine.getById('doc', 'doc:1'))!;
71
+ expect(row.state).toEqual(state);
72
+ // The SDK hands bytes over as an ArrayBuffer; they come back as a Uint8Array.
73
+ expect(row.sdk).toEqual(state);
74
+ expect((await engine.selectByIds('doc', ['doc:1']))[0].state).toEqual(state);
75
+ expect((await engine.select({ table: 'doc' }))[0].state).toEqual(state);
76
+ });
77
+
78
+ it('selects by plan with record ids in the filter, the params and the window', async () => {
79
+ await engine.execute(
80
+ surql.seal(surql.tx([surql.upsertMerge('a', 'da'), surql.upsertMerge('b', 'db'), surql.upsertMerge('c', 'dc')])),
81
+ {
82
+ a: new RecordId('game', 'a'),
83
+ da: { white: new RecordId('user', '1'), moves: 10 },
84
+ b: new RecordId('game', 'b'),
85
+ db: { white: new RecordId('user', '2'), moves: 20 },
86
+ c: new RecordId('game', 'c'),
87
+ dc: { white: new RecordId('user', '1'), moves: 30 },
88
+ }
89
+ );
90
+ const byWhite: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: new RecordId('user', '1') }] };
91
+ expect((await engine.select(byWhite)).map((r) => r.id)).toEqual(['game:a', 'game:c']);
92
+ const byParam: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: undefined, paramRef: 'who' }] };
93
+ expect((await engine.select(byParam, { who: new RecordId('user', '2') })).map((r) => r.id)).toEqual(['game:b']);
94
+ const window: QueryPlan = { table: 'game', ids: [new RecordId('game', 'c'), 'game:a'], select: ['moves'] };
95
+ expect(await engine.select(window)).toEqual([
96
+ { id: 'game:c', moves: 30 },
97
+ { id: 'game:a', moves: 10 },
98
+ ]);
99
+ });
100
+
101
+ it('resolves relations in one round trip', async () => {
102
+ await engine.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
103
+ await engine.upsert('game', 'game:a', { white: 'user:1' }, 'replace');
104
+ await engine.upsert('comment', 'comment:1', { game: 'game:a', rank: 2 }, 'replace');
105
+ await engine.upsert('comment', 'comment:2', { game: 'game:a', rank: 1 }, 'replace');
106
+ host.calls.length = 0;
107
+ const rows = await engine.select({
108
+ table: 'game',
109
+ relations: [
110
+ { alias: 'white', table: 'user', cardinality: 'one', foreignKeyField: 'white' },
111
+ { alias: 'comments', table: 'comment', cardinality: 'many', foreignKeyField: 'game', orderBy: [['rank', 'asc']] },
112
+ ],
113
+ });
114
+ expect(rows).toEqual([
115
+ {
116
+ id: 'game:a',
117
+ white: { id: 'user:1', name: 'Ada' },
118
+ comments: [
119
+ { id: 'comment:2', game: 'game:a', rank: 1 },
120
+ { id: 'comment:1', game: 'game:a', rank: 2 },
121
+ ],
122
+ },
123
+ ]);
124
+ expect(host.calls.map((c) => c.type)).toEqual(['select']);
125
+ expect(await engine.fetchRelation({ table: 'comment', matchField: 'game', keys: [new RecordId('game', 'a')], orderBy: [['rank', 'desc']] })).toEqual([
126
+ { id: 'comment:1', game: 'game:a', rank: 2 },
127
+ { id: 'comment:2', game: 'game:a', rank: 1 },
128
+ ]);
129
+ });
130
+
131
+ it('applies RFC 6902 patches and runs a transaction of verbs', async () => {
132
+ await engine.upsert('game', 'game:a', { tags: ['x'], n: 1 }, 'replace');
133
+ await engine.patch('game', 'game:a', [
134
+ { op: 'add', path: '/tags/-', value: 'y' },
135
+ { op: 'replace', path: '/n', value: 2 },
136
+ ]);
137
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', tags: ['x', 'y'], n: 2 });
138
+ await engine.transaction(async (tx) => {
139
+ await tx.upsert('game', 'game:b', { n: 1 }, 'replace');
140
+ await tx.patch('game', 'game:b', [{ op: 'add', path: '/m', value: true }]);
141
+ await tx.delete('game', 'game:a');
142
+ });
143
+ expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:b', n: 1, m: true }]);
144
+ });
145
+ });
146
+
147
+ describe('RowsCacheEngine: the SurrealQL statements the client emits', () => {
148
+ it('creates a row and its outbox entry in one atomic, flushed batch', async () => {
149
+ const file = host.disks.get('user_a')!.a;
150
+ const flushes = file.flushes;
151
+ host.calls.length = 0;
152
+ const sealed = surql.seal(
153
+ surql.tx([
154
+ surql.createSet('id', [
155
+ { key: 'provider', variable: 'data_provider' },
156
+ { key: 'username', variable: 'data_username' },
157
+ ]),
158
+ surql.createMutation('create', 'mid', 'id', 'data'),
159
+ ]),
160
+ { resultIndex: 0 }
161
+ );
162
+ const created = (await engine.execute(sealed, {
163
+ id: new RecordId('connection', 'CONN_abc'),
164
+ mid: new RecordId('_00_pending_mutations', '1'),
165
+ data_provider: 'chesscom',
166
+ data_username: 'hikaru',
167
+ data: { provider: 'chesscom', username: 'hikaru' },
168
+ })) as unknown as Row;
169
+ expect(created.id).toBe('connection:CONN_abc');
170
+ expect(created.provider).toBe('chesscom');
171
+ // One message for both rows, and the outbox makes it a flushed write.
172
+ expect(host.calls.map((c) => c.type)).toEqual(['write']);
173
+ expect(host.calls[0].payload.sync).toBe(true);
174
+ expect(host.calls[0].payload.ops.length).toBe(2);
175
+ expect(file.flushes).toBe(flushes + 1);
176
+ expect(await engine.getById('connection', 'connection:CONN_abc')).toEqual({
177
+ id: 'connection:CONN_abc',
178
+ provider: 'chesscom',
179
+ username: 'hikaru',
180
+ });
181
+ const [pending] = await engine.query<[Row[]]>('SELECT * FROM _00_pending_mutations ORDER BY id ASC');
182
+ expect(pending.length).toBe(1);
183
+ expect(pending[0].id).toBe('_00_pending_mutations:1');
184
+ });
185
+
186
+ it('does not flush a write that only copies server state', async () => {
187
+ const file = host.disks.get('user_a')!.a;
188
+ const flushes = file.flushes;
189
+ await engine.execute(surql.seal(surql.tx([surql.upsertMerge('id', 'data')])), { id: new RecordId('game', 'a'), data: { n: 1 } });
190
+ expect(host.calls.at(-1)!.payload.sync).toBe(false);
191
+ expect(file.flushes).toBe(flushes);
192
+ expect(ROWS_DURABLE_TABLES.has('_00_pending_mutations')).toBe(true);
193
+ });
194
+
195
+ it('answers the raw selects, counts and INFO', async () => {
196
+ for (let i = 0; i < 6; i++) {
197
+ await engine.upsert('game_insight', `game_insight:${i}`, { tag: i % 2 ? 'odd' : 'even', n: i }, 'replace');
198
+ }
199
+ const [all] = await engine.query<[Row[]]>('SELECT * FROM game_insight');
200
+ expect(all.map((r) => r.n)).toEqual([0, 1, 2, 3, 4, 5]);
201
+ const [window] = await engine.query<[Row[]]>('SELECT * FROM game_insight LIMIT 2 START 3');
202
+ expect(window.map((r) => r.n)).toEqual([3, 4]);
203
+ const [filtered] = await engine.query<[Row[]]>("SELECT * FROM game_insight WHERE tag = 'odd' ORDER BY n DESC");
204
+ expect(filtered.map((r) => r.n)).toEqual([5, 3, 1]);
205
+ const [values] = await engine.query<[unknown[]]>('SELECT VALUE n FROM game_insight WHERE n >= 4');
206
+ expect(values).toEqual([4, 5]);
207
+ const [fields] = await engine.query<[Row[]]>('SELECT tag, n FROM game_insight LIMIT 1');
208
+ expect(fields).toEqual([{ id: 'game_insight:0', tag: 'even', n: 0 }]);
209
+ expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM game_insight GROUP ALL'))[0]).toEqual([{ count: 6 }]);
210
+ expect((await engine.query<[{ count: number }[]]>("SELECT count() FROM game_insight WHERE tag = 'odd' GROUP ALL"))[0]).toEqual([{ count: 3 }]);
211
+ expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM empty GROUP ALL'))[0]).toEqual([{ count: 0 }]);
212
+ const [info] = await engine.query<[{ tables: Record<string, string> }]>('INFO FOR DB');
213
+ expect(Object.keys(info.tables)).toEqual(['game_insight']);
214
+
215
+ const [one] = await engine.query<[Row | null]>('SELECT * FROM ONLY $id', { id: new RecordId('game_insight', '2') });
216
+ expect(one).toEqual({ id: 'game_insight:2', tag: 'even', n: 2 });
217
+ const [some] = await engine.query<[Row[]]>('SELECT * FROM $ids', {
218
+ ids: [new RecordId('game_insight', '5'), new RecordId('game_insight', 'x'), new RecordId('game_insight', '1')],
219
+ });
220
+ expect(some.map((r) => r.n)).toEqual([5, 1]);
221
+
222
+ await engine.query('DELETE $id', { id: new RecordId('game_insight', '0') });
223
+ expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM game_insight GROUP ALL'))[0]).toEqual([{ count: 5 }]);
224
+ await engine.query('DELETE game_insight');
225
+ expect((await engine.query<[Row[]]>('SELECT * FROM game_insight'))[0]).toEqual([]);
226
+ });
227
+
228
+ it('runs a LET / UPDATE SET / RETURN transaction against the stored row', async () => {
229
+ await engine.upsert('counter', 'counter:1', { n: 5, label: 'old' }, 'replace');
230
+ const res = await engine.query<unknown[]>(
231
+ 'BEGIN TRANSACTION; LET $updated = (UPDATE $id SET n += $by, label = $label); RETURN { target: $updated }; COMMIT TRANSACTION;',
232
+ { id: new RecordId('counter', '1'), by: 3, label: 'new' }
233
+ );
234
+ expect(res.at(-1)).toEqual({ target: { id: 'counter:1', n: 8, label: 'new' } });
235
+ expect(await engine.getById('counter', 'counter:1')).toEqual({ id: 'counter:1', n: 8, label: 'new' });
236
+ });
237
+
238
+ it('refuses a write under a stale epoch', async () => {
239
+ const epoch = engine.epoch;
240
+ await engine.switchBucket('user_b');
241
+ await expect(engine.query('DELETE game', {}, { epoch })).rejects.toThrow();
242
+ });
243
+ });
244
+
245
+ describe('RowsCacheEngine: store lifecycle', () => {
246
+ it('keeps each bucket apart and finds its rows again after a reopen', async () => {
247
+ const disks: RowsDisks = new Map();
248
+ await boot(disks, 'user_a');
249
+ await engine.upsert('game', 'game:a', { owner: 'a' }, 'replace');
250
+ await engine.switchBucket('user_b');
251
+ expect(engine.currentBucketId).toBe('user_b');
252
+ expect(await engine.getById('game', 'game:a')).toBeNull();
253
+ await engine.upsert('game', 'game:b', { owner: 'b' }, 'replace');
254
+ await engine.close();
255
+
256
+ await boot(disks, 'user_a');
257
+ expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:a', owner: 'a' }]);
258
+ await engine.switchBucket('user_b');
259
+ expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:b', owner: 'b' }]);
260
+ });
261
+
262
+ it('reports a durable store and its numbers', async () => {
263
+ expect(engine.storageHealth).toEqual({ status: 'persistent', fallback: false });
264
+ await engine.upsert('game', 'game:a', { n: 1 }, 'replace');
265
+ await engine.upsert('user', 'user:1', { n: 1 }, 'replace');
266
+ await engine.putSnapshot('circuit', new Uint8Array([1, 2, 3]), { formatVersion: 1, schemaHash: 'h', savedAt: 1 });
267
+ const diag = await engine.getStorageDiagnostics({ tableCounts: true });
268
+ expect(diag.engine).toBe('rows');
269
+ expect(diag.bucketId).toBe('user_a');
270
+ expect(diag.dbSizeBytes).toBeGreaterThan(4096);
271
+ expect(diag.tableCounts).toEqual([
272
+ { table: 'game', rows: 1 },
273
+ { table: 'user', rows: 1 },
274
+ ]);
275
+ expect((await engine.getStorageDiagnostics()).tableCounts).toBeUndefined();
276
+ expect(() => engine.getClient()).toThrow();
277
+ });
278
+
279
+ it('stores the circuit snapshot without taking the caller\'s bytes', async () => {
280
+ const bytes = new Uint8Array(100_000);
281
+ for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 13) & 255;
282
+ const meta = { formatVersion: 3, schemaHash: 'abc', savedAt: 1700000000000, maxRv: { game: 9 } };
283
+ await engine.putSnapshot('circuit', bytes, meta);
284
+ expect(bytes.byteLength).toBe(100_000);
285
+ const stored = (await engine.getSnapshot('circuit'))!;
286
+ expect(stored.bytes).toEqual(bytes);
287
+ expect(stored.meta).toEqual(meta);
288
+ expect(await engine.getSnapshot('other')).toBeNull();
289
+ // The snapshot's rows are no row a query returns.
290
+ expect((await engine.query<[Row[]]>('SELECT * FROM _00_circuit_snapshot'))[0]).toEqual([]);
291
+ await engine.deleteSnapshot('circuit');
292
+ expect(await engine.getSnapshot('circuit')).toBeNull();
293
+ });
294
+
295
+ it('scans versions from the index and resets them when a table\'s columns change', async () => {
296
+ await engine.upsert('game', 'game:a', { _00_rv: 4, title: 'a' }, 'replace');
297
+ await engine.upsert('game', 'game:b', { _00_rv: 7, title: 'b' }, 'replace');
298
+ await engine.upsert('user', 'user:1', { _00_rv: 2 }, 'replace');
299
+ expect(await engine.scanVersions(['game', 'user', 'absent'])).toEqual({
300
+ game: [
301
+ ['game:a', 4],
302
+ ['game:b', 7],
303
+ ],
304
+ user: [['user:1', 2]],
305
+ absent: [],
306
+ });
307
+
308
+ const v1 = columnFingerprints([
309
+ { name: 'game', columns: { title: 1 } },
310
+ { name: 'user', columns: { name: 1 } },
311
+ ]);
312
+ // Nothing recorded yet: every table that holds rows is reset once.
313
+ expect((await engine.resetChangedTables(v1, new Set(['game:b']))).sort()).toEqual(['game', 'user']);
314
+ expect((await engine.scanVersions(['game', 'user']))).toEqual({
315
+ game: [
316
+ ['game:a', 0],
317
+ ['game:b', 7],
318
+ ],
319
+ user: [['user:1', 0]],
320
+ });
321
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', _00_rv: 0, title: 'a' });
322
+
323
+ await engine.upsert('game', 'game:a', { _00_rv: 5 }, 'merge');
324
+ await engine.upsert('user', 'user:1', { _00_rv: 3 }, 'merge');
325
+ // Same columns: nothing to do.
326
+ expect(await engine.resetChangedTables(v1, new Set())).toEqual([]);
327
+ const v2 = columnFingerprints([
328
+ { name: 'game', columns: { title: 1, layout: 1 } },
329
+ { name: 'user', columns: { name: 1 } },
330
+ ]);
331
+ expect(await engine.resetChangedTables(v2, new Set())).toEqual(['game']);
332
+ expect(await engine.scanVersions(['game', 'user'])).toEqual({
333
+ game: [
334
+ ['game:a', 0],
335
+ ['game:b', 0],
336
+ ],
337
+ user: [['user:1', 3]],
338
+ });
339
+ // The recorded sets are not a row.
340
+ expect((await engine.query<[Row[]]>('SELECT * FROM _00_schema'))[0]).toEqual([]);
341
+ });
342
+
343
+ it('serves a follower over a port and survives the leader handing over', async () => {
344
+ const disks: RowsDisks = new Map();
345
+ await boot(disks);
346
+ const health = await engine.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
347
+ expect(health.role ?? 'leader').toBe('leader');
348
+ await engine.upsert('game', 'game:a', { n: 1 }, 'replace');
349
+ const before = engine.epoch;
350
+ await engine.adoptOwner('user_a', { workerLockName: 'lock-2', allowMemoryFallback: false, resumeHeld: false });
351
+ expect(engine.epoch).toBeGreaterThan(before);
352
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
353
+ });
354
+ });
355
+
356
+ describe('a follower that reads the store\'s file itself', () => {
357
+ let disks: RowsDisks;
358
+ let leader: RowsCacheEngine;
359
+ let host: ReturnType<typeof inProcessRows>;
360
+ /** Workers followers started for reading. */
361
+ let readers: FakeRowsWorker[];
362
+ const attached = { bucketId: 'user_a', storageHealth: { status: 'persistent', fallback: false } as const };
363
+
364
+ const follower = (config: Record<string, unknown> = { followerReads: 'direct' }): RowsCacheEngine =>
365
+ new RowsCacheEngine(
366
+ {
367
+ store: 'indexeddb',
368
+ ...config,
369
+ workers: {
370
+ rows: () => {
371
+ const worker = new FakeRowsWorker(disks);
372
+ readers.push(worker);
373
+ return worker as unknown as Worker;
374
+ },
375
+ },
376
+ } as any,
377
+ logger,
378
+ { useOpfs: true, shared: true }
379
+ );
380
+
381
+ /** A port into the leader's worker, as the tabs broker hands one to a follower. */
382
+ const leaderPort = () => {
383
+ const port = {
384
+ onmessage: null as null | ((ev: { data: unknown }) => void),
385
+ onmessageerror: null,
386
+ posted: [] as string[],
387
+ start() {},
388
+ close() {},
389
+ postMessage(msg: { id: number; type: string; payload: unknown }, transfer?: Transferable[]) {
390
+ port.posted.push(msg.type);
391
+ const payload = structuredClone(msg.payload, { transfer: transfer ?? [] });
392
+ void host.answer(msg.type, payload).then(
393
+ ({ result, transfer: back }) =>
394
+ port.onmessage?.({ data: { id: msg.id, ok: true, wt: 0, ...(structuredClone(result, { transfer: back ?? [] }) as object) } }),
395
+ (error: unknown) => port.onmessage?.({ data: { id: msg.id, ok: false, error: String(error) } })
396
+ );
397
+ },
398
+ };
399
+ return port;
400
+ };
401
+ const attach = async (tab: RowsCacheEngine) => {
402
+ const port = leaderPort();
403
+ await tab.adoptAttached(port as unknown as MessagePort, attached, () => {});
404
+ return port;
405
+ };
406
+
407
+ beforeEach(async () => {
408
+ disks = new Map();
409
+ readers = [];
410
+ leader = new RowsCacheEngine({ store: 'indexeddb', followerReads: 'direct' } as any, logger, { useOpfs: true, shared: true });
411
+ host = inProcessRows(leader, disks);
412
+ await leader.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
413
+ await leader.upsert('game', 'game:a', { n: 1, white: 'user:1' }, 'replace');
414
+ });
415
+
416
+ it('reads from its own worker, writes through the leader, and sees every write at once', async () => {
417
+ const tab = follower();
418
+ const port = await attach(tab);
419
+ expect(tab.readsDirectly).toBe(true);
420
+ expect(readers[0].posted.map((m) => m.type)).toEqual(['open']);
421
+ expect(await tab.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1, white: 'user:1' });
422
+
423
+ await tab.upsert('game', 'game:b', { n: 2, white: 'user:1' }, 'replace');
424
+ expect((await tab.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
425
+ // Another tab's write, and the leader's own.
426
+ await leader.upsert('game', 'game:c', { n: 3, white: 'user:2' }, 'replace');
427
+ await leader.delete('game', 'game:a');
428
+ expect((await tab.select({ table: 'game' })).map((r) => r.id)).toEqual(['game:b', 'game:c']);
429
+ expect(await tab.scanVersions(['game'])).toEqual(await leader.scanVersions(['game']));
430
+
431
+ // Only the write crossed to the leader.
432
+ expect(port.posted).toEqual(['write']);
433
+ expect(readers[0].posted.map((m) => m.type)).toEqual(['open', 'get', 'by-ids', 'select', 'versions']);
434
+ });
435
+
436
+ it('uses the indexes the leader keeps and builds none of its own', async () => {
437
+ for (let i = 0; i < 80; i++) await leader.upsert('game', `game:x${i}`, { n: i, white: `user:${i % 20}` }, 'replace');
438
+ const byWhite: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: 'user:7' }] };
439
+ const byN: QueryPlan = { table: 'game', where: [{ field: 'n', op: '=', value: 7 }] };
440
+ const tab = follower();
441
+ const port = await attach(tab);
442
+ const size = (): number => disks.get('user_a')!.a.size() + disks.get('user_a')!.b.size();
443
+ const before = size();
444
+ // A field nobody indexed yet: the follower scans, and writes nothing to find out.
445
+ expect((await tab.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
446
+ expect(size()).toBe(before);
447
+ expect(await tab.select(byWhite)).toEqual(await leader.select(byWhite));
448
+ // The leader builds the index for `n`; the follower reads through it from then on.
449
+ expect((await leader.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
450
+ expect(size()).toBeGreaterThan(before);
451
+ expect((await tab.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
452
+ expect(port.posted).toEqual([]);
453
+ });
454
+
455
+ it('follows the rows through a compaction of the leader\'s', async () => {
456
+ const tab = follower();
457
+ await attach(tab);
458
+ for (let i = 0; i < 60; i++) await leader.upsert('game', `game:x${i}`, { n: i, pad: 'p'.repeat(300) }, 'replace');
459
+ expect((await tab.select({ table: 'game' })).length).toBe(61);
460
+ for (let i = 0; i < 50; i++) await leader.delete('game', `game:x${i}`);
461
+ await host.store()!.compact();
462
+ expect(host.store()!.stats().file).toBe('b');
463
+ expect(await tab.select({ table: 'game' })).toEqual(await leader.select({ table: 'game' }));
464
+ await leader.upsert('game', 'game:z', { n: 99 }, 'replace');
465
+ expect(await tab.getById('game', 'game:z')).toEqual({ id: 'game:z', n: 99 });
466
+ });
467
+
468
+ it('reads through the leader when it is not asked to read directly, or cannot', async () => {
469
+ const plain = follower({});
470
+ const plainPort = await attach(plain);
471
+ expect(plain.readsDirectly).toBe(false);
472
+ expect(readers).toEqual([]);
473
+ expect((await plain.getById('game', 'game:a'))?.n).toBe(1);
474
+ expect(plainPort.posted).toEqual(['get']);
475
+
476
+ // A browser without shared handles: the reader's open fails.
477
+ const tab = new RowsCacheEngine(
478
+ {
479
+ store: 'indexeddb',
480
+ followerReads: 'direct',
481
+ workers: {
482
+ rows: () => {
483
+ const worker = new FakeRowsWorker(disks);
484
+ worker.postMessage = (msg: { id: number }) =>
485
+ queueMicrotask(() => worker.onmessage?.({ data: { id: msg.id, ok: false, error: 'opfs-unavailable: shared access handles' } }));
486
+ readers.push(worker);
487
+ return worker as unknown as Worker;
488
+ },
489
+ },
490
+ } as any,
491
+ logger,
492
+ { useOpfs: true, shared: true }
493
+ );
494
+ const port = await attach(tab);
495
+ expect(tab.readsDirectly).toBe(false);
496
+ expect(readers[0].terminated).toBe(true);
497
+ expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
498
+ expect(port.posted).toEqual(['get']);
499
+ });
500
+
501
+ it('asks the leader when its reader fails, and from then on', async () => {
502
+ const tab = follower();
503
+ const port = await attach(tab);
504
+ expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
505
+ readers[0].postMessage = () => readers[0].onerror?.({ message: 'out of memory' });
506
+ expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
507
+ expect(tab.readsDirectly).toBe(false);
508
+ expect(readers[0].terminated).toBe(true);
509
+ expect((await tab.selectByIds('game', ['game:a'])).length).toBe(1);
510
+ expect(port.posted).toEqual(['get', 'by-ids']);
511
+ });
512
+
513
+ it('lets go of the reader when the role changes', async () => {
514
+ const tab = follower();
515
+ await attach(tab);
516
+ tab.onLeaderLost('leader tab closed');
517
+ expect(tab.readsDirectly).toBe(false);
518
+ expect(readers[0].terminated).toBe(true);
519
+ // A new leader, a new reader.
520
+ await attach(tab);
521
+ expect(tab.readsDirectly).toBe(true);
522
+ expect(readers.length).toBe(2);
523
+ await tab.close();
524
+ expect(readers[1].terminated).toBe(true);
525
+ });
526
+ });
527
+
528
+ describe('packWrites', () => {
529
+ it('lays every row\'s text in one buffer and says where', () => {
530
+ const { wire, buf, sync } = packWrites([
531
+ { kind: 'upsert', table: 'game', key: 'game:a', data: { title: 'Épée \u{1f600}', _00_rv: 3 }, mode: 'replace' },
532
+ { kind: 'upsert', table: 'game', key: 'game:b', data: { n: 1, gone: undefined, bytes: new Uint8Array([7]) }, mode: 'merge' },
533
+ { kind: 'delete', table: 'game', key: 'game:c' },
534
+ { kind: 'clear', table: 'old' },
535
+ ]);
536
+ expect(sync).toBe(false);
537
+ const text = (off: number, len: number): string => new TextDecoder().decode(new Uint8Array(buf!, off, len));
538
+ expect(wire[0].slice(0, 5)).toEqual(['put', 'game', 'game:a', 3, 0]);
539
+ expect(JSON.parse(text(wire[0][5] as number, wire[0][6] as number))).toEqual({ title: 'Épée \u{1f600}', _00_rv: 3, id: 'game:a' });
540
+ // A merge that clears a field carries a patch beside the row to insert.
541
+ expect(wire[1].slice(0, 5)).toEqual(['merge', 'game', 'game:b', 0, 1]);
542
+ expect(JSON.parse(text(wire[1][5] as number, wire[1][6] as number))).toEqual({ n: 1, bytes: { __u8: 'Bw==' }, id: 'game:b' });
543
+ expect(JSON.parse(text(wire[1][7] as number, wire[1][8] as number))).toEqual({ n: 1, bytes: { __u8: 'Bw==' }, id: 'game:b', gone: null });
544
+ expect(wire[2]).toEqual(['del', 'game', 'game:c']);
545
+ expect(wire[3]).toEqual(['clear', 'old']);
546
+ });
547
+
548
+ it('asks for a flush when a table of unsent work is written, deleted from or cleared', () => {
549
+ expect(packWrites([{ kind: 'upsert', table: '_00_pending_mutations', key: '_00_pending_mutations:1', data: {}, mode: 'replace' }]).sync).toBe(true);
550
+ expect(packWrites([{ kind: 'delete', table: '_00_pending_writes', key: 'x' }]).sync).toBe(true);
551
+ expect(packWrites([{ kind: 'clear', table: '_00_crdt_local' }]).sync).toBe(true);
552
+ expect(packWrites([{ kind: 'delete', table: 'game', key: 'x' }])).toEqual({ wire: [['del', 'game', 'x']], buf: null, sync: false });
553
+ expect(packWrites([])).toEqual({ wire: [], buf: null, sync: false });
554
+ });
555
+ });
556
+
557
+ describe('row store housekeeping', () => {
558
+ const stats = (over: Partial<StoreStats>): StoreStats => ({
559
+ file: 'a',
560
+ fileBytes: 0,
561
+ liveBytes: 0,
562
+ indexBytes: 0,
563
+ garbageBytes: 0,
564
+ tailBytes: 0,
565
+ tailOps: 0,
566
+ tables: 0,
567
+ rebuilt: false,
568
+ ...over,
569
+ });
570
+
571
+ it('persists the index first, then compacts once dead bytes pass half the live ones', () => {
572
+ expect(maintenance(stats({}))).toBeNull();
573
+ expect(maintenance(stats({ tailBytes: 1, garbageBytes: 1 << 30 }))).toBe('checkpoint');
574
+ // Small stores are left alone however fragmented.
575
+ expect(maintenance(stats({ liveBytes: 1 << 20, garbageBytes: 3 << 20 }))).toBeNull();
576
+ expect(maintenance(stats({ liveBytes: 40 << 20, garbageBytes: 19 << 20 }))).toBeNull();
577
+ expect(maintenance(stats({ liveBytes: 40 << 20, garbageBytes: 21 << 20 }))).toBe('compact');
578
+ });
579
+
580
+ it('compacts a rewritten store down to its rows and keeps serving it', async () => {
581
+ const row = (i: number, round: number): Row => ({ n: i, round, pad: 'x'.repeat(2000) });
582
+ for (let round = 0; round < 6; round++) {
583
+ const vars: Record<string, unknown> = {};
584
+ const statements: string[] = [];
585
+ for (let i = 0; i < 500; i++) {
586
+ vars[`i${i}`] = `game:${i}`;
587
+ vars[`d${i}`] = row(i, round);
588
+ statements.push(surql.upsertMerge(`i${i}`, `d${i}`));
589
+ }
590
+ await engine.execute(surql.seal(surql.tx(statements)), vars);
591
+ }
592
+ const store = host.store()!;
593
+ store.checkpoint();
594
+ const before = store.stats();
595
+ expect(maintenance(before)).toBe('compact');
596
+ await store.compact();
597
+ const after = store.stats();
598
+ expect(maintenance(after)).toBeNull();
599
+ expect(after.fileBytes).toBeLessThan(before.fileBytes / 4);
600
+ expect(await engine.getById('game', 'game:499')).toEqual({ id: 'game:499', ...row(499, 5) });
601
+ expect((await engine.getStorageDiagnostics()).freelistBytes).toBeLessThan(64 << 10);
602
+ });
603
+
604
+ it('lets a follower tab read and write, and nothing else', () => {
605
+ for (const op of ['select', 'by-ids', 'get', 'relation', 'write', 'versions']) expect(ROWS_CLIENT_OPS.has(op)).toBe(true);
606
+ for (const op of ['open', 'close', 'shutdown', 'relock', 'diag']) expect(ROWS_CLIENT_OPS.has(op)).toBe(false);
607
+ });
608
+ });
609
+
610
+ describe('prewarming the row worker', () => {
611
+ const g = globalThis as Record<string, unknown>;
612
+ let stored: Map<string, string>;
613
+ let disks: RowsDisks;
614
+ /** Workers started through `new Worker(url)`, i.e. by the prewarm. */
615
+ let started: { url: string; worker: FakeRowsWorker }[];
616
+ /** Workers the engine started itself. */
617
+ let own: FakeRowsWorker[];
618
+ let prewarmedProto: number | undefined;
619
+
620
+ const makeEngine = (): RowsCacheEngine =>
621
+ new RowsCacheEngine(
622
+ {
623
+ store: 'indexeddb',
624
+ workers: {
625
+ rows: () => {
626
+ const worker = new FakeRowsWorker(disks);
627
+ own.push(worker);
628
+ return worker as unknown as Worker;
629
+ },
630
+ },
631
+ } as any,
632
+ logger,
633
+ { useOpfs: true }
634
+ );
635
+
636
+ beforeEach(() => {
637
+ stored = new Map();
638
+ disks = new Map();
639
+ started = [];
640
+ own = [];
641
+ prewarmedProto = undefined;
642
+ g.localStorage = {
643
+ getItem: (k: string) => stored.get(k) ?? null,
644
+ setItem: (k: string, v: string) => void stored.set(k, v),
645
+ removeItem: (k: string) => void stored.delete(k),
646
+ };
647
+ g.Worker = class {
648
+ constructor(url: string) {
649
+ const worker = new FakeRowsWorker(disks, prewarmedProto);
650
+ started.push({ url, worker });
651
+ return worker as unknown as object;
652
+ }
653
+ };
654
+ });
655
+
656
+ afterEach(() => {
657
+ delete g.localStorage;
658
+ delete g.Worker;
659
+ delete g.__sp00kyRowsPrewarm;
660
+ });
661
+
662
+ it('does nothing on a first visit, and learns the worker from the first open', async () => {
663
+ prewarmRows();
664
+ expect(started).toEqual([]);
665
+ const first = makeEngine();
666
+ await first.connect('user_a');
667
+ expect(own.length).toBe(1);
668
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!)).toEqual({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_a' });
669
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
670
+ await first.close();
671
+ });
672
+
673
+ it('hands the engine a worker that already has the store open', async () => {
674
+ const first = makeEngine();
675
+ await first.connect('user_a');
676
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
677
+ await first.close();
678
+ own.length = 0;
679
+
680
+ prewarmRows();
681
+ prewarmRows();
682
+ expect(started.map((s) => s.url)).toEqual(['https://app.test/assets/rows-worker.js']);
683
+ expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
684
+ const second = makeEngine();
685
+ await second.connect('user_a');
686
+ // The engine started no worker of its own, and nothing is left for a later engine to take.
687
+ expect(own).toEqual([]);
688
+ expect(g.__sp00kyRowsPrewarm).toBeUndefined();
689
+ expect(await second.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
690
+ expect(second.storageHealth.status).toBe('persistent');
691
+ });
692
+
693
+ it('does not ask an adopted worker to open what it has already answered for', async () => {
694
+ const first = makeEngine();
695
+ await first.connect('user_a');
696
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
697
+ await first.close();
698
+ own.length = 0;
699
+
700
+ prewarmRows();
701
+ // The worker answers while the bundle loads, long before the client connects.
702
+ await new Promise((resolve) => setTimeout(resolve, 0));
703
+ const second = makeEngine();
704
+ await second.connect('user_a');
705
+ expect(own).toEqual([]);
706
+ expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
707
+ expect(second.storageHealth.status).toBe('persistent');
708
+ expect(await second.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
709
+ expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm', 'get']);
710
+ });
711
+
712
+ it('asks a worker prewarmed on another store to open the one it wants', async () => {
713
+ const first = makeEngine();
714
+ await first.connect('user_a');
715
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
716
+ await first.close();
717
+
718
+ prewarmRows();
719
+ await new Promise((resolve) => setTimeout(resolve, 0));
720
+ const second = makeEngine();
721
+ await second.connect('user_b');
722
+ expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm', 'open']);
723
+ expect(await second.getById('game', 'game:a')).toBeNull();
724
+ });
725
+
726
+ describe('reading ahead', () => {
727
+ const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
728
+ const save = (e: RowsCacheEngine): void => (e as unknown as { saveStartupReads(): void }).saveStartupReads();
729
+ const types = (): string[] => started[0].worker.posted.map((m) => m.type);
730
+
731
+ /** A session that reads two games at startup, and what it leaves for the next page load. */
732
+ const firstSession = async (): Promise<void> => {
733
+ const first = makeEngine();
734
+ await first.connect('user_a');
735
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
736
+ await first.upsert('game', 'game:b', { n: 2 }, 'replace');
737
+ expect(await first.selectByIds('game', ['game:a', 'game:b'])).toEqual([
738
+ { id: 'game:a', n: 1 },
739
+ { id: 'game:b', n: 2 },
740
+ ]);
741
+ save(first);
742
+ await first.close();
743
+ own.length = 0;
744
+ };
745
+
746
+ it('saves the reads of a session start and asks them again from the page head', async () => {
747
+ await firstSession();
748
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a', 'game:b'] }]]);
749
+ prewarmRows();
750
+ expect(started[0].worker.posted).toEqual([
751
+ { type: 'open', id: -1 },
752
+ { type: 'by-ids', id: -10 },
753
+ { type: 'warm', id: -2 },
754
+ ]);
755
+ });
756
+
757
+ it('answers the first read from what the worker already sent, without a trip', async () => {
758
+ await firstSession();
759
+ prewarmRows();
760
+ await tick();
761
+ const second = makeEngine();
762
+ await second.connect('user_a');
763
+ expect(await second.selectByIds('game', ['game:a', 'game:b'])).toEqual([
764
+ { id: 'game:a', n: 1 },
765
+ { id: 'game:b', n: 2 },
766
+ ]);
767
+ expect(types()).toEqual(['open', 'by-ids', 'warm']);
768
+ // An answer is used once: the same read again is asked of the worker.
769
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).length).toBe(2);
770
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'by-ids']);
771
+ // And another read never matches.
772
+ expect(await second.selectByIds('game', ['game:a'])).toEqual([{ id: 'game:a', n: 1 }]);
773
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'by-ids', 'by-ids']);
774
+ });
775
+
776
+ it('waits for an answer that is still on its way, and does not ask twice', async () => {
777
+ await firstSession();
778
+ prewarmRows();
779
+ const second = makeEngine();
780
+ await second.connect('user_a');
781
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
782
+ // The open had not been answered yet, so that one was asked; the read was not.
783
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
784
+ });
785
+
786
+ it('forgets what was read ahead the moment the session writes', async () => {
787
+ await firstSession();
788
+ prewarmRows();
789
+ await tick();
790
+ const second = makeEngine();
791
+ await second.connect('user_a');
792
+ await second.upsert('game', 'game:a', { n: 9 }, 'replace');
793
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([9, 2]);
794
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'write', 'by-ids']);
795
+ });
796
+
797
+ it('asks nothing ahead for another bucket, and keeps no reads across a change of bucket', async () => {
798
+ await firstSession();
799
+ prewarmRows();
800
+ await tick();
801
+ const second = makeEngine();
802
+ await second.connect('user_b');
803
+ expect(await second.selectByIds('game', ['game:a', 'game:b'])).toEqual([]);
804
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open', 'by-ids']);
805
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!)).toEqual({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' });
806
+ });
807
+
808
+ it('does not save a read whose payload JSON would change', async () => {
809
+ const first = makeEngine();
810
+ await first.connect('user_a');
811
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
812
+ const byParam: QueryPlan = { table: 'game', where: [{ field: 'n', op: '=', value: undefined, paramRef: 'n' }] };
813
+ await first.select(byParam, { n: 1 });
814
+ await first.select(byParam, { n: new Date(0) });
815
+ save(first);
816
+ const reads = JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads as [string, { params: unknown }][];
817
+ expect(reads.map((r) => r[1].params)).toEqual([{ n: 1 }]);
818
+ await first.close();
819
+ });
820
+ });
821
+
822
+ describe('with shared tabs', () => {
823
+ const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
824
+ const save = (e: RowsCacheEngine): void => (e as unknown as { saveStartupReads(): void }).saveStartupReads();
825
+ const types = (): string[] => started[0].worker.posted.map((m) => m.type);
826
+ const lead = { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false };
827
+ const sharedEngine = (): RowsCacheEngine =>
828
+ new RowsCacheEngine(
829
+ {
830
+ store: 'indexeddb',
831
+ workers: {
832
+ rows: () => {
833
+ const worker = new FakeRowsWorker(disks);
834
+ own.push(worker);
835
+ return worker as unknown as Worker;
836
+ },
837
+ },
838
+ } as any,
839
+ logger,
840
+ { useOpfs: true, shared: true }
841
+ );
842
+
843
+ /** A leader's session that reads two games at startup, and what it leaves for the next page load. */
844
+ const firstSession = async (): Promise<void> => {
845
+ const first = sharedEngine();
846
+ await first.adoptOwner('user_a', lead);
847
+ await first.upsert('game', 'game:a', { n: 1 }, 'replace');
848
+ await first.upsert('game', 'game:b', { n: 2 }, 'replace');
849
+ expect((await first.selectByIds('game', ['game:a', 'game:b'])).length).toBe(2);
850
+ save(first);
851
+ await first.close();
852
+ own.length = 0;
853
+ };
854
+
855
+ it('saves a leader\'s startup reads, and answers the next leader\'s first read from the page head', async () => {
856
+ await firstSession();
857
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a', 'game:b'] }]]);
858
+ prewarmRows();
859
+ await tick();
860
+ const second = sharedEngine();
861
+ await second.adoptOwner('user_a', lead);
862
+ // Its own worker was not needed. The open is asked: it is what takes the role's lock.
863
+ expect(own).toEqual([]);
864
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
865
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
866
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
867
+ });
868
+
869
+ it('forgets what was read ahead once another tab can write through the worker', async () => {
870
+ await firstSession();
871
+ prewarmRows();
872
+ await tick();
873
+ const second = sharedEngine();
874
+ await second.adoptOwner('user_a', lead);
875
+ const { port1 } = new MessageChannel();
876
+ // The fake worker knows no ports; what matters is what the engine did before asking.
877
+ await second.exposeClientPort('tab-2', port1).catch(() => {});
878
+ port1.close();
879
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
880
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
881
+ });
882
+
883
+ it('saves the startup reads of a session once, whatever roles follow', async () => {
884
+ await firstSession();
885
+ const tab = sharedEngine();
886
+ await tab.adoptOwner('user_a', lead);
887
+ await tab.selectByIds('game', ['game:a']);
888
+ save(tab);
889
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a'] }]]);
890
+ // Leadership moves on and comes back, long after startup: what the tab reads then is not a startup read.
891
+ (tab as unknown as { startupUntil: number }).startupUntil = 0;
892
+ await tab.adoptOwner('user_a', { ...lead, workerLockName: 'lock-2' });
893
+ await tab.selectByIds('game', ['game:b']);
894
+ save(tab);
895
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a'] }]]);
896
+ await tab.close();
897
+ });
898
+
899
+ it('asks for the open even when the worker answered it, in a tab that may share the store', async () => {
900
+ await firstSession();
901
+ prewarmRows();
902
+ await tick();
903
+ // Shared tabs were not to be had and the tab opens the store alone.
904
+ const solo = sharedEngine();
905
+ await solo.connect('user_a');
906
+ expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
907
+ expect(await solo.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
908
+ });
909
+
910
+ const gaveAway = { id: -1, ok: false, error: 'rows worker: gave the store to the tab that leads' };
911
+
912
+ it('takes back its open and everything read ahead when the worker gave the store away', async () => {
913
+ for (const start of [prewarmRows, () => void new Function(ROWS_PREWARM_SNIPPET)()]) {
914
+ disks = new Map();
915
+ stored = new Map();
916
+ started.length = 0;
917
+ delete g.__sp00kyRowsPrewarm;
918
+ await firstSession();
919
+ start();
920
+ await tick();
921
+ const pre = g.__sp00kyRowsPrewarm as { opened?: unknown; reads: unknown[]; replies: Record<number, unknown> };
922
+ expect(pre.opened).toBeDefined();
923
+ expect(Object.keys(pre.replies).length).toBe(1);
924
+ // Another tab leads: this page's worker closes its store and says so.
925
+ started[0].worker.postMessage({ id: -5, type: 'close', payload: undefined });
926
+ await tick();
927
+ started[0].worker.onmessage?.({ data: gaveAway });
928
+ expect(pre.opened).toBeUndefined();
929
+ expect(pre.reads).toEqual([]);
930
+ expect(pre.replies).toEqual({});
931
+ // That tab writes, and is gone before this page has a role. (It has a worker of its own.)
932
+ delete g.__sp00kyRowsPrewarm;
933
+ const other = sharedEngine();
934
+ await other.adoptOwner('user_a', { ...lead, workerLockName: 'lock-other' });
935
+ await other.upsert('game', 'game:a', { n: 100 }, 'merge');
936
+ await other.close();
937
+ own.length = 0;
938
+ g.__sp00kyRowsPrewarm = pre;
939
+
940
+ const second = sharedEngine();
941
+ await second.adoptOwner('user_a', lead);
942
+ // The read is asked of the worker, and answers what the other tab wrote.
943
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([100, 2]);
944
+ // On the worker its head script started: one read asked ahead, one asked now.
945
+ expect(own).toEqual([]);
946
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
947
+ await second.close();
948
+ }
949
+ });
950
+
951
+ it('drops what was read ahead when the store is given away after the worker was adopted', async () => {
952
+ await firstSession();
953
+ prewarmRows();
954
+ await tick();
955
+ const second = sharedEngine();
956
+ await second.adoptOwner('user_a', lead);
957
+ // The hand-over was under way when the page adopted the worker: its word arrives now.
958
+ started[0].worker.onmessage?.({ data: gaveAway });
959
+ expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
960
+ expect(types().filter((t) => t === 'by-ids').length).toBe(2);
961
+ });
962
+
963
+ it('starts its own worker when the one started ahead is another release', async () => {
964
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker-OLD.js', bucket: 'user_a' }));
965
+ prewarmedProto = 0;
966
+ prewarmRows();
967
+ const engine = sharedEngine();
968
+ await engine.adoptOwner('user_a', lead);
969
+ expect(started[0].worker.terminated).toBe(true);
970
+ expect(own.length).toBe(1);
971
+ await engine.upsert('game', 'game:a', { n: 2 }, 'replace');
972
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 2 });
973
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).url).toBe('https://app.test/assets/rows-worker.js');
974
+ });
975
+ });
976
+
977
+ it('starts its own worker when the prewarmed one is another release', async () => {
978
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker-OLD.js', bucket: 'user_a' }));
979
+ prewarmedProto = 0;
980
+ prewarmRows();
981
+ const engine = makeEngine();
982
+ await engine.connect('user_a');
983
+ expect(started[0].worker.terminated).toBe(true);
984
+ expect(own.length).toBe(1);
985
+ await engine.upsert('game', 'game:a', { n: 2 }, 'replace');
986
+ expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 2 });
987
+ // The next load prewarms the worker that works.
988
+ expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).url).toBe('https://app.test/assets/rows-worker.js');
989
+ });
990
+
991
+ it('drops a prewarmed worker that failed to start', async () => {
992
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/gone.js', bucket: 'user_a' }));
993
+ prewarmRows();
994
+ started[0].worker.onerror?.({ message: '404' });
995
+ const engine = makeEngine();
996
+ await engine.connect('user_a');
997
+ expect(started[0].worker.terminated).toBe(true);
998
+ expect(own.length).toBe(1);
999
+ });
1000
+
1001
+ it('ships the same thing as a script for the page head', () => {
1002
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' }));
1003
+ new Function(ROWS_PREWARM_SNIPPET)();
1004
+ expect(started.map((s) => s.url)).toEqual(['https://app.test/assets/rows-worker.js']);
1005
+ expect((g.__sp00kyRowsPrewarm as { bucket: string }).bucket).toBe('user_b');
1006
+ expect(started[0].worker.posted).toEqual([
1007
+ { type: 'open', id: -1 },
1008
+ { type: 'warm', id: -2 },
1009
+ ]);
1010
+ });
1011
+
1012
+ it('keeps the answer to its open in the head script too', async () => {
1013
+ stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' }));
1014
+ new Function(ROWS_PREWARM_SNIPPET)();
1015
+ await new Promise((resolve) => setTimeout(resolve, 0));
1016
+ const engine = makeEngine();
1017
+ await engine.connect('user_b');
1018
+ expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
1019
+ expect(engine.storageHealth.status).toBe('persistent');
1020
+ });
1021
+ });
1022
+
1023
+ describe('painting from the last session', () => {
1024
+ const g = globalThis as Record<string, unknown>;
1025
+ let stored: Map<string, string>;
1026
+ let disks: RowsDisks;
1027
+ const flush = (e: RowsCacheEngine): void => (e as unknown as { paint: { flush(): void } }).paint.flush();
1028
+ const fresh = (config: Record<string, unknown> = {}, useOpfs = true): RowsCacheEngine => {
1029
+ const next = new RowsCacheEngine({ store: 'indexeddb', ...config } as any, logger, { useOpfs });
1030
+ inProcessRows(next, disks);
1031
+ return next;
1032
+ };
1033
+ const ids = ['game:b', 'game:a'];
1034
+
1035
+ beforeEach(async () => {
1036
+ stored = new Map();
1037
+ disks = new Map();
1038
+ g.localStorage = {
1039
+ getItem: (k: string) => stored.get(k) ?? null,
1040
+ setItem: (k: string, v: string) => void stored.set(k, v),
1041
+ removeItem: (k: string) => void stored.delete(k),
1042
+ key: (i: number) => [...stored.keys()][i] ?? null,
1043
+ get length() {
1044
+ return stored.size;
1045
+ },
1046
+ };
1047
+ engine = fresh();
1048
+ await engine.connect('user_a');
1049
+ await engine.upsert('game', 'game:a', { n: 1, white: 'user:1' }, 'replace');
1050
+ await engine.upsert('game', 'game:b', { n: 2, blob: new Uint8Array([1, 2]) }, 'replace');
1051
+ await engine.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
1052
+ });
1053
+
1054
+ afterEach(() => {
1055
+ delete g.localStorage;
1056
+ });
1057
+
1058
+ it('hands back a startup read before the store is open', async () => {
1059
+ expect(engine.peekByIds('game', ids)).toBeNull();
1060
+ const rows = await engine.selectByIds('game', ids);
1061
+ flush(engine);
1062
+ await engine.close();
1063
+
1064
+ const next = fresh();
1065
+ const opening = next.connect('user_a');
1066
+ // Nothing has been awaited: the worker has not answered, the peek has.
1067
+ expect(next.peekByIds('game', ids)).toEqual(rows);
1068
+ expect(next.peekByIds('game', ids)![0].blob).toEqual(new Uint8Array([1, 2]));
1069
+ expect(next.peekByIds('game', ['game:a'])).toBeNull();
1070
+ expect(next.peekByIds('game', ids, { select: ['n'] })).toBeNull();
1071
+ await opening;
1072
+ expect(await next.selectByIds('game', ids)).toEqual(rows);
1073
+ });
1074
+
1075
+ it('keeps a named read under its name, whatever its arguments were', async () => {
1076
+ const whole: QueryPlan = { table: 'game' };
1077
+ const one: QueryPlan = { table: 'game', ids: [new RecordId('game', 'a')] };
1078
+ // A query whose id set moved between two renders: one name, the latest answer.
1079
+ await engine.select(whole, {}, { paintKey: 'view-1' });
1080
+ const latest = await engine.select(one, {}, { paintKey: 'view-1' });
1081
+ expect(latest.map((r) => r.id)).toEqual(['game:a']);
1082
+ flush(engine);
1083
+ await engine.close();
1084
+
1085
+ const next = fresh();
1086
+ void next.connect('user_a');
1087
+ expect(next.peekSelect(whole, {}, { paintKey: 'view-1' })).toEqual(latest);
1088
+ expect(next.peekSelect(whole, {}, { paintKey: 'view-2' })).toBeNull();
1089
+ // The unnamed read of the same plan is another thing.
1090
+ expect(next.peekSelect(whole)).toBeNull();
1091
+ });
1092
+
1093
+ it('answers before connect once it is told which bucket is about to open', async () => {
1094
+ const plan: QueryPlan = { table: 'game' };
1095
+ const rows = await engine.select(plan, {}, { paintKey: 'view-1' });
1096
+ flush(engine);
1097
+ await engine.close();
1098
+
1099
+ const next = fresh();
1100
+ // Nothing says whose rows these would be.
1101
+ expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
1102
+ next.expectBucket('user_a');
1103
+ expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
1104
+ // The first word stands until the store is opened.
1105
+ next.expectBucket('user_b');
1106
+ expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
1107
+ // Opened on another bucket after all: none of the first one's rows are handed out.
1108
+ await next.connect('user_b');
1109
+ expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
1110
+ await next.close();
1111
+
1112
+ // A tab that shares the store with others is told the same way, before it has a role.
1113
+ const shared = new RowsCacheEngine({ store: 'indexeddb' } as any, logger, { useOpfs: true, shared: true });
1114
+ shared.expectBucket('user_a');
1115
+ expect(shared.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
1116
+ });
1117
+
1118
+ it('lets go of a copy the moment its table is written, and takes the next read of the same thing', async () => {
1119
+ await engine.selectByIds('game', ids);
1120
+ flush(engine);
1121
+ expect([...stored.keys()].some((k) => k.startsWith('sp00ky.paint.user_a.'))).toBe(true);
1122
+ await engine.upsert('game', 'game:a', { n: 10 }, 'merge');
1123
+ expect(engine.peekByIds('game', ids)).toBeNull();
1124
+ // Nothing is left but the marks of the tables written to.
1125
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.startsWith('sp00ky.paint.user_a.t.'))).toEqual([]);
1126
+ // A write to another table leaves it alone.
1127
+ const again = await engine.selectByIds('game', ids);
1128
+ await engine.upsert('user', 'user:1', { name: 'Ada L.' }, 'merge');
1129
+ flush(engine);
1130
+ expect(engine.peekByIds('game', ids)).toEqual(again);
1131
+ expect(again[1].n).toBe(10);
1132
+ });
1133
+
1134
+ it('never keeps a read that a write overtook', async () => {
1135
+ const reading = engine.selectByIds('game', ids);
1136
+ const writing = engine.upsert('game', 'game:a', { n: 99 }, 'merge');
1137
+ await Promise.all([reading, writing]);
1138
+ flush(engine);
1139
+ expect(engine.peekByIds('game', ids)).toBeNull();
1140
+ });
1141
+
1142
+ it('keeps a select with relations, and drops it when any table it read is written', async () => {
1143
+ const plan: QueryPlan = {
1144
+ table: 'game',
1145
+ ids: ['game:a'],
1146
+ relations: [{ alias: 'white', table: 'user', cardinality: 'one', foreignKeyField: 'white' }],
1147
+ };
1148
+ const rows = await engine.select(plan);
1149
+ flush(engine);
1150
+ expect(engine.peekSelect(plan)).toEqual(rows);
1151
+ expect((engine.peekSelect(plan)![0].white as Row).name).toBe('Ada');
1152
+ await engine.upsert('user', 'user:1', { name: 'Grace' }, 'merge');
1153
+ expect(engine.peekSelect(plan)).toBeNull();
1154
+ });
1155
+
1156
+ it('keeps each bucket apart and forgets a dropped one', async () => {
1157
+ await engine.selectByIds('game', ids);
1158
+ await engine.switchBucket('user_b');
1159
+ expect(engine.peekByIds('game', ids)).toBeNull();
1160
+ await engine.dropBucket('user_a');
1161
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a'))).toEqual([]);
1162
+ });
1163
+
1164
+ it('is off for a memory store and when configured off', async () => {
1165
+ for (const quiet of [fresh({}, false), fresh({ paintCache: false })]) {
1166
+ await quiet.connect('user_a');
1167
+ await quiet.selectByIds('game', ids);
1168
+ expect(quiet.peekByIds('game', ids)).toBeNull();
1169
+ }
1170
+ });
1171
+ });
1172
+
1173
+ describe('painting with shared tabs', () => {
1174
+ const g = globalThis as Record<string, unknown>;
1175
+ let stored: Map<string, string>;
1176
+ let disks: RowsDisks;
1177
+ let leader: RowsCacheEngine;
1178
+ let leaderHost: RowsHost;
1179
+ const ids = ['game:b', 'game:a'];
1180
+ const flush = (e: RowsCacheEngine): void => (e as unknown as { paint: { flush(): void } }).paint.flush();
1181
+ const shared = (config: Record<string, unknown> = {}): RowsCacheEngine =>
1182
+ new RowsCacheEngine({ store: 'indexeddb', ...config } as any, logger, { useOpfs: true, shared: true });
1183
+ const attached = { bucketId: 'user_a', storageHealth: { status: 'persistent', fallback: false } as const };
1184
+
1185
+ /** A follower tab: its ops go into the leader's worker through a port. */
1186
+ const follow = async (health: { status: 'persistent' | 'memory'; fallback: boolean } = attached.storageHealth): Promise<RowsCacheEngine> => {
1187
+ const tab = shared();
1188
+ const port = {
1189
+ onmessage: null as null | ((ev: { data: unknown }) => void),
1190
+ onmessageerror: null,
1191
+ start() {},
1192
+ close() {},
1193
+ postMessage(msg: { id: number; type: string; payload: unknown }, transfer?: Transferable[]) {
1194
+ const payload = structuredClone(msg.payload, { transfer: transfer ?? [] });
1195
+ void leaderHost.answer(msg.type, payload).then(
1196
+ ({ result, transfer: back }) =>
1197
+ port.onmessage?.({ data: { id: msg.id, ok: true, wt: 0, ...(structuredClone(result, { transfer: back ?? [] }) as object) } }),
1198
+ (error: unknown) => port.onmessage?.({ data: { id: msg.id, ok: false, error: String(error) } })
1199
+ );
1200
+ },
1201
+ };
1202
+ await tab.adoptAttached(port as unknown as MessagePort, { ...attached, storageHealth: health }, () => {});
1203
+ return tab;
1204
+ };
1205
+
1206
+ beforeEach(async () => {
1207
+ stored = new Map();
1208
+ disks = new Map();
1209
+ g.localStorage = {
1210
+ getItem: (k: string) => stored.get(k) ?? null,
1211
+ setItem: (k: string, v: string) => void stored.set(k, v),
1212
+ removeItem: (k: string) => void stored.delete(k),
1213
+ key: (i: number) => [...stored.keys()][i] ?? null,
1214
+ get length() {
1215
+ return stored.size;
1216
+ },
1217
+ };
1218
+ leader = shared();
1219
+ leaderHost = inProcessRows(leader, disks);
1220
+ await leader.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
1221
+ await leader.upsert('game', 'game:a', { n: 1 }, 'replace');
1222
+ await leader.upsert('game', 'game:b', { n: 2 }, 'replace');
1223
+ await leader.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
1224
+ });
1225
+
1226
+ afterEach(() => {
1227
+ delete g.localStorage;
1228
+ });
1229
+
1230
+ it('keeps what a leader and a follower read at startup, for whichever tab opens next', async () => {
1231
+ const tab = await follow();
1232
+ const games = await leader.selectByIds('game', ids);
1233
+ const users = await tab.selectByIds('user', ['user:1']);
1234
+ flush(leader);
1235
+ flush(tab);
1236
+
1237
+ // The next page load, before it has any role.
1238
+ const next = shared();
1239
+ next.expectBucket('user_a');
1240
+ expect(next.peekByIds('game', ids)).toEqual(games);
1241
+ expect(next.peekByIds('user', ['user:1'])).toEqual(users);
1242
+ // And each tab has the other's copy.
1243
+ expect(tab.peekByIds('game', ids)).toEqual(games);
1244
+ expect(leader.peekByIds('user', ['user:1'])).toEqual(users);
1245
+ });
1246
+
1247
+ it('hands out no copy of a table another tab has written to since', async () => {
1248
+ const tab = await follow();
1249
+ await tab.selectByIds('game', ids);
1250
+ await tab.selectByIds('user', ['user:1']);
1251
+ flush(tab);
1252
+ expect(tab.peekByIds('game', ids)).not.toBeNull();
1253
+
1254
+ await leader.upsert('game', 'game:a', { n: 10 }, 'merge');
1255
+ // Not in the tab that holds it in memory, not in one that would read it from storage.
1256
+ expect(tab.peekByIds('game', ids)).toBeNull();
1257
+ const next = shared();
1258
+ next.expectBucket('user_a');
1259
+ expect(next.peekByIds('game', ids)).toBeNull();
1260
+ // The other table's copy stands.
1261
+ expect(next.peekByIds('user', ['user:1'])).not.toBeNull();
1262
+
1263
+ // The follower's own write voids the leader's copy the same way.
1264
+ await leader.selectByIds('user', ['user:1']);
1265
+ await tab.upsert('user', 'user:1', { name: 'Grace' }, 'merge');
1266
+ expect(leader.peekByIds('user', ['user:1'])).toBeNull();
1267
+ // The next read of the same thing is kept again.
1268
+ const again = await tab.selectByIds('game', ids);
1269
+ expect(again[1].n).toBe(10);
1270
+ flush(tab);
1271
+ expect(next.peekByIds('game', ids)).toEqual(again);
1272
+ });
1273
+
1274
+ it('does not keep a read that another tab\'s write overtook', async () => {
1275
+ const tab = await follow();
1276
+ const kept = (e: RowsCacheEngine): number => (e as unknown as { paint: { entries: Map<string, unknown> } }).paint.entries.size;
1277
+ const reading = tab.selectByIds('game', ids);
1278
+ const writing = leader.upsert('game', 'game:a', { n: 99 }, 'merge');
1279
+ await Promise.all([reading, writing]);
1280
+ // Not kept at all: its marks alone would not say so had the read come back after the leader's second mark.
1281
+ expect(kept(tab)).toBe(0);
1282
+ flush(tab);
1283
+ expect(tab.peekByIds('game', ids)).toBeNull();
1284
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.includes('.t.'))).toEqual([]);
1285
+ });
1286
+
1287
+ it('does not write a copy that went stale over one another tab took since', async () => {
1288
+ const tab = await follow();
1289
+ await tab.selectByIds('game', ids);
1290
+ await leader.upsert('game', 'game:a', { n: 5 }, 'merge');
1291
+ const fresh = await leader.selectByIds('game', ids);
1292
+ flush(leader);
1293
+ // The follower's copy is the older one, and still unsaved.
1294
+ flush(tab);
1295
+ const next = shared();
1296
+ next.expectBucket('user_a');
1297
+ expect(next.peekByIds('game', ids)).toEqual(fresh);
1298
+ });
1299
+
1300
+ it('starts a session with the first role only', async () => {
1301
+ const tab = await follow();
1302
+ await tab.selectByIds('game', ids);
1303
+ const paint = (tab as unknown as { paint: { since: number } }).paint;
1304
+ const since = paint.since;
1305
+ expect(since).toBeGreaterThan(0);
1306
+ paint.since = since - 10_000;
1307
+ // Promoted later: reads from here on are not what the tab reads at startup.
1308
+ inProcessRows(tab, disks);
1309
+ await leader.close();
1310
+ await tab.adoptOwner('user_a', { workerLockName: 'lock-2', allowMemoryFallback: false, resumeHeld: false });
1311
+ expect(paint.since).toBe(since - 10_000);
1312
+ await tab.selectByIds('user', ['user:1']);
1313
+ expect(tab.peekByIds('user', ['user:1'])).toBeNull();
1314
+ // What it kept at startup it keeps renewing.
1315
+ await tab.upsert('game', 'game:a', { n: 7 }, 'merge');
1316
+ const again = await tab.selectByIds('game', ids);
1317
+ expect(tab.peekByIds('game', ids)).toEqual(again);
1318
+ });
1319
+
1320
+ it('keeps nothing while the shared store lives in memory', async () => {
1321
+ const tab = await follow({ status: 'memory', fallback: true });
1322
+ await tab.selectByIds('game', ids);
1323
+ flush(tab);
1324
+ expect(tab.peekByIds('game', ids)).toBeNull();
1325
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.') && !k.includes('.t.'))).toEqual([]);
1326
+ // Nor does a leader that was granted a store in memory.
1327
+ const lost = shared();
1328
+ inProcessRows(lost, new Map());
1329
+ // The worker could not have the files and was allowed to open in memory.
1330
+ const seam = lost as unknown as { createTransport: () => { call: (type: string, ...rest: unknown[]) => Promise<object> } };
1331
+ const make = seam.createTransport;
1332
+ seam.createTransport = () => {
1333
+ const transport = make();
1334
+ const call = transport.call;
1335
+ transport.call = async (type, ...rest) => {
1336
+ const reply = await call(type, ...rest);
1337
+ return type === 'open' ? { ...reply, persisted: false, opfsError: 'held by another tab' } : reply;
1338
+ };
1339
+ return transport;
1340
+ };
1341
+ await lost.adoptOwner('user_m', { workerLockName: 'lock-m', allowMemoryFallback: true, resumeHeld: false });
1342
+ expect(lost.storageHealth.status).toBe('memory');
1343
+ await lost.upsert('game', 'game:m', { n: 1 }, 'replace');
1344
+ await lost.selectByIds('game', ['game:m']);
1345
+ flush(lost);
1346
+ expect(lost.peekByIds('game', ['game:m'])).toBeNull();
1347
+ expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_m'))).toEqual([]);
1348
+ });
1349
+ });
1350
+
1351
+ describe('PaintCache marks', () => {
1352
+ const g = globalThis as Record<string, unknown>;
1353
+ let stored: Map<string, string>;
1354
+ const rows = JSON.stringify([{ id: 'game:a', n: 1 }]);
1355
+ const none = (b64: string): Uint8Array => new Uint8Array(b64.length);
1356
+ const open = (max = 1_000_000): PaintCache => {
1357
+ const cache = new PaintCache(max);
1358
+ cache.start('user_a');
1359
+ return cache;
1360
+ };
1361
+
1362
+ beforeEach(() => {
1363
+ stored = new Map();
1364
+ g.localStorage = {
1365
+ getItem: (k: string) => stored.get(k) ?? null,
1366
+ setItem: (k: string, v: string) => void stored.set(k, v),
1367
+ removeItem: (k: string) => void stored.delete(k),
1368
+ key: (i: number) => [...stored.keys()][i] ?? null,
1369
+ get length() {
1370
+ return stored.size;
1371
+ },
1372
+ };
1373
+ });
1374
+
1375
+ afterEach(() => {
1376
+ delete g.localStorage;
1377
+ });
1378
+
1379
+ it('keeps a tab\'s own read that was queued behind its write', () => {
1380
+ const a = open();
1381
+ a.touch(['game']);
1382
+ const sent = a.stamp(['game']);
1383
+ // The store answers the write, then the read.
1384
+ a.touch(['game'], true);
1385
+ a.note('k', ['game'], rows, false, sent);
1386
+ expect(a.get('k', none)).toEqual(JSON.parse(rows));
1387
+ // A read sent before the write is another matter.
1388
+ const early = a.stamp(['game']);
1389
+ a.touch(['game']);
1390
+ a.touch(['game'], true);
1391
+ a.note('k2', ['game'], rows, false, early);
1392
+ expect(a.get('k2', none)).toBeNull();
1393
+ });
1394
+
1395
+ it('voids the copy a tab took between another tab\'s write being sent and being taken', () => {
1396
+ const a = open();
1397
+ const b = open();
1398
+ a.touch(['game']);
1399
+ // B reads after A's first mark, and the store answers it before A's write.
1400
+ const sent = b.stamp(['game']);
1401
+ b.note('k', ['game'], rows, false, sent);
1402
+ expect(b.get('k', none)).not.toBeNull();
1403
+ a.touch(['game'], true);
1404
+ expect(b.get('k', none)).toBeNull();
1405
+ b.flush();
1406
+ expect(stored.has('sp00ky.paint.user_a.k')).toBe(false);
1407
+ });
1408
+
1409
+ it('counts another tab\'s write against a read on its way, even under a mark of its own', () => {
1410
+ const a = open();
1411
+ const b = open();
1412
+ const sent = b.stamp(['game']);
1413
+ a.touch(['game']);
1414
+ a.touch(['game'], true);
1415
+ // B writes too before its read answers: A's mark is covered, not forgotten.
1416
+ b.touch(['user']);
1417
+ b.note('k', ['game'], rows, false, sent);
1418
+ expect(b.get('k', none)).toBeNull();
1419
+ const again = b.stamp(['game']);
1420
+ b.note('k', ['game'], rows, false, again);
1421
+ expect(b.get('k', none)).not.toBeNull();
1422
+ });
1423
+
1424
+ it('keeps one budget for all tabs and clears out what no longer stands', () => {
1425
+ const big = JSON.stringify([{ id: 'game:a', pad: 'p'.repeat(400) }]);
1426
+ const a = open(1000);
1427
+ const b = open(1000);
1428
+ a.note('a1', ['game'], big, false, a.stamp(['game']));
1429
+ a.flush();
1430
+ b.note('b1', ['user'], big, false, b.stamp(['user']));
1431
+ b.note('b2', ['user'], big, false, b.stamp(['user']));
1432
+ b.flush();
1433
+ // B's two fill the budget: A's is the one that goes.
1434
+ expect(stored.has('sp00ky.paint.user_a.a1')).toBe(false);
1435
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!)).sort()).toEqual(['b1', 'b2']);
1436
+
1437
+ // A copy from another release, and one whose table was written by a tab that is gone.
1438
+ stored.set('sp00ky.paint.user_a.old', '0[{"id":"game:z"}]');
1439
+ stored.set('sp00ky.paint.user_a', JSON.stringify({ ...JSON.parse(stored.get('sp00ky.paint.user_a')!), old: ['game'] }));
1440
+ const c = open(1000);
1441
+ expect(c.get('old', none)).toBeNull();
1442
+ stored.set('sp00ky.paint.user_a.t.user', 'gone.1');
1443
+ expect(c.get('b1', none)).toBeNull();
1444
+ c.flush();
1445
+ expect([...stored.keys()].filter((k) => !k.includes('.t.')).sort()).toEqual(['sp00ky.paint.user_a']);
1446
+ expect(JSON.parse(stored.get('sp00ky.paint.user_a')!)).toEqual({});
1447
+ });
1448
+
1449
+ it('tells the other tabs even when there is no room for a mark', () => {
1450
+ const a = open();
1451
+ const b = open();
1452
+ a.touch(['game']);
1453
+ a.touch(['game'], true);
1454
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1455
+ expect(b.get('k', none)).not.toBeNull();
1456
+ const setItem = (g.localStorage as { setItem: unknown }).setItem;
1457
+ (g.localStorage as { setItem: unknown }).setItem = () => {
1458
+ throw new Error('QuotaExceededError');
1459
+ };
1460
+ a.touch(['game']);
1461
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1462
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(false);
1463
+ expect(b.get('k', none)).toBeNull();
1464
+ });
1465
+
1466
+ it('makes room for a mark by letting the copies go, on a table that never had one too', () => {
1467
+ const a = open();
1468
+ const b = open();
1469
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1470
+ b.note('u', ['user'], rows, false, b.stamp(['user']));
1471
+ b.flush();
1472
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(false);
1473
+ // Full: a new key does not fit, an existing one can still be removed.
1474
+ const setItem = (g.localStorage as { setItem: (k: string, v: string) => void }).setItem;
1475
+ (g.localStorage as { setItem: unknown }).setItem = (k: string, v: string) => {
1476
+ if ([...stored.keys()].some((name) => /^sp00ky\.paint\.user_a\.[^.]+$/.test(name))) throw new Error('QuotaExceededError');
1477
+ setItem(k, v);
1478
+ };
1479
+ a.touch(['game']);
1480
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1481
+ // The copies went, the mark is there, and no tab hands out what it held.
1482
+ expect(stored.has('sp00ky.paint.user_a.t.game')).toBe(true);
1483
+ expect([...stored.keys()].filter((name) => /^sp00ky\.paint\.user_a\.[^.]+$/.test(name))).toEqual([]);
1484
+ expect(b.get('k', none)).toBeNull();
1485
+ });
1486
+
1487
+ it('saves the copies that fit when one does not, and lets go of copies the index lost', () => {
1488
+ const a = open();
1489
+ a.note('fits', ['game'], rows, false, a.stamp(['game']));
1490
+ a.note('too-big', ['user'], rows, false, a.stamp(['user']));
1491
+ const setItem = (g.localStorage as { setItem: (k: string, v: string) => void }).setItem;
1492
+ (g.localStorage as { setItem: unknown }).setItem = (k: string, v: string) => {
1493
+ if (k.endsWith('.too-big')) throw new Error('QuotaExceededError');
1494
+ setItem(k, v);
1495
+ };
1496
+ a.flush();
1497
+ (g.localStorage as { setItem: unknown }).setItem = setItem;
1498
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!))).toEqual(['fits']);
1499
+ expect(a.get('fits', none)).not.toBeNull();
1500
+
1501
+ // A copy two tabs saving at once left out of the index. Its table is written, then some tab saves.
1502
+ const stray = stored.get('sp00ky.paint.user_a.fits')!;
1503
+ stored.set('sp00ky.paint.user_a.stray', stray);
1504
+ const b = open();
1505
+ b.touch(['game']);
1506
+ b.touch(['game'], true);
1507
+ b.flush();
1508
+ expect(stored.has('sp00ky.paint.user_a.stray')).toBe(false);
1509
+ // One that still stands is taken into the index, and goes with the next write to its table.
1510
+ b.note('again', ['game'], rows, false, b.stamp(['game']));
1511
+ b.flush();
1512
+ stored.set('sp00ky.paint.user_a.stray2', stored.get('sp00ky.paint.user_a.again')!);
1513
+ const c = open();
1514
+ c.flush();
1515
+ expect(Object.keys(JSON.parse(stored.get('sp00ky.paint.user_a')!)).sort()).toEqual(['again', 'stray2']);
1516
+ c.touch(['game']);
1517
+ expect(stored.has('sp00ky.paint.user_a.stray2')).toBe(false);
1518
+ });
1519
+
1520
+ it('hands out another tab\'s newer copy when its own no longer stands', () => {
1521
+ const a = open();
1522
+ const b = open();
1523
+ b.note('k', ['game'], rows, false, b.stamp(['game']));
1524
+ a.touch(['game']);
1525
+ a.touch(['game'], true);
1526
+ const newer = JSON.stringify([{ id: 'game:a', n: 2 }]);
1527
+ a.note('k', ['game'], newer, false, a.stamp(['game']));
1528
+ a.flush();
1529
+ expect(b.get('k', none)).toEqual(JSON.parse(newer));
1530
+ });
1531
+
1532
+ it('leaves no marks, and touches storage for no write, in a tab that is alone in the store', () => {
1533
+ const solo = new PaintCache(1_000_000, false);
1534
+ solo.start('user_a');
1535
+ let calls = 0;
1536
+ const real = g.localStorage as Record<string, unknown>;
1537
+ g.localStorage = new Proxy(real, {
1538
+ get: (target, prop) => {
1539
+ const value = target[prop as string];
1540
+ if (typeof value !== 'function') return value;
1541
+ return (...args: unknown[]) => {
1542
+ calls++;
1543
+ return (value as (...a: unknown[]) => unknown)(...args);
1544
+ };
1545
+ },
1546
+ });
1547
+ for (let i = 0; i < 100; i++) {
1548
+ solo.touch(['game']);
1549
+ solo.touch(['game'], true);
1550
+ }
1551
+ // The index is read once; after that a write costs nothing while no copy of its table is kept.
1552
+ expect(calls).toBeLessThanOrEqual(1);
1553
+ expect([...stored.keys()].filter((k) => k.includes('.t.'))).toEqual([]);
1554
+ // Its own writes still drop its copies, and an overtaken read is still not kept.
1555
+ const early = solo.stamp(['game']);
1556
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1557
+ solo.flush();
1558
+ expect(solo.get('k', none)).not.toBeNull();
1559
+ solo.touch(['game']);
1560
+ expect(solo.get('k', none)).toBeNull();
1561
+ solo.note('k', ['game'], rows, false, early);
1562
+ expect(solo.get('k', none)).toBeNull();
1563
+ // A copy it cannot account for (not in the index) is not kept on trust.
1564
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1565
+ solo.flush();
1566
+ stored.set('sp00ky.paint.user_a.stray', stored.get('sp00ky.paint.user_a.k')!);
1567
+ solo.note('k', ['game'], rows, false, solo.stamp(['game']));
1568
+ solo.flush();
1569
+ expect(stored.has('sp00ky.paint.user_a.stray')).toBe(false);
1570
+ g.localStorage = real;
1571
+ });
1572
+
1573
+ it('never keeps a read under the bucket that came after it', () => {
1574
+ const a = open();
1575
+ const sent = a.stamp(['game']);
1576
+ a.start('user_b');
1577
+ a.note('k', ['game'], rows, false, sent);
1578
+ expect(a.get('k', none)).toBeNull();
1579
+ a.stop();
1580
+ expect(a.stamp(['game'])).toBe('');
1581
+ a.touch(['game']);
1582
+ expect([...stored.keys()].filter((k) => k.includes('user_b'))).toEqual([]);
1583
+ });
1584
+ });