@pgxsinkit/client 0.2.5 → 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/event-lane.d.ts +266 -0
- package/dist/event-lane.d.ts.map +1 -0
- package/dist/index.d.ts +94 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2797 -1995
- package/dist/index.js.map +16 -15
- package/dist/local-tables.d.ts +170 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +37 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +12 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +7 -1
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +7 -7
- package/skills/core/SKILL.md +47 -9
- package/skills/operating/SKILL.md +359 -352
- package/src/event-lane.ts +1194 -0
- package/src/index.ts +244 -8
- package/src/local-tables.ts +48 -1
- package/src/mutation.ts +13 -1
- package/src/schema.ts +81 -1
- package/src/worker/attach-sync-client.ts +81 -2
- package/src/worker/define-sync-worker.ts +48 -0
- package/src/worker/protocol.ts +14 -0
|
@@ -3,129 +3,122 @@ name: operating
|
|
|
3
3
|
description: >-
|
|
4
4
|
Load when deploying or operating a live pgxsinkit app, when diagnosing a sync/write that "feels slow"
|
|
5
5
|
in a browser even though the server is fast, or when wiring backups/export/restore. Covers the runtime
|
|
6
|
-
and deployment properties (not toolkit bugs) that decide whether
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
6
|
+
and deployment properties (not toolkit bugs) that decide whether an app feels fast: convergence cadence
|
|
7
|
+
(writes flush on enqueue; the interval is a fallback), serverless edge cold starts and warming,
|
|
8
|
+
cache-control:no-store on a same-origin shape proxy, the browser HTTP/2 connection budget, the edge
|
|
9
|
+
worker timeout vs Electric's long-poll, globalThis.__pgxsinkitDebug + the BootReport, worker mode
|
|
10
|
+
(defineSyncWorker/attachSyncClient — capability-driven engine placement, factories, relocation outcomes,
|
|
11
|
+
the forwarded rail), the store lifecycle surface (storePath naming, durability, backend permanence,
|
|
12
|
+
supervised destruction, the three exports, restoreFrom), and Event-lane
|
|
13
|
+
observability: onOutboxStatus, onEventLaneReport verdicts including deferred-on-skew, and the Outbox in
|
|
14
|
+
destroy/restore/backup/dropReadCache.
|
|
14
15
|
metadata:
|
|
15
16
|
type: task
|
|
16
17
|
library: "@pgxsinkit/client"
|
|
17
|
-
library_version: "0.2.
|
|
18
|
+
library_version: "0.2.7"
|
|
18
19
|
source: https://pgxsinkit.github.io/start/operating-in-production/
|
|
19
20
|
---
|
|
20
21
|
|
|
21
22
|
# Operating a pgxsinkit app in production
|
|
22
23
|
|
|
23
24
|
The read/write/converge primitives are fast. When a live app feels slow it is almost always one of the
|
|
24
|
-
properties below — none are toolkit bugs; they are how serverless edges, browser HTTP
|
|
25
|
-
|
|
25
|
+
properties below — none are toolkit bugs; they are how serverless edges, browser HTTP and CDN-shaped caching
|
|
26
|
+
behave. If writes or sync feel slow in a real browser but server benchmarks are fast, start here.
|
|
26
27
|
|
|
27
28
|
## Convergence cadence: event-driven, interval is a fallback
|
|
28
29
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
30
|
+
With an `autoSync` trigger, the client drives `flush → reconcile` **event-driven**: it calls `requestPass()`
|
|
31
|
+
the moment a mutation is enqueued, so a local write flushes immediately and does **not** wait for the
|
|
32
|
+
interval (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in worker mode
|
|
33
|
+
`defineSyncWorker`'s `convergenceIntervalMs`, default 15s), which is only a fallback for
|
|
34
|
+
retries/recovery/cross-tab.
|
|
34
35
|
|
|
35
36
|
Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
|
|
36
37
|
~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
|
|
37
|
-
demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to
|
|
38
|
-
|
|
39
|
-
the interval to "make writes faster" — it does nothing and burns CPU.
|
|
38
|
+
demo uses `intervalMs: 15_000`, cutting idle CPU from ~70% of a core to ~2% with **no change to convergence
|
|
39
|
+
latency** (latency is bounded by the Electric echo). Do **not** shorten it to "make writes faster".
|
|
40
40
|
|
|
41
41
|
## Serve the gateway over HTTP/2 (the connection budget)
|
|
42
42
|
|
|
43
|
-
Electric's client holds **one live long-poll connection open per synced shape
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
Any production ingress already does (Cloud Supabase, Electric Cloud, istio/Envoy, a TLS reverse proxy);
|
|
52
|
-
it only bites a local stack on plain `http://` (browsers only negotiate HTTP/2 over TLS).
|
|
43
|
+
Electric's client holds **one live long-poll connection open per synced shape**, and browsers cap
|
|
44
|
+
**HTTP/1.1 at ~6 connections per origin** — so over plain HTTP six shapes' long-polls consume every slot and
|
|
45
|
+
the same-origin **write** request is **Stalled in the browser's connection queue** for a whole long-poll
|
|
46
|
+
cycle before it is even dispatched. This presents as multi-second writes invisible to `curl`/Node (no
|
|
47
|
+
per-host cap); only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled**
|
|
48
|
+
time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one
|
|
49
|
+
connection. Any production ingress already does; it only bites a local stack on plain `http://` (browsers
|
|
50
|
+
only negotiate HTTP/2 over TLS).
|
|
53
51
|
|
|
54
52
|
## Serverless edge cold starts
|
|
55
53
|
|
|
56
54
|
On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
|
|
57
|
-
after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm,
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
`writeRequestHeaders` is merged over it on the write path only. Put the region header in
|
|
70
|
-
`writeRequestHeaders`; never in the shared `requestHeaders`, which reads also send.
|
|
55
|
+
after a quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s
|
|
56
|
+
after ~15s idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived
|
|
57
|
+
Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap
|
|
58
|
+
request (an empty `{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker
|
|
59
|
+
wall-clock timeout **above** Electric's ~25s long-poll so a live subscription is not recycled mid-cycle.
|
|
60
|
+
|
|
61
|
+
Region-pin **only the DB-bound write function**, not read proxies. Pinning it to the database's region
|
|
62
|
+
(Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a read proxy's upstream is
|
|
63
|
+
Electric Cloud's global CDN, so pinning reads away from a distant caller instead **adds** intercontinental
|
|
64
|
+
hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this: `requestHeaders` is the shared base
|
|
65
|
+
(reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is merged over it on the write path
|
|
66
|
+
only. Put the region header in `writeRequestHeaders`, never in the shared `requestHeaders`.
|
|
71
67
|
|
|
72
68
|
## Pre-warming PGlite's boot assets
|
|
73
69
|
|
|
74
70
|
A cold `PGlite.create` spends ~2.5s fetching + compiling the Postgres WASM (plus the initdb WASM and the
|
|
75
|
-
filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
pglite-warm.ts` shows the Vite `?url` asset-URL pattern PGlite's `exports` field otherwise blocks.)
|
|
71
|
+
filesystem bundle) before it can open a store — otherwise paid **after** sign-in, on the path to first paint.
|
|
72
|
+
`createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled assets
|
|
73
|
+
(`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into `PGlite.create` so
|
|
74
|
+
it skips its own lazy load. Start the fetch+compile on an **earlier screen** and hand the pending promise in
|
|
75
|
+
— the WASM cost then hides behind user think-time. It is best-effort: a rejected warm is caught to
|
|
76
|
+
`undefined` and PGlite loads its own assets. The `boot pglite assets warm` rail stamp times it. (Board demo:
|
|
77
|
+
`apps/board/src/board/pglite-warm.ts` shows the Vite `?url` pattern PGlite's `exports` field otherwise blocks.)
|
|
83
78
|
|
|
84
79
|
**In worker mode the engine loads PGlite's OWN assets — deliberately; do not pre-supply them.** The tab's
|
|
85
|
-
warm still serves the engine
|
|
80
|
+
warm still serves the engine by priming the same-origin HTTP cache the worker fetches from. Handing the
|
|
86
81
|
engine a pre-compiled `WebAssembly.Module` benched NET-NEGATIVE: it forces compile-to-completion before
|
|
87
|
-
instantiate (forfeiting
|
|
88
|
-
|
|
82
|
+
instantiate (forfeiting PGlite's streaming-load pipelining), and the engine realm's only overlap window is
|
|
83
|
+
the placement/handshake gap, so the compile just competes for CPU at spawn.
|
|
89
84
|
|
|
90
85
|
Pre-warming only hides the WASM fetch+compile; `PGlite.create` still spends ~1.9s on `initdb` + store open,
|
|
91
|
-
|
|
86
|
+
which can't start until the store id is known (usually the signed-in user). To hide that too, create the
|
|
92
87
|
store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(storePath,
|
|
93
|
-
{ bootAssets })` runs the exact same create the client does internally
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
memoised per userId so the provider's later open adopts it rather than opening a second instance. (Board
|
|
104
|
-
demo: `apps/board/src/board/store-registry.ts`, `store-prewarm.ts`.)
|
|
88
|
+
{ bootAssets })` runs the exact same create the client does internally and returns a schemaless instance;
|
|
89
|
+
hand the still-pending promise to `createSyncClient`'s `precreatedPglite`. Unlike `pgliteInstance` (caller
|
|
90
|
+
owns schema), `precreatedPglite` lets the client still run schema exec, prepare hooks, journal recovery and
|
|
91
|
+
store-version reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays
|
|
92
|
+
post-auth. A rejected `precreatedPglite` falls back to the `storePath` create path, so it is a pure
|
|
93
|
+
accelerator, never a boot dependency. Bind eager stores to users with a small localStorage registry
|
|
94
|
+
(userId→storeId plus one unbound "spare"): create a spare on the login screen, claim it at sign-in, GC any
|
|
95
|
+
store that is neither mapped nor the spare. On a signed-in RELOAD there is no login screen to create ahead of,
|
|
96
|
+
so START the mapped-store open at app bootstrap (before React render), memoised per userId so the provider's
|
|
97
|
+
later open adopts it. (Board demo: `store-registry.ts`, `store-prewarm.ts`.)
|
|
105
98
|
|
|
106
99
|
## Worker mode: capability-placed off-thread engine (browser apps)
|
|
107
100
|
|
|
108
|
-
In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
101
|
+
In a browser, prefer worker mode so PGlite, shape streams, journal machinery, and convergence leave the main
|
|
102
|
+
thread. The SharedWorker is always the communication centre. There is no placement option: where the engine
|
|
103
|
+
runs is a runtime capability decision. Under the default `storage.backend: "opfs"`, an unconditional real
|
|
104
|
+
synchronous-handle open at boot chooses the engine home — real macOS/iOS Safari runs the OPFS-repacked engine
|
|
105
|
+
directly in the SharedWorker, Chromium/Firefox elect one tab-spawned dedicated engine worker through Web
|
|
106
|
+
Locks, and Playwright WebKitGTK denies the handle in both worker kinds, exercising the capability fallback to
|
|
107
|
+
idb (declared durability kept, `storageBackend: "idbfs"` + `storageFallbackReason` on the BootReport). The
|
|
108
|
+
one opt-out is `storage.backend: "idbfs"` on the registry: no probe, no election, the engine boots in the
|
|
109
|
+
SharedWorker on idb. `createSyncClient` remains the bun/Node mode and the main-thread idb fallback where
|
|
110
|
+
SharedWorker is missing.
|
|
118
111
|
|
|
119
112
|
**A home with NO grant refuses a store already committed to OPFS.** A boot whose home holds no sync-access
|
|
120
113
|
grant (a tab realm, the in-process fallback) over a store whose meta record says `opfs-committed` fails
|
|
121
|
-
CLOSED with `CommittedStoreUnreachableError
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
114
|
+
CLOSED with `CommittedStoreUnreachableError`, because `idb://<storePath>` would be an EMPTY sibling (app
|
|
115
|
+
looks wiped, offline writes fork into a store no worker-mode boot opens). No override flag; the message names
|
|
116
|
+
both exits — boot from a granted home, or destroy first with `destroyStoreArtifacts(storePath)`, the
|
|
117
|
+
path-addressed destroy (a failed boot leaves you no client to call `destroy()` on) that deletes both backends
|
|
118
|
+
plus the sentinel and the meta record and needs no grant, quiescing any live worker for the path first
|
|
119
|
+
(`quiesceStoreWorker`). The error is `instanceof`-branchable on the tab side too (it crosses the bridge as
|
|
120
|
+
its class) and carries the refused `storePath`; a no-grant `provision` declines that store for the same
|
|
121
|
+
reason rather than pre-minting the sibling.
|
|
129
122
|
|
|
130
123
|
**Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
|
|
131
124
|
`defineSyncWorker({ registry, electricUrl, batchWriteUrl, … })` at module top level — no placement or
|
|
@@ -133,172 +126,155 @@ durability option (both are runtime/registry concerns); the registry is CODE, _i
|
|
|
133
126
|
file, never cloned/serialized in. Give each store a stable SharedWorker name and always pass
|
|
134
127
|
`extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
|
|
135
128
|
`attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
|
|
136
|
-
over a bare instance or a raw `port`
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
`
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
`
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
engine
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
stable SharedWorker name for each store. Multiple stores may remain alive concurrently. Detach/stop the old
|
|
178
|
-
client and immediately attach the new identity's worker/store — never wait for the old SharedWorker, elected
|
|
179
|
-
engine, provision expiry, or `extendedLifetime` grace period. In worker mode `stop()` detaches only this tab;
|
|
180
|
-
in-process mode it disposes live queries before closing that client's engine and store. The board's
|
|
181
|
-
`userId → storeId` registry and real-browser identity-switch lane demonstrate this guarantee.
|
|
129
|
+
over a bare instance or a raw `port` — a SharedWorker cannot be reconstructed from itself, so **in elected
|
|
130
|
+
placement** (Chromium/Firefox) the factory is what arms SharedWorker(router)-death recovery via the election
|
|
131
|
+
coordinator's keepalive. A `port`/instance input stays fully functional (provision, attach, and the
|
|
132
|
+
`storePath`-keyed handoff all work) but **forfeits that reconstruction** — the coordinator detects the death
|
|
133
|
+
and can only stop. In SW-direct placement (Safari/idbfs) the engine lives in the SharedWorker and there is no
|
|
134
|
+
keepalive; neither form auto-recovers a dead SharedWorker (opt into `bridgeSilenceMs` + a factory for a
|
|
135
|
+
bridge-silence reconnect there). The elected engine worker needs no consumer wiring: the SharedWorker reports
|
|
136
|
+
its own script URL and the winning tab constructs `new Worker(reportedUrl, { type: "module" })`. Supply
|
|
137
|
+
`createEngineWorker` ONLY for entries that cannot be reconstructed from their URL as a module worker
|
|
138
|
+
(classic-script workers, `blob:`/`data:` URLs, CSP); with no override and no derivable URL, attach fails with
|
|
139
|
+
a typed error — never a silent no-engine attach.
|
|
140
|
+
|
|
141
|
+
The attached facade returns the same client shape as `createSyncClient` (write API, one-shot Drizzle reads,
|
|
142
|
+
live rows, `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine.
|
|
143
|
+
One-shot reads (`query`/`queryRow`/`queryRaw`/`queryRawRow`) compile on the tab and cross the bridge as ONE
|
|
144
|
+
guarded round trip — the worker runs the read gate + lazy-group guard, then Drizzle's own mapping runs back
|
|
145
|
+
on the tab, so results match the in-process client exactly. A bare awaited `client.drizzle` builder is ALSO
|
|
146
|
+
guarded here, and `client.drizzle.transaction()` throws (no tab-local store). `ensureSynced` is proxied
|
|
147
|
+
(additive, idempotent); `isSynced` throws — it is a SYNCHRONOUS activation-started peek the tab's cached
|
|
148
|
+
catch-up readiness cannot answer (use `groupReady` for catch-up, `ensureSynced` to activate). Local `pglite`
|
|
149
|
+
and `dropReadCache` are NOT proxied (no tab-local store; a cache rebuild is engine-wide). `destroy()` IS
|
|
150
|
+
proxied through a tab-side supervisor: it refuses peers with `StoreDestroyRefusedError`, refuses owed journal
|
|
151
|
+
rows unless `{ force: true }`, retires/closes the engine, then runs a resumable deletion. The lazy lifecycle
|
|
152
|
+
methods ARE proxied, but the engine is SHARED: `desync(tableKey)` from one tab reverts the consistency group
|
|
153
|
+
for EVERY attached tab (the footgun). For an ephemeral delivery window use `discardEphemeral(tableKey)`
|
|
154
|
+
instead — the scoped, multi-tab-safe finalize (drops the ephemeral rows, reverts to dormant, refuses a group
|
|
155
|
+
with any persistent member), safe under a shared engine because an ephemeral window is per-delivery-session
|
|
156
|
+
and single-consumer. The exception is the INSPECTION surface `rawQuery(sql, params)` / `rawExec(sql)` (debug
|
|
157
|
+
pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the attach client), it
|
|
158
|
+
runs raw against the local store — bypassing the journal/overlay, any write staying local and never
|
|
159
|
+
converging — so it is not an app-data read path. `replAdapter(client)` shapes it into the `{ query, exec }`
|
|
160
|
+
duck `@electric-sql/pglite-repl` needs. A worker file can bake multiple role variants and pick per attach via
|
|
161
|
+
`resolveRegistry(role)` + the tab's `role`, and can pass the schema prepare hooks
|
|
162
|
+
`prepareLocalDbBeforeSchema` / `prepareLocalDbAfterSchema` (app migrations, indexes, views) — worker-entry,
|
|
163
|
+
not attach, options, because a hook is a function and cannot cross the bridge.
|
|
164
|
+
|
|
165
|
+
**Identity switches do not wait for worker retirement.** Scope each worker identity by `storePath` with a
|
|
166
|
+
distinct, stable SharedWorker name; multiple stores may remain alive concurrently. Detach/stop the old client
|
|
167
|
+
and immediately attach the new identity's worker/store — never wait for the old SharedWorker, elected engine,
|
|
168
|
+
provision expiry, or `extendedLifetime` grace. In worker mode `stop()` detaches only this tab; in-process it
|
|
169
|
+
disposes live queries before closing that client's engine and store.
|
|
182
170
|
|
|
183
171
|
**Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
|
|
184
|
-
`notifyAuthChanged`; the worker uses the cached token and
|
|
185
|
-
|
|
186
|
-
|
|
172
|
+
`notifyAuthChanged`; the worker uses the cached token and pull-requests one only when a request finds it near
|
|
173
|
+
expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher, so
|
|
174
|
+
GoTrue refresh-token reuse detection can't be tripped by a second client.
|
|
187
175
|
|
|
188
176
|
**Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
|
|
189
177
|
schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
|
|
190
178
|
registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
|
|
191
|
-
Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery
|
|
192
|
-
|
|
193
|
-
SharedWorker's own script URL (
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
`boot store claimed`, `boot shape prefetch start`, `boot commits opened`.
|
|
179
|
+
Call `provisionSyncWorker` with the same `worker` input as attach (the factory form, so elected-mode recovery
|
|
180
|
+
is armed for provisioning too); an elected pre-open shares the tab's one election coordinator and derives the
|
|
181
|
+
engine from the SharedWorker's own script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it
|
|
182
|
+
retires the abandoned elected claim AND settles the returned promise with the typed `ProvisionExpiredError`
|
|
183
|
+
in both modes, so a provision behind a dead SharedWorker connection fails loudly rather than hanging. It
|
|
184
|
+
bounds YOUR promise; the worker-side create attempt follows the placement. SW-direct: the attempt is left
|
|
185
|
+
running — a later attach adopts it if it completed and waits on it if it is stuck, and a retried provision
|
|
186
|
+
re-acks the same attempt rather than opening a second. Elected: the deadline also releases the provision
|
|
187
|
+
claim, and a LAST-claim release retires and terminates the engine with that attempt inside it, so the next
|
|
188
|
+
attach elects a fresh one (an attach that adopted the coordinator earlier keeps its claim, and that engine).
|
|
189
|
+
Fire-and-forget callers should `.catch()` it like any un-awaited promise. Claim = bind id, attach, push
|
|
190
|
+
config + token. On a PROVABLY-fresh claimed store pass `attachSyncClient({ freshStore: true })` (never for a
|
|
191
|
+
mapped/returning store) and the worker overlaps the shape catch-up with schema/journal/store-version
|
|
192
|
+
recovery — far-user boot bounded by `max(create+schema, catch-up)`, not their sum. Boot-rail stamps: `boot
|
|
193
|
+
spare store ensured`, `boot mapped store prewarm`, `boot store claimed`, `boot shape prefetch start`,
|
|
194
|
+
`boot commits opened`.
|
|
208
195
|
|
|
209
196
|
**`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
|
|
210
|
-
progressive paint use `await client.groupReady(tableKey)` or read `status.groups
|
|
197
|
+
progressive paint use `await client.groupReady(tableKey)` or read `status.groups`.
|
|
211
198
|
|
|
212
|
-
**Debug rail is forwarded and origin-tagged.** A SharedWorker's
|
|
199
|
+
**Debug rail is forwarded and origin-tagged.** A SharedWorker's console is invisible to the page (only
|
|
213
200
|
`chrome://inspect`), so the worker forwards every rail line to each tab, stamped with the WORKER's monotonic
|
|
214
|
-
clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`.
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
(`chrome://inspect/#workers` → inspect) for the real requests, status codes, and errors (e.g. CORS
|
|
222
|
-
rejections surface only there). Full model:
|
|
223
|
-
<https://pgxsinkit.github.io/concepts/worker-mode/>.
|
|
201
|
+
clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. The
|
|
202
|
+
front half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those
|
|
203
|
+
pre-attach lines in a bounded ring (last 500) and replays them `[replay]`-marked to the first attaching tab.
|
|
204
|
+
The worker's NETWORK traffic is invisible the same way: shape requests never appear in the page's Network
|
|
205
|
+
panel — "rail shows `shape request start`, Network tab shows nothing" is worker mode working as designed.
|
|
206
|
+
Inspect the worker itself (`chrome://inspect/#workers`) for the real requests, status codes, and errors (CORS
|
|
207
|
+
rejections surface only there). Full model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
|
|
224
208
|
|
|
225
209
|
**Placement and relocation diagnostics.** Pull `client.bootReport()` and inspect `storageBackend`
|
|
226
|
-
(`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome`
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
otherwise); SW-direct Safari rejects it as unsupported.
|
|
210
|
+
(`opfs-repacked`/`idbfs`/`filesystem`/`memory`), `engineHome` (`shared-worker`/`elected-worker`/
|
|
211
|
+
`in-process`) and `storageFallbackReason`; never user-agent-sniff the backend. During elected-engine handoff
|
|
212
|
+
`EngineRelocatedError("not-dispatched")` is safe to retry, while `"unknown"` means a dispatched mutation may
|
|
213
|
+
already be journaled — inspect/reconcile, never retry blindly. The opt-in `executionLimit` is disabled by
|
|
214
|
+
default (no finite worst-case query duration exists, and the limit converts slow to terminated by policy);
|
|
215
|
+
it is elected-only and must match between the worker entry and every tab
|
|
216
|
+
(`ExecutionLimitMismatchError`), and SW-direct Safari rejects it as unsupported.
|
|
234
217
|
|
|
235
218
|
## Live-query manager: dedup + keep-alive (ADR-0040)
|
|
236
219
|
|
|
237
220
|
Every reactive read (`useLiveDrizzleRows`/`useLiveQueryRaw`/`subscribeLiveRows`) is a **local SQL live
|
|
238
221
|
query**: PGlite materialises it once, then re-runs + diffs it on every write to its tables. That registration
|
|
239
|
-
is a real cost
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
query cost one materialisation, not N. You do nothing to get this.
|
|
222
|
+
is a real cost (~a few hundred ms for a heavy aggregate) and is **automatically deduplicated** — identical
|
|
223
|
+
queries (keyed on executed SQL + bound params, NOT `use`) share ONE registration and ONE re-run + diff per
|
|
224
|
+
write, fanned to every subscriber, so N components (or N tabs on the shared worker) cost one materialisation.
|
|
243
225
|
|
|
244
226
|
Default lifetime is route-scoped: a live query is torn down the instant its last consumer unmounts, so a
|
|
245
227
|
navigate-away-and-back RE-materialises it. Opt a genuinely hot query into a grace period with a per-hook hint
|
|
246
|
-
`useLiveDrizzleRows(build, deps, { keepAliveMs: 30_000 })` (
|
|
247
|
-
|
|
248
|
-
maxRetainedRows } })` (defaults `0` / `16` / `50_000`; same block
|
|
249
|
-
keep-alive is `max(default, subscribers' hints)`; the count/row
|
|
250
|
-
LRU-evict zero-subscriber entries
|
|
251
|
-
|
|
252
|
-
**Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused
|
|
253
|
-
PGlite live queries can't be
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
every route dedups onto it — not a retention setting; there is deliberately no retain-forever knob.
|
|
228
|
+
`useLiveDrizzleRows(build, deps, { keepAliveMs: 30_000 })` (same field on the raw hook and
|
|
229
|
+
`subscribeLiveRows`), or a worker/client-wide policy `defineSyncWorker({ …, liveQueries: {
|
|
230
|
+
defaultKeepAliveMs, maxRetainedQueries, maxRetainedRows } })` (defaults `0` / `16` / `50_000`; the same block
|
|
231
|
+
exists on `createSyncClient`). The effective keep-alive is `max(default, subscribers' hints)`; the count/row
|
|
232
|
+
budgets outrank any hint and LRU-evict zero-subscriber entries; active entries are never evicted.
|
|
233
|
+
|
|
234
|
+
**Keep the default 0 unless you have a specific hot query.** A retained zero-subscriber query is NOT paused
|
|
235
|
+
(PGlite live queries can't be), so it still pays a full re-run + diff on every write to its tables while
|
|
236
|
+
held: retention wins only for a frequently-re-mounted, write-COLD query. For a fixed hot set the endorsed
|
|
237
|
+
"permanent" pattern is a **mounted subscriber** (a root-provider hook that never unmounts) — one live
|
|
238
|
+
registration for the app's life, every route dedups onto it; there is deliberately no retain-forever knob.
|
|
258
239
|
|
|
259
240
|
`client.liveQueryDiagnostics()` returns a per-entry snapshot — fingerprint DIGEST (never SQL/params/rows),
|
|
260
|
-
subscriber + row counts,
|
|
261
|
-
`live-query register|dedup-hit|retained|evicted|teardown-complete` lines
|
|
241
|
+
subscriber + row counts, timings, retention state — safe to log. The manager also emits
|
|
242
|
+
`live-query register|dedup-hit|retained|evicted|teardown-complete` rail lines (digests only).
|
|
262
243
|
|
|
263
244
|
## Store naming, backups, and restore (ADR-0035/0036)
|
|
264
245
|
|
|
265
246
|
**Stores are named by a plain `storePath`, never a storage URL.** The backend is derived, not named — a
|
|
266
|
-
capability-proven browser engine home uses OPFS-repacked; fixed worker mode, a denied engine home
|
|
267
|
-
main-thread
|
|
268
|
-
`InvalidStorePathError` —
|
|
269
|
-
|
|
247
|
+
capability-proven browser engine home uses OPFS-repacked; fixed worker mode, a denied engine home and the
|
|
248
|
+
main-thread fallback use IndexedDB; bun/Node uses the filesystem. Anything containing `://` throws
|
|
249
|
+
`InvalidStorePathError` — drop the scheme, don't re-add it. Memory-backed stores are deliberately unreachable
|
|
250
|
+
from the production API (durability semantics assume a persisted store): tests spread
|
|
270
251
|
`memoryStoreForTests("name")` from `@pgxsinkit/client/testing`, and a caller-owned
|
|
271
|
-
`pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
risk
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
~100–200ms/write (allowed and documented, not forbidden).
|
|
294
|
-
|
|
295
|
-
On OPFS-repacked, browser/worker termination recovers the longest valid stable metadata-log prefix; an
|
|
296
|
-
unflushed suffix may be absent. A returned strict boundary is stable under that browser-failure model. Do
|
|
297
|
-
not generalize this to power loss, media failure, or external store edits.
|
|
252
|
+
`pgliteInstance`/`precreatedPglite` that is provably non-persistent (`dataDir` undefined, or `memory://`) is
|
|
253
|
+
refused with `NonPersistentStoreError` unless `testStoreAcknowledgment()` is spread alongside. For browser
|
|
254
|
+
store GC, get the IndexedDB name from `storeIndexedDbDatabaseName(storePath)`, never assemble `/pglite/…`.
|
|
255
|
+
|
|
256
|
+
**Relaxed durability is the default**, declared once on the registry
|
|
257
|
+
(`SyncRegistryDefinition.storage.durability`) — never on a minting surface, worker entry or attach site,
|
|
258
|
+
because durability follows the data and one declaration binds every open of every store minted from that
|
|
259
|
+
registry. Its physical behavior is backend-specific: on idb, relaxed returns before the whole-datadir
|
|
260
|
+
snapshot flush and schedules it asynchronously while strict pays that synchronous snapshot (~100–200ms per
|
|
261
|
+
optimistic mutation); on OPFS-repacked the host still awaits every sync, with relaxed asserting VFS health
|
|
262
|
+
and running any due deferred repack without an ordinary physical flush while strict flushes arena data
|
|
263
|
+
before metadata (initialization, repack activation and open-state close use strict ordering either way).
|
|
264
|
+
The resolved value is stamped on the `boot pglite.create` rail line.
|
|
265
|
+
|
|
266
|
+
**The idb loss window.** On idb the store is an in-memory FS with debounced whole-snapshot writes, so
|
|
267
|
+
`relaxed`'s window is every write since the last COMPLETED snapshot. The risk lands only on a crash before
|
|
268
|
+
BOTH the journal rows reach the write API (~hundreds of ms after enqueue) AND the scheduled snapshot lands —
|
|
269
|
+
and synced tables are server-recoverable by construction, so only consumer **local-only** tables carry real
|
|
270
|
+
risk. `durability: "strict"` is the escape hatch if you keep unrecoverable local-only data; on idb it costs
|
|
271
|
+
~100–200ms/write. On OPFS-repacked, browser/worker termination recovers the longest valid stable
|
|
272
|
+
metadata-log prefix and an unflushed suffix may be absent; a returned strict boundary is stable under that
|
|
273
|
+
browser-failure model — do not generalize it to power loss, media failure, or external store edits.
|
|
298
274
|
|
|
299
275
|
**Three exports, named by purpose, all returning `{ file, report }`** (report = phase timings + a
|
|
300
|
-
`MutationDiagnostics` snapshot
|
|
301
|
-
|
|
276
|
+
`MutationDiagnostics` snapshot). They work identically on both client forms (the artefact crosses the bridge
|
|
277
|
+
as a transferred buffer):
|
|
302
278
|
|
|
303
279
|
- `exportStore()` — the **store backup**: a live, checkpointed `dumpDataDir` tarball of the WHOLE store,
|
|
304
280
|
journal and overlay included. Never blocks, works offline with unflushed writes; restorable ONLY into
|
|
@@ -306,85 +282,122 @@ attach client (the artefact crosses the bridge as a transferred buffer):
|
|
|
306
282
|
- `exportDiagnostics()` — everything as SQL (synced + overlay + journal + views/functions + the `pgxsinkit`
|
|
307
283
|
schema) for support evidence. Never blocks; not for restoring.
|
|
308
284
|
- `exportData({ drainJournal? })` — the **portable** SQL (synced tables + their enum types, nothing of
|
|
309
|
-
pgxsinkit's machinery; loads into vanilla Postgres). The ONE blocking variant: it requires a fully
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
285
|
+
pgxsinkit's machinery; loads into vanilla Postgres). The ONE blocking variant: it requires a fully drained
|
|
286
|
+
journal (an `acked` write whose echo has not landed is NOT yet in the synced tables), so it flushes and
|
|
287
|
+
awaits convergence up to `drainJournal.timeoutMs` (default 15s), failing fast with `DataExportDrainError`
|
|
288
|
+
(which carries diagnostics) on `failed`/`quarantined`/`conflicted` rows. `drainJournal: false` exports
|
|
289
|
+
as-is and flags it.
|
|
314
290
|
|
|
315
291
|
The pg_dump variants run against a **throwaway clone** booted from the backup — the live engine is never
|
|
316
|
-
suspended and tabs never pause. Exports, `destroy()`, `discardEphemeral()
|
|
317
|
-
|
|
318
|
-
|
|
292
|
+
suspended and tabs never pause. Exports, `destroy()`, `discardEphemeral()` and `dropReadCache()` serialise
|
|
293
|
+
through one lifecycle slot: a concurrent call rejects immediately with `LifecycleBusyError` (no queueing —
|
|
294
|
+
retry after the holder settles). Ephemeral (`pg_temp`) content is never in any artefact.
|
|
319
295
|
|
|
320
296
|
**Restore** = `createSyncClient({ restoreFrom: backupFile, … })` (or `attachSyncClient` — the tarball rides
|
|
321
297
|
the boot attach), ONLY into a store path that does not exist in EITHER idb or OPFS
|
|
322
298
|
(`RestoreTargetExistsError` otherwise; the overwrite path is a deliberate `destroy()` first). Recovered
|
|
323
|
-
journal rows are quarantined because the write path has no mutation dedupe
|
|
324
|
-
offline for inspection
|
|
325
|
-
`diagnostics()`, resolve quarantined rows via `discardQuarantined
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
backend
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
and
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
**Resetting and deleting stores (ADR-0050).** Three non-interchangeable levers — pick by what you keep
|
|
342
|
-
and whether the store is running:
|
|
299
|
+
journal rows are quarantined because the write path has no mutation dedupe; a dirty-journal restore stays
|
|
300
|
+
offline for inspection, a clean-journal one may honor the normal online options immediately. Inspect
|
|
301
|
+
`diagnostics()`, resolve quarantined rows via `discardQuarantined`, then reboot the persisted store normally
|
|
302
|
+
(<https://pgxsinkit.github.io/concepts/export-and-restore/>).
|
|
303
|
+
|
|
304
|
+
**Backend permanence.** A store's backend is FIXED at its first mint, for the store's whole life. An
|
|
305
|
+
existing idb store is opened IN PLACE by a newly capable OPFS home — nothing copied, nothing deleted
|
|
306
|
+
(`storageBackend: "idbfs"` + a `storageFallbackReason` on the report); a no-grant home refuses a committed
|
|
307
|
+
OPFS store instead (above). The ONE route to another backend is a deliberate destroy — `client.destroy()`,
|
|
308
|
+
or `destroyStoreArtifacts(storePath)` for a store nobody holds — then a fresh boot that re-syncs and mints
|
|
309
|
+
on the then-best backend. Budget a full cold bootstrap, and expect local-only state (anything written via
|
|
310
|
+
`rawExec`, un-flushed journal rows dropped by `force`) to be gone: the replacement is a NEW store, not a
|
|
311
|
+
converted one. There is no migration API and no in-place conversion. For a storage-PREFERENCE change, mint
|
|
312
|
+
under a FRESH path and destroy the obsolete one in the background — never delete-and-recreate a live path.
|
|
313
|
+
|
|
314
|
+
**Resetting and deleting stores (ADR-0050).** Four non-interchangeable levers, picked by what you keep and
|
|
315
|
+
whether the store is running:
|
|
343
316
|
|
|
344
317
|
- `client.dropReadCache()` — keep the store, drop synced rows, resync in place (overlay + journal survive).
|
|
345
318
|
- `client.destroy()` — delete a RUNNING store from an attached client: peer-count checked
|
|
346
|
-
(`StoreDestroyRefusedError`
|
|
347
|
-
teardown-acknowledged before deletion.
|
|
319
|
+
(`StoreDestroyRefusedError`), owed-journal checked (refused unless `force`), teardown-acked before deletion.
|
|
348
320
|
- `destroyStoreArtifacts(storePath)` — delete a NOT-running store by path: OPFS directory + commitment
|
|
349
321
|
sentinel + meta record + idb database, backend-agnostic, bounded ownership-lag retry. Documented
|
|
350
322
|
precondition, no liveness probe: on a still-held path it throws the ownership error — loud and safely
|
|
351
|
-
re-runnable (
|
|
352
|
-
|
|
353
|
-
- `quiesceStoreWorker(worker, opts?)`
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
home is a no-op (`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
|
|
323
|
+
re-runnable (a `deleting`-marked store is refused for boot). Keep failed paths on a retry list for the next
|
|
324
|
+
boot. An idb-only sweep is NOT a substitute — it leaks the OPFS arena.
|
|
325
|
+
- `quiesceStoreWorker(worker, opts?)` — the by-path TEARDOWN companion that MAKES a store not-running before
|
|
326
|
+
`destroyStoreArtifacts`. Give it a worker factory of the shape `attachSyncClient` takes
|
|
327
|
+
(`() => new SharedWorker(url, { name: storePath })`) that constructs the worker with **byte-identical
|
|
328
|
+
options to the LIVE store worker**, `extendedLifetime: true` included: a named SharedWorker dedups onto one
|
|
329
|
+
instance, and Chromium (148+) FAILS a second `new SharedWorker(name, …)` whose options disagree (an `error`
|
|
330
|
+
event, no `onconnect`), so the teardown port exchanges zero messages and only times out. Omitting
|
|
331
|
+
`extendedLifetime` does not shorten the teardown worker's life (`closeHost` + `scope.close()` end it) — it
|
|
332
|
+
only breaks the dedup and defeats the primitive. It reaches the worker by name, posts the declaration,
|
|
333
|
+
queries placement, and for an SW-direct home sends `engine-teardown` and AWAITS the reserved ack (engine
|
|
334
|
+
stopped, backend connection released → `{ toreDown: true }`); an elected home is a no-op
|
|
335
|
+
(`{ toreDown: false }` — the elected engine dies with its tab). Compose best-effort:
|
|
365
336
|
`await quiesceStoreWorker(f).catch(() => {}); await destroyStoreArtifacts(path)`. A timeout REJECTS (not
|
|
366
|
-
proof of teardown, default 6s) and must not abort the destroy; omit `storage`
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
**Storage-preference changes.** A store's storage declaration
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
the
|
|
375
|
-
`
|
|
376
|
-
|
|
377
|
-
(opfs releases on idle; idbfs does not) — tearing the host down releases the connection so the first
|
|
337
|
+
proof of teardown, default 6s) and must not abort the destroy; omit `storage` so a worker on an older
|
|
338
|
+
declaration is never refused; idempotent + safe on an already-dead store.
|
|
339
|
+
|
|
340
|
+
**Storage-preference changes.** A store's storage declaration is IMMUTABLE — bound at first contact,
|
|
341
|
+
conflicts refused typed (`StorageDeclarationRefusedError`). Never re-home or delete-and-recreate a live path
|
|
342
|
+
(an `extendedLifetime` predecessor may still hold it). The pattern: atomically drop bindings + record the old
|
|
343
|
+
exact paths on an obsolete list FIRST, then write the new preference and reload; fresh stores mint under
|
|
344
|
+
fresh paths, and each boot walks the obsolete list in the background (never awaited on sign-in), per path
|
|
345
|
+
QUIESCING the worker BEFORE `destroyStoreArtifacts`. The quiesce is what makes idbfs converge: an
|
|
346
|
+
`extendedLifetime` idbfs predecessor holds its IndexedDB connection across the reload, so a bare destroy
|
|
347
|
+
would block forever (opfs releases on idle; idbfs does not) — tearing the host down releases it so the first
|
|
378
348
|
retry wins. Dynamic declarations travel as the wire `storage` option on
|
|
379
|
-
`attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative.
|
|
380
|
-
<https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
|
|
349
|
+
`attachSyncClient`/`provisionSyncWorker`; a registry-attached static declaration stays authoritative.
|
|
350
|
+
Consumer docs: <https://pgxsinkit.github.io/concepts/local-store-lifecycle/>.
|
|
351
|
+
|
|
352
|
+
## Event lane: observing the Outbox (ADR-0053)
|
|
353
|
+
|
|
354
|
+
If your registry declares `streams`, `client.appendEvent(stream, payload)` stages a fire-and-forget fact in
|
|
355
|
+
the **Outbox** — a durable, local-only table, never synced, overlaid or conflict-resolved. It resolves on
|
|
356
|
+
**durable local enqueue, not on delivery**, so it never blocks on the network and an append made offline
|
|
357
|
+
survives a reload. Two observation surfaces, identical on both client forms:
|
|
358
|
+
|
|
359
|
+
- **`onOutboxStatus(cb)` — the drain signal.** `{ empty }`, fired on the empty ↔ non-empty **transitions**,
|
|
360
|
+
current state delivered on subscribe (`await client.outboxStatus()` is the one-shot pull twin). It is the
|
|
361
|
+
invalidation hook for a best-guess view composing pending events with down-synced aggregates: when the
|
|
362
|
+
Outbox drains, the aggregate is authoritative again. It carries **no count** deliberately (one updated only
|
|
363
|
+
on transitions is stale by construction) — query `getOutboxTable(registry)` when you need one.
|
|
364
|
+
- **`onEventLaneReport(cb)` — the verdicts.** Per flush pass: terminal non-`acked` verdicts, `deferred` ones,
|
|
365
|
+
and batch-level backoff transitions. `acked` is never reported (a high-volume lane would drown you), and it
|
|
366
|
+
is **EPHEMERAL** — with **nothing subscribed the library warn-logs each report**. Subscribe for the app's
|
|
367
|
+
lifetime: once a row is deleted the Outbox cannot answer for it.
|
|
368
|
+
|
|
369
|
+
**Read the verdicts correctly — one of the four is not a failure.** `acked` is enqueued server-side. `refused`
|
|
370
|
+
(your `eventGate` said no) and `rejected` are **terminal**: the row is deleted, and `refused` is expected, not
|
|
371
|
+
an error. `rejected` has THREE causes on a KNOWN stream — a payload the schema refuses (or a parse output JSON
|
|
372
|
+
cannot carry), an oversized payload, and an **identity claim the stream declares that the verified claims
|
|
373
|
+
cannot resolve** (absent/null/object/array/empty — fail-closed, no partial stamp). The first two mean a
|
|
374
|
+
non-library caller or a broken deployment (the library validates at append) — a **bug**; the third means the
|
|
375
|
+
ISSUER stopped minting that claim, or moved its path. `deferred` is **NOT terminal**: the server does not
|
|
376
|
+
(yet) know that stream — rollout skew — so the rows stay, retry with backoff, and drain once the deploy lands.
|
|
377
|
+
A burst after a release is deploy order; one that never clears means the registry LACKS it.
|
|
378
|
+
|
|
379
|
+
**There is no attempt cap and no client-side quarantine, by design.** Retry has two classes: retryable
|
|
380
|
+
(network, 5xx, 408/425/429 — jittered backoff with a ceiling, honouring `Retry-After`, paused offline) and
|
|
381
|
+
auth (refresh once, then retryable). A row leaves the Outbox **only** on a server-issued per-event verdict,
|
|
382
|
+
so a stuck lane is a growing Outbox with backoff transitions on the report, never silent loss. A persistent
|
|
383
|
+
**503 / batch backoff** is the OTHER diagnosis — the server KNOWS the stream but could not enqueue the whole
|
|
384
|
+
batch: check the `--events` migration is applied (no queue, no enqueue), then DB reachability. Cadence/batch
|
|
385
|
+
caps are client config (`events`, validated at construction — a bad `batchSize` throws instead of wedging a
|
|
386
|
+
stream), clamped by the contracts limits; `flushEvents()` is the manual hatch without `autoSync`.
|
|
387
|
+
|
|
388
|
+
**The Outbox on every lifecycle surface** (durable owned state): `destroy()` **refuses** while it is
|
|
389
|
+
non-empty, exactly as on owed mutations — the refusal names which of the two blocked it, and `{ force: true }`
|
|
390
|
+
is the escape hatch. `dropReadCache()` never touches it (not read cache). `exportStore()` and
|
|
391
|
+
`exportDiagnostics()` include it; `exportData()` (synced tables only) excludes it. And **restore does NOT
|
|
392
|
+
quarantine restored Outbox rows** — the deliberate asymmetry with the mutation journal: they resume flushing
|
|
393
|
+
normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
|
|
381
394
|
|
|
382
395
|
## Proxying Electric: force `cache-control: no-store`
|
|
383
396
|
|
|
384
|
-
Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`)
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
397
|
+
Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`), so
|
|
398
|
+
behind a **same-origin proxy with no CDN** the browser cache serves them **stale** the moment a shape handle
|
|
399
|
+
rotates (re-seed, re-login, restart) and the client loops on "expired shape handle" **409s** until it
|
|
400
|
+
self-heals. Force `cache-control: no-store` on the proxied response:
|
|
388
401
|
|
|
389
402
|
```ts
|
|
390
403
|
const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
|
|
@@ -393,22 +406,18 @@ headers.set("cache-control", "no-store");
|
|
|
393
406
|
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
394
407
|
```
|
|
395
408
|
|
|
396
|
-
Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap,
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to
|
|
400
|
-
fresh commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
|
|
409
|
+
Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap, not
|
|
410
|
+
the HTTP cache. Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to fresh
|
|
411
|
+
commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
|
|
401
412
|
propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
|
|
402
|
-
(`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
self-hosted;
|
|
411
|
-
set `false` to restore untouched forwarding.
|
|
413
|
+
(`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY upstream-defect
|
|
414
|
+
mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin fan-out at scale), so
|
|
415
|
+
flip it off once Electric Cloud wakes coalesced polls reliably; distinct from the ADR-0033 sibling nudge,
|
|
416
|
+
which is permanent protocol behavior. Running your own CDN in front of self-hosted Electric: key on the FULL
|
|
417
|
+
query string (every param is load-bearing), respect origin cache-control, keep SWR windows modest, let
|
|
418
|
+
coalesced live polls complete immediately on origin response, read-timeouts 60s+, then VERIFY with bust off
|
|
419
|
+
— cross-client render ≲3s = healthy, ~a full hold cycle = live path served blind (full checklist:
|
|
420
|
+
operating-in-production docs page). Harmless self-hosted; set `false` to restore untouched forwarding.
|
|
412
421
|
|
|
413
422
|
## Debugging latency: `globalThis.__pgxsinkitDebug`
|
|
414
423
|
|
|
@@ -419,67 +428,61 @@ every phase. Enable it from the console or before boot:
|
|
|
419
428
|
globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pgxsinkit" + enable Verbose
|
|
420
429
|
```
|
|
421
430
|
|
|
422
|
-
Read the **gaps** between phases: `mutation staged {mutationId, table}` (
|
|
423
|
-
|
|
424
|
-
(
|
|
425
|
-
`
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
`
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
`boot pglite assets warm` times the optional boot-asset pre-warm (see below).
|
|
438
|
-
|
|
439
|
-
**Structured boot numbers — the `BootReport`.** The rail lines are for a human reading a console; for
|
|
431
|
+
Read the **gaps** between phases: `mutation staged {mutationId, table}` (correlate by id with the later
|
|
432
|
+
sent/acked lines); `convergence pass requested` → `flush` / `reconcile`; `board-write auth token resolved
|
|
433
|
+
{ms}` (a stalling token fetch); `board-write responded {status, ms}` (a cold worker or a connection stall);
|
|
434
|
+
`sync received change batch` → `sync applied {ms}` (fires only when the batch committed; a batch gated behind
|
|
435
|
+
a quiet sibling's watermark instead logs `sync change batch held by group frontier` and `live-tail sibling
|
|
436
|
+
nudge {shape}`, ADR-0033); `live query updated → re-render`. The read path has its own pair: `shape request
|
|
437
|
+
start` → `shape request done {shape, status, ms, upToDate?}` for EVERY Electric HTTP cycle, plus `must-refetch
|
|
438
|
+
received {shape}` when the server rotates a shape (the truncate + re-snapshot trigger — what to look for when
|
|
439
|
+
a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits matching
|
|
440
|
+
`[pgxsinkit-timing]` lines (the `deploying` skill); client-observed minus server `totalMs` isolates routing +
|
|
441
|
+
network. Boot too: `boot pglite.create` → `boot client ready` (store open, schema apply, journal recovery,
|
|
442
|
+
store-version reconcile, sync start) attributes a slow first paint to a phase; `boot pglite assets warm` times
|
|
443
|
+
the optional pre-warm.
|
|
444
|
+
|
|
445
|
+
**Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
|
|
440
446
|
machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
|
|
441
447
|
independently of the rail so it exists whether or not the flag is on (ADR-0034). Read it by push
|
|
442
|
-
(`onBootReport?: (report) => void
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
the
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
{shape, target, round}` → commit on the refreshed watermarks; `live-tail nudge exhausted` means a
|
|
461
|
-
sibling never advanced and the engine degraded to waiting out its poll (ADR-0033). Full prose:
|
|
448
|
+
(`onBootReport?: (report) => void`, fires once at boot completion) or pull (`await client.bootReport()` → the
|
|
449
|
+
most recent completed boot, `null` before the first sync; in worker mode it round-trips to the worker's
|
|
450
|
+
stored report, so a late tab reads a boot that predates it). It carries `totalMs`, decomposed `phases`, and a
|
|
451
|
+
per-group `groups[]`. Two reading caveats: groups catch up CONCURRENTLY on one WASM thread, so a group's
|
|
452
|
+
`fetchMs` is an UPPER BOUND on network wait and concurrent `applyMs` can overlap — never sum them into a
|
|
453
|
+
`totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made visible (then
|
|
454
|
+
`phases.pgliteCreateMs` is `null`).
|
|
455
|
+
|
|
456
|
+
A `catch-up watermark aligned {floor}` line marks the one moment a group finished its initial catch-up and
|
|
457
|
+
aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
|
|
458
|
+
`up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise hold
|
|
459
|
+
a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud — the
|
|
460
|
+
"stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head instead;
|
|
461
|
+
the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one round trip.
|
|
462
|
+
The same hold recurs on the **live tail**, where the engine **nudges** the laggards instead of waiting —
|
|
463
|
+
`sync change batch held by group frontier` → `live-tail sibling nudge {shape, target, round}` → commit on
|
|
464
|
+
the refreshed watermarks; `live-tail nudge exhausted` means a sibling never advanced and the engine degraded
|
|
465
|
+
to waiting out its poll (ADR-0033). Full prose:
|
|
462
466
|
<https://pgxsinkit.github.io/start/operating-in-production/>.
|
|
463
467
|
|
|
464
468
|
**Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
|
|
465
469
|
a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
|
|
466
470
|
instrumentation's network timings and a server-side `curl` over a poll loop.
|
|
467
471
|
|
|
468
|
-
**Inspecting a stuck or failed write.** To see _why_ a write is not converging —
|
|
469
|
-
attempt/retry counts, last error,
|
|
470
|
-
|
|
471
|
-
`getSyncStateView(registry, tableKey)`
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
**Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and
|
|
475
|
-
symmetric discard
|
|
476
|
-
`client.discardConflict(table, entityKey)
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
mis-route it to `conflicted` to borrow a discard.
|
|
472
|
+
**Inspecting a stuck or failed write.** To see _why_ a write is not converging — journal status,
|
|
473
|
+
attempt/retry counts, last error, a table's pending/conflict/quarantine state — read the generated journal
|
|
474
|
+
and sync-state relations with the typed factories `getJournalTable(registry, tableKey)` /
|
|
475
|
+
`getSyncStateView(registry, tableKey)` (typed Drizzle, no hand-written SQL against `<t>_mutations`). One-shot
|
|
476
|
+
diagnostic reads only — don't poll them in a loop.
|
|
477
|
+
|
|
478
|
+
**Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and have a
|
|
479
|
+
symmetric discard: a stale-write `conflicted` row (via `onConflict`) rolls back with
|
|
480
|
+
`client.discardConflict(table, entityKey)`, a structurally-rejected `quarantined` row (via `onQuarantine` —
|
|
481
|
+
a validation failure or a permanent policy denial such as an RLS `42501`) with
|
|
482
|
+
`client.discardQuarantined(table, entityKey)`. Each clears the entity's terminal journal rows + kept overlay,
|
|
483
|
+
so the read model falls back to the synced value and the entity accepts new mutations again (a lingering
|
|
484
|
+
terminal row otherwise blocks a re-create and chains a later update onto a dead head). Because quarantine has
|
|
485
|
+
a real rollback, route a permanent policy denial to `quarantined` — never mis-route it to `conflicted`.
|
|
483
486
|
|
|
484
487
|
## Common mistakes
|
|
485
488
|
|
|
@@ -488,5 +491,9 @@ mis-route it to `conflicted` to borrow a discard.
|
|
|
488
491
|
- Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
|
|
489
492
|
- Treating an edge cold start as a toolkit/sync-rail problem.
|
|
490
493
|
- Measuring latency by polling PGlite in a loop instead of at the network boundary.
|
|
494
|
+
- Treating `deferred` as a failure and "cleaning up" the Outbox — it is rollout skew, and those rows drain
|
|
495
|
+
themselves once the server deploy lands.
|
|
496
|
+
- Subscribing to `onEventLaneReport` per-screen (verdicts are ephemeral), or expecting `acked` on it.
|
|
497
|
+
- Assuming `appendEvent` resolving means delivered — it means durably staged locally; delivery is the flush.
|
|
491
498
|
|
|
492
499
|
Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
|