@spooky-sync/core 1.0.0-beta.10 → 1.0.0-beta.12
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 +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +328 -72
- package/dist/rows-worker.js +95 -3
- package/dist/types.d.ts +2 -0
- package/package.json +3 -3
- package/src/client/sp00ky-client.ts +5 -4
- package/src/services/database/rows-cache-engine.test.ts +573 -3
- package/src/services/database/rows-cache-engine.ts +349 -67
- package/src/services/database/rows-prewarm.ts +29 -3
- package/src/services/database/rows-worker.ts +22 -3
- package/src/services/database/rows-yield.test.ts +141 -0
- package/src/services/database/rows-yield.ts +92 -0
- package/src/types.ts +2 -0
package/AGENTS.md
CHANGED
|
@@ -65,7 +65,7 @@ re-materialized from state, never patched in place.
|
|
|
65
65
|
- **`db.preload` is a registered query.** Resolved before on this device (a `_00_view` row exists) it returns at once; never resolved it waits until the server's membership and every body are local. A signed-out session without `enableAnonymousLiveQueries` is never sent membership, so its preload returns at once instead of blocking. It holds no subscriber, so it is evicted a ttl after registration unless a view mounts the same query. `refresh`/`staleTime` are ignored; pass `signal` to abort a cold wait.
|
|
66
66
|
- **A never-resolved query paints only vouched rows.** Before the server answers (`cold`), the local predicate scan shows a cached body only if some `_00_view` row names it (as a member or subquery child) or a write for it is in flight. A body no view names is an orphan (deleted upstream while nothing watched it): it stays hidden, and the GC deletes it 30 s after boot and then hourly. A `_00_view` row no query has resolved for 14 days is retired by the same sweep, so that query paints cold again.
|
|
67
67
|
- **`database.store` defaults to `'memory'`.** `'indexeddb'` keeps one IndexedDB database per user bucket (`sp00ky-<bucket>`) and needs `@surrealdb/wasm` >= 3.1.0: the 3.0.x engine opened the store but failed every write (`An IndexedDB error occured: idb error`), so each session fell back to memory. 3.1.0 ships the engine as `@surrealdb/wasm-native`; a Vite app lists it in `optimizeDeps.exclude` next to `@surrealdb/wasm`. A store that still cannot open after a drop runs the session in memory (error log `falling back to in-memory`). Under `localEngine: 'sqlite'` or `'rows'`, `'indexeddb'` means OPFS.
|
|
68
|
-
- **`localEngine: 'rows'` is the client's own row store (experimental).** `services/database/rows-store.ts` (one append-only file per bucket on OPFS sync access handles: hashed batches, a flat typed-array index per table, checkpoints, compaction; opening replays only the writes since the last checkpoint), `rows-exec.ts` (the verbs; bodies are the JSON text the SQLite engine stores and cross the worker as transferred bytes, parsed once on the page), `rows-worker.ts`, `rows-cache-engine.ts` (extends `SqliteCacheEngine` for the op queue, epoch fencing and shared-tabs roles, replaces everything that renders SQL). Same answers as `'sqlite'`, checked against real SQLite in `rows-exec.integration.test.ts`; where SQL leaves an order open (ties on `orderBy`, children of an unordered `.related()`) it returns id order. Writes to `ROWS_DURABLE_TABLES` (outbox, pending writes, failed mutations, local CRDT edits) are flushed before they resolve, everything else within ~100 ms. Works with `sharedTabs`. A change to how the SQLite engine filters, orders or merges needs the same change in `rows-exec.ts`. Secondary indexes are hidden tables in the same store (ids `value\0rowId`, empty bodies, written in the row's own batch): one per field that holds record links (found as rows are written), one per field a query filters on with `=` (built on first use; a field with fewer than 8 distinct values is left to scans); the registry is a row of the hidden meta table. `prewarmRows()` / `ROWS_PREWARM_SNIPPET` start the worker and open the last bucket from the page head, before the bundle; the engine adopts that worker (`createTransport`), takes the answer the worker already gave to that `open` when there is one (so its first read is one trip, not two) and replaces the worker when the answer names another `ROWS_PROTOCOL`. The worker's `warm` reads one table's index per turn and only after 15 ms without an op (`warmStep`): read all at once, it made the page's first read wait 10 ms. Bump `ROWS_PROTOCOL` when the worker's messages change. Read ahead (`rows-prewarm.ts`, a file without imports so a build script can load the snippet from it): the engine saves a session's first reads (`select` / `by-ids` / `relation` within 3 s of connecting, JSON-safe payloads only, at most 24) in the prewarm record; the next load's prewarm sends them under ids `<= ROWS_AHEAD_ID` (the worker refuses anything but those reads there), and `createTransport` answers a matching read from the reply already in the page (`ReadAhead`), so the client's first reads cost no trip. Answers are dropped on the first op that is not a read, on an open of another bucket
|
|
68
|
+
- **`localEngine: 'rows'` is the client's own row store (experimental).** `services/database/rows-store.ts` (one append-only file per bucket on OPFS sync access handles: hashed batches, a flat typed-array index per table, checkpoints, compaction; opening replays only the writes since the last checkpoint), `rows-exec.ts` (the verbs; bodies are the JSON text the SQLite engine stores and cross the worker as transferred bytes, parsed once on the page), `rows-worker.ts`, `rows-cache-engine.ts` (extends `SqliteCacheEngine` for the op queue, epoch fencing and shared-tabs roles, replaces everything that renders SQL). Same answers as `'sqlite'`, checked against real SQLite in `rows-exec.integration.test.ts`; where SQL leaves an order open (ties on `orderBy`, children of an unordered `.related()`) it returns id order. Writes to `ROWS_DURABLE_TABLES` (outbox, pending writes, failed mutations, local CRDT edits) are flushed before they resolve, everything else within ~100 ms. Works with `sharedTabs`. A change to how the SQLite engine filters, orders or merges needs the same change in `rows-exec.ts`. Secondary indexes are hidden tables in the same store (ids `value\0rowId`, empty bodies, written in the row's own batch): one per field that holds record links (found as rows are written), one per field a query filters on with `=` (built on first use; a field with fewer than 8 distinct values is left to scans); the registry is a row of the hidden meta table. `prewarmRows()` / `ROWS_PREWARM_SNIPPET` start the worker and open the last bucket from the page head, before the bundle; the engine adopts that worker (`createTransport`), takes the answer the worker already gave to that `open` when there is one (so its first read is one trip, not two) and replaces the worker when the answer names another `ROWS_PROTOCOL`. The worker's `warm` reads one table's index per turn and only after 15 ms without an op (`warmStep`): read all at once, it made the page's first read wait 10 ms. Bump `ROWS_PROTOCOL` when the worker's messages change. Read ahead (`rows-prewarm.ts`, a file without imports so a build script can load the snippet from it): the engine saves a session's first reads (`select` / `by-ids` / `relation` within 3 s of connecting, JSON-safe payloads only, at most 24) in the prewarm record; the next load's prewarm sends them under ids `<= ROWS_AHEAD_ID` (the worker refuses anything but those reads there), and `createTransport` answers a matching read from the reply already in the page (`ReadAhead`), so the client's first reads cost no trip. Answers are dropped on the first op that is not a read, on an open of another bucket, and 3 s after adoption. With `sharedTabs`: a tab's startup reads are recorded once per session whatever its role; the tab that becomes leader on the worker its head script started keeps the answers through the open under the role lock (the worker keeps the store it has open; the answer to the prewarm's own `open` is never reused there, the open is what takes the lock), and drops them when a follower's port is handed to the worker (`exposeClientPort`). A prewarm cannot know whether its tab will lead, so a store opened ahead and not yet claimed by its page (`AheadStore` in `rows-yield.ts`, kept out of `rows-worker.ts` so it has tests; any message with a positive id claims) is given up when a leading worker asks on the `ROWS_YIELD_CHANNEL` BroadcastChannel, which a worker opening under a role lock does after each failed attempt; the worker then says so under the prewarm open's id and the page forgets that open's answer and everything read ahead (the handler in `prewarmRows` and the snippet before adoption, `ReadAhead.arrived` after): the tab that got the store writes to it. Without this the elected tab's ten attempts all failed against the handles of a worker nobody used. `PaintCache` (`database.paintCache`) keeps the reads of a session's first 3 s in localStorage; `engine.peekSelect` / `peekByIds` (optional on `LocalStore`) return that copy synchronously before the store is open, a write to any table it read drops it, the next read of the same request takes it again. A peek is for painting, the read that follows is the answer. The cache is one for all tabs of a bucket: every table has a mark in localStorage (`sp00ky.paint.<bucket>.t.<table>`) that a writing tab replaces before its write is sent and again once the store answered (`touch(tables)`, `touch(tables, true)`; only an engine built with `shared`, a tab alone in the store leaves no marks and does no storage I/O per write, dropping its own copies is enough there); a copy stores the marks it was read under and `get` hands it out only while they stand; `stamp` counts a tab's own writes plus every foreign mark change it sees, so a read overtaken by another tab's write is not kept, while the tab's own second mark does not fail its reads queued behind the write. `flush` skips copies whose marks moved, merges the other tabs' index, removes what no longer stands (copies in another release's layout, and copies the index lost track of, found by a scan of the bucket's keys) and keeps one budget for the bucket; a mark that does not fit (quota) makes room by dropping the bucket's copies. Roles start it through `paint.adopt` (first hand-over of a bucket only), and a store that fell back to memory keeps nothing (`paint.stop`). The client uses it for a query's first render: `materialize` names its read by the query's view key (`fx.local.select(plan, params, paintKey)`, so the copy kept is the query's latest render whatever its id set was), and `registerLocal` seeds a new entry's `records` from `fx.local.peekSelect` with the same render set and the same cold filter (`renderRead` in `query/materialize.ts`), leaving it unnotified and unanswered; `materialize` then confirms or replaces the rows. Before `init()`: `Sp00kyClient.peekQuery(finalQuery)` hands those rows back synchronously on a client that is not open (the bindings' `eager` providers render with them). For that the paint key is `paintKeyOf(def, ids)` in `query/materialize.ts`, the query's text and parameters (no digest: a component asks while it renders), with a `\ncold` suffix for a cold scan so a closed client, which cannot apply the cold filter, only ever gets a membership render's rows; and the constructor tells the engine which bucket boot will open (`expectBucket(readBootBucketHint() ?? 'anon')`). Calls made before `init()` finished wait for it instead of failing (`opened()`: `query().run()`, `queryRaw`, `preload`, `create` / `update` / `delete`, channel writes, `openCrdtField`, every `BucketHandle` method; the feature flag and app release registrations wait while there is no session yet), and reject with its error if it fails; `whenReady()` is the same promise for apps. `followerReads: 'direct'` (with `sharedTabs`): the leader's worker opens the files with `readwrite-unsafe` handles (`share` in the `open` payload), and a follower starts a worker of its own on a `RowStore` in reader mode (`RowStore.open(io, { reader: true })`: never writes, `refresh()` replays what was appended, `current()` after a read says whether a compaction moved the file under it; `handleReaderOp` retries then) and routes `ROWS_READER_OPS` to it (`rawCall` override), everything else to the leader's port; any failure of the reader falls back to the port. A reader builds no index (`RowsExec` `readOnly`) and re-reads the registry when the leader rewrites it. `dist/rows-worker.js` is built on its own (third tsdown config) so it is one self-contained file starting with the V8 compile hint `//# allFunctionsCalledOnLoad`. Benchmark: `apps/storage-bench`.
|
|
69
69
|
- **`database.workers` lets the app start the local store's worker.** Only for a bundler that does not bundle a `new Worker(new URL(...))` inside a dependency, i.e. the Angular CLI: `workers.surreal` returns a module worker whose entry is `import '@surrealdb/wasm/worker'`, `workers.sqlite` (with `localEngine: 'sqlite'`) one whose entry is `import '@spooky-sync/core/sqlite-worker'`, `workers.rows` (with `localEngine: 'rows'`) one whose entry is `import '@spooky-sync/core/rows-worker'` (exports kept in `sideEffects` so the bare import survives tree shaking). Unset, the built-in worker expressions run as before; Vite / Rollup / webpack apps leave it unset.
|
|
70
70
|
- **Boot owns the first identity.** The facade subscribes to auth with `immediate: false`: boot opens the bucket the hint names and `auth.restoreSession` announces the user. `LocalDatabaseService.switchStore` also waits for an in-flight `connect`, and lets statements already past the gate finish before it closes a client: the 3.1 engine streams results from its worker, and a statement whose client closed under it stayed pending until its 30 s deadline with every later local statement queued behind it.
|
|
71
71
|
- **A rejected write is not lost.** Application errors roll the local row back (create/update/delete) and move the mutation to `_00_failed_mutations`; the tray API above lists, retries (as a fresh write) or discards it. Network errors keep the row queued, and so does a write SurrealDB refused only because sp00ky's own `_00_` ingest event could not post to the scheduler/SSP (refused, past its TIMEOUT, DNS, 5xx/408/429; `SP00KY_EVENT_POST_FAILED` in `utils/error-classification.ts`).
|
package/dist/index.d.ts
CHANGED
|
@@ -2213,8 +2213,9 @@ declare class Sp00kyClient<S extends SchemaStructure> {
|
|
|
2213
2213
|
* handed back at once and with no need for `init()` to have run: something
|
|
2214
2214
|
* for a component to render on its first pass, where it would have rendered
|
|
2215
2215
|
* an empty list. `null` when the local store keeps no such copy (only
|
|
2216
|
-
* `localEngine: 'rows'` with its paint cache does,
|
|
2217
|
-
*
|
|
2216
|
+
* `localEngine: 'rows'` with its paint cache does), or has none for this
|
|
2217
|
+
* query: it never rendered at startup, or a tab has written to one of its
|
|
2218
|
+
* tables since.
|
|
2218
2219
|
*
|
|
2219
2220
|
* They are rows to paint from, not a result. The query still has to be run
|
|
2220
2221
|
* and subscribed to; what that delivers is the answer, and it replaces these
|