@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,607 @@
1
+ /// <reference lib="webworker" />
2
+ /**
3
+ * Dedicated Web Worker that owns a bucket's row store (`rows-store.ts`): the
4
+ * OPFS sync access handles it reads and writes through exist only in a
5
+ * dedicated worker, and are exclusive, so one worker per bucket holds them and
6
+ * every tab's reads and writes go through it.
7
+ *
8
+ * It speaks the request/response protocol of the SQLite worker (requests keyed
9
+ * by `id`, replies on the channel the request came in on), with the same
10
+ * lifecycle messages, so the engine's transport, its shared-tabs roles and the
11
+ * leader fencing work unchanged:
12
+ *
13
+ * { id, type: 'open', payload: { dbName, useOpfs, workerLockName?, openOptions?, share?, reader? } }
14
+ * -> { id, ok, persisted, opfsError? }
15
+ * { id, type: 'close' | 'shutdown' | 'relock' | 'add-client' | 'remove-client' | 'diag' }
16
+ * every other type is a data op, answered by `handleRowsOp` (rows-exec.ts)
17
+ *
18
+ * Rows travel as JSON text in a transferred buffer, in both directions.
19
+ *
20
+ * Housekeeping runs on the same chain as the ops, in the quiet after them:
21
+ * unflushed writes are flushed within {@link FLUSH_LAG_MS}, the index is
22
+ * persisted after {@link IDLE_MS} without traffic (and at once when the log
23
+ * written since the last checkpoint grows past its bound), and dead bytes are
24
+ * compacted away when they outweigh the live ones.
25
+ */
26
+ import { verifyLockStillHeld as verifyLockStillHeldBounded } from './sqlite-lock-verify';
27
+ import { MemoryFile, RowStore, bucketDirName, type StoreIo, type SyncFile } from './rows-store';
28
+ import {
29
+ CHECKPOINT_TAIL_BYTES,
30
+ CHECKPOINT_TAIL_OPS,
31
+ ROWS_CLIENT_OPS,
32
+ ROWS_PROTOCOL,
33
+ RowsExec,
34
+ handleReaderOp,
35
+ handleRowsOp,
36
+ maintenance,
37
+ visibleTables,
38
+ } from './rows-exec';
39
+ import { ROWS_AHEAD_ID, ROWS_AHEAD_OPS, ROWS_PREWARM_OPEN_ID, ROWS_YIELD_CHANNEL } from './rows-prewarm';
40
+ import { AheadStore, type YieldChannel } from './rows-yield';
41
+
42
+ type PostTarget = Pick<MessagePort, 'postMessage'>;
43
+
44
+ interface OpenOptions {
45
+ maxAttempts?: number;
46
+ backoffMs?: number[];
47
+ disallowMemoryFallback?: boolean;
48
+ }
49
+
50
+ /**
51
+ * Retry schedule for an open that finds the files held. The usual holder is
52
+ * this tab's previous worker, whose handles the browser releases a moment
53
+ * after a reload, so the first retries come within milliseconds: a reload
54
+ * should not wait a quarter second for a file that is free after five. The
55
+ * whole ramp still gives another tab about as long as the SQLite worker does
56
+ * (750 ms) before falling back to memory.
57
+ */
58
+ const DEFAULT_BACKOFF_MS = [4, 8, 16, 32, 64, 128, 250, 250];
59
+ const DEFAULT_MAX_ATTEMPTS = DEFAULT_BACKOFF_MS.length + 1;
60
+
61
+ /** How long a write may sit with the operating system before it is flushed. */
62
+ const FLUSH_LAG_MS = 100;
63
+ /** Quiet time after which the index is persisted and the store tidied. */
64
+ const IDLE_MS = 500;
65
+
66
+ class OpfsFile implements SyncFile {
67
+ constructor(private access: FileSystemSyncAccessHandle) {}
68
+ read(buffer: Uint8Array, at: number): number {
69
+ return this.access.read(buffer, { at });
70
+ }
71
+ write(buffer: Uint8Array, at: number): number {
72
+ const written = this.access.write(buffer, { at });
73
+ // A short write is a full disk: fail the batch rather than store part of it.
74
+ if (written !== buffer.length) throw new Error(`rows: wrote ${written} of ${buffer.length} bytes (storage full?)`);
75
+ return written;
76
+ }
77
+ size(): number {
78
+ return this.access.getSize();
79
+ }
80
+ truncate(size: number): void {
81
+ this.access.truncate(size);
82
+ }
83
+ flush(): void {
84
+ this.access.flush();
85
+ }
86
+ close(): void {
87
+ this.access.close();
88
+ }
89
+ }
90
+
91
+ let store: RowStore | null = null;
92
+ let exec: RowsExec | null = null;
93
+ /** The open store is a reader's: it answers reads beside another worker's writes and does no housekeeping. */
94
+ let reading = false;
95
+ /** What the open store was opened as, so a second `open` for the same thing is a no-op. */
96
+ let opened: { dbName: string; useOpfs: boolean; mode: FileMode; result: { persisted: boolean; opfsError?: string } } | null = null;
97
+ /** Handles held for the open store, closed with it. */
98
+ let openFiles: SyncFile[] = [];
99
+
100
+ /**
101
+ * How the store's files are opened.
102
+ * `own` the default: one worker holds them, any other fails to open.
103
+ * `share` a shared-tabs leader that lets followers read the file beside it.
104
+ * `reader` such a follower: it only reads (`RowStore` in reader mode).
105
+ * The last two use `readwrite-unsafe` handles (Chrome 121+), which several
106
+ * workers can hold on one file. Nothing but the leader's Web Lock then stands
107
+ * between two writers, which is why sharing is something an app asks for.
108
+ */
109
+ type FileMode = 'own' | 'share' | 'reader';
110
+
111
+ /**
112
+ * Whether this browser opens a second `readwrite-unsafe` handle on a file. One
113
+ * that does not know the option ignores it and hands out the exclusive handle,
114
+ * so the only way to know is to try, on a file of no importance.
115
+ */
116
+ async function canShareFiles(dir: FileSystemDirectoryHandle): Promise<boolean> {
117
+ const handles: FileSystemSyncAccessHandle[] = [];
118
+ try {
119
+ const probe = await dir.getFileHandle('probe', { create: true });
120
+ // oxlint-disable-next-line typescript/no-explicit-any
121
+ const open = (): Promise<FileSystemSyncAccessHandle> => (probe as any).createSyncAccessHandle({ mode: 'readwrite-unsafe' });
122
+ handles.push(await open());
123
+ handles.push(await open());
124
+ return true;
125
+ } catch {
126
+ return false;
127
+ } finally {
128
+ for (const handle of handles) handle.close();
129
+ }
130
+ }
131
+
132
+ async function opfsIo(bucketId: string, mode: FileMode = 'own'): Promise<StoreIo> {
133
+ const root = await navigator.storage.getDirectory();
134
+ const dir = await root.getDirectoryHandle(bucketDirName(bucketId), { create: true });
135
+ let shared = false;
136
+ if (mode !== 'own') {
137
+ shared = await canShareFiles(dir);
138
+ // A leader without the option leads as before; a reader has nothing to read with.
139
+ if (!shared && mode === 'reader') throw new Error('Missing required OPFS APIs: shared access handles');
140
+ }
141
+ return {
142
+ open: async (name) => {
143
+ const handle = await dir.getFileHandle(name, { create: true });
144
+ // oxlint-disable-next-line typescript/no-explicit-any
145
+ const access = await (shared ? (handle as any).createSyncAccessHandle({ mode: 'readwrite-unsafe' }) : handle.createSyncAccessHandle());
146
+ const file = new OpfsFile(access as FileSystemSyncAccessHandle);
147
+ openFiles.push(file);
148
+ return file;
149
+ },
150
+ };
151
+ }
152
+
153
+ function memoryIo(): StoreIo {
154
+ const files = { a: new MemoryFile(), b: new MemoryFile() };
155
+ return { open: (name) => files[name] };
156
+ }
157
+
158
+ function closeFiles(): void {
159
+ for (const file of openFiles) {
160
+ try {
161
+ file.close();
162
+ } catch {
163
+ /* already closed */
164
+ }
165
+ }
166
+ openFiles = [];
167
+ }
168
+
169
+ const errMessage = (e: unknown): string =>
170
+ e instanceof Error ? (e.name && e.name !== 'Error' ? `${e.name}: ${e.message}` : e.message) : String(e);
171
+
172
+ /**
173
+ * Open `bucketId`'s store. Sync access handles are exclusive, so a second
174
+ * worker on the same bucket (another tab that is still closing) fails here:
175
+ * retry, then fall back to memory and say so loudly, as the SQLite worker
176
+ * does. A caller that must not run in memory (a shared-tabs leader) gets the
177
+ * error instead.
178
+ */
179
+ async function openStore(
180
+ bucketId: string,
181
+ useOpfs: boolean,
182
+ opts: OpenOptions = {},
183
+ mode: FileMode = 'own',
184
+ leading = false
185
+ ): Promise<{ persisted: boolean; opfsError?: string }> {
186
+ reading = false;
187
+ if (!useOpfs) {
188
+ store = await RowStore.open(memoryIo());
189
+ exec = new RowsExec(store);
190
+ return { persisted: false };
191
+ }
192
+ const maxAttempts = Math.max(1, opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
193
+ const backoffMs = opts.backoffMs ?? DEFAULT_BACKOFF_MS;
194
+ let lastError = 'unknown error';
195
+ let attempts = 0;
196
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
197
+ attempts = attempt;
198
+ try {
199
+ if (!navigator.storage?.getDirectory) throw new Error('Missing required OPFS APIs');
200
+ store = await RowStore.open(await opfsIo(bucketId, mode), { reader: mode === 'reader' });
201
+ exec = new RowsExec(store, mode === 'reader');
202
+ reading = mode === 'reader';
203
+ return { persisted: true };
204
+ } catch (e) {
205
+ closeFiles();
206
+ lastError = errMessage(e);
207
+ if (attempt === maxAttempts || lastError.includes('Missing required OPFS APIs')) break;
208
+ // The holder may be a worker some page started ahead of itself.
209
+ if (leading) aheadStore.ask(bucketId);
210
+ await new Promise((resolve) => setTimeout(resolve, backoffMs[Math.min(attempt - 1, backoffMs.length - 1)] ?? 0));
211
+ }
212
+ }
213
+ // A reader in memory would read nothing of the leader's: it has no fallback.
214
+ if (opts.disallowMemoryFallback || mode === 'reader') throw new Error(`opfs-unavailable: ${lastError} (after ${attempts} attempts)`);
215
+ // Deliberately console, not a logger: host apps set their own log level, and
216
+ // losing durability must never be filtered into silence.
217
+ // oxlint-disable-next-line no-console
218
+ console.error(
219
+ `[sp00ky] OPFS persistence unavailable for "${bucketId}" after ${attempts} attempt${attempts === 1 ? '' : 's'}: ` +
220
+ `${lastError}. The local row store is running IN MEMORY, which keeps the whole dataset in RAM and loses ` +
221
+ 'every local write on reload. The usual cause is another tab of this app holding the storage lock, so ' +
222
+ 'closing the other tabs and reloading restores persistence.'
223
+ );
224
+ store = await RowStore.open(memoryIo());
225
+ exec = new RowsExec(store);
226
+ return { persisted: false, opfsError: lastError };
227
+ }
228
+
229
+ // ---- a store opened ahead of the page ----
230
+ // See `rows-yield.ts`: a store `prewarmRows` opened and no page has claimed is
231
+ // given up to the worker of the tab that leads, which asks when its open fails.
232
+
233
+ const aheadStore = new AheadStore({
234
+ channel: () => (typeof BroadcastChannel === 'function' ? (new BroadcastChannel(ROWS_YIELD_CHANNEL) as unknown as YieldChannel) : null),
235
+ openBucket: () => (store !== null && opened !== null ? opened.dbName : null),
236
+ enqueue: (fn) => void enqueue(fn),
237
+ closeStore: () => closeStore(),
238
+ tellPage: (message) => (self as unknown as Worker).postMessage(message),
239
+ });
240
+
241
+ /** Persist the index and let go of the files. */
242
+ function closeStore(): void {
243
+ clearTimers();
244
+ try {
245
+ store?.checkpoint();
246
+ } catch {
247
+ /* the log already holds every write; the next open replays it */
248
+ }
249
+ try {
250
+ store?.close();
251
+ } catch {
252
+ /* ignore */
253
+ }
254
+ store = null;
255
+ exec = null;
256
+ opened = null;
257
+ reading = false;
258
+ warmQueue = null;
259
+ closeFiles();
260
+ }
261
+
262
+ // ==================== housekeeping ====================
263
+
264
+ let flushTimer: ReturnType<typeof setTimeout> | null = null;
265
+ let idleTimer: ReturnType<typeof setTimeout> | null = null;
266
+
267
+ function clearTimers(): void {
268
+ if (flushTimer) clearTimeout(flushTimer);
269
+ if (idleTimer) clearTimeout(idleTimer);
270
+ flushTimer = null;
271
+ idleTimer = null;
272
+ }
273
+
274
+ function afterOp(wrote: boolean): void {
275
+ if (!store) return;
276
+ if (wrote) {
277
+ const stats = store.stats();
278
+ // Bound what the next open has to replay, even under constant writing.
279
+ if (stats.tailBytes > CHECKPOINT_TAIL_BYTES || stats.tailOps > CHECKPOINT_TAIL_OPS) store.checkpoint();
280
+ else if (!flushTimer) {
281
+ flushTimer = setTimeout(() => {
282
+ flushTimer = null;
283
+ enqueue(() => store?.flush());
284
+ }, FLUSH_LAG_MS);
285
+ }
286
+ }
287
+ if (idleTimer) clearTimeout(idleTimer);
288
+ idleTimer = setTimeout(() => {
289
+ idleTimer = null;
290
+ enqueue(tidy);
291
+ }, IDLE_MS);
292
+ }
293
+
294
+ async function tidy(): Promise<void> {
295
+ if (!store) return;
296
+ store.flush();
297
+ // A checkpoint, then at most a compaction and the checkpoint after it.
298
+ for (let round = 0; round < 3 && store; round++) {
299
+ const step = maintenance(store.stats());
300
+ if (!step) break;
301
+ if (step === 'checkpoint') store.checkpoint();
302
+ else await store.compact();
303
+ }
304
+ }
305
+
306
+ // ==================== leader fencing (worker web lock) ====================
307
+ // Same scheme as the SQLite worker: a Web Lock named per leadership, held for
308
+ // the store's lifetime. Losing it without having released it means the broker
309
+ // gave the bucket to another tab, and this worker must never write again.
310
+
311
+ let fenced = false;
312
+
313
+ interface HeldLock {
314
+ name: string;
315
+ release: () => void;
316
+ }
317
+
318
+ let currentLock: HeldLock | null = null;
319
+
320
+ function workerLocks(): LockManager | null {
321
+ const nav = (globalThis as { navigator?: { locks?: LockManager } }).navigator;
322
+ return nav?.locks && typeof nav.locks.request === 'function' ? nav.locks : null;
323
+ }
324
+
325
+ function acquireWorkerLock(name: string): Promise<HeldLock | null> {
326
+ const locks = workerLocks();
327
+ if (!locks) return Promise.resolve({ name, release() {} });
328
+ return new Promise<HeldLock | null>((resolve) => {
329
+ let granted = false;
330
+ let intentional = false;
331
+ let releaseGrant: (() => void) | null = null;
332
+ locks
333
+ .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
334
+ if (!lock) {
335
+ resolve(null);
336
+ return;
337
+ }
338
+ granted = true;
339
+ resolve({
340
+ name,
341
+ release() {
342
+ intentional = true;
343
+ releaseGrant?.();
344
+ },
345
+ });
346
+ return new Promise<void>((release) => {
347
+ releaseGrant = release;
348
+ });
349
+ })
350
+ .then(
351
+ () => {
352
+ if (granted && !intentional) fence('worker lock stolen');
353
+ },
354
+ () => {
355
+ if (granted && !intentional) fence('worker lock request failed');
356
+ }
357
+ );
358
+ });
359
+ }
360
+
361
+ function releaseHeldLock(): void {
362
+ currentLock?.release();
363
+ currentLock = null;
364
+ }
365
+
366
+ /** Terminal: close the files without another write, tell the owner, stop. */
367
+ function fence(reason: string): void {
368
+ if (fenced) return;
369
+ fenced = true;
370
+ // oxlint-disable-next-line no-console
371
+ console.error(
372
+ `[sp00ky] row store worker fenced (${reason}): leadership was taken over, ` +
373
+ 'closing the store and refusing further ops.'
374
+ );
375
+ clearTimers();
376
+ // No checkpoint: the new leader owns the file now.
377
+ store = null;
378
+ exec = null;
379
+ opened = null;
380
+ closeFiles();
381
+ try {
382
+ (self as unknown as Worker).postMessage({ type: 'lock-lost', reason });
383
+ } catch {
384
+ /* owner gone */
385
+ }
386
+ releaseHeldLock();
387
+ self.close();
388
+ }
389
+
390
+ // A frozen tab's worker resumes with its queue intact, and a queued write could
391
+ // run before the lock-steal callback does. After a long gap, ops wait for a
392
+ // lock check first. See the SQLite worker for the reasoning behind the bound.
393
+ const FREEZE_SUSPECT_MS = 10_000;
394
+ let lastTickAt = performance.now();
395
+ let thawVerification: Promise<void> | null = null;
396
+
397
+ function noteTick(): void {
398
+ const now = performance.now();
399
+ const gap = now - lastTickAt;
400
+ lastTickAt = now;
401
+ if (gap > FREEZE_SUSPECT_MS && currentLock && !fenced && !thawVerification) {
402
+ thawVerification = verifyLockStillHeldBounded(
403
+ // oxlint-disable-next-line typescript/no-explicit-any
404
+ workerLocks() as any,
405
+ currentLock?.name,
406
+ (reason) => Promise.resolve(fence(reason)),
407
+ undefined,
408
+ // oxlint-disable-next-line no-console
409
+ (msg) => console.warn(`[rows-worker] ${msg}`)
410
+ ).finally(() => {
411
+ thawVerification = null;
412
+ });
413
+ }
414
+ }
415
+ setInterval(noteTick, 1000);
416
+
417
+ // ==================== dispatch ====================
418
+
419
+ const clients = new Map<string, MessagePort>();
420
+
421
+ /** One chain for every op from every channel, housekeeping included. */
422
+ let opChain: Promise<unknown> = Promise.resolve();
423
+
424
+ /** Ops queued or running, and when the last one finished. */
425
+ let pendingOps = 0;
426
+ let lastOpAt = 0;
427
+
428
+ function enqueue<T>(fn: () => T | Promise<T>): Promise<T> {
429
+ pendingOps++;
430
+ const result = opChain.then(fn, fn);
431
+ const settle = (): void => {
432
+ pendingOps--;
433
+ lastOpAt = performance.now();
434
+ };
435
+ opChain = result.then(
436
+ () => settle(),
437
+ () => settle()
438
+ );
439
+ return result;
440
+ }
441
+
442
+ // ---- warming ----
443
+ // Reading every index at once took 15 to 20 ms on an 80,000 row store, and a
444
+ // request that arrived meanwhile waited for all of it: the page's first read
445
+ // came back slower than with no warming at all. So a table is read per turn,
446
+ // and only once the worker has been left alone for a moment. A request never
447
+ // waits for more than the one table being read.
448
+
449
+ const WARM_QUIET_MS = 15;
450
+ /** Tables whose index is still to be read; null when there is nothing to warm. */
451
+ let warmQueue: string[] | null = null;
452
+ let warmTimer: ReturnType<typeof setTimeout> | null = null;
453
+
454
+ function warmSoon(delay: number): void {
455
+ if (warmTimer === null) warmTimer = setTimeout(warmStep, delay);
456
+ }
457
+
458
+ function warmStep(): void {
459
+ warmTimer = null;
460
+ if (!warmQueue || !store || fenced) {
461
+ warmQueue = null;
462
+ return;
463
+ }
464
+ if (pendingOps > 0 || performance.now() - lastOpAt < WARM_QUIET_MS) return warmSoon(WARM_QUIET_MS);
465
+ const table = warmQueue.shift();
466
+ if (table === undefined) {
467
+ warmQueue = null;
468
+ return;
469
+ }
470
+ try {
471
+ // No op is running (the count is zero), so this reads beside none.
472
+ store.ordered(table);
473
+ } catch {
474
+ /* whatever is wrong with this index, the read that needs it reports */
475
+ }
476
+ warmSoon(0);
477
+ }
478
+
479
+ // oxlint-disable-next-line typescript/no-explicit-any
480
+ async function handle(type: string, payload: any, source: 'owner' | 'client'): Promise<{ result: object; transfer?: Transferable[] }> {
481
+ if (fenced) throw new Error('rows: fenced, leadership was taken over');
482
+ if (source === 'client' && !ROWS_CLIENT_OPS.has(type)) {
483
+ throw new Error(`rows worker: op ${type} is not allowed on a client port`);
484
+ }
485
+ switch (type) {
486
+ case 'open': {
487
+ if (payload.workerLockName) {
488
+ const lock = await acquireWorkerLock(payload.workerLockName);
489
+ if (!lock) throw new Error('worker-lock-unavailable');
490
+ releaseHeldLock();
491
+ currentLock = lock;
492
+ }
493
+ // The page may have started this worker and its store ahead of itself
494
+ // (`prewarmRows`): the store it asks for is then already open.
495
+ const mode: FileMode = payload.reader ? 'reader' : payload.share ? 'share' : 'own';
496
+ const same =
497
+ store !== null && opened !== null && opened.dbName === payload.dbName && opened.useOpfs === payload.useOpfs && opened.mode === mode;
498
+ if (!same) {
499
+ closeStore();
500
+ const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode, Boolean(payload.workerLockName));
501
+ opened = { dbName: payload.dbName, useOpfs: payload.useOpfs, mode, result };
502
+ }
503
+ return { result: { ...opened!.result, proto: ROWS_PROTOCOL, workerUrl: self.location.href } };
504
+ }
505
+ case 'warm':
506
+ // Read the tables' indexes ahead of the page, so its first query finds
507
+ // them in memory. One table at a time and only while nothing is asked
508
+ // for: see `warmStep`.
509
+ warmQueue = exec ? exec.warmOrder() : null;
510
+ warmSoon(WARM_QUIET_MS);
511
+ return { result: {} };
512
+ case 'relock': {
513
+ const lock = await acquireWorkerLock(payload.workerLockName);
514
+ if (!lock) throw new Error('worker-lock-unavailable');
515
+ releaseHeldLock();
516
+ currentLock = lock;
517
+ return { result: {} };
518
+ }
519
+ case 'close':
520
+ closeStore();
521
+ releaseHeldLock();
522
+ return { result: {} };
523
+ case 'shutdown':
524
+ // Graceful pagehide: persist the index and release the handles now, so
525
+ // the next leader's open does not wait for this worker to be collected.
526
+ closeStore();
527
+ releaseHeldLock();
528
+ queueMicrotask(() => self.close());
529
+ return { result: {} };
530
+ case 'remove-client': {
531
+ clients.get(payload.clientId)?.close();
532
+ clients.delete(payload.clientId);
533
+ return { result: {} };
534
+ }
535
+ case 'diag': {
536
+ if (!store) throw new Error('rows: store not open');
537
+ store.refresh();
538
+ const stats = store.stats();
539
+ const tableCounts = payload?.tableCounts
540
+ ? visibleTables(store).map((table) => ({ table, rows: store!.count(table) }))
541
+ : undefined;
542
+ return { result: { stats, tableCounts } };
543
+ }
544
+ default: {
545
+ if (!store || !exec) throw new Error('rows: store not open');
546
+ if (reading) {
547
+ const answer = await handleReaderOp(exec, store, type, payload);
548
+ if (!answer) throw new Error(`rows worker: unknown message ${type}`);
549
+ return answer;
550
+ }
551
+ const reply = await handleRowsOp(exec, store, type, payload);
552
+ if (!reply) throw new Error(`rows worker: unknown message ${type}`);
553
+ afterOp(type === 'write' || type === 'reset-versions' || type === 'blob-put' || type === 'blob-del');
554
+ return reply;
555
+ }
556
+ }
557
+ }
558
+
559
+ // oxlint-disable-next-line typescript/no-explicit-any
560
+ function dispatch(target: PostTarget, data: any, source: 'owner' | 'client'): void {
561
+ const { id, type, payload } = data ?? {};
562
+ noteTick();
563
+ // What a page head replays from localStorage (`prewarmRows`) is a read, whatever the storage says.
564
+ if (typeof id === 'number' && id <= ROWS_AHEAD_ID && !ROWS_AHEAD_OPS.has(type)) {
565
+ target.postMessage({ id, ok: false, error: 'rows worker: only reads may be asked ahead' });
566
+ return;
567
+ }
568
+ void enqueue(async () => {
569
+ const t0 = performance.now();
570
+ try {
571
+ if (thawVerification) await thawVerification;
572
+ const { result, transfer } = await handle(type, payload, source);
573
+ if (id === ROWS_PREWARM_OPEN_ID && type === 'open' && source === 'owner') aheadStore.openedAhead();
574
+ // `wt` is the time spent in here, so the page can tell work from transit.
575
+ target.postMessage({ id, ok: true, wt: performance.now() - t0, ...result }, transfer ?? []);
576
+ } catch (err) {
577
+ target.postMessage({ id, ok: false, error: err instanceof Error ? err.message : String(err) });
578
+ }
579
+ });
580
+ }
581
+
582
+ self.onmessage = (ev: MessageEvent) => {
583
+ const data = ev.data ?? {};
584
+ // Everything a prewarm sends goes under a negative id (`rows-prewarm.ts`).
585
+ if (typeof data.id === 'number' && data.id > 0) aheadStore.claim();
586
+ // Handled off the chain: registering a port must not wait behind a long op,
587
+ // or the follower's first requests would deadlock its attach.
588
+ if (data.type === 'add-client') {
589
+ const port = ev.ports?.[0];
590
+ const clientId = data.payload?.clientId as string | undefined;
591
+ if (!port || !clientId) {
592
+ (self as unknown as Worker).postMessage({
593
+ id: data.id,
594
+ ok: false,
595
+ error: 'rows worker: add-client needs a clientId and a transferred port',
596
+ });
597
+ return;
598
+ }
599
+ clients.get(clientId)?.close();
600
+ clients.set(clientId, port);
601
+ port.onmessage = (pe: MessageEvent) => dispatch(port, pe.data, 'client');
602
+ port.start?.();
603
+ (self as unknown as Worker).postMessage({ id: data.id, ok: true, wt: 0 });
604
+ return;
605
+ }
606
+ dispatch(self as unknown as Worker, data, 'owner');
607
+ };