@pgxsinkit/client 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/boot-report.d.ts +5 -2
- package/dist/boot-report.d.ts.map +1 -1
- package/dist/circuits/envelope-to-change.d.ts +35 -0
- package/dist/circuits/envelope-to-change.d.ts.map +1 -0
- package/dist/circuits/group-sync.d.ts +123 -0
- package/dist/circuits/group-sync.d.ts.map +1 -0
- package/dist/circuits/shape-group.d.ts +77 -0
- package/dist/circuits/shape-group.d.ts.map +1 -0
- package/dist/circuits/stream-inbox.d.ts +126 -0
- package/dist/circuits/stream-inbox.d.ts.map +1 -0
- package/dist/circuits/stream-source.d.ts +90 -0
- package/dist/circuits/stream-source.d.ts.map +1 -0
- package/dist/circuits/subscription-client.d.ts +143 -0
- package/dist/circuits/subscription-client.d.ts.map +1 -0
- package/dist/circuits/sync-engine.d.ts +131 -0
- package/dist/circuits/sync-engine.d.ts.map +1 -0
- package/dist/debug.d.ts +0 -10
- package/dist/debug.d.ts.map +1 -1
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/index.d.ts +47 -19
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6258 -6443
- package/dist/index.js.map +26 -26
- package/dist/local-tables.d.ts +1 -1
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +13 -21
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +8 -8
- package/dist/sync/fold.d.ts +40 -0
- package/dist/sync/fold.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +25 -1
- package/dist/sync/metadata-tables.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +21 -2
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/sync/types.d.ts +9 -129
- package/dist/sync/types.d.ts.map +1 -1
- package/dist/testing.js +3 -3
- package/dist/testing.js.map +2 -2
- package/dist/worker/attach-sync-client.d.ts +3 -1
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +17 -1
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/engine-control.d.ts +53 -0
- package/dist/worker/engine-control.d.ts.map +1 -1
- package/package.json +4 -5
- package/skills/core/SKILL.md +72 -55
- package/skills/operating/SKILL.md +120 -120
- package/src/boot-report.ts +4 -3
- package/src/circuits/envelope-to-change.ts +102 -0
- package/src/circuits/group-sync.ts +1047 -0
- package/src/circuits/shape-group.ts +158 -0
- package/src/circuits/stream-inbox.ts +225 -0
- package/src/circuits/stream-source.ts +165 -0
- package/src/circuits/subscription-client.ts +353 -0
- package/src/circuits/sync-engine.ts +641 -0
- package/src/debug.ts +1 -85
- package/src/export-dump.ts +3 -2
- package/src/index.ts +290 -273
- package/src/lazy-guard.ts +1 -1
- package/src/local-tables.ts +9 -2
- package/src/schema.ts +2 -11
- package/src/sync/apply.ts +72 -110
- package/src/sync/copy.ts +15 -15
- package/src/sync/fold.ts +94 -0
- package/src/sync/metadata-tables.ts +42 -1
- package/src/sync/subscription-state.ts +21 -3
- package/src/sync/types.ts +13 -141
- package/src/testing.ts +2 -2
- package/src/worker/attach-sync-client.ts +8 -1
- package/src/worker/define-sync-worker.ts +122 -13
- package/src/worker/engine-control.ts +89 -0
- package/dist/read-stream-stall.d.ts +0 -54
- package/dist/read-stream-stall.d.ts.map +0 -1
- package/dist/shape-sync.d.ts +0 -207
- package/dist/shape-sync.d.ts.map +0 -1
- package/dist/sync/index.d.ts +0 -32
- package/dist/sync/index.d.ts.map +0 -1
- package/dist/sync/nudge.d.ts +0 -49
- package/dist/sync/nudge.d.ts.map +0 -1
- package/dist/sync/shape-inbox.d.ts +0 -215
- package/dist/sync/shape-inbox.d.ts.map +0 -1
- package/dist/sync/tags.d.ts +0 -142
- package/dist/sync/tags.d.ts.map +0 -1
- package/dist/sync-auth.d.ts +0 -53
- package/dist/sync-auth.d.ts.map +0 -1
- package/src/read-stream-stall.ts +0 -102
- package/src/shape-sync.ts +0 -533
- package/src/sync/index.ts +0 -1124
- package/src/sync/nudge.ts +0 -110
- package/src/sync/shape-inbox.ts +0 -566
- package/src/sync/tags.ts +0 -390
- package/src/sync-auth.ts +0 -117
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: operating
|
|
3
3
|
description: >-
|
|
4
|
-
Load when deploying or operating a
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
worker timeout vs
|
|
10
|
-
|
|
11
|
-
the forwarded rail), the store lifecycle
|
|
12
|
-
|
|
13
|
-
observability: onOutboxStatus, onEventLaneReport verdicts including
|
|
14
|
-
destroy/restore/backup
|
|
4
|
+
Load when deploying or operating a pgxsinkit app, when a sync/write "feels slow" in a browser
|
|
5
|
+
but the server is fast, or when wiring backups/export/restore. Covers the runtime/deployment
|
|
6
|
+
properties (not toolkit bugs) deciding whether an app feels fast: convergence cadence (writes
|
|
7
|
+
flush on enqueue; the interval is a fallback), serverless edge cold starts, the read path's cache
|
|
8
|
+
split (no-store control plane, cacheable edge on its own origin, token out of the cache key), the
|
|
9
|
+
browser HTTP/2 connection budget, the edge worker timeout vs the durable-streams long-poll hold,
|
|
10
|
+
globalThis.__pgxsinkitDebug + the BootReport, worker mode (defineSyncWorker/attachSyncClient —
|
|
11
|
+
capability-driven engine placement, relocation outcomes, the forwarded rail), the store lifecycle
|
|
12
|
+
surface (storePath naming, durability, backend permanence, destruction, the three exports,
|
|
13
|
+
restoreFrom), and Event-lane observability: onOutboxStatus, onEventLaneReport verdicts including
|
|
14
|
+
deferred-on-skew, and the Outbox across destroy/restore/backup.
|
|
15
15
|
metadata:
|
|
16
16
|
type: task
|
|
17
17
|
library: "@pgxsinkit/client"
|
|
18
|
-
library_version: "0.
|
|
18
|
+
library_version: "0.3.0"
|
|
19
19
|
source: https://pgxsinkit.github.io/start/operating-in-production/
|
|
20
20
|
---
|
|
21
21
|
|
|
@@ -36,34 +36,36 @@ retries/recovery/cross-tab.
|
|
|
36
36
|
Therefore **keep the interval long.** A short interval is the dominant idle cost: every PGlite query is
|
|
37
37
|
~50ms of WASM work on one thread, and an unconditional reconcile each tick re-runs every live query. The
|
|
38
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
|
|
39
|
+
latency** (latency is bounded by the read-path 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
|
-
|
|
44
|
-
**HTTP/1.1 at ~6 connections per origin** — so over
|
|
45
|
-
the same-origin **write** request is **Stalled in the
|
|
46
|
-
cycle before it is even dispatched. This presents as
|
|
47
|
-
per-host cap); only a real browser shows it (DevTools → Network
|
|
48
|
-
time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which
|
|
49
|
-
connection. Any production ingress already does; it only bites a local stack
|
|
50
|
-
only negotiate HTTP/2 over TLS).
|
|
43
|
+
`@durable-streams/client` holds **one live long-poll connection open per subscribed stream** (a subject in K
|
|
44
|
+
scopes of a shared shape holds K streams), and browsers cap **HTTP/1.1 at ~6 connections per origin** — so over
|
|
45
|
+
plain HTTP six streams' long-polls consume every slot and the same-origin **write** request is **Stalled in the
|
|
46
|
+
browser's connection queue** for a whole long-poll cycle before it is even dispatched. This presents as
|
|
47
|
+
multi-second writes invisible to `curl`/Node (no per-host cap); only a real browser shows it (DevTools → Network
|
|
48
|
+
→ a stuck `write` with a long **Stalled** time). Fix: serve the gateway over **HTTP/2** (or HTTP/3), which
|
|
49
|
+
multiplexes every request over one connection. Any production ingress already does; it only bites a local stack
|
|
50
|
+
on plain `http://` (browsers only negotiate HTTP/2 over TLS).
|
|
51
51
|
|
|
52
52
|
## Serverless edge cold starts
|
|
53
53
|
|
|
54
|
-
On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
54
|
+
On a serverless edge a worker is suspended when idle and evicted after longer idle, so the **first write after a
|
|
55
|
+
quiet period** pays a cold start while steady-state writes are instant (measured: ~20ms warm, ~0.45s after ~15s
|
|
56
|
+
idle, ~5.8s on a cold module cache). That is the deployment target, not pgxsinkit — a long-lived Bun/Deno
|
|
57
|
+
process or a managed warm pool has none. Mitigate: keep the worker warm with a periodic cheap request (an empty
|
|
58
|
+
`{"mutations":[]}` POST, rejected at validation before any DB work), and set the worker wall-clock timeout
|
|
59
|
+
**above** the durable-streams long-poll hold so a live subscription is not recycled mid-cycle (the board gives
|
|
60
|
+
its read functions `EDGE_WORKER_TIMEOUT_MS: "600000"`, not the stock 60s).
|
|
61
|
+
|
|
62
|
+
Region-pin **only the DB-bound write function**, never the two read functions. Pinning it to the database's
|
|
63
|
+
region (Supabase `x-region`) keeps its chatty function→DB protocol on a ~1ms loop; the read halves are not
|
|
64
|
+
DB-bound at all — the control plane's upstream is the Circuits engine, the edge's is durable-streams — and the
|
|
65
|
+
edge wants to sit near the CALLER, so catch-up bytes take the short hop. `createSyncClient` splits this:
|
|
66
|
+
`requestHeaders` is the shared base (reads AND writes — e.g. a gateway `apikey`), `writeRequestHeaders` is
|
|
67
|
+
merged over it on the write path only. Put the region header in `writeRequestHeaders`, never in the shared
|
|
68
|
+
`requestHeaders`.
|
|
67
69
|
|
|
68
70
|
## Pre-warming PGlite's boot assets
|
|
69
71
|
|
|
@@ -121,9 +123,10 @@ its class) and carries the refused `storePath`; a no-grant `provision` declines
|
|
|
121
123
|
reason rather than pre-minting the sibling.
|
|
122
124
|
|
|
123
125
|
**Two-file pattern.** One worker entry, bundled for both SharedWorker and dedicated Worker, calls
|
|
124
|
-
`defineSyncWorker({ registry,
|
|
125
|
-
|
|
126
|
-
|
|
126
|
+
`defineSyncWorker({ registry, controlPlaneUrl, streamBaseUrl, batchWriteUrl, … })` at module top level (read
|
|
127
|
+
URLs both-or-neither, as on `createSyncClient`) — no placement or durability option (both are
|
|
128
|
+
runtime/registry concerns); the registry is CODE, _imported_ by the worker file, never cloned/serialized
|
|
129
|
+
in. Give each store a stable SharedWorker name and always pass
|
|
127
130
|
`extendedLifetime: true` (Chromium 148+ grace period; ignore-safe elsewhere). The tab calls
|
|
128
131
|
`attachSyncClient({ worker, registry, getToken })`. Prefer the **factory** form (`worker: () => SharedWorker`)
|
|
129
132
|
over a bare instance or a raw `port` — a SharedWorker cannot be reconstructed from itself, so **in elected
|
|
@@ -173,25 +176,25 @@ disposes live queries before closing that client's engine and store.
|
|
|
173
176
|
expiry (any tab answers via `getToken`, first wins). The worker NEVER refreshes — exactly one refresher, so
|
|
174
177
|
GoTrue refresh-token reuse detection can't be tripped by a second client.
|
|
175
178
|
|
|
176
|
-
**Boot: spare-as-worker
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
`boot
|
|
179
|
+
**Boot: spare-as-worker.** The spare store (see above) becomes a pre-spawned schemaless worker at the login
|
|
180
|
+
screen (create + initdb off every thread that matters); the userId→storeId registry stays tab-side in
|
|
181
|
+
localStorage so binding resolves before attach (SharedWorker naming needs it). Call `provisionSyncWorker` with
|
|
182
|
+
the same `worker` input as attach (the factory form, so elected-mode recovery is armed for provisioning too); an
|
|
183
|
+
elected pre-open shares the tab's one election coordinator and derives the engine from the SharedWorker's own
|
|
184
|
+
script URL. `provisionExpiryMs` (default 60000) is ONE deadline: it retires the abandoned elected claim AND
|
|
185
|
+
settles the returned promise with the typed `ProvisionExpiredError` in both modes, so a provision behind a dead
|
|
186
|
+
SharedWorker connection fails loudly rather than hanging. It bounds YOUR promise; the worker-side create attempt
|
|
187
|
+
follows the placement. SW-direct: the attempt is left running — a later attach adopts it if it completed and
|
|
188
|
+
waits on it if it is stuck, and a retried provision re-acks the same attempt rather than opening a second.
|
|
189
|
+
Elected: the deadline also releases the provision claim, and a LAST-claim release retires and terminates the
|
|
190
|
+
engine with that attempt inside it, so the next attach elects a fresh one (an attach that adopted the
|
|
191
|
+
coordinator earlier keeps its claim, and that engine). Fire-and-forget callers should `.catch()` it like any
|
|
192
|
+
un-awaited promise. Claim = bind id, attach, push config + token. On a PROVABLY-fresh claimed store pass
|
|
193
|
+
`attachSyncClient({ freshStore: true })` (never for a mapped/returning store): it asserts freshness, so streams
|
|
194
|
+
start from the beginning and the subscription-state read is skipped — a wrong `true` on a warm store
|
|
195
|
+
re-snapshots instead of resuming. It buys no catch-up/schema OVERLAP (that needed a commit gate the native read
|
|
196
|
+
path has no equivalent of, so boot is strictly sequential); what the spare removes is the store create itself.
|
|
197
|
+
Board boot-rail stamps: `boot spare store ensured`, `boot mapped store prewarm`, `boot store claimed`.
|
|
195
198
|
|
|
196
199
|
**`ready` unchanged; per-group readiness exposed.** `client.ready` still gates on every eager group; for
|
|
197
200
|
progressive paint use `await client.groupReady(tableKey)` or read `status.groups`.
|
|
@@ -201,19 +204,20 @@ progressive paint use `await client.groupReady(tableKey)` or read `status.groups
|
|
|
201
204
|
clock and re-printed as `[pgxsinkit·w <ms>ms] …`, gated by that tab's own `globalThis.__pgxsinkitDebug`. The
|
|
202
205
|
front half of boot runs on the FIRST attach before any tab is listening, so the worker buffers those
|
|
203
206
|
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:
|
|
205
|
-
panel — "
|
|
206
|
-
Inspect the worker itself (`chrome://inspect/#workers`) for the real requests
|
|
207
|
-
rejections surface only there). Full
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
(
|
|
211
|
-
`in-process`)
|
|
212
|
-
`EngineRelocatedError("not-dispatched")` is safe to retry
|
|
213
|
-
already be journaled — inspect/reconcile, never retry
|
|
214
|
-
default (no finite worst-case query duration exists
|
|
215
|
-
|
|
216
|
-
|
|
207
|
+
The worker's NETWORK traffic is invisible the same way: the subscribe calls and the streams' long-polls never
|
|
208
|
+
appear in the page's Network panel — "the app is syncing but the Network tab shows nothing" is worker mode
|
|
209
|
+
working as designed. Inspect the worker itself (`chrome://inspect/#workers`) for the real requests and errors
|
|
210
|
+
(CORS rejections surface only there, a missing `Access-Control-Expose-Headers` on the edge included). Full
|
|
211
|
+
model: <https://pgxsinkit.github.io/concepts/worker-mode/>.
|
|
212
|
+
|
|
213
|
+
**Placement and relocation diagnostics.** Pull `client.bootReport()`: `storageBackend`, `engineHome`
|
|
214
|
+
(`shared-worker`/`elected-worker`/`in-process`), `storageFallbackReason`; never user-agent-sniff the backend. On
|
|
215
|
+
elected-engine handoff `EngineRelocatedError("not-dispatched")` is safe to retry; `"unknown"` means a dispatched
|
|
216
|
+
mutation may already be journaled — inspect/reconcile, never retry. The opt-in `executionLimit` is disabled by
|
|
217
|
+
default (no finite worst-case query duration exists; slow becomes terminated by policy), is elected-only, must
|
|
218
|
+
match across the worker entry and every tab (`ExecutionLimitMismatchError`); SW-direct rejects it. An attach
|
|
219
|
+
waits for an in-flight spare provision only within `provisionAdoptionBudgetMs` (default 20s from provision
|
|
220
|
+
start), then raises `ProvisionStalledError` — rebind to a fresh store; it bounds the accelerator, not liveness.
|
|
217
221
|
|
|
218
222
|
## Live-query manager: dedup + keep-alive (ADR-0040)
|
|
219
223
|
|
|
@@ -392,32 +396,28 @@ is the escape hatch. `dropReadCache()` never touches it (not read cache). `expor
|
|
|
392
396
|
quarantine restored Outbox rows** — the deliberate asymmetry with the mutation journal: they resume flushing
|
|
393
397
|
normally, because event delivery is idempotent end-to-end (`eventId` dedupe), which mutation replay is not.
|
|
394
398
|
|
|
395
|
-
##
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
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.
|
|
399
|
+
## The read path's cache split: uncacheable control plane, cacheable edge
|
|
400
|
+
|
|
401
|
+
The two read halves have opposite caching postures. The **control plane** (`/sync/v1/subscribe`, `/refresh`,
|
|
402
|
+
`/barrier`) answers per-subject questions and mints stream tokens, so force `cache-control: no-store` on it. The
|
|
403
|
+
**edge** (`createStreamGate` at `/v1/stream`) is the only surface a CDN may share, and durable-streams already
|
|
404
|
+
labels its responses for one — a catch-up read returns `cache-control: public, max-age=60,
|
|
405
|
+
stale-while-revalidate=300` and an `etag`, exactly where the bytes are. Sharing is a **shared-tier** property
|
|
406
|
+
only: a `rowFilter` fuses the subject into the predicate, so those bytes are shareable with nobody.
|
|
407
|
+
|
|
408
|
+
**Put the edge on its own origin, and keep the stream token out of the cache key.** The cache key is the URL, so
|
|
409
|
+
a same-origin mount makes the cacheable and uncacheable surfaces share one key and forecloses ever fronting the
|
|
410
|
+
shared tier; the token rides in `Authorization` (never a query parameter) for the same reason, and the cache
|
|
411
|
+
must not vary on that header. Revocation latency then follows the deployment: behind a hit-serving CDN it is
|
|
412
|
+
bounded by the token TTL (5 minutes by default), behind a cache sitting _behind_ the edge's verifier it is
|
|
413
|
+
entitlement-propagation latency.
|
|
414
|
+
|
|
415
|
+
**Every `createStreamGate` mount must set `Access-Control-Expose-Headers` from the exported
|
|
416
|
+
`STREAM_READ_EXPOSED_HEADERS`.** CORS lets script read only a short safelist, and every header durable-streams
|
|
417
|
+
answers with is outside it, so a cross-origin browser gets a response whose stream headers are simply not there:
|
|
418
|
+
`@durable-streams/client` steers its read loop off them, never learns an offset, and re-requests from the
|
|
419
|
+
start in a hot loop, with no error raised on either side. It presents as "sync does nothing, and the console
|
|
420
|
+
is clean". Mount details: the `deploying` skill.
|
|
421
421
|
|
|
422
422
|
## Debugging latency: `globalThis.__pgxsinkitDebug`
|
|
423
423
|
|
|
@@ -429,18 +429,17 @@ globalThis.__pgxsinkitDebug = true; // reproduce, then filter the console to "pg
|
|
|
429
429
|
```
|
|
430
430
|
|
|
431
431
|
Read the **gaps** between phases: `mutation staged {mutationId, table}` (correlate by id with the later
|
|
432
|
-
sent/acked lines); `convergence pass requested` → `flush` / `
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
`
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
the optional pre-warm.
|
|
432
|
+
sent/acked lines); `convergence pass requested (event-driven, …)` → `convergence flush` / `convergence
|
|
433
|
+
reconcile`; `flushBatch sending to board-write`; `board-write auth token resolved {ms}` (a stalling token
|
|
434
|
+
fetch); `board-write responded {status, ms}` (a cold worker or a connection stall); `board-write acks`; and
|
|
435
|
+
`live-query register|dedup-hit|retained|evicted|teardown-complete` (digests only). **The read path emits no rail
|
|
436
|
+
lines** — its cost is routing latency rather than phases, so read it off the `BootReport`'s per-group rows
|
|
437
|
+
(below) and off `status` / `status.lastError` (`degraded`/stream = subscribe failing or the stream silent;
|
|
438
|
+
`auth-needed` = the control plane refused this credential), and inspect the real requests in the worker's own
|
|
439
|
+
DevTools. Server-side, `createSyncServer({ logTimings: true })` emits matching `[pgxsinkit-timing]` lines (the
|
|
440
|
+
`deploying` skill); client-observed minus server `totalMs` isolates routing + network. Boot too: `boot
|
|
441
|
+
pglite.create` → `boot client ready` (store open, schema apply, journal recovery, store-version reconcile, sync
|
|
442
|
+
start) attributes a slow first paint to a phase; `boot pglite assets warm` times the optional pre-warm.
|
|
444
443
|
|
|
445
444
|
**Structured boot numbers — the `BootReport`.** The rail is for a human reading a console; for
|
|
446
445
|
machine-keepable numbers (dashboards, CI budget gates) every boot ALSO builds a versioned `BootReport`,
|
|
@@ -453,17 +452,17 @@ per-group `groups[]`. Two reading caveats: groups catch up CONCURRENTLY on one W
|
|
|
453
452
|
`totalMs` partition; and a non-null `provision` block is a spare's off-thread `initdb` made visible (then
|
|
454
453
|
`phases.pgliteCreateMs` is `null`).
|
|
455
454
|
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
to
|
|
466
|
-
<https://pgxsinkit.github.io/start/operating-in-production/>.
|
|
455
|
+
**How a group decides to commit (ADR-0056), and the one state that is terminal.** There is **no commit floor**
|
|
456
|
+
and no cross-shape position comparison — offsets are per-stream and comparable only within one — so a group
|
|
457
|
+
commits when **every** one of its shapes' most recent responses asserted up-to-date (a quiet shape re-asserts
|
|
458
|
+
freshness on every `204` long-poll timeout). Atomic at boot/catch-up alignment; LIVE deliveries commit per
|
|
459
|
+
response, so two halves of one transaction can land milliseconds apart (backlog 0014). The **first**
|
|
460
|
+
commit of each alignment generation (boot, and after any must-refetch) also reads the engine's convergence
|
|
461
|
+
barrier through the control plane's `/sync/v1/barrier`, aligning only with `pendingFlips` at zero — no computed
|
|
462
|
+
membership revocation still undelivered. A barrier the client cannot READ is a delay: the group stays on the
|
|
463
|
+
pre-alignment gate and retries. `flipFailures > 0` is **terminal**: the engine abandoned membership-flip
|
|
464
|
+
batches, those effects are lost, and the client refuses to align and goes `degraded` rather than waiting —
|
|
465
|
+
restart the engine and re-subscribe. Full prose: <https://pgxsinkit.github.io/start/operating-in-production/>.
|
|
467
466
|
|
|
468
467
|
**Measure at the network boundary, not by polling PGlite.** Each PGlite query is ~50ms on one thread, so
|
|
469
468
|
a tight `setInterval` reading PGlite to "watch" a value inflates the very latency it reports. Trust the
|
|
@@ -487,8 +486,9 @@ a real rollback, route a permanent policy denial to `quarantined` — never mis-
|
|
|
487
486
|
## Common mistakes
|
|
488
487
|
|
|
489
488
|
- Shortening the convergence interval to chase write latency (no effect; wastes CPU).
|
|
490
|
-
- Serving many-
|
|
491
|
-
-
|
|
489
|
+
- Serving many-stream sync over plain HTTP/1.1 and blaming the server for stalled writes.
|
|
490
|
+
- Mounting the stream edge on the control plane's origin (one cache key for both read surfaces), or
|
|
491
|
+
omitting `Access-Control-Expose-Headers` on it — that one hot-loops the client, silently on both sides.
|
|
492
492
|
- Treating an edge cold start as a toolkit/sync-rail problem.
|
|
493
493
|
- Measuring latency by polling PGlite in a loop instead of at the network boundary.
|
|
494
494
|
- Treating `deferred` as a failure and "cleaning up" the Outbox — it is rollout skew, and those rows drain
|
package/src/boot-report.ts
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
import { syncDebug } from "./debug";
|
|
12
12
|
|
|
13
13
|
/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */
|
|
14
|
-
|
|
14
|
+
/** The monotonic clock every boot offset and duration in this module is measured on. */
|
|
15
|
+
export const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:
|
|
@@ -95,7 +96,7 @@ export interface BootReport {
|
|
|
95
96
|
journalRecoveryMs: number;
|
|
96
97
|
storeVersionReconcileMs: number;
|
|
97
98
|
/**
|
|
98
|
-
* `
|
|
99
|
+
* `startCircuitsSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
|
|
99
100
|
* {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema, journal
|
|
100
101
|
* recovery, and registry reconciliation, so this includes that shared wall. Structurally 0 when the boot
|
|
101
102
|
* is ready inside the
|
|
@@ -179,7 +180,7 @@ export interface GroupBootStamp {
|
|
|
179
180
|
markReady: () => void;
|
|
180
181
|
}
|
|
181
182
|
|
|
182
|
-
/** The seam `
|
|
183
|
+
/** The seam `startCircuitsSync` uses to open a boot group's accumulator (implemented by the builder). */
|
|
183
184
|
export interface BootStampCollector {
|
|
184
185
|
beginGroup: (groupKey: string, tables: number) => GroupBootStamp;
|
|
185
186
|
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { StreamEnvelope, StreamValue, SyncOperation } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
import type { ApplyTarget } from "../local-tables";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Separator the engine joins composite primary-key values with (`schema.rs`, `PK_"\u001f"`).
|
|
7
|
+
*
|
|
8
|
+
* ASCII Unit Separator, chosen upstream so it cannot collide with real id text. Restated here rather
|
|
9
|
+
* than derived: getting it wrong does not fail loudly, it produces deletes that match no row.
|
|
10
|
+
*/
|
|
11
|
+
const PK_SEPARATOR = "\u001f";
|
|
12
|
+
|
|
13
|
+
/** The applier's message shape, once an envelope has been resolved against its table. */
|
|
14
|
+
export interface ChangeLike {
|
|
15
|
+
key: string;
|
|
16
|
+
value: Record<string, unknown>;
|
|
17
|
+
headers: { operation: SyncOperation };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Coerce one primary-key value out of its key-string rendering.
|
|
22
|
+
*
|
|
23
|
+
* The engine writes keys through `Value::to_key_string`, which erases type: `Int(42)` becomes
|
|
24
|
+
* `"42"`, `Bool(true)` becomes `"true"`. A delete carries **only** that key, so the pk has to be
|
|
25
|
+
* re-typed here or the `WHERE` binds text against a non-text column.
|
|
26
|
+
*
|
|
27
|
+
* `bigint` and `numeric` stay strings deliberately — routing them through `Number` would lose
|
|
28
|
+
* precision above 2^53, and a silently-wrong id is worse than a driver-level coercion.
|
|
29
|
+
*/
|
|
30
|
+
function coercePrimaryKeyValue(sqlType: string, raw: string): StreamValue {
|
|
31
|
+
switch (sqlType) {
|
|
32
|
+
case "integer":
|
|
33
|
+
case "smallint":
|
|
34
|
+
case "serial":
|
|
35
|
+
case "smallserial":
|
|
36
|
+
return Number(raw);
|
|
37
|
+
case "boolean":
|
|
38
|
+
return raw === "true";
|
|
39
|
+
default:
|
|
40
|
+
return raw;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Rebuild the primary-key columns of a row from the stream key.
|
|
46
|
+
*
|
|
47
|
+
* Composite keys are joined in **primary-key declaration order**, which is the order `ApplyTarget`
|
|
48
|
+
* already holds — so the two must agree. A count mismatch is thrown rather than tolerated: a
|
|
49
|
+
* silently short split would produce a `WHERE` over only part of the key, and a delete matching more
|
|
50
|
+
* rows than it should is data loss, not a stale row.
|
|
51
|
+
*/
|
|
52
|
+
export function primaryKeyFromStreamKey(target: ApplyTarget, key: string): Record<string, unknown> {
|
|
53
|
+
const parts = target.primaryKey.length === 1 ? [key] : key.split(PK_SEPARATOR);
|
|
54
|
+
if (parts.length !== target.primaryKey.length) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`[pgxsinkit] stream key "${key}" splits into ${parts.length} part(s) but the target has a ` +
|
|
57
|
+
`${target.primaryKey.length}-column primary key (${target.primaryKey.join(", ")})`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const row: Record<string, unknown> = {};
|
|
62
|
+
target.primaryKey.forEach((column, index) => {
|
|
63
|
+
const sqlType = target.columnTypes.find((type) => type.name === column)?.sqlType ?? "text";
|
|
64
|
+
row[column] = coercePrimaryKeyValue(sqlType, parts[index]!);
|
|
65
|
+
});
|
|
66
|
+
return row;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Translate a Circuits envelope into the message the applier consumes.
|
|
71
|
+
*
|
|
72
|
+
* There is no operation mapping to do — {@link SyncOperation} is the wire's own vocabulary. What
|
|
73
|
+
* this function carries is the one structural difference: **a delete has no row body**, only its
|
|
74
|
+
* key, so the pk columns are reconstructed here. That is a privacy improvement (an eviction
|
|
75
|
+
* discloses the key and nothing else) and an implementation hazard in the same change, which is why
|
|
76
|
+
* the reconstruction is a named, tested function rather than an inline split.
|
|
77
|
+
*
|
|
78
|
+
* An `upsert` carries the **complete projected row** every time — the engine's `row_to_json_cols`
|
|
79
|
+
* emits every column of the shape's `out_cols`, never a changed-column subset — which is what lets
|
|
80
|
+
* the apply path refresh every non-pk column from `excluded` without knowing whether the row already
|
|
81
|
+
* existed locally.
|
|
82
|
+
*/
|
|
83
|
+
export function envelopeToChange(target: ApplyTarget, envelope: StreamEnvelope): ChangeLike {
|
|
84
|
+
const operation = envelope.headers.operation;
|
|
85
|
+
|
|
86
|
+
if (operation === "delete") {
|
|
87
|
+
return {
|
|
88
|
+
key: envelope.key,
|
|
89
|
+
value: primaryKeyFromStreamKey(target, envelope.key),
|
|
90
|
+
headers: { operation: "delete" },
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (envelope.value === undefined) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`[pgxsinkit] ${operation} envelope for key "${envelope.key}" carries no row body — only a ` +
|
|
97
|
+
`delete may omit one`,
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
return { key: envelope.key, value: envelope.value, headers: { operation: "upsert" } };
|
|
102
|
+
}
|