@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,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
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// Diagnostic dump (ADR-0035, via the throwaway clone of the addendum). Where a store backup keeps the
|
|
2
|
+
// datadir tarball as its artefact, a diagnostic dump turns the store into human-readable SQL — every table
|
|
3
|
+
// (synced + the `_overlay`/`_mutations` journal), the `pgxsinkit` metadata schema, the read-model views,
|
|
4
|
+
// and the reconcile functions/triggers — so a support engineer sees the misbehaving store EXACTLY as it
|
|
5
|
+
// holds it, unflushed writes and all.
|
|
6
|
+
//
|
|
7
|
+
// The mechanism is the addendum's throwaway clone, NOT the abandoned suspend/reopen seam: (1) take a LIVE
|
|
8
|
+
// datadir dump of the running store (the SAME checkpoint + `dumpDataDir` core the store backup uses, but
|
|
9
|
+
// uncompressed — the clone consumes it immediately, so the gzip+gunzip round trip is pure waste); (2) boot
|
|
10
|
+
// a memory-backed THROWAWAY PGlite from that dump via `loadDataDir` — engine-less, no `live` extension,
|
|
11
|
+
// nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) run `pg_dump` against the throwaway; (4) discard
|
|
12
|
+
// it. The live engine is never touched — the addendum's whole point — so tabs never notice beyond the
|
|
13
|
+
// lifecycle slot reporting busy.
|
|
14
|
+
//
|
|
15
|
+
// `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` below (ADR-0035 decision 7): its
|
|
16
|
+
// ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle, fetched on first
|
|
17
|
+
// `exportDiagnostics`.
|
|
18
|
+
|
|
19
|
+
import { PGlite } from "@electric-sql/pglite";
|
|
20
|
+
|
|
21
|
+
import type { MutationDiagnostics } from "@pgxsinkit/contracts";
|
|
22
|
+
|
|
23
|
+
import { compactTimestamp, type DiagnosticDumpReport, deriveStoreId, nowMs, performDatadirDump } from "./export-store";
|
|
24
|
+
import type { ClientPGlite } from "./index";
|
|
25
|
+
import { resolveStoreDataDir } from "./store-path";
|
|
26
|
+
|
|
27
|
+
/** Options for {@link SyncClient.exportDiagnostics}. */
|
|
28
|
+
export interface DiagnosticExportOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Override the generated artefact file name. When omitted, the name is
|
|
31
|
+
* `<storeId>-<timestamp>-diagnostics.sql`, where `storeId` is a filesystem-safe derivation of the store
|
|
32
|
+
* path (see `deriveStoreId`).
|
|
33
|
+
*/
|
|
34
|
+
fileName?: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The SQL artefact + its report — the resolved value of {@link SyncClient.exportDiagnostics}. */
|
|
38
|
+
export interface DiagnosticExportResult {
|
|
39
|
+
/** The `pg_dump` output as a named `File` (`application/sql`), loadable into a vanilla Postgres. */
|
|
40
|
+
file: File;
|
|
41
|
+
/** The structured record of the export (ADR-0035). */
|
|
42
|
+
report: DiagnosticDumpReport;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */
|
|
46
|
+
export interface DiagnosticExportDeps {
|
|
47
|
+
/** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
|
|
48
|
+
pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">;
|
|
49
|
+
/** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
|
|
50
|
+
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
51
|
+
/**
|
|
52
|
+
* The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact
|
|
53
|
+
* file name. The resolved PGlite dataDir URL is deliberately NOT used: it is internal plumbing and must
|
|
54
|
+
* not leak into an artefact name as something to imitate.
|
|
55
|
+
*/
|
|
56
|
+
storePath?: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* The shape of `@electric-sql/pglite-tools/pg_dump` — declared locally so the dynamic `import()` stays
|
|
61
|
+
* typed without a static top-level dependency on the module (which would pull its WASM into the boot
|
|
62
|
+
* bundle). `pgDump` runs the WASM `pg_dump` on the given instance's single connection and returns the SQL
|
|
63
|
+
* as a `File`. We run it against the THROWAWAY clone only, never the live engine.
|
|
64
|
+
*/
|
|
65
|
+
interface PgliteToolsModule {
|
|
66
|
+
pgDump: (opts: { pg: PGlite; args?: string[]; fileName?: string }) => Promise<File>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* A process-unique suffix source for the throwaway clone's store name. The clone is memory-backed and
|
|
71
|
+
* closed in a `finally`, so a collision would only matter if two dumps overlapped — the lifecycle slot
|
|
72
|
+
* already forbids that — but a monotonic counter plus a random token makes the name collision-free by
|
|
73
|
+
* construction regardless, so a stray second clone can never adopt a live one's memory namespace.
|
|
74
|
+
*/
|
|
75
|
+
let cloneCounter = 0;
|
|
76
|
+
const nextCloneStorePath = (): string =>
|
|
77
|
+
`pgxsinkit-export-clone-${++cloneCounter}-${Math.random().toString(36).slice(2, 10)}`;
|
|
78
|
+
|
|
79
|
+
/** The four extra phase walls the throwaway-clone pipeline adds on top of the shared checkpoint/dump pair. */
|
|
80
|
+
export interface CloneDumpPhases {
|
|
81
|
+
/** Offset from `startPerf` when the internal `dumpDataDir` (the clone's source) began. */
|
|
82
|
+
dumpStartedAtMs: number;
|
|
83
|
+
/** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
|
|
84
|
+
dumpMs: number;
|
|
85
|
+
/** Offset from `startPerf` when the `CHECKPOINT` began. */
|
|
86
|
+
checkpointStartedAtMs: number;
|
|
87
|
+
/** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */
|
|
88
|
+
checkpointMs: number;
|
|
89
|
+
/** Offset from `startPerf` when the throwaway clone's `PGlite.create({ loadDataDir })` began. */
|
|
90
|
+
cloneBootStartedAtMs: number;
|
|
91
|
+
/** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
|
|
92
|
+
cloneBootMs: number;
|
|
93
|
+
/** Offset from `startPerf` when `pg_dump` began running against the clone. */
|
|
94
|
+
pgDumpStartedAtMs: number;
|
|
95
|
+
/** `pg_dump` wall — the WASM `pg_dump` reading the clone out to SQL. */
|
|
96
|
+
pgDumpMs: number;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */
|
|
100
|
+
export interface CloneDumpResult {
|
|
101
|
+
/** The `pg_dump` output bytes (unwrapped from pglite-tools' `File` polyfill). */
|
|
102
|
+
sqlBytes: Uint8Array<ArrayBuffer>;
|
|
103
|
+
/** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */
|
|
104
|
+
phases: CloneDumpPhases;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The throwaway-clone dump core shared by BOTH `pgDump` exports (ADR-0035 addendum): (1) a LIVE datadir dump
|
|
109
|
+
* of the running store (`compression: "none"` — the clone consumes the bytes immediately, so gzip+gunzip is
|
|
110
|
+
* pure waste); (2) a memory-backed THROWAWAY PGlite booted from it via `loadDataDir` — engine-less, no
|
|
111
|
+
* `live` extension, nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) `pg_dump` against the throwaway
|
|
112
|
+
* with the caller's `args` (none for a diagnostic dump; the `-t` allowlist + `--no-owner` for a data
|
|
113
|
+
* export); (4) discard the clone in a `finally`. Factored out so `performDiagnosticExport` and
|
|
114
|
+
* `performDataExport` cannot drift on the clone plumbing, the memory-scheme selection, or the timing house
|
|
115
|
+
* style — the ONLY differences between the two dumps are the `pg_dump` args and the artefact assembly.
|
|
116
|
+
*
|
|
117
|
+
* `@electric-sql/pglite-tools` is loaded ONLY via the dynamic `import()` here (ADR-0035 decision 7): its
|
|
118
|
+
* ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle.
|
|
119
|
+
*/
|
|
120
|
+
export interface CloneDumpOptions {
|
|
121
|
+
/** The `pg_dump` args (none for a diagnostic dump; `-t` allowlist + `--no-owner` for a data export). */
|
|
122
|
+
pgDumpArgs?: string[];
|
|
123
|
+
/**
|
|
124
|
+
* A hook run on the throwaway clone AFTER boot, BEFORE `pg_dump` — its one legitimate window to mutate the
|
|
125
|
+
* clone (which is fully owned and discarded straight after). The data export uses it to drop the reconcile
|
|
126
|
+
* triggers `pg_dump -t` would otherwise pull into the artefact (see `buildDataExportCloneCleanupSql`); a
|
|
127
|
+
* diagnostic dump passes none (it wants the store verbatim).
|
|
128
|
+
*/
|
|
129
|
+
prepareClone?: (clone: PGlite) => Promise<void>;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function runThrowawayCloneDump(
|
|
133
|
+
pglite: Pick<ClientPGlite, "exec" | "dumpDataDir">,
|
|
134
|
+
startPerf: number,
|
|
135
|
+
options: CloneDumpOptions = {},
|
|
136
|
+
): Promise<CloneDumpResult> {
|
|
137
|
+
// Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).
|
|
138
|
+
const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
|
|
139
|
+
pglite,
|
|
140
|
+
"none",
|
|
141
|
+
startPerf,
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
// Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036
|
|
145
|
+
// decision 5: NEVER PGlite's explicit `fs: new MemoryFS()` — on 0.5.4 a `dumpDataDir` from an explicit-fs
|
|
146
|
+
// instance silently omits post-initdb relation files). No extensions, no `electric` engine, no `live`:
|
|
147
|
+
// the clone exists only to be read out by `pg_dump`, and `DEALLOCATE ALL` has nothing here to corrupt.
|
|
148
|
+
const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
|
|
149
|
+
const cloneBootStartedAtMs = nowMs() - startPerf;
|
|
150
|
+
const cloneBootStartPerf = nowMs();
|
|
151
|
+
const throwaway = await PGlite.create({ dataDir: cloneDataDir, loadDataDir: dumped });
|
|
152
|
+
const cloneBootMs = nowMs() - cloneBootStartPerf;
|
|
153
|
+
|
|
154
|
+
let sqlBytes: Uint8Array<ArrayBuffer>;
|
|
155
|
+
let pgDumpStartedAtMs: number;
|
|
156
|
+
let pgDumpMs: number;
|
|
157
|
+
try {
|
|
158
|
+
// Between boot and dump — the clone's one mutation window (owned, discarded next) — run the caller's
|
|
159
|
+
// prepare hook. The data export drops the reconcile triggers `-t` would otherwise capture; timed inside
|
|
160
|
+
// the pgDump-prep gap, it is a couple of tiny DROPs, so it is not given its own report phase.
|
|
161
|
+
if (options.prepareClone) {
|
|
162
|
+
await options.prepareClone(throwaway);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Step 3 — the lazy `pg_dump`. The subpath specifier (its export map's `./pg_dump` entry) keeps the
|
|
166
|
+
// main pglite-tools entry — and its WASM — off this import. The caller rebuilds the artefact `File`
|
|
167
|
+
// from the returned bytes, so `fileName` here is cosmetic only.
|
|
168
|
+
pgDumpStartedAtMs = nowMs() - startPerf;
|
|
169
|
+
const pgDumpStartPerf = nowMs();
|
|
170
|
+
const { pgDump } = (await import("@electric-sql/pglite-tools/pg_dump")) as PgliteToolsModule;
|
|
171
|
+
const dumpFile = await pgDump({
|
|
172
|
+
pg: throwaway,
|
|
173
|
+
...(options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {}),
|
|
174
|
+
fileName: "pgxsinkit-export.sql",
|
|
175
|
+
});
|
|
176
|
+
pgDumpMs = nowMs() - pgDumpStartPerf;
|
|
177
|
+
sqlBytes = new Uint8Array(await dumpFile.arrayBuffer());
|
|
178
|
+
} finally {
|
|
179
|
+
// Step 4 — discard the throwaway in a `finally`, so a THROWING `pg_dump` never leaks the clone (its
|
|
180
|
+
// memory is co-resident with the live engine for the export's duration; leaking one is a real cost).
|
|
181
|
+
await throwaway.close();
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
sqlBytes,
|
|
186
|
+
phases: {
|
|
187
|
+
checkpointStartedAtMs,
|
|
188
|
+
checkpointMs,
|
|
189
|
+
dumpStartedAtMs,
|
|
190
|
+
dumpMs,
|
|
191
|
+
cloneBootStartedAtMs,
|
|
192
|
+
cloneBootMs,
|
|
193
|
+
pgDumpStartedAtMs,
|
|
194
|
+
pgDumpMs,
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Run a diagnostic dump (ADR-0035): live datadir dump → memory-backed throwaway clone → `pg_dump` → discard
|
|
201
|
+
* the clone → assemble the report. The caller (`createSyncClient`) awaits engine-ready and enters the
|
|
202
|
+
* lifecycle slot BEFORE calling this, exactly as it does for the store backup — kept out of here so the
|
|
203
|
+
* helper stays a pure "do the dump" unit.
|
|
204
|
+
*/
|
|
205
|
+
export async function performDiagnosticExport(
|
|
206
|
+
deps: DiagnosticExportDeps,
|
|
207
|
+
options: DiagnosticExportOptions = {},
|
|
208
|
+
): Promise<DiagnosticExportResult> {
|
|
209
|
+
const startedAt = Date.now();
|
|
210
|
+
const startPerf = nowMs();
|
|
211
|
+
|
|
212
|
+
// A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +
|
|
213
|
+
// functions — everything a support engineer needs to read a misbehaving store.
|
|
214
|
+
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pglite, startPerf);
|
|
215
|
+
|
|
216
|
+
const storeId = deriveStoreId(deps.storePath);
|
|
217
|
+
const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;
|
|
218
|
+
// Build the artefact `File` from the raw bytes, NOT by re-wrapping pglite-tools' `File`: it is a polyfill
|
|
219
|
+
// in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name (the same bun
|
|
220
|
+
// quirk the store backup hit) — the bytes-first path guarantees the store-scoped name/mime stick.
|
|
221
|
+
const file = new File([sqlBytes], fileName, { type: "application/sql" });
|
|
222
|
+
|
|
223
|
+
// Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the
|
|
224
|
+
// SQL also carries, so the report and the artefact agree on what was unflushed at dump time.
|
|
225
|
+
const diagnostics = await deps.readMutationStats();
|
|
226
|
+
|
|
227
|
+
const report: DiagnosticDumpReport = {
|
|
228
|
+
reportVersion: 1,
|
|
229
|
+
kind: "diagnostic-dump",
|
|
230
|
+
scope: "everything",
|
|
231
|
+
startedAt,
|
|
232
|
+
totalMs: nowMs() - startPerf,
|
|
233
|
+
byteLength: file.size,
|
|
234
|
+
phases,
|
|
235
|
+
diagnostics,
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
return { file, report };
|
|
239
|
+
}
|