@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.
- package/LICENSE +23 -0
- package/NOTICE +1890 -0
- package/README.md +79 -0
- package/artefacts/amcheck.tar.gz +0 -0
- package/artefacts/initdb.d.ts +6 -0
- package/artefacts/initdb.js +2 -0
- package/artefacts/initdb.wasm +0 -0
- package/artefacts/postgres.d.ts +6 -0
- package/artefacts/postgres.data +37595 -8
- package/artefacts/postgres.js +2 -0
- package/artefacts/postgres.wasm +0 -0
- package/artefacts/prepopulated.tar.gz +0 -0
- package/dist/artefact-pins.d.ts +57 -0
- package/dist/artefact-pins.d.ts.map +1 -0
- package/dist/artefacts.d.ts +37 -0
- package/dist/artefacts.d.ts.map +1 -0
- package/dist/build.d.ts +53 -0
- package/dist/build.d.ts.map +1 -0
- package/dist/contrib/amcheck.d.ts +9 -0
- package/dist/contrib/amcheck.d.ts.map +1 -0
- package/dist/contrib/amcheck.js +13 -0
- package/dist/contrib/amcheck.js.map +10 -0
- package/dist/host/artefact-loader.d.ts +9 -0
- package/dist/host/artefact-loader.d.ts.map +1 -0
- package/dist/host/command-line.d.ts +11 -0
- package/dist/host/command-line.d.ts.map +1 -0
- package/dist/host/data-dir.d.ts +11 -0
- package/dist/host/data-dir.d.ts.map +1 -0
- package/dist/host/emscripten.d.ts +143 -0
- package/dist/host/emscripten.d.ts.map +1 -0
- package/dist/host/exit-code.d.ts +12 -0
- package/dist/host/exit-code.d.ts.map +1 -0
- package/dist/host/extensions.d.ts +15 -0
- package/dist/host/extensions.d.ts.map +1 -0
- package/dist/host/initdb.d.ts +25 -0
- package/dist/host/initdb.d.ts.map +1 -0
- package/dist/host/mounts/file.d.ts +17 -0
- package/dist/host/mounts/file.d.ts.map +1 -0
- package/dist/host/mounts/idb.d.ts +32 -0
- package/dist/host/mounts/idb.d.ts.map +1 -0
- package/dist/host/mounts/index.d.ts +6 -0
- package/dist/host/mounts/index.d.ts.map +1 -0
- package/dist/host/mounts/memory.d.ts +12 -0
- package/dist/host/mounts/memory.d.ts.map +1 -0
- package/dist/host/mounts/storage-mount.d.ts +15 -0
- package/dist/host/mounts/storage-mount.d.ts.map +1 -0
- package/dist/host/mounts/vfs.d.ts +15 -0
- package/dist/host/mounts/vfs.d.ts.map +1 -0
- package/dist/host/paths.d.ts +10 -0
- package/dist/host/paths.d.ts.map +1 -0
- package/dist/host/postgres-instance.d.ts +63 -0
- package/dist/host/postgres-instance.d.ts.map +1 -0
- package/dist/host/vfs-mount.d.ts +10 -0
- package/dist/host/vfs-mount.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1393 -0
- package/dist/index.js.map +26 -0
- package/dist/prepopulated.d.ts +28 -0
- package/dist/prepopulated.d.ts.map +1 -0
- package/dist/prepopulated.js +15 -0
- package/dist/prepopulated.js.map +10 -0
- package/package.json +56 -0
- package/src/artefact-pins.ts +36 -0
- package/src/artefacts.ts +46 -0
- package/src/build.ts +326 -0
- package/src/contrib/amcheck.ts +17 -0
- package/src/host/artefact-loader.ts +75 -0
- package/src/host/command-line.ts +64 -0
- package/src/host/data-dir.ts +70 -0
- package/src/host/emscripten.ts +158 -0
- package/src/host/exit-code.ts +29 -0
- package/src/host/extensions.ts +83 -0
- package/src/host/initdb.ts +180 -0
- package/src/host/mounts/file.ts +44 -0
- package/src/host/mounts/idb.ts +152 -0
- package/src/host/mounts/index.ts +26 -0
- package/src/host/mounts/memory.ts +22 -0
- package/src/host/mounts/storage-mount.ts +15 -0
- package/src/host/mounts/vfs.ts +43 -0
- package/src/host/paths.ts +18 -0
- package/src/host/postgres-instance.ts +495 -0
- package/src/host/vfs-mount.ts +258 -0
- package/src/index.ts +3 -0
- package/src/prepopulated.ts +38 -0
|
@@ -0,0 +1,158 @@
|
|
|
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
|
+
* The parts of the Emscripten runtime the C build's host code uses, typed here rather than through
|
|
6
|
+
* `@types/emscripten` (a global-ambient package that would put a global `FS` into every file of the
|
|
7
|
+
* repository's single typecheck program). Only what is called is declared.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** An Emscripten filesystem type (MEMFS, NODEFS, IDBFS, PROXYFS or one of ours). */
|
|
11
|
+
export interface EmscriptenFilesystemType {
|
|
12
|
+
readonly [member: string]: unknown;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EmscriptenNode {
|
|
16
|
+
name: string;
|
|
17
|
+
mode: number;
|
|
18
|
+
id: number;
|
|
19
|
+
rdev: number;
|
|
20
|
+
parent: EmscriptenNode;
|
|
21
|
+
mount: { opts: { root?: string } };
|
|
22
|
+
node_ops: unknown;
|
|
23
|
+
stream_ops: unknown;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface EmscriptenStream {
|
|
27
|
+
node: EmscriptenNode;
|
|
28
|
+
position: number;
|
|
29
|
+
nfd?: number;
|
|
30
|
+
shared: { refcount: number };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface EmscriptenStat {
|
|
34
|
+
mode: number;
|
|
35
|
+
size: number;
|
|
36
|
+
mtime: Date | number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface EmscriptenErrnoError extends Error {
|
|
40
|
+
errno: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface IdbfsType extends EmscriptenFilesystemType {
|
|
44
|
+
readonly dbs: Readonly<Record<string, { close(): void } | undefined>>;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Emscripten's `FS` object. */
|
|
48
|
+
export interface EmscriptenFS {
|
|
49
|
+
readonly filesystems: {
|
|
50
|
+
readonly MEMFS: EmscriptenFilesystemType;
|
|
51
|
+
readonly NODEFS: EmscriptenFilesystemType;
|
|
52
|
+
readonly IDBFS: IdbfsType;
|
|
53
|
+
};
|
|
54
|
+
readonly ErrnoError: new (errno: number) => EmscriptenErrnoError;
|
|
55
|
+
analyzePath(path: string): { exists: boolean };
|
|
56
|
+
mkdir(path: string, mode?: number): void;
|
|
57
|
+
mkdirTree(path: string, mode?: number): void;
|
|
58
|
+
mount(type: EmscriptenFilesystemType, opts: Record<string, unknown>, mountpoint: string): void;
|
|
59
|
+
symlink(target: string, path: string): void;
|
|
60
|
+
readdir(path: string): string[];
|
|
61
|
+
stat(path: string): EmscriptenStat;
|
|
62
|
+
isFile(mode: number): boolean;
|
|
63
|
+
isDir(mode: number): boolean;
|
|
64
|
+
readFile(path: string, options?: { encoding: "binary" }): Uint8Array;
|
|
65
|
+
writeFile(path: string, data: Uint8Array | string): void;
|
|
66
|
+
utime(path: string, atime: number, mtime: number): void;
|
|
67
|
+
chmod(path: string, mode: number): void;
|
|
68
|
+
unlink(path: string): void;
|
|
69
|
+
rmdir(path: string): void;
|
|
70
|
+
makedev(major: number, minor: number): number;
|
|
71
|
+
registerDevice(dev: number, ops: EmscriptenDeviceOps): void;
|
|
72
|
+
mkdev(path: string, dev: number): void;
|
|
73
|
+
createNode(parent: EmscriptenNode | null, name: string, mode: number, dev?: number): EmscriptenNode;
|
|
74
|
+
createPreloadedFile(
|
|
75
|
+
parent: string,
|
|
76
|
+
name: string,
|
|
77
|
+
data: Uint8Array,
|
|
78
|
+
canRead: boolean,
|
|
79
|
+
canWrite: boolean,
|
|
80
|
+
onload: () => void,
|
|
81
|
+
onerror: () => void,
|
|
82
|
+
dontCreateFile: boolean,
|
|
83
|
+
): void;
|
|
84
|
+
syncfs(populate: boolean, callback: (error: unknown) => void): void;
|
|
85
|
+
quit(): void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface EmscriptenDeviceOps {
|
|
89
|
+
open(stream: EmscriptenStream): void;
|
|
90
|
+
close(stream: EmscriptenStream): void;
|
|
91
|
+
read(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
|
|
92
|
+
write(stream: EmscriptenStream, buffer: Uint8Array, offset: number, length: number, position: number): number;
|
|
93
|
+
llseek(stream: EmscriptenStream, offset: number, whence: number): number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** What the module factories accept; the members the host sets. */
|
|
97
|
+
export interface ModuleOverrides<TModule> {
|
|
98
|
+
thisProgram: string;
|
|
99
|
+
arguments?: string[];
|
|
100
|
+
noExitRuntime?: boolean;
|
|
101
|
+
wasmMemory?: WebAssembly.Memory;
|
|
102
|
+
stdin?: () => number | null;
|
|
103
|
+
print?: (text: string) => void;
|
|
104
|
+
printErr?: (text: string) => void;
|
|
105
|
+
instantiateWasm?: (
|
|
106
|
+
imports: Parameters<typeof WebAssembly.instantiate>[1],
|
|
107
|
+
successCallback: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,
|
|
108
|
+
) => Record<string, never>;
|
|
109
|
+
getPreloadedPackage?: (name: string, size: number) => ArrayBuffer;
|
|
110
|
+
preRun?: ((module: TModule) => void)[];
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** The members every Emscripten module the C build loads has. */
|
|
114
|
+
export interface EmscriptenModuleBase {
|
|
115
|
+
readonly FS: EmscriptenFS;
|
|
116
|
+
readonly ENV: Record<string, string>;
|
|
117
|
+
readonly HEAPU8: Uint8Array;
|
|
118
|
+
readonly HEAP8: Int8Array;
|
|
119
|
+
onRuntimeInitialized?: () => void;
|
|
120
|
+
callMain(args: string[]): number;
|
|
121
|
+
addFunction(fn: (...args: number[]) => number | void, signature: string): number;
|
|
122
|
+
removeFunction(pointer: number): void;
|
|
123
|
+
UTF8ToString(pointer: number): string;
|
|
124
|
+
stringToUTF8OnStack(value: string): number;
|
|
125
|
+
_fopen(path: number, mode: number): number;
|
|
126
|
+
_fclose(stream: number): number;
|
|
127
|
+
_pgl_set_system_fn(fn: number): void;
|
|
128
|
+
_pgl_set_popen_fn(fn: number): void;
|
|
129
|
+
_pgl_set_pclose_fn(fn: number): void;
|
|
130
|
+
_pgl_freopen(path: number, mode: number, stream: number): number;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** The Postgres module (`postgres.js`). */
|
|
134
|
+
export interface PostgresModule extends EmscriptenModuleBase {
|
|
135
|
+
readonly PROXYFS: EmscriptenFilesystemType;
|
|
136
|
+
_pgl_set_rw_cbs(readCallback: number, writeCallback: number): void;
|
|
137
|
+
_pgl_pq_flush(): void;
|
|
138
|
+
_pgl_setPGliteActive(value: number): number;
|
|
139
|
+
_pgl_startPGlite(): void;
|
|
140
|
+
_pgl_getMyProcPort(): number;
|
|
141
|
+
_pgl_sendConnData(): void;
|
|
142
|
+
_pgl_run_atexit_funcs(): void;
|
|
143
|
+
_pgl_setPGliteExitStatus(status: number): number;
|
|
144
|
+
_PostgresMainLoopOnce(): void;
|
|
145
|
+
_PostgresMainLongJmp(): void;
|
|
146
|
+
_PostgresSendReadyForQueryIfNecessary(): void;
|
|
147
|
+
_ProcessStartupPacket(port: number, sslDone: boolean, gssDone: boolean): number;
|
|
148
|
+
_pq_buffer_remaining_data(): number;
|
|
149
|
+
_emscripten_force_exit(status: number): void;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** The initdb module (`initdb.js`). */
|
|
153
|
+
export interface InitdbModule extends EmscriptenModuleBase {
|
|
154
|
+
readonly PROXYFS: EmscriptenFilesystemType;
|
|
155
|
+
_pclose(stream: number): number;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export type ModuleFactory<TModule> = (overrides: ModuleOverrides<TModule>) => Promise<TModule>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Emscripten's runtime writes an exit status onto the host's `process.exitCode` when the program
|
|
3
|
+
* exits, and Postgres' single-user mode reports a successful start by exiting with 99. Under Bun that
|
|
4
|
+
* sentinel would survive to the end of the process and fail an otherwise green run. Every glue call that
|
|
5
|
+
* can exit is wrapped so the host's own exit code is left as it was.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
interface ProcessWithExitCode {
|
|
9
|
+
exitCode?: number | string | undefined;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function hostProcess(): ProcessWithExitCode | undefined {
|
|
13
|
+
return (globalThis as { process?: ProcessWithExitCode }).process;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Run `fn`, restoring `process.exitCode` (where there is a process) to its value before. Bun ignores an
|
|
18
|
+
* assignment of `undefined`, so an exit code that was unset is restored as 0 — only when `fn` changed it.
|
|
19
|
+
*/
|
|
20
|
+
export function preservingExitCode<T>(fn: () => T): T {
|
|
21
|
+
const proc = hostProcess();
|
|
22
|
+
if (proc === undefined) return fn();
|
|
23
|
+
const before = proc.exitCode;
|
|
24
|
+
try {
|
|
25
|
+
return fn();
|
|
26
|
+
} finally {
|
|
27
|
+
if (proc.exitCode !== before) proc.exitCode = before ?? 0;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
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 { gunzipIfCompressed, readTar, type ServerExtension, type TarEntry } from "@pgxsinkit/pgwasm/build";
|
|
5
|
+
|
|
6
|
+
import type { EmscriptenFS, PostgresModule } from "./emscripten";
|
|
7
|
+
import { PG_ROOT } from "./paths";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* An extension bundle's files, fetched now so the download overlaps the boot. The bundle is a gzipped
|
|
11
|
+
* tar; a server that already decompressed it (Content-Encoding) hands over the plain tar, which is
|
|
12
|
+
* recognised by its missing gzip magic.
|
|
13
|
+
*/
|
|
14
|
+
export async function fetchExtensionBundle(extension: ServerExtension): Promise<TarEntry[]> {
|
|
15
|
+
const response = await fetch(extension.bundle);
|
|
16
|
+
if (!response.ok) {
|
|
17
|
+
throw new Error(
|
|
18
|
+
`Could not load the "${extension.name}" extension bundle ${extension.bundle.href}: HTTP ${response.status}`,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
const bytes = await gunzipIfCompressed(new Uint8Array(await response.arrayBuffer()));
|
|
22
|
+
return readTar(bytes);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function writeFile(FS: EmscriptenFS, path: string, data: Uint8Array): void {
|
|
26
|
+
const directory = path.slice(0, path.lastIndexOf("/"));
|
|
27
|
+
if (!FS.analyzePath(directory).exists) FS.mkdirTree(directory);
|
|
28
|
+
FS.writeFile(path, data);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Install extension files under `/pgwasm` (`lib/postgresql/*.so`, `share/postgresql/extension/*`).
|
|
33
|
+
* Shared objects go through the runtime's preload plugin, which compiles them ahead of `dlopen`; a
|
|
34
|
+
* preload that fails leaves the plain file, and `dlopen` compiles it when it is first needed.
|
|
35
|
+
*/
|
|
36
|
+
export async function installExtensionFiles(
|
|
37
|
+
module: PostgresModule,
|
|
38
|
+
bundles: readonly TarEntry[][],
|
|
39
|
+
log: (...args: unknown[]) => void,
|
|
40
|
+
): Promise<void> {
|
|
41
|
+
const FS = module.FS;
|
|
42
|
+
const preloads: Promise<void>[] = [];
|
|
43
|
+
for (const bundle of bundles) {
|
|
44
|
+
// Sorted so a library preloads before the ones that link against it (e.g. postgis-3.so before
|
|
45
|
+
// postgis_topology-3.so).
|
|
46
|
+
const entries = [...bundle].sort((a, b) => (a.name > b.name ? 1 : a.name < b.name ? -1 : 0));
|
|
47
|
+
for (const entry of entries) {
|
|
48
|
+
const path = `${PG_ROOT}/${entry.name}`.replace(/\/+$/, "");
|
|
49
|
+
if (entry.type === "directory") {
|
|
50
|
+
if (!FS.analyzePath(path).exists) FS.mkdirTree(path);
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (entry.name.startsWith(".")) continue;
|
|
54
|
+
if (entry.name.endsWith(".so")) {
|
|
55
|
+
const directory = path.slice(0, path.lastIndexOf("/"));
|
|
56
|
+
const soName = path.slice(path.lastIndexOf("/") + 1);
|
|
57
|
+
if (!FS.analyzePath(directory).exists) FS.mkdirTree(directory);
|
|
58
|
+
log(`pgwasm-c: preloading ${path}`);
|
|
59
|
+
preloads.push(
|
|
60
|
+
new Promise<void>((resolve) => {
|
|
61
|
+
FS.createPreloadedFile(
|
|
62
|
+
directory,
|
|
63
|
+
soName,
|
|
64
|
+
entry.data,
|
|
65
|
+
true,
|
|
66
|
+
true,
|
|
67
|
+
() => resolve(),
|
|
68
|
+
() => {
|
|
69
|
+
log(`pgwasm-c: preloading ${path} failed; installing the plain file`);
|
|
70
|
+
writeFile(FS, path, entry.data);
|
|
71
|
+
resolve();
|
|
72
|
+
},
|
|
73
|
+
false,
|
|
74
|
+
);
|
|
75
|
+
}),
|
|
76
|
+
);
|
|
77
|
+
} else {
|
|
78
|
+
writeFile(FS, path, entry.data);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
await Promise.all(preloads);
|
|
83
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
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 { CBuildArtefactSet } from "../artefacts";
|
|
5
|
+
import { commandWords } from "./command-line";
|
|
6
|
+
import type { InitdbModule } from "./emscripten";
|
|
7
|
+
import { preservingExitCode } from "./exit-code";
|
|
8
|
+
import {
|
|
9
|
+
ICU_DATA_PATH,
|
|
10
|
+
INITDB_EXE_PATH,
|
|
11
|
+
PG_ROOT,
|
|
12
|
+
PG_STDIN_PATH,
|
|
13
|
+
PG_STDOUT_PATH,
|
|
14
|
+
PGDATA,
|
|
15
|
+
POSTGRES_EXE_PATH,
|
|
16
|
+
} from "./paths";
|
|
17
|
+
import type { PostgresInstance } from "./postgres-instance";
|
|
18
|
+
|
|
19
|
+
export interface InitdbResult {
|
|
20
|
+
readonly exitCode: number;
|
|
21
|
+
readonly stderr: string;
|
|
22
|
+
readonly stdout: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** The arguments every initdb run starts with. */
|
|
26
|
+
export const INITDB_ARGS: readonly string[] = [
|
|
27
|
+
"--allow-group-access",
|
|
28
|
+
"--encoding",
|
|
29
|
+
"UTF8",
|
|
30
|
+
"--locale=C.UTF-8",
|
|
31
|
+
"--locale-provider=libc",
|
|
32
|
+
"--auth=trust",
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
function assert(condition: unknown, message: string): asserts condition {
|
|
36
|
+
if (!condition) throw new Error(message);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Run initdb against a scratch Postgres instance. initdb is its own wasm module; the backend commands it
|
|
41
|
+
* shells out to (`postgres --boot`, `postgres --single`) are run on the scratch instance, whose heap is
|
|
42
|
+
* reset to its pristine state before each. initdb sees the instance's filesystem through PROXYFS, so the
|
|
43
|
+
* cluster it creates lands in the instance's `/pgwasm/data`.
|
|
44
|
+
*/
|
|
45
|
+
export async function runInitdb({
|
|
46
|
+
createInitdbModule,
|
|
47
|
+
postgres,
|
|
48
|
+
initdbWasm,
|
|
49
|
+
debug,
|
|
50
|
+
onCommand,
|
|
51
|
+
}: {
|
|
52
|
+
/** The initdb glue (`initdb.js`) of the build whose `initdbWasm` this is. */
|
|
53
|
+
readonly createInitdbModule: CBuildArtefactSet["createInitdbModule"];
|
|
54
|
+
readonly postgres: PostgresInstance;
|
|
55
|
+
readonly initdbWasm: WebAssembly.Module;
|
|
56
|
+
readonly debug: number;
|
|
57
|
+
/** @internal Every command line initdb hands to the host (the tokenizer's test pins these). */
|
|
58
|
+
readonly onCommand?: (command: string) => void;
|
|
59
|
+
}): Promise<InitdbResult> {
|
|
60
|
+
const log = (...args: unknown[]) => {
|
|
61
|
+
if (debug > 0) console.log("initdb:", ...args);
|
|
62
|
+
};
|
|
63
|
+
const pg = postgres.module;
|
|
64
|
+
let needToCallPgMain = false;
|
|
65
|
+
let postgresArgs: string[] = [];
|
|
66
|
+
let pgMainResult = 0;
|
|
67
|
+
let initdbStdinFd = -1;
|
|
68
|
+
let initdbStdoutFd = -1;
|
|
69
|
+
let stderr = "";
|
|
70
|
+
let stdout = "";
|
|
71
|
+
|
|
72
|
+
const pristineHeap = pg.HEAPU8.slice();
|
|
73
|
+
const callPgMain = (args: string[]): number => {
|
|
74
|
+
const [program, ...rest] = args;
|
|
75
|
+
assert(program === POSTGRES_EXE_PATH, `initdb tried to execute ${String(program)}`);
|
|
76
|
+
pg.HEAPU8.set(pristineHeap);
|
|
77
|
+
log("executing postgres with", rest);
|
|
78
|
+
const result = postgres.callMain(rest);
|
|
79
|
+
postgresArgs = [];
|
|
80
|
+
return result;
|
|
81
|
+
};
|
|
82
|
+
const commandArgs = (module: InitdbModule, pointer: number): string[] => {
|
|
83
|
+
const command = module.UTF8ToString(pointer);
|
|
84
|
+
onCommand?.(command);
|
|
85
|
+
return commandWords(command);
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
let rejectInstantiation: (error: unknown) => void = () => undefined;
|
|
89
|
+
const instantiationFailed = new Promise<never>((_, reject) => {
|
|
90
|
+
rejectInstantiation = reject;
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const initdb = await Promise.race([
|
|
94
|
+
createInitdbModule({
|
|
95
|
+
thisProgram: INITDB_EXE_PATH,
|
|
96
|
+
arguments: [...INITDB_ARGS],
|
|
97
|
+
noExitRuntime: false,
|
|
98
|
+
stdin: () => null,
|
|
99
|
+
print: (text) => {
|
|
100
|
+
stdout += text;
|
|
101
|
+
log("stdout", text);
|
|
102
|
+
},
|
|
103
|
+
printErr: (text) => {
|
|
104
|
+
stderr += text;
|
|
105
|
+
log("stderr", text);
|
|
106
|
+
},
|
|
107
|
+
instantiateWasm: (imports, successCallback) => {
|
|
108
|
+
WebAssembly.instantiate(initdbWasm, imports).then(
|
|
109
|
+
(instance) => successCallback(instance, initdbWasm),
|
|
110
|
+
(error: unknown) => rejectInstantiation(error),
|
|
111
|
+
);
|
|
112
|
+
return {};
|
|
113
|
+
},
|
|
114
|
+
// Run in the order listed, after the filesystem bundle loads (see PostgresInstance.create): the
|
|
115
|
+
// environment, then the runtime callbacks, then the PROXYFS mount of the backend's /pgwasm.
|
|
116
|
+
preRun: [
|
|
117
|
+
(module) => {
|
|
118
|
+
const env = module.ENV;
|
|
119
|
+
env["PGDATA"] = PGDATA;
|
|
120
|
+
env["HOME"] = "/home/postgres";
|
|
121
|
+
env["USER"] = "postgres";
|
|
122
|
+
env["LOGNAME"] = "postgres";
|
|
123
|
+
env["ICU_DATA"] = ICU_DATA_PATH;
|
|
124
|
+
},
|
|
125
|
+
(module) => {
|
|
126
|
+
module.onRuntimeInitialized = () => {
|
|
127
|
+
module._pgl_set_system_fn(
|
|
128
|
+
module.addFunction((command: number) => {
|
|
129
|
+
postgresArgs = commandArgs(module, command);
|
|
130
|
+
return callPgMain(postgresArgs);
|
|
131
|
+
}, "pi"),
|
|
132
|
+
);
|
|
133
|
+
module._pgl_set_popen_fn(
|
|
134
|
+
module.addFunction((command: number, mode: number) => {
|
|
135
|
+
const openMode = module.UTF8ToString(mode);
|
|
136
|
+
postgresArgs = commandArgs(module, command);
|
|
137
|
+
if (openMode === "r") {
|
|
138
|
+
pgMainResult = callPgMain(postgresArgs);
|
|
139
|
+
return initdbStdinFd;
|
|
140
|
+
}
|
|
141
|
+
if (openMode === "w") {
|
|
142
|
+
needToCallPgMain = true;
|
|
143
|
+
return initdbStdoutFd;
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`Unexpected popen mode ${openMode}`);
|
|
146
|
+
}, "ppi"),
|
|
147
|
+
);
|
|
148
|
+
module._pgl_set_pclose_fn(
|
|
149
|
+
module.addFunction((stream: number) => {
|
|
150
|
+
if (stream === initdbStdinFd || stream === initdbStdoutFd) {
|
|
151
|
+
// A popen in "w" mode runs postgres' main once initdb has written its input.
|
|
152
|
+
if (needToCallPgMain) {
|
|
153
|
+
needToCallPgMain = false;
|
|
154
|
+
pgMainResult = callPgMain(postgresArgs);
|
|
155
|
+
}
|
|
156
|
+
return pgMainResult;
|
|
157
|
+
}
|
|
158
|
+
return module._pclose(stream);
|
|
159
|
+
}, "pi"),
|
|
160
|
+
);
|
|
161
|
+
// The backend reads initdb's output and writes initdb's input through two files.
|
|
162
|
+
pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack("r"), 0);
|
|
163
|
+
pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack("w"), 1);
|
|
164
|
+
initdbStdinFd = module._fopen(module.stringToUTF8OnStack(PG_STDOUT_PATH), module.stringToUTF8OnStack("r"));
|
|
165
|
+
initdbStdoutFd = module._fopen(module.stringToUTF8OnStack(PG_STDIN_PATH), module.stringToUTF8OnStack("w"));
|
|
166
|
+
};
|
|
167
|
+
},
|
|
168
|
+
(module) => {
|
|
169
|
+
module.FS.mkdir(PG_ROOT);
|
|
170
|
+
module.FS.mount(module.PROXYFS, { root: PG_ROOT, fs: pg.FS }, PG_ROOT);
|
|
171
|
+
},
|
|
172
|
+
],
|
|
173
|
+
}),
|
|
174
|
+
instantiationFailed,
|
|
175
|
+
]);
|
|
176
|
+
|
|
177
|
+
log("running initdb with", INITDB_ARGS);
|
|
178
|
+
const exitCode = preservingExitCode(() => initdb.callMain([...INITDB_ARGS]));
|
|
179
|
+
return { exitCode, stderr, stdout };
|
|
180
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
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 { PGDATA } from "../paths";
|
|
6
|
+
import type { StorageMount } from "./storage-mount";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The data directory as a directory on disk, through Emscripten's NODEFS (Bun). Writes go straight to
|
|
10
|
+
* the host filesystem, so there is nothing to persist; closing flushes the runtime's streams.
|
|
11
|
+
*/
|
|
12
|
+
export class FileMount implements StorageMount {
|
|
13
|
+
readonly #path: string;
|
|
14
|
+
#root: string | undefined;
|
|
15
|
+
|
|
16
|
+
constructor(path: string) {
|
|
17
|
+
this.#path = path;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
async acquire(): Promise<void> {
|
|
21
|
+
// Loaded lazily so the browser bundle carries no static `node:` import; this storage is Bun's.
|
|
22
|
+
const [{ mkdirSync }, { resolve }] = await Promise.all([import("node:fs"), import("node:path")]);
|
|
23
|
+
this.#root = resolve(this.#path);
|
|
24
|
+
mkdirSync(this.#root, { recursive: true });
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
get preRun(): (module: PostgresModule) => void {
|
|
28
|
+
return (module) => {
|
|
29
|
+
if (this.#root === undefined) throw new Error("the file mount was not acquired");
|
|
30
|
+
module.FS.mkdir(PGDATA);
|
|
31
|
+
module.FS.mount(module.FS.filesystems.NODEFS, { root: this.#root }, PGDATA);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async initialSync(): Promise<void> {}
|
|
36
|
+
|
|
37
|
+
async persist(): Promise<void> {}
|
|
38
|
+
|
|
39
|
+
async close(module: PostgresModule | undefined): Promise<void> {
|
|
40
|
+
module?.FS.quit();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async cleanupFailedInit(): Promise<void> {}
|
|
44
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
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 { StorageInUseError, UnsupportedFeatureError } from "@pgxsinkit/pgwasm";
|
|
5
|
+
|
|
6
|
+
import type { PostgresModule } from "../emscripten";
|
|
7
|
+
import { PG_ROOT, PGDATA } from "../paths";
|
|
8
|
+
import type { StorageMount } from "./storage-mount";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The IndexedDB database behind `idb://<name>`: `/pgwasm/<name>`. IDBFS names the database after its
|
|
12
|
+
* mount point, so this is both. It is a store's identity: a change to it (as the root rename in 18.6.2)
|
|
13
|
+
* opens a new, empty store and leaves the old database behind, never deleted here.
|
|
14
|
+
*/
|
|
15
|
+
export function idbDatabaseName(name: string): string {
|
|
16
|
+
return `${PG_ROOT}/${name}`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** The Web Lock that guards `idb://<name>` against a second open: `pgwasm-idbfs:/pgwasm/<name>`. */
|
|
20
|
+
export function idbLockName(name: string): string {
|
|
21
|
+
return `pgwasm-idbfs:${idbDatabaseName(name)}`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The slice of the Web Locks API this mount uses. */
|
|
25
|
+
interface LockManagerLike {
|
|
26
|
+
request(
|
|
27
|
+
name: string,
|
|
28
|
+
options: { mode: "exclusive"; ifAvailable: boolean },
|
|
29
|
+
callback: (lock: unknown) => Promise<void>,
|
|
30
|
+
): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The data directory in IndexedDB, through Emscripten's IDBFS: the whole directory lives in memory and
|
|
35
|
+
* is synced to an IndexedDB database named after its mount point, `/pgwasm/<name>`.
|
|
36
|
+
*
|
|
37
|
+
* One open per database: a Web Lock named after the database guards it, so a second open fails with
|
|
38
|
+
* {@link StorageInUseError}. Both names come from {@link idbDatabaseName} and {@link idbLockName} only.
|
|
39
|
+
*
|
|
40
|
+
* Deliberately no exclusive persist: a relaxed persist is a background snapshot that statements run
|
|
41
|
+
* beside (measured: an exclusive lane made relaxed as slow as strict, ~80 ms per statement). A crash
|
|
42
|
+
* during a snapshot can lose its tail, which is relaxed durability's documented loss window.
|
|
43
|
+
*/
|
|
44
|
+
export class IdbMount implements StorageMount {
|
|
45
|
+
readonly #name: string;
|
|
46
|
+
#releaseHeldLock: (() => void) | undefined;
|
|
47
|
+
#lockRequest: Promise<void> | undefined;
|
|
48
|
+
|
|
49
|
+
constructor(name: string) {
|
|
50
|
+
this.#name = name;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
get #mountPoint(): string {
|
|
54
|
+
return idbDatabaseName(this.#name);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async acquire(): Promise<void> {
|
|
58
|
+
const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;
|
|
59
|
+
if (!locks) {
|
|
60
|
+
throw new UnsupportedFeatureError("IndexedDB storage needs the Web Locks API, which this context lacks.");
|
|
61
|
+
}
|
|
62
|
+
let resolveAcquired!: (acquired: boolean) => void;
|
|
63
|
+
let rejectAcquired!: (reason: unknown) => void;
|
|
64
|
+
const acquired = new Promise<boolean>((resolve, reject) => {
|
|
65
|
+
resolveAcquired = resolve;
|
|
66
|
+
rejectAcquired = reject;
|
|
67
|
+
});
|
|
68
|
+
let releaseLock!: () => void;
|
|
69
|
+
const held = new Promise<void>((resolve) => {
|
|
70
|
+
releaseLock = resolve;
|
|
71
|
+
});
|
|
72
|
+
const lockRequest = locks.request(
|
|
73
|
+
idbLockName(this.#name),
|
|
74
|
+
{ mode: "exclusive", ifAvailable: true },
|
|
75
|
+
async (lock) => {
|
|
76
|
+
resolveAcquired(lock !== null);
|
|
77
|
+
if (lock !== null) await held;
|
|
78
|
+
},
|
|
79
|
+
);
|
|
80
|
+
this.#lockRequest = lockRequest;
|
|
81
|
+
lockRequest.catch(rejectAcquired);
|
|
82
|
+
if (!(await acquired)) {
|
|
83
|
+
await lockRequest;
|
|
84
|
+
this.#lockRequest = undefined;
|
|
85
|
+
throw new StorageInUseError(`The IndexedDB store "${this.#name}" is already open.`);
|
|
86
|
+
}
|
|
87
|
+
this.#releaseHeldLock = releaseLock;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
get preRun(): (module: PostgresModule) => void {
|
|
91
|
+
return (module) => {
|
|
92
|
+
const FS = module.FS;
|
|
93
|
+
if (!FS.analyzePath(this.#mountPoint).exists) FS.mkdirTree(this.#mountPoint);
|
|
94
|
+
FS.mount(FS.filesystems.IDBFS, {}, this.#mountPoint);
|
|
95
|
+
FS.symlink(this.#mountPoint, PGDATA);
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async initialSync(module: PostgresModule): Promise<void> {
|
|
100
|
+
await this.#syncfs(module, true);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async persist(module: PostgresModule): Promise<void> {
|
|
104
|
+
await this.#syncfs(module, false);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async close(module: PostgresModule | undefined): Promise<void> {
|
|
108
|
+
await this.#closeAndRelease(module);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async cleanupFailedInit(module: PostgresModule | undefined): Promise<void> {
|
|
112
|
+
await this.#closeAndRelease(module);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async #closeAndRelease(module: PostgresModule | undefined): Promise<void> {
|
|
116
|
+
try {
|
|
117
|
+
if (module) {
|
|
118
|
+
// IDBDatabase.close() returns at once; the database closes when its transactions finish. Deleting
|
|
119
|
+
// it right after needs the caller to wait for that.
|
|
120
|
+
module.FS.filesystems.IDBFS.dbs[this.#mountPoint]?.close();
|
|
121
|
+
module.FS.quit();
|
|
122
|
+
}
|
|
123
|
+
} finally {
|
|
124
|
+
const release = this.#releaseHeldLock;
|
|
125
|
+
const request = this.#lockRequest;
|
|
126
|
+
this.#releaseHeldLock = undefined;
|
|
127
|
+
this.#lockRequest = undefined;
|
|
128
|
+
release?.();
|
|
129
|
+
await request;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async #syncfs(module: PostgresModule, populate: boolean): Promise<void> {
|
|
134
|
+
const timestampFloor = Date.now();
|
|
135
|
+
await new Promise<void>((resolve, reject) => {
|
|
136
|
+
module.FS.syncfs(populate, (error) => {
|
|
137
|
+
if (error) {
|
|
138
|
+
reject(error instanceof Error ? error : new Error(`IDBFS sync failed: ${JSON.stringify(error)}`));
|
|
139
|
+
} else resolve();
|
|
140
|
+
});
|
|
141
|
+
});
|
|
142
|
+
// IDBFS compares millisecond mtimes only: a later write must not reuse a timestamp this sync may have
|
|
143
|
+
// persisted. This spins only when the whole sync fit inside one clock millisecond.
|
|
144
|
+
const waitStartedAt = performance.now();
|
|
145
|
+
while (Date.now() === timestampFloor) {
|
|
146
|
+
if (performance.now() - waitStartedAt >= 1000) {
|
|
147
|
+
throw new Error("IDBFS cannot guarantee a distinct MEMFS timestamp");
|
|
148
|
+
}
|
|
149
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
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 { StorageRequest } from "@pgxsinkit/pgwasm/build";
|
|
5
|
+
|
|
6
|
+
import { FileMount } from "./file";
|
|
7
|
+
import { IdbMount } from "./idb";
|
|
8
|
+
import { MemoryMount } from "./memory";
|
|
9
|
+
import type { StorageMount } from "./storage-mount";
|
|
10
|
+
import { VfsMount } from "./vfs";
|
|
11
|
+
|
|
12
|
+
export type { StorageMount } from "./storage-mount";
|
|
13
|
+
|
|
14
|
+
/** The mount for a storage request. */
|
|
15
|
+
export function mountFor(storage: StorageRequest): StorageMount {
|
|
16
|
+
switch (storage.kind) {
|
|
17
|
+
case "memory":
|
|
18
|
+
return new MemoryMount();
|
|
19
|
+
case "idb":
|
|
20
|
+
return new IdbMount(storage.name);
|
|
21
|
+
case "file":
|
|
22
|
+
return new FileMount(storage.path);
|
|
23
|
+
case "vfs":
|
|
24
|
+
return new VfsMount(storage.vfs);
|
|
25
|
+
}
|
|
26
|
+
}
|