@pgxsinkit/client 0.1.36 → 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/dist/boot-report.d.ts +134 -0
- package/dist/boot-report.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 +206 -13
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +886 -69
- package/dist/index.js.map +21 -14
- package/dist/lazy-guard.d.ts +4 -3
- package/dist/lazy-guard.d.ts.map +1 -1
- 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/mutation-state.d.ts +9 -2
- package/dist/mutation-state.d.ts.map +1 -1
- package/dist/mutation.d.ts +12 -0
- package/dist/mutation.d.ts.map +1 -1
- package/dist/schema.d.ts +33 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/shape-sync.d.ts +10 -0
- package/dist/shape-sync.d.ts.map +1 -1
- package/dist/store-path.d.ts +132 -0
- package/dist/store-path.d.ts.map +1 -0
- package/dist/sync/index.d.ts +1 -1
- package/dist/sync/index.d.ts.map +1 -1
- package/dist/sync/types.d.ts +8 -0
- package/dist/sync/types.d.ts.map +1 -1
- 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 +23 -2
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +5 -4
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +89 -8
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +9 -4
- package/skills/core/SKILL.md +14 -1
- package/skills/operating/SKILL.md +75 -15
- package/src/boot-report.ts +287 -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 +623 -82
- package/src/lazy-guard.ts +23 -9
- package/src/lifecycle-slot.ts +66 -0
- package/src/live-rows-sql.ts +45 -0
- package/src/mutation-state.ts +11 -2
- package/src/mutation.ts +42 -0
- package/src/schema.ts +120 -1
- package/src/shape-sync.ts +21 -0
- package/src/store-path.ts +249 -0
- package/src/sync/index.ts +11 -0
- package/src/sync/types.ts +9 -0
- package/src/testing.ts +53 -0
- package/src/worker/attach-sync-client.ts +101 -6
- package/src/worker/define-sync-worker.ts +196 -30
- package/src/worker/protocol.ts +110 -10
|
@@ -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,300 @@
|
|
|
1
|
+
// Data export (ADR-0035 decision 1, via the throwaway clone of the addendum). The PORTABLE artefact: the
|
|
2
|
+
// synced tables and the enum types they depend on, schema + data, nothing of pgxsinkit's machinery —
|
|
3
|
+
// loadable into a vanilla Postgres. It is `generated enum DDL header + pg_dump -t (per synced table)`
|
|
4
|
+
// concatenated: `pg_dump -t` emits the allowlisted TABLES but not the enum TYPES their columns reference
|
|
5
|
+
// (and `--exclude-*` cannot subtract the reconcile functions), so the header carries the enums and `-t`
|
|
6
|
+
// carries exactly the physical synced tables — overlay/journal/metadata/views/functions fall outside `-t`
|
|
7
|
+
// by construction. `--no-owner` keeps the SQL portable across roles.
|
|
8
|
+
//
|
|
9
|
+
// Unlike the store backup and the diagnostic dump, the data export is the ONE variant that silently loses
|
|
10
|
+
// unflushed writes (decision 3): an `acked` write whose synced echo has not landed lives only in the Overlay
|
|
11
|
+
// and the `destroy()`-style "owed" predicate does not count it. So `exportData` requires a DRAINED journal —
|
|
12
|
+
// "drained" meaning all six mutation counts zero (CONTEXT.md → Data export: "drained ≠ nothing owed"), which
|
|
13
|
+
// for `acked` rows clears only via the synced echo through the Convergence barrier. The drain actively
|
|
14
|
+
// `flush()`es drainable rows and awaits that convergence, bounded by `drainJournal.timeoutMs`; non-drainable
|
|
15
|
+
// states (`failed`/`quarantined`/`conflicted`) never drain on their own, so they fail FAST with the
|
|
16
|
+
// diagnostics snapshot rather than burning the timeout. `drainJournal: false` is the explicit escape hatch
|
|
17
|
+
// exporting synced state as-is.
|
|
18
|
+
//
|
|
19
|
+
// The drain runs INSIDE the lifecycle slot (the caller enters the slot, then calls this): `flush()` needs
|
|
20
|
+
// the running engine and is not a lifecycle-exclusive op, but the artefact must be taken RIGHT AFTER the
|
|
21
|
+
// drain with no window for a new write to slip in — so export owns the store's lifecycle for the whole
|
|
22
|
+
// drain+dump, the simplest correct placement.
|
|
23
|
+
|
|
24
|
+
import type { MutationDiagnostics } from "@pgxsinkit/contracts";
|
|
25
|
+
|
|
26
|
+
import { runThrowawayCloneDump } from "./export-dump";
|
|
27
|
+
import { compactTimestamp, type DataExportReport, deriveStoreId, nowMs } from "./export-store";
|
|
28
|
+
import type { ClientPGlite } from "./index";
|
|
29
|
+
|
|
30
|
+
/** The default drain budget: actively flush + await the convergence barrier for up to 15s before failing. */
|
|
31
|
+
export const DEFAULT_DRAIN_TIMEOUT_MS = 15_000;
|
|
32
|
+
/** How often the drain re-checks the diagnostics seam while waiting for the journal to converge. */
|
|
33
|
+
const DRAIN_POLL_INTERVAL_MS = 50;
|
|
34
|
+
|
|
35
|
+
/** The drain guard's tuning: the wait budget for reaching a fully-drained journal. */
|
|
36
|
+
export interface DrainJournalOptions {
|
|
37
|
+
/** Milliseconds to flush + await convergence before throwing {@link DataExportDrainError}. */
|
|
38
|
+
timeoutMs: number;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `exportData`'s drain policy: the default `{ timeoutMs }` guard, or `false` — the explicit escape hatch
|
|
43
|
+
* that skips the drain and exports the SYNCED state as-is (unflushed local writes silently absent). A plain
|
|
44
|
+
* JSON shape, so it survives structured clone across the worker bridge unchanged.
|
|
45
|
+
*/
|
|
46
|
+
export type DrainJournalOption = DrainJournalOptions | false;
|
|
47
|
+
|
|
48
|
+
/** Options for {@link SyncClient.exportData}. Plain JSON — structured-clone-safe across the worker bridge. */
|
|
49
|
+
export interface DataExportOptions {
|
|
50
|
+
/**
|
|
51
|
+
* Override the generated artefact file name. When omitted, the name is `<storeId>-<timestamp>-data.sql`,
|
|
52
|
+
* where `storeId` is a filesystem-safe derivation of the store path (see `deriveStoreId`).
|
|
53
|
+
*/
|
|
54
|
+
fileName?: string;
|
|
55
|
+
/**
|
|
56
|
+
* The drain guard (ADR-0035 decision 3). Default `{ timeoutMs: 15_000 }`: fail fast on non-drainable
|
|
57
|
+
* states, else flush + await convergence up to the budget. `false` is the escape hatch — export synced
|
|
58
|
+
* state as-is, skipping the drain entirely.
|
|
59
|
+
*/
|
|
60
|
+
drainJournal?: DrainJournalOption;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The SQL artefact + its report — the resolved value of {@link SyncClient.exportData}. */
|
|
64
|
+
export interface DataExportResult {
|
|
65
|
+
/** The portable SQL as a named `File` (`application/sql`), loadable into a vanilla Postgres. */
|
|
66
|
+
file: File;
|
|
67
|
+
/** The structured record of the export (ADR-0035). */
|
|
68
|
+
report: DataExportReport;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Thrown when `exportData`'s strict drain cannot produce a drained journal (ADR-0035 decision 3). Carries
|
|
73
|
+
* the `MutationDiagnostics` snapshot at the moment of failure so the caller sees exactly what blocked the
|
|
74
|
+
* export, and a `reason` distinguishing the two failure modes:
|
|
75
|
+
*
|
|
76
|
+
* - `"non-drainable-state"` — `failed`/`quarantined`/`conflicted` rows are present (either pre-existing, so
|
|
77
|
+
* the failure is immediate with no waiting, or a mid-drain `flush()` failure that moved rows to `failed`);
|
|
78
|
+
* these terminal states never drain on their own, so waiting is pointless.
|
|
79
|
+
* - `"timeout"` — drainable rows (`pending`/`sending`/`acked`) did not reach fully-drained within the
|
|
80
|
+
* budget; most commonly `acked` writes whose synced echo never arrived (an offline device, a stalled
|
|
81
|
+
* read path).
|
|
82
|
+
*
|
|
83
|
+
* A distinct type — not a bare `Error` — so a caller can `instanceof`-branch a drain failure from a genuine
|
|
84
|
+
* export failure, inspect the diagnostics, and choose the escape hatch (`drainJournal: false`) or the
|
|
85
|
+
* lossless store backup instead.
|
|
86
|
+
*/
|
|
87
|
+
export class DataExportDrainError extends Error {
|
|
88
|
+
/** Which drain failure occurred (see the class doc). */
|
|
89
|
+
readonly reason: "non-drainable-state" | "timeout";
|
|
90
|
+
/** The mutation diagnostics at the moment the drain gave up — the evidence of what was unflushed. */
|
|
91
|
+
readonly diagnostics: MutationDiagnostics;
|
|
92
|
+
|
|
93
|
+
constructor(reason: "non-drainable-state" | "timeout", diagnostics: MutationDiagnostics) {
|
|
94
|
+
const detail =
|
|
95
|
+
reason === "non-drainable-state"
|
|
96
|
+
? `non-drainable journal rows are present (failed=${diagnostics.failedCount}, ` +
|
|
97
|
+
`quarantined=${diagnostics.quarantinedCount}, conflicted=${diagnostics.conflictedCount}) — these never ` +
|
|
98
|
+
"drain on their own"
|
|
99
|
+
: `the journal did not drain within the timeout (pending=${diagnostics.pendingCount}, ` +
|
|
100
|
+
`sending=${diagnostics.sendingCount}, acked=${diagnostics.ackedCount}) — most likely acked writes whose ` +
|
|
101
|
+
"synced echo has not landed";
|
|
102
|
+
super(
|
|
103
|
+
`[pgxsinkit] exportData refused: ${detail}. A strict data export needs a DRAINED journal (ADR-0035); ` +
|
|
104
|
+
"resolve the rows, retry once they converge, use `drainJournal: false` to export synced state as-is, or " +
|
|
105
|
+
"take a lossless `exportStore` backup instead.",
|
|
106
|
+
);
|
|
107
|
+
this.name = "DataExportDrainError";
|
|
108
|
+
this.reason = reason;
|
|
109
|
+
this.diagnostics = diagnostics;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The dependencies {@link performDataExport} needs from the owning client — narrow, so it is unit-testable. */
|
|
114
|
+
export interface DataExportDeps {
|
|
115
|
+
/** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
|
|
116
|
+
pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">;
|
|
117
|
+
/** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
|
|
118
|
+
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
119
|
+
/** The optimistic flush (`client.flush()`), driven during the drain to send drainable rows. */
|
|
120
|
+
flush: () => Promise<void>;
|
|
121
|
+
/**
|
|
122
|
+
* The `-t` allowlist: the schema-qualified physical synced table names, resolved from the registry by the
|
|
123
|
+
* SAME projection the DDL generator uses (`collectDataExportSyncedTableNames`) — never re-derived here.
|
|
124
|
+
*/
|
|
125
|
+
syncedTableNames: string[];
|
|
126
|
+
/**
|
|
127
|
+
* The generated enum DDL header (`buildDataExportEnumHeaderSql`) — the `CREATE TYPE` statements for the
|
|
128
|
+
* enums the exported tables reference, which `pg_dump -t` omits. `""` when no exported table uses an enum.
|
|
129
|
+
*/
|
|
130
|
+
enumHeaderSql: string;
|
|
131
|
+
/**
|
|
132
|
+
* The clone-cleanup SQL (`buildDataExportCloneCleanupSql`) run on the throwaway clone before `pg_dump -t`,
|
|
133
|
+
* dropping the reconcile triggers `-t` would otherwise pull into the artefact (referencing pgxsinkit
|
|
134
|
+
* functions the export excludes). `""` when the registry has no writable owning table.
|
|
135
|
+
*/
|
|
136
|
+
cloneCleanupSql: string;
|
|
137
|
+
/**
|
|
138
|
+
* The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact
|
|
139
|
+
* file name. The resolved PGlite dataDir URL is deliberately NOT used: internal plumbing, never an
|
|
140
|
+
* artefact-name seed.
|
|
141
|
+
*/
|
|
142
|
+
storePath?: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A non-drainable state is present when any terminal count is non-zero — waiting on these is pointless. */
|
|
146
|
+
const hasNonDrainableRows = (diagnostics: MutationDiagnostics): boolean =>
|
|
147
|
+
diagnostics.failedCount > 0 || diagnostics.quarantinedCount > 0 || diagnostics.conflictedCount > 0;
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Fully drained = all SIX counts zero. `acked` explicitly counts: an acked write whose echo has not landed
|
|
151
|
+
* is still only in the Overlay (CONTEXT.md → Data export), so a strict export must wait for it to clear via
|
|
152
|
+
* the Convergence barrier — that is the POINT of the drain, not merely "nothing owed".
|
|
153
|
+
*/
|
|
154
|
+
const isFullyDrained = (diagnostics: MutationDiagnostics): boolean =>
|
|
155
|
+
diagnostics.pendingCount === 0 &&
|
|
156
|
+
diagnostics.sendingCount === 0 &&
|
|
157
|
+
diagnostics.ackedCount === 0 &&
|
|
158
|
+
!hasNonDrainableRows(diagnostics);
|
|
159
|
+
|
|
160
|
+
const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Drive the journal to fully-drained (ADR-0035 decision 3), or throw {@link DataExportDrainError}:
|
|
164
|
+
*
|
|
165
|
+
* 1. Read diagnostics and fail FAST — before any waiting — when a non-drainable state pre-exists (an offline
|
|
166
|
+
* device with a dirty journal cannot produce a strict export).
|
|
167
|
+
* 2. An already-empty journal returns instantly with ZERO network involvement — an offline device with a
|
|
168
|
+
* clean journal exports strictly (the assert-in-a-test case).
|
|
169
|
+
* 3. Otherwise drainable rows are present: `flush()` them and poll the diagnostics seam until fully-drained,
|
|
170
|
+
* bounded by `timeoutMs`. A `flush()` that FAILS moves rows to `failed`, so the next poll sees a
|
|
171
|
+
* non-drainable state and fails fast (well under the budget) rather than burning the whole timeout. Its
|
|
172
|
+
* throw is swallowed — the diagnostics re-read, not the throw, is the source of truth for what happened.
|
|
173
|
+
*/
|
|
174
|
+
async function drainJournalForExport(
|
|
175
|
+
deps: DataExportDeps,
|
|
176
|
+
timeoutMs: number,
|
|
177
|
+
): Promise<{ diagnostics: MutationDiagnostics; drainMs: number }> {
|
|
178
|
+
const drainStartPerf = nowMs();
|
|
179
|
+
|
|
180
|
+
// (1)/(2) — fail fast on pre-existing terminal rows; return instantly on an empty journal.
|
|
181
|
+
let diagnostics = await deps.readMutationStats();
|
|
182
|
+
if (hasNonDrainableRows(diagnostics)) {
|
|
183
|
+
throw new DataExportDrainError("non-drainable-state", diagnostics);
|
|
184
|
+
}
|
|
185
|
+
if (isFullyDrained(diagnostics)) {
|
|
186
|
+
return { diagnostics, drainMs: nowMs() - drainStartPerf };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// (3) — drainable rows present: flush + await convergence, bounded by the budget.
|
|
190
|
+
for (;;) {
|
|
191
|
+
// A throwing flush (e.g. a dead write endpoint) still marks rows `failed`; the re-read below detects it.
|
|
192
|
+
await deps.flush().catch(() => undefined);
|
|
193
|
+
|
|
194
|
+
diagnostics = await deps.readMutationStats();
|
|
195
|
+
// A flush that failed mid-wait shows up here as `failed` rows — fail fast, do not burn the timeout.
|
|
196
|
+
if (hasNonDrainableRows(diagnostics)) {
|
|
197
|
+
throw new DataExportDrainError("non-drainable-state", diagnostics);
|
|
198
|
+
}
|
|
199
|
+
if (isFullyDrained(diagnostics)) {
|
|
200
|
+
return { diagnostics, drainMs: nowMs() - drainStartPerf };
|
|
201
|
+
}
|
|
202
|
+
if (nowMs() - drainStartPerf >= timeoutMs) {
|
|
203
|
+
throw new DataExportDrainError("timeout", diagnostics);
|
|
204
|
+
}
|
|
205
|
+
await sleep(DRAIN_POLL_INTERVAL_MS);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* A short SQL comment header describing the artefact and how it was produced — self-describing provenance so
|
|
211
|
+
* a human reading the `.sql` knows what it is, which tables it carries, and whether the escape hatch dropped
|
|
212
|
+
* unflushed writes. Emitted ahead of the enum header and the `pg_dump -t` output.
|
|
213
|
+
*/
|
|
214
|
+
function buildArtefactCommentHeader(tableNames: string[], escapeHatch: boolean): string {
|
|
215
|
+
const tableList = tableNames.length > 0 ? tableNames.join(", ") : "(none)";
|
|
216
|
+
return [
|
|
217
|
+
"-- pgxsinkit data export (ADR-0035): the synced tables + their enum types, schema + data,",
|
|
218
|
+
"-- nothing of pgxsinkit's overlay/journal/metadata machinery — loadable into a vanilla Postgres.",
|
|
219
|
+
"-- Produced by a generated enum DDL header concatenated ahead of `pg_dump -t <table> ... --no-owner`",
|
|
220
|
+
"-- run against a throwaway in-memory clone of the local store.",
|
|
221
|
+
`-- Tables: ${tableList}`,
|
|
222
|
+
escapeHatch
|
|
223
|
+
? "-- Journal drain: SKIPPED (drainJournal: false) — reflects synced state as-is; unflushed local writes are absent."
|
|
224
|
+
: "-- Journal drain: enforced — the Mutation journal was fully drained before the dump.",
|
|
225
|
+
"",
|
|
226
|
+
].join("\n");
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Run a data export (ADR-0035): drain the journal (unless the escape hatch is set) → throwaway-clone
|
|
231
|
+
* `pg_dump -t` per synced table → concatenate the comment + enum DDL header → assemble the report. The
|
|
232
|
+
* caller (`createSyncClient`) awaits engine-ready and enters the lifecycle slot BEFORE calling this, so the
|
|
233
|
+
* whole drain+dump runs under the store's single lifecycle slot (the drain must sit inside it — see the
|
|
234
|
+
* module header).
|
|
235
|
+
*/
|
|
236
|
+
export async function performDataExport(
|
|
237
|
+
deps: DataExportDeps,
|
|
238
|
+
options: DataExportOptions = {},
|
|
239
|
+
): Promise<DataExportResult> {
|
|
240
|
+
const startedAt = Date.now();
|
|
241
|
+
const startPerf = nowMs();
|
|
242
|
+
|
|
243
|
+
const drainOption: DrainJournalOption = options.drainJournal ?? { timeoutMs: DEFAULT_DRAIN_TIMEOUT_MS };
|
|
244
|
+
const escapeHatch = drainOption === false;
|
|
245
|
+
|
|
246
|
+
// Phase 1 — the drain guard. The escape hatch skips it entirely (0-wall); otherwise it may throw a typed
|
|
247
|
+
// DataExportDrainError before any dump work happens.
|
|
248
|
+
const drainStartedAtMs = nowMs() - startPerf;
|
|
249
|
+
const drainMs = escapeHatch ? 0 : (await drainJournalForExport(deps, drainOption.timeoutMs)).drainMs;
|
|
250
|
+
|
|
251
|
+
// Phase 2 — the throwaway-clone dump, restricted to the physical synced tables via `-t`, `--no-owner` for
|
|
252
|
+
// portability. `-t` is repeated once per table. `runThrowawayCloneDump` phases are offset from the SAME
|
|
253
|
+
// export-start anchor, so they compose after the drain wall into one timeline.
|
|
254
|
+
const pgDumpArgs = ["--no-owner", ...deps.syncedTableNames.flatMap((name) => ["-t", name])];
|
|
255
|
+
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf, {
|
|
256
|
+
pgDumpArgs,
|
|
257
|
+
// Drop the reconcile triggers on the clone so `-t` yields portable, machinery-free tables.
|
|
258
|
+
...(deps.cloneCleanupSql.length > 0
|
|
259
|
+
? { prepareClone: async (clone) => void (await clone.exec(deps.cloneCleanupSql)) }
|
|
260
|
+
: {}),
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
// Concatenate: comment header + generated enum DDL header + pg_dump output. The header is text; the dump
|
|
264
|
+
// is raw bytes — `File` accepts a mixed BlobPart list and encodes both as UTF-8, so the bytes are decoded
|
|
265
|
+
// exactly once (never a decode/re-encode round trip).
|
|
266
|
+
const header = buildArtefactCommentHeader(deps.syncedTableNames, escapeHatch) + deps.enumHeaderSql;
|
|
267
|
+
const storeId = deriveStoreId(deps.storePath);
|
|
268
|
+
const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-data.sql`;
|
|
269
|
+
const file = new File([header, sqlBytes], fileName, { type: "application/sql" });
|
|
270
|
+
|
|
271
|
+
// Snapshot diagnostics AT dump time (post-drain): on the strict path this is a drained journal; under the
|
|
272
|
+
// escape hatch it is whatever synced-as-is state the artefact reflects.
|
|
273
|
+
const diagnostics = await deps.readMutationStats();
|
|
274
|
+
|
|
275
|
+
const report: DataExportReport = {
|
|
276
|
+
reportVersion: 1,
|
|
277
|
+
kind: "data-export",
|
|
278
|
+
scope: "synced-tables",
|
|
279
|
+
tables: deps.syncedTableNames,
|
|
280
|
+
escapeHatch,
|
|
281
|
+
startedAt,
|
|
282
|
+
totalMs: nowMs() - startPerf,
|
|
283
|
+
byteLength: file.size,
|
|
284
|
+
phases: {
|
|
285
|
+
drainStartedAtMs,
|
|
286
|
+
drainMs,
|
|
287
|
+
checkpointStartedAtMs: phases.checkpointStartedAtMs,
|
|
288
|
+
checkpointMs: phases.checkpointMs,
|
|
289
|
+
dumpStartedAtMs: phases.dumpStartedAtMs,
|
|
290
|
+
dumpMs: phases.dumpMs,
|
|
291
|
+
cloneBootStartedAtMs: phases.cloneBootStartedAtMs,
|
|
292
|
+
cloneBootMs: phases.cloneBootMs,
|
|
293
|
+
pgDumpStartedAtMs: phases.pgDumpStartedAtMs,
|
|
294
|
+
pgDumpMs: phases.pgDumpMs,
|
|
295
|
+
},
|
|
296
|
+
diagnostics,
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
return { file, report };
|
|
300
|
+
}
|