@spooky-sync/core 0.0.1-canary.153 → 0.0.1-canary.155
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/dist/index.d.ts +151 -0
- package/dist/index.js +1694 -126
- package/dist/{sqlite-plan-sql.js → sqlite-open.js} +83 -1
- package/dist/sqlite-worker.js +268 -108
- package/dist/tabs-broker-worker.d.ts +8 -0
- package/dist/tabs-broker-worker.js +434 -0
- package/dist/types.d.ts +55 -0
- package/package.json +4 -4
- package/scripts/check-broker-bundle.mjs +33 -0
- package/src/modules/cache/index.ts +35 -0
- package/src/modules/data/index.ts +13 -3
- package/src/modules/data/mutation-id.test.ts +25 -0
- package/src/modules/data/mutation-id.ts +35 -0
- package/src/modules/devtools/index.ts +82 -0
- package/src/modules/devtools/storage-info.test.ts +79 -0
- package/src/modules/devtools/storage-info.ts +116 -0
- package/src/modules/sync/queue/queue-up.forwarded.test.ts +51 -0
- package/src/modules/sync/queue/queue-up.ts +74 -38
- package/src/modules/sync/scheduler.ts +4 -2
- package/src/modules/sync/sync.ts +186 -8
- package/src/services/database/cache-engine.ts +8 -0
- package/src/services/database/engine-factory.ts +3 -2
- package/src/services/database/sqlite-cache-engine.test.ts +214 -85
- package/src/services/database/sqlite-cache-engine.ts +345 -76
- package/src/services/database/sqlite-open.ts +36 -1
- package/src/services/database/sqlite-select.test.ts +13 -46
- package/src/services/database/sqlite-transport.fixture.ts +30 -0
- package/src/services/database/sqlite-transport.ts +219 -0
- package/src/services/database/sqlite-worker.ts +340 -55
- package/src/services/database/surreal-cache-engine.ts +2 -0
- package/src/services/stream-processor/index.ts +11 -2
- package/src/services/tabs/broker-client.ts +283 -0
- package/src/services/tabs/broker.test.ts +278 -0
- package/src/services/tabs/coordinator.test.ts +192 -0
- package/src/services/tabs/coordinator.ts +567 -0
- package/src/services/tabs/fake-ports.fixture.ts +70 -0
- package/src/services/tabs/leader-locks.ts +75 -0
- package/src/services/tabs/protocol.ts +239 -0
- package/src/services/tabs/support.ts +36 -0
- package/src/services/tabs/tabs-broker-worker.ts +581 -0
- package/src/sp00ky.ts +164 -6
- package/src/types.ts +25 -0
- package/tsdown.config.ts +19 -10
|
@@ -9,13 +9,37 @@
|
|
|
9
9
|
* is unavailable it retries, then falls back to an in-memory DB and REPORTS the
|
|
10
10
|
* loss of durability (see `sqlite-open.ts`) instead of degrading silently.
|
|
11
11
|
*
|
|
12
|
-
* Message protocol (request/response keyed by `id
|
|
13
|
-
*
|
|
12
|
+
* Message protocol (request/response keyed by `id`; replies go to the channel
|
|
13
|
+
* the request arrived on):
|
|
14
|
+
* { id, type: 'open', payload: { dbName, useOpfs, workerLockName? } }
|
|
15
|
+
* -> { id, ok, persisted, opfsError? }
|
|
14
16
|
* { id, type: 'exec', payload: { sql, bind } } -> { id, ok, rows }
|
|
15
17
|
* { id, type: 'run', payload: { sql, bind } } -> { id, ok }
|
|
16
18
|
* { id, type: 'batch', payload: [{ sql, bind }] } (atomic BEGIN/COMMIT)
|
|
17
19
|
* { id, type: 'select', payload: { plan, params } } -> { id, ok, rows, relationFetches }
|
|
18
20
|
* { id, type: 'close' }
|
|
21
|
+
* { id, type: 'shutdown' } (owner only: close + pauseVfs + self.close)
|
|
22
|
+
* { id, type: 'relock', payload: { workerLockName } } (owner only)
|
|
23
|
+
* { id, type: 'add-client', payload: { clientId } } + ev.ports[0] (owner only)
|
|
24
|
+
* { id, type: 'remove-client', payload: { clientId } } (owner only)
|
|
25
|
+
*
|
|
26
|
+
* Multi-client (shared-tabs mode): the OWNER (the leader tab's engine) speaks
|
|
27
|
+
* on the worker's own channel and controls the lifecycle. Follower tabs get a
|
|
28
|
+
* MessagePort each (`add-client`) and may only issue data ops
|
|
29
|
+
* (exec/run/batch/select). Every op, from any channel, runs through ONE op
|
|
30
|
+
* chain so an async `select` from one client can never interleave with another
|
|
31
|
+
* client's `batch` at the VFS layer.
|
|
32
|
+
*
|
|
33
|
+
* Leader fencing (shared-tabs mode): `open` may carry `workerLockName`, a Web
|
|
34
|
+
* Lock this worker acquires BEFORE opening the pool and holds for the DB's
|
|
35
|
+
* lifetime. The name is unique per leadership, so the lock being gone has
|
|
36
|
+
* exactly one meaning: the broker stole it because this tab was presumed dead
|
|
37
|
+
* (usually frozen). When that happens the worker FENCES itself: closes the DB,
|
|
38
|
+
* releases the OPFS sync access handles (pauseVfs), tells the owner, and
|
|
39
|
+
* refuses every further op. A frozen-then-thawed ex-leader therefore can never
|
|
40
|
+
* write the durable file after a new leader took over. The thaw gate below
|
|
41
|
+
* closes the wake-up ordering race where a queued write could run before the
|
|
42
|
+
* lock-loss callback fires.
|
|
19
43
|
*
|
|
20
44
|
* `select` executes a whole QueryPlan — table creation, base select, the full
|
|
21
45
|
* `.related()` tree (shared `resolveRelations`), and JSON row parsing — in ONE
|
|
@@ -23,7 +47,12 @@
|
|
|
23
47
|
* hot path; the per-statement ops remain for the write/shim paths.
|
|
24
48
|
*/
|
|
25
49
|
import sqlite3InitModule from '@sqlite.org/sqlite-wasm';
|
|
26
|
-
import {
|
|
50
|
+
import {
|
|
51
|
+
openDb,
|
|
52
|
+
type OpenDbOptions,
|
|
53
|
+
type SqliteDbHandle,
|
|
54
|
+
type SqlitePoolHandle,
|
|
55
|
+
} from './sqlite-open';
|
|
27
56
|
import { executeSelect, type SelectDb } from './sqlite-select';
|
|
28
57
|
|
|
29
58
|
interface Stmt {
|
|
@@ -31,18 +60,181 @@ interface Stmt {
|
|
|
31
60
|
bind?: unknown[];
|
|
32
61
|
}
|
|
33
62
|
|
|
63
|
+
interface PostTarget {
|
|
64
|
+
postMessage: (msg: unknown) => void;
|
|
65
|
+
}
|
|
66
|
+
|
|
34
67
|
let db: SqliteDbHandle | null = null;
|
|
68
|
+
let pool: SqlitePoolHandle | null = null;
|
|
69
|
+
|
|
70
|
+
// ==================== leader fencing (worker web lock) ====================
|
|
71
|
+
|
|
72
|
+
/** Once fenced, every op is refused and the DB stays closed. Terminal. */
|
|
73
|
+
let fenced = false;
|
|
74
|
+
|
|
75
|
+
interface HeldLock {
|
|
76
|
+
name: string;
|
|
77
|
+
/** Release on purpose; the closure-local flag keeps the steal handler from
|
|
78
|
+
* mistaking it for a takeover. Idempotent. */
|
|
79
|
+
release: () => void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The per-leadership lock currently held (null = no fencing active). A
|
|
83
|
+
* relock (same-leader re-promotion after a broker restart) briefly holds two
|
|
84
|
+
* locks: the new one is installed here first, then the old one's own release
|
|
85
|
+
* is called, so there is no window where neither is held. */
|
|
86
|
+
let currentLock: HeldLock | null = null;
|
|
87
|
+
|
|
88
|
+
function workerLocks(): LockManager | null {
|
|
89
|
+
const nav = (globalThis as { navigator?: { locks?: LockManager } }).navigator;
|
|
90
|
+
return nav?.locks && typeof nav.locks.request === 'function' ? nav.locks : null;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Acquire `name` exclusively without waiting. Resolves with a handle when
|
|
95
|
+
* granted, null when someone else holds it. If the request settles while the
|
|
96
|
+
* holder still believes it owns the lock, the broker stole it: fence.
|
|
97
|
+
*/
|
|
98
|
+
function acquireWorkerLock(name: string): Promise<HeldLock | null> {
|
|
99
|
+
const locks = workerLocks();
|
|
100
|
+
// No Web Locks (non-browser test env): no fencing, behave as before.
|
|
101
|
+
if (!locks) return Promise.resolve({ name, release() {} });
|
|
102
|
+
return new Promise<HeldLock | null>((resolve) => {
|
|
103
|
+
let granted = false;
|
|
104
|
+
let intentional = false;
|
|
105
|
+
let releaseGrant: (() => void) | null = null;
|
|
106
|
+
locks
|
|
107
|
+
.request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
|
|
108
|
+
if (!lock) {
|
|
109
|
+
resolve(null);
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
granted = true;
|
|
113
|
+
resolve({
|
|
114
|
+
name,
|
|
115
|
+
release() {
|
|
116
|
+
intentional = true;
|
|
117
|
+
releaseGrant?.();
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
return new Promise<void>((release) => {
|
|
121
|
+
releaseGrant = release;
|
|
122
|
+
});
|
|
123
|
+
})
|
|
124
|
+
.then(
|
|
125
|
+
() => {
|
|
126
|
+
if (granted && !intentional) void fence('worker lock stolen');
|
|
127
|
+
},
|
|
128
|
+
() => {
|
|
129
|
+
if (granted && !intentional) void fence('worker lock request failed');
|
|
130
|
+
}
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function releaseHeldLock(): void {
|
|
136
|
+
currentLock?.release();
|
|
137
|
+
currentLock = null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Terminal teardown after leadership loss. Closing the DB first makes
|
|
142
|
+
* pauseVfs legal (it throws while files are open); pausing releases the sync
|
|
143
|
+
* access handles so the NEW leader's open succeeds without waiting for this
|
|
144
|
+
* worker to be garbage collected.
|
|
145
|
+
*/
|
|
146
|
+
async function fence(reason: string): Promise<void> {
|
|
147
|
+
if (fenced) return;
|
|
148
|
+
fenced = true;
|
|
149
|
+
// Deliberately console, not a logger: this must be visible in any host app
|
|
150
|
+
// regardless of its configured log level.
|
|
151
|
+
// oxlint-disable-next-line no-console
|
|
152
|
+
console.error(
|
|
153
|
+
`[sp00ky] sqlite worker fenced (${reason}): leadership was taken over, ` +
|
|
154
|
+
'closing the database and refusing further ops.'
|
|
155
|
+
);
|
|
156
|
+
try {
|
|
157
|
+
db?.close();
|
|
158
|
+
} catch {
|
|
159
|
+
/* already closed */
|
|
160
|
+
}
|
|
161
|
+
db = null;
|
|
162
|
+
try {
|
|
163
|
+
pool?.pauseVfs?.();
|
|
164
|
+
} catch {
|
|
165
|
+
/* pool already torn down or files still open; new leader retries anyway */
|
|
166
|
+
}
|
|
167
|
+
pool = null;
|
|
168
|
+
try {
|
|
169
|
+
(self as unknown as Worker).postMessage({ type: 'lock-lost', reason });
|
|
170
|
+
} catch {
|
|
171
|
+
/* owner gone */
|
|
172
|
+
}
|
|
173
|
+
releaseHeldLock();
|
|
174
|
+
self.close();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ==================== thaw gate ====================
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* A frozen tab's worker resumes with its message queue intact, and a queued
|
|
181
|
+
* write could run BEFORE the lock-steal callback fires. Both the 1s interval
|
|
182
|
+
* and every op call `noteTick()`; whichever runs first after a long gap kicks
|
|
183
|
+
* off a lock verification, and ops await it before touching the DB. The gap
|
|
184
|
+
* threshold must stay BELOW the broker's pong timeout: a freeze shorter than
|
|
185
|
+
* the threshold cannot have triggered a steal yet, so skipping the check for
|
|
186
|
+
* small gaps is safe.
|
|
187
|
+
*/
|
|
188
|
+
const FREEZE_SUSPECT_MS = 10_000;
|
|
189
|
+
let lastTickAt = performance.now();
|
|
190
|
+
let thawVerification: Promise<void> | null = null;
|
|
191
|
+
|
|
192
|
+
function noteTick(): void {
|
|
193
|
+
const now = performance.now();
|
|
194
|
+
const gap = now - lastTickAt;
|
|
195
|
+
lastTickAt = now;
|
|
196
|
+
if (gap > FREEZE_SUSPECT_MS && currentLock && !fenced && !thawVerification) {
|
|
197
|
+
thawVerification = verifyLockStillHeld().finally(() => {
|
|
198
|
+
thawVerification = null;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
setInterval(noteTick, 1000);
|
|
203
|
+
|
|
204
|
+
async function verifyLockStillHeld(): Promise<void> {
|
|
205
|
+
const locks = workerLocks();
|
|
206
|
+
const name = currentLock?.name;
|
|
207
|
+
if (!locks || !name || typeof locks.query !== 'function') return;
|
|
208
|
+
try {
|
|
209
|
+
const state = await locks.query();
|
|
210
|
+
const stillHeld = (state.held ?? []).some((l) => l.name === name);
|
|
211
|
+
if (!stillHeld) await fence('lock missing after suspected freeze');
|
|
212
|
+
} catch {
|
|
213
|
+
/* query unavailable: fall back to the steal callback */
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// ==================== db ops ====================
|
|
35
218
|
|
|
36
219
|
async function open(
|
|
37
220
|
dbName: string,
|
|
38
221
|
useOpfs: boolean,
|
|
39
|
-
systemTables: readonly string[] = []
|
|
222
|
+
systemTables: readonly string[] = [],
|
|
223
|
+
workerLockName?: string,
|
|
224
|
+
openOptions?: OpenDbOptions
|
|
40
225
|
): Promise<{ persisted: boolean; opfsError?: string }> {
|
|
226
|
+
if (workerLockName) {
|
|
227
|
+
const handle = await acquireWorkerLock(workerLockName);
|
|
228
|
+
if (!handle) throw new Error('worker-lock-unavailable');
|
|
229
|
+
releaseHeldLock();
|
|
230
|
+
currentLock = handle;
|
|
231
|
+
}
|
|
41
232
|
const sqlite3: any = await sqlite3InitModule();
|
|
42
233
|
// Retry/fallback policy (and the loud report when persistence is lost) lives
|
|
43
234
|
// in `sqlite-open.ts` so it can be unit tested off-worker.
|
|
44
|
-
const
|
|
45
|
-
db =
|
|
235
|
+
const result = await openDb(sqlite3, dbName, useOpfs, openOptions ?? {});
|
|
236
|
+
db = result.db;
|
|
237
|
+
pool = result.pool ?? null;
|
|
46
238
|
// Physically create the internal `_00_*` tables the client reads before any
|
|
47
239
|
// write (DEFINE is a noop on this engine, so the migrator can't). Prevents
|
|
48
240
|
// "no such table: _00_query" on a fresh bucket right after signup.
|
|
@@ -50,7 +242,7 @@ async function open(
|
|
|
50
242
|
db!.exec({ sql: `CREATE TABLE IF NOT EXISTS "${t}" (id TEXT PRIMARY KEY, data TEXT NOT NULL)` });
|
|
51
243
|
}
|
|
52
244
|
// Retry (rather than instantly failing with SQLITE_BUSY=5) if a lock is held.
|
|
53
|
-
// Combined with the
|
|
245
|
+
// Combined with the single-flight op chain, overlap is avoided.
|
|
54
246
|
// `cache_size` is negated → KiB (here 32 MiB) so SQLite's page cache can't
|
|
55
247
|
// grow unbounded and starve a wasm-heavy renderer.
|
|
56
248
|
try {
|
|
@@ -58,7 +250,17 @@ async function open(
|
|
|
58
250
|
} catch {
|
|
59
251
|
/* pragma best-effort */
|
|
60
252
|
}
|
|
61
|
-
return { persisted, opfsError };
|
|
253
|
+
return { persisted: result.persisted, opfsError: result.opfsError };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function closeDb(): void {
|
|
257
|
+
db?.close();
|
|
258
|
+
db = null;
|
|
259
|
+
pool = null;
|
|
260
|
+
selectDb.knownTables.clear();
|
|
261
|
+
// The lock is scoped to (bucket, leadership); a same-worker bucket switch
|
|
262
|
+
// closes then reopens under a NEW name, so the old one must go now.
|
|
263
|
+
releaseHeldLock();
|
|
62
264
|
}
|
|
63
265
|
|
|
64
266
|
function exec(sql: string, bind?: unknown[]): unknown[] {
|
|
@@ -90,63 +292,146 @@ function batch(stmts: Stmt[]): void {
|
|
|
90
292
|
// ==================== worker-side plan execution ('select') ====================
|
|
91
293
|
|
|
92
294
|
/** DB handle for `executeSelect` (see `sqlite-select.ts`, the unit-testable
|
|
93
|
-
* plan executor). `knownTables` is cleared on open/close
|
|
94
|
-
*
|
|
295
|
+
* plan executor). `knownTables` is cleared on open/close, which covers both
|
|
296
|
+
* the solo fresh-worker path and the shared-mode same-worker bucket switch. */
|
|
95
297
|
const selectDb: SelectDb = {
|
|
96
298
|
exec: (sql, bind) => exec(sql, bind) as { data: string }[],
|
|
97
299
|
run,
|
|
98
300
|
knownTables: new Set<string>(),
|
|
99
301
|
};
|
|
100
302
|
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
303
|
+
// ==================== dispatch ====================
|
|
304
|
+
|
|
305
|
+
/** Follower client ports, keyed by the clientId the owner assigned. */
|
|
306
|
+
const clients = new Map<string, MessagePort>();
|
|
307
|
+
|
|
308
|
+
/** Data ops a follower client port may issue; lifecycle stays owner-only. */
|
|
309
|
+
const CLIENT_OPS = new Set(['exec', 'run', 'batch', 'select']);
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* ONE chain for every op from every channel. The handlers for `open` and
|
|
313
|
+
* `select` are async; without this, a follower's select could interleave with
|
|
314
|
+
* the owner's batch mid-transaction at the VFS layer. (Solo mode kept this
|
|
315
|
+
* invariant on the main thread via the engine's opQueue; with multiple client
|
|
316
|
+
* ports only the worker can.)
|
|
317
|
+
*/
|
|
318
|
+
let opChain: Promise<void> = Promise.resolve();
|
|
319
|
+
|
|
320
|
+
async function handle(type: string, payload: any, source: 'owner' | 'client'): Promise<unknown> {
|
|
321
|
+
if (fenced) throw new Error('sqlite: fenced, leadership was taken over');
|
|
322
|
+
if (source === 'client' && !CLIENT_OPS.has(type)) {
|
|
323
|
+
throw new Error(`sqlite worker: op ${type} is not allowed on a client port`);
|
|
324
|
+
}
|
|
325
|
+
switch (type) {
|
|
326
|
+
case 'open':
|
|
327
|
+
selectDb.knownTables.clear();
|
|
328
|
+
{
|
|
329
|
+
const result = await open(
|
|
330
|
+
payload.dbName,
|
|
331
|
+
payload.useOpfs,
|
|
332
|
+
payload.systemTables,
|
|
333
|
+
payload.workerLockName,
|
|
334
|
+
payload.openOptions
|
|
335
|
+
);
|
|
112
336
|
// The freshly seeded system tables exist — record them so the select
|
|
113
337
|
// path doesn't redundantly re-issue CREATE TABLE for each.
|
|
114
338
|
for (const t of (payload.systemTables ?? []) as string[]) selectDb.knownTables.add(t);
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
339
|
+
return result;
|
|
340
|
+
}
|
|
341
|
+
case 'relock': {
|
|
342
|
+
// Same-leader re-promotion after a broker restart: the DB stays open,
|
|
343
|
+
// only the per-leadership lock name rolls forward. Acquire the new lock
|
|
344
|
+
// BEFORE releasing the old one so there is no unfenced window.
|
|
345
|
+
const handle = await acquireWorkerLock(payload.workerLockName);
|
|
346
|
+
if (!handle) throw new Error('worker-lock-unavailable');
|
|
347
|
+
releaseHeldLock();
|
|
348
|
+
currentLock = handle;
|
|
349
|
+
return {};
|
|
350
|
+
}
|
|
351
|
+
case 'select':
|
|
352
|
+
return executeSelect(payload.plan, payload.params ?? {}, selectDb);
|
|
353
|
+
case 'exec':
|
|
354
|
+
return { rows: exec(payload.sql, payload.bind) };
|
|
355
|
+
case 'run':
|
|
356
|
+
run(payload.sql, payload.bind);
|
|
357
|
+
return {};
|
|
358
|
+
case 'batch':
|
|
359
|
+
batch(payload as Stmt[]);
|
|
360
|
+
return {};
|
|
361
|
+
case 'close':
|
|
362
|
+
closeDb();
|
|
363
|
+
return {};
|
|
364
|
+
case 'shutdown':
|
|
365
|
+
// Graceful pagehide path: pausing the VFS releases the sync access
|
|
366
|
+
// handles NOW instead of whenever this worker gets garbage collected,
|
|
367
|
+
// so the next leader's open does not race the browser's GC.
|
|
368
|
+
try {
|
|
131
369
|
db?.close();
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
370
|
+
} catch {
|
|
371
|
+
/* ignore */
|
|
372
|
+
}
|
|
373
|
+
db = null;
|
|
374
|
+
try {
|
|
375
|
+
pool?.pauseVfs?.();
|
|
376
|
+
} catch {
|
|
377
|
+
/* ignore */
|
|
378
|
+
}
|
|
379
|
+
pool = null;
|
|
380
|
+
releaseHeldLock();
|
|
381
|
+
queueMicrotask(() => self.close());
|
|
382
|
+
return {};
|
|
383
|
+
case 'remove-client': {
|
|
384
|
+
const port = clients.get(payload.clientId);
|
|
385
|
+
port?.close();
|
|
386
|
+
clients.delete(payload.clientId);
|
|
387
|
+
return {};
|
|
138
388
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
389
|
+
default:
|
|
390
|
+
throw new Error(`sqlite worker: unknown message ${type}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function dispatch(target: PostTarget, data: any, source: 'owner' | 'client'): void {
|
|
395
|
+
const { id, type, payload } = data ?? {};
|
|
396
|
+
noteTick();
|
|
397
|
+
const t0 = performance.now();
|
|
398
|
+
const runOp = async () => {
|
|
399
|
+
try {
|
|
400
|
+
if (thawVerification) await thawVerification;
|
|
401
|
+
const result = await handle(type, payload, source);
|
|
402
|
+
// `wt` (worker time) lets the main thread split a round-trip into actual
|
|
403
|
+
// DB work vs postMessage/queue overhead (see `__sqliteStats`).
|
|
404
|
+
target.postMessage({ id, ok: true, wt: performance.now() - t0, ...(result as object) });
|
|
405
|
+
} catch (err) {
|
|
406
|
+
target.postMessage({ id, ok: false, error: err instanceof Error ? err.message : String(err) });
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
opChain = opChain.then(runOp, runOp);
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
self.onmessage = (ev: MessageEvent) => {
|
|
413
|
+
const data = ev.data ?? {};
|
|
414
|
+
// `add-client` is handled inline (not on the op chain): it only registers a
|
|
415
|
+
// port and must not wait behind a long select, or the follower's first ops
|
|
416
|
+
// (already queued on that port by the time the ack arrives) would deadlock
|
|
417
|
+
// the attach handshake in the engine.
|
|
418
|
+
if (data.type === 'add-client') {
|
|
419
|
+
const port = ev.ports?.[0];
|
|
420
|
+
const clientId = data.payload?.clientId as string | undefined;
|
|
421
|
+
if (!port || !clientId) {
|
|
422
|
+
(self as unknown as Worker).postMessage({
|
|
423
|
+
id: data.id,
|
|
424
|
+
ok: false,
|
|
425
|
+
error: 'sqlite worker: add-client needs a clientId and a transferred port',
|
|
426
|
+
});
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
clients.get(clientId)?.close();
|
|
430
|
+
clients.set(clientId, port);
|
|
431
|
+
port.onmessage = (pe: MessageEvent) => dispatch(port, pe.data, 'client');
|
|
432
|
+
port.start?.();
|
|
433
|
+
(self as unknown as Worker).postMessage({ id: data.id, ok: true, wt: 0 });
|
|
434
|
+
return;
|
|
151
435
|
}
|
|
436
|
+
dispatch(self as unknown as Worker, data, 'owner');
|
|
152
437
|
};
|
|
@@ -31,6 +31,8 @@ export class SurrealCacheEngine extends LocalDatabaseService implements LocalCac
|
|
|
31
31
|
/** SurrealDB needs its SurrealQL schema provisioned locally. */
|
|
32
32
|
readonly usesSurqlSchema = true;
|
|
33
33
|
|
|
34
|
+
readonly engineKind = 'surrealdb' as const;
|
|
35
|
+
|
|
34
36
|
/** {@link LocalCacheEngine} alias for {@link LocalDatabaseService.switchStore}. */
|
|
35
37
|
switchBucket(bucketId: string): Promise<void> {
|
|
36
38
|
return this.switchStore(bucketId);
|
|
@@ -85,6 +85,10 @@ export class StreamProcessorService {
|
|
|
85
85
|
// switch — the fire-and-forget calls in `ingest`/`flushCoalescing` can land
|
|
86
86
|
// late.
|
|
87
87
|
private stateGeneration = 0;
|
|
88
|
+
// Shared-tabs: follower circuits are in-memory ONLY. Persisting them would
|
|
89
|
+
// stomp the leader's snapshot under the same key (the pre-existing cross-tab
|
|
90
|
+
// localStorage hazard); a promoted follower flips this back on.
|
|
91
|
+
private persistState = true;
|
|
88
92
|
|
|
89
93
|
constructor(
|
|
90
94
|
public events: EventSystem<StreamProcessorEvents>,
|
|
@@ -268,8 +272,13 @@ export class StreamProcessorService {
|
|
|
268
272
|
);
|
|
269
273
|
}
|
|
270
274
|
|
|
275
|
+
/** Toggle circuit-state persistence (shared-tabs follower/leader role). */
|
|
276
|
+
setPersistenceEnabled(enabled: boolean): void {
|
|
277
|
+
this.persistState = enabled;
|
|
278
|
+
}
|
|
279
|
+
|
|
271
280
|
async loadState() {
|
|
272
|
-
if (!this.processor) return;
|
|
281
|
+
if (!this.processor || !this.persistState) return;
|
|
273
282
|
try {
|
|
274
283
|
const result = await this.persistenceClient.get(this.stateKey());
|
|
275
284
|
|
|
@@ -360,7 +369,7 @@ export class StreamProcessorService {
|
|
|
360
369
|
}
|
|
361
370
|
|
|
362
371
|
async saveState() {
|
|
363
|
-
if (!this.processor) return;
|
|
372
|
+
if (!this.processor || !this.persistState) return;
|
|
364
373
|
const generation = this.stateGeneration;
|
|
365
374
|
try {
|
|
366
375
|
// Assuming processor has a save_state method that returns the state string/bytes
|