@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,251 @@
1
+ /**
2
+ * Starting the row store ahead of the app. Kept free of imports: a build
3
+ * script that only wants {@link ROWS_PREWARM_SNIPPET} for the page's `<head>`
4
+ * loads this file and nothing else of the client.
5
+ *
6
+ * What a page load can have done before its bundle has run:
7
+ *
8
+ * 1. the worker started and the last bucket's store opened;
9
+ * 2. the reads the app made in its first seconds last time, asked again
10
+ * ("read ahead"), their answers waiting in the page;
11
+ * 3. the tables' indexes read into the worker's memory.
12
+ *
13
+ * The engine (`rows-cache-engine.ts`) adopts all three when it connects, and
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.
21
+ */
22
+
23
+ /** localStorage key under which the engine leaves what {@link prewarmRows} needs. */
24
+ export const ROWS_PREWARM_KEY = 'sp00ky.rows.prewarm';
25
+
26
+ /** Message id of the open a prewarm sends. */
27
+ export const ROWS_PREWARM_OPEN_ID = -1;
28
+ /** Read `i` of a prewarm goes out as message `ROWS_AHEAD_ID - i`. The worker answers reads only under these ids. */
29
+ export const ROWS_AHEAD_ID = -10;
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
+
38
+ /** The worker ops a prewarm may ask ahead: the ones that answer rows and change nothing. */
39
+ export const ROWS_AHEAD_OPS: ReadonlySet<string> = new Set(['select', 'by-ids', 'relation']);
40
+
41
+ /** What the engine saves for the next page load. */
42
+ export interface PrewarmRecord {
43
+ url: string;
44
+ bucket: string;
45
+ /** `[op, payload]` of the reads to ask ahead; JSON all the way down. */
46
+ reads?: [string, unknown][];
47
+ }
48
+
49
+ /** A worker's reply as it arrives: the transport's envelope around an op's result. */
50
+ export interface PrewarmReply {
51
+ id: number;
52
+ ok: boolean;
53
+ error?: string;
54
+ [field: string]: unknown;
55
+ }
56
+
57
+ export interface Prewarmed {
58
+ worker: Worker;
59
+ bucket: string;
60
+ failed: boolean;
61
+ /** The worker's answer to the open it was started with, once it has come. */
62
+ opened?: PrewarmReply;
63
+ /** The reads asked ahead, and the answers that have come, by position. */
64
+ reads: [string, unknown][];
65
+ replies: Record<number, PrewarmReply>;
66
+ }
67
+
68
+ type PrewarmGlobal = { __sp00kyRowsPrewarm?: Prewarmed };
69
+
70
+ /**
71
+ * Start the row store's worker and open the last bucket NOW, before the app
72
+ * has loaded. A worker takes about 10 ms to start and the store a few more to
73
+ * open; started from the first bytes of the page, that happens while the
74
+ * bundle downloads and parses, and by the time the client connects the store
75
+ * is open, its indexes are in memory and the answers to the app's first reads
76
+ * are already in the page. The engine finds the worker and adopts it; if
77
+ * anything about it is wrong (a new release, another bucket, a failed start)
78
+ * it starts its own, as it would have without this.
79
+ *
80
+ * Call it as early as the app can, or inline {@link ROWS_PREWARM_SNIPPET} in
81
+ * the page's `<head>`, which is this function without the bundle. A no-op on
82
+ * a first visit: the worker's URL is learned from the engine's first open.
83
+ */
84
+ export function prewarmRows(): void {
85
+ try {
86
+ const g = globalThis as PrewarmGlobal;
87
+ const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
88
+ if (!saved?.url || !saved.bucket || g.__sp00kyRowsPrewarm) return;
89
+ const reads = Array.isArray(saved.reads) ? saved.reads : [];
90
+ const pre: Prewarmed = {
91
+ worker: new Worker(saved.url, { type: 'module' }),
92
+ bucket: saved.bucket,
93
+ failed: false,
94
+ reads,
95
+ replies: {},
96
+ };
97
+ pre.worker.onerror = () => {
98
+ pre.failed = true;
99
+ };
100
+ // Kept for the engine: with the worker's answers in hand it does not ask
101
+ // again, and its first reads cost no trip to the worker at all.
102
+ pre.worker.onmessage = (ev: MessageEvent) => {
103
+ const data = ev.data as PrewarmReply | null;
104
+ if (!data) return;
105
+ if (data.id === ROWS_PREWARM_OPEN_ID) {
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
+ }
115
+ } else if (data.id <= ROWS_AHEAD_ID) pre.replies[ROWS_AHEAD_ID - data.id] = data;
116
+ };
117
+ // One attempt and no memory fallback: if the files are held (another tab
118
+ // leads), the engine's own open sorts it out.
119
+ pre.worker.postMessage({
120
+ id: ROWS_PREWARM_OPEN_ID,
121
+ type: 'open',
122
+ payload: { dbName: saved.bucket, useOpfs: true, openOptions: { maxAttempts: 1, disallowMemoryFallback: true } },
123
+ });
124
+ for (let i = 0; i < reads.length; i++) pre.worker.postMessage({ id: ROWS_AHEAD_ID - i, type: reads[i][0], payload: reads[i][1] });
125
+ pre.worker.postMessage({ id: -2, type: 'warm' });
126
+ g.__sp00kyRowsPrewarm = pre;
127
+ } catch {
128
+ // No storage, no workers, a blocked URL: the engine starts its own worker.
129
+ }
130
+ }
131
+
132
+ /** {@link prewarmRows} as a script to inline in `<head>`, ahead of the app's bundle. */
133
+ export const ROWS_PREWARM_SNIPPET =
134
+ `(function(){try{var g=globalThis,p=JSON.parse(localStorage.getItem("${ROWS_PREWARM_KEY}")||"null");` +
135
+ `if(!p||!p.url||!p.bucket||g.__sp00kyRowsPrewarm)return;` +
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:{}};` +
137
+ `s.worker.onerror=function(){s.failed=true};` +
138
+ `s.worker.onmessage=function(e){var d=e.data;if(!d)return;` +
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};` +
141
+ `s.worker.postMessage({id:${ROWS_PREWARM_OPEN_ID},type:"open",payload:{dbName:p.bucket,useOpfs:true,openOptions:{maxAttempts:1,disallowMemoryFallback:true}}});` +
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]});` +
143
+ `s.worker.postMessage({id:-2,type:"warm"});g.__sp00kyRowsPrewarm=s}catch(e){}})();`;
144
+
145
+ /** The prewarmed worker, once: whoever takes it owns it. */
146
+ export function takePrewarmed(): Prewarmed | null {
147
+ const g = globalThis as PrewarmGlobal;
148
+ const pre = g.__sp00kyRowsPrewarm ?? null;
149
+ delete g.__sp00kyRowsPrewarm;
150
+ return pre;
151
+ }
152
+
153
+ /** How a read is told from another: its op and its payload, as JSON. */
154
+ export const aheadKey = (type: string, payload: unknown): string => `${type}\n${JSON.stringify(payload)}`;
155
+
156
+ /**
157
+ * Whether `value` is the same thing after a trip through JSON. Only such a
158
+ * payload may be saved and asked again: a `Date` would come back as a string,
159
+ * and the worker would answer another question under the same key.
160
+ */
161
+ export function jsonSafe(value: unknown): boolean {
162
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return true;
163
+ if (typeof value === 'number') return Number.isFinite(value);
164
+ if (typeof value !== 'object') return false;
165
+ if (Array.isArray(value)) return value.every(jsonSafe);
166
+ const proto = Object.getPrototypeOf(value) as unknown;
167
+ if (proto !== Object.prototype && proto !== null) return false;
168
+ // An `undefined` property is one JSON leaves out, as if it had not been set.
169
+ return Object.values(value).every((v) => v === undefined || jsonSafe(v));
170
+ }
171
+
172
+ /**
173
+ * The answers a prewarmed worker gave, or is about to give, to the reads the
174
+ * last session made at startup. The engine takes one when it is about to ask
175
+ * the worker the very same thing, and so does not ask.
176
+ *
177
+ * Why the answer is the one the worker would give now: it read the store
178
+ * after opening it and before this page asked for anything, and nothing has
179
+ * written since. The engine drops everything left here the moment it sends a
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).
183
+ */
184
+ export class ReadAhead {
185
+ private wanted = new Map<string, number>();
186
+ private waiting = new Map<number, (reply: PrewarmReply | null) => void>();
187
+
188
+ /** Call once the transport has taken the worker: answers on their way pass through here first. */
189
+ constructor(
190
+ private pre: Prewarmed,
191
+ private waitMs: number
192
+ ) {
193
+ pre.reads.forEach((read, i) => {
194
+ if (Array.isArray(read) && ROWS_AHEAD_OPS.has(read[0])) this.wanted.set(aheadKey(read[0], read[1]), i);
195
+ });
196
+ const worker = pre.worker;
197
+ const inner = worker.onmessage;
198
+ worker.onmessage = (ev: MessageEvent) => {
199
+ const data = ev.data as PrewarmReply | null;
200
+ if (typeof data?.id === 'number' && data.id < 0) this.arrived(data);
201
+ else inner?.call(worker, ev);
202
+ };
203
+ }
204
+
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();
209
+ if (data.id > ROWS_AHEAD_ID) return;
210
+ const i = ROWS_AHEAD_ID - data.id;
211
+ const waiter = this.waiting.get(i);
212
+ if (waiter) waiter(data.ok ? data : null);
213
+ else if (this.wanted.size > 0) this.pre.replies[i] = data;
214
+ }
215
+
216
+ /**
217
+ * The answer to this read if it was asked ahead: a promise of the reply,
218
+ * or of `null` when it failed or does not come. `null` when it was not
219
+ * asked ahead (or was taken already): ask the worker.
220
+ */
221
+ take(type: string, payload: unknown): Promise<PrewarmReply | null> | null {
222
+ if (this.wanted.size === 0) return null;
223
+ const key = aheadKey(type, payload);
224
+ const i = this.wanted.get(key);
225
+ if (i === undefined) return null;
226
+ this.wanted.delete(key);
227
+ const here = this.pre.replies[i];
228
+ if (here) {
229
+ delete this.pre.replies[i];
230
+ return Promise.resolve(here.ok ? here : null);
231
+ }
232
+ // Sent before the app existed, so it is ahead of anything sent now:
233
+ // waiting for it is never slower than asking again. Not forever, though.
234
+ return new Promise((resolve) => {
235
+ const settle = (reply: PrewarmReply | null): void => {
236
+ clearTimeout(timer);
237
+ this.waiting.delete(i);
238
+ resolve(reply);
239
+ };
240
+ const timer = setTimeout(() => settle(null), this.waitMs);
241
+ this.waiting.set(i, settle);
242
+ });
243
+ }
244
+
245
+ /** Forget every answer not taken yet: the store is about to change, or the session has moved on. */
246
+ drop(): void {
247
+ this.wanted.clear();
248
+ this.pre.replies = {};
249
+ for (const settle of [...this.waiting.values()]) settle(null);
250
+ }
251
+ }