@spooky-sync/core 1.0.0-beta.10 → 1.0.0-beta.12

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.
@@ -12,6 +12,12 @@
12
12
  *
13
13
  * The engine (`rows-cache-engine.ts`) adopts all three when it connects, and
14
14
  * starts its own worker when anything about them is wrong.
15
+ *
16
+ * With shared tabs the page does not know yet which tab will lead. If it is
17
+ * this one, its engine adopts the worker as it would alone. If it is another,
18
+ * that tab's worker finds the files held, asks for them (`rows-worker.ts`,
19
+ * `ROWS_YIELD_CHANNEL`), and the worker started here closes its store and
20
+ * says so under the open's id, so nothing here goes on believing it is open.
15
21
  */
16
22
 
17
23
  /** localStorage key under which the engine leaves what {@link prewarmRows} needs. */
@@ -22,6 +28,13 @@ export const ROWS_PREWARM_OPEN_ID = -1;
22
28
  /** Read `i` of a prewarm goes out as message `ROWS_AHEAD_ID - i`. The worker answers reads only under these ids. */
23
29
  export const ROWS_AHEAD_ID = -10;
24
30
 
31
+ /**
32
+ * BroadcastChannel on which a worker that leads a bucket and finds its files
33
+ * held asks for them: `{ bucket }`. A worker holding that store for a page
34
+ * that has not claimed it yet (a prewarm) lets go.
35
+ */
36
+ export const ROWS_YIELD_CHANNEL = 'sp00ky.rows.yield';
37
+
25
38
  /** The worker ops a prewarm may ask ahead: the ones that answer rows and change nothing. */
26
39
  export const ROWS_AHEAD_OPS: ReadonlySet<string> = new Set(['select', 'by-ids', 'relation']);
27
40
 
@@ -91,6 +104,14 @@ export function prewarmRows(): void {
91
104
  if (!data) return;
92
105
  if (data.id === ROWS_PREWARM_OPEN_ID) {
93
106
  if (data.ok === true) pre.opened = data;
107
+ else {
108
+ // A second word under the open's id takes the first back: the worker
109
+ // gave its store to the tab that leads (`ROWS_YIELD_CHANNEL`). That
110
+ // tab writes to it from here on, so nothing read ahead stands either.
111
+ pre.opened = undefined;
112
+ pre.reads = [];
113
+ pre.replies = {};
114
+ }
94
115
  } else if (data.id <= ROWS_AHEAD_ID) pre.replies[ROWS_AHEAD_ID - data.id] = data;
95
116
  };
96
117
  // One attempt and no memory fallback: if the files are held (another tab
@@ -115,7 +136,8 @@ export const ROWS_PREWARM_SNIPPET =
115
136
  `var r=Array.isArray(p.reads)?p.reads:[],s={worker:new Worker(p.url,{type:"module"}),bucket:p.bucket,failed:false,reads:r,replies:{}};` +
116
137
  `s.worker.onerror=function(){s.failed=true};` +
117
138
  `s.worker.onmessage=function(e){var d=e.data;if(!d)return;` +
118
- `if(d.id===${ROWS_PREWARM_OPEN_ID}){if(d.ok===true)s.opened=d}else if(d.id<=${ROWS_AHEAD_ID})s.replies[${ROWS_AHEAD_ID}-d.id]=d};` +
139
+ `if(d.id===${ROWS_PREWARM_OPEN_ID}){if(d.ok===true)s.opened=d;else{s.opened=void 0;s.reads=[];s.replies={}}}` +
140
+ `else if(d.id<=${ROWS_AHEAD_ID})s.replies[${ROWS_AHEAD_ID}-d.id]=d};` +
119
141
  `s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});` +
120
142
  `for(var i=0;i<r.length;i++)s.worker.postMessage({id:${ROWS_AHEAD_ID}-i,type:r[i][0],payload:r[i][1]});` +
121
143
  `s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
@@ -155,8 +177,9 @@ export function jsonSafe(value: unknown): boolean {
155
177
  * Why the answer is the one the worker would give now: it read the store
156
178
  * after opening it and before this page asked for anything, and nothing has
157
179
  * written since. The engine drops everything left here the moment it sends a
158
- * write (or anything else that is not a plain read), and never uses this at
159
- * all when other tabs write through the same worker.
180
+ * write (or anything else that is not a plain read), and the moment another
181
+ * tab can write through the same worker (a follower's port handed to a
182
+ * shared-tabs leader).
160
183
  */
161
184
  export class ReadAhead {
162
185
  private wanted = new Map<string, number>();
@@ -180,6 +203,9 @@ export class ReadAhead {
180
203
  }
181
204
 
182
205
  private arrived(data: PrewarmReply): void {
206
+ // The worker gave the store away after all (see `prewarmRows`): another
207
+ // tab writes to it now, and what was read before that is not its state.
208
+ if (data.id === ROWS_PREWARM_OPEN_ID && !data.ok) return this.drop();
183
209
  if (data.id > ROWS_AHEAD_ID) return;
184
210
  const i = ROWS_AHEAD_ID - data.id;
185
211
  const waiter = this.waiting.get(i);
@@ -36,7 +36,8 @@ import {
36
36
  maintenance,
37
37
  visibleTables,
38
38
  } from './rows-exec';
39
- import { ROWS_AHEAD_ID, ROWS_AHEAD_OPS } from './rows-prewarm';
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';
40
41
 
41
42
  type PostTarget = Pick<MessagePort, 'postMessage'>;
42
43
 
@@ -179,7 +180,8 @@ async function openStore(
179
180
  bucketId: string,
180
181
  useOpfs: boolean,
181
182
  opts: OpenOptions = {},
182
- mode: FileMode = 'own'
183
+ mode: FileMode = 'own',
184
+ leading = false
183
185
  ): Promise<{ persisted: boolean; opfsError?: string }> {
184
186
  reading = false;
185
187
  if (!useOpfs) {
@@ -203,6 +205,8 @@ async function openStore(
203
205
  closeFiles();
204
206
  lastError = errMessage(e);
205
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);
206
210
  await new Promise((resolve) => setTimeout(resolve, backoffMs[Math.min(attempt - 1, backoffMs.length - 1)] ?? 0));
207
211
  }
208
212
  }
@@ -222,6 +226,18 @@ async function openStore(
222
226
  return { persisted: false, opfsError: lastError };
223
227
  }
224
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
+
225
241
  /** Persist the index and let go of the files. */
226
242
  function closeStore(): void {
227
243
  clearTimers();
@@ -481,7 +497,7 @@ async function handle(type: string, payload: any, source: 'owner' | 'client'): P
481
497
  store !== null && opened !== null && opened.dbName === payload.dbName && opened.useOpfs === payload.useOpfs && opened.mode === mode;
482
498
  if (!same) {
483
499
  closeStore();
484
- const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode);
500
+ const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode, Boolean(payload.workerLockName));
485
501
  opened = { dbName: payload.dbName, useOpfs: payload.useOpfs, mode, result };
486
502
  }
487
503
  return { result: { ...opened!.result, proto: ROWS_PROTOCOL, workerUrl: self.location.href } };
@@ -554,6 +570,7 @@ function dispatch(target: PostTarget, data: any, source: 'owner' | 'client'): vo
554
570
  try {
555
571
  if (thawVerification) await thawVerification;
556
572
  const { result, transfer } = await handle(type, payload, source);
573
+ if (id === ROWS_PREWARM_OPEN_ID && type === 'open' && source === 'owner') aheadStore.openedAhead();
557
574
  // `wt` is the time spent in here, so the page can tell work from transit.
558
575
  target.postMessage({ id, ok: true, wt: performance.now() - t0, ...result }, transfer ?? []);
559
576
  } catch (err) {
@@ -564,6 +581,8 @@ function dispatch(target: PostTarget, data: any, source: 'owner' | 'client'): vo
564
581
 
565
582
  self.onmessage = (ev: MessageEvent) => {
566
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();
567
586
  // Handled off the chain: registering a port must not wait behind a long op,
568
587
  // or the follower's first requests would deadlock its attach.
569
588
  if (data.type === 'add-client') {
@@ -0,0 +1,141 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { AheadStore, type AheadHost, type YieldChannel } from './rows-yield';
3
+ import { ROWS_PREWARM_OPEN_ID } from './rows-prewarm';
4
+
5
+ /** BroadcastChannels of one name: a message reaches every channel but the one that sent it. */
6
+ function hub(): () => YieldChannel {
7
+ const channels: YieldChannel[] = [];
8
+ return () => {
9
+ const channel: YieldChannel = {
10
+ onmessage: null,
11
+ postMessage: (data) => {
12
+ for (const other of channels) if (other !== channel) other.onmessage?.({ data } as MessageEvent);
13
+ },
14
+ };
15
+ channels.push(channel);
16
+ return channel;
17
+ };
18
+ }
19
+
20
+ /** A worker as `AheadStore` sees it: an open bucket, a queue of ops, a page. */
21
+ function worker(channel: (() => YieldChannel) | null, bucket: string | null = 'user_a') {
22
+ const state = {
23
+ bucket,
24
+ queue: [] as (() => void)[],
25
+ closed: 0,
26
+ told: [] as { id: number; ok: false; error: string }[],
27
+ /** Run what waits in the op queue. */
28
+ run() {
29
+ for (const fn of state.queue.splice(0)) fn();
30
+ },
31
+ };
32
+ const host: AheadHost = {
33
+ channel: () => channel?.() ?? null,
34
+ openBucket: () => state.bucket,
35
+ enqueue: (fn) => void state.queue.push(fn),
36
+ closeStore: () => {
37
+ state.closed++;
38
+ state.bucket = null;
39
+ },
40
+ tellPage: (message) => void state.told.push(message),
41
+ };
42
+ return { state, store: new AheadStore(host) };
43
+ }
44
+
45
+ describe('a store opened ahead of its page', () => {
46
+ it('is given to the worker that leads, and the page is told under the open\'s id', () => {
47
+ const channel = hub();
48
+ const held = worker(channel);
49
+ const leader = worker(channel, null);
50
+ held.store.openedAhead();
51
+ leader.store.ask('user_a');
52
+ // In turn with the ops: nothing is closed under a read that is running.
53
+ expect(held.state.closed).toBe(0);
54
+ held.state.run();
55
+ expect(held.state.closed).toBe(1);
56
+ expect(held.state.told).toEqual([{ id: ROWS_PREWARM_OPEN_ID, ok: false, error: expect.stringContaining('gave the store') }]);
57
+ // Asked again (the leader's next attempt): there is nothing left to give.
58
+ leader.store.ask('user_a');
59
+ held.state.run();
60
+ expect(held.state.closed).toBe(1);
61
+ expect(held.state.told.length).toBe(1);
62
+ });
63
+
64
+ it('stays with a page that has claimed it', () => {
65
+ const channel = hub();
66
+ const held = worker(channel);
67
+ const leader = worker(channel, null);
68
+ held.store.openedAhead();
69
+ held.store.claim();
70
+ leader.store.ask('user_a');
71
+ held.state.run();
72
+ expect(held.state.closed).toBe(0);
73
+ expect(held.state.told).toEqual([]);
74
+ });
75
+
76
+ it('stays with a page that claims it while the hand-over waits its turn', () => {
77
+ const channel = hub();
78
+ const held = worker(channel);
79
+ const leader = worker(channel, null);
80
+ held.store.openedAhead();
81
+ leader.store.ask('user_a');
82
+ expect(held.state.queue.length).toBe(1);
83
+ held.store.claim();
84
+ held.state.run();
85
+ expect(held.state.closed).toBe(0);
86
+ expect(held.state.told).toEqual([]);
87
+ });
88
+
89
+ it('is not given up for another bucket, nor by a worker whose page opened it itself', () => {
90
+ const channel = hub();
91
+ const held = worker(channel);
92
+ const owned = worker(channel);
93
+ const leader = worker(channel, null);
94
+ held.store.openedAhead();
95
+ // `owned` never opened ahead: its store was asked for by its page.
96
+ owned.store.claim();
97
+ owned.store.openedAhead();
98
+ leader.store.ask('user_b');
99
+ held.state.run();
100
+ owned.state.run();
101
+ expect(held.state.closed).toBe(0);
102
+ leader.store.ask('user_a');
103
+ held.state.run();
104
+ owned.state.run();
105
+ expect(held.state.closed).toBe(1);
106
+ expect(owned.state.closed).toBe(0);
107
+ });
108
+
109
+ it('is asked for again when the first asking came while it was still being opened', () => {
110
+ const channel = hub();
111
+ const held = worker(channel, null);
112
+ const leader = worker(channel, null);
113
+ // The open is under way: no store yet, and nobody listening.
114
+ held.store.openedAhead();
115
+ leader.store.ask('user_a');
116
+ held.state.run();
117
+ expect(held.state.closed).toBe(0);
118
+ held.state.bucket = 'user_a';
119
+ held.store.openedAhead();
120
+ // The leader's next failed attempt.
121
+ leader.store.ask('user_a');
122
+ held.state.run();
123
+ expect(held.state.closed).toBe(1);
124
+ });
125
+
126
+ it('does nothing where there is no channel to ask on', () => {
127
+ const held = worker(null);
128
+ held.store.openedAhead();
129
+ expect(() => held.store.ask('user_a')).not.toThrow();
130
+ held.state.run();
131
+ expect(held.state.closed).toBe(0);
132
+ // Nor when the channel throws.
133
+ const broken = worker(() => ({
134
+ onmessage: null,
135
+ postMessage: () => {
136
+ throw new Error('closed');
137
+ },
138
+ }));
139
+ expect(() => broken.store.ask('user_a')).not.toThrow();
140
+ });
141
+ });
@@ -0,0 +1,92 @@
1
+ /**
2
+ * A store opened ahead of its page, and how the tab that leads gets it back.
3
+ *
4
+ * `prewarmRows` (rows-prewarm.ts) starts the row worker from the page head and
5
+ * opens the last bucket's store before the app has loaded. With shared tabs
6
+ * the page cannot know then whether it will lead. When another tab does, that
7
+ * tab's worker finds the files held by a worker nobody uses: its page becomes
8
+ * a follower and ends it, but only once its bundle has loaded and it was told
9
+ * its role, and the leader's ten attempts are over by then.
10
+ *
11
+ * So a worker that leads asks for the files each time an open fails, and a
12
+ * worker that holds them unclaimed gives them up and tells its page. A page
13
+ * claims its worker with the first message it sends under an id of its own
14
+ * (everything a prewarm sends goes under a negative one).
15
+ *
16
+ * Kept apart from `rows-worker.ts`, which runs only in a worker on OPFS, so
17
+ * this can be tested.
18
+ */
19
+ import { ROWS_PREWARM_OPEN_ID } from './rows-prewarm';
20
+
21
+ /** What this needs of a BroadcastChannel. A channel never hears its own messages. */
22
+ export interface YieldChannel {
23
+ postMessage(message: unknown): void;
24
+ onmessage: ((ev: MessageEvent) => void) | null;
25
+ }
26
+
27
+ export interface AheadHost {
28
+ /** The channel the workers of an origin ask each other on, or null where there is none. */
29
+ channel(): YieldChannel | null;
30
+ /** The bucket whose store is open in this worker, or null. */
31
+ openBucket(): string | null;
32
+ /** Run `fn` in turn with the worker's ops, so a store is not closed under a read. */
33
+ enqueue(fn: () => void): void;
34
+ closeStore(): void;
35
+ /** Post to the page that started this worker. */
36
+ tellPage(message: { id: number; ok: false; error: string }): void;
37
+ }
38
+
39
+ export class AheadStore {
40
+ /** The open store was opened ahead of the page. */
41
+ private ahead = false;
42
+ /** The page has sent a message of its own: what is open here is its store from now on. */
43
+ private claimed = false;
44
+ private heard: YieldChannel | null = null;
45
+
46
+ constructor(private host: AheadHost) {}
47
+
48
+ /** A message from the page under an id of its own. */
49
+ claim(): void {
50
+ this.claimed = true;
51
+ }
52
+
53
+ /** The open a prewarm asked for has succeeded. */
54
+ openedAhead(): void {
55
+ if (this.claimed || this.host.openBucket() === null || !this.listen()) return;
56
+ this.ahead = true;
57
+ }
58
+
59
+ /** This worker leads `bucket` and could not open its files: whoever holds them unclaimed is asked for them. */
60
+ ask(bucket: string): void {
61
+ try {
62
+ this.listen()?.postMessage({ bucket });
63
+ } catch {
64
+ /* no channel: the retries are all there is */
65
+ }
66
+ }
67
+
68
+ private wanted(bucket: unknown): boolean {
69
+ return this.ahead && !this.claimed && this.host.openBucket() !== null && this.host.openBucket() === bucket;
70
+ }
71
+
72
+ private listen(): YieldChannel | null {
73
+ if (this.heard) return this.heard;
74
+ const channel = this.host.channel();
75
+ if (!channel) return null;
76
+ channel.onmessage = (ev) => {
77
+ const bucket = (ev.data as { bucket?: unknown } | null)?.bucket;
78
+ if (!this.wanted(bucket)) return;
79
+ // The page may claim the store while this waits its turn.
80
+ this.host.enqueue(() => {
81
+ if (!this.wanted(bucket)) return;
82
+ this.ahead = false;
83
+ this.host.closeStore();
84
+ // Under the open's id: the page then takes neither that open as answered
85
+ // nor anything it had read ahead (`prewarmRows`, `ReadAhead`).
86
+ this.host.tellPage({ id: ROWS_PREWARM_OPEN_ID, ok: false, error: 'rows worker: gave the store to the tab that leads' });
87
+ });
88
+ };
89
+ this.heard = channel;
90
+ return channel;
91
+ }
92
+ }
package/src/types.ts CHANGED
@@ -174,6 +174,8 @@ export interface Sp00kyConfig<S extends SchemaStructure> {
174
174
  * `localEngine: 'rows'` only. Keep a copy of the rows the app reads at
175
175
  * startup in localStorage (up to about 1 MB), so `peekSelect` / `peekByIds`
176
176
  * can hand a screen what it showed last time before the store is open.
177
+ * Works with `sharedTabs`: a copy is dropped for every tab as soon as any
178
+ * tab writes to a table it was read from.
177
179
  * Default `true` for a durable store; `false` turns it off.
178
180
  */
179
181
  paintCache?: boolean;