@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -3
- package/dist/index.d.ts +169 -9
- package/dist/index.js +4512 -2338
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +129 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +157 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +39 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
|
@@ -0,0 +1,1014 @@
|
|
|
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
|
+
RowsCacheEngine,
|
|
6
|
+
ROWS_DURABLE_TABLES,
|
|
7
|
+
ROWS_PREWARM_KEY,
|
|
8
|
+
ROWS_PREWARM_SNIPPET,
|
|
9
|
+
packWrites,
|
|
10
|
+
prewarmRows,
|
|
11
|
+
} from './rows-cache-engine';
|
|
12
|
+
import { createLocalEngine } from './engine-factory';
|
|
13
|
+
import { FakeRowsWorker, inProcessRows, type RowsDisks, type RowsHost } from './rows-transport.fixture';
|
|
14
|
+
import { ROWS_CLIENT_OPS, maintenance } from './rows-exec';
|
|
15
|
+
import type { StoreStats } from './rows-store';
|
|
16
|
+
import { columnFingerprints } from './sqlite-column-reset';
|
|
17
|
+
import { surql } from '../../utils/surql';
|
|
18
|
+
import type { Row } from './cache-engine';
|
|
19
|
+
|
|
20
|
+
const logger = {
|
|
21
|
+
info() {},
|
|
22
|
+
warn() {},
|
|
23
|
+
error() {},
|
|
24
|
+
debug() {},
|
|
25
|
+
trace() {},
|
|
26
|
+
child() {
|
|
27
|
+
return logger;
|
|
28
|
+
},
|
|
29
|
+
} as any;
|
|
30
|
+
|
|
31
|
+
let engine: RowsCacheEngine;
|
|
32
|
+
let host: RowsHost;
|
|
33
|
+
|
|
34
|
+
async function boot(disks?: RowsDisks, bucket = 'user_a'): Promise<void> {
|
|
35
|
+
engine = new RowsCacheEngine({ store: 'indexeddb' } as any, logger, { useOpfs: true });
|
|
36
|
+
host = inProcessRows(engine, disks);
|
|
37
|
+
await engine.connect(bucket);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
beforeEach(() => boot());
|
|
41
|
+
|
|
42
|
+
describe('RowsCacheEngine: verbs', () => {
|
|
43
|
+
it('is what `localEngine: "rows"` builds', () => {
|
|
44
|
+
const built = createLocalEngine('rows', { store: 'indexeddb' } as any, logger);
|
|
45
|
+
expect(built).toBeInstanceOf(RowsCacheEngine);
|
|
46
|
+
expect(built.engineKind).toBe('rows');
|
|
47
|
+
expect(built.usesSurqlSchema).toBe(false);
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it('writes, reads, merges and deletes rows', async () => {
|
|
51
|
+
await engine.upsert('game', 'game:a', { title: 'Alpha', moves: 3, _00_rv: 2 }, 'replace');
|
|
52
|
+
await engine.upsert('game', new RecordId('game', 'b'), { title: 'Beta', white: new RecordId('user', '1') }, 'replace');
|
|
53
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', title: 'Alpha', moves: 3, _00_rv: 2 });
|
|
54
|
+
// A record link is stored, and read back, as its `table:id` string.
|
|
55
|
+
expect(await engine.getById('game', new RecordId('game', 'b'))).toEqual({ id: 'game:b', title: 'Beta', white: 'user:1' });
|
|
56
|
+
expect(await engine.getById('game', 'game:none')).toBeNull();
|
|
57
|
+
|
|
58
|
+
await engine.upsert('game', 'game:a', { moves: 4, extra: { k: 1 }, title: undefined }, 'merge');
|
|
59
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', moves: 4, _00_rv: 2, extra: { k: 1 } });
|
|
60
|
+
|
|
61
|
+
await engine.delete('game', 'game:a');
|
|
62
|
+
expect(await engine.getById('game', 'game:a')).toBeNull();
|
|
63
|
+
expect(await engine.selectByIds('game', ['game:a', 'game:b'])).toEqual([{ id: 'game:b', title: 'Beta', white: 'user:1' }]);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('keeps bytes as bytes', async () => {
|
|
67
|
+
const state = new Uint8Array([1, 2, 3, 254, 255]);
|
|
68
|
+
await engine.upsert('doc', 'doc:1', { state, sdk: state.slice().buffer, n: 1 }, 'replace');
|
|
69
|
+
const row = (await engine.getById('doc', 'doc:1'))!;
|
|
70
|
+
expect(row.state).toEqual(state);
|
|
71
|
+
// The SDK hands bytes over as an ArrayBuffer; they come back as a Uint8Array.
|
|
72
|
+
expect(row.sdk).toEqual(state);
|
|
73
|
+
expect((await engine.selectByIds('doc', ['doc:1']))[0].state).toEqual(state);
|
|
74
|
+
expect((await engine.select({ table: 'doc' }))[0].state).toEqual(state);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it('selects by plan with record ids in the filter, the params and the window', async () => {
|
|
78
|
+
await engine.execute(
|
|
79
|
+
surql.seal(surql.tx([surql.upsertMerge('a', 'da'), surql.upsertMerge('b', 'db'), surql.upsertMerge('c', 'dc')])),
|
|
80
|
+
{
|
|
81
|
+
a: new RecordId('game', 'a'),
|
|
82
|
+
da: { white: new RecordId('user', '1'), moves: 10 },
|
|
83
|
+
b: new RecordId('game', 'b'),
|
|
84
|
+
db: { white: new RecordId('user', '2'), moves: 20 },
|
|
85
|
+
c: new RecordId('game', 'c'),
|
|
86
|
+
dc: { white: new RecordId('user', '1'), moves: 30 },
|
|
87
|
+
}
|
|
88
|
+
);
|
|
89
|
+
const byWhite: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: new RecordId('user', '1') }] };
|
|
90
|
+
expect((await engine.select(byWhite)).map((r) => r.id)).toEqual(['game:a', 'game:c']);
|
|
91
|
+
const byParam: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: undefined, paramRef: 'who' }] };
|
|
92
|
+
expect((await engine.select(byParam, { who: new RecordId('user', '2') })).map((r) => r.id)).toEqual(['game:b']);
|
|
93
|
+
const window: QueryPlan = { table: 'game', ids: [new RecordId('game', 'c'), 'game:a'], select: ['moves'] };
|
|
94
|
+
expect(await engine.select(window)).toEqual([
|
|
95
|
+
{ id: 'game:c', moves: 30 },
|
|
96
|
+
{ id: 'game:a', moves: 10 },
|
|
97
|
+
]);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('resolves relations in one round trip', async () => {
|
|
101
|
+
await engine.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
|
|
102
|
+
await engine.upsert('game', 'game:a', { white: 'user:1' }, 'replace');
|
|
103
|
+
await engine.upsert('comment', 'comment:1', { game: 'game:a', rank: 2 }, 'replace');
|
|
104
|
+
await engine.upsert('comment', 'comment:2', { game: 'game:a', rank: 1 }, 'replace');
|
|
105
|
+
host.calls.length = 0;
|
|
106
|
+
const rows = await engine.select({
|
|
107
|
+
table: 'game',
|
|
108
|
+
relations: [
|
|
109
|
+
{ alias: 'white', table: 'user', cardinality: 'one', foreignKeyField: 'white' },
|
|
110
|
+
{ alias: 'comments', table: 'comment', cardinality: 'many', foreignKeyField: 'game', orderBy: [['rank', 'asc']] },
|
|
111
|
+
],
|
|
112
|
+
});
|
|
113
|
+
expect(rows).toEqual([
|
|
114
|
+
{
|
|
115
|
+
id: 'game:a',
|
|
116
|
+
white: { id: 'user:1', name: 'Ada' },
|
|
117
|
+
comments: [
|
|
118
|
+
{ id: 'comment:2', game: 'game:a', rank: 1 },
|
|
119
|
+
{ id: 'comment:1', game: 'game:a', rank: 2 },
|
|
120
|
+
],
|
|
121
|
+
},
|
|
122
|
+
]);
|
|
123
|
+
expect(host.calls.map((c) => c.type)).toEqual(['select']);
|
|
124
|
+
expect(await engine.fetchRelation({ table: 'comment', matchField: 'game', keys: [new RecordId('game', 'a')], orderBy: [['rank', 'desc']] })).toEqual([
|
|
125
|
+
{ id: 'comment:1', game: 'game:a', rank: 2 },
|
|
126
|
+
{ id: 'comment:2', game: 'game:a', rank: 1 },
|
|
127
|
+
]);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('applies RFC 6902 patches and runs a transaction of verbs', async () => {
|
|
131
|
+
await engine.upsert('game', 'game:a', { tags: ['x'], n: 1 }, 'replace');
|
|
132
|
+
await engine.patch('game', 'game:a', [
|
|
133
|
+
{ op: 'add', path: '/tags/-', value: 'y' },
|
|
134
|
+
{ op: 'replace', path: '/n', value: 2 },
|
|
135
|
+
]);
|
|
136
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', tags: ['x', 'y'], n: 2 });
|
|
137
|
+
await engine.transaction(async (tx) => {
|
|
138
|
+
await tx.upsert('game', 'game:b', { n: 1 }, 'replace');
|
|
139
|
+
await tx.patch('game', 'game:b', [{ op: 'add', path: '/m', value: true }]);
|
|
140
|
+
await tx.delete('game', 'game:a');
|
|
141
|
+
});
|
|
142
|
+
expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:b', n: 1, m: true }]);
|
|
143
|
+
});
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
describe('RowsCacheEngine: the SurrealQL statements the client emits', () => {
|
|
147
|
+
it('creates a row and its outbox entry in one atomic, flushed batch', async () => {
|
|
148
|
+
const file = host.disks.get('user_a')!.a;
|
|
149
|
+
const flushes = file.flushes;
|
|
150
|
+
host.calls.length = 0;
|
|
151
|
+
const sealed = surql.seal(
|
|
152
|
+
surql.tx([
|
|
153
|
+
surql.createSet('id', [
|
|
154
|
+
{ key: 'provider', variable: 'data_provider' },
|
|
155
|
+
{ key: 'username', variable: 'data_username' },
|
|
156
|
+
]),
|
|
157
|
+
surql.createMutation('create', 'mid', 'id', 'data'),
|
|
158
|
+
]),
|
|
159
|
+
{ resultIndex: 0 }
|
|
160
|
+
);
|
|
161
|
+
const created = (await engine.execute(sealed, {
|
|
162
|
+
id: new RecordId('connection', 'CONN_abc'),
|
|
163
|
+
mid: new RecordId('_00_pending_mutations', '1'),
|
|
164
|
+
data_provider: 'chesscom',
|
|
165
|
+
data_username: 'hikaru',
|
|
166
|
+
data: { provider: 'chesscom', username: 'hikaru' },
|
|
167
|
+
})) as unknown as Row;
|
|
168
|
+
expect(created.id).toBe('connection:CONN_abc');
|
|
169
|
+
expect(created.provider).toBe('chesscom');
|
|
170
|
+
// One message for both rows, and the outbox makes it a flushed write.
|
|
171
|
+
expect(host.calls.map((c) => c.type)).toEqual(['write']);
|
|
172
|
+
expect(host.calls[0].payload.sync).toBe(true);
|
|
173
|
+
expect(host.calls[0].payload.ops.length).toBe(2);
|
|
174
|
+
expect(file.flushes).toBe(flushes + 1);
|
|
175
|
+
expect(await engine.getById('connection', 'connection:CONN_abc')).toEqual({
|
|
176
|
+
id: 'connection:CONN_abc',
|
|
177
|
+
provider: 'chesscom',
|
|
178
|
+
username: 'hikaru',
|
|
179
|
+
});
|
|
180
|
+
const [pending] = await engine.query<[Row[]]>('SELECT * FROM _00_pending_mutations ORDER BY id ASC');
|
|
181
|
+
expect(pending.length).toBe(1);
|
|
182
|
+
expect(pending[0].id).toBe('_00_pending_mutations:1');
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('does not flush a write that only copies server state', async () => {
|
|
186
|
+
const file = host.disks.get('user_a')!.a;
|
|
187
|
+
const flushes = file.flushes;
|
|
188
|
+
await engine.execute(surql.seal(surql.tx([surql.upsertMerge('id', 'data')])), { id: new RecordId('game', 'a'), data: { n: 1 } });
|
|
189
|
+
expect(host.calls.at(-1)!.payload.sync).toBe(false);
|
|
190
|
+
expect(file.flushes).toBe(flushes);
|
|
191
|
+
expect(ROWS_DURABLE_TABLES.has('_00_pending_mutations')).toBe(true);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('answers the raw selects, counts and INFO', async () => {
|
|
195
|
+
for (let i = 0; i < 6; i++) {
|
|
196
|
+
await engine.upsert('game_insight', `game_insight:${i}`, { tag: i % 2 ? 'odd' : 'even', n: i }, 'replace');
|
|
197
|
+
}
|
|
198
|
+
const [all] = await engine.query<[Row[]]>('SELECT * FROM game_insight');
|
|
199
|
+
expect(all.map((r) => r.n)).toEqual([0, 1, 2, 3, 4, 5]);
|
|
200
|
+
const [window] = await engine.query<[Row[]]>('SELECT * FROM game_insight LIMIT 2 START 3');
|
|
201
|
+
expect(window.map((r) => r.n)).toEqual([3, 4]);
|
|
202
|
+
const [filtered] = await engine.query<[Row[]]>("SELECT * FROM game_insight WHERE tag = 'odd' ORDER BY n DESC");
|
|
203
|
+
expect(filtered.map((r) => r.n)).toEqual([5, 3, 1]);
|
|
204
|
+
const [values] = await engine.query<[unknown[]]>('SELECT VALUE n FROM game_insight WHERE n >= 4');
|
|
205
|
+
expect(values).toEqual([4, 5]);
|
|
206
|
+
const [fields] = await engine.query<[Row[]]>('SELECT tag, n FROM game_insight LIMIT 1');
|
|
207
|
+
expect(fields).toEqual([{ id: 'game_insight:0', tag: 'even', n: 0 }]);
|
|
208
|
+
expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM game_insight GROUP ALL'))[0]).toEqual([{ count: 6 }]);
|
|
209
|
+
expect((await engine.query<[{ count: number }[]]>("SELECT count() FROM game_insight WHERE tag = 'odd' GROUP ALL"))[0]).toEqual([{ count: 3 }]);
|
|
210
|
+
expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM empty GROUP ALL'))[0]).toEqual([{ count: 0 }]);
|
|
211
|
+
const [info] = await engine.query<[{ tables: Record<string, string> }]>('INFO FOR DB');
|
|
212
|
+
expect(Object.keys(info.tables)).toEqual(['game_insight']);
|
|
213
|
+
|
|
214
|
+
const [one] = await engine.query<[Row | null]>('SELECT * FROM ONLY $id', { id: new RecordId('game_insight', '2') });
|
|
215
|
+
expect(one).toEqual({ id: 'game_insight:2', tag: 'even', n: 2 });
|
|
216
|
+
const [some] = await engine.query<[Row[]]>('SELECT * FROM $ids', {
|
|
217
|
+
ids: [new RecordId('game_insight', '5'), new RecordId('game_insight', 'x'), new RecordId('game_insight', '1')],
|
|
218
|
+
});
|
|
219
|
+
expect(some.map((r) => r.n)).toEqual([5, 1]);
|
|
220
|
+
|
|
221
|
+
await engine.query('DELETE $id', { id: new RecordId('game_insight', '0') });
|
|
222
|
+
expect((await engine.query<[{ count: number }[]]>('SELECT count() FROM game_insight GROUP ALL'))[0]).toEqual([{ count: 5 }]);
|
|
223
|
+
await engine.query('DELETE game_insight');
|
|
224
|
+
expect((await engine.query<[Row[]]>('SELECT * FROM game_insight'))[0]).toEqual([]);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it('runs a LET / UPDATE SET / RETURN transaction against the stored row', async () => {
|
|
228
|
+
await engine.upsert('counter', 'counter:1', { n: 5, label: 'old' }, 'replace');
|
|
229
|
+
const res = await engine.query<unknown[]>(
|
|
230
|
+
'BEGIN TRANSACTION; LET $updated = (UPDATE $id SET n += $by, label = $label); RETURN { target: $updated }; COMMIT TRANSACTION;',
|
|
231
|
+
{ id: new RecordId('counter', '1'), by: 3, label: 'new' }
|
|
232
|
+
);
|
|
233
|
+
expect(res.at(-1)).toEqual({ target: { id: 'counter:1', n: 8, label: 'new' } });
|
|
234
|
+
expect(await engine.getById('counter', 'counter:1')).toEqual({ id: 'counter:1', n: 8, label: 'new' });
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
it('refuses a write under a stale epoch', async () => {
|
|
238
|
+
const epoch = engine.epoch;
|
|
239
|
+
await engine.switchBucket('user_b');
|
|
240
|
+
await expect(engine.query('DELETE game', {}, { epoch })).rejects.toThrow();
|
|
241
|
+
});
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
describe('RowsCacheEngine: store lifecycle', () => {
|
|
245
|
+
it('keeps each bucket apart and finds its rows again after a reopen', async () => {
|
|
246
|
+
const disks: RowsDisks = new Map();
|
|
247
|
+
await boot(disks, 'user_a');
|
|
248
|
+
await engine.upsert('game', 'game:a', { owner: 'a' }, 'replace');
|
|
249
|
+
await engine.switchBucket('user_b');
|
|
250
|
+
expect(engine.currentBucketId).toBe('user_b');
|
|
251
|
+
expect(await engine.getById('game', 'game:a')).toBeNull();
|
|
252
|
+
await engine.upsert('game', 'game:b', { owner: 'b' }, 'replace');
|
|
253
|
+
await engine.close();
|
|
254
|
+
|
|
255
|
+
await boot(disks, 'user_a');
|
|
256
|
+
expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:a', owner: 'a' }]);
|
|
257
|
+
await engine.switchBucket('user_b');
|
|
258
|
+
expect(await engine.select({ table: 'game' })).toEqual([{ id: 'game:b', owner: 'b' }]);
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
it('reports a durable store and its numbers', async () => {
|
|
262
|
+
expect(engine.storageHealth).toEqual({ status: 'persistent', fallback: false });
|
|
263
|
+
await engine.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
264
|
+
await engine.upsert('user', 'user:1', { n: 1 }, 'replace');
|
|
265
|
+
await engine.putSnapshot('circuit', new Uint8Array([1, 2, 3]), { formatVersion: 1, schemaHash: 'h', savedAt: 1 });
|
|
266
|
+
const diag = await engine.getStorageDiagnostics({ tableCounts: true });
|
|
267
|
+
expect(diag.engine).toBe('rows');
|
|
268
|
+
expect(diag.bucketId).toBe('user_a');
|
|
269
|
+
expect(diag.dbSizeBytes).toBeGreaterThan(4096);
|
|
270
|
+
expect(diag.tableCounts).toEqual([
|
|
271
|
+
{ table: 'game', rows: 1 },
|
|
272
|
+
{ table: 'user', rows: 1 },
|
|
273
|
+
]);
|
|
274
|
+
expect((await engine.getStorageDiagnostics()).tableCounts).toBeUndefined();
|
|
275
|
+
expect(() => engine.getClient()).toThrow();
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('stores the circuit snapshot without taking the caller\'s bytes', async () => {
|
|
279
|
+
const bytes = new Uint8Array(100_000);
|
|
280
|
+
for (let i = 0; i < bytes.length; i++) bytes[i] = (i * 13) & 255;
|
|
281
|
+
const meta = { formatVersion: 3, schemaHash: 'abc', savedAt: 1700000000000, maxRv: { game: 9 } };
|
|
282
|
+
await engine.putSnapshot('circuit', bytes, meta);
|
|
283
|
+
expect(bytes.byteLength).toBe(100_000);
|
|
284
|
+
const stored = (await engine.getSnapshot('circuit'))!;
|
|
285
|
+
expect(stored.bytes).toEqual(bytes);
|
|
286
|
+
expect(stored.meta).toEqual(meta);
|
|
287
|
+
expect(await engine.getSnapshot('other')).toBeNull();
|
|
288
|
+
// The snapshot's rows are no row a query returns.
|
|
289
|
+
expect((await engine.query<[Row[]]>('SELECT * FROM _00_circuit_snapshot'))[0]).toEqual([]);
|
|
290
|
+
await engine.deleteSnapshot('circuit');
|
|
291
|
+
expect(await engine.getSnapshot('circuit')).toBeNull();
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it('scans versions from the index and resets them when a table\'s columns change', async () => {
|
|
295
|
+
await engine.upsert('game', 'game:a', { _00_rv: 4, title: 'a' }, 'replace');
|
|
296
|
+
await engine.upsert('game', 'game:b', { _00_rv: 7, title: 'b' }, 'replace');
|
|
297
|
+
await engine.upsert('user', 'user:1', { _00_rv: 2 }, 'replace');
|
|
298
|
+
expect(await engine.scanVersions(['game', 'user', 'absent'])).toEqual({
|
|
299
|
+
game: [
|
|
300
|
+
['game:a', 4],
|
|
301
|
+
['game:b', 7],
|
|
302
|
+
],
|
|
303
|
+
user: [['user:1', 2]],
|
|
304
|
+
absent: [],
|
|
305
|
+
});
|
|
306
|
+
|
|
307
|
+
const v1 = columnFingerprints([
|
|
308
|
+
{ name: 'game', columns: { title: 1 } },
|
|
309
|
+
{ name: 'user', columns: { name: 1 } },
|
|
310
|
+
]);
|
|
311
|
+
// Nothing recorded yet: every table that holds rows is reset once.
|
|
312
|
+
expect((await engine.resetChangedTables(v1, new Set(['game:b']))).sort()).toEqual(['game', 'user']);
|
|
313
|
+
expect((await engine.scanVersions(['game', 'user']))).toEqual({
|
|
314
|
+
game: [
|
|
315
|
+
['game:a', 0],
|
|
316
|
+
['game:b', 7],
|
|
317
|
+
],
|
|
318
|
+
user: [['user:1', 0]],
|
|
319
|
+
});
|
|
320
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', _00_rv: 0, title: 'a' });
|
|
321
|
+
|
|
322
|
+
await engine.upsert('game', 'game:a', { _00_rv: 5 }, 'merge');
|
|
323
|
+
await engine.upsert('user', 'user:1', { _00_rv: 3 }, 'merge');
|
|
324
|
+
// Same columns: nothing to do.
|
|
325
|
+
expect(await engine.resetChangedTables(v1, new Set())).toEqual([]);
|
|
326
|
+
const v2 = columnFingerprints([
|
|
327
|
+
{ name: 'game', columns: { title: 1, layout: 1 } },
|
|
328
|
+
{ name: 'user', columns: { name: 1 } },
|
|
329
|
+
]);
|
|
330
|
+
expect(await engine.resetChangedTables(v2, new Set())).toEqual(['game']);
|
|
331
|
+
expect(await engine.scanVersions(['game', 'user'])).toEqual({
|
|
332
|
+
game: [
|
|
333
|
+
['game:a', 0],
|
|
334
|
+
['game:b', 0],
|
|
335
|
+
],
|
|
336
|
+
user: [['user:1', 3]],
|
|
337
|
+
});
|
|
338
|
+
// The recorded sets are not a row.
|
|
339
|
+
expect((await engine.query<[Row[]]>('SELECT * FROM _00_schema'))[0]).toEqual([]);
|
|
340
|
+
});
|
|
341
|
+
|
|
342
|
+
it('serves a follower over a port and survives the leader handing over', async () => {
|
|
343
|
+
const disks: RowsDisks = new Map();
|
|
344
|
+
await boot(disks);
|
|
345
|
+
const health = await engine.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
|
|
346
|
+
expect(health.role ?? 'leader').toBe('leader');
|
|
347
|
+
await engine.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
348
|
+
const before = engine.epoch;
|
|
349
|
+
await engine.adoptOwner('user_a', { workerLockName: 'lock-2', allowMemoryFallback: false, resumeHeld: false });
|
|
350
|
+
expect(engine.epoch).toBeGreaterThan(before);
|
|
351
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
describe('a follower that reads the store\'s file itself', () => {
|
|
356
|
+
let disks: RowsDisks;
|
|
357
|
+
let leader: RowsCacheEngine;
|
|
358
|
+
let host: ReturnType<typeof inProcessRows>;
|
|
359
|
+
/** Workers followers started for reading. */
|
|
360
|
+
let readers: FakeRowsWorker[];
|
|
361
|
+
const attached = { bucketId: 'user_a', storageHealth: { status: 'persistent', fallback: false } as const };
|
|
362
|
+
|
|
363
|
+
const follower = (config: Record<string, unknown> = { followerReads: 'direct' }): RowsCacheEngine =>
|
|
364
|
+
new RowsCacheEngine(
|
|
365
|
+
{
|
|
366
|
+
store: 'indexeddb',
|
|
367
|
+
...config,
|
|
368
|
+
workers: {
|
|
369
|
+
rows: () => {
|
|
370
|
+
const worker = new FakeRowsWorker(disks);
|
|
371
|
+
readers.push(worker);
|
|
372
|
+
return worker as unknown as Worker;
|
|
373
|
+
},
|
|
374
|
+
},
|
|
375
|
+
} as any,
|
|
376
|
+
logger,
|
|
377
|
+
{ useOpfs: true, shared: true }
|
|
378
|
+
);
|
|
379
|
+
|
|
380
|
+
/** A port into the leader's worker, as the tabs broker hands one to a follower. */
|
|
381
|
+
const leaderPort = () => {
|
|
382
|
+
const port = {
|
|
383
|
+
onmessage: null as null | ((ev: { data: unknown }) => void),
|
|
384
|
+
onmessageerror: null,
|
|
385
|
+
posted: [] as string[],
|
|
386
|
+
start() {},
|
|
387
|
+
close() {},
|
|
388
|
+
postMessage(msg: { id: number; type: string; payload: unknown }, transfer?: Transferable[]) {
|
|
389
|
+
port.posted.push(msg.type);
|
|
390
|
+
const payload = structuredClone(msg.payload, { transfer: transfer ?? [] });
|
|
391
|
+
void host.answer(msg.type, payload).then(
|
|
392
|
+
({ result, transfer: back }) =>
|
|
393
|
+
port.onmessage?.({ data: { id: msg.id, ok: true, wt: 0, ...(structuredClone(result, { transfer: back ?? [] }) as object) } }),
|
|
394
|
+
(error: unknown) => port.onmessage?.({ data: { id: msg.id, ok: false, error: String(error) } })
|
|
395
|
+
);
|
|
396
|
+
},
|
|
397
|
+
};
|
|
398
|
+
return port;
|
|
399
|
+
};
|
|
400
|
+
const attach = async (tab: RowsCacheEngine) => {
|
|
401
|
+
const port = leaderPort();
|
|
402
|
+
await tab.adoptAttached(port as unknown as MessagePort, attached, () => {});
|
|
403
|
+
return port;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
beforeEach(async () => {
|
|
407
|
+
disks = new Map();
|
|
408
|
+
readers = [];
|
|
409
|
+
leader = new RowsCacheEngine({ store: 'indexeddb', followerReads: 'direct' } as any, logger, { useOpfs: true, shared: true });
|
|
410
|
+
host = inProcessRows(leader, disks);
|
|
411
|
+
await leader.adoptOwner('user_a', { workerLockName: 'lock-1', allowMemoryFallback: false, resumeHeld: false });
|
|
412
|
+
await leader.upsert('game', 'game:a', { n: 1, white: 'user:1' }, 'replace');
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
it('reads from its own worker, writes through the leader, and sees every write at once', async () => {
|
|
416
|
+
const tab = follower();
|
|
417
|
+
const port = await attach(tab);
|
|
418
|
+
expect(tab.readsDirectly).toBe(true);
|
|
419
|
+
expect(readers[0].posted.map((m) => m.type)).toEqual(['open']);
|
|
420
|
+
expect(await tab.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1, white: 'user:1' });
|
|
421
|
+
|
|
422
|
+
await tab.upsert('game', 'game:b', { n: 2, white: 'user:1' }, 'replace');
|
|
423
|
+
expect((await tab.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
|
|
424
|
+
// Another tab's write, and the leader's own.
|
|
425
|
+
await leader.upsert('game', 'game:c', { n: 3, white: 'user:2' }, 'replace');
|
|
426
|
+
await leader.delete('game', 'game:a');
|
|
427
|
+
expect((await tab.select({ table: 'game' })).map((r) => r.id)).toEqual(['game:b', 'game:c']);
|
|
428
|
+
expect(await tab.scanVersions(['game'])).toEqual(await leader.scanVersions(['game']));
|
|
429
|
+
|
|
430
|
+
// Only the write crossed to the leader.
|
|
431
|
+
expect(port.posted).toEqual(['write']);
|
|
432
|
+
expect(readers[0].posted.map((m) => m.type)).toEqual(['open', 'get', 'by-ids', 'select', 'versions']);
|
|
433
|
+
});
|
|
434
|
+
|
|
435
|
+
it('uses the indexes the leader keeps and builds none of its own', async () => {
|
|
436
|
+
for (let i = 0; i < 80; i++) await leader.upsert('game', `game:x${i}`, { n: i, white: `user:${i % 20}` }, 'replace');
|
|
437
|
+
const byWhite: QueryPlan = { table: 'game', where: [{ field: 'white', op: '=', value: 'user:7' }] };
|
|
438
|
+
const byN: QueryPlan = { table: 'game', where: [{ field: 'n', op: '=', value: 7 }] };
|
|
439
|
+
const tab = follower();
|
|
440
|
+
const port = await attach(tab);
|
|
441
|
+
const size = (): number => disks.get('user_a')!.a.size() + disks.get('user_a')!.b.size();
|
|
442
|
+
const before = size();
|
|
443
|
+
// A field nobody indexed yet: the follower scans, and writes nothing to find out.
|
|
444
|
+
expect((await tab.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
|
|
445
|
+
expect(size()).toBe(before);
|
|
446
|
+
expect(await tab.select(byWhite)).toEqual(await leader.select(byWhite));
|
|
447
|
+
// The leader builds the index for `n`; the follower reads through it from then on.
|
|
448
|
+
expect((await leader.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
|
|
449
|
+
expect(size()).toBeGreaterThan(before);
|
|
450
|
+
expect((await tab.select(byN)).map((r) => r.id)).toEqual(['game:x7']);
|
|
451
|
+
expect(port.posted).toEqual([]);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
it('follows the rows through a compaction of the leader\'s', async () => {
|
|
455
|
+
const tab = follower();
|
|
456
|
+
await attach(tab);
|
|
457
|
+
for (let i = 0; i < 60; i++) await leader.upsert('game', `game:x${i}`, { n: i, pad: 'p'.repeat(300) }, 'replace');
|
|
458
|
+
expect((await tab.select({ table: 'game' })).length).toBe(61);
|
|
459
|
+
for (let i = 0; i < 50; i++) await leader.delete('game', `game:x${i}`);
|
|
460
|
+
await host.store()!.compact();
|
|
461
|
+
expect(host.store()!.stats().file).toBe('b');
|
|
462
|
+
expect(await tab.select({ table: 'game' })).toEqual(await leader.select({ table: 'game' }));
|
|
463
|
+
await leader.upsert('game', 'game:z', { n: 99 }, 'replace');
|
|
464
|
+
expect(await tab.getById('game', 'game:z')).toEqual({ id: 'game:z', n: 99 });
|
|
465
|
+
});
|
|
466
|
+
|
|
467
|
+
it('reads through the leader when it is not asked to read directly, or cannot', async () => {
|
|
468
|
+
const plain = follower({});
|
|
469
|
+
const plainPort = await attach(plain);
|
|
470
|
+
expect(plain.readsDirectly).toBe(false);
|
|
471
|
+
expect(readers).toEqual([]);
|
|
472
|
+
expect((await plain.getById('game', 'game:a'))?.n).toBe(1);
|
|
473
|
+
expect(plainPort.posted).toEqual(['get']);
|
|
474
|
+
|
|
475
|
+
// A browser without shared handles: the reader's open fails.
|
|
476
|
+
const tab = new RowsCacheEngine(
|
|
477
|
+
{
|
|
478
|
+
store: 'indexeddb',
|
|
479
|
+
followerReads: 'direct',
|
|
480
|
+
workers: {
|
|
481
|
+
rows: () => {
|
|
482
|
+
const worker = new FakeRowsWorker(disks);
|
|
483
|
+
worker.postMessage = (msg: { id: number }) =>
|
|
484
|
+
queueMicrotask(() => worker.onmessage?.({ data: { id: msg.id, ok: false, error: 'opfs-unavailable: shared access handles' } }));
|
|
485
|
+
readers.push(worker);
|
|
486
|
+
return worker as unknown as Worker;
|
|
487
|
+
},
|
|
488
|
+
},
|
|
489
|
+
} as any,
|
|
490
|
+
logger,
|
|
491
|
+
{ useOpfs: true, shared: true }
|
|
492
|
+
);
|
|
493
|
+
const port = await attach(tab);
|
|
494
|
+
expect(tab.readsDirectly).toBe(false);
|
|
495
|
+
expect(readers[0].terminated).toBe(true);
|
|
496
|
+
expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
|
|
497
|
+
expect(port.posted).toEqual(['get']);
|
|
498
|
+
});
|
|
499
|
+
|
|
500
|
+
it('asks the leader when its reader fails, and from then on', async () => {
|
|
501
|
+
const tab = follower();
|
|
502
|
+
const port = await attach(tab);
|
|
503
|
+
expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
|
|
504
|
+
readers[0].postMessage = () => readers[0].onerror?.({ message: 'out of memory' });
|
|
505
|
+
expect((await tab.getById('game', 'game:a'))?.n).toBe(1);
|
|
506
|
+
expect(tab.readsDirectly).toBe(false);
|
|
507
|
+
expect(readers[0].terminated).toBe(true);
|
|
508
|
+
expect((await tab.selectByIds('game', ['game:a'])).length).toBe(1);
|
|
509
|
+
expect(port.posted).toEqual(['get', 'by-ids']);
|
|
510
|
+
});
|
|
511
|
+
|
|
512
|
+
it('lets go of the reader when the role changes', async () => {
|
|
513
|
+
const tab = follower();
|
|
514
|
+
await attach(tab);
|
|
515
|
+
tab.onLeaderLost('leader tab closed');
|
|
516
|
+
expect(tab.readsDirectly).toBe(false);
|
|
517
|
+
expect(readers[0].terminated).toBe(true);
|
|
518
|
+
// A new leader, a new reader.
|
|
519
|
+
await attach(tab);
|
|
520
|
+
expect(tab.readsDirectly).toBe(true);
|
|
521
|
+
expect(readers.length).toBe(2);
|
|
522
|
+
await tab.close();
|
|
523
|
+
expect(readers[1].terminated).toBe(true);
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
|
|
527
|
+
describe('packWrites', () => {
|
|
528
|
+
it('lays every row\'s text in one buffer and says where', () => {
|
|
529
|
+
const { wire, buf, sync } = packWrites([
|
|
530
|
+
{ kind: 'upsert', table: 'game', key: 'game:a', data: { title: 'Épée \u{1f600}', _00_rv: 3 }, mode: 'replace' },
|
|
531
|
+
{ kind: 'upsert', table: 'game', key: 'game:b', data: { n: 1, gone: undefined, bytes: new Uint8Array([7]) }, mode: 'merge' },
|
|
532
|
+
{ kind: 'delete', table: 'game', key: 'game:c' },
|
|
533
|
+
{ kind: 'clear', table: 'old' },
|
|
534
|
+
]);
|
|
535
|
+
expect(sync).toBe(false);
|
|
536
|
+
const text = (off: number, len: number): string => new TextDecoder().decode(new Uint8Array(buf!, off, len));
|
|
537
|
+
expect(wire[0].slice(0, 5)).toEqual(['put', 'game', 'game:a', 3, 0]);
|
|
538
|
+
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' });
|
|
539
|
+
// A merge that clears a field carries a patch beside the row to insert.
|
|
540
|
+
expect(wire[1].slice(0, 5)).toEqual(['merge', 'game', 'game:b', 0, 1]);
|
|
541
|
+
expect(JSON.parse(text(wire[1][5] as number, wire[1][6] as number))).toEqual({ n: 1, bytes: { __u8: 'Bw==' }, id: 'game:b' });
|
|
542
|
+
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 });
|
|
543
|
+
expect(wire[2]).toEqual(['del', 'game', 'game:c']);
|
|
544
|
+
expect(wire[3]).toEqual(['clear', 'old']);
|
|
545
|
+
});
|
|
546
|
+
|
|
547
|
+
it('asks for a flush when a table of unsent work is written, deleted from or cleared', () => {
|
|
548
|
+
expect(packWrites([{ kind: 'upsert', table: '_00_pending_mutations', key: '_00_pending_mutations:1', data: {}, mode: 'replace' }]).sync).toBe(true);
|
|
549
|
+
expect(packWrites([{ kind: 'delete', table: '_00_pending_writes', key: 'x' }]).sync).toBe(true);
|
|
550
|
+
expect(packWrites([{ kind: 'clear', table: '_00_crdt_local' }]).sync).toBe(true);
|
|
551
|
+
expect(packWrites([{ kind: 'delete', table: 'game', key: 'x' }])).toEqual({ wire: [['del', 'game', 'x']], buf: null, sync: false });
|
|
552
|
+
expect(packWrites([])).toEqual({ wire: [], buf: null, sync: false });
|
|
553
|
+
});
|
|
554
|
+
});
|
|
555
|
+
|
|
556
|
+
describe('row store housekeeping', () => {
|
|
557
|
+
const stats = (over: Partial<StoreStats>): StoreStats => ({
|
|
558
|
+
file: 'a',
|
|
559
|
+
fileBytes: 0,
|
|
560
|
+
liveBytes: 0,
|
|
561
|
+
indexBytes: 0,
|
|
562
|
+
garbageBytes: 0,
|
|
563
|
+
tailBytes: 0,
|
|
564
|
+
tailOps: 0,
|
|
565
|
+
tables: 0,
|
|
566
|
+
rebuilt: false,
|
|
567
|
+
...over,
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
it('persists the index first, then compacts once dead bytes pass half the live ones', () => {
|
|
571
|
+
expect(maintenance(stats({}))).toBeNull();
|
|
572
|
+
expect(maintenance(stats({ tailBytes: 1, garbageBytes: 1 << 30 }))).toBe('checkpoint');
|
|
573
|
+
// Small stores are left alone however fragmented.
|
|
574
|
+
expect(maintenance(stats({ liveBytes: 1 << 20, garbageBytes: 3 << 20 }))).toBeNull();
|
|
575
|
+
expect(maintenance(stats({ liveBytes: 40 << 20, garbageBytes: 19 << 20 }))).toBeNull();
|
|
576
|
+
expect(maintenance(stats({ liveBytes: 40 << 20, garbageBytes: 21 << 20 }))).toBe('compact');
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
it('compacts a rewritten store down to its rows and keeps serving it', async () => {
|
|
580
|
+
const row = (i: number, round: number): Row => ({ n: i, round, pad: 'x'.repeat(2000) });
|
|
581
|
+
for (let round = 0; round < 6; round++) {
|
|
582
|
+
const vars: Record<string, unknown> = {};
|
|
583
|
+
const statements: string[] = [];
|
|
584
|
+
for (let i = 0; i < 500; i++) {
|
|
585
|
+
vars[`i${i}`] = `game:${i}`;
|
|
586
|
+
vars[`d${i}`] = row(i, round);
|
|
587
|
+
statements.push(surql.upsertMerge(`i${i}`, `d${i}`));
|
|
588
|
+
}
|
|
589
|
+
await engine.execute(surql.seal(surql.tx(statements)), vars);
|
|
590
|
+
}
|
|
591
|
+
const store = host.store()!;
|
|
592
|
+
store.checkpoint();
|
|
593
|
+
const before = store.stats();
|
|
594
|
+
expect(maintenance(before)).toBe('compact');
|
|
595
|
+
await store.compact();
|
|
596
|
+
const after = store.stats();
|
|
597
|
+
expect(maintenance(after)).toBeNull();
|
|
598
|
+
expect(after.fileBytes).toBeLessThan(before.fileBytes / 4);
|
|
599
|
+
expect(await engine.getById('game', 'game:499')).toEqual({ id: 'game:499', ...row(499, 5) });
|
|
600
|
+
expect((await engine.getStorageDiagnostics()).freelistBytes).toBeLessThan(64 << 10);
|
|
601
|
+
});
|
|
602
|
+
|
|
603
|
+
it('lets a follower tab read and write, and nothing else', () => {
|
|
604
|
+
for (const op of ['select', 'by-ids', 'get', 'relation', 'write', 'versions']) expect(ROWS_CLIENT_OPS.has(op)).toBe(true);
|
|
605
|
+
for (const op of ['open', 'close', 'shutdown', 'relock', 'diag']) expect(ROWS_CLIENT_OPS.has(op)).toBe(false);
|
|
606
|
+
});
|
|
607
|
+
});
|
|
608
|
+
|
|
609
|
+
describe('prewarming the row worker', () => {
|
|
610
|
+
const g = globalThis as Record<string, unknown>;
|
|
611
|
+
let stored: Map<string, string>;
|
|
612
|
+
let disks: RowsDisks;
|
|
613
|
+
/** Workers started through `new Worker(url)`, i.e. by the prewarm. */
|
|
614
|
+
let started: { url: string; worker: FakeRowsWorker }[];
|
|
615
|
+
/** Workers the engine started itself. */
|
|
616
|
+
let own: FakeRowsWorker[];
|
|
617
|
+
let prewarmedProto: number | undefined;
|
|
618
|
+
|
|
619
|
+
const makeEngine = (): RowsCacheEngine =>
|
|
620
|
+
new RowsCacheEngine(
|
|
621
|
+
{
|
|
622
|
+
store: 'indexeddb',
|
|
623
|
+
workers: {
|
|
624
|
+
rows: () => {
|
|
625
|
+
const worker = new FakeRowsWorker(disks);
|
|
626
|
+
own.push(worker);
|
|
627
|
+
return worker as unknown as Worker;
|
|
628
|
+
},
|
|
629
|
+
},
|
|
630
|
+
} as any,
|
|
631
|
+
logger,
|
|
632
|
+
{ useOpfs: true }
|
|
633
|
+
);
|
|
634
|
+
|
|
635
|
+
beforeEach(() => {
|
|
636
|
+
stored = new Map();
|
|
637
|
+
disks = new Map();
|
|
638
|
+
started = [];
|
|
639
|
+
own = [];
|
|
640
|
+
prewarmedProto = undefined;
|
|
641
|
+
g.localStorage = {
|
|
642
|
+
getItem: (k: string) => stored.get(k) ?? null,
|
|
643
|
+
setItem: (k: string, v: string) => void stored.set(k, v),
|
|
644
|
+
removeItem: (k: string) => void stored.delete(k),
|
|
645
|
+
};
|
|
646
|
+
g.Worker = class {
|
|
647
|
+
constructor(url: string) {
|
|
648
|
+
const worker = new FakeRowsWorker(disks, prewarmedProto);
|
|
649
|
+
started.push({ url, worker });
|
|
650
|
+
return worker as unknown as object;
|
|
651
|
+
}
|
|
652
|
+
};
|
|
653
|
+
});
|
|
654
|
+
|
|
655
|
+
afterEach(() => {
|
|
656
|
+
delete g.localStorage;
|
|
657
|
+
delete g.Worker;
|
|
658
|
+
delete g.__sp00kyRowsPrewarm;
|
|
659
|
+
});
|
|
660
|
+
|
|
661
|
+
it('does nothing on a first visit, and learns the worker from the first open', async () => {
|
|
662
|
+
prewarmRows();
|
|
663
|
+
expect(started).toEqual([]);
|
|
664
|
+
const first = makeEngine();
|
|
665
|
+
await first.connect('user_a');
|
|
666
|
+
expect(own.length).toBe(1);
|
|
667
|
+
expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!)).toEqual({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_a' });
|
|
668
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
669
|
+
await first.close();
|
|
670
|
+
});
|
|
671
|
+
|
|
672
|
+
it('hands the engine a worker that already has the store open', async () => {
|
|
673
|
+
const first = makeEngine();
|
|
674
|
+
await first.connect('user_a');
|
|
675
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
676
|
+
await first.close();
|
|
677
|
+
own.length = 0;
|
|
678
|
+
|
|
679
|
+
prewarmRows();
|
|
680
|
+
prewarmRows();
|
|
681
|
+
expect(started.map((s) => s.url)).toEqual(['https://app.test/assets/rows-worker.js']);
|
|
682
|
+
expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
|
|
683
|
+
const second = makeEngine();
|
|
684
|
+
await second.connect('user_a');
|
|
685
|
+
// The engine started no worker of its own, and nothing is left for a later engine to take.
|
|
686
|
+
expect(own).toEqual([]);
|
|
687
|
+
expect(g.__sp00kyRowsPrewarm).toBeUndefined();
|
|
688
|
+
expect(await second.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
|
|
689
|
+
expect(second.storageHealth.status).toBe('persistent');
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
it('does not ask an adopted worker to open what it has already answered for', async () => {
|
|
693
|
+
const first = makeEngine();
|
|
694
|
+
await first.connect('user_a');
|
|
695
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
696
|
+
await first.close();
|
|
697
|
+
own.length = 0;
|
|
698
|
+
|
|
699
|
+
prewarmRows();
|
|
700
|
+
// The worker answers while the bundle loads, long before the client connects.
|
|
701
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
702
|
+
const second = makeEngine();
|
|
703
|
+
await second.connect('user_a');
|
|
704
|
+
expect(own).toEqual([]);
|
|
705
|
+
expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
|
|
706
|
+
expect(second.storageHealth.status).toBe('persistent');
|
|
707
|
+
expect(await second.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 1 });
|
|
708
|
+
expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm', 'get']);
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
it('asks a worker prewarmed on another store to open the one it wants', async () => {
|
|
712
|
+
const first = makeEngine();
|
|
713
|
+
await first.connect('user_a');
|
|
714
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
715
|
+
await first.close();
|
|
716
|
+
|
|
717
|
+
prewarmRows();
|
|
718
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
719
|
+
const second = makeEngine();
|
|
720
|
+
await second.connect('user_b');
|
|
721
|
+
expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm', 'open']);
|
|
722
|
+
expect(await second.getById('game', 'game:a')).toBeNull();
|
|
723
|
+
});
|
|
724
|
+
|
|
725
|
+
describe('reading ahead', () => {
|
|
726
|
+
const tick = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0));
|
|
727
|
+
const save = (e: RowsCacheEngine): void => (e as unknown as { saveStartupReads(): void }).saveStartupReads();
|
|
728
|
+
const types = (): string[] => started[0].worker.posted.map((m) => m.type);
|
|
729
|
+
|
|
730
|
+
/** A session that reads two games at startup, and what it leaves for the next page load. */
|
|
731
|
+
const firstSession = async (): Promise<void> => {
|
|
732
|
+
const first = makeEngine();
|
|
733
|
+
await first.connect('user_a');
|
|
734
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
735
|
+
await first.upsert('game', 'game:b', { n: 2 }, 'replace');
|
|
736
|
+
expect(await first.selectByIds('game', ['game:a', 'game:b'])).toEqual([
|
|
737
|
+
{ id: 'game:a', n: 1 },
|
|
738
|
+
{ id: 'game:b', n: 2 },
|
|
739
|
+
]);
|
|
740
|
+
save(first);
|
|
741
|
+
await first.close();
|
|
742
|
+
own.length = 0;
|
|
743
|
+
};
|
|
744
|
+
|
|
745
|
+
it('saves the reads of a session start and asks them again from the page head', async () => {
|
|
746
|
+
await firstSession();
|
|
747
|
+
expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads).toEqual([['by-ids', { table: 'game', ids: ['game:a', 'game:b'] }]]);
|
|
748
|
+
prewarmRows();
|
|
749
|
+
expect(started[0].worker.posted).toEqual([
|
|
750
|
+
{ type: 'open', id: -1 },
|
|
751
|
+
{ type: 'by-ids', id: -10 },
|
|
752
|
+
{ type: 'warm', id: -2 },
|
|
753
|
+
]);
|
|
754
|
+
});
|
|
755
|
+
|
|
756
|
+
it('answers the first read from what the worker already sent, without a trip', async () => {
|
|
757
|
+
await firstSession();
|
|
758
|
+
prewarmRows();
|
|
759
|
+
await tick();
|
|
760
|
+
const second = makeEngine();
|
|
761
|
+
await second.connect('user_a');
|
|
762
|
+
expect(await second.selectByIds('game', ['game:a', 'game:b'])).toEqual([
|
|
763
|
+
{ id: 'game:a', n: 1 },
|
|
764
|
+
{ id: 'game:b', n: 2 },
|
|
765
|
+
]);
|
|
766
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm']);
|
|
767
|
+
// An answer is used once: the same read again is asked of the worker.
|
|
768
|
+
expect((await second.selectByIds('game', ['game:a', 'game:b'])).length).toBe(2);
|
|
769
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm', 'by-ids']);
|
|
770
|
+
// And another read never matches.
|
|
771
|
+
expect(await second.selectByIds('game', ['game:a'])).toEqual([{ id: 'game:a', n: 1 }]);
|
|
772
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm', 'by-ids', 'by-ids']);
|
|
773
|
+
});
|
|
774
|
+
|
|
775
|
+
it('waits for an answer that is still on its way, and does not ask twice', async () => {
|
|
776
|
+
await firstSession();
|
|
777
|
+
prewarmRows();
|
|
778
|
+
const second = makeEngine();
|
|
779
|
+
await second.connect('user_a');
|
|
780
|
+
expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([1, 2]);
|
|
781
|
+
// The open had not been answered yet, so that one was asked; the read was not.
|
|
782
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm', 'open']);
|
|
783
|
+
});
|
|
784
|
+
|
|
785
|
+
it('forgets what was read ahead the moment the session writes', async () => {
|
|
786
|
+
await firstSession();
|
|
787
|
+
prewarmRows();
|
|
788
|
+
await tick();
|
|
789
|
+
const second = makeEngine();
|
|
790
|
+
await second.connect('user_a');
|
|
791
|
+
await second.upsert('game', 'game:a', { n: 9 }, 'replace');
|
|
792
|
+
expect((await second.selectByIds('game', ['game:a', 'game:b'])).map((r) => r.n)).toEqual([9, 2]);
|
|
793
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm', 'write', 'by-ids']);
|
|
794
|
+
});
|
|
795
|
+
|
|
796
|
+
it('asks nothing ahead for another bucket, and keeps no reads across a change of bucket', async () => {
|
|
797
|
+
await firstSession();
|
|
798
|
+
prewarmRows();
|
|
799
|
+
await tick();
|
|
800
|
+
const second = makeEngine();
|
|
801
|
+
await second.connect('user_b');
|
|
802
|
+
expect(await second.selectByIds('game', ['game:a', 'game:b'])).toEqual([]);
|
|
803
|
+
expect(types()).toEqual(['open', 'by-ids', 'warm', 'open', 'by-ids']);
|
|
804
|
+
expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!)).toEqual({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' });
|
|
805
|
+
});
|
|
806
|
+
|
|
807
|
+
it('does not save a read whose payload JSON would change', async () => {
|
|
808
|
+
const first = makeEngine();
|
|
809
|
+
await first.connect('user_a');
|
|
810
|
+
await first.upsert('game', 'game:a', { n: 1 }, 'replace');
|
|
811
|
+
const byParam: QueryPlan = { table: 'game', where: [{ field: 'n', op: '=', value: undefined, paramRef: 'n' }] };
|
|
812
|
+
await first.select(byParam, { n: 1 });
|
|
813
|
+
await first.select(byParam, { n: new Date(0) });
|
|
814
|
+
save(first);
|
|
815
|
+
const reads = JSON.parse(stored.get(ROWS_PREWARM_KEY)!).reads as [string, { params: unknown }][];
|
|
816
|
+
expect(reads.map((r) => r[1].params)).toEqual([{ n: 1 }]);
|
|
817
|
+
await first.close();
|
|
818
|
+
});
|
|
819
|
+
});
|
|
820
|
+
|
|
821
|
+
it('starts its own worker when the prewarmed one is another release', async () => {
|
|
822
|
+
stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker-OLD.js', bucket: 'user_a' }));
|
|
823
|
+
prewarmedProto = 0;
|
|
824
|
+
prewarmRows();
|
|
825
|
+
const engine = makeEngine();
|
|
826
|
+
await engine.connect('user_a');
|
|
827
|
+
expect(started[0].worker.terminated).toBe(true);
|
|
828
|
+
expect(own.length).toBe(1);
|
|
829
|
+
await engine.upsert('game', 'game:a', { n: 2 }, 'replace');
|
|
830
|
+
expect(await engine.getById('game', 'game:a')).toEqual({ id: 'game:a', n: 2 });
|
|
831
|
+
// The next load prewarms the worker that works.
|
|
832
|
+
expect(JSON.parse(stored.get(ROWS_PREWARM_KEY)!).url).toBe('https://app.test/assets/rows-worker.js');
|
|
833
|
+
});
|
|
834
|
+
|
|
835
|
+
it('drops a prewarmed worker that failed to start', async () => {
|
|
836
|
+
stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/gone.js', bucket: 'user_a' }));
|
|
837
|
+
prewarmRows();
|
|
838
|
+
started[0].worker.onerror?.({ message: '404' });
|
|
839
|
+
const engine = makeEngine();
|
|
840
|
+
await engine.connect('user_a');
|
|
841
|
+
expect(started[0].worker.terminated).toBe(true);
|
|
842
|
+
expect(own.length).toBe(1);
|
|
843
|
+
});
|
|
844
|
+
|
|
845
|
+
it('ships the same thing as a script for the page head', () => {
|
|
846
|
+
stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' }));
|
|
847
|
+
new Function(ROWS_PREWARM_SNIPPET)();
|
|
848
|
+
expect(started.map((s) => s.url)).toEqual(['https://app.test/assets/rows-worker.js']);
|
|
849
|
+
expect((g.__sp00kyRowsPrewarm as { bucket: string }).bucket).toBe('user_b');
|
|
850
|
+
expect(started[0].worker.posted).toEqual([
|
|
851
|
+
{ type: 'open', id: -1 },
|
|
852
|
+
{ type: 'warm', id: -2 },
|
|
853
|
+
]);
|
|
854
|
+
});
|
|
855
|
+
|
|
856
|
+
it('keeps the answer to its open in the head script too', async () => {
|
|
857
|
+
stored.set(ROWS_PREWARM_KEY, JSON.stringify({ url: 'https://app.test/assets/rows-worker.js', bucket: 'user_b' }));
|
|
858
|
+
new Function(ROWS_PREWARM_SNIPPET)();
|
|
859
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
860
|
+
const engine = makeEngine();
|
|
861
|
+
await engine.connect('user_b');
|
|
862
|
+
expect(started[0].worker.posted.map((m) => m.type)).toEqual(['open', 'warm']);
|
|
863
|
+
expect(engine.storageHealth.status).toBe('persistent');
|
|
864
|
+
});
|
|
865
|
+
});
|
|
866
|
+
|
|
867
|
+
describe('painting from the last session', () => {
|
|
868
|
+
const g = globalThis as Record<string, unknown>;
|
|
869
|
+
let stored: Map<string, string>;
|
|
870
|
+
let disks: RowsDisks;
|
|
871
|
+
const flush = (e: RowsCacheEngine): void => (e as unknown as { paint: { flush(): void } }).paint.flush();
|
|
872
|
+
const fresh = (config: Record<string, unknown> = {}, useOpfs = true): RowsCacheEngine => {
|
|
873
|
+
const next = new RowsCacheEngine({ store: 'indexeddb', ...config } as any, logger, { useOpfs });
|
|
874
|
+
inProcessRows(next, disks);
|
|
875
|
+
return next;
|
|
876
|
+
};
|
|
877
|
+
const ids = ['game:b', 'game:a'];
|
|
878
|
+
|
|
879
|
+
beforeEach(async () => {
|
|
880
|
+
stored = new Map();
|
|
881
|
+
disks = new Map();
|
|
882
|
+
g.localStorage = {
|
|
883
|
+
getItem: (k: string) => stored.get(k) ?? null,
|
|
884
|
+
setItem: (k: string, v: string) => void stored.set(k, v),
|
|
885
|
+
removeItem: (k: string) => void stored.delete(k),
|
|
886
|
+
key: (i: number) => [...stored.keys()][i] ?? null,
|
|
887
|
+
get length() {
|
|
888
|
+
return stored.size;
|
|
889
|
+
},
|
|
890
|
+
};
|
|
891
|
+
engine = fresh();
|
|
892
|
+
await engine.connect('user_a');
|
|
893
|
+
await engine.upsert('game', 'game:a', { n: 1, white: 'user:1' }, 'replace');
|
|
894
|
+
await engine.upsert('game', 'game:b', { n: 2, blob: new Uint8Array([1, 2]) }, 'replace');
|
|
895
|
+
await engine.upsert('user', 'user:1', { name: 'Ada' }, 'replace');
|
|
896
|
+
});
|
|
897
|
+
|
|
898
|
+
afterEach(() => {
|
|
899
|
+
delete g.localStorage;
|
|
900
|
+
});
|
|
901
|
+
|
|
902
|
+
it('hands back a startup read before the store is open', async () => {
|
|
903
|
+
expect(engine.peekByIds('game', ids)).toBeNull();
|
|
904
|
+
const rows = await engine.selectByIds('game', ids);
|
|
905
|
+
flush(engine);
|
|
906
|
+
await engine.close();
|
|
907
|
+
|
|
908
|
+
const next = fresh();
|
|
909
|
+
const opening = next.connect('user_a');
|
|
910
|
+
// Nothing has been awaited: the worker has not answered, the peek has.
|
|
911
|
+
expect(next.peekByIds('game', ids)).toEqual(rows);
|
|
912
|
+
expect(next.peekByIds('game', ids)![0].blob).toEqual(new Uint8Array([1, 2]));
|
|
913
|
+
expect(next.peekByIds('game', ['game:a'])).toBeNull();
|
|
914
|
+
expect(next.peekByIds('game', ids, { select: ['n'] })).toBeNull();
|
|
915
|
+
await opening;
|
|
916
|
+
expect(await next.selectByIds('game', ids)).toEqual(rows);
|
|
917
|
+
});
|
|
918
|
+
|
|
919
|
+
it('keeps a named read under its name, whatever its arguments were', async () => {
|
|
920
|
+
const whole: QueryPlan = { table: 'game' };
|
|
921
|
+
const one: QueryPlan = { table: 'game', ids: [new RecordId('game', 'a')] };
|
|
922
|
+
// A query whose id set moved between two renders: one name, the latest answer.
|
|
923
|
+
await engine.select(whole, {}, { paintKey: 'view-1' });
|
|
924
|
+
const latest = await engine.select(one, {}, { paintKey: 'view-1' });
|
|
925
|
+
expect(latest.map((r) => r.id)).toEqual(['game:a']);
|
|
926
|
+
flush(engine);
|
|
927
|
+
await engine.close();
|
|
928
|
+
|
|
929
|
+
const next = fresh();
|
|
930
|
+
void next.connect('user_a');
|
|
931
|
+
expect(next.peekSelect(whole, {}, { paintKey: 'view-1' })).toEqual(latest);
|
|
932
|
+
expect(next.peekSelect(whole, {}, { paintKey: 'view-2' })).toBeNull();
|
|
933
|
+
// The unnamed read of the same plan is another thing.
|
|
934
|
+
expect(next.peekSelect(whole)).toBeNull();
|
|
935
|
+
});
|
|
936
|
+
|
|
937
|
+
it('answers before connect once it is told which bucket is about to open', async () => {
|
|
938
|
+
const plan: QueryPlan = { table: 'game' };
|
|
939
|
+
const rows = await engine.select(plan, {}, { paintKey: 'view-1' });
|
|
940
|
+
flush(engine);
|
|
941
|
+
await engine.close();
|
|
942
|
+
|
|
943
|
+
const next = fresh();
|
|
944
|
+
// Nothing says whose rows these would be.
|
|
945
|
+
expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
|
|
946
|
+
next.expectBucket('user_a');
|
|
947
|
+
expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
|
|
948
|
+
// The first word stands until the store is opened.
|
|
949
|
+
next.expectBucket('user_b');
|
|
950
|
+
expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toEqual(rows);
|
|
951
|
+
// Opened on another bucket after all: none of the first one's rows are handed out.
|
|
952
|
+
await next.connect('user_b');
|
|
953
|
+
expect(next.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
|
|
954
|
+
await next.close();
|
|
955
|
+
|
|
956
|
+
// With shared tabs no copy is kept, so none is handed out.
|
|
957
|
+
const shared = new RowsCacheEngine({ store: 'indexeddb' } as any, logger, { useOpfs: true, shared: true });
|
|
958
|
+
shared.expectBucket('user_a');
|
|
959
|
+
expect(shared.peekSelect(plan, {}, { paintKey: 'view-1' })).toBeNull();
|
|
960
|
+
});
|
|
961
|
+
|
|
962
|
+
it('lets go of a copy the moment its table is written, and takes the next read of the same thing', async () => {
|
|
963
|
+
await engine.selectByIds('game', ids);
|
|
964
|
+
flush(engine);
|
|
965
|
+
expect([...stored.keys()].some((k) => k.startsWith('sp00ky.paint.user_a.'))).toBe(true);
|
|
966
|
+
await engine.upsert('game', 'game:a', { n: 10 }, 'merge');
|
|
967
|
+
expect(engine.peekByIds('game', ids)).toBeNull();
|
|
968
|
+
expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a.'))).toEqual([]);
|
|
969
|
+
// A write to another table leaves it alone.
|
|
970
|
+
const again = await engine.selectByIds('game', ids);
|
|
971
|
+
await engine.upsert('user', 'user:1', { name: 'Ada L.' }, 'merge');
|
|
972
|
+
flush(engine);
|
|
973
|
+
expect(engine.peekByIds('game', ids)).toEqual(again);
|
|
974
|
+
expect(again[1].n).toBe(10);
|
|
975
|
+
});
|
|
976
|
+
|
|
977
|
+
it('never keeps a read that a write overtook', async () => {
|
|
978
|
+
const reading = engine.selectByIds('game', ids);
|
|
979
|
+
const writing = engine.upsert('game', 'game:a', { n: 99 }, 'merge');
|
|
980
|
+
await Promise.all([reading, writing]);
|
|
981
|
+
flush(engine);
|
|
982
|
+
expect(engine.peekByIds('game', ids)).toBeNull();
|
|
983
|
+
});
|
|
984
|
+
|
|
985
|
+
it('keeps a select with relations, and drops it when any table it read is written', async () => {
|
|
986
|
+
const plan: QueryPlan = {
|
|
987
|
+
table: 'game',
|
|
988
|
+
ids: ['game:a'],
|
|
989
|
+
relations: [{ alias: 'white', table: 'user', cardinality: 'one', foreignKeyField: 'white' }],
|
|
990
|
+
};
|
|
991
|
+
const rows = await engine.select(plan);
|
|
992
|
+
flush(engine);
|
|
993
|
+
expect(engine.peekSelect(plan)).toEqual(rows);
|
|
994
|
+
expect((engine.peekSelect(plan)![0].white as Row).name).toBe('Ada');
|
|
995
|
+
await engine.upsert('user', 'user:1', { name: 'Grace' }, 'merge');
|
|
996
|
+
expect(engine.peekSelect(plan)).toBeNull();
|
|
997
|
+
});
|
|
998
|
+
|
|
999
|
+
it('keeps each bucket apart and forgets a dropped one', async () => {
|
|
1000
|
+
await engine.selectByIds('game', ids);
|
|
1001
|
+
await engine.switchBucket('user_b');
|
|
1002
|
+
expect(engine.peekByIds('game', ids)).toBeNull();
|
|
1003
|
+
await engine.dropBucket('user_a');
|
|
1004
|
+
expect([...stored.keys()].filter((k) => k.startsWith('sp00ky.paint.user_a'))).toEqual([]);
|
|
1005
|
+
});
|
|
1006
|
+
|
|
1007
|
+
it('is off for a memory store and when configured off', async () => {
|
|
1008
|
+
for (const quiet of [fresh({}, false), fresh({ paintCache: false })]) {
|
|
1009
|
+
await quiet.connect('user_a');
|
|
1010
|
+
await quiet.selectByIds('game', ids);
|
|
1011
|
+
expect(quiet.peekByIds('game', ids)).toBeNull();
|
|
1012
|
+
}
|
|
1013
|
+
});
|
|
1014
|
+
});
|