@pgxsinkit/pgwasm-pg-dump 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.ts ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * The database's own session, before and after pg_dump runs on it.
3
+ *
4
+ * pg_dump expects a connection of its own and leaves the session in a state a real disconnect would
5
+ * discard: its read-only transaction open (it never commits; ending the connection ends it), its
6
+ * prepared statements, and every setting it changed (`search_path`, `row_security`,
7
+ * `restrict_nonsystem_relation_kind`, `extra_float_digits`, the timeouts, …). Here the session is the
8
+ * database's, so each of those is undone explicitly, and nothing of the database's own is touched.
9
+ * Every exchange runs over `/protocol` inside the exclusive session pgDump holds, without persisting
10
+ * (nothing here writes data).
11
+ */
12
+
13
+ import { PgwasmClosedError, PgwasmFailedError } from "@pgxsinkit/pgwasm";
14
+ import { messages, serialize, type BackendMessage, type PgwasmProtocol } from "@pgxsinkit/pgwasm/protocol";
15
+
16
+ import { PgDumpSessionError } from "./errors";
17
+
18
+ /**
19
+ * Every setting a session can change for itself, and the role (`SET ROLE`, which `pg_settings` does not
20
+ * list). The three transaction-scoped settings end with the transaction.
21
+ */
22
+ const SETTINGS_QUERY = `SELECT name, pg_catalog.current_setting(name) FROM pg_catalog.pg_settings
23
+ WHERE context IN ('user', 'superuser')
24
+ AND name NOT IN ('transaction_isolation', 'transaction_read_only', 'transaction_deferrable')
25
+ UNION ALL SELECT 'role', pg_catalog.current_setting('role')`;
26
+
27
+ const PREPARED_STATEMENTS_QUERY = "SELECT name FROM pg_catalog.pg_prepared_statements";
28
+
29
+ const SET_CONFIG = "SELECT pg_catalog.set_config($1, $2, false)";
30
+
31
+ /** What of the session pg_dump can change: its settings, by name, and its prepared statements. */
32
+ export interface SessionState {
33
+ readonly settings: ReadonlyMap<string, string>;
34
+ readonly preparedStatements: ReadonlySet<string>;
35
+ }
36
+
37
+ async function exchange(wire: PgwasmProtocol, message: Uint8Array): Promise<BackendMessage[]> {
38
+ return (await wire.execProtocol(message, { persist: false })).messages;
39
+ }
40
+
41
+ function concat(parts: readonly Uint8Array[]): Uint8Array {
42
+ const out = new Uint8Array(parts.reduce((sum, part) => sum + part.byteLength, 0));
43
+ let offset = 0;
44
+ for (const part of parts) {
45
+ out.set(part, offset);
46
+ offset += part.byteLength;
47
+ }
48
+ return out;
49
+ }
50
+
51
+ /**
52
+ * The transaction status: `I` idle, `T` in a transaction block, `E` in a failed one. A lone Sync runs
53
+ * nothing: the backend only answers it with ReadyForQuery (and ends an extended-query cycle a failed
54
+ * client left without its Sync).
55
+ */
56
+ export async function transactionStatus(wire: PgwasmProtocol): Promise<string> {
57
+ const replies = await exchange(wire, serialize.sync());
58
+ const ready = replies.findLast((reply) => reply instanceof messages.ReadyForQueryMessage);
59
+ if (!(ready instanceof messages.ReadyForQueryMessage)) {
60
+ throw new Error("the database answered a Sync without ReadyForQuery");
61
+ }
62
+ return ready.status;
63
+ }
64
+
65
+ /** Each data row's text fields. */
66
+ async function rows(wire: PgwasmProtocol, sql: string): Promise<(string | null)[][]> {
67
+ return (await exchange(wire, serialize.query(sql)))
68
+ .filter((reply) => reply instanceof messages.DataRowMessage)
69
+ .map((row) => row.fields);
70
+ }
71
+
72
+ async function readSettings(wire: PgwasmProtocol): Promise<Map<string, string>> {
73
+ const settings = new Map<string, string>();
74
+ for (const [name, value] of await rows(wire, SETTINGS_QUERY)) {
75
+ if (typeof name === "string" && typeof value === "string") settings.set(name, value);
76
+ }
77
+ return settings;
78
+ }
79
+
80
+ async function readPreparedStatements(wire: PgwasmProtocol): Promise<Set<string>> {
81
+ return new Set((await rows(wire, PREPARED_STATEMENTS_QUERY)).flatMap(([name]) => (name == null ? [] : [name])));
82
+ }
83
+
84
+ /** The session's settings and prepared statements. */
85
+ export async function readSession(wire: PgwasmProtocol): Promise<SessionState> {
86
+ return { settings: await readSettings(wire), preparedStatements: await readPreparedStatements(wire) };
87
+ }
88
+
89
+ function differing(before: ReadonlyMap<string, string>, now: ReadonlyMap<string, string>): string[] {
90
+ return [...before].filter(([name, value]) => now.get(name) !== value).map(([name]) => name);
91
+ }
92
+
93
+ const quoteIdentifier = (name: string) => `"${name.replaceAll('"', '""')}"`;
94
+
95
+ /**
96
+ * Put the session back as it was before pg_dump: end the transaction it left open, deallocate the
97
+ * statements it prepared, and restore every setting it changed (the role last, undoing pg_dump's own
98
+ * order). Every step is attempted even when an earlier one fails. Whatever still differs afterwards (the
99
+ * transaction, a statement of pg_dump's, a setting) is a {@link PgDumpSessionError} naming all of it,
100
+ * whose cause is what failed on the way. A failed or closed database fails every exchange: its error is
101
+ * thrown as it is.
102
+ */
103
+ export async function restoreSession(wire: PgwasmProtocol, before: SessionState): Promise<void> {
104
+ const failures: unknown[] = [];
105
+ const attempt = async <T>(step: () => Promise<T>): Promise<T | undefined> => {
106
+ try {
107
+ return await step();
108
+ } catch (error) {
109
+ if (error instanceof PgwasmFailedError || error instanceof PgwasmClosedError) throw error;
110
+ failures.push(error);
111
+ return undefined;
112
+ }
113
+ };
114
+ const ownStatements = (names: ReadonlySet<string>) =>
115
+ [...names].filter((name) => !before.preparedStatements.has(name));
116
+
117
+ // pg_dump never ends its read-only transaction (a disconnect would); nothing it did needs keeping.
118
+ await attempt(async () => {
119
+ if ((await transactionStatus(wire)) !== "I") await exchange(wire, serialize.query("ROLLBACK"));
120
+ });
121
+ // A disconnect would drop pg_dump's prepared statements; the database's own (a live query's) stay.
122
+ for (const name of ownStatements((await attempt(() => readPreparedStatements(wire))) ?? new Set())) {
123
+ await attempt(() => exchange(wire, serialize.query(`DEALLOCATE ${quoteIdentifier(name)}`)));
124
+ }
125
+ const settings = await attempt(() => readSettings(wire));
126
+ const changed = (settings === undefined ? [] : differing(before.settings, settings)).sort((a, b) =>
127
+ a === "role" ? 1 : b === "role" ? -1 : a.localeCompare(b),
128
+ );
129
+ for (const name of changed) {
130
+ const value = before.settings.get(name) ?? "";
131
+ await attempt(() =>
132
+ exchange(
133
+ wire,
134
+ concat([
135
+ serialize.parse({ text: SET_CONFIG }),
136
+ serialize.bind({ values: [name, value] }),
137
+ serialize.execute({}),
138
+ serialize.sync(),
139
+ ]),
140
+ ),
141
+ );
142
+ }
143
+
144
+ // What is left of pg_dump's, each checked on its own.
145
+ const left: string[] = [];
146
+ const status = await attempt(() => transactionStatus(wire));
147
+ if (status !== "I") {
148
+ left.push(
149
+ status === undefined ? "the transaction status could not be read" : "pg_dump's transaction is still open",
150
+ );
151
+ }
152
+ const statements = await attempt(() => readPreparedStatements(wire));
153
+ const remaining = statements === undefined ? undefined : ownStatements(statements);
154
+ if (remaining === undefined) left.push("the prepared statements could not be read");
155
+ else if (remaining.length > 0) left.push(`statements it prepared: ${remaining.join(", ")}`);
156
+ const settingsAfter = await attempt(() => readSettings(wire));
157
+ const unrestored = settingsAfter === undefined ? [] : differing(before.settings, settingsAfter);
158
+ if (settingsAfter === undefined) {
159
+ left.push("the settings could not be read");
160
+ } else if (unrestored.length > 0) {
161
+ left.push(`settings it changed, which keep pg_dump's values: ${unrestored.join(", ")}`);
162
+ }
163
+
164
+ if (left.length > 0) {
165
+ throw new PgDumpSessionError(
166
+ `The database's session could not be fully restored after pg_dump: ${left.join("; ")}.`,
167
+ unrestored,
168
+ failures.length === 0
169
+ ? undefined
170
+ : { cause: failures.length === 1 ? failures[0] : new AggregateError(failures, "restoring the session failed") },
171
+ );
172
+ }
173
+ }
package/src/wasm.ts ADDED
@@ -0,0 +1,34 @@
1
+ // Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
2
+ // — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
3
+
4
+ /**
5
+ * pg_dump's WebAssembly module, fetched and compiled once per URL. One path for Bun and browsers: Bun's
6
+ * `fetch` reads `file://` URLs and serves `.wasm` as `application/wasm`.
7
+ */
8
+
9
+ const compiled = new Map<string, Promise<WebAssembly.Module>>();
10
+
11
+ export function compileModule(url: URL): Promise<WebAssembly.Module> {
12
+ const key = url.href;
13
+ let pending = compiled.get(key);
14
+ if (pending === undefined) {
15
+ pending = (async () => {
16
+ const response = await fetch(url);
17
+ if (!response.ok) throw new Error(`Could not load ${key}: HTTP ${response.status} ${response.statusText}`);
18
+ try {
19
+ // Bun's Response and the WebAssembly typings' Response are distinct declarations of one type.
20
+ return await WebAssembly.compileStreaming(
21
+ response.clone() as unknown as Parameters<typeof WebAssembly.compileStreaming>[0],
22
+ );
23
+ } catch (error) {
24
+ // A server that sends the wrong MIME type defeats streaming compilation; compile the bytes.
25
+ if (error instanceof TypeError) return await WebAssembly.compile(await response.arrayBuffer());
26
+ throw error;
27
+ }
28
+ })();
29
+ compiled.set(key, pending);
30
+ // A failed download or compile is retried on the next dump rather than cached.
31
+ pending.catch(() => compiled.delete(key));
32
+ }
33
+ return pending;
34
+ }