@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,1027 @@
1
+ /**
2
+ * What the row store's worker does with a request: the client's verbs, run
3
+ * against a {@link RowStore}.
4
+ *
5
+ * # Bodies are JSON text, and stay text as long as they can
6
+ *
7
+ * A row's body is the same JSON the SQLite engine stores (`serializeRow`):
8
+ * record links as `table:id` strings, bytes as `{"__u8": base64}`. JSON
9
+ * because the engine's own parser is several times faster than any decoder
10
+ * written in JavaScript, and that parser is the whole read path here:
11
+ *
12
+ * - a read that needs no look inside the rows (a window by id, the common
13
+ * case) never parses them in the worker. The bodies are copied out of the
14
+ * file between `[`, `,` and `]`, the buffer is transferred, and the page
15
+ * runs one `JSON.parse` over the lot;
16
+ * - a scan reads the file in ranges of megabytes, blanks the bytes between
17
+ * two bodies in the buffer (whitespace, one comma) and parses each range in
18
+ * one call. No per-row decode, no copy.
19
+ *
20
+ * # Indexes are tables
21
+ *
22
+ * A secondary index over `field` of `table` is a hidden table in the same
23
+ * store whose ids are `value\0rowId` and whose bodies are empty. Ids are kept
24
+ * sorted, so "every row whose field is X" is one search and a short walk, and
25
+ * the index is written in the same atomic batch as the rows it describes: it
26
+ * cannot disagree with them, and it is on disk for the next session. Two ways
27
+ * a field gets one: it holds record links (found as rows are written, so a
28
+ * `.related()` never waits for a build), or a query filters on it with `=`
29
+ * (built by one scan the first time, kept up from then on). A field with a
30
+ * handful of distinct values is left alone: a scan reads its matches faster.
31
+ *
32
+ * # Same answers as the SQLite engine
33
+ *
34
+ * Filters, ordering and merges follow what that engine's SQL does, so a query
35
+ * reads the same on either: `json_extract` storage classes (a boolean is 1 or
36
+ * 0, an object is its JSON text), NULL never matching, numbers below text,
37
+ * text in UTF-8 byte order, `json_patch` (RFC 7396) for merges. Two
38
+ * differences, both where SQL leaves the order open: rows that tie on an
39
+ * ORDER BY, and the children of an unordered `.related()`, come back in id
40
+ * order here and in insertion order there.
41
+ */
42
+ import type { QueryPlan, WhereComparison, WhereNode } from '@spooky-sync/query-builder';
43
+ import { resolveRelations, stableKey } from './relation-resolver';
44
+ import { project, scalar } from './sqlite-plan-sql';
45
+ import type { OrderBy, RelationFetch, Row, RowFetcher } from './cache-engine';
46
+ import {
47
+ FLAG_RAW,
48
+ FLAG_U8,
49
+ cmpText,
50
+ runId,
51
+ type Entry,
52
+ type RowStore,
53
+ type Run,
54
+ type StoreOp,
55
+ type StoreStats,
56
+ } from './rows-store';
57
+
58
+ const encoder = new TextEncoder();
59
+ const decoder = new TextDecoder();
60
+
61
+ /** A value as SQLite holds it once `json_extract` or a bind produced it. */
62
+ type SqlValue = null | number | string;
63
+
64
+ /** Rows on their way to the page: JSON text of an array, as bytes. */
65
+ export interface RowBytes {
66
+ buf: ArrayBuffer;
67
+ /** Some body carries `{"__u8": …}` tags the page has to revive. */
68
+ u8: boolean;
69
+ }
70
+
71
+ /** One write, as the page sends it: bodies are ranges of the batch's buffer. */
72
+ export type WireOp =
73
+ | ['put', table: string, id: string, rv: number, flags: number, off: number, len: number]
74
+ | ['merge', table: string, id: string, rv: number, flags: number, off: number, len: number, patchOff: number, patchLen: number]
75
+ | ['del', table: string, id: string]
76
+ | ['clear', table: string];
77
+
78
+ const MAX_GAP = 4096;
79
+ const MAX_RANGE = 4 << 20;
80
+ /** Tables the store keeps for itself start with this; no client table can. */
81
+ const HIDDEN = '\u0001';
82
+ const META_TABLE = `${HIDDEN}meta`;
83
+ const INDEXES_ROW = 'indexes';
84
+ const SEP = '\u0000';
85
+ const MAX_KEY_CHARS = 200;
86
+ /** An index build writes its entries in batches of this many. */
87
+ const INDEX_BATCH = 20_000;
88
+ /** A value that addresses a record: `table:id`, and not a URL. */
89
+ const LINK = /^[A-Za-z_][A-Za-z0-9_]*:(?!\/\/).{1,80}$/s;
90
+ const NO_ENTRY = new Uint8Array(0);
91
+
92
+ const indexTable = (table: string, field: string): string => `${HIDDEN}i${HIDDEN}${table}${HIDDEN}${field}`;
93
+ /** Tables that get indexes: the app's own. The client's `_00_` tables are small and read whole. */
94
+ const isUserTable = (table: string): boolean => !table.startsWith('_00_') && !table.startsWith(HIDDEN);
95
+
96
+ /** The tables a client may see: everything but the store's own. */
97
+ export const visibleTables = (store: RowStore): string[] => store.tableNames().filter((t) => !t.startsWith(HIDDEN));
98
+
99
+ /** A value as an index key, or `null` when it is not indexed (NULL, very long, or holding the separator). */
100
+ function indexKey(value: SqlValue): string | null {
101
+ if (value === null) return null;
102
+ const key = typeof value === 'number' ? `n${value}` : `s${value}`;
103
+ return key.length > MAX_KEY_CHARS || key.includes(SEP) ? null : key;
104
+ }
105
+ const U8_TAG = '"__u8"';
106
+
107
+ // ---- SQLite value semantics --------------------------------------------------
108
+
109
+ function walk(row: unknown, field: string): unknown {
110
+ if (!field.includes('.') && !field.includes('[')) {
111
+ return row !== null && typeof row === 'object' ? (row as Row)[field] : undefined;
112
+ }
113
+ let cur: unknown = row;
114
+ for (const part of field.split('.')) {
115
+ const m = /^([^[]*)((?:\[\d+\])*)$/.exec(part);
116
+ if (!m) return undefined;
117
+ if (m[1] !== '') {
118
+ if (cur === null || typeof cur !== 'object' || Array.isArray(cur)) return undefined;
119
+ cur = (cur as Row)[m[1]];
120
+ }
121
+ for (const idx of m[2].matchAll(/\[(\d+)\]/g)) {
122
+ if (!Array.isArray(cur)) return undefined;
123
+ cur = cur[Number(idx[1])];
124
+ }
125
+ }
126
+ return cur;
127
+ }
128
+
129
+ /** `json_extract(data, '$.<field>')`, or the id column for `id`. */
130
+ function extract(row: Row, field: string): SqlValue {
131
+ const v = walk(row, field);
132
+ if (v === null || v === undefined) return null;
133
+ if (typeof v === 'number' || typeof v === 'string') return v;
134
+ if (typeof v === 'boolean') return v ? 1 : 0;
135
+ return JSON.stringify(v);
136
+ }
137
+
138
+ /** A bound parameter, after `scalar()` and SQLite's binding rules. */
139
+ function bound(value: unknown, forId: boolean): SqlValue {
140
+ const v = scalar(value);
141
+ if (v === null || v === undefined) return null;
142
+ if (typeof v === 'boolean') return v ? 1 : 0;
143
+ if (typeof v === 'bigint') return Number(v);
144
+ // The id column has TEXT affinity, which a number compared to it takes on.
145
+ if (typeof v === 'number') return forId ? String(v) : v;
146
+ return String(v);
147
+ }
148
+
149
+ function sqlCompare(a: number | string, b: number | string): number {
150
+ const an = typeof a === 'number';
151
+ const bn = typeof b === 'number';
152
+ if (an && bn) return (a as number) < (b as number) ? -1 : (a as number) > (b as number) ? 1 : 0;
153
+ if (an) return -1;
154
+ if (bn) return 1;
155
+ return cmpText(a as string, b as string);
156
+ }
157
+
158
+ /** The value a comparison binds: the query's own param when it has one, else the baked literal. */
159
+ function rhsOf(c: WhereComparison, params: Record<string, unknown>): SqlValue {
160
+ const useParam =
161
+ c.paramRef !== undefined && (c.value === undefined || Object.prototype.hasOwnProperty.call(params, c.paramRef));
162
+ return bound(useParam ? params[c.paramRef!] : c.value, c.field === 'id');
163
+ }
164
+
165
+ function compileComparison(c: WhereComparison, params: Record<string, unknown>): (row: Row) => boolean {
166
+ const rhs = rhsOf(c, params);
167
+ const field = c.field;
168
+ const sign = c.swap ? -1 : 1;
169
+ let test: (cmp: number) => boolean;
170
+ switch (c.op) {
171
+ case '=':
172
+ test = (cmp) => cmp === 0;
173
+ break;
174
+ case '!=':
175
+ test = (cmp) => cmp !== 0;
176
+ break;
177
+ case '<':
178
+ test = (cmp) => cmp < 0;
179
+ break;
180
+ case '<=':
181
+ test = (cmp) => cmp <= 0;
182
+ break;
183
+ case '>':
184
+ test = (cmp) => cmp > 0;
185
+ break;
186
+ case '>=':
187
+ test = (cmp) => cmp >= 0;
188
+ break;
189
+ default:
190
+ throw new Error(`rows: unsupported comparison operator ${String(c.op)}`);
191
+ }
192
+ // A comparison with NULL is NULL, which no WHERE lets through.
193
+ if (rhs === null) return () => false;
194
+ return (row) => {
195
+ const lhs = extract(row, field);
196
+ return lhs !== null && test(sign * sqlCompare(lhs, rhs));
197
+ };
198
+ }
199
+
200
+ /** The filter a WHERE describes; `null` when there is none. */
201
+ export function compileWhere(
202
+ nodes: WhereNode[] | undefined,
203
+ params: Record<string, unknown>
204
+ ): ((row: Row) => boolean) | null {
205
+ if (!nodes || nodes.length === 0) return null;
206
+ const tests = nodes.map((node) => {
207
+ if ('or' in node) {
208
+ const any = node.or.map((c) => compileComparison(c, params));
209
+ return (row: Row) => any.some((t) => t(row));
210
+ }
211
+ return compileComparison(node, params);
212
+ });
213
+ return tests.length === 1 ? tests[0] : (row) => tests.every((t) => t(row));
214
+ }
215
+
216
+ /** Sort as `ORDER BY json_extract(…)` does; ties fall back to the id. */
217
+ export function sortSql(rows: Row[], orderBy: OrderBy): Row[] {
218
+ const keyed = rows.map((row) => ({ row, keys: orderBy.map(([field]) => extract(row, field)) }));
219
+ keyed.sort((a, b) => {
220
+ for (let i = 0; i < orderBy.length; i++) {
221
+ const x = a.keys[i];
222
+ const y = b.keys[i];
223
+ // NULL is the smallest value.
224
+ const cmp = x === null ? (y === null ? 0 : -1) : y === null ? 1 : sqlCompare(x, y);
225
+ if (cmp !== 0) return orderBy[i][1] === 'desc' ? -cmp : cmp;
226
+ }
227
+ return cmpText(String(a.row.id), String(b.row.id));
228
+ });
229
+ return keyed.map((k) => k.row);
230
+ }
231
+
232
+ /** `json_patch(target, patch)`: RFC 7396. A `null` member removes its key. */
233
+ export function mergePatch(target: unknown, patch: unknown): unknown {
234
+ if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return patch;
235
+ const out: Row =
236
+ target !== null && typeof target === 'object' && !Array.isArray(target) ? (target as Row) : {};
237
+ for (const key of Object.keys(patch as Row)) {
238
+ const value = (patch as Row)[key];
239
+ if (value === null) delete out[key];
240
+ else out[key] = mergePatch(out[key], value);
241
+ }
242
+ return out;
243
+ }
244
+
245
+ // ---- bytes in, bytes out -----------------------------------------------------
246
+
247
+ function toBytes(rows: unknown): RowBytes {
248
+ const text = JSON.stringify(rows);
249
+ const bytes = encoder.encode(text);
250
+ return { buf: bytes.buffer as ArrayBuffer, u8: text.includes(U8_TAG) };
251
+ }
252
+
253
+ /** The page's side of {@link RowBytes}: one parse for the whole answer. */
254
+ export function parseRowBytes<T = Row[]>(res: { buf: ArrayBuffer | null; u8?: boolean }, revive: (b64: string) => Uint8Array): T {
255
+ if (!res.buf) return null as T;
256
+ const text = decoder.decode(new Uint8Array(res.buf));
257
+ if (!res.u8) return JSON.parse(text) as T;
258
+ return JSON.parse(text, (_k, v) =>
259
+ v && typeof v === 'object' && typeof (v as { __u8?: unknown }).__u8 === 'string' ? revive((v as { __u8: string }).__u8) : v
260
+ ) as T;
261
+ }
262
+
263
+ export class RowsExec {
264
+ /** table -> field -> `true` indexed, `false` looked at and left to scans. */
265
+ private indexes = new Map<string, Map<string, boolean>>();
266
+ /** table -> fields seen holding something that is not a link. Not persisted: a guess that saves a regex per row. */
267
+ private plain = new Map<string, Set<string>>();
268
+ private scratch = new Uint8Array(256 << 10);
269
+ /** Relation fetches of the request in flight, for the engine's stats. */
270
+ private relationFetches = 0;
271
+
272
+ /** Where the registry row read last lies in the file; tells a reader when the writer has changed it. */
273
+ private registryAt = -1;
274
+
275
+ /**
276
+ * `readOnly` is for a store opened as a reader (a follower tab on the
277
+ * leader's file): it uses the indexes the writer keeps and builds none.
278
+ */
279
+ constructor(
280
+ private store: RowStore,
281
+ private readOnly = false
282
+ ) {
283
+ this.syncRegistry();
284
+ }
285
+
286
+ /** Read the index registry, again when the store's writer has rewritten it. */
287
+ syncRegistry(): void {
288
+ const at = this.store.find(META_TABLE, INDEXES_ROW)?.off ?? -1;
289
+ if (at === this.registryAt) return;
290
+ this.registryAt = at;
291
+ this.indexes.clear();
292
+ const saved = at < 0 ? null : this.store.get(META_TABLE, INDEXES_ROW);
293
+ if (!saved) return;
294
+ try {
295
+ const parsed = JSON.parse(decoder.decode(saved.body)) as Record<string, Record<string, boolean>>;
296
+ for (const [table, fields] of Object.entries(parsed)) this.indexes.set(table, new Map(Object.entries(fields)));
297
+ } catch {
298
+ // An unreadable registry only costs the indexes: they are rebuilt on use.
299
+ }
300
+ }
301
+
302
+ // ---- reading bodies ------------------------------------------------------
303
+
304
+ /** The bodies of `entries` as one JSON array, straight from the file. */
305
+ private concat(entries: Entry[]): { bytes: Uint8Array; u8: boolean } {
306
+ let total = 2;
307
+ for (const e of entries) total += e.len + 1;
308
+ if (entries.length > 0) total--;
309
+ const bytes = new Uint8Array(new ArrayBuffer(Math.max(total, 2)));
310
+ let p = 0;
311
+ let u8 = false;
312
+ bytes[p++] = 0x5b;
313
+ for (let i = 0; i < entries.length; i++) {
314
+ const e = entries[i];
315
+ if (i > 0) bytes[p++] = 0x2c;
316
+ this.store.readInto(e.off, e.len, bytes, p);
317
+ p += e.len;
318
+ if (e.flags & FLAG_U8) u8 = true;
319
+ }
320
+ bytes[p] = 0x5d;
321
+ return { bytes, u8 };
322
+ }
323
+
324
+ private raw(entries: Entry[]): RowBytes {
325
+ const { bytes, u8 } = this.concat(entries);
326
+ return { buf: bytes.buffer as ArrayBuffer, u8 };
327
+ }
328
+
329
+ private parse(entries: Entry[]): Row[] {
330
+ if (entries.length === 0) return [];
331
+ return JSON.parse(decoder.decode(this.concat(entries).bytes)) as Row[];
332
+ }
333
+
334
+ private findAll(table: string, keys: string[]): Entry[] {
335
+ const out: Entry[] = [];
336
+ for (const key of keys) {
337
+ const entry = this.store.find(table, key);
338
+ if (entry && !(entry.flags & FLAG_RAW)) out.push(entry);
339
+ }
340
+ return out;
341
+ }
342
+
343
+ /**
344
+ * Visit every row of a table. The file is read in offset order, a range of
345
+ * megabytes at a time, and each range is parsed in one call: the bytes
346
+ * between two bodies (record heads, dead rows) are blanked in the buffer and
347
+ * one of them becomes the comma. `visit` returns false to stop.
348
+ */
349
+ private scan(table: string, visit: (row: Row, at: number, run: Run) => boolean | void): void {
350
+ const run = this.store.ordered(table);
351
+ if (run.n === 0) return;
352
+ const order = run.byOff ?? (run.byOff = byOffset(run));
353
+ let k = 0;
354
+ while (k < order.length) {
355
+ const first = k;
356
+ const start = run.off[order[k]] - 1;
357
+ let end = run.off[order[k]] + run.len[order[k]];
358
+ k++;
359
+ while (k < order.length) {
360
+ const i = order[k];
361
+ if (run.off[i] - end > MAX_GAP || run.off[i] + run.len[i] - start > MAX_RANGE) break;
362
+ end = run.off[i] + run.len[i];
363
+ k++;
364
+ }
365
+ const size = end - start + 1;
366
+ if (this.scratch.length < size) this.scratch = new Uint8Array(size);
367
+ const buf = this.scratch;
368
+ this.store.readInto(start, end - start, buf, 0);
369
+ buf[0] = 0x5b;
370
+ buf[size - 1] = 0x5d;
371
+ let p = run.off[order[first]] + run.len[order[first]] - start;
372
+ for (let j = first + 1; j < k; j++) {
373
+ const rel = run.off[order[j]] - start;
374
+ buf[p] = 0x2c;
375
+ buf.fill(0x20, p + 1, rel);
376
+ p = rel + run.len[order[j]];
377
+ }
378
+ const rows = JSON.parse(decoder.decode(buf.subarray(0, size))) as Row[];
379
+ for (let j = first; j < k; j++) {
380
+ if (visit(rows[j - first], order[j], run) === false) return;
381
+ }
382
+ }
383
+ if (this.scratch.length > MAX_RANGE * 2) this.scratch = new Uint8Array(256 << 10);
384
+ }
385
+
386
+ // ---- indexes -------------------------------------------------------------
387
+
388
+ private fieldsOf(table: string): string[] {
389
+ const fields = this.indexes.get(table);
390
+ if (!fields) return [];
391
+ const out: string[] = [];
392
+ for (const [field, on] of fields) if (on) out.push(field);
393
+ return out;
394
+ }
395
+
396
+ private keysOf(fields: string[], row: Row | null): (string | null)[] {
397
+ return fields.map((field) => (row ? indexKey(extract(row, field)) : null));
398
+ }
399
+
400
+ /** Move a row's index entries from its old keys to its new ones. */
401
+ private reindex(
402
+ table: string,
403
+ id: string,
404
+ fields: string[],
405
+ before: (string | null)[],
406
+ after: (string | null)[],
407
+ out: StoreOp[]
408
+ ): void {
409
+ for (let i = 0; i < fields.length; i++) {
410
+ if (before[i] === after[i]) continue;
411
+ const index = indexTable(table, fields[i]);
412
+ if (before[i] !== null) out.push({ t: 'del', table: index, id: before[i] + SEP + id });
413
+ if (after[i] !== null) out.push({ t: 'put', table: index, id: after[i] + SEP + id, rv: 0, flags: FLAG_RAW, body: NO_ENTRY });
414
+ }
415
+ }
416
+
417
+ private registryOp(): StoreOp {
418
+ const all: Record<string, Record<string, boolean>> = {};
419
+ for (const [table, fields] of this.indexes) all[table] = Object.fromEntries(fields);
420
+ return { t: 'put', table: META_TABLE, id: INDEXES_ROW, rv: 0, flags: FLAG_RAW, body: encoder.encode(JSON.stringify(all)) };
421
+ }
422
+
423
+ private mark(table: string, field: string, on: boolean): void {
424
+ let fields = this.indexes.get(table);
425
+ if (!fields) this.indexes.set(table, (fields = new Map()));
426
+ fields.set(field, on);
427
+ }
428
+
429
+ /** Fields of `row` that hold a record link and have no index yet: they get one now. */
430
+ private discover(table: string, row: Row, added: [string, string][]): void {
431
+ const fields = this.indexes.get(table);
432
+ let plain = this.plain.get(table);
433
+ for (const field in row) {
434
+ const value = row[field];
435
+ if (typeof value !== 'string' || field === 'id' || fields?.has(field) || plain?.has(field)) continue;
436
+ if (LINK.test(value)) {
437
+ this.mark(table, field, true);
438
+ added.push([table, field]);
439
+ } else {
440
+ if (!plain) this.plain.set(table, (plain = new Set()));
441
+ plain.add(field);
442
+ }
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Whether `field` of `table` has an index, building it if it has none yet:
448
+ * one scan, written to the store, kept up by every write after. Without
449
+ * `force`, a field with too few distinct values to be worth one is turned
450
+ * down, and that answer is remembered too.
451
+ */
452
+ private ensureIndex(table: string, field: string, force: boolean): boolean {
453
+ const known = this.indexes.get(table)?.get(field);
454
+ if (known === true) return true;
455
+ if (known === false && !force) return false;
456
+ // A reader has what the writer built and scans for the rest.
457
+ if (this.readOnly) return false;
458
+ const index = indexTable(table, field);
459
+ const puts: StoreOp[] = [];
460
+ const distinct = new Set<string>();
461
+ let rows = 0;
462
+ this.scan(table, (row) => {
463
+ rows++;
464
+ const key = indexKey(extract(row, field));
465
+ if (key === null) return;
466
+ distinct.add(key);
467
+ puts.push({ t: 'put', table: index, id: key + SEP + String(row.id), rv: 0, flags: FLAG_RAW, body: NO_ENTRY });
468
+ });
469
+ // With fewer than 8 values each one matches an eighth of the table or more.
470
+ const worth = force || rows < 64 || distinct.size >= 8;
471
+ this.mark(table, field, worth);
472
+ if (!worth) {
473
+ this.store.write([this.registryOp()]);
474
+ return false;
475
+ }
476
+ for (let i = 0; i < puts.length; i += INDEX_BATCH) this.store.write(puts.slice(i, i + INDEX_BATCH));
477
+ this.store.write([this.registryOp()]);
478
+ return true;
479
+ }
480
+
481
+ private lookup(table: string, field: string, key: string): string[] {
482
+ return this.store.prefix(indexTable(table, field), key + SEP);
483
+ }
484
+
485
+ // ---- select --------------------------------------------------------------
486
+
487
+ /**
488
+ * The rows a filter can possibly match, when an index can say so without
489
+ * reading the table: an `id = …`, or an `=` on an indexed field. In id
490
+ * order. `null` means read the table.
491
+ */
492
+ private narrow(table: string, where: WhereNode[] | undefined, params: Record<string, unknown>): Entry[] | null {
493
+ if (!where) return null;
494
+ for (const node of where) {
495
+ if ('or' in node || node.op !== '=') continue;
496
+ const value = rhsOf(node, params);
497
+ // `= NULL` is never true, and it is ANDed with the rest.
498
+ if (value === null) return [];
499
+ if (node.field === 'id') return this.findAll(table, [String(value)]);
500
+ if (!isUserTable(table)) continue;
501
+ const key = indexKey(value);
502
+ if (key === null || !this.ensureIndex(table, node.field, false)) continue;
503
+ const ids = this.lookup(table, node.field, key);
504
+ // Past a third of the table a scan reads the matches faster than this many point reads.
505
+ if (ids.length > Math.max(256, this.store.count(table) / 3)) continue;
506
+ return this.findAll(table, ids);
507
+ }
508
+ return null;
509
+ }
510
+
511
+ /** Rows matching `where`, as (row, entry) in the order SQL would give them. */
512
+ private filtered(
513
+ table: string,
514
+ where: WhereNode[] | undefined,
515
+ params: Record<string, unknown>,
516
+ orderBy: OrderBy | undefined,
517
+ limit: number | undefined,
518
+ offset: number | undefined
519
+ ): { rows: Row[]; entries: Entry[] } {
520
+ const test = compileWhere(where, params);
521
+ const ordered = orderBy !== undefined && orderBy.length > 0;
522
+ const from = offset ?? 0;
523
+ const to = limit === undefined ? undefined : from + limit;
524
+ const narrowed = this.narrow(table, where, params);
525
+ if (!narrowed && !ordered && to !== undefined) return this.firstInIdOrder(table, test, from, to);
526
+
527
+ // Every match, in id order.
528
+ let rows: Row[] = [];
529
+ let entries: Entry[] = [];
530
+ if (narrowed) {
531
+ const parsed = this.parse(narrowed);
532
+ for (let i = 0; i < parsed.length; i++) {
533
+ if (test && !test(parsed[i])) continue;
534
+ rows.push(parsed[i]);
535
+ entries.push(narrowed[i]);
536
+ }
537
+ } else {
538
+ const hits: { row: Row; at: number }[] = [];
539
+ let seen: Run | null = null;
540
+ this.scan(table, (row, at, run) => {
541
+ seen = run;
542
+ if (!test || test(row)) hits.push({ row, at });
543
+ });
544
+ // The scan walks the file; run order is id order.
545
+ hits.sort((a, b) => a.at - b.at);
546
+ const run = seen as Run | null;
547
+ rows = hits.map((h) => h.row);
548
+ entries = run ? hits.map((h) => ({ off: run.off[h.at], len: run.len[h.at], rv: run.rv[h.at], flags: run.flags[h.at] })) : [];
549
+ }
550
+ if (ordered) {
551
+ const entryOf = new Map<Row, Entry>();
552
+ for (let i = 0; i < rows.length; i++) entryOf.set(rows[i], entries[i]);
553
+ rows = sortSql(rows, orderBy!).slice(from, to);
554
+ return { rows, entries: rows.map((row) => entryOf.get(row)!) };
555
+ }
556
+ return { rows: rows.slice(from, to), entries: entries.slice(from, to) };
557
+ }
558
+
559
+ /**
560
+ * The matches numbered `from` to `to` in id order, reading no further than
561
+ * it has to: an unordered query with a LIMIT stops at its last row instead
562
+ * of walking the table.
563
+ */
564
+ private firstInIdOrder(
565
+ table: string,
566
+ test: ((row: Row) => boolean) | null,
567
+ from: number,
568
+ to: number
569
+ ): { rows: Row[]; entries: Entry[] } {
570
+ const run = this.store.ordered(table);
571
+ const rows: Row[] = [];
572
+ const entries: Entry[] = [];
573
+ let i = 0;
574
+ let step = 64;
575
+ while (i < run.n && rows.length < to) {
576
+ const chunk: Entry[] = [];
577
+ for (; i < run.n && chunk.length < step; i++) {
578
+ if (run.flags[i] & FLAG_RAW) continue;
579
+ chunk.push({ off: run.off[i], len: run.len[i], rv: run.rv[i], flags: run.flags[i] });
580
+ }
581
+ const parsed = this.parse(chunk);
582
+ for (let j = 0; j < parsed.length && rows.length < to; j++) {
583
+ if (test && !test(parsed[j])) continue;
584
+ rows.push(parsed[j]);
585
+ entries.push(chunk[j]);
586
+ }
587
+ step = Math.min(step * 2, 2048);
588
+ }
589
+ return { rows: rows.slice(from), entries: entries.slice(from) };
590
+ }
591
+
592
+ async select(plan: QueryPlan, params: Record<string, unknown>): Promise<RowBytes & { relationFetches: number }> {
593
+ this.relationFetches = 0;
594
+ const shaped = plan.select !== undefined || (plan.relations !== undefined && plan.relations.length > 0);
595
+ let rows: Row[];
596
+ if (plan.ids) {
597
+ const entries = this.findAll(plan.table, windowOrder(plan.ids.map(stableKey)));
598
+ const ordered = plan.orderBy !== undefined && plan.orderBy.length > 0;
599
+ if (!shaped && !ordered) return { ...this.raw(entries), relationFetches: 0 };
600
+ rows = this.parse(entries);
601
+ if (ordered) rows = sortSql(rows, plan.orderBy!);
602
+ } else {
603
+ const hit = this.filtered(plan.table, plan.where, params, plan.orderBy, plan.limit, plan.offset);
604
+ if (!shaped) return { ...this.raw(hit.entries), relationFetches: 0 };
605
+ rows = hit.rows;
606
+ }
607
+ if (plan.select) rows = rows.map((row) => project(row, plan.select!));
608
+ const fetcher: RowFetcher = {
609
+ fetchRelation: (req) => {
610
+ this.relationFetches++;
611
+ return Promise.resolve(this.relationRows(req));
612
+ },
613
+ };
614
+ await resolveRelations(rows, plan.relations, fetcher);
615
+ return { ...toBytes(rows), relationFetches: this.relationFetches };
616
+ }
617
+
618
+ byIds(table: string, ids: string[], select?: string[], orderBy?: OrderBy): RowBytes {
619
+ const entries = this.findAll(table, windowOrder(ids));
620
+ const ordered = orderBy !== undefined && orderBy.length > 0;
621
+ if (!select && !ordered) return this.raw(entries);
622
+ let rows = this.parse(entries);
623
+ if (ordered) rows = sortSql(rows, orderBy!);
624
+ return toBytes(select ? rows.map((row) => project(row, select)) : rows);
625
+ }
626
+
627
+ get(table: string, id: string): { buf: ArrayBuffer | null; u8: boolean } {
628
+ const hit = this.store.get(table, id);
629
+ if (!hit || hit.entry.flags & FLAG_RAW) return { buf: null, u8: false };
630
+ return { buf: hit.body.buffer as ArrayBuffer, u8: (hit.entry.flags & FLAG_U8) !== 0 };
631
+ }
632
+
633
+ selectTable(
634
+ table: string,
635
+ where: WhereNode[] | undefined,
636
+ orderBy: OrderBy | undefined,
637
+ limit: number | undefined,
638
+ start: number | undefined
639
+ ): RowBytes {
640
+ return this.raw(this.filtered(table, where, {}, orderBy, limit, start).entries);
641
+ }
642
+
643
+ count(table: string, where: WhereNode[] | undefined): number {
644
+ if (!where || where.length === 0) return this.store.count(table);
645
+ return this.filtered(table, where, {}, undefined, undefined, undefined).rows.length;
646
+ }
647
+
648
+ // ---- relations -----------------------------------------------------------
649
+
650
+ relation(req: RelationFetch): RowBytes {
651
+ return toBytes(this.relationRows(req));
652
+ }
653
+
654
+ private relationRows(req: RelationFetch): Row[] {
655
+ const keys = [...new Set(req.keys.map(stableKey))];
656
+ let rows: Row[];
657
+ if (req.matchField === 'id') {
658
+ // Probed in id order, as an index lookup would return them.
659
+ rows = this.parse(this.findAll(req.table, keys.sort(cmpText)));
660
+ } else {
661
+ const indexKeys = keys.map((key) => indexKey(key));
662
+ if (isUserTable(req.table) && indexKeys.every((k) => k !== null) && this.ensureIndex(req.table, req.matchField, true)) {
663
+ const ids: string[] = [];
664
+ for (const key of indexKeys) for (const id of this.lookup(req.table, req.matchField, key!)) ids.push(id);
665
+ rows = this.parse(this.findAll(req.table, ids.sort(cmpText)));
666
+ } else {
667
+ // Only string values match: the keys are record ids, and SQL's `IN`
668
+ // over text keys never matches a number either.
669
+ const wanted = new Set(keys);
670
+ const hits: { row: Row; at: number }[] = [];
671
+ this.scan(req.table, (row, at) => {
672
+ const value = walk(row, req.matchField);
673
+ if (typeof value === 'string' && wanted.has(value)) hits.push({ row, at });
674
+ });
675
+ rows = hits.sort((a, b) => a.at - b.at).map((h) => h.row);
676
+ }
677
+ }
678
+ const test = compileWhere(req.where, {});
679
+ if (test) rows = rows.filter(test);
680
+ if (req.orderBy && req.orderBy.length > 0) rows = sortSql(rows, req.orderBy);
681
+ return req.select ? rows.map((row) => project(row, req.select!)) : rows;
682
+ }
683
+
684
+ // ---- writes --------------------------------------------------------------
685
+
686
+ /**
687
+ * Apply one batch from the page. A merge reads the stored row, folds the
688
+ * patch in and writes the result; a row that is not there yet takes the
689
+ * patch's insert text as it came. Index entries of the app's tables move in
690
+ * the same batch as the rows they point at.
691
+ */
692
+ write(ops: WireOp[], buf: ArrayBuffer | null, sync: boolean): void {
693
+ const bytes = buf ? new Uint8Array(buf) : new Uint8Array(0);
694
+ const out: StoreOp[] = [];
695
+ // What this batch has already done to a row, for a later op on the same row.
696
+ const pending = new Map<string, Uint8Array | null>();
697
+ const cleared = new Set<string>();
698
+ // The app's rows as this batch leaves them, for an index that appears partway through it.
699
+ const touched = new Map<string, Map<string, Row | null>>();
700
+ const added: [string, string][] = [];
701
+ const note = (table: string, id: string, row: Row | null): void => {
702
+ let rows = touched.get(table);
703
+ if (!rows) touched.set(table, (rows = new Map()));
704
+ rows.set(id, row);
705
+ };
706
+ for (const op of ops) {
707
+ const table = op[1];
708
+ const user = isUserTable(table);
709
+ if (op[0] === 'clear') {
710
+ out.push({ t: 'clear', table });
711
+ if (user) for (const field of this.fieldsOf(table)) out.push({ t: 'clear', table: indexTable(table, field) });
712
+ cleared.add(table);
713
+ for (const key of [...pending.keys()]) if (key.startsWith(table + '\n')) pending.delete(key);
714
+ touched.get(table)?.clear();
715
+ continue;
716
+ }
717
+ const id = op[2];
718
+ const key = table + '\n' + id;
719
+ const stored = (): Uint8Array | null => {
720
+ const earlier = pending.get(key);
721
+ if (earlier !== undefined) return earlier;
722
+ return cleared.has(table) ? null : (this.store.get(table, id)?.body ?? null);
723
+ };
724
+ if (op[0] === 'del') {
725
+ const fields = user ? this.fieldsOf(table) : [];
726
+ if (fields.length > 0) {
727
+ const old = stored();
728
+ if (old) this.reindex(table, id, fields, this.keysOf(fields, JSON.parse(decoder.decode(old)) as Row), this.keysOf(fields, null), out);
729
+ }
730
+ out.push({ t: 'del', table, id });
731
+ pending.set(key, null);
732
+ if (user) note(table, id, null);
733
+ continue;
734
+ }
735
+ const insert = bytes.subarray(op[5], op[5] + op[6]);
736
+ let body = insert;
737
+ let rv = op[3];
738
+ let flags = op[4];
739
+ let next: Row | null = null;
740
+ let fields = user ? this.fieldsOf(table) : [];
741
+ const old = op[0] === 'merge' || fields.length > 0 ? stored() : null;
742
+ const previous = old ? (JSON.parse(decoder.decode(old)) as Row) : null;
743
+ // Read before the merge below reuses the object.
744
+ const before = this.keysOf(fields, previous);
745
+ if (op[0] === 'merge' && previous) {
746
+ const patch = op[8] > 0 ? bytes.subarray(op[7], op[7] + op[8]) : insert;
747
+ next = mergePatch(previous, JSON.parse(decoder.decode(patch))) as Row;
748
+ const text = JSON.stringify(next);
749
+ body = encoder.encode(text);
750
+ rv = Number(next?._00_rv) || 0;
751
+ flags = text.includes(U8_TAG) ? FLAG_U8 : 0;
752
+ } else if (user) {
753
+ next = JSON.parse(decoder.decode(insert)) as Row;
754
+ }
755
+ if (user && next) {
756
+ const known = added.length;
757
+ this.discover(table, next, added);
758
+ if (added.length > known) {
759
+ // An index born on this row comes after the ones there were, and has no old entry for it.
760
+ fields = this.fieldsOf(table);
761
+ while (before.length < fields.length) before.push(null);
762
+ }
763
+ this.reindex(table, id, fields, before, this.keysOf(fields, next), out);
764
+ note(table, id, next);
765
+ }
766
+ out.push({ t: 'put', table, id, rv, flags, body });
767
+ pending.set(key, body);
768
+ }
769
+ // An index that appeared in this batch still lacks the rows that were there before it.
770
+ for (const [table, field] of added) {
771
+ const index = indexTable(table, field);
772
+ const mine = touched.get(table);
773
+ const put = (id: string, row: Row): void => {
774
+ const k = indexKey(extract(row, field));
775
+ if (k !== null) out.push({ t: 'put', table: index, id: k + SEP + id, rv: 0, flags: FLAG_RAW, body: NO_ENTRY });
776
+ };
777
+ if (!cleared.has(table)) {
778
+ this.scan(table, (row) => {
779
+ const id = String(row.id);
780
+ if (!mine?.has(id)) put(id, row);
781
+ });
782
+ }
783
+ if (mine) for (const [id, row] of mine) if (row) put(id, row);
784
+ }
785
+ if (added.length > 0) out.push(this.registryOp());
786
+ this.store.write(out, sync);
787
+ }
788
+
789
+ // ---- the rest ------------------------------------------------------------
790
+
791
+ versions(tables: string[]): Record<string, [string, number][]> {
792
+ const out: Record<string, [string, number][]> = {};
793
+ for (const table of tables) out[table] = this.store.versions(table);
794
+ return out;
795
+ }
796
+
797
+ /** Set the cached `_00_rv` of every row of `tables` to 0, except `keep`. Returns the rows rewritten. */
798
+ resetVersions(tables: string[], keep: string[]): number {
799
+ const kept = new Set(keep);
800
+ const out: StoreOp[] = [];
801
+ let rewritten = 0;
802
+ for (const table of tables) {
803
+ const fields = isUserTable(table) ? this.fieldsOf(table) : [];
804
+ this.scan(table, (row, at, run) => {
805
+ const rv = extract(row, '_00_rv');
806
+ if (rv === null || rv === 0 || kept.has(String(row.id))) return;
807
+ const id = runId(run, at);
808
+ const before = this.keysOf(fields, row);
809
+ row._00_rv = 0;
810
+ this.reindex(table, id, fields, before, this.keysOf(fields, row), out);
811
+ out.push({ t: 'put', table, id, rv: 0, flags: run.flags[at], body: encoder.encode(JSON.stringify(row)) });
812
+ rewritten++;
813
+ });
814
+ }
815
+ this.store.write(out);
816
+ return rewritten;
817
+ }
818
+
819
+ /** A raw blob and the JSON row beside it: the circuit snapshot's two halves. */
820
+ getBlob(table: string, key: string): { bytes: ArrayBuffer | null; meta: string | null } {
821
+ const blob = this.store.get(table, key);
822
+ const meta = this.store.get(table, `${key}:meta`);
823
+ return {
824
+ bytes: blob ? (blob.body.buffer as ArrayBuffer) : null,
825
+ meta: meta ? decoder.decode(meta.body) : null,
826
+ };
827
+ }
828
+
829
+ putBlob(table: string, key: string, bytes: ArrayBuffer, meta: string): void {
830
+ this.store.write([
831
+ { t: 'put', table, id: key, rv: 0, flags: FLAG_RAW, body: new Uint8Array(bytes) },
832
+ { t: 'put', table, id: `${key}:meta`, rv: 0, flags: FLAG_RAW, body: encoder.encode(meta) },
833
+ ]);
834
+ }
835
+
836
+ deleteBlob(table: string, key: string): void {
837
+ this.store.write([
838
+ { t: 'del', table, id: key },
839
+ { t: 'del', table, id: `${key}:meta` },
840
+ ]);
841
+ }
842
+
843
+ /**
844
+ * The tables to read ahead, in the order worth reading them: the app's own
845
+ * first (its first query is by id or over a window of one of them), then the
846
+ * indexes over them.
847
+ */
848
+ warmOrder(): string[] {
849
+ const names = this.store.tableNames();
850
+ return [...names.filter((name) => !name.startsWith(HIDDEN)), ...names.filter((name) => name.startsWith(HIDDEN))];
851
+ }
852
+
853
+ /** Read every table's index into memory, so the first query does not wait for it. */
854
+ warm(): void {
855
+ for (const table of this.warmOrder()) this.store.ordered(table);
856
+ }
857
+ }
858
+
859
+ /**
860
+ * The ids of a window, each once, in the order the SQLite engine restores:
861
+ * by position in the list, a repeated id counting where it appears last.
862
+ */
863
+ function windowOrder(keys: string[]): string[] {
864
+ const position = new Map(keys.map((key, i) => [key, i]));
865
+ if (position.size === keys.length) return keys;
866
+ return [...position.keys()].sort((a, b) => position.get(a)! - position.get(b)!);
867
+ }
868
+
869
+ /** Row positions of a run ordered by where their bodies lie, skipping raw blobs. */
870
+ function byOffset(run: Run): Uint32Array {
871
+ let json = 0;
872
+ let ascending = true;
873
+ let last = -1;
874
+ for (let i = 0; i < run.n; i++) {
875
+ if (run.flags[i] & FLAG_RAW) continue;
876
+ json++;
877
+ if (run.off[i] < last) ascending = false;
878
+ last = run.off[i];
879
+ }
880
+ const order = new Uint32Array(json);
881
+ let k = 0;
882
+ for (let i = 0; i < run.n; i++) if (!(run.flags[i] & FLAG_RAW)) order[k++] = i;
883
+ // A compacted table already lies in id order.
884
+ if (!ascending) order.sort((a, b) => run.off[a] - run.off[b]);
885
+ return order;
886
+ }
887
+
888
+ /**
889
+ * Version of what the page and the worker say to each other. A worker that
890
+ * answers `open` with another number was built from another release (a
891
+ * prewarmed worker started from a URL remembered across a deploy) and is
892
+ * replaced by a fresh one.
893
+ */
894
+ export const ROWS_PROTOCOL = 1;
895
+
896
+ /** Data ops a follower tab may send over its port; the rest belong to the owner. */
897
+ export const ROWS_CLIENT_OPS: ReadonlySet<string> = new Set([
898
+ 'select',
899
+ 'by-ids',
900
+ 'get',
901
+ 'relation',
902
+ 'select-table',
903
+ 'count',
904
+ 'write',
905
+ 'versions',
906
+ 'reset-versions',
907
+ 'tables',
908
+ 'blob-get',
909
+ 'blob-put',
910
+ 'blob-del',
911
+ ]);
912
+
913
+ export interface RowsReply {
914
+ result: Record<string, unknown>;
915
+ transfer?: Transferable[];
916
+ }
917
+
918
+ const withBytes = (rows: { buf: ArrayBuffer | null; u8: boolean }, extra: Record<string, unknown> = {}): RowsReply => ({
919
+ result: { ...rows, ...extra },
920
+ transfer: rows.buf ? [rows.buf] : undefined,
921
+ });
922
+
923
+ /**
924
+ * Answer one data message. Kept apart from the worker so the engine's tests
925
+ * can run the same code in-process. Returns `null` for a message it does not
926
+ * know.
927
+ */
928
+ /** The ops a reader store answers: the ones that leave the store as it was. */
929
+ export const ROWS_READER_OPS: ReadonlySet<string> = new Set([
930
+ 'select',
931
+ 'by-ids',
932
+ 'get',
933
+ 'relation',
934
+ 'select-table',
935
+ 'count',
936
+ 'versions',
937
+ 'tables',
938
+ 'blob-get',
939
+ ]);
940
+
941
+ const READER_ATTEMPTS = 4;
942
+
943
+ /**
944
+ * {@link handleRowsOp} on a store opened as a reader, beside its writer. The
945
+ * reader takes in what was appended, answers, and then checks that the file
946
+ * it read is still the live one (`RowStore.current`): a compaction that
947
+ * emptied it meanwhile means the answer was read from bytes that are gone,
948
+ * and it is read again from the file the rows moved to.
949
+ */
950
+ // oxlint-disable-next-line typescript/no-explicit-any
951
+ export async function handleReaderOp(exec: RowsExec, store: RowStore, type: string, payload: any): Promise<RowsReply | null> {
952
+ if (!ROWS_READER_OPS.has(type)) throw new Error(`rows reader: op ${type} is not a read`);
953
+ for (let attempt = 1; ; attempt++) {
954
+ store.refresh();
955
+ exec.syncRegistry();
956
+ try {
957
+ // oxlint-disable-next-line no-await-in-loop
958
+ const reply = await handleRowsOp(exec, store, type, payload);
959
+ if (store.current()) return reply;
960
+ } catch (error) {
961
+ // Rows read from an emptied file do not parse. Only when the file is
962
+ // still live is the failure the read's own.
963
+ if (store.current()) throw error;
964
+ }
965
+ if (attempt === READER_ATTEMPTS) throw new Error('rows reader: the store kept moving under the read');
966
+ }
967
+ }
968
+
969
+ // oxlint-disable-next-line typescript/no-explicit-any
970
+ export async function handleRowsOp(exec: RowsExec, store: RowStore, type: string, payload: any): Promise<RowsReply | null> {
971
+ switch (type) {
972
+ case 'select': {
973
+ const { relationFetches, ...rows } = await exec.select(payload.plan, payload.params ?? {});
974
+ return withBytes(rows, { relationFetches });
975
+ }
976
+ case 'by-ids':
977
+ return withBytes(exec.byIds(payload.table, payload.ids, payload.select, payload.orderBy));
978
+ case 'get':
979
+ return withBytes(exec.get(payload.table, payload.id));
980
+ case 'relation':
981
+ return withBytes(exec.relation(payload));
982
+ case 'select-table':
983
+ return withBytes(exec.selectTable(payload.table, payload.where, payload.orderBy, payload.limit, payload.start));
984
+ case 'count':
985
+ return { result: { n: exec.count(payload.table, payload.where) } };
986
+ case 'write':
987
+ exec.write(payload.ops, payload.buf ?? null, payload.sync === true);
988
+ return { result: {} };
989
+ case 'versions':
990
+ return { result: { versions: exec.versions(payload.tables) } };
991
+ case 'reset-versions':
992
+ return { result: { rows: exec.resetVersions(payload.tables, payload.keep ?? []) } };
993
+ case 'tables':
994
+ return { result: { tables: visibleTables(store) } };
995
+ case 'blob-get': {
996
+ const blob = exec.getBlob(payload.table, payload.key);
997
+ return { result: blob, transfer: blob.bytes ? [blob.bytes] : undefined };
998
+ }
999
+ case 'blob-put':
1000
+ exec.putBlob(payload.table, payload.key, payload.bytes, payload.meta);
1001
+ return { result: {} };
1002
+ case 'blob-del':
1003
+ exec.deleteBlob(payload.table, payload.key);
1004
+ return { result: {} };
1005
+ default:
1006
+ return null;
1007
+ }
1008
+ }
1009
+
1010
+ /**
1011
+ * The log a store may carry past its last checkpoint while it is busy: what
1012
+ * the next open would have to replay if the tab died right now. Past either
1013
+ * bound the index is persisted at once instead of at the next quiet moment.
1014
+ */
1015
+ export const CHECKPOINT_TAIL_BYTES = 8 << 20;
1016
+ export const CHECKPOINT_TAIL_OPS = 20_000;
1017
+
1018
+ /**
1019
+ * What the store should do now that it has a quiet moment: persist its index
1020
+ * when writes are waiting on it, compact when dead bytes outweigh live ones.
1021
+ */
1022
+ export function maintenance(stats: StoreStats): 'checkpoint' | 'compact' | null {
1023
+ if (stats.tailBytes > 0) return 'checkpoint';
1024
+ // Dead bytes may reach half the live ones: the file is at most 1.5 times its rows.
1025
+ if (stats.garbageBytes > Math.max(4 << 20, stats.liveBytes / 2)) return 'compact';
1026
+ return null;
1027
+ }