@spooky-sync/core 1.0.0-beta.10 → 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.
@@ -2147,6 +2147,12 @@ function maintenance(stats) {
2147
2147
  *
2148
2148
  * The engine (`rows-cache-engine.ts`) adopts all three when it connects, and
2149
2149
  * starts its own worker when anything about them is wrong.
2150
+ *
2151
+ * With shared tabs the page does not know yet which tab will lead. If it is
2152
+ * this one, its engine adopts the worker as it would alone. If it is another,
2153
+ * that tab's worker finds the files held, asks for them (`rows-worker.ts`,
2154
+ * `ROWS_YIELD_CHANNEL`), and the worker started here closes its store and
2155
+ * says so under the open's id, so nothing here goes on believing it is open.
2150
2156
  */
2151
2157
  /** localStorage key under which the engine leaves what {@link prewarmRows} needs. */
2152
2158
  const ROWS_PREWARM_KEY = "sp00ky.rows.prewarm";
@@ -2154,6 +2160,12 @@ const ROWS_PREWARM_KEY = "sp00ky.rows.prewarm";
2154
2160
  const ROWS_PREWARM_OPEN_ID = -1;
2155
2161
  /** Read `i` of a prewarm goes out as message `ROWS_AHEAD_ID - i`. The worker answers reads only under these ids. */
2156
2162
  const ROWS_AHEAD_ID = -10;
2163
+ /**
2164
+ * BroadcastChannel on which a worker that leads a bucket and finds its files
2165
+ * held asks for them: `{ bucket }`. A worker holding that store for a page
2166
+ * that has not claimed it yet (a prewarm) lets go.
2167
+ */
2168
+ const ROWS_YIELD_CHANNEL = "sp00ky.rows.yield";
2157
2169
  /** The worker ops a prewarm may ask ahead: the ones that answer rows and change nothing. */
2158
2170
  const ROWS_AHEAD_OPS = new Set([
2159
2171
  "select",
@@ -2161,7 +2173,77 @@ const ROWS_AHEAD_OPS = new Set([
2161
2173
  "relation"
2162
2174
  ]);
2163
2175
  /** {@link prewarmRows} as a script to inline in `<head>`, ahead of the app's bundle. */
2164
- const ROWS_PREWARM_SNIPPET = `(function(){try{var g=globalThis,p=JSON.parse(localStorage.getItem("${ROWS_PREWARM_KEY}")||"null");if(!p||!p.url||!p.bucket||g.__sp00kyRowsPrewarm)return;var r=Array.isArray(p.reads)?p.reads:[],s={worker:new Worker(p.url,{type:"module"}),bucket:p.bucket,failed:false,reads:r,replies:{}};s.worker.onerror=function(){s.failed=true};s.worker.onmessage=function(e){var d=e.data;if(!d)return;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};s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});for(var i=0;i<r.length;i++)s.worker.postMessage({id:${ROWS_AHEAD_ID}-i,type:r[i][0],payload:r[i][1]});s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
2176
+ const ROWS_PREWARM_SNIPPET = `(function(){try{var g=globalThis,p=JSON.parse(localStorage.getItem("${ROWS_PREWARM_KEY}")||"null");if(!p||!p.url||!p.bucket||g.__sp00kyRowsPrewarm)return;var r=Array.isArray(p.reads)?p.reads:[],s={worker:new Worker(p.url,{type:"module"}),bucket:p.bucket,failed:false,reads:r,replies:{}};s.worker.onerror=function(){s.failed=true};s.worker.onmessage=function(e){var d=e.data;if(!d)return;if(d.id===${ROWS_PREWARM_OPEN_ID}){if(d.ok===true)s.opened=d;else{s.opened=void 0;s.reads=[];s.replies={}}}else if(d.id<=${ROWS_AHEAD_ID})s.replies[${ROWS_AHEAD_ID}-d.id]=d};s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});for(var i=0;i<r.length;i++)s.worker.postMessage({id:${ROWS_AHEAD_ID}-i,type:r[i][0],payload:r[i][1]});s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
2177
+
2178
+ //#endregion
2179
+ //#region src/services/database/rows-yield.ts
2180
+ /**
2181
+ * A store opened ahead of its page, and how the tab that leads gets it back.
2182
+ *
2183
+ * `prewarmRows` (rows-prewarm.ts) starts the row worker from the page head and
2184
+ * opens the last bucket's store before the app has loaded. With shared tabs
2185
+ * the page cannot know then whether it will lead. When another tab does, that
2186
+ * tab's worker finds the files held by a worker nobody uses: its page becomes
2187
+ * a follower and ends it, but only once its bundle has loaded and it was told
2188
+ * its role, and the leader's ten attempts are over by then.
2189
+ *
2190
+ * So a worker that leads asks for the files each time an open fails, and a
2191
+ * worker that holds them unclaimed gives them up and tells its page. A page
2192
+ * claims its worker with the first message it sends under an id of its own
2193
+ * (everything a prewarm sends goes under a negative one).
2194
+ *
2195
+ * Kept apart from `rows-worker.ts`, which runs only in a worker on OPFS, so
2196
+ * this can be tested.
2197
+ */
2198
+ var AheadStore = class {
2199
+ /** The open store was opened ahead of the page. */
2200
+ ahead = false;
2201
+ /** The page has sent a message of its own: what is open here is its store from now on. */
2202
+ claimed = false;
2203
+ heard = null;
2204
+ constructor(host) {
2205
+ this.host = host;
2206
+ }
2207
+ /** A message from the page under an id of its own. */
2208
+ claim() {
2209
+ this.claimed = true;
2210
+ }
2211
+ /** The open a prewarm asked for has succeeded. */
2212
+ openedAhead() {
2213
+ if (this.claimed || this.host.openBucket() === null || !this.listen()) return;
2214
+ this.ahead = true;
2215
+ }
2216
+ /** This worker leads `bucket` and could not open its files: whoever holds them unclaimed is asked for them. */
2217
+ ask(bucket) {
2218
+ try {
2219
+ this.listen()?.postMessage({ bucket });
2220
+ } catch {}
2221
+ }
2222
+ wanted(bucket) {
2223
+ return this.ahead && !this.claimed && this.host.openBucket() !== null && this.host.openBucket() === bucket;
2224
+ }
2225
+ listen() {
2226
+ if (this.heard) return this.heard;
2227
+ const channel = this.host.channel();
2228
+ if (!channel) return null;
2229
+ channel.onmessage = (ev) => {
2230
+ const bucket = ev.data?.bucket;
2231
+ if (!this.wanted(bucket)) return;
2232
+ this.host.enqueue(() => {
2233
+ if (!this.wanted(bucket)) return;
2234
+ this.ahead = false;
2235
+ this.host.closeStore();
2236
+ this.host.tellPage({
2237
+ id: ROWS_PREWARM_OPEN_ID,
2238
+ ok: false,
2239
+ error: "rows worker: gave the store to the tab that leads"
2240
+ });
2241
+ });
2242
+ };
2243
+ this.heard = channel;
2244
+ return channel;
2245
+ }
2246
+ };
2165
2247
 
2166
2248
  //#endregion
2167
2249
  //#region src/services/database/rows-worker.ts
@@ -2299,7 +2381,7 @@ const errMessage = (e) => e instanceof Error ? e.name && e.name !== "Error" ? `$
2299
2381
  * does. A caller that must not run in memory (a shared-tabs leader) gets the
2300
2382
  * error instead.
2301
2383
  */
2302
- async function openStore(bucketId, useOpfs, opts = {}, mode = "own") {
2384
+ async function openStore(bucketId, useOpfs, opts = {}, mode = "own", leading = false) {
2303
2385
  reading = false;
2304
2386
  if (!useOpfs) {
2305
2387
  store = await RowStore.open(memoryIo());
@@ -2322,6 +2404,7 @@ async function openStore(bucketId, useOpfs, opts = {}, mode = "own") {
2322
2404
  closeFiles();
2323
2405
  lastError = errMessage(e);
2324
2406
  if (attempt === maxAttempts || lastError.includes("Missing required OPFS APIs")) break;
2407
+ if (leading) aheadStore.ask(bucketId);
2325
2408
  await new Promise((resolve) => setTimeout(resolve, backoffMs[Math.min(attempt - 1, backoffMs.length - 1)] ?? 0));
2326
2409
  }
2327
2410
  }
@@ -2334,6 +2417,13 @@ async function openStore(bucketId, useOpfs, opts = {}, mode = "own") {
2334
2417
  opfsError: lastError
2335
2418
  };
2336
2419
  }
2420
+ const aheadStore = new AheadStore({
2421
+ channel: () => typeof BroadcastChannel === "function" ? new BroadcastChannel(ROWS_YIELD_CHANNEL) : null,
2422
+ openBucket: () => store !== null && opened !== null ? opened.dbName : null,
2423
+ enqueue: (fn) => void enqueue(fn),
2424
+ closeStore: () => closeStore(),
2425
+ tellPage: (message) => self.postMessage(message)
2426
+ });
2337
2427
  /** Persist the index and let go of the files. */
2338
2428
  function closeStore() {
2339
2429
  clearTimers();
@@ -2515,7 +2605,7 @@ async function handle(type, payload, source) {
2515
2605
  const mode = payload.reader ? "reader" : payload.share ? "share" : "own";
2516
2606
  if (!(store !== null && opened !== null && opened.dbName === payload.dbName && opened.useOpfs === payload.useOpfs && opened.mode === mode)) {
2517
2607
  closeStore();
2518
- const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode);
2608
+ const result = await openStore(payload.dbName, payload.useOpfs, payload.openOptions, mode, Boolean(payload.workerLockName));
2519
2609
  opened = {
2520
2610
  dbName: payload.dbName,
2521
2611
  useOpfs: payload.useOpfs,
@@ -2593,6 +2683,7 @@ function dispatch(target, data, source) {
2593
2683
  try {
2594
2684
  if (thawVerification) await thawVerification;
2595
2685
  const { result, transfer } = await handle(type, payload, source);
2686
+ if (id === ROWS_PREWARM_OPEN_ID && type === "open" && source === "owner") aheadStore.openedAhead();
2596
2687
  target.postMessage({
2597
2688
  id,
2598
2689
  ok: true,
@@ -2610,6 +2701,7 @@ function dispatch(target, data, source) {
2610
2701
  }
2611
2702
  self.onmessage = (ev) => {
2612
2703
  const data = ev.data ?? {};
2704
+ if (typeof data.id === "number" && data.id > 0) aheadStore.claim();
2613
2705
  if (data.type === "add-client") {
2614
2706
  const port = ev.ports?.[0];
2615
2707
  const clientId = data.payload?.clientId;
package/dist/types.d.ts CHANGED
@@ -1765,6 +1765,8 @@ interface Sp00kyConfig<S extends SchemaStructure> {
1765
1765
  * `localEngine: 'rows'` only. Keep a copy of the rows the app reads at
1766
1766
  * startup in localStorage (up to about 1 MB), so `peekSelect` / `peekByIds`
1767
1767
  * can hand a screen what it showed last time before the store is open.
1768
+ * Works with `sharedTabs`: a copy is dropped for every tab as soon as any
1769
+ * tab writes to a table it was read from.
1768
1770
  * Default `true` for a durable store; `false` turns it off.
1769
1771
  */
1770
1772
  paintCache?: boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spooky-sync/core",
3
- "version": "1.0.0-beta.10",
3
+ "version": "1.0.0-beta.11",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./dist/sqlite-worker.js",
@@ -86,8 +86,8 @@
86
86
  }
87
87
  },
88
88
  "dependencies": {
89
- "@spooky-sync/query-builder": "1.0.0-beta.10",
90
- "@spooky-sync/ssp-wasm": "1.0.0-beta.10",
89
+ "@spooky-sync/query-builder": "1.0.0-beta.11",
90
+ "@spooky-sync/ssp-wasm": "1.0.0-beta.11",
91
91
  "@sqlite.org/sqlite-wasm": "3.53.0-build1",
92
92
  "@surrealdb/wasm": "^3.1.0",
93
93
  "@surrealdb/wasm-native": "^3.3.4",
@@ -290,8 +290,8 @@ export class Sp00kyClient<S extends SchemaStructure> {
290
290
  // Unobserved, a failed boot must not also be an unhandled rejection.
291
291
  this.ready.promise.catch(() => {});
292
292
  // The bucket `boot` is about to open, so the store can paint from it now
293
- // (`peekQuery`). Alone in the store only: see `LocalStore.expectBucket`.
294
- if (!s.tabs) s.local.expectBucket?.(readBootBucketHint() ?? ANON_USER_ID);
293
+ // (`peekQuery`): see `LocalStore.expectBucket`.
294
+ s.local.expectBucket?.(readBootBucketHint() ?? ANON_USER_ID);
295
295
  }
296
296
 
297
297
  /** Adapter callbacks become runtime events; runtime events reach the legacy services. */
@@ -491,8 +491,9 @@ export class Sp00kyClient<S extends SchemaStructure> {
491
491
  * handed back at once and with no need for `init()` to have run: something
492
492
  * for a component to render on its first pass, where it would have rendered
493
493
  * an empty list. `null` when the local store keeps no such copy (only
494
- * `localEngine: 'rows'` with its paint cache does, and not with shared
495
- * tabs), or has none for this query.
494
+ * `localEngine: 'rows'` with its paint cache does), or has none for this
495
+ * query: it never rendered at startup, or a tab has written to one of its
496
+ * tables since.
496
497
  *
497
498
  * They are rows to paint from, not a result. The query still has to be run
498
499
  * and subscribed to; what that delivers is the answer, and it replaces these