@pgxsinkit/client 0.3.0 → 0.5.1
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/LICENSE +21 -0
- package/LICENSE-APACHE-2.0 +202 -0
- package/NOTICE +81 -0
- package/README.md +10 -3
- package/dist/boot-report.d.ts +8 -8
- package/dist/circuits/envelope-to-change.d.ts +9 -5
- package/dist/circuits/envelope-to-change.d.ts.map +1 -1
- package/dist/circuits/group-sync.d.ts +2 -2
- package/dist/circuits/group-sync.d.ts.map +1 -1
- package/dist/circuits/stream-source.d.ts +6 -0
- package/dist/circuits/stream-source.d.ts.map +1 -1
- package/dist/circuits/sync-engine.d.ts +2 -2
- package/dist/circuits/sync-engine.d.ts.map +1 -1
- package/dist/event-lane.d.ts +32 -1
- package/dist/event-lane.d.ts.map +1 -1
- package/dist/export-data.d.ts +3 -3
- package/dist/export-dump.d.ts +10 -10
- package/dist/export-dump.d.ts.map +1 -1
- package/dist/export-store.d.ts +13 -13
- package/dist/index.d.ts +196 -100
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1044 -487
- package/dist/index.js.map +39 -36
- package/dist/local-store.d.ts +1 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-tables.d.ts +58 -0
- package/dist/local-tables.d.ts.map +1 -1
- package/dist/mutation.d.ts +2 -2
- package/dist/mutation.d.ts.map +1 -1
- package/dist/mutations-api.d.ts +1 -1
- package/dist/mutations-api.d.ts.map +1 -1
- package/dist/opfs-effects.d.ts +30 -2
- package/dist/opfs-effects.d.ts.map +1 -1
- package/dist/schema.d.ts +12 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/store-boot.d.ts +30 -2
- package/dist/store-boot.d.ts.map +1 -1
- package/dist/store-build.d.ts +19 -0
- package/dist/store-build.d.ts.map +1 -0
- package/dist/store-engine.d.ts +22 -0
- package/dist/store-engine.d.ts.map +1 -0
- package/dist/store-meta.d.ts +29 -3
- package/dist/store-meta.d.ts.map +1 -1
- package/dist/store-ownership-lock.d.ts +33 -0
- package/dist/store-ownership-lock.d.ts.map +1 -0
- package/dist/store-path.d.ts +43 -31
- package/dist/store-path.d.ts.map +1 -1
- package/dist/sync/apply.d.ts +5 -5
- package/dist/sync/apply.d.ts.map +1 -1
- package/dist/sync/copy.d.ts +82 -6
- package/dist/sync/copy.d.ts.map +1 -1
- package/dist/sync/drizzle-executor.d.ts +4 -4
- package/dist/sync/drizzle-executor.d.ts.map +1 -1
- package/dist/sync/subscription-state.d.ts +5 -5
- package/dist/sync/subscription-state.d.ts.map +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +2 -1
- package/dist/testing.js.map +4 -4
- package/dist/worker/attach-sync-client.d.ts +24 -13
- package/dist/worker/attach-sync-client.d.ts.map +1 -1
- package/dist/worker/define-sync-worker.d.ts +35 -18
- package/dist/worker/define-sync-worker.d.ts.map +1 -1
- package/dist/worker/live-query-manager.d.ts +3 -3
- package/dist/worker/live-query-manager.d.ts.map +1 -1
- package/dist/worker/live-query-params-guard.d.ts +5 -5
- package/dist/worker/live-query-params-guard.d.ts.map +1 -1
- package/dist/worker/protocol.d.ts +26 -7
- package/dist/worker/protocol.d.ts.map +1 -1
- package/package.json +11 -8
- package/skills/core/SKILL.md +80 -15
- package/skills/operating/SKILL.md +129 -129
- package/skills/operating/references/postgres-builds.md +48 -0
- package/src/boot-report.ts +12 -12
- package/src/circuits/envelope-to-change.ts +121 -12
- package/src/circuits/group-sync.ts +2 -2
- package/src/circuits/stream-source.ts +35 -9
- package/src/circuits/sync-engine.ts +6 -4
- package/src/event-lane.ts +132 -14
- package/src/export-data.ts +4 -4
- package/src/export-dump.ts +31 -36
- package/src/export-store.ts +20 -20
- package/src/index.ts +576 -340
- package/src/live-rows-sql.ts +1 -1
- package/src/local-store.ts +2 -2
- package/src/local-tables.ts +70 -6
- package/src/mutation.ts +9 -8
- package/src/mutations-api.ts +4 -4
- package/src/opfs-effects.ts +74 -10
- package/src/schema.ts +124 -18
- package/src/store-boot.ts +71 -7
- package/src/store-build.ts +37 -0
- package/src/store-engine.ts +94 -0
- package/src/store-lifecycle.ts +1 -1
- package/src/store-meta.ts +155 -4
- package/src/store-ownership-lock.ts +109 -0
- package/src/store-path.ts +59 -43
- package/src/sync/apply.ts +32 -46
- package/src/sync/copy.ts +108 -13
- package/src/sync/drizzle-executor.ts +18 -19
- package/src/sync/metadata-tables.ts +1 -1
- package/src/sync/subscription-state.ts +7 -7
- package/src/testing.ts +3 -3
- package/src/worker/attach-sync-client.ts +146 -60
- package/src/worker/define-sync-worker.ts +212 -83
- package/src/worker/engine-router.ts +1 -1
- package/src/worker/live-query-fingerprint.ts +4 -4
- package/src/worker/live-query-manager.ts +12 -12
- package/src/worker/live-query-params-guard.ts +16 -15
- package/src/worker/protocol.ts +38 -7
package/src/event-lane.ts
CHANGED
|
@@ -18,10 +18,15 @@
|
|
|
18
18
|
* client-side quarantine (ADR-0053 decision 4): terminal deletion happens only on `acked`/`refused`/
|
|
19
19
|
* `rejected`. A batch that keeps failing backs off at a ceiling, observably, while the Outbox keeps
|
|
20
20
|
* absorbing appends — it is designed to hold offline weeks.
|
|
21
|
+
*
|
|
22
|
+
* ADR-0060 adds one wrinkle to that second invariant's `acked` half: with `events.ackedRetentionMs > 0` an
|
|
23
|
+
* acked row is STAMPED (`acked_at_us`) and retained for the retention rather than deleted at once, so a
|
|
24
|
+
* best-guess view can keep counting it across the ack→fold→sync window. It is a delayed delete, not a
|
|
25
|
+
* changed verdict — a stamped row is no longer PENDING anywhere in this file (assembly skips it, the drain
|
|
26
|
+
* signal ignores it), and the sweep retires it.
|
|
21
27
|
*/
|
|
22
28
|
|
|
23
29
|
import { and, asc, eq, inArray, isNull, lte, notInArray, or, sql } from "drizzle-orm";
|
|
24
|
-
import { drizzle } from "drizzle-orm/pglite";
|
|
25
30
|
|
|
26
31
|
import {
|
|
27
32
|
batchEventAckSchema,
|
|
@@ -38,11 +43,12 @@ import {
|
|
|
38
43
|
type EventStreamEntry,
|
|
39
44
|
type SyncTableRegistry,
|
|
40
45
|
} from "@pgxsinkit/contracts";
|
|
46
|
+
import { drizzle } from "@pgxsinkit/pgwasm/drizzle";
|
|
41
47
|
|
|
42
48
|
import { syncDebug } from "./debug";
|
|
43
49
|
import { getOutboxTable } from "./local-tables";
|
|
44
50
|
|
|
45
|
-
/** The raw local-store seam the Event lane executes through (structurally
|
|
51
|
+
/** The raw local-store seam the Event lane executes through (structurally pgwasm; mirrors `MutationDb`). */
|
|
46
52
|
export interface EventLaneDb {
|
|
47
53
|
query: <TRow extends Record<string, unknown> = Record<string, unknown>>(
|
|
48
54
|
sql: string,
|
|
@@ -104,6 +110,28 @@ export interface EventLaneOptions {
|
|
|
104
110
|
intervalMs?: number;
|
|
105
111
|
/** Backoff tuning for deferred rows and for batch-level faults. */
|
|
106
112
|
backoff?: EventBackoffOptions;
|
|
113
|
+
/**
|
|
114
|
+
* How long an **acked** row is RETAINED in the Outbox after the server accepts it, in ms (ADR-0060).
|
|
115
|
+
* Defaults to `0`.
|
|
116
|
+
*
|
|
117
|
+
* `0` is exactly the lane's original behaviour: an `acked` verdict DELETES the row on the spot, in the
|
|
118
|
+
* same statement that retires the terminal `refused`/`rejected` ones — no stamp, no sweep, no added cost
|
|
119
|
+
* on the default path. Anything greater turns on the **acked ledger**: the row stays, stamped with
|
|
120
|
+
* `acked_at_us`, until a sweep retires it that many ms later.
|
|
121
|
+
*
|
|
122
|
+
* It exists for ONE consumer shape — a best-guess view composing pending Outbox rows with down-synced
|
|
123
|
+
* aggregates. The server accepts an event well BEFORE its consumer folds it, and the folded row syncs
|
|
124
|
+
* back down later still, so a composition that drops the event at the ack dips for the whole ack→fold→sync
|
|
125
|
+
* window. With a retention the acked row is still there to be counted during it. The library takes no
|
|
126
|
+
* position on when the fold landed (it cannot know); the view keeps the row until its own synced value
|
|
127
|
+
* accounts for it, and the retention is the backstop.
|
|
128
|
+
*
|
|
129
|
+
* Retained rows are NOT pending: they are invisible to batch assembly (never re-posted), to the drain
|
|
130
|
+
* signal `{ empty }`, to `diagnostics().outbox`, and to the non-forced `destroy()` refusal. Size it to
|
|
131
|
+
* the deployment's ack→fold→sync latency plus margin, not to "how long I want the history" — the Outbox
|
|
132
|
+
* is not an archive.
|
|
133
|
+
*/
|
|
134
|
+
ackedRetentionMs?: number;
|
|
107
135
|
/** Per-Event-stream overrides, keyed by Event-stream name. */
|
|
108
136
|
streams?: Record<string, EventStreamFlushOptions>;
|
|
109
137
|
}
|
|
@@ -122,6 +150,9 @@ export interface EventAppendResult {
|
|
|
122
150
|
* The **drain signal** (ADR-0053 decision 2): whether the Outbox is empty. Deliberately no count — a count
|
|
123
151
|
* that updates only on transitions is stale by construction, and a count updated per append is a worse live
|
|
124
152
|
* query. Richer detail is a query against the Outbox table.
|
|
153
|
+
*
|
|
154
|
+
* "Empty" is "nothing AWAITS A SERVER VERDICT", so acked rows the ledger is retaining (ADR-0060) do not
|
|
155
|
+
* hold it `false` — they have had their verdict.
|
|
125
156
|
*/
|
|
126
157
|
export interface OutboxStatus {
|
|
127
158
|
empty: boolean;
|
|
@@ -488,6 +519,10 @@ export function validateEventLaneOptions(options: EventLaneOptions): void {
|
|
|
488
519
|
|
|
489
520
|
requireCount("events.batchSize", options.batchSize);
|
|
490
521
|
requireMs("events.intervalMs", options.intervalMs, 1);
|
|
522
|
+
// The acked ledger's retention (ADR-0060). `0` is meaningful — it IS the default, "delete on ack" — so
|
|
523
|
+
// the floor is 0, not 1; a negative or NaN retention would make the sweep's cutoff nonsense (a negative
|
|
524
|
+
// one would retire rows the server acked in the FUTURE, a NaN one would retire nothing, silently).
|
|
525
|
+
requireMs("events.ackedRetentionMs", options.ackedRetentionMs, 0);
|
|
491
526
|
const globalBackoff = requireBackoff("events.backoff", options.backoff, defaults);
|
|
492
527
|
|
|
493
528
|
for (const [stream, streamOptions] of Object.entries(options.streams ?? {})) {
|
|
@@ -531,6 +566,13 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
531
566
|
// Clamp to the contracts-level cap: the server enforces it independently of any client tuning, so a
|
|
532
567
|
// client configured above it would only ever produce 413s.
|
|
533
568
|
const batchSize = Math.max(1, Math.min(laneOptions.batchSize ?? DEFAULT_EVENT_BATCH_SIZE, MAX_EVENTS_PER_BATCH));
|
|
569
|
+
/**
|
|
570
|
+
* The acked ledger's retention (ADR-0060). The default `0` keeps the lane's original semantics EXACTLY:
|
|
571
|
+
* an `acked` verdict deletes the row in the same statement as the other terminal verdicts, so no row is
|
|
572
|
+
* ever stamped while this runtime runs and the per-pass sweep is not needed at all.
|
|
573
|
+
*/
|
|
574
|
+
const ackedRetentionMs = laneOptions.ackedRetentionMs ?? 0;
|
|
575
|
+
const retainsAcked = ackedRetentionMs > 0;
|
|
534
576
|
|
|
535
577
|
const nowUs = (): string => (BigInt(clockMs()) * 1000n).toString();
|
|
536
578
|
const backoffFor = (stream?: string): EventBackoffOptions => ({
|
|
@@ -560,11 +602,17 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
560
602
|
* The drain signal's read. Deliberately `LIMIT 1`, never `count(*)`: the signal is a BOOLEAN, and an
|
|
561
603
|
* Outbox designed to hold offline weeks would make a counting scan the expensive part of every flush pass
|
|
562
604
|
* and every lifecycle check. (An app that genuinely wants a count queries the table itself.)
|
|
605
|
+
*
|
|
606
|
+
* "Empty" means NO ROW AWAITS A SERVER VERDICT (ADR-0060) — `acked_at_us IS NULL` — not "no row at all".
|
|
607
|
+
* An acked row being held for the ledger's retention has already had its verdict, so it must not keep the
|
|
608
|
+
* signal `{ empty: false }`: this boolean is what the export drain polls, what `diagnostics().outbox`
|
|
609
|
+
* answers, and what a non-forced `destroy()` refuses on, and every one of those means "still owed".
|
|
563
610
|
*/
|
|
564
611
|
const isOutboxEmpty = async (): Promise<boolean> => {
|
|
565
612
|
const query = queryBuilder()
|
|
566
613
|
.select({ one: sql<number>`1`.as("one") })
|
|
567
614
|
.from(outbox)
|
|
615
|
+
.where(isNull(outbox.ackedAtUs))
|
|
568
616
|
.limit(1)
|
|
569
617
|
.toSQL();
|
|
570
618
|
const result = await options.db.query<{ one: number }>(query.sql, query.params as unknown[]);
|
|
@@ -577,13 +625,38 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
577
625
|
return empty;
|
|
578
626
|
};
|
|
579
627
|
|
|
628
|
+
/**
|
|
629
|
+
* The acked ledger's sweep (ADR-0060): retire every row whose `acked_at_us` is older than the configured
|
|
630
|
+
* retention. One statement, served by the `(acked_at_us, seq)` index; pending rows are excluded by SQL's
|
|
631
|
+
* own NULL semantics (`NULL <= x` is never true), so no `IS NOT NULL` is needed to keep them.
|
|
632
|
+
*
|
|
633
|
+
* A retention of `0` makes the cutoff `now`, which retires every stamped row — the correct cleanup when a
|
|
634
|
+
* deployment turns the ledger OFF again, and the reason this runs once at construction unconditionally.
|
|
635
|
+
*/
|
|
636
|
+
const sweepAckedLedger = async (): Promise<void> => {
|
|
637
|
+
const cutoffUs = (BigInt(nowUs()) - BigInt(Math.round(ackedRetentionMs)) * 1000n).toString();
|
|
638
|
+
const query = queryBuilder().delete(outbox).where(lte(outbox.ackedAtUs, cutoffUs)).toSQL();
|
|
639
|
+
await options.db.query(query.sql, query.params as unknown[]);
|
|
640
|
+
};
|
|
641
|
+
|
|
580
642
|
// The first read of the drain signal, kicked off eagerly so a subscriber that arrives before any append
|
|
581
643
|
// or flush still gets the CURRENT state delivered (never a silent subscription). Failures are swallowed:
|
|
582
644
|
// an unreadable Outbox at boot is a store problem the boot path itself reports.
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
645
|
+
//
|
|
646
|
+
// The ledger sweep runs FIRST, and at construction it runs whatever the retention is: rows stamped by a
|
|
647
|
+
// PREVIOUS run under a different (or since-removed) retention are the only stamped rows a retention-0
|
|
648
|
+
// runtime can ever meet, and this is where they are retired. Afterwards a retention-0 lane can produce no
|
|
649
|
+
// stamped row at all, which is why its flush passes skip the sweep entirely and stay exactly as cheap as
|
|
650
|
+
// they were before the ledger existed.
|
|
651
|
+
const initialProbe = sweepAckedLedger()
|
|
652
|
+
.catch((error: unknown) => {
|
|
653
|
+
syncDebug("event lane: initial acked-ledger sweep failed", { error });
|
|
654
|
+
})
|
|
655
|
+
.then(() => refreshDrainSignal())
|
|
656
|
+
.catch((error: unknown) => {
|
|
657
|
+
syncDebug("event lane: initial drain-signal probe failed", { error });
|
|
658
|
+
return false;
|
|
659
|
+
});
|
|
587
660
|
|
|
588
661
|
const emitReport = (report: EventLaneReport): void => {
|
|
589
662
|
if (report.terminal.length === 0 && report.deferred.length === 0 && report.backoff == null) {
|
|
@@ -683,9 +756,14 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
683
756
|
);
|
|
684
757
|
|
|
685
758
|
/**
|
|
686
|
-
* A row deferred by the server waits out its own backoff; every other row is eligible.
|
|
759
|
+
* A row deferred by the server waits out its own backoff; every other PENDING row is eligible.
|
|
760
|
+
*
|
|
761
|
+
* `acked_at_us IS NULL` is the pending half (ADR-0060) and it is not optional: a row the server has
|
|
762
|
+
* already acked is being held for the ledger's retention, and re-posting it would be a duplicate delivery
|
|
763
|
+
* the `eventId` dedupe would have to absorb — exactly the traffic the ledger is not for.
|
|
687
764
|
*/
|
|
688
|
-
const eligibleNow = () =>
|
|
765
|
+
const eligibleNow = () =>
|
|
766
|
+
and(isNull(outbox.ackedAtUs), or(isNull(outbox.nextRetryAtUs), lte(outbox.nextRetryAtUs, nowUs())));
|
|
689
767
|
|
|
690
768
|
const readEligibleRows = async (limit: number): Promise<OutboxRow[]> => {
|
|
691
769
|
// Rows come back through the RAW seam (no drizzle result mapping), so every column is aliased to its
|
|
@@ -810,6 +888,23 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
810
888
|
await options.db.query(query.sql, query.params as unknown[]);
|
|
811
889
|
};
|
|
812
890
|
|
|
891
|
+
/**
|
|
892
|
+
* Stamp acked rows instead of deleting them (ADR-0060, the ledger's `ackedRetentionMs > 0` path). The
|
|
893
|
+
* stamp is what makes the row non-pending everywhere while leaving it readable by a best-guess view for
|
|
894
|
+
* the retention window; the sweep is what eventually retires it.
|
|
895
|
+
*/
|
|
896
|
+
const stampAcked = async (eventIds: readonly string[]): Promise<void> => {
|
|
897
|
+
if (eventIds.length === 0) {
|
|
898
|
+
return;
|
|
899
|
+
}
|
|
900
|
+
const query = queryBuilder()
|
|
901
|
+
.update(outbox)
|
|
902
|
+
.set({ ackedAtUs: nowUs() })
|
|
903
|
+
.where(inArray(outbox.eventId, [...eventIds]))
|
|
904
|
+
.toSQL();
|
|
905
|
+
await options.db.query(query.sql, query.params as unknown[]);
|
|
906
|
+
};
|
|
907
|
+
|
|
813
908
|
/** Park one deferred row: bump its attempt count and push its next retry out by the jittered backoff. */
|
|
814
909
|
const deferEvent = async (row: OutboxRow, reason: string | undefined): Promise<void> => {
|
|
815
910
|
const attempt = row.attemptCount + 1;
|
|
@@ -910,6 +1005,8 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
910
1005
|
const terminal: EventLaneVerdict[] = [];
|
|
911
1006
|
const deferred: EventLaneVerdict[] = [];
|
|
912
1007
|
const deletable: string[] = [];
|
|
1008
|
+
/** Acked rows the ledger RETAINS (empty unless `ackedRetentionMs > 0` — see {@link stampAcked}). */
|
|
1009
|
+
const stampable: string[] = [];
|
|
913
1010
|
|
|
914
1011
|
for (const ack of acks) {
|
|
915
1012
|
const row = batch.rowsByEventId.get(ack.eventId);
|
|
@@ -933,19 +1030,29 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
933
1030
|
continue;
|
|
934
1031
|
}
|
|
935
1032
|
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
//
|
|
939
|
-
//
|
|
940
|
-
terminal.
|
|
1033
|
+
if (ack.status === "acked") {
|
|
1034
|
+
// The acked ledger (ADR-0060). With a retention the row is STAMPED and kept — the server has
|
|
1035
|
+
// accepted the event, but its consumer has not folded it and the folded aggregate has not synced
|
|
1036
|
+
// back down, so a best-guess view still needs the row. At the default retention of `0` it joins the
|
|
1037
|
+
// terminal deletes below, which is the pre-ledger behaviour byte for byte.
|
|
1038
|
+
(retainsAcked ? stampable : deletable).push(ack.eventId);
|
|
1039
|
+
continue;
|
|
941
1040
|
}
|
|
1041
|
+
|
|
1042
|
+
// `refused` (gating) and `rejected` (schema-invalid/oversized for a KNOWN stream) are terminal and
|
|
1043
|
+
// reported: once the row is deleted the Outbox can no longer answer what happened to it. They are
|
|
1044
|
+
// never retained — the ledger exists to bridge an ack to its fold, and neither of these will ever be
|
|
1045
|
+
// folded.
|
|
1046
|
+
deletable.push(ack.eventId);
|
|
1047
|
+
terminal.push(verdict);
|
|
942
1048
|
}
|
|
943
1049
|
|
|
944
1050
|
// An envelope the server answered for at all is settled; one it did not answer for stays put and rides
|
|
945
1051
|
// the next batch (the server owes a verdict per well-formed envelope, so this is a server bug, not a
|
|
946
1052
|
// reason to discard).
|
|
947
1053
|
await deleteEvents(deletable);
|
|
948
|
-
|
|
1054
|
+
await stampAcked(stampable);
|
|
1055
|
+
return { terminal, deferred, settledCount: deletable.length + stampable.length + deferred.length };
|
|
949
1056
|
};
|
|
950
1057
|
|
|
951
1058
|
let flushChain: Promise<void> = Promise.resolve();
|
|
@@ -954,6 +1061,17 @@ export function createEventLaneRuntime<TRegistry extends SyncTableRegistry>(
|
|
|
954
1061
|
if (!hasStreams) {
|
|
955
1062
|
return;
|
|
956
1063
|
}
|
|
1064
|
+
// The ledger's sweep (ADR-0060), at the TOP of the pass and BEFORE the backoff gate: retiring rows the
|
|
1065
|
+
// server already acked is store-local bookkeeping that owes the network nothing, so a lane sitting in
|
|
1066
|
+
// batch backoff must still make the retention true. Skipped entirely at the default retention of `0`,
|
|
1067
|
+
// where nothing can be stamped (the construction-time sweep already retired anything a previous run
|
|
1068
|
+
// left behind), so the default path costs exactly what it did before.
|
|
1069
|
+
if (retainsAcked) {
|
|
1070
|
+
await sweepAckedLedger().catch((error: unknown) => {
|
|
1071
|
+
// The sweep is bookkeeping: a failure delays a delete, it never costs an event. Never fail a pass.
|
|
1072
|
+
syncDebug("event lane: acked-ledger sweep failed", { error });
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
957
1075
|
if (batchAttempt > 0 && clockMs() < batchRetryAtMs) {
|
|
958
1076
|
syncDebug("event lane: flush skipped (batch-level backoff)", {
|
|
959
1077
|
retryInMs: batchRetryAtMs - clockMs(),
|
package/src/export-data.ts
CHANGED
|
@@ -25,7 +25,7 @@ import type { MutationDiagnostics } from "@pgxsinkit/contracts";
|
|
|
25
25
|
|
|
26
26
|
import { runThrowawayCloneDump } from "./export-dump";
|
|
27
27
|
import { compactTimestamp, type DataExportReport, deriveStoreId, nowMs } from "./export-store";
|
|
28
|
-
import type {
|
|
28
|
+
import type { PgwasmClient } from "./index";
|
|
29
29
|
|
|
30
30
|
/** The default drain budget: actively flush + await the convergence barrier for up to 15s before failing. */
|
|
31
31
|
export const DEFAULT_DRAIN_TIMEOUT_MS = 15_000;
|
|
@@ -113,7 +113,7 @@ export class DataExportDrainError extends Error {
|
|
|
113
113
|
/** The dependencies {@link performDataExport} needs from the owning client — narrow, so it is unit-testable. */
|
|
114
114
|
export interface DataExportDeps {
|
|
115
115
|
/** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
|
|
116
|
-
|
|
116
|
+
pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">;
|
|
117
117
|
/** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
|
|
118
118
|
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
119
119
|
/** The optimistic flush (`client.flush()`), driven during the drain to send drainable rows. */
|
|
@@ -136,7 +136,7 @@ export interface DataExportDeps {
|
|
|
136
136
|
cloneCleanupSql: string;
|
|
137
137
|
/**
|
|
138
138
|
* The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact
|
|
139
|
-
* file name. The resolved
|
|
139
|
+
* file name. The resolved pgwasm dataDir URL is deliberately NOT used: internal plumbing, never an
|
|
140
140
|
* artefact-name seed.
|
|
141
141
|
*/
|
|
142
142
|
storePath?: string;
|
|
@@ -252,7 +252,7 @@ export async function performDataExport(
|
|
|
252
252
|
// portability. `-t` is repeated once per table. `runThrowawayCloneDump` phases are offset from the SAME
|
|
253
253
|
// export-start anchor, so they compose after the drain wall into one timeline.
|
|
254
254
|
const pgDumpArgs = ["--no-owner", ...deps.syncedTableNames.flatMap((name) => ["-t", name])];
|
|
255
|
-
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.
|
|
255
|
+
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pgwasm, startPerf, {
|
|
256
256
|
pgDumpArgs,
|
|
257
257
|
// Drop the reconcile triggers on the clone so `-t` yields portable, machinery-free tables.
|
|
258
258
|
...(deps.cloneCleanupSql.length > 0
|
package/src/export-dump.ts
CHANGED
|
@@ -7,21 +7,21 @@
|
|
|
7
7
|
// The mechanism is the addendum's throwaway clone, NOT the abandoned suspend/reopen seam: (1) take a LIVE
|
|
8
8
|
// datadir dump of the running store (the SAME checkpoint + `dumpDataDir` core the store backup uses, but
|
|
9
9
|
// uncompressed — the clone consumes it immediately, so the gzip+gunzip round trip is pure waste); (2) boot
|
|
10
|
-
// a memory-backed THROWAWAY
|
|
10
|
+
// a memory-backed THROWAWAY pgwasm from that dump via `loadDataDir` — engine-less, no `live` extension,
|
|
11
11
|
// nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) run `pg_dump` against the throwaway; (4) discard
|
|
12
12
|
// it. The live engine is never touched — the addendum's whole point — so tabs never notice beyond the
|
|
13
13
|
// lifecycle slot reporting busy.
|
|
14
14
|
//
|
|
15
|
-
// `@
|
|
15
|
+
// `@pgxsinkit/pgwasm-pg-dump` is loaded ONLY via the dynamic `import()` below (ADR-0035 decision 7): its
|
|
16
16
|
// ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle, fetched on first
|
|
17
17
|
// `exportDiagnostics`.
|
|
18
18
|
|
|
19
|
-
import { PGlite } from "@electric-sql/pglite";
|
|
20
|
-
|
|
21
19
|
import type { MutationDiagnostics } from "@pgxsinkit/contracts";
|
|
20
|
+
import { createPgwasm, type Pgwasm } from "@pgxsinkit/pgwasm";
|
|
21
|
+
import { cBuild } from "@pgxsinkit/pgwasm-c";
|
|
22
22
|
|
|
23
23
|
import { compactTimestamp, type DiagnosticDumpReport, deriveStoreId, nowMs, performDatadirDump } from "./export-store";
|
|
24
|
-
import type {
|
|
24
|
+
import type { PgwasmClient } from "./index";
|
|
25
25
|
import { resolveStoreDataDir } from "./store-path";
|
|
26
26
|
|
|
27
27
|
/** Options for {@link SyncClient.exportDiagnostics}. */
|
|
@@ -45,27 +45,17 @@ export interface DiagnosticExportResult {
|
|
|
45
45
|
/** The dependencies {@link performDiagnosticExport} needs from the owning client — narrow, so it is unit-testable. */
|
|
46
46
|
export interface DiagnosticExportDeps {
|
|
47
47
|
/** The live store to checkpoint and dump (the clone source; the live engine is never suspended). */
|
|
48
|
-
|
|
48
|
+
pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">;
|
|
49
49
|
/** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
|
|
50
50
|
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
51
51
|
/**
|
|
52
52
|
* The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default artefact
|
|
53
|
-
* file name. The resolved
|
|
53
|
+
* file name. The resolved pgwasm dataDir URL is deliberately NOT used: it is internal plumbing and must
|
|
54
54
|
* not leak into an artefact name as something to imitate.
|
|
55
55
|
*/
|
|
56
56
|
storePath?: string;
|
|
57
57
|
}
|
|
58
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
59
|
/**
|
|
70
60
|
* A process-unique suffix source for the throwaway clone's store name. The clone is memory-backed and
|
|
71
61
|
* closed in a `finally`, so a collision would only matter if two dumps overlapped — the lifecycle slot
|
|
@@ -86,7 +76,7 @@ export interface CloneDumpPhases {
|
|
|
86
76
|
checkpointStartedAtMs: number;
|
|
87
77
|
/** `CHECKPOINT` wall — flushing dirty buffers before the internal datadir dump the clone consumes. */
|
|
88
78
|
checkpointMs: number;
|
|
89
|
-
/** Offset from `startPerf` when the throwaway clone's `
|
|
79
|
+
/** Offset from `startPerf` when the throwaway clone's `pgwasm.create({ loadDataDir })` began. */
|
|
90
80
|
cloneBootStartedAtMs: number;
|
|
91
81
|
/** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
|
|
92
82
|
cloneBootMs: number;
|
|
@@ -98,7 +88,7 @@ export interface CloneDumpPhases {
|
|
|
98
88
|
|
|
99
89
|
/** The raw SQL bytes plus the pipeline phase walls — {@link runThrowawayCloneDump}'s result. */
|
|
100
90
|
export interface CloneDumpResult {
|
|
101
|
-
/** The `pg_dump` output bytes (unwrapped from
|
|
91
|
+
/** The `pg_dump` output bytes (unwrapped from the `File` `pgDump` returns). */
|
|
102
92
|
sqlBytes: Uint8Array<ArrayBuffer>;
|
|
103
93
|
/** The pipeline phase timings, all offset from the caller's `startPerf` anchor. */
|
|
104
94
|
phases: CloneDumpPhases;
|
|
@@ -107,14 +97,14 @@ export interface CloneDumpResult {
|
|
|
107
97
|
/**
|
|
108
98
|
* The throwaway-clone dump core shared by BOTH `pgDump` exports (ADR-0035 addendum): (1) a LIVE datadir dump
|
|
109
99
|
* of the running store (`compression: "none"` — the clone consumes the bytes immediately, so gzip+gunzip is
|
|
110
|
-
* pure waste); (2) a memory-backed THROWAWAY
|
|
100
|
+
* pure waste); (2) a memory-backed THROWAWAY pgwasm booted from it via `loadDataDir` — engine-less, no
|
|
111
101
|
* `live` extension, nothing `pg_dump`'s `DEALLOCATE ALL` can corrupt; (3) `pg_dump` against the throwaway
|
|
112
102
|
* with the caller's `args` (none for a diagnostic dump; the `-t` allowlist + `--no-owner` for a data
|
|
113
103
|
* export); (4) discard the clone in a `finally`. Factored out so `performDiagnosticExport` and
|
|
114
104
|
* `performDataExport` cannot drift on the clone plumbing, the memory-scheme selection, or the timing house
|
|
115
105
|
* style — the ONLY differences between the two dumps are the `pg_dump` args and the artefact assembly.
|
|
116
106
|
*
|
|
117
|
-
* `@
|
|
107
|
+
* `@pgxsinkit/pgwasm-pg-dump` is loaded ONLY via the dynamic `import()` here (ADR-0035 decision 7): its
|
|
118
108
|
* ~700 kB `pg_dump.wasm` (+ ~100 kB JS) stays off boot and off every non-exporting bundle.
|
|
119
109
|
*/
|
|
120
110
|
export interface CloneDumpOptions {
|
|
@@ -126,26 +116,26 @@ export interface CloneDumpOptions {
|
|
|
126
116
|
* triggers `pg_dump -t` would otherwise pull into the artefact (see `buildDataExportCloneCleanupSql`); a
|
|
127
117
|
* diagnostic dump passes none (it wants the store verbatim).
|
|
128
118
|
*/
|
|
129
|
-
prepareClone?: (clone:
|
|
119
|
+
prepareClone?: (clone: Pgwasm) => Promise<void>;
|
|
130
120
|
}
|
|
131
121
|
|
|
132
122
|
export async function runThrowawayCloneDump(
|
|
133
|
-
|
|
123
|
+
pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">,
|
|
134
124
|
startPerf: number,
|
|
135
125
|
options: CloneDumpOptions = {},
|
|
136
126
|
): Promise<CloneDumpResult> {
|
|
137
127
|
// Step 1 — the LIVE datadir dump the clone boots from (checkpoint → `dumpDataDir`, the shared core).
|
|
138
128
|
const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
|
|
139
|
-
|
|
129
|
+
pgwasm,
|
|
140
130
|
"none",
|
|
141
131
|
startPerf,
|
|
142
132
|
);
|
|
143
133
|
|
|
144
134
|
// Step 2 — boot the throwaway. Memory-backed via the resolution module's SCHEME selection (ADR-0036
|
|
145
|
-
// decision 5: NEVER
|
|
146
|
-
// instance silently omits post-initdb relation files). No extensions at
|
|
147
|
-
// sync runtime: the clone exists only to be read out by `pg_dump`, and
|
|
148
|
-
// here to corrupt.
|
|
135
|
+
// decision 5: NEVER pgwasm's explicit `fs: new MemoryFS()` — as probed before the pgwasm switch (ADR-0062),
|
|
136
|
+
// a `dumpDataDir` from an explicit-fs instance silently omits post-initdb relation files). No extensions at
|
|
137
|
+
// all — not even `live` — and no sync runtime: the clone exists only to be read out by `pg_dump`, and
|
|
138
|
+
// `DEALLOCATE ALL` has nothing here to corrupt.
|
|
149
139
|
const cloneDataDir = resolveStoreDataDir(nextCloneStorePath(), "memory");
|
|
150
140
|
const cloneBootStartedAtMs = nowMs() - startPerf;
|
|
151
141
|
const cloneBootStartPerf = nowMs();
|
|
@@ -153,7 +143,12 @@ export async function runThrowawayCloneDump(
|
|
|
153
143
|
// → discarded), so it has no idb flush to relax — the flag is a no-op on the memory backend and is set
|
|
154
144
|
// purely to state intent (a throwaway never needs synchronous durability) and stay correct if the clone's
|
|
155
145
|
// backend ever changes.
|
|
156
|
-
const throwaway = await
|
|
146
|
+
const throwaway = await createPgwasm({
|
|
147
|
+
build: cBuild,
|
|
148
|
+
dataDir: cloneDataDir,
|
|
149
|
+
loadDataDir: dumped,
|
|
150
|
+
relaxedDurability: true,
|
|
151
|
+
});
|
|
157
152
|
const cloneBootMs = nowMs() - cloneBootStartPerf;
|
|
158
153
|
|
|
159
154
|
let sqlBytes: Uint8Array<ArrayBuffer>;
|
|
@@ -167,12 +162,12 @@ export async function runThrowawayCloneDump(
|
|
|
167
162
|
await options.prepareClone(throwaway);
|
|
168
163
|
}
|
|
169
164
|
|
|
170
|
-
// Step 3 — the lazy `pg_dump`. The
|
|
171
|
-
//
|
|
165
|
+
// Step 3 — the lazy `pg_dump`. The dynamic `import()` keeps `@pgxsinkit/pgwasm-pg-dump` — and its WASM —
|
|
166
|
+
// off the boot bundle. The caller rebuilds the artefact `File`
|
|
172
167
|
// from the returned bytes, so `fileName` here is cosmetic only.
|
|
173
168
|
pgDumpStartedAtMs = nowMs() - startPerf;
|
|
174
169
|
const pgDumpStartPerf = nowMs();
|
|
175
|
-
const { pgDump } =
|
|
170
|
+
const { pgDump } = await import("@pgxsinkit/pgwasm-pg-dump");
|
|
176
171
|
const dumpFile = await pgDump({
|
|
177
172
|
pg: throwaway,
|
|
178
173
|
...(options.pgDumpArgs != null ? { args: options.pgDumpArgs } : {}),
|
|
@@ -216,13 +211,13 @@ export async function performDiagnosticExport(
|
|
|
216
211
|
|
|
217
212
|
// A diagnostic dump takes the WHOLE store (no `-t`): synced + overlay + journal + metadata + views +
|
|
218
213
|
// functions — everything a support engineer needs to read a misbehaving store.
|
|
219
|
-
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.
|
|
214
|
+
const { sqlBytes, phases } = await runThrowawayCloneDump(deps.pgwasm, startPerf);
|
|
220
215
|
|
|
221
216
|
const storeId = deriveStoreId(deps.storePath);
|
|
222
217
|
const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}-diagnostics.sql`;
|
|
223
|
-
// Build the artefact `File` from the raw bytes, NOT by re-wrapping
|
|
224
|
-
// in non-browser hosts
|
|
225
|
-
//
|
|
218
|
+
// Build the artefact `File` from the raw bytes, NOT by re-wrapping the `File` `pgDump` returned: a wrapped
|
|
219
|
+
// polyfilled `File` keeps its own name in non-browser hosts (the same bun quirk the store backup hit) — the
|
|
220
|
+
// bytes-first path guarantees the store-scoped name/mime stick whatever `File` the dump hands back.
|
|
226
221
|
const file = new File([sqlBytes], fileName, { type: "application/sql" });
|
|
227
222
|
|
|
228
223
|
// Snapshot diagnostics of the LIVE store (the clone is already closed) — the journal state whose rows the
|
package/src/export-store.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
// Local store export (ADR-0035). Slice 1 ships the **store backup**: a full-fidelity,
|
|
1
|
+
// Local store export (ADR-0035). Slice 1 ships the **store backup**: a full-fidelity, pgwasm-restorable
|
|
2
2
|
// tarball of the whole local store, taken LIVE (no engine suspension). It is a `CHECKPOINT` — run through
|
|
3
3
|
// the engine's normal query serialisation so it orders behind in-flight engine work — followed by
|
|
4
|
-
//
|
|
4
|
+
// pgwasm's `dumpDataDir`. Because the dump is of the datadir itself, the Mutation journal and Overlay
|
|
5
5
|
// travel INSIDE the artefact: a store backup is the lossless option, the only export an offline device
|
|
6
6
|
// with unflushed writes can take (CONTEXT.md → Store backup).
|
|
7
7
|
//
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
|
|
13
13
|
import type { MutationDiagnostics } from "@pgxsinkit/contracts";
|
|
14
14
|
|
|
15
|
-
import type {
|
|
15
|
+
import type { PgwasmClient } from "./index";
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Monotonic clock (ms) — `performance.now()` where available, else `Date.now()` (mirrors BootReport).
|
|
@@ -24,7 +24,7 @@ export const nowMs = (): number => (typeof performance !== "undefined" ? perform
|
|
|
24
24
|
/** Options for {@link SyncClient.exportStore}. */
|
|
25
25
|
export interface StoreExportOptions {
|
|
26
26
|
/**
|
|
27
|
-
* How to compress the tarball, forwarded to
|
|
27
|
+
* How to compress the tarball, forwarded to pgwasm's `dumpDataDir`. `"auto"` (the default) gzips when a
|
|
28
28
|
* `CompressionStream` is available and falls back to an uncompressed tar otherwise; `"gzip"` forces
|
|
29
29
|
* compression; `"none"` skips it. The report's `compression` records the compression that was actually
|
|
30
30
|
* applied (which, under `"auto"`, is resolved at runtime).
|
|
@@ -61,7 +61,7 @@ export interface ExportReportCommon {
|
|
|
61
61
|
}
|
|
62
62
|
|
|
63
63
|
/**
|
|
64
|
-
* A live **store backup** (ADR-0035): the whole datadir as a
|
|
64
|
+
* A live **store backup** (ADR-0035): the whole datadir as a pgwasm-restorable tarball, journal and overlay
|
|
65
65
|
* included. `checkpoint`/`dump` are the only phases — a store backup is a `CHECKPOINT` + `dumpDataDir`, no
|
|
66
66
|
* clone. Slice-1 shape, kept unchanged (the union is additive).
|
|
67
67
|
*/
|
|
@@ -88,7 +88,7 @@ export interface StoreBackupReport extends ExportReportCommon {
|
|
|
88
88
|
* A **diagnostic dump** (ADR-0035, via the throwaway clone of the addendum): human-readable SQL of
|
|
89
89
|
* EVERYTHING the store holds — synced tables, the `_overlay`/`_mutations` journal, the `pgxsinkit` metadata
|
|
90
90
|
* schema, the read-model views, and the reconcile functions/triggers. It is a live datadir dump (checkpoint
|
|
91
|
-
* + `dumpDataDir`) fed into a memory-backed throwaway
|
|
91
|
+
* + `dumpDataDir`) fed into a memory-backed throwaway pgwasm via `loadDataDir`, against which `pg_dump` runs
|
|
92
92
|
* — so the live engine is never touched (the addendum's whole point). Its phases add the clone boot and the
|
|
93
93
|
* `pg_dump` walls to the shared checkpoint/dump pair.
|
|
94
94
|
*/
|
|
@@ -105,7 +105,7 @@ export interface DiagnosticDumpReport extends ExportReportCommon {
|
|
|
105
105
|
dumpStartedAtMs: number;
|
|
106
106
|
/** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
|
|
107
107
|
dumpMs: number;
|
|
108
|
-
/** Offset from export start when the throwaway clone's `
|
|
108
|
+
/** Offset from export start when the throwaway clone's `pgwasm.create({ loadDataDir })` began. */
|
|
109
109
|
cloneBootStartedAtMs: number;
|
|
110
110
|
/** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
|
|
111
111
|
cloneBootMs: number;
|
|
@@ -154,7 +154,7 @@ export interface DataExportReport extends ExportReportCommon {
|
|
|
154
154
|
dumpStartedAtMs: number;
|
|
155
155
|
/** `dumpDataDir` wall — the uncompressed internal tarball the throwaway clone boots from (`compression: "none"`). */
|
|
156
156
|
dumpMs: number;
|
|
157
|
-
/** Offset from export start when the throwaway clone's `
|
|
157
|
+
/** Offset from export start when the throwaway clone's `pgwasm.create({ loadDataDir })` began. */
|
|
158
158
|
cloneBootStartedAtMs: number;
|
|
159
159
|
/** Clone boot wall — booting the memory-backed throwaway from the internal dump. */
|
|
160
160
|
cloneBootMs: number;
|
|
@@ -175,7 +175,7 @@ export type ExportReport = StoreBackupReport | DiagnosticDumpReport | DataExport
|
|
|
175
175
|
|
|
176
176
|
/** The artefact + its report — the resolved value of {@link SyncClient.exportStore}. */
|
|
177
177
|
export interface StoreExportResult {
|
|
178
|
-
/** The store-backup tarball as a named `File`, restorable by
|
|
178
|
+
/** The store-backup tarball as a named `File`, restorable by pgwasm via `loadDataDir`. */
|
|
179
179
|
file: File;
|
|
180
180
|
/** The structured record of the export (ADR-0035). */
|
|
181
181
|
report: StoreBackupReport;
|
|
@@ -183,7 +183,7 @@ export interface StoreExportResult {
|
|
|
183
183
|
|
|
184
184
|
/**
|
|
185
185
|
* Reduce a plain store PATH (ADR-0036) to a filesystem-safe token for the backup file name. Takes the
|
|
186
|
-
* path's LAST segment (as
|
|
186
|
+
* path's LAST segment (as pgwasm's own `dumpDataDir` does when it names the inner db), then keeps only
|
|
187
187
|
* `[A-Za-z0-9._-]`. No scheme stripping — the store path is a plain name, never a storage URL. Falls back
|
|
188
188
|
* to a fixed token for an empty path so the name is always well formed.
|
|
189
189
|
*/
|
|
@@ -209,16 +209,16 @@ export const compactTimestamp = (): string => new Date().toISOString().replace(/
|
|
|
209
209
|
* (the caller's export-start monotonic anchor) so the timings compose into either report.
|
|
210
210
|
*
|
|
211
211
|
* The `CHECKPOINT` is a utility statement — Drizzle has no builder for it, so a raw `exec` is the justified
|
|
212
|
-
* tier-③ form here. Running it via `
|
|
212
|
+
* tier-③ form here. Running it via `pgwasm.exec` serialises it behind any in-flight engine work on pgwasm's
|
|
213
213
|
* single connection, flushing dirty buffers to the datadir the dump then reads — so the tarball reflects
|
|
214
214
|
* committed state, not a torn mid-write datadir.
|
|
215
215
|
*/
|
|
216
216
|
export async function performDatadirDump(
|
|
217
|
-
|
|
217
|
+
pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">,
|
|
218
218
|
compression: "auto" | "gzip" | "none",
|
|
219
219
|
startPerf: number,
|
|
220
220
|
): Promise<{
|
|
221
|
-
dumped: Awaited<ReturnType<
|
|
221
|
+
dumped: Awaited<ReturnType<PgwasmClient["dumpDataDir"]>>;
|
|
222
222
|
checkpointStartedAtMs: number;
|
|
223
223
|
checkpointMs: number;
|
|
224
224
|
dumpStartedAtMs: number;
|
|
@@ -226,12 +226,12 @@ export async function performDatadirDump(
|
|
|
226
226
|
}> {
|
|
227
227
|
const checkpointStartedAtMs = nowMs() - startPerf;
|
|
228
228
|
const checkpointStartPerf = nowMs();
|
|
229
|
-
await
|
|
229
|
+
await pgwasm.exec("CHECKPOINT");
|
|
230
230
|
const checkpointMs = nowMs() - checkpointStartPerf;
|
|
231
231
|
|
|
232
232
|
const dumpStartedAtMs = nowMs() - startPerf;
|
|
233
233
|
const dumpStartPerf = nowMs();
|
|
234
|
-
const dumped = await
|
|
234
|
+
const dumped = await pgwasm.dumpDataDir(compression);
|
|
235
235
|
const dumpMs = nowMs() - dumpStartPerf;
|
|
236
236
|
|
|
237
237
|
return { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs };
|
|
@@ -240,12 +240,12 @@ export async function performDatadirDump(
|
|
|
240
240
|
/** The dependencies {@link performStoreExport} needs from the owning client — narrow, so it is unit-testable. */
|
|
241
241
|
export interface StoreExportDeps {
|
|
242
242
|
/** The live store to checkpoint and dump. */
|
|
243
|
-
|
|
243
|
+
pgwasm: Pick<PgwasmClient, "exec" | "dumpDataDir">;
|
|
244
244
|
/** The Mutation diagnostics seam (`client.diagnostics().mutation` / `readMutationStats`). */
|
|
245
245
|
readMutationStats: () => Promise<MutationDiagnostics>;
|
|
246
246
|
/**
|
|
247
247
|
* The store's configured plain store PATH (ADR-0036) — reduced to the `storeId` in the default backup
|
|
248
|
-
* file name (`deriveStoreId`). The resolved
|
|
248
|
+
* file name (`deriveStoreId`). The resolved pgwasm dataDir URL is deliberately NOT used here: it is
|
|
249
249
|
* internal plumbing and must not leak into an artefact name as something to imitate.
|
|
250
250
|
*/
|
|
251
251
|
storePath?: string;
|
|
@@ -268,12 +268,12 @@ export async function performStoreExport(
|
|
|
268
268
|
// Live dump of the whole datadir (checkpoint → `dumpDataDir`, the shared core) — the journal and overlay
|
|
269
269
|
// ride inside it (the lossless backup, ADR-0035).
|
|
270
270
|
const { dumped, checkpointStartedAtMs, checkpointMs, dumpStartedAtMs, dumpMs } = await performDatadirDump(
|
|
271
|
-
deps.
|
|
271
|
+
deps.pgwasm,
|
|
272
272
|
compression,
|
|
273
273
|
startPerf,
|
|
274
274
|
);
|
|
275
275
|
|
|
276
|
-
//
|
|
276
|
+
// pgwasm names its dump `<db>.tar.gz` (type `application/x-gzip`) when it compressed, `<db>.tar`
|
|
277
277
|
// (`application/x-tar`) otherwise — so the RESULT, not the requested option, tells us what `"auto"`
|
|
278
278
|
// resolved to. Detect from whichever of name/type the runtime populated (its `File` is a polyfill in
|
|
279
279
|
// non-browser hosts, so trust both).
|
|
@@ -284,7 +284,7 @@ export async function performStoreExport(
|
|
|
284
284
|
const mimeType = gzipped ? "application/x-gzip" : "application/x-tar";
|
|
285
285
|
const storeId = deriveStoreId(deps.storePath);
|
|
286
286
|
const fileName = options.fileName ?? `${storeId}-${compactTimestamp()}${extension}`;
|
|
287
|
-
// Build the artefact `File` from the raw bytes, NOT by re-wrapping `dumped`:
|
|
287
|
+
// Build the artefact `File` from the raw bytes, NOT by re-wrapping `dumped`: pgwasm's dump is a File
|
|
288
288
|
// polyfill in non-browser hosts, and `new File([polyfillFile], name)` keeps the polyfill's own name
|
|
289
289
|
// rather than the one we pass. Extracting the bytes first guarantees the store-scoped name sticks.
|
|
290
290
|
const bytes = new Uint8Array(await dumped.arrayBuffer());
|