@pgxsinkit/client 0.1.53 → 0.2.1
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/README.md +22 -0
- package/dist/adoption.d.ts +118 -0
- package/dist/adoption.d.ts.map +1 -0
- package/dist/boot-report.d.ts +54 -15
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/convergence.d.ts +2 -1
- package/dist/convergence.d.ts.map +1 -1
- package/dist/export-store.d.ts +1 -1
- package/dist/export-store.d.ts.map +1 -1
- package/dist/index.d.ts +286 -51
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4795 -1519
- package/dist/index.js.map +34 -24
- package/dist/live-rows-sql.d.ts +1 -1
- package/dist/local-store.d.ts +16 -31
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +4 -4
- package/dist/mutation.d.ts +18 -15
- package/dist/mutation.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +51 -0
- package/dist/opfs-effects.d.ts.map +1 -0
- package/dist/placement-probe.d.ts +75 -0
- package/dist/placement-probe.d.ts.map +1 -0
- package/dist/schema.d.ts +11 -16
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +77 -0
- package/dist/store-boot.d.ts.map +1 -0
- package/dist/store-lifecycle.d.ts +153 -0
- package/dist/store-lifecycle.d.ts.map +1 -0
- package/dist/store-meta.d.ts +190 -0
- package/dist/store-meta.d.ts.map +1 -0
- package/dist/store-path.d.ts +77 -7
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/shape-inbox.d.ts +1 -1
- package/dist/sync/types.d.ts +3 -3
- package/dist/testing.js.map +3 -3
- package/dist/worker/attach-sync-client.d.ts +300 -16
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +164 -23
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/election-coordinator.d.ts +95 -0
- package/dist/worker/election-coordinator.d.ts.map +1 -0
- package/dist/worker/engine-control.d.ts +266 -0
- package/dist/worker/engine-control.d.ts.map +1 -0
- package/dist/worker/engine-router.d.ts +75 -0
- package/dist/worker/engine-router.d.ts.map +1 -0
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +47 -31
- package/dist/worker/protocol.d.ts.map +1 -1
- package/dist/worker/sw-placement.d.ts +37 -0
- package/dist/worker/sw-placement.d.ts.map +1 -0
- package/package.json +4 -3
- package/skills/core/SKILL.md +15 -12
- package/skills/operating/SKILL.md +142 -46
- package/src/adoption.ts +275 -0
- package/src/boot-report.ts +70 -17
- package/src/convergence.ts +2 -1
- package/src/export-store.ts +1 -1
- package/src/index.ts +1157 -115
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +18 -40
- package/src/local-tables.ts +2 -2
- package/src/mutation.ts +115 -53
- package/src/mutations-api.ts +3 -3
- package/src/opfs-effects.ts +160 -0
- package/src/placement-probe.ts +168 -0
- package/src/schema.ts +17 -22
- package/src/store-boot.ts +343 -0
- package/src/store-lifecycle.ts +227 -0
- package/src/store-meta.ts +459 -0
- package/src/store-path.ts +197 -22
- package/src/sync/apply.ts +63 -63
- package/src/sync/index.ts +2 -2
- package/src/sync/shape-inbox.ts +1 -1
- package/src/sync/types.ts +3 -3
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +1753 -102
- package/src/worker/define-sync-worker.ts +1034 -71
- package/src/worker/election-coordinator.ts +462 -0
- package/src/worker/engine-control.ts +379 -0
- package/src/worker/engine-router.ts +355 -0
- package/src/worker/live-query-manager.ts +4 -1
- package/src/worker/protocol.ts +46 -16
- package/src/worker/sw-placement.ts +64 -0
|
@@ -7,13 +7,14 @@ description: >-
|
|
|
7
7
|
cadence (writes flush on enqueue; the interval is only a fallback), serverless edge cold starts and
|
|
8
8
|
warming, cache-control:no-store on a same-origin Electric shape proxy, the browser HTTP/2 connection
|
|
9
9
|
budget, the edge worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport,
|
|
10
|
-
worker mode (defineSyncWorker/attachSyncClient —
|
|
11
|
-
|
|
12
|
-
storePath naming,
|
|
10
|
+
worker mode (defineSyncWorker/attachSyncClient — capability-driven Safari SharedWorker vs elected
|
|
11
|
+
Chromium/Firefox engine placement, factories, relocation outcomes, diagnostics, and the forwarded rail),
|
|
12
|
+
and the store lifecycle surface: storePath naming, backend-specific durability, adoption, supervised
|
|
13
|
+
destruction, exportStore/exportDiagnostics/exportData (+ drain guard), and restoreFrom.
|
|
13
14
|
metadata:
|
|
14
15
|
type: task
|
|
15
16
|
library: "@pgxsinkit/client"
|
|
16
|
-
library_version: "0.
|
|
17
|
+
library_version: "0.2.2"
|
|
17
18
|
source: https://pgxsinkit.github.io/start/operating-in-production/
|
|
18
19
|
---
|
|
19
20
|
|
|
@@ -96,18 +97,32 @@ no login screen to create ahead of, so START the mapped-store open at app bootst
|
|
|
96
97
|
memoised per userId so the provider's later open adopts it rather than opening a second instance. (Board
|
|
97
98
|
demo: `apps/board/src/board/store-registry.ts`, `store-prewarm.ts`.)
|
|
98
99
|
|
|
99
|
-
## Worker mode:
|
|
100
|
-
|
|
101
|
-
In a browser, prefer
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
100
|
+
## Worker mode: capability-placed off-thread engine (browser apps)
|
|
101
|
+
|
|
102
|
+
In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the
|
|
103
|
+
main thread. The SharedWorker is always the communication centre. There is no placement option: where the
|
|
104
|
+
engine runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an
|
|
105
|
+
unconditional real synchronous-handle open at boot chooses the engine home: real macOS/iOS Safari
|
|
106
|
+
runs the OPFS-repacked engine directly in the SharedWorker; Chromium/Firefox elect one tab-spawned
|
|
107
|
+
dedicated engine worker through Web Locks. Playwright WebKitGTK denies the handle in both worker kinds and
|
|
108
|
+
exercises the capability fallback to idb (declared durability kept, `storageBackend: "idbfs"` +
|
|
109
|
+
`storageFallbackReason` on the BootReport). The one opt-out is `storage.backend: "idbfs"` on the registry:
|
|
110
|
+
no probe, no election, the engine boots in the SharedWorker on idb. `createSyncClient` remains the bun/Node
|
|
111
|
+
mode and the main-thread idb fallback where SharedWorker is missing.
|
|
112
|
+
|
|
113
|
+
**Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
|
|
114
|
+
`defineSyncWorker({ registry, electricUrl, batchWriteUrl, … })` at module top level — no placement or
|
|
115
|
+
durability option (both are runtime/registry concerns); the registry is CODE, _imported_ by the worker
|
|
116
|
+
file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
|
|
117
|
+
`extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
|
|
118
|
+
`attachSyncClient({ worker, registry, getToken })`, where `worker` is a **factory**
|
|
119
|
+
(`worker: () => SharedWorker`), not an instance — a SharedWorker cannot be reconstructed from itself, and
|
|
120
|
+
the factory is what makes SharedWorker-death recovery a guarantee. The elected engine worker needs no
|
|
121
|
+
consumer wiring: the SharedWorker reports its own script URL and the winning tab constructs the engine as
|
|
122
|
+
`new Worker(reportedUrl, { type: "module" })`. Supply `createEngineWorker` ONLY as an override for entries
|
|
123
|
+
that cannot be reconstructed from their URL as a module worker (classic-script workers, `blob:`/`data:`
|
|
124
|
+
URLs, CSP); with no override and no derivable URL, attach fails with a typed error — never a silent
|
|
125
|
+
no-engine attach. The attached facade returns the same
|
|
111
126
|
client shape as `createSyncClient` (write API, one-shot Drizzle reads, live rows,
|
|
112
127
|
`ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine. One-shot
|
|
113
128
|
reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab and cross the bridge as ONE guarded
|
|
@@ -117,8 +132,10 @@ guarded here (the in-process unguarded escape hatch has no attach equivalent), a
|
|
|
117
132
|
`client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied (additive,
|
|
118
133
|
idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached catch-up
|
|
119
134
|
readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local
|
|
120
|
-
`pglite
|
|
121
|
-
|
|
135
|
+
`pglite` and `dropReadCache` are NOT proxied — there is no tab-local store and a cache rebuild is
|
|
136
|
+
engine-wide. `destroy()` IS proxied through a tab-side supervisor: it refuses peers with
|
|
137
|
+
`StoreDestroyRefusedError`, refuses owed journal rows unless `{ force: true }`, retires/closes the engine,
|
|
138
|
+
then runs a resumable deletion. The lazy lifecycle methods ARE proxied, but the engine is SHARED:
|
|
122
139
|
`desync(tableKey)` from one tab reverts the consistency group for EVERY attached tab (desync's group-wide
|
|
123
140
|
revert is engine-wide here — the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
|
|
124
141
|
instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a
|
|
@@ -129,10 +146,17 @@ attach client), it runs raw against the local store — bypasses the journal/ove
|
|
|
129
146
|
and never converges — so it is not an app-data read path. `replAdapter(client)` shapes it into the
|
|
130
147
|
`{ query, exec }` duck `@electric-sql/pglite-repl` needs (`client.pglite` stays unavailable). A worker file can bake multiple role variants and pick per attach via
|
|
131
148
|
`resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it). The
|
|
132
|
-
worker entry can also pass the app-level schema prepare hooks `prepareLocalDbBeforeSchema` / `
|
|
149
|
+
worker entry can also pass the app-level schema prepare hooks `prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema`
|
|
133
150
|
(app migrations, indexes, views) — same semantics as in-process, run in the worker around the registry schema
|
|
134
151
|
exec; they are worker-entry (not attach) options because a hook is a function and cannot cross the bridge.
|
|
135
152
|
|
|
153
|
+
**Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath`; use a distinct,
|
|
154
|
+
stable SharedWorker name for each store. Multiple stores may remain alive concurrently. Detach/stop the old
|
|
155
|
+
client and immediately attach the new identity's worker/store — never wait for the old SharedWorker, elected
|
|
156
|
+
engine, provision expiry, or `extendedLifetime` grace period. In worker mode `stop()` detaches only this tab;
|
|
157
|
+
in-process mode it disposes live queries before closing that client's engine and store. The board's
|
|
158
|
+
`userId → storeId` registry and real-browser identity-switch lane demonstrate this guarantee.
|
|
159
|
+
|
|
136
160
|
**Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
|
|
137
161
|
`notifyAuthChanged`; the worker uses the cached token and sends a pull-request only when a request finds it
|
|
138
162
|
near expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher,
|
|
@@ -141,6 +165,9 @@ so GoTrue refresh-token reuse detection can't be tripped by a second client.
|
|
|
141
165
|
**Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
|
|
142
166
|
schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
|
|
143
167
|
registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
|
|
168
|
+
Call `provisionSyncWorker` with the same `worker` factory as attach; an elected
|
|
169
|
+
Chromium/Firefox pre-open shares the tab's one election coordinator and auto-derives the engine from the
|
|
170
|
+
SharedWorker's own script URL (override with `createEngineWorker` only for non-module/underivable entries).
|
|
144
171
|
Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store, pass
|
|
145
172
|
`attachSyncClient({ freshStore: true })` (never for a mapped/returning store) and the worker overlaps the
|
|
146
173
|
shape catch-up with schema/journal/store-version recovery — far-user boot bounded by `max(create+schema,
|
|
@@ -163,6 +190,16 @@ shows nothing" is worker mode working as designed, not an absence of requests. I
|
|
|
163
190
|
rejections surface only there). Full model:
|
|
164
191
|
<https://pgxsinkit.github.io/concepts/worker-mode/>.
|
|
165
192
|
|
|
193
|
+
**Placement and relocation diagnostics.** Pull `client.bootReport()` and inspect `storageBackend`
|
|
194
|
+
(`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome`
|
|
195
|
+
(`shared-worker`/`elected-worker`/`in-process`), and `storageFallbackReason`; never user-agent-sniff the
|
|
196
|
+
backend. During elected-engine handoff, `EngineRelocatedError("not-dispatched")` is safe to retry, while
|
|
197
|
+
`"unknown"` means a dispatched mutation may already be journaled — inspect/reconcile, never retry blindly.
|
|
198
|
+
The opt-in `executionLimit` is disabled by default — no finite worst-case query duration exists and the
|
|
199
|
+
limit converts slow to terminated by policy, so enabling it must be a deliberate choice. It is
|
|
200
|
+
elected-only, and must match between the worker entry and every tab (`ExecutionLimitMismatchError`
|
|
201
|
+
otherwise); SW-direct Safari rejects it as unsupported.
|
|
202
|
+
|
|
166
203
|
## Live-query manager: dedup + keep-alive (ADR-0040)
|
|
167
204
|
|
|
168
205
|
Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
|
|
@@ -193,27 +230,39 @@ subscriber + row counts, setup/refresh timings, retention state — safe to log.
|
|
|
193
230
|
|
|
194
231
|
## Store naming, backups, and restore (ADR-0035/0036)
|
|
195
232
|
|
|
196
|
-
**Stores are named by a plain `storePath`, never a storage URL.** The backend is derived
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
`
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
`
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
233
|
+
**Stores are named by a plain `storePath`, never a storage URL.** The backend is derived, not named — a
|
|
234
|
+
capability-proven browser engine home uses OPFS-repacked; fixed worker mode, a denied engine home, and the
|
|
235
|
+
main-thread browser fallback use IndexedDB; bun/Node uses the filesystem. Anything containing `://` throws
|
|
236
|
+
`InvalidStorePathError` — do not "fix" that by re-adding a scheme, drop it. Memory-backed stores are
|
|
237
|
+
deliberately unreachable from the production API (durability semantics assume a persisted store): tests spread
|
|
238
|
+
`memoryStoreForTests("name")` from `@pgxsinkit/client/testing`, and a caller-owned
|
|
239
|
+
`pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined — a bare
|
|
240
|
+
`new PGlite()` — or `memory://`) is refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()`
|
|
241
|
+
is spread alongside. For browser store GC, get the IndexedDB name from
|
|
242
|
+
`storeIndexedDbDatabaseName(storePath)` — never assemble `/pglite/…` yourself.
|
|
243
|
+
|
|
244
|
+
**Relaxed durability is the default.** It is declared once, on the registry
|
|
245
|
+
(`SyncRegistryDefinition.storage.durability`, `"relaxed" | "strict"`) — never on a minting surface,
|
|
246
|
+
worker entry, or attach site, because durability follows the data, and one declaration binds every open
|
|
247
|
+
of every store minted from that registry. Its physical behavior is
|
|
248
|
+
backend-specific. On idb, relaxed returns before the whole-datadir snapshot flush and schedules it
|
|
249
|
+
asynchronously; strict pays that synchronous snapshot (~100–200ms per optimistic mutation). On
|
|
250
|
+
OPFS-repacked the host still awaits every sync: relaxed asserts VFS health and runs any due deferred repack
|
|
251
|
+
without an ordinary physical flush, while strict flushes arena data before metadata. Initialization,
|
|
252
|
+
repack activation, and open-state close use strict ordering in either OPFS mode. The resolved value is
|
|
253
|
+
stamped on the `boot pglite.create` rail line.
|
|
254
|
+
|
|
255
|
+
**The idb loss window.** On the idb backend the store is an in-memory FS with debounced whole-snapshot writes to
|
|
256
|
+
IndexedDB, so `relaxed`'s window is every write since the last COMPLETED snapshot (a whole-FS debounce). The
|
|
257
|
+
risk lands only on a crash before BOTH the journal rows reach the write API (~hundreds of ms after enqueue)
|
|
258
|
+
AND the scheduled snapshot lands — and synced tables are server-recoverable by construction, so only consumer
|
|
259
|
+
**local-only** tables carry real risk. `storage: { durability: "strict" }` on the registry is the escape
|
|
260
|
+
hatch if you keep unrecoverable local-only data and cannot accept that window; on idb it costs
|
|
261
|
+
~100–200ms/write (allowed and documented, not forbidden).
|
|
262
|
+
|
|
263
|
+
On OPFS-repacked, browser/worker termination recovers the longest valid stable metadata-log prefix; an
|
|
264
|
+
unflushed suffix may be absent. A returned strict boundary is stable under that browser-failure model. Do
|
|
265
|
+
not generalize this to power loss, media failure, or external store edits.
|
|
217
266
|
|
|
218
267
|
**Three exports, named by purpose, all returning `{ file, report }`** (report = phase timings + a
|
|
219
268
|
`MutationDiagnostics` snapshot, BootReport-style). They work identically on the in-process client and the
|
|
@@ -237,14 +286,61 @@ serialise through one lifecycle slot: a concurrent call rejects immediately with
|
|
|
237
286
|
(no queueing — retry after the holder settles). Ephemeral (`pg_temp`) content is never in any artefact.
|
|
238
287
|
|
|
239
288
|
**Restore** = `createSyncClient({ restoreFrom: backupFile, … })` (or `attachSyncClient` — the tarball rides
|
|
240
|
-
the boot attach), ONLY into a store path that does not exist
|
|
241
|
-
overwrite path is a deliberate `destroy()` first).
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
289
|
+
the boot attach), ONLY into a store path that does not exist in EITHER idb or OPFS
|
|
290
|
+
(`RestoreTargetExistsError` otherwise; the overwrite path is a deliberate `destroy()` first). Recovered
|
|
291
|
+
journal rows are quarantined because the write path has no mutation dedupe. A dirty-journal restore stays
|
|
292
|
+
offline for inspection; a clean-journal restore may honor the normal online options immediately. Inspect
|
|
293
|
+
`diagnostics()`, resolve quarantined rows via `discardQuarantined` (+ re-author if wanted), then reboot the
|
|
294
|
+
persisted store normally. Consumer docs:
|
|
246
295
|
<https://pgxsinkit.github.io/concepts/export-and-restore/>.
|
|
247
296
|
|
|
297
|
+
**Adoption.** An existing idb store is authoritative and is never silently replaced by a newly capable
|
|
298
|
+
OPFS home. Automatic adoption is default-off and requires the worker-entry declaration
|
|
299
|
+
`adoption: "server-reconstructible"`; only a drained journal, authorized online reconstruction, and a
|
|
300
|
+
returned strict barrier permit the idb predecessor to be deleted. `adoptStore()` is the manual
|
|
301
|
+
creation-path equivalent and refuses a live store with `StoreInUseError`.
|
|
302
|
+
|
|
303
|
+
**Resetting and deleting stores (ADR-0050).** Three non-interchangeable levers — pick by what you keep
|
|
304
|
+
and whether the store is running:
|
|
305
|
+
|
|
306
|
+
- `client.dropReadCache()` — keep the store, drop synced rows, resync in place (overlay + journal survive).
|
|
307
|
+
- `client.destroy()` — delete a RUNNING store from an attached client: peer-count checked
|
|
308
|
+
(`StoreDestroyRefusedError` while peers hold it), owed-journal checked (refused unless `force`),
|
|
309
|
+
teardown-acknowledged before deletion.
|
|
310
|
+
- `destroyStoreArtifacts(storePath)` — delete a NOT-running store by path: OPFS directory + commitment
|
|
311
|
+
sentinel + meta record + idb database, backend-agnostic, bounded ownership-lag retry. Documented
|
|
312
|
+
precondition, no liveness probe: on a still-held path it throws the ownership error — loud and safely
|
|
313
|
+
re-runnable (idempotent, phase-recorded; a `deleting`-marked store is refused for boot). Keep failed
|
|
314
|
+
paths on a retry list for the next boot. An idb-only sweep is NOT a substitute — it leaks the OPFS arena.
|
|
315
|
+
- `quiesceStoreWorker(worker, opts?)` (ADR-0050) — the by-path TEARDOWN companion that MAKES a store
|
|
316
|
+
not-running before `destroyStoreArtifacts`. Give it a worker factory of the same shape `attachSyncClient`
|
|
317
|
+
takes (`() => new SharedWorker(url, { name: storePath })`) — but the factory MUST construct the worker with
|
|
318
|
+
**byte-identical options to the LIVE store worker**, `extendedLifetime: true` included. A named SharedWorker
|
|
319
|
+
dedups onto one instance, and Chromium (148+) FAILS a second `new SharedWorker(name, …)` whose options
|
|
320
|
+
disagree with the live one (an `error` event, no `onconnect`) — the teardown port then exchanges zero
|
|
321
|
+
messages and only times out. Omitting `extendedLifetime` on the teardown worker does not shorten its life
|
|
322
|
+
(`closeHost` + `scope.close()` end it); it only breaks the dedup and defeats the primitive. It reaches the
|
|
323
|
+
worker by name, posts the
|
|
324
|
+
declaration, queries placement, and for an SW-direct home (idbfs, real-Safari opfs) sends `engine-teardown`
|
|
325
|
+
and AWAITS the reserved ack (engine stopped, backend connection released → `{ toreDown: true }`); an elected
|
|
326
|
+
home is a no-op (`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
|
|
327
|
+
`await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)`. A timeout REJECTS (not
|
|
328
|
+
proof of teardown, default 6s) and must not abort the destroy; omit `storage` (no opinion) so a worker on
|
|
329
|
+
an older declaration is never refused; idempotent + safe on an already-dead store.
|
|
330
|
+
|
|
331
|
+
**Storage-preference changes.** A store's storage declaration (backend/durability) is IMMUTABLE — bound at
|
|
332
|
+
first contact, conflicts refused typed (`StorageDeclarationRefusedError`). Never re-home or
|
|
333
|
+
delete-and-recreate a live path (an `extendedLifetime` predecessor may still hold it). The pattern:
|
|
334
|
+
atomically drop bindings + record the old exact paths on an obsolete list FIRST, then write the new
|
|
335
|
+
preference and reload; fresh stores mint under fresh paths, and each boot walks the obsolete list in
|
|
336
|
+
the background (never awaited on sign-in), per path QUIESCING the worker (`quiesceStoreWorker`) BEFORE
|
|
337
|
+
`destroyStoreArtifacts`. The quiesce is what makes idbfs converge: an `extendedLifetime` idbfs
|
|
338
|
+
predecessor holds its IndexedDB connection across the reload, so a bare destroy would block forever
|
|
339
|
+
(opfs releases on idle; idbfs does not) — tearing the host down releases the connection so the first
|
|
340
|
+
retry wins. Dynamic declarations travel as the wire `storage` option on
|
|
341
|
+
`attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative. Consumer docs:
|
|
342
|
+
<https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
|
|
343
|
+
|
|
248
344
|
## Proxying Electric: force `cache-control: no-store`
|
|
249
345
|
|
|
250
346
|
Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`).
|
package/src/adoption.ts
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
// Adoption orchestrator + declaration surface — ADR-0049 (capability-driven engine placement) decision 7,
|
|
2
|
+
// plan step 11a. The automatic and manual adoption transitions that turn an existing idb-authoritative store
|
|
3
|
+
// into a committed opfs successor, expressed as ONE pure, effect-injected sequence over the plan's
|
|
4
|
+
// "Adoption sequence (exclusive, quiescent — D7)" and its adoption crash rows. CONTEXT § "Language — engine
|
|
5
|
+
// placement" terms are used exactly: "Adoption gate", "Adoption-bootstrap gate", "Drain predicate".
|
|
6
|
+
//
|
|
7
|
+
// EFFECT-INJECTED BY CONSTRUCTION. Like `store-lifecycle.ts`, this module touches NO IndexedDB, OPFS, or
|
|
8
|
+
// PGlite: every side effect is a method on an injected {@link AdoptionEffects}. Plan step 11b wires the REAL
|
|
9
|
+
// effects into the boot path (`createSyncClient` / `defineSyncWorker`) — the pre-expose idb boot, the drain
|
|
10
|
+
// read, the opfs candidate build via the normal server bootstrap through the Adoption-bootstrap gate, the
|
|
11
|
+
// shared commitment barrier (`runCommitmentBarrier` from `store-lifecycle.ts`), and the predecessor deletion.
|
|
12
|
+
// Here the orchestrator owns only the DECISION SEQUENCE and its failure recovery; wiring is NOT this step.
|
|
13
|
+
//
|
|
14
|
+
// INVARIANTS (ADR-0049): the transition runs at boot BEFORE any engine is exposed — the caller guarantees
|
|
15
|
+
// pre-expose exclusivity (invariant 3, no-race-by-construction), so the drain predicate cannot be raced by a
|
|
16
|
+
// concurrent mutation. Automatic adoption is default OFF and consults the declaration FIRST (invariant 4 — no
|
|
17
|
+
// silent local-only data loss; hook absence is never authority because `rawExec` writes documented local-only
|
|
18
|
+
// state on any store). The idb predecessor is deleted ONLY after the commitment barrier publishes
|
|
19
|
+
// (invariant 3/4 — commitment precedes exposure; nothing strands, nothing is silently lost).
|
|
20
|
+
|
|
21
|
+
import { journalOwesNothing, runCommitmentBarrier, type JournalStatusCounts } from "./store-lifecycle";
|
|
22
|
+
import type { StoreBootVerdict, StoreMetaPhase } from "./store-meta";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The consumer's explicit reconstructibility declaration (ADR-0049 D7). `"server-reconstructible"` authorizes
|
|
26
|
+
* AUTOMATIC adoption: the store is server-reconstructible and its local-only data is disposable. DEFAULT OFF
|
|
27
|
+
* (`undefined`) — hook absence is NEVER authority: `rawExec` writes documented local-only state on any store,
|
|
28
|
+
* so only this explicit declaration (or the manual adoption API) authorizes deleting the idb predecessor.
|
|
29
|
+
*/
|
|
30
|
+
export type AdoptionDeclaration = "server-reconstructible" | undefined;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The effects the adoption transition drives, in the one order it always runs them (step 11b supplies the real
|
|
34
|
+
* implementations). The transition is a strict data-before-authority sequence: prove the idb store owes the
|
|
35
|
+
* server nothing, reconstruct an opfs successor through the Adoption-bootstrap gate, commit it via the shared
|
|
36
|
+
* barrier, and only THEN delete the predecessor.
|
|
37
|
+
*/
|
|
38
|
+
export interface AdoptionEffects {
|
|
39
|
+
/**
|
|
40
|
+
* Boot the idb engine PRE-EXPOSE (never surfaced to tabs — invariant 3) and return the journal status
|
|
41
|
+
* counts the drain predicate reads. The engine is booted solely to read the journal; the caller never
|
|
42
|
+
* exposes THIS booted instance until adoption defers (journal owed) or fails.
|
|
43
|
+
*/
|
|
44
|
+
bootIdbPreExpose(): Promise<JournalStatusCounts>;
|
|
45
|
+
/** Strict-sync the never-exposed idb engine, then close it (all handles released) before building the successor. */
|
|
46
|
+
strictSyncAndCloseIdb(): Promise<void>;
|
|
47
|
+
/** Advance the store meta record phase. The transition calls it with `"adopting"` and, on failure, `"idb-authoritative"`. */
|
|
48
|
+
setPhase(phase: StoreMetaPhase): Promise<void>;
|
|
49
|
+
/**
|
|
50
|
+
* Build the opfs candidate via the normal server bootstrap path AND await the Adoption-bootstrap gate:
|
|
51
|
+
* authorized online reconstruction — the initial catch-up of the eager Consistency groups a valid initial
|
|
52
|
+
* store requires ("authorized" includes legitimately anonymous/public shapes). Resolves ONLY when the gate
|
|
53
|
+
* passed; THROWS on gate failure (offline, unauthorized, `syncEnabled: false`, or a bootstrap error).
|
|
54
|
+
*/
|
|
55
|
+
buildCandidateThroughGate(): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Run the shared commitment barrier on the CANDIDATE engine: `strictSync()` returns with VFS health good →
|
|
58
|
+
* sentinel → `opfs-committed`. Step 11b wires `runCommitmentBarrier` (store-lifecycle.ts) with real effects;
|
|
59
|
+
* here it is one injected step. It MUST be all-or-nothing: a barrier failure publishes NOTHING (invariant 3),
|
|
60
|
+
* so a throw leaves the idb store authoritative and the candidate uncommitted.
|
|
61
|
+
*/
|
|
62
|
+
commitCandidate(): Promise<void>;
|
|
63
|
+
/** Delete the idb predecessor now the opfs successor is committed. Idempotent: absent counts as deleted. */
|
|
64
|
+
deleteIdbPredecessor(): Promise<void>;
|
|
65
|
+
/**
|
|
66
|
+
* Tear down a failed candidate: delete the stale sentinel (if any) AND the candidate directory,
|
|
67
|
+
* delete-if-present (a barrier-gap crash's sentinel must never survive). Recreate-only; idempotent.
|
|
68
|
+
*/
|
|
69
|
+
teardownCandidate(): Promise<void>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The narrow candidate surface the real boot wiring hands this module. */
|
|
73
|
+
export interface AdoptionCandidateHandle {
|
|
74
|
+
ready: Promise<void>;
|
|
75
|
+
strictSync(): Promise<void>;
|
|
76
|
+
close(): Promise<void>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** IO callbacks needed to construct the real stateful adoption effects without importing the client entrypoint. */
|
|
80
|
+
export interface AdoptionEffectBuilderOptions {
|
|
81
|
+
readIdbJournal(): Promise<JournalStatusCounts>;
|
|
82
|
+
setPhase(phase: StoreMetaPhase): Promise<void>;
|
|
83
|
+
buildCandidate(): Promise<AdoptionCandidateHandle>;
|
|
84
|
+
publishSentinel(): Promise<void>;
|
|
85
|
+
deleteSentinel(): Promise<void>;
|
|
86
|
+
deleteStoreDirectory(): Promise<void>;
|
|
87
|
+
deleteIdbPredecessor(): Promise<void>;
|
|
88
|
+
gateDeadlineMs?: number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const DEFAULT_ADOPTION_GATE_DEADLINE_MS = 30_000;
|
|
92
|
+
|
|
93
|
+
async function awaitAdoptionGate(ready: Promise<void>, deadlineMs: number): Promise<void> {
|
|
94
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
95
|
+
const deadline = new Promise<never>((_, reject) => {
|
|
96
|
+
timer = setTimeout(
|
|
97
|
+
() =>
|
|
98
|
+
reject(
|
|
99
|
+
new Error(
|
|
100
|
+
"[pgxsinkit] adoption gate unmet: the eager Consistency groups did not complete their initial " +
|
|
101
|
+
`catch-up within ${deadlineMs}ms (offline, unauthorized, or the server was unreachable). The idb ` +
|
|
102
|
+
"store stays authoritative.",
|
|
103
|
+
),
|
|
104
|
+
),
|
|
105
|
+
deadlineMs,
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
try {
|
|
109
|
+
await Promise.race([ready, deadline]);
|
|
110
|
+
} finally {
|
|
111
|
+
if (timer !== undefined) clearTimeout(timer);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Construct the stateful adoption effects around narrow IO callbacks. Candidate ownership, gate timing,
|
|
117
|
+
* data-before-authority publication, and failed-candidate cleanup live here rather than in the package entrypoint.
|
|
118
|
+
*/
|
|
119
|
+
export function buildAdoptionEffects(options: AdoptionEffectBuilderOptions): AdoptionEffects {
|
|
120
|
+
let candidate: AdoptionCandidateHandle | undefined;
|
|
121
|
+
return {
|
|
122
|
+
bootIdbPreExpose: () => options.readIdbJournal(),
|
|
123
|
+
async strictSyncAndCloseIdb() {
|
|
124
|
+
// The callback's drain read closes its read-only strict IDB engine before returning.
|
|
125
|
+
},
|
|
126
|
+
setPhase: (phase) => options.setPhase(phase),
|
|
127
|
+
async buildCandidateThroughGate() {
|
|
128
|
+
candidate = await options.buildCandidate();
|
|
129
|
+
await awaitAdoptionGate(candidate.ready, options.gateDeadlineMs ?? DEFAULT_ADOPTION_GATE_DEADLINE_MS);
|
|
130
|
+
},
|
|
131
|
+
async commitCandidate() {
|
|
132
|
+
const active = candidate;
|
|
133
|
+
if (active === undefined) throw new Error("[pgxsinkit] adoption: commit called before the candidate was built");
|
|
134
|
+
await runCommitmentBarrier({
|
|
135
|
+
strictSyncReturns: () => active.strictSync(),
|
|
136
|
+
publishSentinel: () => options.publishSentinel(),
|
|
137
|
+
setPhase: (phase) => options.setPhase(phase),
|
|
138
|
+
});
|
|
139
|
+
await active.close().catch(() => undefined);
|
|
140
|
+
candidate = undefined;
|
|
141
|
+
},
|
|
142
|
+
deleteIdbPredecessor: () => options.deleteIdbPredecessor(),
|
|
143
|
+
async teardownCandidate() {
|
|
144
|
+
if (candidate !== undefined) {
|
|
145
|
+
await candidate.close().catch(() => undefined);
|
|
146
|
+
candidate = undefined;
|
|
147
|
+
}
|
|
148
|
+
await options.deleteSentinel();
|
|
149
|
+
await options.deleteStoreDirectory();
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* The outcome of an adoption transition. `adopted: true` means the opfs successor is committed and the idb
|
|
156
|
+
* predecessor is gone (or scheduled for cleanup — see `predecessorCleanupPending`). Every `adopted: false`
|
|
157
|
+
* outcome leaves the idb store AUTHORITATIVE and untouched:
|
|
158
|
+
* - `not-declared` — automatic adoption without the declaration (default off); nothing ran (invariant 4).
|
|
159
|
+
* - `journal-owed` — the drain predicate failed; adoption is DEFERRED (the caller exposes the idb engine
|
|
160
|
+
* normally). The orchestrator boots the idb engine to READ the journal but exposes nothing itself.
|
|
161
|
+
* - `gate-failed` — the Adoption-bootstrap gate rejected (offline/unauthorized/`syncEnabled: false`/bootstrap
|
|
162
|
+
* error). The candidate was torn down; idb stays authoritative. `error` carries the gate failure text.
|
|
163
|
+
* - `barrier-failed` — the commitment barrier threw (strict sync did not return / VFS health bad). Nothing
|
|
164
|
+
* published; candidate torn down; idb stays authoritative. `error` carries the barrier failure text.
|
|
165
|
+
*/
|
|
166
|
+
export type AdoptionOutcome =
|
|
167
|
+
| {
|
|
168
|
+
adopted: true;
|
|
169
|
+
/**
|
|
170
|
+
* Set only when the predecessor deletion FAILED after a successful commit. Adoption still SUCCEEDED
|
|
171
|
+
* (the phase is `opfs-committed`); the boot classifier's lingering-idb row (adoption crash-row 3 →
|
|
172
|
+
* `opfs-committed` with an idb store present → `open-committed`, then `completeAdoption` finishes the
|
|
173
|
+
* deletion) completes the cleanup on the next boot. Carries the deletion failure text for diagnostics.
|
|
174
|
+
*/
|
|
175
|
+
predecessorCleanupPending?: string;
|
|
176
|
+
}
|
|
177
|
+
| { adopted: false; reason: "not-declared" | "journal-owed" | "gate-failed" | "barrier-failed"; error?: string };
|
|
178
|
+
|
|
179
|
+
/** Extract a stable message from a thrown value (an `Error`'s message, else its string form). */
|
|
180
|
+
function errorText(error: unknown): string {
|
|
181
|
+
return error instanceof Error ? error.message : String(error);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* The shared transition body — identical for the automatic and manual entry points (they differ ONLY in the
|
|
186
|
+
* declaration check, applied before this runs). Steps, in order (plan "Adoption sequence"):
|
|
187
|
+
*
|
|
188
|
+
* 1. Boot the idb engine pre-expose and read the journal. NOT drained → `journal-owed` (the orchestrator boots
|
|
189
|
+
* NOTHING further and exposes NOTHING itself — the caller then exposes the idb engine normally; adoption
|
|
190
|
+
* deferred). Drained → continue.
|
|
191
|
+
* 2. Strict-sync + close the never-exposed idb engine.
|
|
192
|
+
* 3. Phase → `adopting`.
|
|
193
|
+
* 4. Build the opfs candidate through the Adoption-bootstrap gate. On throw → tear the candidate down + set
|
|
194
|
+
* `idb-authoritative` (idb stays authoritative, plan gate-unmet row) → `gate-failed`.
|
|
195
|
+
* 5. Commit the candidate via the shared barrier. On throw → tear the candidate down + set `idb-authoritative`
|
|
196
|
+
* → `barrier-failed` (the barrier is all-or-nothing; nothing published).
|
|
197
|
+
* 6. Delete the idb predecessor → adopted. A deletion throw here does NOT unadopt: the phase is already
|
|
198
|
+
* `opfs-committed`, so the outcome is `adopted: true` with `predecessorCleanupPending` recorded and the
|
|
199
|
+
* classifier's lingering-idb row finishes the deletion next boot.
|
|
200
|
+
*/
|
|
201
|
+
async function runTransition(effects: AdoptionEffects): Promise<AdoptionOutcome> {
|
|
202
|
+
const counts = await effects.bootIdbPreExpose();
|
|
203
|
+
if (!journalOwesNothing(counts)) return { adopted: false, reason: "journal-owed" };
|
|
204
|
+
|
|
205
|
+
await effects.strictSyncAndCloseIdb();
|
|
206
|
+
await effects.setPhase("adopting");
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
await effects.buildCandidateThroughGate();
|
|
210
|
+
} catch (error) {
|
|
211
|
+
// Adoption-bootstrap gate unmet (offline/unauthorized/syncEnabled: false/bootstrap error): nothing
|
|
212
|
+
// published, so idb stays authoritative (plan "Adoption gate unmet" row).
|
|
213
|
+
await effects.teardownCandidate();
|
|
214
|
+
await effects.setPhase("idb-authoritative");
|
|
215
|
+
return { adopted: false, reason: "gate-failed", error: errorText(error) };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
await effects.commitCandidate();
|
|
220
|
+
} catch (error) {
|
|
221
|
+
// The barrier is all-or-nothing — a failure publishes NOTHING (invariant 3). Recover to idb-authoritative.
|
|
222
|
+
await effects.teardownCandidate();
|
|
223
|
+
await effects.setPhase("idb-authoritative");
|
|
224
|
+
return { adopted: false, reason: "barrier-failed", error: errorText(error) };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
try {
|
|
228
|
+
await effects.deleteIdbPredecessor();
|
|
229
|
+
} catch (error) {
|
|
230
|
+
// Adoption already SUCCEEDED (phase `opfs-committed`); a failed predecessor deletion never unadopts. The
|
|
231
|
+
// boot classifier's lingering-idb row completes the deletion next boot (plan adoption crash-row 3).
|
|
232
|
+
return { adopted: true, predecessorCleanupPending: errorText(error) };
|
|
233
|
+
}
|
|
234
|
+
return { adopted: true };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The AUTOMATIC adoption transition, run at boot BEFORE any engine is exposed (the caller guarantees pre-expose
|
|
239
|
+
* exclusivity — invariant 3's no-race-by-construction). Consults the {@link AdoptionDeclaration} FIRST: without
|
|
240
|
+
* `"server-reconstructible"` it refuses with `not-declared` and runs ZERO effects (invariant 4 — default off,
|
|
241
|
+
* hook absence is never authority). With the declaration it runs the shared {@link runTransition}.
|
|
242
|
+
*/
|
|
243
|
+
export function runAdoptionTransition(
|
|
244
|
+
declaration: AdoptionDeclaration,
|
|
245
|
+
effects: AdoptionEffects,
|
|
246
|
+
): Promise<AdoptionOutcome> {
|
|
247
|
+
if (declaration !== "server-reconstructible") {
|
|
248
|
+
return Promise.resolve({ adopted: false, reason: "not-declared" });
|
|
249
|
+
}
|
|
250
|
+
return runTransition(effects);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* The MANUAL adoption API's core: the identical transition, but WITHOUT the declaration check — the consumer's
|
|
255
|
+
* explicit call IS the authorization (they were told to export/migrate any local-only data first). The drain
|
|
256
|
+
* predicate still gates it (a store that owes the server work is not adoptable), and every failure recovery is
|
|
257
|
+
* identical to the automatic path.
|
|
258
|
+
*/
|
|
259
|
+
export function runManualAdoption(effects: AdoptionEffects): Promise<AdoptionOutcome> {
|
|
260
|
+
return runTransition(effects);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The boot-wiring predicate (plan step 11b): is a boot eligible to START an automatic adoption? True IFF the
|
|
265
|
+
* consumer declared `"server-reconstructible"` AND opfs sync access is available in this scope AND the boot
|
|
266
|
+
* classifier landed on `boot-idb-authoritative` — adoption only ever starts from an idb-authoritative store
|
|
267
|
+
* with opfs available (there is nowhere to build the successor otherwise, and no other verdict is a candidate).
|
|
268
|
+
*/
|
|
269
|
+
export function adoptionEligible(
|
|
270
|
+
declaration: AdoptionDeclaration,
|
|
271
|
+
verdict: StoreBootVerdict,
|
|
272
|
+
hasOpfsSyncAccess: boolean,
|
|
273
|
+
): boolean {
|
|
274
|
+
return declaration === "server-reconstructible" && hasOpfsSyncAccess && verdict.action === "boot-idb-authoritative";
|
|
275
|
+
}
|