@pgxsinkit/pgwasm-c 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.
Files changed (85) hide show
  1. package/LICENSE +23 -0
  2. package/NOTICE +1890 -0
  3. package/README.md +79 -0
  4. package/artefacts/amcheck.tar.gz +0 -0
  5. package/artefacts/initdb.d.ts +6 -0
  6. package/artefacts/initdb.js +2 -0
  7. package/artefacts/initdb.wasm +0 -0
  8. package/artefacts/postgres.d.ts +6 -0
  9. package/artefacts/postgres.data +37595 -8
  10. package/artefacts/postgres.js +2 -0
  11. package/artefacts/postgres.wasm +0 -0
  12. package/artefacts/prepopulated.tar.gz +0 -0
  13. package/dist/artefact-pins.d.ts +57 -0
  14. package/dist/artefact-pins.d.ts.map +1 -0
  15. package/dist/artefacts.d.ts +37 -0
  16. package/dist/artefacts.d.ts.map +1 -0
  17. package/dist/build.d.ts +53 -0
  18. package/dist/build.d.ts.map +1 -0
  19. package/dist/contrib/amcheck.d.ts +9 -0
  20. package/dist/contrib/amcheck.d.ts.map +1 -0
  21. package/dist/contrib/amcheck.js +13 -0
  22. package/dist/contrib/amcheck.js.map +10 -0
  23. package/dist/host/artefact-loader.d.ts +9 -0
  24. package/dist/host/artefact-loader.d.ts.map +1 -0
  25. package/dist/host/command-line.d.ts +11 -0
  26. package/dist/host/command-line.d.ts.map +1 -0
  27. package/dist/host/data-dir.d.ts +11 -0
  28. package/dist/host/data-dir.d.ts.map +1 -0
  29. package/dist/host/emscripten.d.ts +143 -0
  30. package/dist/host/emscripten.d.ts.map +1 -0
  31. package/dist/host/exit-code.d.ts +12 -0
  32. package/dist/host/exit-code.d.ts.map +1 -0
  33. package/dist/host/extensions.d.ts +15 -0
  34. package/dist/host/extensions.d.ts.map +1 -0
  35. package/dist/host/initdb.d.ts +25 -0
  36. package/dist/host/initdb.d.ts.map +1 -0
  37. package/dist/host/mounts/file.d.ts +17 -0
  38. package/dist/host/mounts/file.d.ts.map +1 -0
  39. package/dist/host/mounts/idb.d.ts +32 -0
  40. package/dist/host/mounts/idb.d.ts.map +1 -0
  41. package/dist/host/mounts/index.d.ts +6 -0
  42. package/dist/host/mounts/index.d.ts.map +1 -0
  43. package/dist/host/mounts/memory.d.ts +12 -0
  44. package/dist/host/mounts/memory.d.ts.map +1 -0
  45. package/dist/host/mounts/storage-mount.d.ts +15 -0
  46. package/dist/host/mounts/storage-mount.d.ts.map +1 -0
  47. package/dist/host/mounts/vfs.d.ts +15 -0
  48. package/dist/host/mounts/vfs.d.ts.map +1 -0
  49. package/dist/host/paths.d.ts +10 -0
  50. package/dist/host/paths.d.ts.map +1 -0
  51. package/dist/host/postgres-instance.d.ts +63 -0
  52. package/dist/host/postgres-instance.d.ts.map +1 -0
  53. package/dist/host/vfs-mount.d.ts +10 -0
  54. package/dist/host/vfs-mount.d.ts.map +1 -0
  55. package/dist/index.d.ts +4 -0
  56. package/dist/index.d.ts.map +1 -0
  57. package/dist/index.js +1393 -0
  58. package/dist/index.js.map +26 -0
  59. package/dist/prepopulated.d.ts +28 -0
  60. package/dist/prepopulated.d.ts.map +1 -0
  61. package/dist/prepopulated.js +15 -0
  62. package/dist/prepopulated.js.map +10 -0
  63. package/package.json +56 -0
  64. package/src/artefact-pins.ts +36 -0
  65. package/src/artefacts.ts +46 -0
  66. package/src/build.ts +326 -0
  67. package/src/contrib/amcheck.ts +17 -0
  68. package/src/host/artefact-loader.ts +75 -0
  69. package/src/host/command-line.ts +64 -0
  70. package/src/host/data-dir.ts +70 -0
  71. package/src/host/emscripten.ts +158 -0
  72. package/src/host/exit-code.ts +29 -0
  73. package/src/host/extensions.ts +83 -0
  74. package/src/host/initdb.ts +180 -0
  75. package/src/host/mounts/file.ts +44 -0
  76. package/src/host/mounts/idb.ts +152 -0
  77. package/src/host/mounts/index.ts +26 -0
  78. package/src/host/mounts/memory.ts +22 -0
  79. package/src/host/mounts/storage-mount.ts +15 -0
  80. package/src/host/mounts/vfs.ts +43 -0
  81. package/src/host/paths.ts +18 -0
  82. package/src/host/postgres-instance.ts +495 -0
  83. package/src/host/vfs-mount.ts +258 -0
  84. package/src/index.ts +3 -0
  85. package/src/prepopulated.ts +38 -0
@@ -0,0 +1,22 @@
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
+ import type { PostgresModule } from "../emscripten";
5
+ import type { StorageMount } from "./storage-mount";
6
+
7
+ /** The data directory in the module's own memory (MEMFS): gone when the database closes. */
8
+ export class MemoryMount implements StorageMount {
9
+ readonly preRun = undefined;
10
+
11
+ async acquire(): Promise<void> {}
12
+
13
+ async initialSync(): Promise<void> {}
14
+
15
+ async persist(): Promise<void> {}
16
+
17
+ async close(module: PostgresModule | undefined): Promise<void> {
18
+ module?.FS.quit();
19
+ }
20
+
21
+ async cleanupFailedInit(): Promise<void> {}
22
+ }
@@ -0,0 +1,15 @@
1
+ import type { PostgresModule } from "../emscripten";
2
+
3
+ /**
4
+ * How the C build mounts one kind of storage over the data directory. The lifecycle follows the boot:
5
+ * `acquire` before the module exists, `preRun` inside its instantiation, `initialSync` once mounted,
6
+ * `persist` after statements, then `close` (a normal close) or `cleanupFailedInit` (a failed boot).
7
+ */
8
+ export interface StorageMount {
9
+ acquire(): Promise<void>;
10
+ readonly preRun: ((module: PostgresModule) => void) | undefined;
11
+ initialSync(module: PostgresModule): Promise<void>;
12
+ persist(module: PostgresModule, relaxed: boolean): Promise<void>;
13
+ close(module: PostgresModule | undefined): Promise<void>;
14
+ cleanupFailedInit(module: PostgresModule | undefined): Promise<void>;
15
+ }
@@ -0,0 +1,43 @@
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
+ import type { BaseFilesystem } from "@pgxsinkit/pgwasm/fs";
5
+
6
+ import type { PostgresModule } from "../emscripten";
7
+ import { PGDATA } from "../paths";
8
+ import { createVfsFilesystem } from "../vfs-mount";
9
+ import type { StorageMount } from "./storage-mount";
10
+
11
+ /** The data directory on a pgwasm filesystem (`createPgwasm({ fs })`), mounted through an adapter. */
12
+ export class VfsMount implements StorageMount {
13
+ readonly #vfs: BaseFilesystem;
14
+
15
+ constructor(vfs: BaseFilesystem) {
16
+ this.#vfs = vfs;
17
+ }
18
+
19
+ async acquire(): Promise<void> {}
20
+
21
+ get preRun(): (module: PostgresModule) => void {
22
+ return (module) => {
23
+ module.FS.mkdir(PGDATA);
24
+ module.FS.mount(createVfsFilesystem(module, this.#vfs), {}, PGDATA);
25
+ };
26
+ }
27
+
28
+ async initialSync(): Promise<void> {
29
+ await this.#vfs.initialSyncFs();
30
+ }
31
+
32
+ async persist(_module: PostgresModule, relaxed: boolean): Promise<void> {
33
+ await this.#vfs.syncToFs(relaxed);
34
+ }
35
+
36
+ async close(): Promise<void> {
37
+ await this.#vfs.closeFs();
38
+ }
39
+
40
+ async cleanupFailedInit(): Promise<void> {
41
+ await this.#vfs.cleanupFailedInit();
42
+ }
43
+ }
@@ -0,0 +1,18 @@
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
+ // The C build's filesystem layout. The root is a fact of the compiled artefacts, not a choice: the wasm
5
+ // and its filesystem bundle hardcode `/pgwasm` as the filesystem root and install prefix (bin/, share/,
6
+ // lib/, icu/) since pgwasm-postgres 18.6.2, so PG_ROOT must match the release it runs. An IndexedDB
7
+ // store's database is named after its mount point `/pgwasm/<name>` (see mounts/idb.ts), so the root is
8
+ // also part of every IndexedDB store's identity: changing it leaves the stores under the old root behind.
9
+
10
+ export const PG_ROOT = "/pgwasm";
11
+ export const PGDATA = `${PG_ROOT}/data`;
12
+ export const ICU_DATA_PATH = `${PG_ROOT}/icu`;
13
+ export const INITDB_EXE_PATH = `${PG_ROOT}/bin/initdb`;
14
+ export const POSTGRES_EXE_PATH = `${PG_ROOT}/bin/postgres`;
15
+ export const PG_STDOUT_PATH = `${PG_ROOT}/pgstdout`;
16
+ export const PG_STDIN_PATH = `${PG_ROOT}/pgstdin`;
17
+ /** The file `locale -a` output is served from. */
18
+ export const LOCALE_LIST_PATH = `${PG_ROOT}/locale-a`;
@@ -0,0 +1,495 @@
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
+ import type { DebugLevel } from "@pgxsinkit/pgwasm/build";
5
+
6
+ import type { CBuildArtefactSet } from "../artefacts";
7
+ import type { EmscriptenStream, ModuleOverrides, PostgresModule } from "./emscripten";
8
+ import { preservingExitCode } from "./exit-code";
9
+ import { ICU_DATA_PATH, INITDB_EXE_PATH, LOCALE_LIST_PATH, PGDATA, POSTGRES_EXE_PATH } from "./paths";
10
+
11
+ /** Postgres' error longjmp, intercepted by the host: keep in sync with pglitec.c's POSTGRES_MAIN_LONGJMP. */
12
+ const POSTGRES_MAIN_LONGJMP = 100;
13
+ /** The exit status single-user mode reports when it started and stays alive. */
14
+ const PGLITE_EXIT_ALIVE = 99;
15
+ const INITIAL_MEMORY_PAGES = 2048;
16
+ const MAXIMUM_MEMORY_PAGES = 32768;
17
+
18
+ /** The single-user-mode arguments every start begins with. */
19
+ export const DEFAULT_START_PARAMS: readonly string[] = [
20
+ "--single", // single-user mode (must come first)
21
+ "-F", // fsync off: the host persists storage itself
22
+ "-O", // allow system table structure changes
23
+ "-j", // no newline as the interactive query delimiter
24
+ "-c",
25
+ "search_path=public",
26
+ "-c",
27
+ "exit_on_error=false",
28
+ "-c",
29
+ "log_checkpoints=false",
30
+ "-c",
31
+ "max_worker_processes=0",
32
+ "-c",
33
+ "max_parallel_workers=0",
34
+ "-c",
35
+ "max_parallel_workers_per_gather=0",
36
+ "-c",
37
+ "io_method=sync",
38
+ "-c",
39
+ "max_parallel_maintenance_workers=0",
40
+ ];
41
+
42
+ /**
43
+ * Whether `error` is one of the exceptions the Emscripten runtime throws on purpose to unwind the wasm
44
+ * stack back to the main loop, which handles them:
45
+ * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgl_longjmp (pglitec.c) delivers Postgres'
46
+ * siglongjmp to its main-loop error handler, and how a Terminate message ends the loop;
47
+ * - what an emscripten-mode longjmp throws, should one pass every invoke_* frame: an instance of the
48
+ * glue's (unexported) `EmscriptenSjLj` class on Emscripten 6.0.10 (pgwasm-postgres 18.6.1 onwards), a
49
+ * number on Emscripten 3.1.74 (18.3.0 and 18.6.0). Both are recognised, so the host works with either.
50
+ *
51
+ * An `ExitStatus` (from exit()/proc_exit(): a FATAL error) is not: the backend's exit callbacks have
52
+ * already torn its session down, so the loop cannot resume on it (see {@link exitStatusOf}).
53
+ */
54
+ export function isEmscriptenUnwind(error: unknown): boolean {
55
+ if (error === "unwind" || typeof error === "number") return true;
56
+ if (typeof error !== "object" || error === null) return false;
57
+ return (error as { constructor?: { name?: unknown } }).constructor?.name === "EmscriptenSjLj";
58
+ }
59
+
60
+ const invalidBundleSize = (actual: number, expected: number): Error =>
61
+ new Error(`Invalid filesystem bundle size: ${actual} !== ${expected}`);
62
+
63
+ /** The status of the `ExitStatus` the runtime throws from exit()/proc_exit(), or undefined for anything else. */
64
+ export function exitStatusOf(error: unknown): number | undefined {
65
+ if (typeof error !== "object" || error === null || (error as { name?: unknown }).name !== "ExitStatus") {
66
+ return undefined;
67
+ }
68
+ const status = (error as { status?: unknown }).status;
69
+ return typeof status === "number" ? status : -1;
70
+ }
71
+
72
+ /**
73
+ * The wasm's shadow stack pointer: the C stack in linear memory, which the glue exports neither
74
+ * `stackSave` nor `stackRestore` for. A throw that unwinds wasm frames (an ERROR's intercepted
75
+ * siglongjmp, a FATAL's exit) skips their epilogues, so the pointer stays where the deepest of them left
76
+ * it. Unrestored, every ERROR leaked that much stack (about 1.2 kB for `SELECT 1/0`), until
77
+ * `max_stack_depth` refused every statement (from about the 1,700th error in one instance). The host
78
+ * restores it to where the call started, as Postgres' own siglongjmp to PostgresMain would.
79
+ */
80
+ interface ShadowStack {
81
+ save(): number;
82
+ restore(pointer: number): void;
83
+ }
84
+
85
+ function shadowStackOf(instance: WebAssembly.Instance): ShadowStack {
86
+ const current = instance.exports["emscripten_stack_get_current"];
87
+ const restore = instance.exports["_emscripten_stack_restore"];
88
+ if (typeof current !== "function" || typeof restore !== "function") {
89
+ throw new Error(
90
+ "The Postgres module exports no emscripten_stack_get_current or _emscripten_stack_restore: the host cannot restore its stack after an error",
91
+ );
92
+ }
93
+ return {
94
+ save: () => (current as () => number)(),
95
+ restore: (pointer) => (restore as (pointer: number) => void)(pointer),
96
+ };
97
+ }
98
+
99
+ export interface PostgresInstanceConfig {
100
+ /** The Postgres glue (`postgres.js`) and the size of the filesystem bundle it was packaged with. */
101
+ readonly glue: Pick<CBuildArtefactSet, "createPostgresModule" | "fsBundleBytes">;
102
+ readonly wasmModule: Promise<WebAssembly.Module>;
103
+ /** The filesystem bundle, a copy of its own for this instance. */
104
+ readonly fsBundle: Promise<ArrayBuffer>;
105
+ readonly user: string;
106
+ readonly database: string;
107
+ readonly debug: DebugLevel;
108
+ /** preRun steps that mount storage over the data directory; run after the filesystem bundle loads. */
109
+ readonly mountPreRun?: (module: PostgresModule) => void;
110
+ /** @internal A test's view of the module. */
111
+ readonly onModule?: (module: PostgresModule) => void;
112
+ }
113
+
114
+ /**
115
+ * One Emscripten instance of the Postgres module and the host state around it: the socket callbacks
116
+ * the wire goes through, the `/dev/blob` device, and the external-command hooks.
117
+ */
118
+ export class PostgresInstance {
119
+ readonly module: PostgresModule;
120
+ readonly #debug: DebugLevel;
121
+ readonly #stack: ShadowStack;
122
+ // Frontend bytes being fed to Postgres, and how far it has read them.
123
+ #input: Uint8Array = new Uint8Array(0);
124
+ #readOffset = 0;
125
+ // Where backend bytes go during an exchange.
126
+ #sink: ((chunk: Uint8Array) => void) | undefined;
127
+ #blobReadSource: Uint8Array | undefined;
128
+ #blobWritten: Uint8Array<ArrayBuffer>[] | undefined;
129
+ #externalCommandStream: number | null = null;
130
+ #functionPointers: number[] = [];
131
+ #failed = false;
132
+ #exited = false;
133
+ // The last lines Postgres wrote to stderr (since the exchange began, during one), for the error when it
134
+ // fails to start or exits.
135
+ readonly #stderr: string[] = [];
136
+
137
+ private constructor(module: PostgresModule, debug: DebugLevel, stack: ShadowStack) {
138
+ this.module = module;
139
+ this.#debug = debug;
140
+ this.#stack = stack;
141
+ }
142
+
143
+ static async create(config: PostgresInstanceConfig): Promise<PostgresInstance> {
144
+ const [wasmModule, fsBundle] = await Promise.all([config.wasmModule, config.fsBundle]);
145
+ // Checked before the glue runs. Emscripten 6's file packager (pgwasm-postgres 18.6.1 onwards) loads the
146
+ // bundle in an async function it never awaits, so a throw from getPreloadedPackage no longer rejects the
147
+ // factory: it is an unhandled rejection, and the boot fails later on a missing bundle file with an
148
+ // unrelated filesystem error.
149
+ const { createPostgresModule, fsBundleBytes } = config.glue;
150
+ if (fsBundle.byteLength !== fsBundleBytes) throw invalidBundleSize(fsBundle.byteLength, fsBundleBytes);
151
+ let host: PostgresInstance | undefined;
152
+ let stack: ShadowStack | undefined;
153
+ const pendingHost = (module: PostgresModule): PostgresInstance => {
154
+ // The runtime runs no preRun step before the instance it waits on (instantiateWasm) is ready.
155
+ if (stack === undefined) throw new Error("The Postgres module initialised before its wasm instance");
156
+ host ??= new PostgresInstance(module, config.debug, stack);
157
+ return host;
158
+ };
159
+ let rejectInstantiation: (error: unknown) => void = () => undefined;
160
+ const instantiationFailed = new Promise<never>((_, reject) => {
161
+ rejectInstantiation = reject;
162
+ });
163
+
164
+ const log = (text: string) => {
165
+ if (config.debug > 0) console.debug(text);
166
+ };
167
+ const logError = (text: string) => {
168
+ if (host) host.#recordStderr(text);
169
+ if (config.debug > 0) console.error(text);
170
+ };
171
+
172
+ // Emscripten runs preRun callbacks in the order listed (3.1.74, before pgwasm-postgres 18.6.1, ran them
173
+ // in reverse). The build's pre-js loads the filesystem bundle before the first of them, so every one
174
+ // sees the bundle's files. They touch disjoint state (the runtime hook, /dev/blob, the environment, the
175
+ // bundle's files outside the data directory, then the storage mount over the data directory), so none
176
+ // depends on the order of the others.
177
+ const preRun: ((module: PostgresModule) => void)[] = [
178
+ (module) => {
179
+ module.onRuntimeInitialized = () => pendingHost(module).#onRuntimeInitialized();
180
+ },
181
+ (module) => pendingHost(module).#registerBlobDevice(),
182
+ (module) => {
183
+ const env = module.ENV;
184
+ env["HOME"] = "/home/postgres";
185
+ env["USER"] = "postgres";
186
+ env["LOGNAME"] = "postgres";
187
+ env["PGDATA"] = PGDATA;
188
+ env["PGUSER"] = config.user;
189
+ env["PGDATABASE"] = config.database;
190
+ env["LANG"] = "en_US.UTF-8";
191
+ env["LC_COLLATE"] = "en_US.UTF-8";
192
+ env["LC_CTYPE"] = "en_US.UTF-8";
193
+ env["TZ"] = "UTC";
194
+ env["PGTZ"] = "UTC";
195
+ env["PGCLIENTENCODING"] = "UTF8";
196
+ env["ICU_DATA"] = ICU_DATA_PATH;
197
+ },
198
+ (module) => {
199
+ module.FS.chmod("/home/postgres/.pgpass", 0o600); // libpq ignores a .pgpass others can read
200
+ module.FS.chmod(INITDB_EXE_PATH, 0o555);
201
+ module.FS.chmod(POSTGRES_EXE_PATH, 0o555);
202
+ },
203
+ ];
204
+ if (config.mountPreRun) preRun.push(config.mountPreRun);
205
+
206
+ const overrides: ModuleOverrides<PostgresModule> = {
207
+ thisProgram: POSTGRES_EXE_PATH,
208
+ arguments: config.debug > 0 ? ["-d", String(config.debug)] : [],
209
+ noExitRuntime: true,
210
+ wasmMemory: new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: MAXIMUM_MEMORY_PAGES }),
211
+ // A stdin that is always at EOF, so a browser never prompts.
212
+ stdin: () => null,
213
+ print: log,
214
+ printErr: logError,
215
+ instantiateWasm: (imports, successCallback) => {
216
+ WebAssembly.instantiate(wasmModule, imports).then(
217
+ (instance) => {
218
+ try {
219
+ stack = shadowStackOf(instance);
220
+ } catch (error) {
221
+ rejectInstantiation(error);
222
+ return;
223
+ }
224
+ successCallback(instance, wasmModule);
225
+ },
226
+ (error: unknown) => rejectInstantiation(error),
227
+ );
228
+ return {};
229
+ },
230
+ getPreloadedPackage: (name, size) => {
231
+ if (name !== "postgres.data") throw new Error(`Unknown filesystem package: ${name}`);
232
+ if (fsBundle.byteLength !== size) {
233
+ // Unreachable while the glue and the pins agree; if they ever do not, fail the boot with this error.
234
+ const error = invalidBundleSize(fsBundle.byteLength, size);
235
+ rejectInstantiation(error);
236
+ throw error;
237
+ }
238
+ return fsBundle;
239
+ },
240
+ preRun,
241
+ };
242
+
243
+ const module = await Promise.race([createPostgresModule(overrides), instantiationFailed]);
244
+ const instance = pendingHost(module);
245
+ config.onModule?.(module);
246
+ return instance;
247
+ }
248
+
249
+ #recordStderr(text: string): void {
250
+ this.#stderr.push(text);
251
+ if (this.#stderr.length > 20) this.#stderr.shift();
252
+ }
253
+
254
+ #log(...args: unknown[]): void {
255
+ if (this.#debug > 0) console.log(...args);
256
+ }
257
+
258
+ #addFunction(fn: (...args: number[]) => number | void, signature: string): number {
259
+ const pointer = this.module.addFunction(fn, signature);
260
+ this.#functionPointers.push(pointer);
261
+ return pointer;
262
+ }
263
+
264
+ #onRuntimeInitialized(): void {
265
+ const mod = this.module;
266
+ // system() never runs a command: it is logged and fails.
267
+ mod._pgl_set_system_fn(
268
+ this.#addFunction((command: number) => {
269
+ this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);
270
+ return 1;
271
+ }, "pi"),
272
+ );
273
+ mod._pgl_set_popen_fn(
274
+ this.#addFunction((command: number, mode: number) => {
275
+ this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));
276
+ return this.#externalCommandStream;
277
+ }, "ppp"),
278
+ );
279
+ mod._pgl_set_pclose_fn(
280
+ this.#addFunction((stream: number) => {
281
+ if (stream !== this.#externalCommandStream) throw new Error(`Unhandled pclose ${stream}`);
282
+ mod._fclose(stream);
283
+ this.#externalCommandStream = null;
284
+ }, "pi"),
285
+ );
286
+ // Backend bytes: handed to the exchange's sink as a view of the heap, valid during the call.
287
+ const write = this.#addFunction((pointer: number, length: number) => {
288
+ this.#sink?.(this.module.HEAPU8.subarray(pointer, pointer + length));
289
+ return length;
290
+ }, "iii");
291
+ // Frontend bytes: copied into the heap from the message being exchanged.
292
+ const read = this.#addFunction((pointer: number, maxLength: number) => {
293
+ const length = Math.min(this.#input.length - this.#readOffset, maxLength);
294
+ this.module.HEAPU8.set(this.#input.subarray(this.#readOffset, this.#readOffset + length), pointer);
295
+ this.#readOffset += length;
296
+ return length;
297
+ }, "iii");
298
+ mod._pgl_set_rw_cbs(read, write);
299
+ }
300
+
301
+ #handleExternalCommand(command: string, mode: string): number {
302
+ if (command.startsWith("locale -a") && mode === "r") {
303
+ return this.module._fopen(
304
+ this.module.stringToUTF8OnStack(LOCALE_LIST_PATH),
305
+ this.module.stringToUTF8OnStack(mode),
306
+ );
307
+ }
308
+ throw new Error(`Unhandled external command: ${command}`);
309
+ }
310
+
311
+ /** `/dev/blob`: what `COPY … FROM '/dev/blob'` reads and `COPY … TO '/dev/blob'` writes. */
312
+ #registerBlobDevice(): void {
313
+ const FS = this.module.FS;
314
+ const device = FS.makedev(64, 0);
315
+ FS.registerDevice(device, {
316
+ open: () => undefined,
317
+ close: () => undefined,
318
+ read: (_stream, buffer, offset, length, position) => {
319
+ const contents = this.#blobReadSource;
320
+ if (!contents) throw new Error("No /dev/blob File or Blob provided to read from");
321
+ if (position >= contents.length) return 0;
322
+ const size = Math.min(contents.length - position, length);
323
+ buffer.set(contents.subarray(position, position + size), offset);
324
+ return size;
325
+ },
326
+ write: (_stream, buffer, offset, length) => {
327
+ this.#blobWritten ??= [];
328
+ this.#blobWritten.push(new Uint8Array(buffer.subarray(offset, offset + length)));
329
+ return length;
330
+ },
331
+ llseek: (stream: EmscriptenStream, offset: number, whence: number) => {
332
+ const contents = this.#blobReadSource;
333
+ if (!contents) throw new Error("No /dev/blob File or Blob provided to llseek");
334
+ let position = offset;
335
+ if (whence === 1) position += stream.position;
336
+ else if (whence === 2) position = contents.length;
337
+ if (position < 0) throw new FS.ErrnoError(28);
338
+ return position;
339
+ },
340
+ });
341
+ FS.mkdev("/dev/blob", device);
342
+ }
343
+
344
+ setBlobReadSource(data: Uint8Array | undefined): void {
345
+ this.#blobReadSource = data;
346
+ }
347
+
348
+ takeBlobWritten(): Uint8Array<ArrayBuffer>[] | undefined {
349
+ const written = this.#blobWritten;
350
+ this.#blobWritten = undefined;
351
+ return written;
352
+ }
353
+
354
+ /** Run `callMain`, leaving the host's exit code as it was. */
355
+ callMain(args: string[]): number {
356
+ return preservingExitCode(() => this.module.callMain(args));
357
+ }
358
+
359
+ /** Start Postgres in single-user mode on the data directory. */
360
+ startSingleMode(startParams: readonly string[]): void {
361
+ const mod = this.module;
362
+ mod._pgl_setPGliteActive(1);
363
+ this.callMain([...startParams, "-D", PGDATA, mod.ENV["PGDATABASE"] ?? "postgres"]);
364
+ const exitStatus = mod._pgl_setPGliteExitStatus(-3);
365
+ if (exitStatus !== PGLITE_EXIT_ALIVE) {
366
+ const output = this.#stderr.join("\n").trim();
367
+ throw new Error(
368
+ `Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:\n${output}` : ""}`,
369
+ );
370
+ }
371
+ mod._pgl_startPGlite();
372
+ }
373
+
374
+ /**
375
+ * One exchange on the single session: feed `message` to Postgres and hand every backend byte it
376
+ * produces to `onData`, synchronously. A startup packet (first byte 0) is processed as one; a
377
+ * Terminate (`X`) is ignored, as the session ends with the instance. A throw that is not Postgres'
378
+ * own error unwind means the wasm stack was abandoned mid-function, and an exit (a FATAL error) means
379
+ * the backend tore its session down: either fails the session, which refuses every later exchange.
380
+ */
381
+ exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void {
382
+ if (this.#failed) throw new Error("The C build's session failed and cannot be used again");
383
+ if (message[0] === 0x58) return; // Terminate
384
+ this.#sink = onData;
385
+ this.#input = message;
386
+ this.#readOffset = 0;
387
+ this.#stderr.length = 0;
388
+ try {
389
+ if (message[0] === 0) {
390
+ this.#processStartupPacket();
391
+ return;
392
+ }
393
+ this.#runMainLoop(message);
394
+ } catch (error) {
395
+ const status = exitStatusOf(error);
396
+ if (status === undefined) throw error;
397
+ this.#failed = true;
398
+ const output = this.#stderr.join("\n").trim();
399
+ throw new Error(
400
+ `Postgres exited with status ${status} during an exchange: a FATAL error ended the C build's session${output ? `:\n${output}` : ""}`,
401
+ { cause: error },
402
+ );
403
+ } finally {
404
+ this.#sink = undefined;
405
+ this.#input = new Uint8Array(0);
406
+ }
407
+ }
408
+
409
+ /**
410
+ * A call into the backend that may unwind (an ERROR's intercepted siglongjmp, a FATAL's exit):
411
+ * should it throw, the shadow stack pointer is restored to where it began (see {@link ShadowStack}).
412
+ */
413
+ #call<T>(call: () => T): T {
414
+ const stack = this.#stack.save();
415
+ try {
416
+ return call();
417
+ } catch (error) {
418
+ this.#stack.restore(stack);
419
+ throw error;
420
+ }
421
+ }
422
+
423
+ #processStartupPacket(): void {
424
+ const mod = this.module;
425
+ const result = this.#call(() => mod._ProcessStartupPacket(mod._pgl_getMyProcPort(), true, true));
426
+ if (result !== 0) throw new Error("Cannot process the startup packet");
427
+ this.#call(() => {
428
+ mod._pgl_sendConnData();
429
+ mod._pgl_pq_flush();
430
+ });
431
+ }
432
+
433
+ #runMainLoop(message: Uint8Array): void {
434
+ const mod = this.module;
435
+ try {
436
+ // One message may carry several batched statements; the loop returns after each.
437
+ while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {
438
+ const stack = this.#stack.save();
439
+ try {
440
+ mod._PostgresMainLoopOnce();
441
+ } catch (error) {
442
+ // First, as Postgres' own siglongjmp to PostgresMain would: the throw skipped the epilogues of
443
+ // every frame it abandoned (see ShadowStack).
444
+ this.#stack.restore(stack);
445
+ if (!isEmscriptenUnwind(error)) throw error;
446
+ if (mod._pgl_setPGliteExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {
447
+ // Postgres raised an error: its siglongjmp into main was intercepted, and its error handling
448
+ // runs here before the loop resumes with the rest of the batch.
449
+ this.#call(() => mod._PostgresMainLongJmp());
450
+ }
451
+ }
452
+ }
453
+ this.#call(() => {
454
+ mod._PostgresSendReadyForQueryIfNecessary();
455
+ mod._pgl_pq_flush();
456
+ });
457
+ } catch (error) {
458
+ this.#failed = true;
459
+ throw error;
460
+ }
461
+ }
462
+
463
+ /** Postgres' clean exit: its atexit callbacks. An exit status of 0 is the normal outcome. */
464
+ shutdown(): void {
465
+ const mod = this.module;
466
+ try {
467
+ preservingExitCode(() => {
468
+ mod._pgl_setPGliteActive(0);
469
+ this.#call(() => mod._pgl_run_atexit_funcs());
470
+ });
471
+ } catch (error) {
472
+ const exit = error as { name?: unknown; status?: unknown };
473
+ if (!(exit.name === "ExitStatus" && exit.status === 0)) throw error;
474
+ }
475
+ }
476
+
477
+ /** Release the callbacks and exit the runtime, which `noExitRuntime` otherwise keeps alive. */
478
+ dispose(exitStatus: number): void {
479
+ if (this.#exited) return;
480
+ this.#exited = true;
481
+ for (const pointer of this.#functionPointers) {
482
+ try {
483
+ this.module.removeFunction(pointer);
484
+ } catch {
485
+ // continue releasing
486
+ }
487
+ }
488
+ this.#functionPointers = [];
489
+ try {
490
+ preservingExitCode(() => this.module._emscripten_force_exit(exitStatus));
491
+ } catch {
492
+ // The runtime reports a forced exit by throwing ExitStatus.
493
+ }
494
+ }
495
+ }