@spooky-sync/core 1.0.0-beta.1 → 1.0.0-beta.10
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/AGENTS.md +4 -3
- package/dist/index.d.ts +169 -9
- package/dist/index.js +4512 -2338
- package/dist/rows-worker.d.ts +1 -0
- package/dist/rows-worker.js +2639 -0
- package/dist/sqlite-open.js +1 -1
- package/dist/sqlite-worker.js +1 -1
- package/dist/types.d.ts +129 -13
- package/package.json +9 -4
- package/scripts/check-worker-entries.mjs +15 -2
- package/skills/sp00ky-core/SKILL.md +2 -0
- package/src/client/bucket-handle.ts +21 -1
- package/src/client/eager-paint.test.ts +82 -0
- package/src/client/services.ts +4 -1
- package/src/client/sp00ky-client.test.ts +143 -1
- package/src/client/sp00ky-client.ts +157 -19
- package/src/index.ts +9 -0
- package/src/kernel/effects.ts +12 -2
- package/src/kernel/interpreter.test.ts +17 -0
- package/src/kernel/interpreter.ts +5 -2
- package/src/modules/channel/hub.test.ts +223 -0
- package/src/modules/channel/hub.ts +355 -0
- package/src/modules/channel/index.ts +358 -14
- package/src/modules/channel/room.test.ts +340 -0
- package/src/modules/channel/room.ts +367 -0
- package/src/modules/channel/rooms.fixture.ts +383 -0
- package/src/modules/channel/share.test.ts +535 -0
- package/src/modules/channel/webrtc.ts +2 -2
- package/src/modules/devtools/storage-info.ts +4 -3
- package/src/query/materialize.saga.test.ts +16 -0
- package/src/query/materialize.saga.ts +7 -26
- package/src/query/materialize.ts +79 -3
- package/src/query/register.saga.test.ts +61 -0
- package/src/query/register.saga.ts +39 -2
- package/src/services/database/cache-engine.ts +17 -3
- package/src/services/database/engine-factory.ts +7 -0
- package/src/services/database/index.ts +1 -0
- package/src/services/database/rows-cache-engine.test.ts +1014 -0
- package/src/services/database/rows-cache-engine.ts +921 -0
- package/src/services/database/rows-exec.integration.test.ts +589 -0
- package/src/services/database/rows-exec.ts +1027 -0
- package/src/services/database/rows-prewarm.ts +225 -0
- package/src/services/database/rows-store.test.ts +635 -0
- package/src/services/database/rows-store.ts +1208 -0
- package/src/services/database/rows-transport.fixture.ts +151 -0
- package/src/services/database/rows-worker.ts +588 -0
- package/src/services/database/sqlite-cache-engine.test.ts +22 -1
- package/src/services/database/sqlite-cache-engine.ts +55 -34
- package/src/services/database/sqlite-transport.ts +7 -5
- package/src/services/tabs/support.ts +6 -4
- package/src/types.ts +39 -6
- package/tsdown.config.ts +42 -1
- package/vitest.config.ts +4 -0
|
@@ -0,0 +1,921 @@
|
|
|
1
|
+
import type { QueryPlan, WhereNode } from '@spooky-sync/query-builder';
|
|
2
|
+
import type { EngineStorageDiagnostics } from '../../modules/devtools/storage-info';
|
|
3
|
+
import type { StorageHealth } from '../../types';
|
|
4
|
+
import type { Id, OrderBy, RelationFetch, Row, SnapshotMeta, StoredSnapshot } from './cache-engine';
|
|
5
|
+
import { stableKey } from './relation-resolver';
|
|
6
|
+
import { fromBase64, serializeMergeRow, serializeRow } from './sqlite-plan-sql';
|
|
7
|
+
import { COLUMNS_ROW_ID, planColumnReset } from './sqlite-column-reset';
|
|
8
|
+
import {
|
|
9
|
+
SNAPSHOT_TABLE,
|
|
10
|
+
SqliteCacheEngine,
|
|
11
|
+
normalizePlanForClone,
|
|
12
|
+
normalizeWhereForClone,
|
|
13
|
+
toCloneSafe,
|
|
14
|
+
} from './sqlite-cache-engine';
|
|
15
|
+
import { WorkerSqliteTransport, type SqliteTransport } from './sqlite-transport';
|
|
16
|
+
import { tableOf, type SqlOp } from './surql-translate';
|
|
17
|
+
import { ROWS_PROTOCOL, ROWS_READER_OPS, parseRowBytes, type WireOp } from './rows-exec';
|
|
18
|
+
import { FLAG_RAW, FLAG_U8, bucketDirName, type StoreStats } from './rows-store';
|
|
19
|
+
import {
|
|
20
|
+
ROWS_AHEAD_OPS,
|
|
21
|
+
ROWS_PREWARM_KEY,
|
|
22
|
+
ReadAhead,
|
|
23
|
+
aheadKey,
|
|
24
|
+
jsonSafe,
|
|
25
|
+
takePrewarmed,
|
|
26
|
+
type PrewarmRecord,
|
|
27
|
+
} from './rows-prewarm';
|
|
28
|
+
|
|
29
|
+
export { ROWS_PREWARM_KEY, ROWS_PREWARM_SNIPPET, prewarmRows } from './rows-prewarm';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Tables whose rows exist nowhere else: writes the user made that the server
|
|
33
|
+
* has not confirmed. A batch that touches one is flushed to disk before the
|
|
34
|
+
* write resolves. Everything else is a copy of server state and is flushed a
|
|
35
|
+
* moment later, in the worker's own time: losing it to a power cut costs a
|
|
36
|
+
* refetch, not a user's work.
|
|
37
|
+
*/
|
|
38
|
+
export const ROWS_DURABLE_TABLES: ReadonlySet<string> = new Set([
|
|
39
|
+
'_00_pending_mutations',
|
|
40
|
+
'_00_pending_writes',
|
|
41
|
+
'_00_failed_mutations',
|
|
42
|
+
'_00_crdt_local',
|
|
43
|
+
]);
|
|
44
|
+
|
|
45
|
+
const SCHEMA_TABLE = '_00_schema';
|
|
46
|
+
|
|
47
|
+
/** How long after connecting a read counts as one the app makes at startup. */
|
|
48
|
+
const PAINT_CAPTURE_MS = 3000;
|
|
49
|
+
|
|
50
|
+
// What the next page load asks the worker ahead of the app (see `rows-prewarm.ts`).
|
|
51
|
+
// Bounded: the answers wait in the page's memory until the app asks or writes.
|
|
52
|
+
const AHEAD_MAX_READS = 24;
|
|
53
|
+
const AHEAD_MAX_REPLY_BYTES = 512 << 10;
|
|
54
|
+
const AHEAD_MAX_TOTAL_BYTES = 2 << 20;
|
|
55
|
+
const AHEAD_MAX_REQUEST_CHARS = 32_000;
|
|
56
|
+
/** How long a read waits for an answer that was asked ahead before asking again itself. */
|
|
57
|
+
const AHEAD_WAIT_MS = 250;
|
|
58
|
+
/** How long a follower's own reader may take over one read before the leader is asked instead. */
|
|
59
|
+
const READER_OP_TIMEOUT_MS = 2000;
|
|
60
|
+
|
|
61
|
+
/** A timer nothing should wait for (a Node process, a test run). */
|
|
62
|
+
function background<T>(timer: T): T {
|
|
63
|
+
(timer as { unref?: () => void }).unref?.();
|
|
64
|
+
return timer;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Worker ops that leave the store as it was: none of them makes an answer read ahead stale. */
|
|
68
|
+
const ROWS_READ_OPS: ReadonlySet<string> = new Set([
|
|
69
|
+
'select',
|
|
70
|
+
'by-ids',
|
|
71
|
+
'get',
|
|
72
|
+
'relation',
|
|
73
|
+
'select-table',
|
|
74
|
+
'count',
|
|
75
|
+
'versions',
|
|
76
|
+
'tables',
|
|
77
|
+
'blob-get',
|
|
78
|
+
'diag',
|
|
79
|
+
'warm',
|
|
80
|
+
]);
|
|
81
|
+
const PAINT_MAX_KEYS = 64;
|
|
82
|
+
const PAINT_MAX_ENTRY_CHARS = 256_000;
|
|
83
|
+
const PAINT_FLUSH_MS = 1500;
|
|
84
|
+
|
|
85
|
+
interface PaintEntry {
|
|
86
|
+
tables: string[];
|
|
87
|
+
/** `0` or `1` (bytes to revive), then the rows as JSON text. */
|
|
88
|
+
text: string;
|
|
89
|
+
dirty: boolean;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function hashKey(text: string): string {
|
|
93
|
+
let a = 0x811c9dc5;
|
|
94
|
+
let b = 0x01000193;
|
|
95
|
+
for (let i = 0; i < text.length; i++) {
|
|
96
|
+
const c = text.charCodeAt(i);
|
|
97
|
+
a = Math.imul(a ^ c, 0x01000193);
|
|
98
|
+
b = Math.imul(b + c, 0x85ebca6b) ^ (b >>> 13);
|
|
99
|
+
}
|
|
100
|
+
return (a >>> 0).toString(36) + (b >>> 0).toString(36);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The rows the app read at startup last time, kept in localStorage: the one
|
|
105
|
+
* place a page can read synchronously, before a worker exists or a file is
|
|
106
|
+
* open. {@link RowsCacheEngine.peekByIds} and `peekSelect` answer from it in
|
|
107
|
+
* a fraction of a millisecond, so a screen can paint what it showed before
|
|
108
|
+
* while the store opens.
|
|
109
|
+
*
|
|
110
|
+
* What it holds is a copy, and the contract says so: a peek is something to
|
|
111
|
+
* paint from, the read that follows is the answer. The copy is dropped the
|
|
112
|
+
* moment this tab writes to a table it came from, and written again from the
|
|
113
|
+
* next read of the same thing, so in practice the two agree; when they do not
|
|
114
|
+
* (another tab wrote, the browser died before the drop reached the disk) the
|
|
115
|
+
* read that follows corrects the screen a few milliseconds later.
|
|
116
|
+
*/
|
|
117
|
+
export class PaintCache {
|
|
118
|
+
private entries = new Map<string, PaintEntry>();
|
|
119
|
+
/** Reads this session made at startup: the ones worth keeping a copy of, whenever they run again. */
|
|
120
|
+
private known = new Set<string>();
|
|
121
|
+
/** table -> keys, for the entries of earlier sessions too. */
|
|
122
|
+
private byTable: Map<string, Set<string>> | null = null;
|
|
123
|
+
/** table -> writes this tab made to it, to tell a read sent before a write from one sent after. */
|
|
124
|
+
private writes = new Map<string, number>();
|
|
125
|
+
private timer: ReturnType<typeof setTimeout> | null = null;
|
|
126
|
+
private bucket = '';
|
|
127
|
+
private since = 0;
|
|
128
|
+
|
|
129
|
+
constructor(private maxChars: number) {
|
|
130
|
+
if (typeof addEventListener === 'function') {
|
|
131
|
+
// localStorage is synchronous, so the last state can still be saved as the page goes.
|
|
132
|
+
addEventListener('pagehide', () => this.flush());
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** The bucket about to be opened: peeks answer from it until `start` says which one it is. */
|
|
137
|
+
expect(bucket: string): void {
|
|
138
|
+
if (!this.bucket) this.bucket = bucket;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** A new session on `bucket`: reads from now on are startup reads for a while. */
|
|
142
|
+
start(bucket: string): void {
|
|
143
|
+
if (bucket !== this.bucket) {
|
|
144
|
+
this.flush();
|
|
145
|
+
this.entries.clear();
|
|
146
|
+
this.known.clear();
|
|
147
|
+
this.byTable = null;
|
|
148
|
+
}
|
|
149
|
+
this.bucket = bucket;
|
|
150
|
+
this.since = Date.now();
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
private name(key: string): string {
|
|
154
|
+
return `sp00ky.paint.${this.bucket}.${key}`;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private index(): Map<string, Set<string>> {
|
|
158
|
+
if (this.byTable) return this.byTable;
|
|
159
|
+
this.byTable = new Map();
|
|
160
|
+
try {
|
|
161
|
+
const saved = JSON.parse(localStorage.getItem(`sp00ky.paint.${this.bucket}`) ?? '{}') as Record<string, string[]>;
|
|
162
|
+
for (const [key, tables] of Object.entries(saved)) this.link(key, tables);
|
|
163
|
+
} catch {
|
|
164
|
+
/* an unreadable index only means nothing gets dropped that is not there */
|
|
165
|
+
}
|
|
166
|
+
return this.byTable;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
private link(key: string, tables: string[]): void {
|
|
170
|
+
const index = this.byTable!;
|
|
171
|
+
for (const table of tables) {
|
|
172
|
+
let keys = index.get(table);
|
|
173
|
+
if (!keys) index.set(table, (keys = new Set()));
|
|
174
|
+
keys.add(key);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
get(key: string, revive: (b64: string) => Uint8Array): Row[] | null {
|
|
179
|
+
if (!this.bucket) return null;
|
|
180
|
+
try {
|
|
181
|
+
const text = this.entries.get(key)?.text ?? localStorage.getItem(this.name(key));
|
|
182
|
+
if (!text) return null;
|
|
183
|
+
if (text[0] === '0') return JSON.parse(text.slice(1)) as Row[];
|
|
184
|
+
return JSON.parse(text.slice(1), (_k, v) =>
|
|
185
|
+
v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
|
|
186
|
+
) as Row[];
|
|
187
|
+
} catch {
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** How many writes `tables` have seen: taken when a read is sent, checked when it answers. */
|
|
193
|
+
stamp(tables: string[]): number {
|
|
194
|
+
let n = 0;
|
|
195
|
+
for (const table of tables) n += this.writes.get(table) ?? 0;
|
|
196
|
+
return n;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* A read just answered: keep its text if it is a startup read, or one kept
|
|
201
|
+
* before. `sentAt` is {@link stamp} from when it was sent; a write to its
|
|
202
|
+
* tables since then means the answer may already be old, and it is let go.
|
|
203
|
+
*/
|
|
204
|
+
note(key: string, tables: string[], rows: string, u8: boolean, sentAt: number): void {
|
|
205
|
+
if (!this.bucket || sentAt !== this.stamp(tables)) return;
|
|
206
|
+
if (!this.known.has(key)) {
|
|
207
|
+
if (Date.now() - this.since > PAINT_CAPTURE_MS || this.known.size >= PAINT_MAX_KEYS) return;
|
|
208
|
+
this.known.add(key);
|
|
209
|
+
}
|
|
210
|
+
if (rows.length > PAINT_MAX_ENTRY_CHARS) return;
|
|
211
|
+
this.entries.set(key, { tables, text: (u8 ? '1' : '0') + rows, dirty: true });
|
|
212
|
+
this.timer ??= setTimeout(() => this.flush(), PAINT_FLUSH_MS);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** This tab is about to write to `tables`: what was read from them is no longer what they hold. */
|
|
216
|
+
touch(tables: Iterable<string>): void {
|
|
217
|
+
if (!this.bucket) return;
|
|
218
|
+
const index = this.index();
|
|
219
|
+
for (const table of tables) {
|
|
220
|
+
this.writes.set(table, (this.writes.get(table) ?? 0) + 1);
|
|
221
|
+
const keys = index.get(table);
|
|
222
|
+
if (!keys || keys.size === 0) continue;
|
|
223
|
+
for (const key of keys) {
|
|
224
|
+
this.entries.delete(key);
|
|
225
|
+
try {
|
|
226
|
+
localStorage.removeItem(this.name(key));
|
|
227
|
+
} catch {
|
|
228
|
+
/* ignore */
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
keys.clear();
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Write what changed, newest reads first, up to the budget. */
|
|
236
|
+
flush(): void {
|
|
237
|
+
if (this.timer) clearTimeout(this.timer);
|
|
238
|
+
this.timer = null;
|
|
239
|
+
if (!this.bucket) return;
|
|
240
|
+
const index = this.index();
|
|
241
|
+
try {
|
|
242
|
+
let used = 0;
|
|
243
|
+
const kept: Record<string, string[]> = {};
|
|
244
|
+
for (const [key, entry] of [...this.entries].reverse()) {
|
|
245
|
+
if (used + entry.text.length > this.maxChars) {
|
|
246
|
+
this.entries.delete(key);
|
|
247
|
+
localStorage.removeItem(this.name(key));
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
used += entry.text.length;
|
|
251
|
+
kept[key] = entry.tables;
|
|
252
|
+
if (entry.dirty) {
|
|
253
|
+
localStorage.setItem(this.name(key), entry.text);
|
|
254
|
+
entry.dirty = false;
|
|
255
|
+
this.link(key, entry.tables);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
// Entries of earlier sessions that this one never read again stay until a write drops them.
|
|
259
|
+
for (const [table, keys] of index) {
|
|
260
|
+
for (const key of keys) {
|
|
261
|
+
const tables = (kept[key] ??= []);
|
|
262
|
+
if (!tables.includes(table)) tables.push(table);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
localStorage.setItem(`sp00ky.paint.${this.bucket}`, JSON.stringify(kept));
|
|
266
|
+
} catch {
|
|
267
|
+
// Out of quota, or no storage: painting from the cache is a bonus, not a need.
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** Forget everything kept for `bucket`. */
|
|
272
|
+
static drop(bucket: string): void {
|
|
273
|
+
try {
|
|
274
|
+
const prefix = `sp00ky.paint.${bucket}`;
|
|
275
|
+
const mine: string[] = [];
|
|
276
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
277
|
+
const key = localStorage.key(i);
|
|
278
|
+
if (key !== null && (key === prefix || key.startsWith(prefix + '.'))) mine.push(key);
|
|
279
|
+
}
|
|
280
|
+
for (const key of mine) localStorage.removeItem(key);
|
|
281
|
+
} catch {
|
|
282
|
+
/* ignore */
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Every table a plan reads: its own and its relations'. */
|
|
288
|
+
function tablesOf(plan: QueryPlan): string[] {
|
|
289
|
+
const out = new Set<string>([plan.table]);
|
|
290
|
+
const walk = (relations: QueryPlan['relations']): void => {
|
|
291
|
+
for (const relation of relations ?? []) {
|
|
292
|
+
out.add(relation.table);
|
|
293
|
+
walk(relation.relations);
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
walk(plan.relations);
|
|
297
|
+
return [...out];
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const encoder = new TextEncoder();
|
|
301
|
+
const decoder = new TextDecoder();
|
|
302
|
+
|
|
303
|
+
type RowsReply = { buf: ArrayBuffer | null; u8?: boolean };
|
|
304
|
+
|
|
305
|
+
const byIdsKey = (table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): string =>
|
|
306
|
+
hashKey('i' + JSON.stringify([table, ids.map(stableKey), opts?.select ?? null, opts?.orderBy ?? null]));
|
|
307
|
+
|
|
308
|
+
function parseRowText(text: string, u8: boolean): Row[] {
|
|
309
|
+
if (!u8) return JSON.parse(text) as Row[];
|
|
310
|
+
return JSON.parse(text, (_k, v) =>
|
|
311
|
+
v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? fromBase64((v as { __u8: string }).__u8) : v
|
|
312
|
+
) as Row[];
|
|
313
|
+
}
|
|
314
|
+
type OpenReply = { persisted: boolean; opfsError?: string; proto?: number; workerUrl?: string };
|
|
315
|
+
|
|
316
|
+
/** One write, with the table and key already resolved. */
|
|
317
|
+
export type WriteItem =
|
|
318
|
+
| { kind: 'upsert'; table: string; key: string; data: Row; mode: 'replace' | 'merge' }
|
|
319
|
+
| { kind: 'delete'; table: string; key: string }
|
|
320
|
+
| { kind: 'clear'; table: string };
|
|
321
|
+
|
|
322
|
+
/** The writes of a translated statement list; the table is the id's own. */
|
|
323
|
+
function itemsOf(ops: SqlOp[]): WriteItem[] {
|
|
324
|
+
const items: WriteItem[] = [];
|
|
325
|
+
for (const op of ops) {
|
|
326
|
+
if (op.kind === 'noop') continue;
|
|
327
|
+
if (op.kind === 'deleteAll') items.push({ kind: 'clear', table: op.table });
|
|
328
|
+
else if (op.kind === 'delete') items.push({ kind: 'delete', table: tableOf(op.id), key: stableKey(op.id) });
|
|
329
|
+
else if (op.kind === 'upsert') {
|
|
330
|
+
items.push({ kind: 'upsert', table: tableOf(op.id), key: stableKey(op.id), data: op.data, mode: op.mode });
|
|
331
|
+
} else throw new Error(`RowsCacheEngine: ${op.kind} is not a write`);
|
|
332
|
+
}
|
|
333
|
+
return items;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/**
|
|
337
|
+
* Serialize a batch of writes for the worker: every row's JSON text in one
|
|
338
|
+
* buffer, which is transferred, and one small tuple per op saying where its
|
|
339
|
+
* text lies. The text is what `SqliteCacheEngine` stores, byte for byte.
|
|
340
|
+
*/
|
|
341
|
+
export function packWrites(items: WriteItem[]): { wire: WireOp[]; buf: ArrayBuffer | null; sync: boolean } {
|
|
342
|
+
const wire: WireOp[] = [];
|
|
343
|
+
let bytes = new Uint8Array(0);
|
|
344
|
+
let at = 0;
|
|
345
|
+
let sync = false;
|
|
346
|
+
const append = (text: string): [off: number, len: number] => {
|
|
347
|
+
// `encodeInto` needs room for the worst case, three bytes per UTF-16 unit.
|
|
348
|
+
const need = at + text.length * 3;
|
|
349
|
+
if (bytes.length < need) {
|
|
350
|
+
const grown = new Uint8Array(Math.max(need, bytes.length * 2, 1024));
|
|
351
|
+
grown.set(bytes.subarray(0, at));
|
|
352
|
+
bytes = grown;
|
|
353
|
+
}
|
|
354
|
+
const written = encoder.encodeInto(text, bytes.subarray(at)).written;
|
|
355
|
+
const off = at;
|
|
356
|
+
at += written;
|
|
357
|
+
return [off, written];
|
|
358
|
+
};
|
|
359
|
+
for (const op of items) {
|
|
360
|
+
const table = op.table;
|
|
361
|
+
if (ROWS_DURABLE_TABLES.has(table)) sync = true;
|
|
362
|
+
if (op.kind === 'clear') {
|
|
363
|
+
wire.push(['clear', table]);
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
const key = op.key;
|
|
367
|
+
if (op.kind === 'delete') {
|
|
368
|
+
wire.push(['del', table, key]);
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
const row: Row = { ...op.data, id: key };
|
|
372
|
+
const rv = Number(row._00_rv) || 0;
|
|
373
|
+
if (op.mode === 'replace') {
|
|
374
|
+
const text = serializeRow(row);
|
|
375
|
+
const [off, len] = append(text);
|
|
376
|
+
wire.push(['put', table, key, rv, text.includes('"__u8"') ? FLAG_U8 : 0, off, len]);
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
const { insert, patch } = serializeMergeRow(row);
|
|
380
|
+
const [off, len] = append(insert);
|
|
381
|
+
// The patch differs from the row only when a field is being cleared.
|
|
382
|
+
const [patchOff, patchLen] = patch === insert ? [0, 0] : append(patch);
|
|
383
|
+
wire.push(['merge', table, key, rv, insert.includes('"__u8"') ? FLAG_U8 : 0, off, len, patchOff, patchLen]);
|
|
384
|
+
}
|
|
385
|
+
return { wire, buf: at > 0 ? (bytes.buffer as ArrayBuffer) : null, sync };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/**
|
|
389
|
+
* Local cache backend on sp00ky's own row store (`rows-store.ts`), in a
|
|
390
|
+
* dedicated Worker (`rows-worker.ts`) on OPFS.
|
|
391
|
+
*
|
|
392
|
+
* It answers every verb the way {@link SqliteCacheEngine} does (same stored
|
|
393
|
+
* JSON, same filter and ordering rules, checked against real SQLite in
|
|
394
|
+
* `rows-exec.integration.test.ts`), so an app can switch between the two with
|
|
395
|
+
* `localEngine` alone. What differs is underneath: no SQL is rendered, rows
|
|
396
|
+
* cross the worker boundary as JSON text in a transferred buffer and are
|
|
397
|
+
* parsed once, on the side that reads them.
|
|
398
|
+
*
|
|
399
|
+
* It extends the SQLite engine for everything that is about the worker rather
|
|
400
|
+
* than about SQL: the serialized op queue, epoch fencing, bucket switches, the
|
|
401
|
+
* shared-tabs roles, the SurrealQL-vocabulary shim. Every method that renders
|
|
402
|
+
* SQL there is replaced here by a message to the row worker.
|
|
403
|
+
*/
|
|
404
|
+
export class RowsCacheEngine extends SqliteCacheEngine {
|
|
405
|
+
override readonly engineKind = 'rows' as const;
|
|
406
|
+
/** The transport in use wraps a worker `prewarmRows` started. */
|
|
407
|
+
private adopted = false;
|
|
408
|
+
/** Last-seen startup reads, for {@link peekByIds} / {@link peekSelect}. Off for a memory store. */
|
|
409
|
+
private paint: PaintCache | null =
|
|
410
|
+
this.useOpfs && this.config.paintCache !== false && typeof localStorage !== 'undefined' ? new PaintCache(1_000_000) : null;
|
|
411
|
+
|
|
412
|
+
protected override createTransport(): SqliteTransport {
|
|
413
|
+
const pre = takePrewarmed();
|
|
414
|
+
if (pre?.failed) pre.worker.terminate();
|
|
415
|
+
this.adopted = pre !== null && !pre.failed;
|
|
416
|
+
const transport = new WorkerSqliteTransport(
|
|
417
|
+
this.logger,
|
|
418
|
+
this.adopted
|
|
419
|
+
? () => pre!.worker
|
|
420
|
+
: // Same shape as the SQLite worker's URL: `.ts` for bundlers that build
|
|
421
|
+
// from source, rewritten to `./rows-worker.js` in the published build.
|
|
422
|
+
(this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' })))
|
|
423
|
+
);
|
|
424
|
+
// What the worker was asked ahead of the app, for as long as it holds true.
|
|
425
|
+
let ahead = this.adopted ? new ReadAhead(pre!, AHEAD_WAIT_MS) : null;
|
|
426
|
+
const forget = (): void => {
|
|
427
|
+
ahead?.drop();
|
|
428
|
+
ahead = null;
|
|
429
|
+
};
|
|
430
|
+
if (ahead) background(setTimeout(forget, PAINT_CAPTURE_MS));
|
|
431
|
+
let opens = 0;
|
|
432
|
+
// Every open is checked: a worker from another release must not be talked to.
|
|
433
|
+
const call = transport.call.bind(transport);
|
|
434
|
+
transport.call = async <T>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> => {
|
|
435
|
+
if (type === 'open') {
|
|
436
|
+
// The prewarm's work stands only for the first open, of the store it
|
|
437
|
+
// was started on, with nothing more asked of the worker (under a
|
|
438
|
+
// role's lock other tabs write through this worker too).
|
|
439
|
+
const asked = payload as { dbName: string; useOpfs: boolean; workerLockName?: string; share?: boolean };
|
|
440
|
+
// A leader whose followers read the file themselves opens it for sharing.
|
|
441
|
+
if (asked.workerLockName && asked.useOpfs && this.config.followerReads === 'direct') {
|
|
442
|
+
asked.share = true;
|
|
443
|
+
}
|
|
444
|
+
const mine = ahead !== null && opens++ === 0 && asked.useOpfs && asked.dbName === pre!.bucket && !asked.workerLockName;
|
|
445
|
+
const answered = pre?.opened as (OpenReply & { ok?: boolean }) | undefined;
|
|
446
|
+
if (pre) pre.opened = undefined;
|
|
447
|
+
if (!mine) forget();
|
|
448
|
+
else if (answered?.persisted) {
|
|
449
|
+
// The worker answered this very open already: no need to ask again.
|
|
450
|
+
this.opened(transport, asked, answered);
|
|
451
|
+
return answered as T;
|
|
452
|
+
}
|
|
453
|
+
} else if (ahead && ROWS_AHEAD_OPS.has(type)) {
|
|
454
|
+
const early = ahead.take(type, payload);
|
|
455
|
+
const got = early ? await early : null;
|
|
456
|
+
if (got) {
|
|
457
|
+
const { id: _id, ok: _ok, error: _error, ...rest } = got;
|
|
458
|
+
return rest as T;
|
|
459
|
+
}
|
|
460
|
+
} else if (!ROWS_READ_OPS.has(type)) forget();
|
|
461
|
+
const reply = await call<T>(type, payload, transfer);
|
|
462
|
+
if (type === 'open') this.opened(transport, payload as { dbName: string; useOpfs: boolean }, reply as OpenReply);
|
|
463
|
+
return reply;
|
|
464
|
+
};
|
|
465
|
+
return transport;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
private opened(transport: SqliteTransport, asked: { dbName: string; useOpfs: boolean }, reply: OpenReply): void {
|
|
469
|
+
if (reply.proto !== ROWS_PROTOCOL) {
|
|
470
|
+
transport.close('row worker speaks another protocol');
|
|
471
|
+
throw new Error(`RowsCacheEngine: worker protocol ${String(reply.proto)}, expected ${ROWS_PROTOCOL}`);
|
|
472
|
+
}
|
|
473
|
+
// Leave the next page load what it needs to start this worker ahead of the app.
|
|
474
|
+
try {
|
|
475
|
+
if (asked.useOpfs && reply.persisted && reply.workerUrl) {
|
|
476
|
+
const old = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
|
|
477
|
+
const record: PrewarmRecord = { url: reply.workerUrl, bucket: asked.dbName };
|
|
478
|
+
// The reads to ask ahead belong to a bucket: another user's are not kept.
|
|
479
|
+
if (old?.bucket === asked.dbName && Array.isArray(old.reads)) record.reads = old.reads;
|
|
480
|
+
localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify(record));
|
|
481
|
+
}
|
|
482
|
+
} catch {
|
|
483
|
+
// No localStorage (a worker, a locked-down page): nothing to prewarm from.
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* A prewarmed worker is a guess. When it turns out wrong (it failed to
|
|
489
|
+
* load, or it is another release's), drop it and connect again with a
|
|
490
|
+
* worker of our own.
|
|
491
|
+
*/
|
|
492
|
+
override async connect(bucketId: string): Promise<void> {
|
|
493
|
+
// Known before the worker answers, so a peek can be asked for right away.
|
|
494
|
+
this.bucketId = bucketId;
|
|
495
|
+
this.paint?.start(bucketId);
|
|
496
|
+
try {
|
|
497
|
+
await super.connect(bucketId);
|
|
498
|
+
this.beginStartupReads();
|
|
499
|
+
} catch (error) {
|
|
500
|
+
if (!this.adopted) throw error;
|
|
501
|
+
this.adopted = false;
|
|
502
|
+
try {
|
|
503
|
+
localStorage.removeItem(ROWS_PREWARM_KEY);
|
|
504
|
+
} catch {
|
|
505
|
+
/* ignore */
|
|
506
|
+
}
|
|
507
|
+
this.logger.warn(
|
|
508
|
+
{ error, Category: 'sp00ky-client::RowsCacheEngine::connect' },
|
|
509
|
+
'Prewarmed row worker was unusable; starting a fresh one'
|
|
510
|
+
);
|
|
511
|
+
await this.close();
|
|
512
|
+
await super.connect(bucketId);
|
|
513
|
+
this.beginStartupReads();
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
override async switchBucket(bucketId: string): Promise<void> {
|
|
518
|
+
this.dropReader('bucket switch');
|
|
519
|
+
await super.switchBucket(bucketId);
|
|
520
|
+
this.paint?.start(bucketId);
|
|
521
|
+
this.beginStartupReads();
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** A follower reads through the leader's worker; one started ahead for this tab is not needed. */
|
|
525
|
+
override async adoptAttached(
|
|
526
|
+
dbPort: MessagePort,
|
|
527
|
+
snapshot: { bucketId: string; storageHealth: StorageHealth },
|
|
528
|
+
onPortDead: (reason: string) => void
|
|
529
|
+
): Promise<void> {
|
|
530
|
+
takePrewarmed()?.worker.terminate();
|
|
531
|
+
this.dropReader('attaching to a leader');
|
|
532
|
+
await super.adoptAttached(dbPort, snapshot, onPortDead);
|
|
533
|
+
if (this.config.followerReads === 'direct' && this.useOpfs && snapshot.storageHealth.status === 'persistent') {
|
|
534
|
+
await this.startReader(snapshot.bucketId);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// ---- a follower's own reader ------------------------------------------------
|
|
539
|
+
// With `followerReads: 'direct'` a follower answers its reads from a worker
|
|
540
|
+
// of its own, on a reader of the store's file (`RowStore` reader mode). The
|
|
541
|
+
// reader is an optimization and nothing depends on it: when it cannot be
|
|
542
|
+
// had, or fails, the read goes to the leader as it would have.
|
|
543
|
+
|
|
544
|
+
/** The follower's reader worker, while this engine follows and has one. */
|
|
545
|
+
private reader: SqliteTransport | null = null;
|
|
546
|
+
|
|
547
|
+
private async startReader(bucketId: string): Promise<void> {
|
|
548
|
+
let transport: SqliteTransport | null = null;
|
|
549
|
+
// Every change of role bumps the epoch: the same epoch later means still this follower.
|
|
550
|
+
const asFollower = this.epoch;
|
|
551
|
+
try {
|
|
552
|
+
transport = new WorkerSqliteTransport(
|
|
553
|
+
this.logger,
|
|
554
|
+
this.config.workers?.rows ?? (() => new Worker(new URL('./rows-worker.ts', import.meta.url), { type: 'module' }))
|
|
555
|
+
);
|
|
556
|
+
const reply = await transport.call<OpenReply>('open', {
|
|
557
|
+
dbName: bucketId,
|
|
558
|
+
useOpfs: true,
|
|
559
|
+
reader: true,
|
|
560
|
+
openOptions: { maxAttempts: 2, disallowMemoryFallback: true },
|
|
561
|
+
});
|
|
562
|
+
if (reply.proto !== ROWS_PROTOCOL || !reply.persisted) throw new Error('reader worker is not this release\'s');
|
|
563
|
+
// The role may have moved on while the worker started.
|
|
564
|
+
if (this.epoch !== asFollower || this.bucketId !== bucketId) throw new Error('no longer a follower of this store');
|
|
565
|
+
this.reader = transport;
|
|
566
|
+
} catch (error) {
|
|
567
|
+
transport?.close('reader unavailable');
|
|
568
|
+
this.logger.info(
|
|
569
|
+
{ error: String(error), Category: 'sp00ky-client::RowsCacheEngine::reader' },
|
|
570
|
+
'No direct reads for this follower tab; it reads through the leader'
|
|
571
|
+
);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
private dropReader(reason: string): void {
|
|
576
|
+
const reader = this.reader;
|
|
577
|
+
this.reader = null;
|
|
578
|
+
reader?.close(reason);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** True while this follower answers its reads from the store's file itself. */
|
|
582
|
+
get readsDirectly(): boolean {
|
|
583
|
+
return this.reader !== null;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
protected override rawCall<T = unknown>(type: string, payload?: unknown, transfer?: Transferable[]): Promise<T> {
|
|
587
|
+
const reader = this.reader;
|
|
588
|
+
if (!reader || !ROWS_READER_OPS.has(type)) return super.rawCall<T>(type, payload, transfer);
|
|
589
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
590
|
+
const late = new Promise<never>((_resolve, reject) => {
|
|
591
|
+
timer = setTimeout(() => reject(new Error('reader timed out')), READER_OP_TIMEOUT_MS);
|
|
592
|
+
});
|
|
593
|
+
return Promise.race([reader.call<T>(type, payload), late])
|
|
594
|
+
.catch((error: unknown) => {
|
|
595
|
+
if (this.reader === reader) {
|
|
596
|
+
this.dropReader('read failed');
|
|
597
|
+
this.logger.warn(
|
|
598
|
+
{ error: String(error), type, Category: 'sp00ky-client::RowsCacheEngine::reader' },
|
|
599
|
+
'Direct read failed; this tab reads through the leader from here on'
|
|
600
|
+
);
|
|
601
|
+
}
|
|
602
|
+
return super.rawCall<T>(type, payload, transfer);
|
|
603
|
+
})
|
|
604
|
+
.finally(() => clearTimeout(timer));
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
override async adoptOwner(...args: Parameters<SqliteCacheEngine['adoptOwner']>): ReturnType<SqliteCacheEngine['adoptOwner']> {
|
|
608
|
+
this.dropReader('becoming the leader');
|
|
609
|
+
return super.adoptOwner(...args);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
override async releaseOwnership(): Promise<void> {
|
|
613
|
+
this.dropReader('releasing the store');
|
|
614
|
+
return super.releaseOwnership();
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
override onLeaderLost(reason: string): void {
|
|
618
|
+
// The file is still there and still whole, but writes have nowhere to go:
|
|
619
|
+
// read through the next leader, with a reader started against it.
|
|
620
|
+
this.dropReader('leader lost');
|
|
621
|
+
super.onLeaderLost(reason);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
override async close(): Promise<void> {
|
|
625
|
+
this.dropReader('engine closed');
|
|
626
|
+
return super.close();
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** Tables need no creating: a table is the rows written to it. */
|
|
630
|
+
protected override async ensureTable(): Promise<void> {}
|
|
631
|
+
|
|
632
|
+
// ---- read ahead -----------------------------------------------------------
|
|
633
|
+
// The reads of a session's first seconds are saved, and the next page load's
|
|
634
|
+
// prewarm asks them again before the app exists (`rows-prewarm.ts`).
|
|
635
|
+
|
|
636
|
+
private startupReads: Map<string, [string, unknown]> | null = null;
|
|
637
|
+
private startupBytes = 0;
|
|
638
|
+
private startupUntil = 0;
|
|
639
|
+
private startupTimer: ReturnType<typeof setTimeout> | null = null;
|
|
640
|
+
private startupHooked = false;
|
|
641
|
+
|
|
642
|
+
private beginStartupReads(): void {
|
|
643
|
+
// Not with shared tabs: other tabs write through the leader's worker, and
|
|
644
|
+
// an answer read ahead of them could be older than what they wrote.
|
|
645
|
+
if (!this.useOpfs || this.shared || typeof localStorage === 'undefined') return;
|
|
646
|
+
if (!this.startupHooked && typeof addEventListener === 'function') {
|
|
647
|
+
// localStorage is synchronous, so the list can still be saved as the page goes.
|
|
648
|
+
addEventListener('pagehide', () => this.saveStartupReads());
|
|
649
|
+
this.startupHooked = true;
|
|
650
|
+
}
|
|
651
|
+
this.startupReads = new Map();
|
|
652
|
+
this.startupBytes = 0;
|
|
653
|
+
this.startupUntil = performance.now() + PAINT_CAPTURE_MS;
|
|
654
|
+
if (this.startupTimer) clearTimeout(this.startupTimer);
|
|
655
|
+
this.startupTimer = background(setTimeout(() => this.saveStartupReads(), PAINT_CAPTURE_MS + 50));
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
private noteStartupRead(type: string, payload: unknown, replyBytes: number): void {
|
|
659
|
+
const reads = this.startupReads;
|
|
660
|
+
if (!reads || performance.now() > this.startupUntil || !ROWS_AHEAD_OPS.has(type)) return;
|
|
661
|
+
if (reads.size >= AHEAD_MAX_READS || replyBytes > AHEAD_MAX_REPLY_BYTES) return;
|
|
662
|
+
if (this.startupBytes + replyBytes > AHEAD_MAX_TOTAL_BYTES || !jsonSafe(payload)) return;
|
|
663
|
+
const key = aheadKey(type, payload);
|
|
664
|
+
if (key.length > AHEAD_MAX_REQUEST_CHARS || reads.has(key)) return;
|
|
665
|
+
reads.set(key, [type, payload]);
|
|
666
|
+
this.startupBytes += replyBytes;
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
/** Leave this session's startup reads for the next page load. Also runs as the page goes. */
|
|
670
|
+
private saveStartupReads(): void {
|
|
671
|
+
const reads = this.startupReads;
|
|
672
|
+
if (!reads) return;
|
|
673
|
+
try {
|
|
674
|
+
const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
|
|
675
|
+
if (!saved?.url || saved.bucket !== this.bucketId) return;
|
|
676
|
+
localStorage.setItem(ROWS_PREWARM_KEY, JSON.stringify({ url: saved.url, bucket: saved.bucket, reads: [...reads.values()] }));
|
|
677
|
+
} catch {
|
|
678
|
+
// No storage, or no room: the next load asks nothing ahead.
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
/** A read that answers rows. `paint` names it for the paint cache, when it is worth keeping. */
|
|
683
|
+
private async rows(type: string, payload: unknown, paint?: { key: string; tables: string[] }): Promise<Row[]> {
|
|
684
|
+
const sentAt = paint && this.paint ? this.paint.stamp(paint.tables) : 0;
|
|
685
|
+
const reply = await this.call<RowsReply>(type, payload);
|
|
686
|
+
this.noteStartupRead(type, payload, reply.buf?.byteLength ?? 0);
|
|
687
|
+
if (!reply.buf) return [];
|
|
688
|
+
const text = decoder.decode(new Uint8Array(reply.buf));
|
|
689
|
+
if (paint) this.paint?.note(paint.key, paint.tables, text, reply.u8 === true, sentAt);
|
|
690
|
+
return parseRowText(text, reply.u8 === true);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// ---- reads ---------------------------------------------------------------
|
|
694
|
+
|
|
695
|
+
private selectPayload(plan: QueryPlan, params: Record<string, unknown>): { plan: QueryPlan; params: Record<string, unknown> } {
|
|
696
|
+
// Class instances (RecordId) do not survive structured clone; see the
|
|
697
|
+
// SQLite engine's `select` for why the KEYS of `params` must all stay.
|
|
698
|
+
const normParams: Record<string, unknown> = {};
|
|
699
|
+
for (const [k, v] of Object.entries(params)) normParams[k] = toCloneSafe(v);
|
|
700
|
+
return { plan: normalizePlanForClone(plan), params: normParams };
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* The paint cache's name for a select. A caller that reads the same thing
|
|
705
|
+
* again and again under changing arguments (a query whose id set moves)
|
|
706
|
+
* names it itself with `paintKey`, so the copy kept is always its latest
|
|
707
|
+
* answer; without one a read is told apart by its plan and parameters.
|
|
708
|
+
*/
|
|
709
|
+
private selectKey(payload: unknown, opts?: { paintKey?: string }): string {
|
|
710
|
+
return opts?.paintKey === undefined ? hashKey('s' + JSON.stringify(payload)) : hashKey('q' + opts.paintKey);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
override async select(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Promise<Row[]> {
|
|
714
|
+
const payload = this.selectPayload(plan, params);
|
|
715
|
+
return this.rows('select', payload, this.paint ? { key: this.selectKey(payload, opts), tables: tablesOf(plan) } : undefined);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* What `select(plan, params)` answered the last time the app asked at
|
|
720
|
+
* startup, synchronously, or `null`. Available as soon as `connect` was
|
|
721
|
+
* CALLED: it reads localStorage, not the store. Paint from it, then run the
|
|
722
|
+
* real `select`, which is the answer; they differ only when something wrote
|
|
723
|
+
* to these tables that this tab did not see.
|
|
724
|
+
*/
|
|
725
|
+
peekSelect(plan: QueryPlan, params: Record<string, unknown> = {}, opts?: { paintKey?: string }): Row[] | null {
|
|
726
|
+
if (!this.paint) return null;
|
|
727
|
+
// A named read needs no payload to find its copy.
|
|
728
|
+
const payload = opts?.paintKey === undefined ? this.selectPayload(plan, params) : null;
|
|
729
|
+
return this.paint.get(this.selectKey(payload, opts), fromBase64);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* See `LocalStore.expectBucket`. Not with shared tabs: the paint cache is
|
|
734
|
+
* not kept there (other tabs write to the store unseen by this one).
|
|
735
|
+
*/
|
|
736
|
+
expectBucket(bucketId: string): void {
|
|
737
|
+
if (!this.shared) this.paint?.expect(bucketId);
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/** {@link peekSelect} for `selectByIds`. */
|
|
741
|
+
peekByIds(table: string, ids: Id[], opts?: { select?: string[]; orderBy?: OrderBy }): Row[] | null {
|
|
742
|
+
return this.paint?.get(byIdsKey(table, ids, opts), fromBase64) ?? null;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
override async fetchRelation(req: RelationFetch): Promise<Row[]> {
|
|
746
|
+
return this.rows('relation', {
|
|
747
|
+
table: req.table,
|
|
748
|
+
matchField: req.matchField,
|
|
749
|
+
keys: req.keys.map(stableKey),
|
|
750
|
+
where: normalizeWhereForClone(req.where),
|
|
751
|
+
orderBy: req.orderBy,
|
|
752
|
+
select: req.select,
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
override async selectByIds(
|
|
757
|
+
table: string,
|
|
758
|
+
ids: Id[],
|
|
759
|
+
opts?: { select?: string[]; orderBy?: OrderBy }
|
|
760
|
+
): Promise<Row[]> {
|
|
761
|
+
if (ids.length === 0) return [];
|
|
762
|
+
return this.rows(
|
|
763
|
+
'by-ids',
|
|
764
|
+
{ table, ids: ids.map(stableKey), select: opts?.select, orderBy: opts?.orderBy },
|
|
765
|
+
this.paint ? { key: byIdsKey(table, ids, opts), tables: [table] } : undefined
|
|
766
|
+
);
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
override async getById(table: string, id: Id): Promise<Row | null> {
|
|
770
|
+
return parseRowBytes<Row | null>(await this.call<RowsReply>('get', { table, id: stableKey(id) }), fromBase64);
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
override async scanVersions(tables: string[]): Promise<Record<string, [string, number][]>> {
|
|
774
|
+
return (await this.call<{ versions: Record<string, [string, number][]> }>('versions', { tables })).versions;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/**
|
|
778
|
+
* See `sqlite-column-reset.ts`. The recorded column sets live in one raw row
|
|
779
|
+
* of `_00_schema`, which no row read ever returns.
|
|
780
|
+
*/
|
|
781
|
+
override async resetChangedTables(fingerprints: Record<string, string>, keep: Set<string>): Promise<string[]> {
|
|
782
|
+
const { bytes } = await this.call<{ bytes: ArrayBuffer | null }>('blob-get', { table: SCHEMA_TABLE, key: COLUMNS_ROW_ID });
|
|
783
|
+
let stored: Record<string, string> | null = null;
|
|
784
|
+
try {
|
|
785
|
+
if (bytes) stored = JSON.parse(decoder.decode(new Uint8Array(bytes))) as Record<string, string>;
|
|
786
|
+
} catch {
|
|
787
|
+
stored = null;
|
|
788
|
+
}
|
|
789
|
+
const tables = await this.listTables();
|
|
790
|
+
const plan = planColumnReset(stored, fingerprints, new Set(tables), keep);
|
|
791
|
+
if (plan.statements.length === 0) return plan.changed;
|
|
792
|
+
this.paint?.touch(plan.changed);
|
|
793
|
+
if (plan.changed.length > 0) await this.call('reset-versions', { tables: plan.changed, keep: [...keep] });
|
|
794
|
+
// Recorded last: a tab that dies between the two redoes the reset, which is harmless.
|
|
795
|
+
const body = encoder.encode(JSON.stringify(fingerprints));
|
|
796
|
+
const buf = body.buffer as ArrayBuffer;
|
|
797
|
+
await this.call(
|
|
798
|
+
'write',
|
|
799
|
+
{ ops: [['put', SCHEMA_TABLE, COLUMNS_ROW_ID, 0, FLAG_RAW, 0, body.length]] satisfies WireOp[], buf, sync: false },
|
|
800
|
+
[buf]
|
|
801
|
+
);
|
|
802
|
+
return plan.changed;
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
override async getSnapshot(key: string): Promise<StoredSnapshot | null> {
|
|
806
|
+
const { bytes, meta } = await this.call<{ bytes: ArrayBuffer | null; meta: string | null }>('blob-get', {
|
|
807
|
+
table: SNAPSHOT_TABLE,
|
|
808
|
+
key,
|
|
809
|
+
});
|
|
810
|
+
if (!bytes || !meta) return null;
|
|
811
|
+
try {
|
|
812
|
+
return { bytes: new Uint8Array(bytes), meta: JSON.parse(meta) as SnapshotMeta };
|
|
813
|
+
} catch {
|
|
814
|
+
return null;
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
override async putSnapshot(key: string, bytes: Uint8Array, meta: SnapshotMeta): Promise<void> {
|
|
819
|
+
// A copy, so the transfer does not take the caller's buffer away.
|
|
820
|
+
const buf = bytes.slice().buffer as ArrayBuffer;
|
|
821
|
+
await this.call('blob-put', { table: SNAPSHOT_TABLE, key, bytes: buf, meta: JSON.stringify(meta) }, [buf]);
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
override async deleteSnapshot(key: string): Promise<void> {
|
|
825
|
+
await this.call('blob-del', { table: SNAPSHOT_TABLE, key });
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// ---- writes --------------------------------------------------------------
|
|
829
|
+
|
|
830
|
+
override async upsert(table: string, id: Id, data: Row, mode: 'replace' | 'merge'): Promise<void> {
|
|
831
|
+
await this.write([{ kind: 'upsert', table, key: stableKey(id), data, mode }]);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
override async delete(table: string, id: Id): Promise<void> {
|
|
835
|
+
await this.write([{ kind: 'delete', table, key: stableKey(id) }]);
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** One message, one atomic batch in the store, however many rows. */
|
|
839
|
+
private async write(items: WriteItem[]): Promise<void> {
|
|
840
|
+
const { wire, buf, sync } = packWrites(items);
|
|
841
|
+
if (wire.length === 0) return;
|
|
842
|
+
this.paint?.touch(new Set(items.map((item) => item.table)));
|
|
843
|
+
await this.call('write', { ops: wire, buf, sync }, buf ? [buf] : undefined);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
protected override runWriteBatch(ops: SqlOp[]): Promise<void> {
|
|
847
|
+
return this.write(itemsOf(ops));
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
protected override async rawSelectTable(
|
|
851
|
+
table: string,
|
|
852
|
+
where?: WhereNode[],
|
|
853
|
+
orderBy?: OrderBy,
|
|
854
|
+
window?: { limit?: number; start?: number }
|
|
855
|
+
): Promise<Row[]> {
|
|
856
|
+
return this.rows('select-table', {
|
|
857
|
+
table,
|
|
858
|
+
where: normalizeWhereForClone(where),
|
|
859
|
+
orderBy,
|
|
860
|
+
limit: window?.limit,
|
|
861
|
+
start: window?.start,
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
protected override async countRows(table: string, where?: WhereNode[]): Promise<number> {
|
|
866
|
+
return (await this.call<{ n: number }>('count', { table, where: normalizeWhereForClone(where) })).n;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
protected override async listTables(): Promise<string[]> {
|
|
870
|
+
return (await this.call<{ tables: string[] }>('tables')).tables;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
protected override async deleteAllRows(table: string): Promise<void> {
|
|
874
|
+
await this.write([{ kind: 'clear', table }]);
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
// ---- housekeeping --------------------------------------------------------
|
|
878
|
+
|
|
879
|
+
override async getStorageDiagnostics(opts?: { tableCounts?: boolean }): Promise<EngineStorageDiagnostics> {
|
|
880
|
+
const diag: EngineStorageDiagnostics = {
|
|
881
|
+
engine: 'rows',
|
|
882
|
+
bucketId: this.bucketId,
|
|
883
|
+
useOpfs: this.useOpfs,
|
|
884
|
+
workerSelectConfigured: true,
|
|
885
|
+
workerSelectEffective: true,
|
|
886
|
+
};
|
|
887
|
+
try {
|
|
888
|
+
const { stats, tableCounts } = await this.call<{
|
|
889
|
+
stats: StoreStats;
|
|
890
|
+
tableCounts?: { table: string; rows: number }[];
|
|
891
|
+
}>('diag', { tableCounts: opts?.tableCounts === true });
|
|
892
|
+
diag.dbSizeBytes = stats.fileBytes;
|
|
893
|
+
diag.freelistBytes = stats.garbageBytes;
|
|
894
|
+
if (tableCounts) diag.tableCounts = tableCounts.filter((t) => t.table !== SNAPSHOT_TABLE);
|
|
895
|
+
} catch (e) {
|
|
896
|
+
diag.error = e instanceof Error ? e.message : String(e);
|
|
897
|
+
}
|
|
898
|
+
return diag;
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/** See `LocalStore.dropBucket`. Fails harmlessly while a worker holds the files. */
|
|
902
|
+
override async dropBucket(bucketId: string): Promise<void> {
|
|
903
|
+
if (bucketId === this.bucketId) throw new Error('Cannot drop the open bucket.');
|
|
904
|
+
PaintCache.drop(bucketId);
|
|
905
|
+
try {
|
|
906
|
+
// Nothing to start ahead for a store that is gone.
|
|
907
|
+
const saved = JSON.parse(localStorage.getItem(ROWS_PREWARM_KEY) ?? 'null') as Partial<PrewarmRecord> | null;
|
|
908
|
+
if (saved?.bucket === bucketId) localStorage.removeItem(ROWS_PREWARM_KEY);
|
|
909
|
+
} catch {
|
|
910
|
+
/* no storage */
|
|
911
|
+
}
|
|
912
|
+
const storage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
|
|
913
|
+
if (!storage?.getDirectory) return;
|
|
914
|
+
const root = await storage.getDirectory();
|
|
915
|
+
try {
|
|
916
|
+
await root.removeEntry(bucketDirName(bucketId), { recursive: true });
|
|
917
|
+
} catch (error) {
|
|
918
|
+
if ((error as DOMException)?.name !== 'NotFoundError') throw error;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
}
|