@pgxsinkit/client 0.1.32 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +11 -0
  2. package/dist/convergence.d.ts +76 -0
  3. package/dist/convergence.d.ts.map +1 -0
  4. package/dist/debug.d.ts +34 -0
  5. package/dist/debug.d.ts.map +1 -0
  6. package/dist/index.d.ts +421 -7
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +7214 -2234
  9. package/dist/index.js.map +74 -44
  10. package/dist/lazy-guard.d.ts +58 -0
  11. package/dist/lazy-guard.d.ts.map +1 -0
  12. package/dist/local-store.d.ts +56 -0
  13. package/dist/local-store.d.ts.map +1 -0
  14. package/dist/local-tables.d.ts +707 -0
  15. package/dist/local-tables.d.ts.map +1 -0
  16. package/dist/mutation-state.d.ts +62 -0
  17. package/dist/mutation-state.d.ts.map +1 -0
  18. package/dist/mutation.d.ts +117 -4
  19. package/dist/mutation.d.ts.map +1 -1
  20. package/dist/schema.d.ts +49 -0
  21. package/dist/schema.d.ts.map +1 -1
  22. package/dist/shape-sync.d.ts +180 -0
  23. package/dist/shape-sync.d.ts.map +1 -0
  24. package/dist/sync/apply.d.ts +51 -0
  25. package/dist/sync/apply.d.ts.map +1 -0
  26. package/dist/sync/copy.d.ts +43 -0
  27. package/dist/sync/copy.d.ts.map +1 -0
  28. package/dist/sync/drizzle-executor.d.ts +5 -0
  29. package/dist/sync/drizzle-executor.d.ts.map +1 -0
  30. package/dist/sync/index.d.ts +32 -0
  31. package/dist/sync/index.d.ts.map +1 -0
  32. package/dist/sync/metadata-tables.d.ts +131 -0
  33. package/dist/sync/metadata-tables.d.ts.map +1 -0
  34. package/dist/sync/nudge.d.ts +49 -0
  35. package/dist/sync/nudge.d.ts.map +1 -0
  36. package/dist/sync/shape-inbox.d.ts +215 -0
  37. package/dist/sync/shape-inbox.d.ts.map +1 -0
  38. package/dist/sync/subscription-state.d.ts +39 -0
  39. package/dist/sync/subscription-state.d.ts.map +1 -0
  40. package/dist/sync/tags.d.ts +130 -0
  41. package/dist/sync/tags.d.ts.map +1 -0
  42. package/dist/sync/types.d.ts +118 -0
  43. package/dist/sync/types.d.ts.map +1 -0
  44. package/dist/sync-auth.d.ts +53 -0
  45. package/dist/sync-auth.d.ts.map +1 -0
  46. package/dist/worker/attach-sync-client.d.ts +75 -0
  47. package/dist/worker/attach-sync-client.d.ts.map +1 -0
  48. package/dist/worker/define-sync-worker.d.ts +75 -0
  49. package/dist/worker/define-sync-worker.d.ts.map +1 -0
  50. package/dist/worker/live-diff.d.ts +44 -0
  51. package/dist/worker/live-diff.d.ts.map +1 -0
  52. package/dist/worker/protocol.d.ts +260 -0
  53. package/dist/worker/protocol.d.ts.map +1 -0
  54. package/dist/worker/token-cache.d.ts +26 -0
  55. package/dist/worker/token-cache.d.ts.map +1 -0
  56. package/oxlint-plugin.js +143 -0
  57. package/package.json +15 -7
  58. package/skills/core/SKILL.md +197 -0
  59. package/skills/operating/SKILL.md +243 -0
  60. package/src/convergence.ts +197 -0
  61. package/src/debug.ts +151 -0
  62. package/src/index.ts +1104 -44
  63. package/src/lazy-guard.ts +121 -0
  64. package/src/local-store.ts +193 -0
  65. package/src/local-tables.ts +546 -0
  66. package/src/mutation-state.ts +90 -0
  67. package/src/mutation.ts +1868 -562
  68. package/src/schema.ts +352 -27
  69. package/src/shape-sync.ts +477 -0
  70. package/src/sync/apply.ts +530 -0
  71. package/src/sync/copy.ts +206 -0
  72. package/src/sync/drizzle-executor.ts +48 -0
  73. package/src/sync/index.ts +1076 -0
  74. package/src/sync/metadata-tables.ts +67 -0
  75. package/src/sync/nudge.ts +110 -0
  76. package/src/sync/shape-inbox.ts +566 -0
  77. package/src/sync/subscription-state.ts +135 -0
  78. package/src/sync/tags.ts +365 -0
  79. package/src/sync/types.ts +132 -0
  80. package/src/sync-auth.ts +117 -0
  81. package/src/worker/attach-sync-client.ts +558 -0
  82. package/src/worker/define-sync-worker.ts +596 -0
  83. package/src/worker/live-diff.ts +140 -0
  84. package/src/worker/protocol.ts +325 -0
  85. package/src/worker/token-cache.ts +84 -0
@@ -0,0 +1,197 @@
1
+ ---
2
+ name: core
3
+ description: >-
4
+ Load when writing or reviewing code that uses @pgxsinkit/* (client, server, contracts, react) — the
5
+ offline-first sync toolkit for the Postgres -> ElectricSQL -> PGlite read path and the client -> write
6
+ API -> Postgres write path. Teaches the mental model the source does not make obvious: the two paths
7
+ are separate and asymmetric, there is exactly one write path (an in-database apply function, not
8
+ per-table CRUD), the Electric subquery flag is mandatory and fails closed, local PGlite schema is not
9
+ full DDL parity, and writable tables must declare a conflict policy plus managed fields. Load this
10
+ before wiring sync, defining a registry, or debugging "writes don't appear" / "no rows stream" / "a
11
+ removed member still sees rows".
12
+ metadata:
13
+ type: core
14
+ library: "@pgxsinkit/client"
15
+ library_version: "0.1.32"
16
+ source: https://pgxsinkit.github.io/llms-full.txt
17
+ ---
18
+
19
+ # Using pgxsinkit correctly
20
+
21
+ pgxsinkit is a **toolkit**, not a database, a framework, or the demo app. The `@pgxsinkit/*` packages
22
+ are the product: `contracts` (the registry + shared types), `server` (the write API + Electric shape
23
+ proxy), `client` (local PGlite store + mutation runtime + convergence), and `react` (hooks). A consumer
24
+ installs these and wires them; they do not "run pgxsinkit".
25
+
26
+ ## The one idea everything else follows from: two separate, asymmetric paths
27
+
28
+ - **Read path:** Postgres → ElectricSQL → a server-side shape **proxy** (ownership-filtered) → local
29
+ **PGlite**. Reads are served from PGlite.
30
+ - **Write path:** client stages an optimistic local write → flushes a batch to the **write API** → one
31
+ **in-database apply function** (`pgxsinkit_apply_mutations`) applies it under RLS → Postgres.
32
+
33
+ **Writes do not travel back to the writer through Electric.** The loop closes through Postgres: your
34
+ write lands in Postgres, then streams back to _every_ subscriber (including you) as a normal Electric
35
+ change, which clears the optimistic overlay. Do not look for a write to "come back" on the write
36
+ channel, and do not try to write through Electric — Electric is read-only here.
37
+
38
+ ## There is exactly one write path
39
+
40
+ There is no per-table CRUD API and no selectable backend. Every mutation — create, update, delete —
41
+ goes through `POST /api/mutations` and is applied by the single in-database function. You provision that
42
+ function once from your registry with the `pgxsinkit-generate` CLI (a drizzle-kit migration). Do not
43
+ invent REST endpoints per table; do not write to Postgres tables directly from the client.
44
+
45
+ **Blind update — writing a row your read shape excludes.** A pessimistic write unit
46
+ (`client.transaction({ mode: "pessimistic" }, (tx) => …)`) flush-routes to the authoritative endpoint and
47
+ resolves with each member's `acked` / `conflicted` / `rejected` outcome. Alongside `create`/`update`/`delete`
48
+ its handles carry **`updateBlind(entityKey, patch)`**: an update-by-key for a target your own read shape
49
+ excludes (a write-only flow, or an anonymity-scoped moderation write whose row streams only to a different
50
+ projection). Ordinary `update` requires the entity in the local read model (to seed the overlay + capture the
51
+ base version); `updateBlind` skips that — it plans a **journal row only**, writes **no overlay**, and the
52
+ acked row **retires without a synced echo** (nothing local ever converges for it). It is **pessimistic-only**
53
+ and throws at enqueue on an optimistic route. Never seed a phantom base row to satisfy `update` for an
54
+ invisible target — that row + its overlay would linger forever behind the echo barrier; use `updateBlind`.
55
+
56
+ ## Reading the local store: base table vs overlay view
57
+
58
+ Reads run against local PGlite through the client, not hand-written SQL. For a **pure-Drizzle** read, pass
59
+ the builder callback directly to `client.query((c) => …)` (the guarded read): pgxsinkit scans the compiled
60
+ SQL and activates + awaits every `lazy` relation the query touches (FROM, JOIN, subquery, WHERE) before it
61
+ runs — nothing to declare. `client.query` resolves to the **rows array directly** (not `{ rows }`). Inside
62
+ the callback, reach relations through a directly-imported synced table/view object, `c.drizzle`, or
63
+ `c.views`. Only when the builder embeds a raw ``sql`…` `` fragment (which the scan can miss) use
64
+ `client.queryRaw({ use, build })` and name those relations in `use`. `queryRow` / `queryRawRow` are the
65
+ first-row-or-null variants. (Reactive equivalents: `useLiveDrizzleRows` for pure reads,
66
+ `useLiveQueryRaw({ use, build })` for raw fragments.)
67
+
68
+ **Lint the split.** `@pgxsinkit/client` ships an oxlint rule via its `./oxlint` subpath export. Enable it
69
+ in the consuming repo's `.oxlintrc.jsonc` — `"jsPlugins": ["@pgxsinkit/client/oxlint"]` +
70
+ `"pgxsinkit/guarded-query-purity": "error"` — to catch a raw ``sql`…` `` fragment on the pure path and a
71
+ redundant `use` (autofixable), the two things the types can't. (oxlint `jsPlugins` is alpha.)
72
+
73
+ **The non-obvious rule — which relation to select FROM:**
74
+
75
+ - A **readonly** entry syncs only its **base table**. Read it from the entry's **`.table`**
76
+ (`registry.<name>.table`). There is no overlay.
77
+ - A **readwrite** entry also generates a `_read_model` **overlay view** that merges your own optimistic
78
+ (not-yet-synced) writes on top of the synced base rows. Read it from the entry's **`.view`**
79
+ (`registry.<name>.view`) — **not** its `.table`. Selecting the base `.table` of a readwrite entry
80
+ silently omits the writer's own pending writes, so a just-issued create/edit/delete will not appear
81
+ locally until it round-trips through Postgres and streams back via Electric.
82
+
83
+ ```ts
84
+ // readonly entry → base table
85
+ client.query((c) => c.drizzle.select({ id: catalogResource.table.id }).from(catalogResource.table));
86
+
87
+ // readwrite entry → overlay view, so your own optimistic writes are included
88
+ const reportView = registry.report.view!; // `.view` is populated only for readwrite entries
89
+ client.query((c) => c.drizzle.select({ id: reportView.id, status: reportView.status }).from(reportView));
90
+ ```
91
+
92
+ This is the read-side twin of "writes return through Electric": your optimistic write is visible
93
+ immediately **only because you read the overlay view**; the base table catches up when Postgres streams the
94
+ committed row back. (`c.views.<name>` is the client's accessor for the same overlay views; the entry's
95
+ `.view` object is the direct handle. Type note: `.view` is typed as optional on a `SyncTableEntry`, so a
96
+ non-null assertion — `registry.<name>.view!` — is expected at the read site.)
97
+
98
+ **Reaching the generated relations directly (factories).** For **diagnostics, tests, and tooling** — not
99
+ app code — `@pgxsinkit/client` exports a typed factory per generated relation so you author Drizzle instead
100
+ of hand-written SQL against `<t>_overlay` / `<t>_mutations` / `<t>_sync_state` / `<t>_read_model`:
101
+ `getSyncedLocalTable`, `getOverlayTable`, `getJournalTable`, `getSyncStateView`, `getReadModelView`,
102
+ `getLocalMetaTable` (all `(registry, tableKey)`; overlay/journal/sync-state/read-model are writable-only).
103
+
104
+ ```ts
105
+ import { getOverlayTable, getSyncStateView } from "@pgxsinkit/client";
106
+ const overlay = getOverlayTable(registry, "report"); // typed by property key: overlay.id, overlay.overlayKind
107
+ db.select({ pending: getSyncStateView(registry, "report").pendingCount }).from(getSyncStateView(registry, "report"));
108
+ ```
109
+
110
+ Why the factories (vs the entry handles): `entry.table` / `entry.localTable` are already schema-qualified
111
+ (built with the registry's schema, enforced to match it), so for the synced cache the factory only tracks
112
+ a `clientProjection.syncedTable` rename. But `entry.view` (the `_read_model` view) is built **unqualified**
113
+ — a non-public local schema _must_ read it via `getReadModelView` — and `_overlay` / `_mutations` /
114
+ `_sync_state` have **no entry handle at all**. All factory objects carry the registry's local schema and
115
+ memoize per `(registry, tableKey)` (`getLocalMetaTable` per local schema). Typing follows the registry — a
116
+ concretely-typed registry gives real per-column types (`overlay.col`, `$inferInsert`, `.values()` all
117
+ typecheck), a bare `SyncTableRegistry` degrades to bracket access (`overlay["col"]`). `getJournalTable` /
118
+ `getSyncStateView` are **always** conservatively indexed for entity/PK columns, but key them differently:
119
+ the journal by **DB column name** (`journal["author_id"]`), the sync-state view by the entry's **property
120
+ key** (`syncState["authorId"]`); the fixed runtime/state columns stay typed on both.
121
+ **In app code prefer the guarded `client.query`** — the factories are for reading the generated relations
122
+ directly (a test, a perf harness, a diagnostic), not a replacement for it.
123
+
124
+ ## Non-negotiables (each fails closed or throws)
125
+
126
+ 1. **The Electric subquery flag is mandatory.** Run Electric with
127
+ `ELECTRIC_FEATURE_FLAGS=allow_subqueries,tagged_subqueries`. Without it, sync **fails closed** — no
128
+ rows stream — which looks like a bug but is a missing flag. On **managed Electric Cloud** the flag is
129
+ activated per source by Electric staff on request (no self-serve toggle yet; default-on intended) —
130
+ ask Electric to enable subqueries for your source, or self-host Electric with the flag.
131
+ 2. **Writable tables have two hard requirements.** `defineSyncRegistry` throws unless every `readwrite`
132
+ table declares **both** a server-version managed field (a `nowMicroseconds`-on-update column,
133
+ conventionally `updated_at_us`, that optimistic convergence keys on) **and** a `conflictPolicy`
134
+ (`reject-if-stale` | `last-write-wins`). There is no silent default — a silent last-write-wins is the
135
+ exact data loss the choice exists to surface.
136
+ 3. **Managed fields are server-assigned.** Fields stamped by `authClaim` (a verified claim at a JSON path —
137
+ `["sub"]` is the old `auth.uid()` owner idiom) / `nowMicroseconds` are set by the apply function; the
138
+ write API **rejects** a client payload that includes them. Never send them.
139
+ 4. **Enum columns in a shape `where` must be cast to `text`** — `"role"::text = 'manager'`, not
140
+ `"role" = 'manager'`. The column stays an enum everywhere else. This is because **Electric**, not
141
+ Postgres, evaluates the shape filter.
142
+
143
+ ## Authorization runs in two engines — derive both from one predicate
144
+
145
+ A row must never be readable-but-unwritable (or the reverse). The two paths enforce auth in different
146
+ engines, so the subject is referenced two ways:
147
+
148
+ - **Write path — RLS in Postgres:** policies use `auth.uid()` / `current_setting('request.jwt.claims')`;
149
+ the applier sets the claims before applying a batch.
150
+ - **Read path — the shape `rowFilter`:** the proxy builds the Electric `where` and **Electric** runs it, so
151
+ a `customWhere` returns a Drizzle `SQL` fragment — reference columns through `c()` (bare, as Electric
152
+ needs) and bind `claims.sub` as a `$n` param (no hand-escaping); enum cast to `text`; `DENY_ALL` blocks
153
+ all rows.
154
+
155
+ Use `buildSupabaseOwnerOrAdminNativePolicies` / `buildSupabaseMembershipNativePolicies` for the common
156
+ owner/membership shapes — they take **Drizzle columns**, so call them in `defineSyncTable`'s `extras`
157
+ callback; compose your own from `pgPolicy` + Drizzle operators for anything beyond them (e.g. collaborative
158
+ any-member writes). Build the read filter and the RLS policy from the same Drizzle columns so they cannot
159
+ drift.
160
+
161
+ ## Membership changes converge the local store — both ways, even offline
162
+
163
+ A subquery (membership) read filter is reactive in **both** directions, against a running client with no
164
+ re-subscribe: granting a membership **materialises** the container's rows in the member's local PGlite;
165
+ revoking one **evicts** them (a row reachable through a second membership survives until its last grant is
166
+ gone). This holds **live and across an offline gap** — a client disconnected when the membership changed
167
+ converges on reconnect (the resume replays it), so a revoked member's read access never lingers offline.
168
+ Observe it on the live subscription or a normal resume, not by re-probing a shape at `offset=-1`.
169
+
170
+ ## Local PGlite schema is not full DDL parity
171
+
172
+ The local store generates enums, tables, the overlay, the journal, and convergence triggers — **not**
173
+ RLS, arbitrary triggers/functions, or managed-field defaults, and it does not enforce CHECK / FK /
174
+ UNIQUE the way Postgres does. Treat Postgres as the source of truth for integrity; do not assume a
175
+ constraint that holds server-side also holds in PGlite.
176
+
177
+ ## Common mistakes
178
+
179
+ - Expecting an optimistic write to echo back on the write channel — it returns through Electric.
180
+ - Forgetting the Electric subquery flag, then debugging "no rows" as a code bug.
181
+ - Omitting `conflictPolicy` (throws) or sending a managed field in a write payload (rejected).
182
+ - Comparing an enum without `::text` in a shape filter.
183
+ - Writing directly to Postgres tables / building per-table CRUD instead of using the one write path.
184
+ - Reading a **readwrite** entry from its base `.table` instead of its `.view` overlay, so your own
185
+ optimistic writes do not appear locally until they round-trip through Postgres.
186
+ - Assuming PGlite enforces every Postgres constraint.
187
+ - Assuming a revoked member keeps their synced rows offline — membership changes converge both ways,
188
+ live and on resume.
189
+
190
+ ## Where to look
191
+
192
+ - Concepts: the two paths, read path, write path, Electric subqueries, local-schema DDL parity, and
193
+ timestamps (microsecond BIGINT, decimal strings across the boundary).
194
+ - For deployment and runtime/operational behavior (cold starts, convergence cadence, the HTTP/2
195
+ connection budget, the `globalThis.__pgxsinkitDebug` latency instrumentation), load the `operating`
196
+ skill.
197
+ - Full prose: <https://pgxsinkit.github.io/llms-full.txt>.
@@ -0,0 +1,243 @@
1
+ ---
2
+ name: operating
3
+ description: >-
4
+ Load when deploying or operating a live pgxsinkit app, or when diagnosing a sync/write that "feels
5
+ slow" in a browser even though the server is fast. Covers the runtime and deployment properties around
6
+ the toolkit (not toolkit bugs) that decide whether a live app feels fast: convergence cadence (writes
7
+ flush on enqueue; the interval is only a fallback), serverless edge cold starts and warming, forcing
8
+ cache-control:no-store on a same-origin Electric shape proxy, the browser HTTP/2 connection budget when
9
+ many shapes are synced, setting the edge worker timeout above Electric's long-poll, the built-in
10
+ globalThis.__pgxsinkitDebug latency instrumentation, and worker mode (defineSyncWorker/attachSyncClient —
11
+ the whole engine in a SharedWorker off the main thread, with the debug rail forwarded to tabs as
12
+ [pgxsinkit·w], spare-as-worker boot, and per-group readiness). Load before shipping to production or when
13
+ writes take seconds to appear in another client.
14
+ metadata:
15
+ type: task
16
+ library: "@pgxsinkit/client"
17
+ library_version: "0.1.32"
18
+ source: https://pgxsinkit.github.io/start/operating-in-production/
19
+ ---
20
+
21
+ # Operating a pgxsinkit app in production
22
+
23
+ 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, and CDN-shaped
25
+ caching behave. If writes or sync feel slow in a real browser but server benchmarks are fast, start here.
26
+
27
+ ## Convergence cadence: event-driven, interval is a fallback
28
+
29
+ When you pass an `autoSync` trigger to `createSyncClient`, the client drives `flush → reconcile`. The
30
+ pass is **event-driven**: the client calls `requestPass()` the moment a mutation is enqueued, so a local
31
+ write flushes to the server immediately — it does **not** wait for the interval. The interval
32
+ (`createBrowserConvergenceTrigger({ intervalMs })`, default 1.5s; in worker mode `defineSyncWorker`'s
33
+ `convergenceIntervalMs`, default 15s) is only a fallback for retries/recovery/cross-tab.
34
+
35
+ Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
36
+ ~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
+ convergence latency** (latency is bounded by the Electric echo, not the interval). Do **not** shorten
39
+ the interval to "make writes faster" — it does nothing and burns CPU.
40
+
41
+ ## Serve the gateway over HTTP/2 (the connection budget)
42
+
43
+ Electric's client holds **one live long-poll connection open per synced shape**. A client subscribing to
44
+ six shapes keeps six connections busy, and browsers cap **HTTP/1.1 at ~6 connections per origin** — so
45
+ over plain HTTP those long-polls consume every slot and the **write** request (same origin) is
46
+ **Stalled in the browser's connection queue** for a whole long-poll cycle before it is even dispatched.
47
+ This presents as multi-second writes that are invisible to `curl`/Node (which have no per-host cap) —
48
+ only a real browser shows it (DevTools → Network → a stuck `write` with a long **Stalled** time).
49
+
50
+ Fix: serve the gateway over **HTTP/2** (or HTTP/3), which multiplexes every request over one connection.
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).
53
+
54
+ ## Serverless edge cold starts
55
+
56
+ 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
+ ~0.45s after ~15s idle, ~5.8s on a cold module cache). This is a property of the deployment target, not
59
+ pgxsinkit — a long-lived Bun/Deno process or a managed warm pool has none. Mitigate: keep the worker warm
60
+ with a periodic cheap request (an empty `{"mutations":[]}` POST, rejected at validation before any DB
61
+ work), and set the worker wall-clock timeout **above** Electric's ~25s long-poll so a live subscription
62
+ is not recycled mid-cycle.
63
+
64
+ Region-pin **only the DB-bound write function**, not read proxies. Pinning the write function's execution
65
+ to the database's region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; a
66
+ read proxy's upstream is Electric Cloud's global CDN, so pinning reads away from a distant caller instead
67
+ **adds** intercontinental hops per catch-up (~1.2s vs ~300ms). `createSyncClient` splits this cleanly:
68
+ `requestHeaders` is the shared base (sent on reads AND writes — e.g. a gateway `apikey`), and
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.
71
+
72
+ ## Pre-warming PGlite's boot assets
73
+
74
+ 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
+ paint. `createSyncClient` takes a `pgliteBootAssets` option: a promise of the already-fetched/compiled
77
+ assets (`{ pgliteWasmModule?, initdbWasmModule?, fsBundle? }`), awaited and passed straight into
78
+ `PGlite.create` so it skips its own lazy load. Start the fetch+compile on an **earlier screen** (a login /
79
+ identity picker) and hand the pending promise in — the WASM cost then hides behind user think-time. It is
80
+ best-effort: a rejected warm is caught to `undefined` and PGlite loads its own assets, so the warm never
81
+ fails the boot. The `boot pglite assets warm` rail stamp times it. (Board demo: `apps/board/src/board/
82
+ pglite-warm.ts` shows the Vite `?url` asset-URL pattern PGlite's `exports` field otherwise blocks.)
83
+
84
+ Pre-warming only hides the WASM fetch+compile; `PGlite.create` still spends ~1.9s on `initdb` + store open,
85
+ and that can't start until the store id is known (usually the signed-in user). To hide it too, create the
86
+ store EAGERLY under a generated id on the first screen and BIND it at auth. `createClientPGlite(dataDir,
87
+ { bootAssets })` runs the exact same create the client does internally (electric + live extensions, warm
88
+ consumption, the `boot pglite.create` stamp) and returns a schemaless instance; hand the still-pending
89
+ promise to `createSyncClient`'s `precreatedPglite` option. Unlike `pgliteInstance` (caller owns schema),
90
+ `precreatedPglite` lets the client still run schema exec, prepare hooks, journal recovery and store-version
91
+ reconcile — so the eager create buys only `initdb`, and the role/registry-derived schema stays post-auth. A
92
+ rejected `precreatedPglite` is caught and falls back to the `dataDir` create path (which also consumes
93
+ `pgliteBootAssets`), so it is a pure accelerator, never a boot dependency. Bind eager stores to users with a
94
+ small localStorage registry (userId→storeId plus one unbound "spare"): create a spare on the login screen,
95
+ claim it at sign-in, and GC any store that is neither mapped nor the spare. On a signed-in RELOAD there is
96
+ no login screen to create ahead of, so START the mapped-store open at app bootstrap (before React render),
97
+ memoised per userId so the provider's later open adopts it rather than opening a second instance. (Board
98
+ demo: `apps/board/src/board/store-registry.ts`, `store-prewarm.ts`.)
99
+
100
+ ## Worker mode: the engine in a SharedWorker (browser apps)
101
+
102
+ In a browser, prefer running the whole engine in a **SharedWorker** instead of on the calling thread: PGlite,
103
+ the shape streams, the journal machinery, and the convergence loop all leave the main thread, and N tabs
104
+ dedupe onto ONE engine/store/Electric-connection-set (the worker is named by its store id — which also
105
+ removes the two-tabs-one-store hazard structurally, no leader election). `createSyncClient` stays the
106
+ in-process mode for bun/Node and as the **fallback where `SharedWorker` is missing** (correct, just
107
+ main-thread) — so worker mode is never a hard dependency.
108
+
109
+ **Two-file pattern.** A worker entry (bundled as a worker) calls `defineSyncWorker({ registry, electricUrl,
110
+ writeUrl, … })` at module top level — the registry is CODE, _imported_ by the worker file, never cloned/
111
+ serialized in. The tab calls `attachSyncClient({ worker, registry, getToken })`, which returns the same
112
+ client shape as `createSyncClient` (write API, Drizzle read BUILDING on the tab, live rows,
113
+ `ready`/`status`/`stop`) plus `notifyAuthChanged` and `setOnline`, proxied to the shared engine. One-shot
114
+ `query`/`queryRaw` and local `pglite`/`ensureSynced`/`destroy` are NOT proxied (they throw) — reactive live
115
+ rows are the read path in worker mode. The exception is the INSPECTION surface `rawQuery(sql, params)` /
116
+ `rawExec(sql)` (debug pages, REPLs, ad-hoc counts): identical on both clients (executed in the worker on the
117
+ attach client), it runs raw against the local store — bypasses the journal/overlay, any write stays local
118
+ and never converges — so it is not an app-data read path. `replAdapter(client)` shapes it into the
119
+ `{ 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
120
+ `resolveRegistry(role)` + the tab's `role` (the board's admin/member registries; the spare needs it).
121
+
122
+ **Auth stays tab-owned (ADR-0013).** The tab pushes `{accessToken, expiresAt}` at attach and on
123
+ `notifyAuthChanged`; the worker uses the cached token and sends a pull-request only when a request finds it
124
+ near expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher,
125
+ so GoTrue refresh-token reuse detection can't be tripped by a second client.
126
+
127
+ **Boot: spare-as-worker + internal prefetch overlap.** The spare store (see above) becomes a pre-spawned
128
+ schemaless worker at the login screen (create + initdb off every thread that matters); the userId→storeId
129
+ registry stays tab-side in localStorage so binding resolves before attach (SharedWorker naming needs it).
130
+ Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store, pass
131
+ `attachSyncClient({ freshStore: true })` (never for a mapped/returning store) and the worker overlaps the
132
+ shape catch-up with schema/journal/store-version recovery — far-user boot bounded by `max(create+schema,
133
+ catch-up)`, not their sum. New boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`,
134
+ `boot store claimed`, `boot shape prefetch start`, `boot commits opened`.
135
+
136
+ **`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
137
+ progressive paint use `await client.groupReady(tableKey)` or read `status.groups` — no contract change.
138
+
139
+ **Debug rail is forwarded and origin-tagged.** A SharedWorker's own console is invisible to the page (only
140
+ `chrome://inspect`), so the worker forwards every rail line to each tab, stamped with the WORKER's monotonic
141
+ clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. Set
142
+ the flag on the TAB as usual; the write/read/boot phases below read the same, just origin-tagged. Full model:
143
+ <https://pgxsinkit.github.io/concepts/worker-mode/>.
144
+
145
+ ## Proxying Electric: force `cache-control: no-store`
146
+
147
+ Electric tags shape responses with a CDN-oriented `cache-control` (`max-age`, `stale-while-revalidate`).
148
+ Behind a **same-origin proxy with no CDN**, the browser cache serves them **stale** the moment a shape
149
+ handle rotates (re-seed, re-login, restart), and the client loops on "expired shape handle" **409s**
150
+ until it self-heals. Force `cache-control: no-store` on the proxied response:
151
+
152
+ ```ts
153
+ const response = await proxyElectricShapeRequest(request, claims, { registry, electricUrl });
154
+ const headers = new Headers(response.headers);
155
+ headers.set("cache-control", "no-store");
156
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
157
+ ```
158
+
159
+ Resumption stays cheap because Electric's offset/handle bookkeeping (in the local store) makes it cheap,
160
+ not the HTTP cache.
161
+
162
+ Upstream direction, hosted Electric behind a CDN: live long-polls can be answered by a layer blind to
163
+ fresh commits (consecutive full-hold `up-to-date` responses at an unmoved offset → ~40–90s cross-client
164
+ propagation). The proxy appends a unique `cache-buster` to every `live=true` upstream request by default
165
+ (`bustLiveUpstreamCache`; catch-up stays unbusted for CDN cold-fanout sharing). TEMPORARY
166
+ upstream-defect mitigation — it defeats Electric's sanctioned live-poll coalescing (per-client origin
167
+ fan-out at scale); flip off once Electric Cloud wakes coalesced polls reliably. Distinct from the
168
+ ADR-0033 sibling nudge, which is permanent protocol behavior. Running your own CDN in front of
169
+ self-hosted Electric: key on the FULL query string (every param is load-bearing), respect origin
170
+ cache-control, keep SWR windows modest, let coalesced live polls complete immediately on origin
171
+ response, read-timeouts 60s+, then VERIFY with bust off — cross-client render ≲3s = healthy, ~a full
172
+ hold cycle = live path served blind (full checklist: operating-in-production docs page). Harmless
173
+ self-hosted;
174
+ set `false` to restore untouched forwarding.
175
+
176
+ ## Debugging latency: `globalThis.__pgxsinkitDebug`
177
+
178
+ `@pgxsinkit/client` ships opt-in, off-by-default, timestamped instrumentation that traces a write through
179
+ every phase. Enable it from the console or before boot:
180
+
181
+ ```js
182
+ globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pgxsinkit" + enable Verbose
183
+ ```
184
+
185
+ Read the **gaps** between phases: `mutation staged {mutationId, table}` (the write's origin — correlate
186
+ by id with the later sent/acked lines); `convergence pass requested` → `flush` / `reconcile`
187
+ (durations); `board-write auth token resolved {ms}` (a stalling per-request token fetch shows here);
188
+ `board-write responded {status, ms}` (a cold worker, or a browser connection stall, shows here);
189
+ `sync received change batch` → `sync applied {ms}` (truthful: fires only when the batch committed — a
190
+ batch gated behind a quiet sibling's watermark logs `sync change batch held by group frontier` +
191
+ `live-tail sibling nudge {shape}` instead, ADR-0033); `live query updated → re-render`. The read path has
192
+ its own pair: `shape request start {shape, offset, live}` → `shape request done {shape, status, ms,
193
+ upToDate?}` for EVERY Electric HTTP cycle (catch-up and long-poll), plus `must-refetch received {shape}`
194
+ when the server rotates a shape (the truncate + re-snapshot recovery trigger — the thing to look for
195
+ when a table unexpectedly re-syncs). Server-side, `createSyncServer({ logTimings: true })` emits the
196
+ matching per-request `[pgxsinkit-timing]` lines (see the `deploying` skill, `@pgxsinkit/server`);
197
+ client-observed minus server `totalMs` isolates routing + network. Boot is stamped too — the `boot
198
+ pglite.create` → `boot client ready` phases (local store open, schema apply, journal recovery,
199
+ store-version reconcile, sync start) let you attribute a slow first paint to a specific boot phase, and
200
+ `boot pglite assets warm` times the optional boot-asset pre-warm (see below).
201
+
202
+ A `catch-up watermark aligned {floor}` line marks the one moment the group finished its initial catch-up
203
+ and aligned its commit floors (ADR-0031). Electric's catch-up responses are CDN-cacheable and carry the
204
+ `up-to-date` watermark inside the cached body, so a quiet shape's stale cached watermark would otherwise
205
+ hold a busy shape's fresh changes until the quiet shape's first live long-poll (~41s on Electric Cloud —
206
+ the "stale board that rearranges itself" symptom). The client aligns once to the freshest asserted head
207
+ instead; the trade is a sub-second torn view of a multi-table transaction at load, self-healing in one
208
+ round trip, rather than a consistent-but-seconds-stale one. The same hold recurs on the **live tail**
209
+ (a quiet sibling's parked long-poll returns only at hold expiry), where the engine **nudges** the
210
+ laggards instead of waiting — `sync change batch held by group frontier` → `live-tail sibling nudge
211
+ {shape, target, round}` → commit on the refreshed watermarks; `live-tail nudge exhausted` means a
212
+ sibling never advanced and the engine degraded to waiting out its poll (ADR-0033). Full prose:
213
+ <https://pgxsinkit.github.io/start/operating-in-production/>.
214
+
215
+ **Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
216
+ a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
217
+ instrumentation's network timings and a server-side `curl` over a poll loop.
218
+
219
+ **Inspecting a stuck or failed write.** To see _why_ a write is not converging — its journal status,
220
+ attempt/retry counts, last error, or a table's pending/conflict/quarantine state — read the generated
221
+ journal and sync-state relations with the typed factories `getJournalTable(registry, tableKey)` /
222
+ `getSyncStateView(registry, tableKey)` from `@pgxsinkit/client` (typed Drizzle, no hand-written SQL against
223
+ `<t>_mutations`). One-shot diagnostic reads only — don't poll them in a loop.
224
+
225
+ **Rolling back a terminal write.** Both terminal dispositions keep the optimistic overlay and now have a
226
+ symmetric discard. A stale-write `conflicted` row (fired via `onConflict`) rolls back with
227
+ `client.discardConflict(table, entityKey)`; a structurally-rejected `quarantined` row (fired via
228
+ `onQuarantine` — a validation failure or a permanent policy denial such as an RLS `42501`) rolls back
229
+ with `client.discardQuarantined(table, entityKey)`. Each clears the entity's terminal journal rows +
230
+ kept overlay, so the read model falls back to the synced value and the entity accepts new mutations
231
+ again (a lingering terminal row otherwise blocks a re-create and chains a later update onto a dead head).
232
+ Because quarantine has a real rollback now, route a permanent policy denial to `quarantined` — don't
233
+ mis-route it to `conflicted` to borrow a discard.
234
+
235
+ ## Common mistakes
236
+
237
+ - Shortening the convergence interval to chase write latency (no effect; wastes CPU).
238
+ - Serving many-shape sync over plain HTTP/1.1 and blaming the server for stalled writes.
239
+ - Omitting `cache-control: no-store` on a same-origin shape proxy → intermittent 409 loops.
240
+ - Treating an edge cold start as a toolkit/sync-rail problem.
241
+ - Measuring latency by polling PGlite in a loop instead of at the network boundary.
242
+
243
+ Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The opt-in convergence driver (ADR-0005 decision 3).
3
+ *
4
+ * The mechanism primitives (`flush` / `reconcile` / `retryFailed`) stay public and manual.
5
+ * This driver is the *scheduling-policy seam*: the app decides WHEN to converge (online?
6
+ * foregrounded? on power?) and how it learns those conditions, while the library owns the
7
+ * convergence pass and the congestion policy (jittered backoff + attempt cap, already in the
8
+ * mutation runtime). Pass nothing to `createSyncClient` → fully manual, today's behaviour.
9
+ *
10
+ * A pass is `flush` → `reconcile`. It deliberately does NOT call `retryFailed`: `flush`
11
+ * already re-attempts `failed` mutations whose `next_retry_at_us` backoff has elapsed, so a
12
+ * pass leaves the jittered backoff intact. Calling `retryFailed` on every pass would reset
13
+ * every failed mutation to "due now" and, under a short trigger interval, burn the whole
14
+ * attempt budget during a transient outage and quarantine writes prematurely. `retryFailed`
15
+ * stays a manual, user-initiated primitive ("retry my failed writes now").
16
+ */
17
+
18
+ import { syncDebug, timeAsync } from "./debug";
19
+
20
+ /** The mechanism primitives a convergence pass schedules. */
21
+ export interface ConvergenceClient {
22
+ flush: () => Promise<void>;
23
+ reconcile: () => Promise<void>;
24
+ }
25
+
26
+ /**
27
+ * The scheduling-policy seam. Browser (`online` / `visibilitychange`) and React Native
28
+ * (`AppState` / `NetInfo`) are two genuine adapters — which is what earns this its place as a
29
+ * seam rather than being inlined.
30
+ */
31
+ export interface ConvergenceTrigger {
32
+ /** Register a callback fired whenever the app wants a convergence attempt; returns an unsubscribe. */
33
+ subscribe: (onSignal: () => void) => () => void;
34
+ /** Whether a convergence pass should run right now (e.g. online and foregrounded). */
35
+ shouldConverge: () => boolean;
36
+ }
37
+
38
+ export interface ConvergenceDriverOptions {
39
+ client: ConvergenceClient;
40
+ trigger: ConvergenceTrigger;
41
+ /** Invoked after each convergence pass with the error it raised, or `null` on success. */
42
+ onPass?: (error: unknown) => void;
43
+ }
44
+
45
+ export interface ConvergenceDriver {
46
+ start: () => void;
47
+ /**
48
+ * Stop scheduling and **await any in-flight pass** before resolving, so a caller can then
49
+ * safely close or wipe the underlying database without a pass racing against it. Idempotent.
50
+ */
51
+ stop: () => Promise<void>;
52
+ /**
53
+ * Request a convergence pass now — the event-driven path. The client calls this the moment a
54
+ * mutation is enqueued, so a local write flushes immediately instead of waiting for the trigger's
55
+ * next interval tick. Coalesced exactly like a trigger signal (one pass at a time; a request mid-pass
56
+ * queues a single follow-up) and still gated by `shouldConverge()`, so a write made while offline
57
+ * stages without flushing. With this, the trigger's interval is only a fallback (retries/recovery),
58
+ * which lets it run far less often — the interval, not real convergence, is what costs idle CPU.
59
+ */
60
+ requestPass: () => void;
61
+ }
62
+
63
+ /**
64
+ * Drive convergence from a {@link ConvergenceTrigger}. Each signal runs at most one pass at a
65
+ * time (`flush` → `reconcile`); a signal arriving mid-pass coalesces into a single follow-up
66
+ * pass, so a burst of triggers never stampedes the server (the per-mutation backoff in the
67
+ * runtime handles the rest).
68
+ */
69
+ export function createConvergenceDriver(options: ConvergenceDriverOptions): ConvergenceDriver {
70
+ let unsubscribe: (() => void) | null = null;
71
+ let running = false;
72
+ let queued = false;
73
+ let disposed = false;
74
+ // The promise of the pass currently in flight, so stop() can await it before teardown.
75
+ let currentPass: Promise<void> | null = null;
76
+
77
+ const runPass = async (): Promise<void> => {
78
+ if (disposed || running) {
79
+ if (!disposed) {
80
+ queued = true;
81
+ }
82
+ // The signal that mattered most for latency: a write asked to converge but a pass was already
83
+ // running, so this one coalesces and waits for the current pass to finish before it flushes.
84
+ syncDebug("convergence pass coalesced (one already running)", { disposed, queued });
85
+ return;
86
+ }
87
+
88
+ if (!options.trigger.shouldConverge()) {
89
+ syncDebug("convergence pass skipped (shouldConverge=false: offline or backgrounded)");
90
+ return;
91
+ }
92
+
93
+ running = true;
94
+ let error: unknown = null;
95
+ const pass = (async () => {
96
+ try {
97
+ await timeAsync("convergence flush", () => options.client.flush());
98
+ await timeAsync("convergence reconcile", () => options.client.reconcile());
99
+ } catch (passError) {
100
+ error = passError;
101
+ }
102
+ })();
103
+ currentPass = pass;
104
+ await pass;
105
+ running = false;
106
+ currentPass = null;
107
+ options.onPass?.(error);
108
+
109
+ if (queued && !disposed) {
110
+ queued = false;
111
+ void runPass();
112
+ }
113
+ };
114
+
115
+ return {
116
+ start: () => {
117
+ if (unsubscribe || disposed) {
118
+ return;
119
+ }
120
+
121
+ unsubscribe = options.trigger.subscribe(() => {
122
+ void runPass();
123
+ });
124
+ void runPass();
125
+ },
126
+ stop: async () => {
127
+ disposed = true;
128
+ queued = false;
129
+ unsubscribe?.();
130
+ unsubscribe = null;
131
+ // Await the in-flight pass (if any) so the DB is quiescent before the caller closes/wipes it.
132
+ await currentPass;
133
+ },
134
+ requestPass: () => {
135
+ syncDebug("convergence pass requested (event-driven, e.g. local write enqueued)");
136
+ void runPass();
137
+ },
138
+ };
139
+ }
140
+
141
+ /** Minimal browser globals the trigger needs, read off `globalThis` so the library carries no DOM lib dependency. */
142
+ interface EventTargetLike {
143
+ addEventListener: (type: string, handler: () => void) => void;
144
+ removeEventListener: (type: string, handler: () => void) => void;
145
+ }
146
+ interface BrowserEnv {
147
+ window?: EventTargetLike;
148
+ document?: EventTargetLike & { visibilityState?: string };
149
+ navigator?: { onLine?: boolean };
150
+ }
151
+
152
+ /**
153
+ * Browser convergence trigger: fires on `online`, `visibilitychange`, and a fallback interval,
154
+ * and converges only while online and not backgrounded. The adapter most apps use.
155
+ */
156
+ export function createBrowserConvergenceTrigger(options: { intervalMs?: number } = {}): ConvergenceTrigger {
157
+ const intervalMs = options.intervalMs ?? 1500;
158
+ const env = globalThis as unknown as BrowserEnv;
159
+
160
+ return {
161
+ subscribe: (onSignal) => {
162
+ const handler = () => {
163
+ onSignal();
164
+ };
165
+ env.window?.addEventListener("online", handler);
166
+ env.document?.addEventListener("visibilitychange", handler);
167
+ const timer = setInterval(handler, intervalMs);
168
+
169
+ return () => {
170
+ env.window?.removeEventListener("online", handler);
171
+ env.document?.removeEventListener("visibilitychange", handler);
172
+ clearInterval(timer);
173
+ };
174
+ },
175
+ shouldConverge: () => env.navigator?.onLine !== false && env.document?.visibilityState !== "hidden",
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Interval convergence trigger: fires on a fixed cadence and always converges. The minimal
181
+ * non-browser adapter — usable directly in tests/servers and the base a React Native
182
+ * `AppState`/`NetInfo` adapter builds on — which is the second adapter that proves the seam.
183
+ */
184
+ export function createIntervalConvergenceTrigger(intervalMs: number): ConvergenceTrigger {
185
+ return {
186
+ subscribe: (onSignal) => {
187
+ const timer = setInterval(() => {
188
+ onSignal();
189
+ }, intervalMs);
190
+
191
+ return () => {
192
+ clearInterval(timer);
193
+ };
194
+ },
195
+ shouldConverge: () => true,
196
+ };
197
+ }