@pgxsinkit/client 0.1.32 → 0.1.40
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 +11 -0
- package/dist/boot-report.d.ts +134 -0
- package/dist/boot-report.d.ts.map +1 -0
- package/dist/convergence.d.ts +76 -0
- package/dist/convergence.d.ts.map +1 -0
- package/dist/debug.d.ts +34 -0
- package/dist/debug.d.ts.map +1 -0
- package/dist/export-data.d.ts +100 -0
- package/dist/export-data.d.ts.map +1 -0
- package/dist/export-dump.d.ts +92 -0
- package/dist/export-dump.d.ts.map +1 -0
- package/dist/export-store.d.ts +214 -0
- package/dist/export-store.d.ts.map +1 -0
- package/dist/index.d.ts +615 -8
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8083 -2286
- package/dist/index.js.map +81 -44
- package/dist/lazy-guard.d.ts +59 -0
- package/dist/lazy-guard.d.ts.map +1 -0
- package/dist/lifecycle-slot.d.ts +31 -0
- package/dist/lifecycle-slot.d.ts.map +1 -0
- package/dist/live-rows-sql.d.ts +21 -0
- package/dist/live-rows-sql.d.ts.map +1 -0
- package/dist/local-store.d.ts +56 -0
- package/dist/local-store.d.ts.map +1 -0
- package/dist/local-tables.d.ts +707 -0
- package/dist/local-tables.d.ts.map +1 -0
- package/dist/mutation-state.d.ts +69 -0
- package/dist/mutation-state.d.ts.map +1 -0
- package/dist/mutation.d.ts +129 -4
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +82 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +190 -0
- package/dist/shape-sync.d.ts.map +1 -0
- package/dist/store-path.d.ts +132 -0
- package/dist/store-path.d.ts.map +1 -0
- package/dist/sync/apply.d.ts +51 -0
- package/dist/sync/apply.d.ts.map +1 -0
- package/dist/sync/copy.d.ts +43 -0
- package/dist/sync/copy.d.ts.map +1 -0
- package/dist/sync/drizzle-executor.d.ts +5 -0
- package/dist/sync/drizzle-executor.d.ts.map +1 -0
- package/dist/sync/index.d.ts +32 -0
- package/dist/sync/index.d.ts.map +1 -0
- package/dist/sync/metadata-tables.d.ts +131 -0
- package/dist/sync/metadata-tables.d.ts.map +1 -0
- package/dist/sync/nudge.d.ts +49 -0
- package/dist/sync/nudge.d.ts.map +1 -0
- package/dist/sync/shape-inbox.d.ts +215 -0
- package/dist/sync/shape-inbox.d.ts.map +1 -0
- package/dist/sync/subscription-state.d.ts +39 -0
- package/dist/sync/subscription-state.d.ts.map +1 -0
- package/dist/sync/tags.d.ts +130 -0
- package/dist/sync/tags.d.ts.map +1 -0
- package/dist/sync/types.d.ts +126 -0
- package/dist/sync/types.d.ts.map +1 -0
- package/dist/sync-auth.d.ts +53 -0
- package/dist/sync-auth.d.ts.map +1 -0
- package/dist/testing.d.ts +27 -0
- package/dist/testing.d.ts.map +1 -0
- package/dist/testing.js +17 -0
- package/dist/testing.js.map +11 -0
- package/dist/worker/attach-sync-client.d.ts +96 -0
- package/dist/worker/attach-sync-client.d.ts.map +1 -0
- package/dist/worker/define-sync-worker.d.ts +76 -0
- package/dist/worker/define-sync-worker.d.ts.map +1 -0
- package/dist/worker/live-diff.d.ts +44 -0
- package/dist/worker/live-diff.d.ts.map +1 -0
- package/dist/worker/protocol.d.ts +341 -0
- package/dist/worker/protocol.d.ts.map +1 -0
- package/dist/worker/token-cache.d.ts +26 -0
- package/dist/worker/token-cache.d.ts.map +1 -0
- package/oxlint-plugin.js +143 -0
- package/package.json +20 -7
- package/skills/core/SKILL.md +210 -0
- package/skills/operating/SKILL.md +303 -0
- package/src/boot-report.ts +287 -0
- package/src/convergence.ts +197 -0
- package/src/debug.ts +151 -0
- package/src/export-data.ts +300 -0
- package/src/export-dump.ts +239 -0
- package/src/export-store.ts +309 -0
- package/src/index.ts +1652 -51
- package/src/lazy-guard.ts +135 -0
- package/src/lifecycle-slot.ts +66 -0
- package/src/live-rows-sql.ts +45 -0
- package/src/local-store.ts +193 -0
- package/src/local-tables.ts +546 -0
- package/src/mutation-state.ts +99 -0
- package/src/mutation.ts +1910 -562
- package/src/schema.ts +472 -28
- package/src/shape-sync.ts +498 -0
- package/src/store-path.ts +249 -0
- package/src/sync/apply.ts +530 -0
- package/src/sync/copy.ts +206 -0
- package/src/sync/drizzle-executor.ts +48 -0
- package/src/sync/index.ts +1087 -0
- package/src/sync/metadata-tables.ts +67 -0
- package/src/sync/nudge.ts +110 -0
- package/src/sync/shape-inbox.ts +566 -0
- package/src/sync/subscription-state.ts +135 -0
- package/src/sync/tags.ts +365 -0
- package/src/sync/types.ts +141 -0
- package/src/sync-auth.ts +117 -0
- package/src/testing.ts +53 -0
- package/src/worker/attach-sync-client.ts +653 -0
- package/src/worker/define-sync-worker.ts +762 -0
- package/src/worker/live-diff.ts +140 -0
- package/src/worker/protocol.ts +425 -0
- package/src/worker/token-cache.ts +84 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// Boot observability (ADR-0034). Every client boot builds a structured, versioned {@link BootReport} as it
|
|
2
|
+
// runs and finalizes it exactly once at `onInitialSync` (the moment the `boot client ready` rail line fires
|
|
3
|
+
// and `ready` resolves). The report is a plain, allocation-light object — no class instance leaks out — so
|
|
4
|
+
// it structured-clones across the worker bridge unchanged.
|
|
5
|
+
//
|
|
6
|
+
// The numbers are captured INDEPENDENTLY of the debug rail: `timeAsync` only measures when
|
|
7
|
+
// `__pgxsinkitDebug` is on, but the report must exist on every boot, so the builder always measures. It
|
|
8
|
+
// still emits the SAME rail lines `timeAsync` would (`<event> start` / `<event> done {ms}`), gated by
|
|
9
|
+
// `syncDebug`'s own console/sink gate, so the log text tools and tests match is unchanged.
|
|
10
|
+
|
|
11
|
+
import { syncDebug } from "./debug";
|
|
12
|
+
|
|
13
|
+
/** Monotonic clock (ms) — `performance.now()` where available, else `Date.now()`. */
|
|
14
|
+
const nowMs = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A structured, versioned record of one client boot (ADR-0034). `reportVersion` is a contract number:
|
|
18
|
+
* additive fields keep it, a breaking reshape bumps it. All durations are milliseconds; all `*AtMs` are
|
|
19
|
+
* offsets from boot start (the `startedAt` epoch anchor is the only wall-clock value).
|
|
20
|
+
*/
|
|
21
|
+
export interface BootReport {
|
|
22
|
+
reportVersion: 1;
|
|
23
|
+
/** How the engine booted: the in-process client (bun/Node/fallback) or inside `defineSyncWorker`. */
|
|
24
|
+
mode: "in-process" | "worker";
|
|
25
|
+
/** Whether the caller proved the store a schemaless spare (the ADR-0032 S4 fresh-store hint). */
|
|
26
|
+
freshStore: boolean;
|
|
27
|
+
/** Whether the ADR-0032 S4 fetch/schema overlap was active for this boot. */
|
|
28
|
+
overlapPrefetch: boolean;
|
|
29
|
+
/** The registry fingerprint the store is provisioned under — the same value store-version reconcile stamps. */
|
|
30
|
+
registryFingerprint: string;
|
|
31
|
+
/** Epoch anchor (`Date.now()`) at boot start; every other duration/offset is monotonic relative to it. */
|
|
32
|
+
startedAt: number;
|
|
33
|
+
/** Boot start → `onInitialSync` (all eager groups caught up). */
|
|
34
|
+
totalMs: number;
|
|
35
|
+
/**
|
|
36
|
+
* Present only when the store was pre-provisioned (a spare's initdb ran off-thread before this boot
|
|
37
|
+
* adopted it); `null` otherwise. When present, `phases.pgliteCreateMs` is `null` — the create cost is
|
|
38
|
+
* reported here instead.
|
|
39
|
+
*/
|
|
40
|
+
provision: {
|
|
41
|
+
/** The spare's PGlite create (initdb) cost, paid at provision time. */
|
|
42
|
+
initdbMs: number;
|
|
43
|
+
/** How long the provisioned store sat ready before this boot adopted it. */
|
|
44
|
+
provisionedMsBeforeBoot: number;
|
|
45
|
+
} | null;
|
|
46
|
+
phases: {
|
|
47
|
+
/** PGlite create cost, or `null` when the store was adopted from a spare (see {@link BootReport.provision}). */
|
|
48
|
+
pgliteCreateMs: number | null;
|
|
49
|
+
schemaExecMs: number;
|
|
50
|
+
journalRecoveryMs: number;
|
|
51
|
+
storeVersionReconcileMs: number;
|
|
52
|
+
/**
|
|
53
|
+
* `startConfiguredSync`: stream/group construction wall. On an overlap boot (ADR-0032 S4,
|
|
54
|
+
* {@link BootReport.overlapPrefetch}) the early-started segment runs concurrently with schema/journal/
|
|
55
|
+
* reconcile, so this includes that shared wall. Structurally 0 when the boot is ready inside the
|
|
56
|
+
* sync-start call itself (zero eager groups / instant catch-up) — finalize runs before the phase closes.
|
|
57
|
+
*/
|
|
58
|
+
syncStartMs: number;
|
|
59
|
+
/** Sync-start done → last eager boot group ready. */
|
|
60
|
+
catchupMs: number;
|
|
61
|
+
/**
|
|
62
|
+
* Cumulative time in configured prepare hooks (`prepareLocalDbBeforeSchema` + `prepareLocalDb`), present
|
|
63
|
+
* only when at least one hook is configured. Not part of the required v1 shape (ADR-0034).
|
|
64
|
+
*/
|
|
65
|
+
prepareMs?: number;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Per consistency GROUP, for the eager + promoted boot groups only (a lazily-activated-later group never
|
|
69
|
+
* appears — nor mutates a finalized report). Groups run concurrently, so `fetchMs`/`applyMs` are per-group
|
|
70
|
+
* wall SEGMENTS, not a partition of `totalMs`.
|
|
71
|
+
*/
|
|
72
|
+
groups: Array<{
|
|
73
|
+
groupKey: string;
|
|
74
|
+
/** Number of member tables (shapes) in the group. */
|
|
75
|
+
tables: number;
|
|
76
|
+
/** Offset from boot start when the group's streams started. */
|
|
77
|
+
startedAtMs: number;
|
|
78
|
+
/** Offset from boot start when the group reached its initial sync. */
|
|
79
|
+
readyAtMs: number;
|
|
80
|
+
/** Number of batch deliveries the group's stream chain received during boot catch-up. */
|
|
81
|
+
requests: number;
|
|
82
|
+
/** Number of change rows ingested during boot catch-up. */
|
|
83
|
+
rows: number;
|
|
84
|
+
/**
|
|
85
|
+
* Settle→next-delivery wall within this group's chain. On the single-threaded WASM host this absorbs
|
|
86
|
+
* OTHER groups' apply transactions and main-thread work between deliveries — read it as "time this
|
|
87
|
+
* group spent not applying", an upper bound on its network wait, not pure network cost.
|
|
88
|
+
*/
|
|
89
|
+
fetchMs: number;
|
|
90
|
+
/**
|
|
91
|
+
* Wall around this group's batch commits into PGlite. Includes waiting behind another group's
|
|
92
|
+
* transaction on the shared connection (single writer), so concurrent groups' `applyMs` can overlap.
|
|
93
|
+
*/
|
|
94
|
+
applyMs: number;
|
|
95
|
+
}>;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The phase durations the builder captures by key; `catchupMs` is derived, not a captured phase. */
|
|
99
|
+
type PhaseKey = "schemaExec" | "journalRecovery" | "storeVersionReconcile" | "syncStart";
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The per-group accumulator the engine stamps as a boot group's stream chain delivers and applies (ADR-0034).
|
|
103
|
+
* One per consistency group (one `syncShapesToTables` call). Frozen at the group's ready edge so later live
|
|
104
|
+
* traffic never mutates a finalized report.
|
|
105
|
+
*/
|
|
106
|
+
export interface GroupBootStamp {
|
|
107
|
+
/** A batch was delivered to the group's subscribe callback (one response). `changeCount` = its change rows. */
|
|
108
|
+
onBatchDelivered: (changeCount: number) => void;
|
|
109
|
+
/** A commit transaction applied `ms` of work into PGlite for this group. */
|
|
110
|
+
onApply: (ms: number) => void;
|
|
111
|
+
/** The group reached its initial sync — stamp `readyAtMs` and freeze accumulation. */
|
|
112
|
+
markReady: () => void;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The seam `startConfiguredSync` uses to open a boot group's accumulator (implemented by the builder). */
|
|
116
|
+
export interface BootStampCollector {
|
|
117
|
+
beginGroup: (groupKey: string, tables: number) => GroupBootStamp;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface GroupAccumulator extends GroupBootStamp {
|
|
121
|
+
snapshot: () => BootReport["groups"][number];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function createGroupAccumulator(groupKey: string, tables: number, bootStartPerf: number): GroupAccumulator {
|
|
125
|
+
const startedAtMs = nowMs() - bootStartPerf;
|
|
126
|
+
let requests = 0;
|
|
127
|
+
let rows = 0;
|
|
128
|
+
let fetchMs = 0;
|
|
129
|
+
let applyMs = 0;
|
|
130
|
+
let readyAtMs: number | null = null;
|
|
131
|
+
// `markReady` fires from INSIDE the ready-causing commit (before that delivery's `onApply` runs), so we
|
|
132
|
+
// must record that commit's apply before freezing. So `markReady` only flags ready; the freeze snaps shut
|
|
133
|
+
// at the START of the NEXT delivery — the first that is genuinely post-boot live traffic.
|
|
134
|
+
let readyReached = false;
|
|
135
|
+
let frozen = false;
|
|
136
|
+
// Marks the last settle point; the gap to the next delivery is fetch (network) wait. Seeded at creation so
|
|
137
|
+
// the first delivery's gap is the initial catch-up wait.
|
|
138
|
+
let lastMark = nowMs();
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
onBatchDelivered: (changeCount) => {
|
|
142
|
+
// A delivery arriving after the group is ready is post-boot live traffic — freeze here so it (and its
|
|
143
|
+
// apply) is excluded, leaving the ready-causing batch fully recorded.
|
|
144
|
+
if (readyReached) frozen = true;
|
|
145
|
+
if (frozen) return;
|
|
146
|
+
const now = nowMs();
|
|
147
|
+
fetchMs += Math.max(0, now - lastMark);
|
|
148
|
+
lastMark = now;
|
|
149
|
+
requests += 1;
|
|
150
|
+
rows += changeCount;
|
|
151
|
+
},
|
|
152
|
+
onApply: (ms) => {
|
|
153
|
+
if (frozen) return;
|
|
154
|
+
applyMs += ms;
|
|
155
|
+
// Exclude the apply wall from the NEXT fetch gap (the apply happens inside the delivery callback).
|
|
156
|
+
lastMark = nowMs();
|
|
157
|
+
},
|
|
158
|
+
markReady: () => {
|
|
159
|
+
if (readyAtMs != null) return;
|
|
160
|
+
readyAtMs = nowMs() - bootStartPerf;
|
|
161
|
+
readyReached = true;
|
|
162
|
+
},
|
|
163
|
+
snapshot: () => ({
|
|
164
|
+
groupKey,
|
|
165
|
+
tables,
|
|
166
|
+
startedAtMs,
|
|
167
|
+
readyAtMs: readyAtMs ?? nowMs() - bootStartPerf,
|
|
168
|
+
requests,
|
|
169
|
+
rows,
|
|
170
|
+
fetchMs,
|
|
171
|
+
applyMs,
|
|
172
|
+
}),
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Builds a {@link BootReport} across a boot and finalizes it exactly once. Owned by `createSyncClient`. */
|
|
177
|
+
export interface BootReportBuilder extends BootStampCollector {
|
|
178
|
+
/** The monotonic anchor (`performance.now()` at boot start) every offset is relative to. */
|
|
179
|
+
readonly bootStartPerf: number;
|
|
180
|
+
/**
|
|
181
|
+
* Time `fn`, always measuring (unlike `timeAsync`, which only measures when the rail is on) and capturing
|
|
182
|
+
* the duration into the report, while emitting the SAME rail lines `timeAsync` would. `key` is `null` for
|
|
183
|
+
* a prepare hook (folded into the optional `prepareMs`).
|
|
184
|
+
*/
|
|
185
|
+
phase: <T>(
|
|
186
|
+
key: PhaseKey | "prepare",
|
|
187
|
+
event: string,
|
|
188
|
+
fn: () => Promise<T>,
|
|
189
|
+
data?: Record<string, unknown>,
|
|
190
|
+
) => Promise<T>;
|
|
191
|
+
setPgliteCreateMs: (ms: number | null) => void;
|
|
192
|
+
setProvision: (provision: BootReport["provision"]) => void;
|
|
193
|
+
/**
|
|
194
|
+
* Record `phases.syncStartMs` directly — for the ADR-0032 S4 overlap path, where sync construction is
|
|
195
|
+
* kicked off before schema exec (not wrapped in {@link BootReportBuilder.phase}) and has no rail line.
|
|
196
|
+
*/
|
|
197
|
+
setSyncStartMs: (ms: number) => void;
|
|
198
|
+
/** Capture the offset at which sync construction completed — the base for `catchupMs`. */
|
|
199
|
+
markSyncStartDone: () => void;
|
|
200
|
+
/** Build + store the report once (idempotent). Returns the report, or the already-built one on a re-call. */
|
|
201
|
+
finalize: () => BootReport;
|
|
202
|
+
/** The finalized report, or `null` before the first boot completes / after an early stop. */
|
|
203
|
+
report: () => BootReport | null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Inputs known at boot start — the flags and identity the report carries verbatim. */
|
|
207
|
+
export interface BootReportInit {
|
|
208
|
+
mode: BootReport["mode"];
|
|
209
|
+
freshStore: boolean;
|
|
210
|
+
overlapPrefetch: boolean;
|
|
211
|
+
registryFingerprint: string;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function createBootReportBuilder(init: BootReportInit): BootReportBuilder {
|
|
215
|
+
const startedAt = Date.now();
|
|
216
|
+
const bootStartPerf = nowMs();
|
|
217
|
+
const durations = new Map<PhaseKey, number>();
|
|
218
|
+
let prepareMs: number | null = null;
|
|
219
|
+
let pgliteCreateMs: number | null = null;
|
|
220
|
+
let provision: BootReport["provision"] = null;
|
|
221
|
+
let syncStartDoneOffset: number | null = null;
|
|
222
|
+
const groups: GroupAccumulator[] = [];
|
|
223
|
+
let built: BootReport | null = null;
|
|
224
|
+
|
|
225
|
+
const duration = (key: PhaseKey): number => durations.get(key) ?? 0;
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
bootStartPerf,
|
|
229
|
+
phase: async (key, event, fn, data) => {
|
|
230
|
+
const startedAtPerf = nowMs();
|
|
231
|
+
// Mirror `timeAsync`'s rail lines exactly (text tools/tests match); `syncDebug` self-gates the console.
|
|
232
|
+
syncDebug(`${event} start`, data);
|
|
233
|
+
try {
|
|
234
|
+
return await fn();
|
|
235
|
+
} finally {
|
|
236
|
+
const ms = nowMs() - startedAtPerf;
|
|
237
|
+
syncDebug(`${event} done`, { ms: Math.round(ms) });
|
|
238
|
+
if (key === "prepare") prepareMs = (prepareMs ?? 0) + ms;
|
|
239
|
+
else durations.set(key, ms);
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
setPgliteCreateMs: (ms) => {
|
|
243
|
+
pgliteCreateMs = ms;
|
|
244
|
+
},
|
|
245
|
+
setProvision: (value) => {
|
|
246
|
+
provision = value;
|
|
247
|
+
},
|
|
248
|
+
setSyncStartMs: (ms) => {
|
|
249
|
+
durations.set("syncStart", ms);
|
|
250
|
+
},
|
|
251
|
+
markSyncStartDone: () => {
|
|
252
|
+
syncStartDoneOffset = nowMs() - bootStartPerf;
|
|
253
|
+
},
|
|
254
|
+
beginGroup: (groupKey, tables) => {
|
|
255
|
+
const accumulator = createGroupAccumulator(groupKey, tables, bootStartPerf);
|
|
256
|
+
groups.push(accumulator);
|
|
257
|
+
return accumulator;
|
|
258
|
+
},
|
|
259
|
+
finalize: () => {
|
|
260
|
+
if (built) return built;
|
|
261
|
+
const totalMs = nowMs() - bootStartPerf;
|
|
262
|
+
const syncStartBase = syncStartDoneOffset ?? totalMs;
|
|
263
|
+
built = {
|
|
264
|
+
reportVersion: 1,
|
|
265
|
+
mode: init.mode,
|
|
266
|
+
freshStore: init.freshStore,
|
|
267
|
+
overlapPrefetch: init.overlapPrefetch,
|
|
268
|
+
registryFingerprint: init.registryFingerprint,
|
|
269
|
+
startedAt,
|
|
270
|
+
totalMs,
|
|
271
|
+
provision,
|
|
272
|
+
phases: {
|
|
273
|
+
pgliteCreateMs,
|
|
274
|
+
schemaExecMs: duration("schemaExec"),
|
|
275
|
+
journalRecoveryMs: duration("journalRecovery"),
|
|
276
|
+
storeVersionReconcileMs: duration("storeVersionReconcile"),
|
|
277
|
+
syncStartMs: duration("syncStart"),
|
|
278
|
+
catchupMs: Math.max(0, totalMs - syncStartBase),
|
|
279
|
+
...(prepareMs != null ? { prepareMs } : {}),
|
|
280
|
+
},
|
|
281
|
+
groups: groups.map((group) => group.snapshot()),
|
|
282
|
+
};
|
|
283
|
+
return built;
|
|
284
|
+
},
|
|
285
|
+
report: () => built,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
@@ -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
|
+
}
|
package/src/debug.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
// Opt-in runtime instrumentation for diagnosing convergence / sync latency in a live app (e.g. the
|
|
2
|
+
// board demo). It is OFF by default and adds nothing to a normal run: every call early-returns unless
|
|
3
|
+
// `globalThis.__pgxsinkitDebug` is truthy, so it is safe to leave the call sites in shipping code.
|
|
4
|
+
//
|
|
5
|
+
// Enable it from the browser console (`globalThis.__pgxsinkitDebug = true`) — or set it before the
|
|
6
|
+
// client boots; the board's dev build turns it on automatically. Each line is stamped with a monotonic
|
|
7
|
+
// millisecond clock so the gaps between phases (enqueue → flush → server ack → Electric echo →
|
|
8
|
+
// overlay clear → live-query render) can be read straight off the console.
|
|
9
|
+
|
|
10
|
+
interface DebugGlobal {
|
|
11
|
+
__pgxsinkitDebug?: boolean;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const isEnabled = (): boolean => (globalThis as DebugGlobal).__pgxsinkitDebug === true;
|
|
15
|
+
|
|
16
|
+
const now = (): number => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* A sink that receives every `syncDebug` line (event, the worker's monotonic stamp, optional data),
|
|
20
|
+
* INDEPENDENT of the local `__pgxsinkitDebug` console gate. This is the seam `defineSyncWorker` installs
|
|
21
|
+
* to forward the debug rail to tabs (ADR-0032 decision 7): a SharedWorker's own console is invisible
|
|
22
|
+
* (`chrome://inspect`), so lines must cross the bridge and each tab re-prints them gated on ITS OWN flag.
|
|
23
|
+
* Unset by default → no forwarding and zero cost on the in-process path.
|
|
24
|
+
*/
|
|
25
|
+
type SyncDebugSink = (event: string, stamp: number, data?: Record<string, unknown>) => void;
|
|
26
|
+
let syncDebugSink: SyncDebugSink | undefined;
|
|
27
|
+
|
|
28
|
+
/** Install (or clear, with `undefined`) the debug-rail sink. Idempotent; `defineSyncWorker` owns it. */
|
|
29
|
+
export function setSyncDebugSink(sink: SyncDebugSink | undefined): void {
|
|
30
|
+
syncDebugSink = sink;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Log one timestamped event. Prints to the console only when `globalThis.__pgxsinkitDebug` is on, but ALSO
|
|
35
|
+
* feeds any installed {@link setSyncDebugSink} sink (so the worker can forward the rail to tabs even when the
|
|
36
|
+
* worker's own console gate is off). No sink AND not enabled → an early return, so the off-path pays nothing.
|
|
37
|
+
*/
|
|
38
|
+
export function syncDebug(event: string, data?: Record<string, unknown>): void {
|
|
39
|
+
const enabled = isEnabled();
|
|
40
|
+
if (!enabled && syncDebugSink === undefined) return;
|
|
41
|
+
const stamp = now();
|
|
42
|
+
if (enabled) {
|
|
43
|
+
const prefix = `[pgxsinkit ${stamp.toFixed(0)}ms]`;
|
|
44
|
+
if (data) {
|
|
45
|
+
console.debug(`${prefix} ${event}`, data);
|
|
46
|
+
} else {
|
|
47
|
+
console.debug(`${prefix} ${event}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
syncDebugSink?.(event, stamp, data);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The request URL of a `fetch` first argument, in any of its accepted forms; undefined if unreadable. */
|
|
54
|
+
function fetchInputUrl(input: Parameters<typeof fetch>[0]): string | undefined {
|
|
55
|
+
if (typeof input === "string") return input;
|
|
56
|
+
if (input instanceof URL) return input.toString();
|
|
57
|
+
if (typeof input === "object" && input !== null && "url" in input) {
|
|
58
|
+
return (input as { url: string }).url;
|
|
59
|
+
}
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Wrap a `fetch` so every ShapeStream request (the Electric read-path long-poll/catch-up) emits a start
|
|
65
|
+
* line (shape/table, offset, live — derived from the request URL params) and a completion line (status,
|
|
66
|
+
* ms, and whether the response is up-to-date). Passthrough when instrumentation is off: the early return
|
|
67
|
+
* runs before any URL parsing, so the off-path pays nothing per request beyond this closure itself.
|
|
68
|
+
*
|
|
69
|
+
* Inject it as a ShapeStream `fetchClient`; pass the stream's existing `fetchClient` (if any) as the base
|
|
70
|
+
* so the instrumentation composes rather than replaces.
|
|
71
|
+
*/
|
|
72
|
+
export function instrumentShapeFetch(baseFetch: typeof fetch = fetch): typeof fetch {
|
|
73
|
+
const wrapped = (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]): Promise<Response> => {
|
|
74
|
+
if (!isEnabled()) return baseFetch(input, init);
|
|
75
|
+
const url = fetchInputUrl(input);
|
|
76
|
+
const params = url ? new URL(url).searchParams : undefined;
|
|
77
|
+
// Derive the shape identity ONCE and name it on BOTH the start and done lines, so a start/done pair
|
|
78
|
+
// is readable without cross-referencing timing (multiple shapes' requests interleave on the rail).
|
|
79
|
+
const shape = params?.get("table") ?? undefined;
|
|
80
|
+
const live = params?.get("live") === "true";
|
|
81
|
+
const offset = params?.get("offset") ?? undefined;
|
|
82
|
+
// The handle chain is the backlog-0001 forensic: WHICH handle each request carried, which one the
|
|
83
|
+
// response minted, and whether the stale-cache ladder's params were on the wire — so a
|
|
84
|
+
// dead-handle-served-N-times storm reads straight off the rail (same responseHandle across busted
|
|
85
|
+
// attempts) instead of needing a network-tab capture at the moment of recurrence.
|
|
86
|
+
const requestHandle = params?.get("handle") ?? undefined;
|
|
87
|
+
const cacheBuster = params?.has("cache-buster") ?? false;
|
|
88
|
+
const expiredHandle = params?.get("expired_handle") ?? undefined;
|
|
89
|
+
// The whole request identity rides in ONE compact string field: Chrome's console preview truncates
|
|
90
|
+
// object previews at ~5 properties, and a captured log (the only artifact of a live recurrence) keeps
|
|
91
|
+
// just the preview — separate fields silently vanish exactly when they matter (backlog 0001).
|
|
92
|
+
const cursor = params?.get("cursor") ?? undefined;
|
|
93
|
+
const req = [
|
|
94
|
+
`${shape ?? "?"}@${offset ?? "?"}`,
|
|
95
|
+
live ? "live" : "catchup",
|
|
96
|
+
requestHandle ? `h=${requestHandle}` : "no-handle",
|
|
97
|
+
// The live-cycle cursor is Electric's CDN-collapse defense — its absence or non-advancement on
|
|
98
|
+
// live polls is itself a finding (backlog 0001).
|
|
99
|
+
cursor ? `c=${cursor}` : live ? "NO-CURSOR" : "",
|
|
100
|
+
cacheBuster ? "BUSTED" : "",
|
|
101
|
+
expiredHandle ? `expired=${expiredHandle}` : "",
|
|
102
|
+
]
|
|
103
|
+
.filter(Boolean)
|
|
104
|
+
.join(" ");
|
|
105
|
+
syncDebug("shape request start", { req });
|
|
106
|
+
const startedAt = now();
|
|
107
|
+
return baseFetch(input, init).then((response) => {
|
|
108
|
+
// Same single-string discipline for the response half: status/ms stay first-class (they are what
|
|
109
|
+
// rail readers scan), the forensic chain (up-to-date, minted handle, end offset) folds into `resp`.
|
|
110
|
+
const responseHandle = response.headers.get("electric-handle");
|
|
111
|
+
const responseOffset = response.headers.get("electric-offset");
|
|
112
|
+
const responseCursor = response.headers.get("electric-cursor");
|
|
113
|
+
const age = response.headers.get("age");
|
|
114
|
+
const resp = [
|
|
115
|
+
response.headers.has("electric-up-to-date") ? "up-to-date" : "",
|
|
116
|
+
responseHandle && responseHandle !== requestHandle ? `minted h=${responseHandle}` : "",
|
|
117
|
+
responseOffset ? `end=${responseOffset}` : "",
|
|
118
|
+
responseCursor ? `c=${responseCursor}` : "",
|
|
119
|
+
age ? `age=${age}` : "",
|
|
120
|
+
]
|
|
121
|
+
.filter(Boolean)
|
|
122
|
+
.join(" ");
|
|
123
|
+
syncDebug("shape request done", {
|
|
124
|
+
req,
|
|
125
|
+
status: response.status,
|
|
126
|
+
ms: Math.round(now() - startedAt),
|
|
127
|
+
...(resp ? { resp } : {}),
|
|
128
|
+
});
|
|
129
|
+
return response;
|
|
130
|
+
});
|
|
131
|
+
};
|
|
132
|
+
// `typeof fetch` (Bun's global) carries a `preconnect` member the wrapper neither has nor needs — the
|
|
133
|
+
// ShapeStream only ever invokes fetchClient as a plain fetch — so the shape-compatible cast is safe.
|
|
134
|
+
return wrapped as typeof fetch;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Run `fn`, logging `<event> done` with its wall-clock duration (and any extra `data`). When
|
|
139
|
+
* instrumentation is off this is a thin pass-through with no logging and no timing overhead beyond the
|
|
140
|
+
* call itself. Returns whatever `fn` returns.
|
|
141
|
+
*/
|
|
142
|
+
export async function timeAsync<T>(event: string, fn: () => Promise<T>, data?: Record<string, unknown>): Promise<T> {
|
|
143
|
+
if (!isEnabled()) return fn();
|
|
144
|
+
const startedAt = now();
|
|
145
|
+
syncDebug(`${event} start`, data);
|
|
146
|
+
try {
|
|
147
|
+
return await fn();
|
|
148
|
+
} finally {
|
|
149
|
+
syncDebug(`${event} done`, { ms: Math.round(now() - startedAt) });
|
|
150
|
+
}
|
|
151
|
+
}
|