@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
package/dist/index.js
ADDED
|
@@ -0,0 +1,1393 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/pgwasm-c/src/artefacts.ts
|
|
3
|
+
import createInitdbModule from "../artefacts/initdb.js";
|
|
4
|
+
import createPostgresModule from "../artefacts/postgres.js";
|
|
5
|
+
|
|
6
|
+
// packages/pgwasm-c/src/artefact-pins.ts
|
|
7
|
+
var ARTEFACT_RELEASE = {
|
|
8
|
+
repository: "pgxsinkit/pgwasm-postgres",
|
|
9
|
+
tag: "18.6.2",
|
|
10
|
+
name: "pgwasm-postgres 18.6.2",
|
|
11
|
+
commit: "bf7938ad6acd51e1f68a9cb14fee9fea879a3b48",
|
|
12
|
+
upstream: { tag: "REL_18_6", commit: "724edf9bde9d356724ad384a2e196edc3c9f80f7" },
|
|
13
|
+
dataFormat: 1,
|
|
14
|
+
builderImage: "ghcr.io/pgxsinkit/pgwasm-builder@sha256:0c4d5255c5f1824216d1eb347cc231a6f881574c3d5b8172796a8cbe5f9f63c8",
|
|
15
|
+
manifestSha256: "571b72a31003f89510f1bcbb37b5f70c142a5271cfdf24b7229423f9975d621d"
|
|
16
|
+
};
|
|
17
|
+
var ARTEFACT_FILES = {
|
|
18
|
+
"amcheck.tar.gz": { bytes: 21850, sha256: "6151f1f4ff507dd4401dc3dff9e5ad769727c2eb3d510e9fe75329bf52667c3f" },
|
|
19
|
+
"initdb.js": { bytes: 106390, sha256: "a402bd734fda0faf36696b68324471f853d52bd248ab8219893a6344386f6fac" },
|
|
20
|
+
"initdb.wasm": { bytes: 298938, sha256: "0fdc9cb46e2efe6dc1fc957c47c0c7364022c98d327eb8072af3f7fb75237d3e" },
|
|
21
|
+
"postgres.data": { bytes: 6246509, sha256: "012a2ed052fc0a05d50b9920afb5cb1692b3fbf9e09d486da61e4a59bb8f249a" },
|
|
22
|
+
"postgres.js": { bytes: 335115, sha256: "1bfb5740bd836121c0444d058593bbc7fa0de625596214a8e4805414191a23b2" },
|
|
23
|
+
"postgres.wasm": { bytes: 9140085, sha256: "f2d217be96e05dd01c02a6b62e89110d3658ac5be6032fe1d28effc9348b15ac" },
|
|
24
|
+
"prepopulated.tar.gz": { bytes: 4404457, sha256: "f5228a3690329edf675f630bedad6a4f6196f40c277f34aec3ac4d1ee426e0b3" }
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
// packages/pgwasm-c/src/artefacts.ts
|
|
28
|
+
var cBuildArtefacts = {
|
|
29
|
+
postgresWasm: new URL("../artefacts/postgres.wasm", import.meta.url),
|
|
30
|
+
fsBundle: new URL("../artefacts/postgres.data", import.meta.url),
|
|
31
|
+
initdbWasm: new URL("../artefacts/initdb.wasm", import.meta.url)
|
|
32
|
+
};
|
|
33
|
+
var pinnedCBuildArtefacts = {
|
|
34
|
+
createPostgresModule,
|
|
35
|
+
createInitdbModule,
|
|
36
|
+
...cBuildArtefacts,
|
|
37
|
+
fsBundleBytes: ARTEFACT_FILES["postgres.data"].bytes
|
|
38
|
+
};
|
|
39
|
+
// packages/pgwasm-c/src/host/artefact-loader.ts
|
|
40
|
+
var downloads = new Map;
|
|
41
|
+
var compiled = new Map;
|
|
42
|
+
var bundles = new Map;
|
|
43
|
+
function download(url) {
|
|
44
|
+
const key = url.href;
|
|
45
|
+
let pending = downloads.get(key);
|
|
46
|
+
if (pending === undefined) {
|
|
47
|
+
pending = fetch(url).then((response) => {
|
|
48
|
+
if (!response.ok) {
|
|
49
|
+
throw new Error(`Could not load ${key}: HTTP ${response.status} ${response.statusText}`);
|
|
50
|
+
}
|
|
51
|
+
return response;
|
|
52
|
+
});
|
|
53
|
+
downloads.set(key, pending);
|
|
54
|
+
pending.catch(() => downloads.delete(key));
|
|
55
|
+
}
|
|
56
|
+
return pending;
|
|
57
|
+
}
|
|
58
|
+
function prefetch(url) {
|
|
59
|
+
download(url).catch(() => {
|
|
60
|
+
return;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
function compileModule(url) {
|
|
64
|
+
const key = url.href;
|
|
65
|
+
let pending = compiled.get(key);
|
|
66
|
+
if (pending === undefined) {
|
|
67
|
+
pending = download(url).then(async (response) => {
|
|
68
|
+
try {
|
|
69
|
+
return await WebAssembly.compileStreaming(response.clone());
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if (error instanceof TypeError)
|
|
72
|
+
return await WebAssembly.compile(await response.clone().arrayBuffer());
|
|
73
|
+
throw error;
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
compiled.set(key, pending);
|
|
77
|
+
pending.catch(() => compiled.delete(key));
|
|
78
|
+
}
|
|
79
|
+
return pending;
|
|
80
|
+
}
|
|
81
|
+
async function loadBundle(url) {
|
|
82
|
+
const key = url.href;
|
|
83
|
+
let pending = bundles.get(key);
|
|
84
|
+
if (pending === undefined) {
|
|
85
|
+
pending = download(url).then((response) => response.clone().arrayBuffer());
|
|
86
|
+
bundles.set(key, pending);
|
|
87
|
+
pending.catch(() => bundles.delete(key));
|
|
88
|
+
}
|
|
89
|
+
return (await pending).slice(0);
|
|
90
|
+
}
|
|
91
|
+
async function bytesOf(source) {
|
|
92
|
+
return await (await source).arrayBuffer();
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// packages/pgwasm-c/src/host/paths.ts
|
|
96
|
+
var PG_ROOT = "/pgwasm";
|
|
97
|
+
var PGDATA = `${PG_ROOT}/data`;
|
|
98
|
+
var ICU_DATA_PATH = `${PG_ROOT}/icu`;
|
|
99
|
+
var INITDB_EXE_PATH = `${PG_ROOT}/bin/initdb`;
|
|
100
|
+
var POSTGRES_EXE_PATH = `${PG_ROOT}/bin/postgres`;
|
|
101
|
+
var PG_STDOUT_PATH = `${PG_ROOT}/pgstdout`;
|
|
102
|
+
var PG_STDIN_PATH = `${PG_ROOT}/pgstdin`;
|
|
103
|
+
var LOCALE_LIST_PATH = `${PG_ROOT}/locale-a`;
|
|
104
|
+
|
|
105
|
+
// packages/pgwasm-c/src/host/data-dir.ts
|
|
106
|
+
function mtimeSeconds(mtime) {
|
|
107
|
+
return Math.floor((typeof mtime === "number" ? mtime : mtime.getTime()) / 1000);
|
|
108
|
+
}
|
|
109
|
+
function readDataDirEntries(FS, root = PGDATA) {
|
|
110
|
+
const entries = [];
|
|
111
|
+
const walk = (directory) => {
|
|
112
|
+
for (const name of FS.readdir(directory)) {
|
|
113
|
+
if (name === "." || name === "..")
|
|
114
|
+
continue;
|
|
115
|
+
const fullPath = `${directory}/${name}`;
|
|
116
|
+
const stats = FS.stat(fullPath);
|
|
117
|
+
const isFile = FS.isFile(stats.mode);
|
|
118
|
+
entries.push({
|
|
119
|
+
path: fullPath.slice(root.length),
|
|
120
|
+
type: isFile ? "file" : "directory",
|
|
121
|
+
mode: stats.mode & 4095,
|
|
122
|
+
mtimeSeconds: mtimeSeconds(stats.mtime),
|
|
123
|
+
data: isFile ? FS.readFile(fullPath, { encoding: "binary" }) : new Uint8Array(0)
|
|
124
|
+
});
|
|
125
|
+
if (FS.isDir(stats.mode))
|
|
126
|
+
walk(fullPath);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
walk(root);
|
|
130
|
+
return entries;
|
|
131
|
+
}
|
|
132
|
+
function ensureDirectory(FS, path) {
|
|
133
|
+
if (!FS.analyzePath(path).exists)
|
|
134
|
+
FS.mkdirTree(path);
|
|
135
|
+
}
|
|
136
|
+
function writeDataDirEntries(FS, entries, root = PGDATA) {
|
|
137
|
+
ensureDirectory(FS, root);
|
|
138
|
+
for (const entry of entries) {
|
|
139
|
+
const path = `${root}${entry.path}`;
|
|
140
|
+
if (entry.type === "directory") {
|
|
141
|
+
ensureDirectory(FS, path);
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
ensureDirectory(FS, path.slice(0, path.lastIndexOf("/")));
|
|
145
|
+
FS.writeFile(path, entry.data);
|
|
146
|
+
const mtimeMs = entry.mtimeSeconds * 1000;
|
|
147
|
+
FS.utime(path, mtimeMs, mtimeMs);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
function writeDataDirFile(FS, path, data, root = PGDATA) {
|
|
151
|
+
const target = `${root}${path}`;
|
|
152
|
+
ensureDirectory(FS, target.slice(0, target.lastIndexOf("/")));
|
|
153
|
+
FS.writeFile(target, data);
|
|
154
|
+
}
|
|
155
|
+
function readDataDirFile(FS, path, root = PGDATA) {
|
|
156
|
+
const target = `${root}${path}`;
|
|
157
|
+
if (!FS.analyzePath(target).exists)
|
|
158
|
+
return;
|
|
159
|
+
const stats = FS.stat(target);
|
|
160
|
+
if (!FS.isFile(stats.mode))
|
|
161
|
+
return;
|
|
162
|
+
return FS.readFile(target, { encoding: "binary" });
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// packages/pgwasm-c/src/host/extensions.ts
|
|
166
|
+
import { gunzipIfCompressed, readTar } from "@pgxsinkit/pgwasm/build";
|
|
167
|
+
async function fetchExtensionBundle(extension) {
|
|
168
|
+
const response = await fetch(extension.bundle);
|
|
169
|
+
if (!response.ok) {
|
|
170
|
+
throw new Error(`Could not load the "${extension.name}" extension bundle ${extension.bundle.href}: HTTP ${response.status}`);
|
|
171
|
+
}
|
|
172
|
+
const bytes = await gunzipIfCompressed(new Uint8Array(await response.arrayBuffer()));
|
|
173
|
+
return readTar(bytes);
|
|
174
|
+
}
|
|
175
|
+
function writeFile(FS, path, data) {
|
|
176
|
+
const directory = path.slice(0, path.lastIndexOf("/"));
|
|
177
|
+
if (!FS.analyzePath(directory).exists)
|
|
178
|
+
FS.mkdirTree(directory);
|
|
179
|
+
FS.writeFile(path, data);
|
|
180
|
+
}
|
|
181
|
+
async function installExtensionFiles(module, bundles, log) {
|
|
182
|
+
const FS = module.FS;
|
|
183
|
+
const preloads = [];
|
|
184
|
+
for (const bundle of bundles) {
|
|
185
|
+
const entries = [...bundle].sort((a, b) => a.name > b.name ? 1 : a.name < b.name ? -1 : 0);
|
|
186
|
+
for (const entry of entries) {
|
|
187
|
+
const path = `${PG_ROOT}/${entry.name}`.replace(/\/+$/, "");
|
|
188
|
+
if (entry.type === "directory") {
|
|
189
|
+
if (!FS.analyzePath(path).exists)
|
|
190
|
+
FS.mkdirTree(path);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (entry.name.startsWith("."))
|
|
194
|
+
continue;
|
|
195
|
+
if (entry.name.endsWith(".so")) {
|
|
196
|
+
const directory = path.slice(0, path.lastIndexOf("/"));
|
|
197
|
+
const soName = path.slice(path.lastIndexOf("/") + 1);
|
|
198
|
+
if (!FS.analyzePath(directory).exists)
|
|
199
|
+
FS.mkdirTree(directory);
|
|
200
|
+
log(`pgwasm-c: preloading ${path}`);
|
|
201
|
+
preloads.push(new Promise((resolve) => {
|
|
202
|
+
FS.createPreloadedFile(directory, soName, entry.data, true, true, () => resolve(), () => {
|
|
203
|
+
log(`pgwasm-c: preloading ${path} failed; installing the plain file`);
|
|
204
|
+
writeFile(FS, path, entry.data);
|
|
205
|
+
resolve();
|
|
206
|
+
}, false);
|
|
207
|
+
}));
|
|
208
|
+
} else {
|
|
209
|
+
writeFile(FS, path, entry.data);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
await Promise.all(preloads);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// packages/pgwasm-c/src/host/command-line.ts
|
|
217
|
+
function commandWords(command) {
|
|
218
|
+
const words = [];
|
|
219
|
+
let current = "";
|
|
220
|
+
let inWord = false;
|
|
221
|
+
let index = 0;
|
|
222
|
+
const end = command.length;
|
|
223
|
+
const finishWord = () => {
|
|
224
|
+
if (inWord)
|
|
225
|
+
words.push(current);
|
|
226
|
+
current = "";
|
|
227
|
+
inWord = false;
|
|
228
|
+
};
|
|
229
|
+
while (index < end) {
|
|
230
|
+
const char = command[index] ?? "";
|
|
231
|
+
if (char === "'") {
|
|
232
|
+
const close = command.indexOf("'", index + 1);
|
|
233
|
+
if (close === -1)
|
|
234
|
+
throw new SyntaxError(`unterminated ' in command line: ${command}`);
|
|
235
|
+
current += command.slice(index + 1, close);
|
|
236
|
+
inWord = true;
|
|
237
|
+
index = close + 1;
|
|
238
|
+
} else if (char === '"') {
|
|
239
|
+
inWord = true;
|
|
240
|
+
index++;
|
|
241
|
+
while (index < end && command[index] !== '"') {
|
|
242
|
+
const inner = command[index] ?? "";
|
|
243
|
+
const next = command[index + 1];
|
|
244
|
+
if (inner === "\\" && next !== undefined && '"\\$`'.includes(next)) {
|
|
245
|
+
current += next;
|
|
246
|
+
index += 2;
|
|
247
|
+
} else {
|
|
248
|
+
current += inner;
|
|
249
|
+
index++;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (index >= end)
|
|
253
|
+
throw new SyntaxError(`unterminated " in command line: ${command}`);
|
|
254
|
+
index++;
|
|
255
|
+
} else if (char === "\\") {
|
|
256
|
+
const next = command[index + 1];
|
|
257
|
+
if (next !== undefined)
|
|
258
|
+
current += next;
|
|
259
|
+
inWord = true;
|
|
260
|
+
index += 2;
|
|
261
|
+
} else if (/\s/.test(char)) {
|
|
262
|
+
finishWord();
|
|
263
|
+
index++;
|
|
264
|
+
} else if ("<>|&;()".includes(char)) {
|
|
265
|
+
break;
|
|
266
|
+
} else {
|
|
267
|
+
current += char;
|
|
268
|
+
inWord = true;
|
|
269
|
+
index++;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
finishWord();
|
|
273
|
+
return words;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// packages/pgwasm-c/src/host/exit-code.ts
|
|
277
|
+
function hostProcess() {
|
|
278
|
+
return globalThis.process;
|
|
279
|
+
}
|
|
280
|
+
function preservingExitCode(fn) {
|
|
281
|
+
const proc = hostProcess();
|
|
282
|
+
if (proc === undefined)
|
|
283
|
+
return fn();
|
|
284
|
+
const before = proc.exitCode;
|
|
285
|
+
try {
|
|
286
|
+
return fn();
|
|
287
|
+
} finally {
|
|
288
|
+
if (proc.exitCode !== before)
|
|
289
|
+
proc.exitCode = before ?? 0;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// packages/pgwasm-c/src/host/initdb.ts
|
|
294
|
+
var INITDB_ARGS = [
|
|
295
|
+
"--allow-group-access",
|
|
296
|
+
"--encoding",
|
|
297
|
+
"UTF8",
|
|
298
|
+
"--locale=C.UTF-8",
|
|
299
|
+
"--locale-provider=libc",
|
|
300
|
+
"--auth=trust"
|
|
301
|
+
];
|
|
302
|
+
function assert(condition, message) {
|
|
303
|
+
if (!condition)
|
|
304
|
+
throw new Error(message);
|
|
305
|
+
}
|
|
306
|
+
async function runInitdb({
|
|
307
|
+
createInitdbModule,
|
|
308
|
+
postgres,
|
|
309
|
+
initdbWasm,
|
|
310
|
+
debug,
|
|
311
|
+
onCommand
|
|
312
|
+
}) {
|
|
313
|
+
const log = (...args) => {
|
|
314
|
+
if (debug > 0)
|
|
315
|
+
console.log("initdb:", ...args);
|
|
316
|
+
};
|
|
317
|
+
const pg = postgres.module;
|
|
318
|
+
let needToCallPgMain = false;
|
|
319
|
+
let postgresArgs = [];
|
|
320
|
+
let pgMainResult = 0;
|
|
321
|
+
let initdbStdinFd = -1;
|
|
322
|
+
let initdbStdoutFd = -1;
|
|
323
|
+
let stderr = "";
|
|
324
|
+
let stdout = "";
|
|
325
|
+
const pristineHeap = pg.HEAPU8.slice();
|
|
326
|
+
const callPgMain = (args) => {
|
|
327
|
+
const [program, ...rest] = args;
|
|
328
|
+
assert(program === POSTGRES_EXE_PATH, `initdb tried to execute ${String(program)}`);
|
|
329
|
+
pg.HEAPU8.set(pristineHeap);
|
|
330
|
+
log("executing postgres with", rest);
|
|
331
|
+
const result = postgres.callMain(rest);
|
|
332
|
+
postgresArgs = [];
|
|
333
|
+
return result;
|
|
334
|
+
};
|
|
335
|
+
const commandArgs = (module, pointer) => {
|
|
336
|
+
const command = module.UTF8ToString(pointer);
|
|
337
|
+
onCommand?.(command);
|
|
338
|
+
return commandWords(command);
|
|
339
|
+
};
|
|
340
|
+
let rejectInstantiation = () => {
|
|
341
|
+
return;
|
|
342
|
+
};
|
|
343
|
+
const instantiationFailed = new Promise((_, reject) => {
|
|
344
|
+
rejectInstantiation = reject;
|
|
345
|
+
});
|
|
346
|
+
const initdb = await Promise.race([
|
|
347
|
+
createInitdbModule({
|
|
348
|
+
thisProgram: INITDB_EXE_PATH,
|
|
349
|
+
arguments: [...INITDB_ARGS],
|
|
350
|
+
noExitRuntime: false,
|
|
351
|
+
stdin: () => null,
|
|
352
|
+
print: (text) => {
|
|
353
|
+
stdout += text;
|
|
354
|
+
log("stdout", text);
|
|
355
|
+
},
|
|
356
|
+
printErr: (text) => {
|
|
357
|
+
stderr += text;
|
|
358
|
+
log("stderr", text);
|
|
359
|
+
},
|
|
360
|
+
instantiateWasm: (imports, successCallback) => {
|
|
361
|
+
WebAssembly.instantiate(initdbWasm, imports).then((instance) => successCallback(instance, initdbWasm), (error) => rejectInstantiation(error));
|
|
362
|
+
return {};
|
|
363
|
+
},
|
|
364
|
+
preRun: [
|
|
365
|
+
(module) => {
|
|
366
|
+
const env = module.ENV;
|
|
367
|
+
env["PGDATA"] = PGDATA;
|
|
368
|
+
env["HOME"] = "/home/postgres";
|
|
369
|
+
env["USER"] = "postgres";
|
|
370
|
+
env["LOGNAME"] = "postgres";
|
|
371
|
+
env["ICU_DATA"] = ICU_DATA_PATH;
|
|
372
|
+
},
|
|
373
|
+
(module) => {
|
|
374
|
+
module.onRuntimeInitialized = () => {
|
|
375
|
+
module._pgl_set_system_fn(module.addFunction((command) => {
|
|
376
|
+
postgresArgs = commandArgs(module, command);
|
|
377
|
+
return callPgMain(postgresArgs);
|
|
378
|
+
}, "pi"));
|
|
379
|
+
module._pgl_set_popen_fn(module.addFunction((command, mode) => {
|
|
380
|
+
const openMode = module.UTF8ToString(mode);
|
|
381
|
+
postgresArgs = commandArgs(module, command);
|
|
382
|
+
if (openMode === "r") {
|
|
383
|
+
pgMainResult = callPgMain(postgresArgs);
|
|
384
|
+
return initdbStdinFd;
|
|
385
|
+
}
|
|
386
|
+
if (openMode === "w") {
|
|
387
|
+
needToCallPgMain = true;
|
|
388
|
+
return initdbStdoutFd;
|
|
389
|
+
}
|
|
390
|
+
throw new Error(`Unexpected popen mode ${openMode}`);
|
|
391
|
+
}, "ppi"));
|
|
392
|
+
module._pgl_set_pclose_fn(module.addFunction((stream) => {
|
|
393
|
+
if (stream === initdbStdinFd || stream === initdbStdoutFd) {
|
|
394
|
+
if (needToCallPgMain) {
|
|
395
|
+
needToCallPgMain = false;
|
|
396
|
+
pgMainResult = callPgMain(postgresArgs);
|
|
397
|
+
}
|
|
398
|
+
return pgMainResult;
|
|
399
|
+
}
|
|
400
|
+
return module._pclose(stream);
|
|
401
|
+
}, "pi"));
|
|
402
|
+
pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDIN_PATH), pg.stringToUTF8OnStack("r"), 0);
|
|
403
|
+
pg._pgl_freopen(pg.stringToUTF8OnStack(PG_STDOUT_PATH), pg.stringToUTF8OnStack("w"), 1);
|
|
404
|
+
initdbStdinFd = module._fopen(module.stringToUTF8OnStack(PG_STDOUT_PATH), module.stringToUTF8OnStack("r"));
|
|
405
|
+
initdbStdoutFd = module._fopen(module.stringToUTF8OnStack(PG_STDIN_PATH), module.stringToUTF8OnStack("w"));
|
|
406
|
+
};
|
|
407
|
+
},
|
|
408
|
+
(module) => {
|
|
409
|
+
module.FS.mkdir(PG_ROOT);
|
|
410
|
+
module.FS.mount(module.PROXYFS, { root: PG_ROOT, fs: pg.FS }, PG_ROOT);
|
|
411
|
+
}
|
|
412
|
+
]
|
|
413
|
+
}),
|
|
414
|
+
instantiationFailed
|
|
415
|
+
]);
|
|
416
|
+
log("running initdb with", INITDB_ARGS);
|
|
417
|
+
const exitCode = preservingExitCode(() => initdb.callMain([...INITDB_ARGS]));
|
|
418
|
+
return { exitCode, stderr, stdout };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
// packages/pgwasm-c/src/host/mounts/file.ts
|
|
422
|
+
class FileMount {
|
|
423
|
+
#path;
|
|
424
|
+
#root;
|
|
425
|
+
constructor(path) {
|
|
426
|
+
this.#path = path;
|
|
427
|
+
}
|
|
428
|
+
async acquire() {
|
|
429
|
+
const [{ mkdirSync }, { resolve }] = await Promise.all([import("fs"), import("path")]);
|
|
430
|
+
this.#root = resolve(this.#path);
|
|
431
|
+
mkdirSync(this.#root, { recursive: true });
|
|
432
|
+
}
|
|
433
|
+
get preRun() {
|
|
434
|
+
return (module) => {
|
|
435
|
+
if (this.#root === undefined)
|
|
436
|
+
throw new Error("the file mount was not acquired");
|
|
437
|
+
module.FS.mkdir(PGDATA);
|
|
438
|
+
module.FS.mount(module.FS.filesystems.NODEFS, { root: this.#root }, PGDATA);
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
async initialSync() {}
|
|
442
|
+
async persist() {}
|
|
443
|
+
async close(module) {
|
|
444
|
+
module?.FS.quit();
|
|
445
|
+
}
|
|
446
|
+
async cleanupFailedInit() {}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// packages/pgwasm-c/src/host/mounts/idb.ts
|
|
450
|
+
import { StorageInUseError, UnsupportedFeatureError } from "@pgxsinkit/pgwasm";
|
|
451
|
+
function idbDatabaseName(name) {
|
|
452
|
+
return `${PG_ROOT}/${name}`;
|
|
453
|
+
}
|
|
454
|
+
function idbLockName(name) {
|
|
455
|
+
return `pgwasm-idbfs:${idbDatabaseName(name)}`;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
class IdbMount {
|
|
459
|
+
#name;
|
|
460
|
+
#releaseHeldLock;
|
|
461
|
+
#lockRequest;
|
|
462
|
+
constructor(name) {
|
|
463
|
+
this.#name = name;
|
|
464
|
+
}
|
|
465
|
+
get #mountPoint() {
|
|
466
|
+
return idbDatabaseName(this.#name);
|
|
467
|
+
}
|
|
468
|
+
async acquire() {
|
|
469
|
+
const locks = globalThis.navigator?.locks;
|
|
470
|
+
if (!locks) {
|
|
471
|
+
throw new UnsupportedFeatureError("IndexedDB storage needs the Web Locks API, which this context lacks.");
|
|
472
|
+
}
|
|
473
|
+
let resolveAcquired;
|
|
474
|
+
let rejectAcquired;
|
|
475
|
+
const acquired = new Promise((resolve, reject) => {
|
|
476
|
+
resolveAcquired = resolve;
|
|
477
|
+
rejectAcquired = reject;
|
|
478
|
+
});
|
|
479
|
+
let releaseLock;
|
|
480
|
+
const held = new Promise((resolve) => {
|
|
481
|
+
releaseLock = resolve;
|
|
482
|
+
});
|
|
483
|
+
const lockRequest = locks.request(idbLockName(this.#name), { mode: "exclusive", ifAvailable: true }, async (lock) => {
|
|
484
|
+
resolveAcquired(lock !== null);
|
|
485
|
+
if (lock !== null)
|
|
486
|
+
await held;
|
|
487
|
+
});
|
|
488
|
+
this.#lockRequest = lockRequest;
|
|
489
|
+
lockRequest.catch(rejectAcquired);
|
|
490
|
+
if (!await acquired) {
|
|
491
|
+
await lockRequest;
|
|
492
|
+
this.#lockRequest = undefined;
|
|
493
|
+
throw new StorageInUseError(`The IndexedDB store "${this.#name}" is already open.`);
|
|
494
|
+
}
|
|
495
|
+
this.#releaseHeldLock = releaseLock;
|
|
496
|
+
}
|
|
497
|
+
get preRun() {
|
|
498
|
+
return (module) => {
|
|
499
|
+
const FS = module.FS;
|
|
500
|
+
if (!FS.analyzePath(this.#mountPoint).exists)
|
|
501
|
+
FS.mkdirTree(this.#mountPoint);
|
|
502
|
+
FS.mount(FS.filesystems.IDBFS, {}, this.#mountPoint);
|
|
503
|
+
FS.symlink(this.#mountPoint, PGDATA);
|
|
504
|
+
};
|
|
505
|
+
}
|
|
506
|
+
async initialSync(module) {
|
|
507
|
+
await this.#syncfs(module, true);
|
|
508
|
+
}
|
|
509
|
+
async persist(module) {
|
|
510
|
+
await this.#syncfs(module, false);
|
|
511
|
+
}
|
|
512
|
+
async close(module) {
|
|
513
|
+
await this.#closeAndRelease(module);
|
|
514
|
+
}
|
|
515
|
+
async cleanupFailedInit(module) {
|
|
516
|
+
await this.#closeAndRelease(module);
|
|
517
|
+
}
|
|
518
|
+
async#closeAndRelease(module) {
|
|
519
|
+
try {
|
|
520
|
+
if (module) {
|
|
521
|
+
module.FS.filesystems.IDBFS.dbs[this.#mountPoint]?.close();
|
|
522
|
+
module.FS.quit();
|
|
523
|
+
}
|
|
524
|
+
} finally {
|
|
525
|
+
const release = this.#releaseHeldLock;
|
|
526
|
+
const request = this.#lockRequest;
|
|
527
|
+
this.#releaseHeldLock = undefined;
|
|
528
|
+
this.#lockRequest = undefined;
|
|
529
|
+
release?.();
|
|
530
|
+
await request;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
async#syncfs(module, populate) {
|
|
534
|
+
const timestampFloor = Date.now();
|
|
535
|
+
await new Promise((resolve, reject) => {
|
|
536
|
+
module.FS.syncfs(populate, (error) => {
|
|
537
|
+
if (error) {
|
|
538
|
+
reject(error instanceof Error ? error : new Error(`IDBFS sync failed: ${JSON.stringify(error)}`));
|
|
539
|
+
} else
|
|
540
|
+
resolve();
|
|
541
|
+
});
|
|
542
|
+
});
|
|
543
|
+
const waitStartedAt = performance.now();
|
|
544
|
+
while (Date.now() === timestampFloor) {
|
|
545
|
+
if (performance.now() - waitStartedAt >= 1000) {
|
|
546
|
+
throw new Error("IDBFS cannot guarantee a distinct MEMFS timestamp");
|
|
547
|
+
}
|
|
548
|
+
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// packages/pgwasm-c/src/host/mounts/memory.ts
|
|
554
|
+
class MemoryMount {
|
|
555
|
+
preRun = undefined;
|
|
556
|
+
async acquire() {}
|
|
557
|
+
async initialSync() {}
|
|
558
|
+
async persist() {}
|
|
559
|
+
async close(module) {
|
|
560
|
+
module?.FS.quit();
|
|
561
|
+
}
|
|
562
|
+
async cleanupFailedInit() {}
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// packages/pgwasm-c/src/host/vfs-mount.ts
|
|
566
|
+
import { ERRNO_CODES } from "@pgxsinkit/pgwasm/fs";
|
|
567
|
+
function asBytes(buffer) {
|
|
568
|
+
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
|
|
569
|
+
}
|
|
570
|
+
function createVfsFilesystem(module, vfs) {
|
|
571
|
+
const FS = module.FS;
|
|
572
|
+
const log = vfs.debug ? console.log : undefined;
|
|
573
|
+
const tryOperation = (fn, op, path) => {
|
|
574
|
+
try {
|
|
575
|
+
return fn();
|
|
576
|
+
} catch (error) {
|
|
577
|
+
if (error instanceof FS.ErrnoError)
|
|
578
|
+
throw error;
|
|
579
|
+
const code = error?.code;
|
|
580
|
+
const errno = !code ? ERRNO_CODES.EIO : code === "UNKNOWN" ? ERRNO_CODES.EINVAL : code;
|
|
581
|
+
const message = error?.message;
|
|
582
|
+
vfs.recordSyscallError(op, typeof path === "function" ? path() : path, typeof errno === "number" ? errno : -1, typeof message === "string" ? message : String(code ?? error));
|
|
583
|
+
throw new FS.ErrnoError(typeof errno === "number" ? errno : ERRNO_CODES.EIO);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
const realPath = (node) => {
|
|
587
|
+
const parts = [];
|
|
588
|
+
let current = node;
|
|
589
|
+
while (current.parent !== current) {
|
|
590
|
+
parts.push(current.name);
|
|
591
|
+
current = current.parent;
|
|
592
|
+
}
|
|
593
|
+
parts.push(current.mount.opts.root ?? "");
|
|
594
|
+
parts.reverse();
|
|
595
|
+
return parts.join("/");
|
|
596
|
+
};
|
|
597
|
+
const createNode = (parent, name, mode) => {
|
|
598
|
+
if (!FS.isDir(mode) && !FS.isFile(mode)) {
|
|
599
|
+
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
|
|
600
|
+
}
|
|
601
|
+
const node = FS.createNode(parent, name, mode);
|
|
602
|
+
node.node_ops = nodeOps;
|
|
603
|
+
node.stream_ops = streamOps;
|
|
604
|
+
return node;
|
|
605
|
+
};
|
|
606
|
+
const getMode = (path) => tryOperation(() => vfs.lstat(path).mode, "getMode", path);
|
|
607
|
+
const nodeOps = {
|
|
608
|
+
getattr(node) {
|
|
609
|
+
const path = realPath(node);
|
|
610
|
+
log?.("getattr", path);
|
|
611
|
+
return tryOperation(() => {
|
|
612
|
+
const stats = vfs.lstat(path);
|
|
613
|
+
return {
|
|
614
|
+
...stats,
|
|
615
|
+
dev: 0,
|
|
616
|
+
ino: node.id,
|
|
617
|
+
nlink: 1,
|
|
618
|
+
rdev: node.rdev,
|
|
619
|
+
atime: new Date(stats.atime),
|
|
620
|
+
mtime: new Date(stats.mtime),
|
|
621
|
+
ctime: new Date(stats.ctime)
|
|
622
|
+
};
|
|
623
|
+
}, "getattr", path);
|
|
624
|
+
},
|
|
625
|
+
setattr(node, attr) {
|
|
626
|
+
const path = realPath(node);
|
|
627
|
+
log?.("setattr", path, attr);
|
|
628
|
+
tryOperation(() => {
|
|
629
|
+
if (attr.mode !== undefined)
|
|
630
|
+
vfs.chmod(path, attr.mode);
|
|
631
|
+
if (attr.size !== undefined)
|
|
632
|
+
vfs.truncate(path, attr.size);
|
|
633
|
+
if (attr.timestamp !== undefined)
|
|
634
|
+
vfs.utimes(path, attr.timestamp, attr.timestamp);
|
|
635
|
+
}, "setattr", path);
|
|
636
|
+
},
|
|
637
|
+
lookup(parent, name) {
|
|
638
|
+
const path = `${realPath(parent)}/${name}`;
|
|
639
|
+
log?.("lookup", path);
|
|
640
|
+
return createNode(parent, name, getMode(path));
|
|
641
|
+
},
|
|
642
|
+
mknod(parent, name, mode) {
|
|
643
|
+
const node = createNode(parent, name, mode);
|
|
644
|
+
const path = realPath(node);
|
|
645
|
+
log?.("mknod", path, mode);
|
|
646
|
+
return tryOperation(() => {
|
|
647
|
+
if (FS.isDir(node.mode)) {
|
|
648
|
+
vfs.mkdir(path, { mode });
|
|
649
|
+
} else {
|
|
650
|
+
vfs.writeFile(path, "", { mode });
|
|
651
|
+
}
|
|
652
|
+
return node;
|
|
653
|
+
}, "mknod", path);
|
|
654
|
+
},
|
|
655
|
+
rename(oldNode, newDir, newName) {
|
|
656
|
+
const oldPath = realPath(oldNode);
|
|
657
|
+
const newPath = `${realPath(newDir)}/${newName}`;
|
|
658
|
+
log?.("rename", oldPath, newPath);
|
|
659
|
+
tryOperation(() => vfs.rename(oldPath, newPath), "rename", oldPath);
|
|
660
|
+
oldNode.name = newName;
|
|
661
|
+
},
|
|
662
|
+
unlink(parent, name) {
|
|
663
|
+
const path = `${realPath(parent)}/${name}`;
|
|
664
|
+
log?.("unlink", path);
|
|
665
|
+
try {
|
|
666
|
+
vfs.unlink(path);
|
|
667
|
+
} catch (error) {
|
|
668
|
+
const code = error?.code;
|
|
669
|
+
if (code) {
|
|
670
|
+
const message = error?.message;
|
|
671
|
+
vfs.recordSyscallError("unlink", path, typeof code === "number" ? code : -1, typeof message === "string" ? message : JSON.stringify(code));
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
},
|
|
675
|
+
rmdir(parent, name) {
|
|
676
|
+
const path = `${realPath(parent)}/${name}`;
|
|
677
|
+
log?.("rmdir", path);
|
|
678
|
+
tryOperation(() => vfs.rmdir(path), "rmdir", path);
|
|
679
|
+
},
|
|
680
|
+
readdir(node) {
|
|
681
|
+
const path = realPath(node);
|
|
682
|
+
log?.("readdir", path);
|
|
683
|
+
return tryOperation(() => vfs.readdir(path), "readdir", path);
|
|
684
|
+
},
|
|
685
|
+
symlink() {
|
|
686
|
+
throw new FS.ErrnoError(63);
|
|
687
|
+
},
|
|
688
|
+
readlink() {
|
|
689
|
+
throw new FS.ErrnoError(63);
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
const streamOps = {
|
|
693
|
+
open(stream) {
|
|
694
|
+
const path = realPath(stream.node);
|
|
695
|
+
log?.("open", path);
|
|
696
|
+
tryOperation(() => {
|
|
697
|
+
if (FS.isFile(stream.node.mode)) {
|
|
698
|
+
stream.shared.refcount = 1;
|
|
699
|
+
stream.nfd = vfs.open(path);
|
|
700
|
+
}
|
|
701
|
+
}, "open", path);
|
|
702
|
+
},
|
|
703
|
+
close(stream) {
|
|
704
|
+
log?.("close", realPath(stream.node));
|
|
705
|
+
tryOperation(() => {
|
|
706
|
+
if (FS.isFile(stream.node.mode) && stream.nfd !== undefined && --stream.shared.refcount === 0) {
|
|
707
|
+
vfs.close(stream.nfd);
|
|
708
|
+
}
|
|
709
|
+
}, "close", () => realPath(stream.node));
|
|
710
|
+
},
|
|
711
|
+
dup(stream) {
|
|
712
|
+
stream.shared.refcount++;
|
|
713
|
+
},
|
|
714
|
+
read(stream, buffer, offset, length, position) {
|
|
715
|
+
if (length === 0)
|
|
716
|
+
return 0;
|
|
717
|
+
const fd = stream.nfd ?? -1;
|
|
718
|
+
return tryOperation(() => vfs.read(fd, asBytes(buffer), offset, length, position), "read", () => realPath(stream.node));
|
|
719
|
+
},
|
|
720
|
+
write(stream, buffer, offset, length, position) {
|
|
721
|
+
const fd = stream.nfd ?? -1;
|
|
722
|
+
return tryOperation(() => vfs.write(fd, asBytes(buffer), offset, length, position), "write", () => realPath(stream.node));
|
|
723
|
+
},
|
|
724
|
+
llseek(stream, offset, whence) {
|
|
725
|
+
let position = offset;
|
|
726
|
+
if (whence === 1) {
|
|
727
|
+
position += stream.position;
|
|
728
|
+
} else if (whence === 2 && FS.isFile(stream.node.mode)) {
|
|
729
|
+
const fd = stream.nfd ?? -1;
|
|
730
|
+
tryOperation(() => {
|
|
731
|
+
position += vfs.fstat(fd).size;
|
|
732
|
+
}, "llseek", () => realPath(stream.node));
|
|
733
|
+
}
|
|
734
|
+
if (position < 0)
|
|
735
|
+
throw new FS.ErrnoError(ERRNO_CODES.EINVAL);
|
|
736
|
+
return position;
|
|
737
|
+
},
|
|
738
|
+
mmap() {
|
|
739
|
+
throw new FS.ErrnoError(ERRNO_CODES.ENODEV);
|
|
740
|
+
},
|
|
741
|
+
msync() {
|
|
742
|
+
return 0;
|
|
743
|
+
}
|
|
744
|
+
};
|
|
745
|
+
return {
|
|
746
|
+
mount() {
|
|
747
|
+
return createNode(null, "/", 16384 | 511);
|
|
748
|
+
},
|
|
749
|
+
syncfs(_mount, _populate, done) {
|
|
750
|
+
done(null);
|
|
751
|
+
},
|
|
752
|
+
createNode,
|
|
753
|
+
node_ops: nodeOps,
|
|
754
|
+
stream_ops: streamOps
|
|
755
|
+
};
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// packages/pgwasm-c/src/host/mounts/vfs.ts
|
|
759
|
+
class VfsMount {
|
|
760
|
+
#vfs;
|
|
761
|
+
constructor(vfs) {
|
|
762
|
+
this.#vfs = vfs;
|
|
763
|
+
}
|
|
764
|
+
async acquire() {}
|
|
765
|
+
get preRun() {
|
|
766
|
+
return (module) => {
|
|
767
|
+
module.FS.mkdir(PGDATA);
|
|
768
|
+
module.FS.mount(createVfsFilesystem(module, this.#vfs), {}, PGDATA);
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
async initialSync() {
|
|
772
|
+
await this.#vfs.initialSyncFs();
|
|
773
|
+
}
|
|
774
|
+
async persist(_module, relaxed) {
|
|
775
|
+
await this.#vfs.syncToFs(relaxed);
|
|
776
|
+
}
|
|
777
|
+
async close() {
|
|
778
|
+
await this.#vfs.closeFs();
|
|
779
|
+
}
|
|
780
|
+
async cleanupFailedInit() {
|
|
781
|
+
await this.#vfs.cleanupFailedInit();
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// packages/pgwasm-c/src/host/mounts/index.ts
|
|
786
|
+
function mountFor(storage) {
|
|
787
|
+
switch (storage.kind) {
|
|
788
|
+
case "memory":
|
|
789
|
+
return new MemoryMount;
|
|
790
|
+
case "idb":
|
|
791
|
+
return new IdbMount(storage.name);
|
|
792
|
+
case "file":
|
|
793
|
+
return new FileMount(storage.path);
|
|
794
|
+
case "vfs":
|
|
795
|
+
return new VfsMount(storage.vfs);
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
// packages/pgwasm-c/src/host/postgres-instance.ts
|
|
800
|
+
var POSTGRES_MAIN_LONGJMP = 100;
|
|
801
|
+
var PGLITE_EXIT_ALIVE = 99;
|
|
802
|
+
var INITIAL_MEMORY_PAGES = 2048;
|
|
803
|
+
var MAXIMUM_MEMORY_PAGES = 32768;
|
|
804
|
+
var DEFAULT_START_PARAMS = [
|
|
805
|
+
"--single",
|
|
806
|
+
"-F",
|
|
807
|
+
"-O",
|
|
808
|
+
"-j",
|
|
809
|
+
"-c",
|
|
810
|
+
"search_path=public",
|
|
811
|
+
"-c",
|
|
812
|
+
"exit_on_error=false",
|
|
813
|
+
"-c",
|
|
814
|
+
"log_checkpoints=false",
|
|
815
|
+
"-c",
|
|
816
|
+
"max_worker_processes=0",
|
|
817
|
+
"-c",
|
|
818
|
+
"max_parallel_workers=0",
|
|
819
|
+
"-c",
|
|
820
|
+
"max_parallel_workers_per_gather=0",
|
|
821
|
+
"-c",
|
|
822
|
+
"io_method=sync",
|
|
823
|
+
"-c",
|
|
824
|
+
"max_parallel_maintenance_workers=0"
|
|
825
|
+
];
|
|
826
|
+
function isEmscriptenUnwind(error) {
|
|
827
|
+
if (error === "unwind" || typeof error === "number")
|
|
828
|
+
return true;
|
|
829
|
+
if (typeof error !== "object" || error === null)
|
|
830
|
+
return false;
|
|
831
|
+
return error.constructor?.name === "EmscriptenSjLj";
|
|
832
|
+
}
|
|
833
|
+
var invalidBundleSize = (actual, expected) => new Error(`Invalid filesystem bundle size: ${actual} !== ${expected}`);
|
|
834
|
+
function exitStatusOf(error) {
|
|
835
|
+
if (typeof error !== "object" || error === null || error.name !== "ExitStatus") {
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
const status = error.status;
|
|
839
|
+
return typeof status === "number" ? status : -1;
|
|
840
|
+
}
|
|
841
|
+
function shadowStackOf(instance) {
|
|
842
|
+
const current = instance.exports["emscripten_stack_get_current"];
|
|
843
|
+
const restore = instance.exports["_emscripten_stack_restore"];
|
|
844
|
+
if (typeof current !== "function" || typeof restore !== "function") {
|
|
845
|
+
throw new Error("The Postgres module exports no emscripten_stack_get_current or _emscripten_stack_restore: the host cannot restore its stack after an error");
|
|
846
|
+
}
|
|
847
|
+
return {
|
|
848
|
+
save: () => current(),
|
|
849
|
+
restore: (pointer) => restore(pointer)
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
class PostgresInstance {
|
|
854
|
+
module;
|
|
855
|
+
#debug;
|
|
856
|
+
#stack;
|
|
857
|
+
#input = new Uint8Array(0);
|
|
858
|
+
#readOffset = 0;
|
|
859
|
+
#sink;
|
|
860
|
+
#blobReadSource;
|
|
861
|
+
#blobWritten;
|
|
862
|
+
#externalCommandStream = null;
|
|
863
|
+
#functionPointers = [];
|
|
864
|
+
#failed = false;
|
|
865
|
+
#exited = false;
|
|
866
|
+
#stderr = [];
|
|
867
|
+
constructor(module, debug, stack) {
|
|
868
|
+
this.module = module;
|
|
869
|
+
this.#debug = debug;
|
|
870
|
+
this.#stack = stack;
|
|
871
|
+
}
|
|
872
|
+
static async create(config) {
|
|
873
|
+
const [wasmModule, fsBundle] = await Promise.all([config.wasmModule, config.fsBundle]);
|
|
874
|
+
const { createPostgresModule, fsBundleBytes } = config.glue;
|
|
875
|
+
if (fsBundle.byteLength !== fsBundleBytes)
|
|
876
|
+
throw invalidBundleSize(fsBundle.byteLength, fsBundleBytes);
|
|
877
|
+
let host;
|
|
878
|
+
let stack;
|
|
879
|
+
const pendingHost = (module) => {
|
|
880
|
+
if (stack === undefined)
|
|
881
|
+
throw new Error("The Postgres module initialised before its wasm instance");
|
|
882
|
+
host ??= new PostgresInstance(module, config.debug, stack);
|
|
883
|
+
return host;
|
|
884
|
+
};
|
|
885
|
+
let rejectInstantiation = () => {
|
|
886
|
+
return;
|
|
887
|
+
};
|
|
888
|
+
const instantiationFailed = new Promise((_, reject) => {
|
|
889
|
+
rejectInstantiation = reject;
|
|
890
|
+
});
|
|
891
|
+
const log = (text) => {
|
|
892
|
+
if (config.debug > 0)
|
|
893
|
+
console.debug(text);
|
|
894
|
+
};
|
|
895
|
+
const logError = (text) => {
|
|
896
|
+
if (host)
|
|
897
|
+
host.#recordStderr(text);
|
|
898
|
+
if (config.debug > 0)
|
|
899
|
+
console.error(text);
|
|
900
|
+
};
|
|
901
|
+
const preRun = [
|
|
902
|
+
(module) => {
|
|
903
|
+
module.onRuntimeInitialized = () => pendingHost(module).#onRuntimeInitialized();
|
|
904
|
+
},
|
|
905
|
+
(module) => pendingHost(module).#registerBlobDevice(),
|
|
906
|
+
(module) => {
|
|
907
|
+
const env = module.ENV;
|
|
908
|
+
env["HOME"] = "/home/postgres";
|
|
909
|
+
env["USER"] = "postgres";
|
|
910
|
+
env["LOGNAME"] = "postgres";
|
|
911
|
+
env["PGDATA"] = PGDATA;
|
|
912
|
+
env["PGUSER"] = config.user;
|
|
913
|
+
env["PGDATABASE"] = config.database;
|
|
914
|
+
env["LANG"] = "en_US.UTF-8";
|
|
915
|
+
env["LC_COLLATE"] = "en_US.UTF-8";
|
|
916
|
+
env["LC_CTYPE"] = "en_US.UTF-8";
|
|
917
|
+
env["TZ"] = "UTC";
|
|
918
|
+
env["PGTZ"] = "UTC";
|
|
919
|
+
env["PGCLIENTENCODING"] = "UTF8";
|
|
920
|
+
env["ICU_DATA"] = ICU_DATA_PATH;
|
|
921
|
+
},
|
|
922
|
+
(module) => {
|
|
923
|
+
module.FS.chmod("/home/postgres/.pgpass", 384);
|
|
924
|
+
module.FS.chmod(INITDB_EXE_PATH, 365);
|
|
925
|
+
module.FS.chmod(POSTGRES_EXE_PATH, 365);
|
|
926
|
+
}
|
|
927
|
+
];
|
|
928
|
+
if (config.mountPreRun)
|
|
929
|
+
preRun.push(config.mountPreRun);
|
|
930
|
+
const overrides = {
|
|
931
|
+
thisProgram: POSTGRES_EXE_PATH,
|
|
932
|
+
arguments: config.debug > 0 ? ["-d", String(config.debug)] : [],
|
|
933
|
+
noExitRuntime: true,
|
|
934
|
+
wasmMemory: new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: MAXIMUM_MEMORY_PAGES }),
|
|
935
|
+
stdin: () => null,
|
|
936
|
+
print: log,
|
|
937
|
+
printErr: logError,
|
|
938
|
+
instantiateWasm: (imports, successCallback) => {
|
|
939
|
+
WebAssembly.instantiate(wasmModule, imports).then((instance) => {
|
|
940
|
+
try {
|
|
941
|
+
stack = shadowStackOf(instance);
|
|
942
|
+
} catch (error) {
|
|
943
|
+
rejectInstantiation(error);
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
successCallback(instance, wasmModule);
|
|
947
|
+
}, (error) => rejectInstantiation(error));
|
|
948
|
+
return {};
|
|
949
|
+
},
|
|
950
|
+
getPreloadedPackage: (name, size) => {
|
|
951
|
+
if (name !== "postgres.data")
|
|
952
|
+
throw new Error(`Unknown filesystem package: ${name}`);
|
|
953
|
+
if (fsBundle.byteLength !== size) {
|
|
954
|
+
const error = invalidBundleSize(fsBundle.byteLength, size);
|
|
955
|
+
rejectInstantiation(error);
|
|
956
|
+
throw error;
|
|
957
|
+
}
|
|
958
|
+
return fsBundle;
|
|
959
|
+
},
|
|
960
|
+
preRun
|
|
961
|
+
};
|
|
962
|
+
const module = await Promise.race([createPostgresModule(overrides), instantiationFailed]);
|
|
963
|
+
const instance = pendingHost(module);
|
|
964
|
+
config.onModule?.(module);
|
|
965
|
+
return instance;
|
|
966
|
+
}
|
|
967
|
+
#recordStderr(text) {
|
|
968
|
+
this.#stderr.push(text);
|
|
969
|
+
if (this.#stderr.length > 20)
|
|
970
|
+
this.#stderr.shift();
|
|
971
|
+
}
|
|
972
|
+
#log(...args) {
|
|
973
|
+
if (this.#debug > 0)
|
|
974
|
+
console.log(...args);
|
|
975
|
+
}
|
|
976
|
+
#addFunction(fn, signature) {
|
|
977
|
+
const pointer = this.module.addFunction(fn, signature);
|
|
978
|
+
this.#functionPointers.push(pointer);
|
|
979
|
+
return pointer;
|
|
980
|
+
}
|
|
981
|
+
#onRuntimeInitialized() {
|
|
982
|
+
const mod = this.module;
|
|
983
|
+
mod._pgl_set_system_fn(this.#addFunction((command) => {
|
|
984
|
+
this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);
|
|
985
|
+
return 1;
|
|
986
|
+
}, "pi"));
|
|
987
|
+
mod._pgl_set_popen_fn(this.#addFunction((command, mode) => {
|
|
988
|
+
this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));
|
|
989
|
+
return this.#externalCommandStream;
|
|
990
|
+
}, "ppp"));
|
|
991
|
+
mod._pgl_set_pclose_fn(this.#addFunction((stream) => {
|
|
992
|
+
if (stream !== this.#externalCommandStream)
|
|
993
|
+
throw new Error(`Unhandled pclose ${stream}`);
|
|
994
|
+
mod._fclose(stream);
|
|
995
|
+
this.#externalCommandStream = null;
|
|
996
|
+
}, "pi"));
|
|
997
|
+
const write = this.#addFunction((pointer, length) => {
|
|
998
|
+
this.#sink?.(this.module.HEAPU8.subarray(pointer, pointer + length));
|
|
999
|
+
return length;
|
|
1000
|
+
}, "iii");
|
|
1001
|
+
const read = this.#addFunction((pointer, maxLength) => {
|
|
1002
|
+
const length = Math.min(this.#input.length - this.#readOffset, maxLength);
|
|
1003
|
+
this.module.HEAPU8.set(this.#input.subarray(this.#readOffset, this.#readOffset + length), pointer);
|
|
1004
|
+
this.#readOffset += length;
|
|
1005
|
+
return length;
|
|
1006
|
+
}, "iii");
|
|
1007
|
+
mod._pgl_set_rw_cbs(read, write);
|
|
1008
|
+
}
|
|
1009
|
+
#handleExternalCommand(command, mode) {
|
|
1010
|
+
if (command.startsWith("locale -a") && mode === "r") {
|
|
1011
|
+
return this.module._fopen(this.module.stringToUTF8OnStack(LOCALE_LIST_PATH), this.module.stringToUTF8OnStack(mode));
|
|
1012
|
+
}
|
|
1013
|
+
throw new Error(`Unhandled external command: ${command}`);
|
|
1014
|
+
}
|
|
1015
|
+
#registerBlobDevice() {
|
|
1016
|
+
const FS = this.module.FS;
|
|
1017
|
+
const device = FS.makedev(64, 0);
|
|
1018
|
+
FS.registerDevice(device, {
|
|
1019
|
+
open: () => {
|
|
1020
|
+
return;
|
|
1021
|
+
},
|
|
1022
|
+
close: () => {
|
|
1023
|
+
return;
|
|
1024
|
+
},
|
|
1025
|
+
read: (_stream, buffer, offset, length, position) => {
|
|
1026
|
+
const contents = this.#blobReadSource;
|
|
1027
|
+
if (!contents)
|
|
1028
|
+
throw new Error("No /dev/blob File or Blob provided to read from");
|
|
1029
|
+
if (position >= contents.length)
|
|
1030
|
+
return 0;
|
|
1031
|
+
const size = Math.min(contents.length - position, length);
|
|
1032
|
+
buffer.set(contents.subarray(position, position + size), offset);
|
|
1033
|
+
return size;
|
|
1034
|
+
},
|
|
1035
|
+
write: (_stream, buffer, offset, length) => {
|
|
1036
|
+
this.#blobWritten ??= [];
|
|
1037
|
+
this.#blobWritten.push(new Uint8Array(buffer.subarray(offset, offset + length)));
|
|
1038
|
+
return length;
|
|
1039
|
+
},
|
|
1040
|
+
llseek: (stream, offset, whence) => {
|
|
1041
|
+
const contents = this.#blobReadSource;
|
|
1042
|
+
if (!contents)
|
|
1043
|
+
throw new Error("No /dev/blob File or Blob provided to llseek");
|
|
1044
|
+
let position = offset;
|
|
1045
|
+
if (whence === 1)
|
|
1046
|
+
position += stream.position;
|
|
1047
|
+
else if (whence === 2)
|
|
1048
|
+
position = contents.length;
|
|
1049
|
+
if (position < 0)
|
|
1050
|
+
throw new FS.ErrnoError(28);
|
|
1051
|
+
return position;
|
|
1052
|
+
}
|
|
1053
|
+
});
|
|
1054
|
+
FS.mkdev("/dev/blob", device);
|
|
1055
|
+
}
|
|
1056
|
+
setBlobReadSource(data) {
|
|
1057
|
+
this.#blobReadSource = data;
|
|
1058
|
+
}
|
|
1059
|
+
takeBlobWritten() {
|
|
1060
|
+
const written = this.#blobWritten;
|
|
1061
|
+
this.#blobWritten = undefined;
|
|
1062
|
+
return written;
|
|
1063
|
+
}
|
|
1064
|
+
callMain(args) {
|
|
1065
|
+
return preservingExitCode(() => this.module.callMain(args));
|
|
1066
|
+
}
|
|
1067
|
+
startSingleMode(startParams) {
|
|
1068
|
+
const mod = this.module;
|
|
1069
|
+
mod._pgl_setPGliteActive(1);
|
|
1070
|
+
this.callMain([...startParams, "-D", PGDATA, mod.ENV["PGDATABASE"] ?? "postgres"]);
|
|
1071
|
+
const exitStatus = mod._pgl_setPGliteExitStatus(-3);
|
|
1072
|
+
if (exitStatus !== PGLITE_EXIT_ALIVE) {
|
|
1073
|
+
const output = this.#stderr.join(`
|
|
1074
|
+
`).trim();
|
|
1075
|
+
throw new Error(`Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:
|
|
1076
|
+
${output}` : ""}`);
|
|
1077
|
+
}
|
|
1078
|
+
mod._pgl_startPGlite();
|
|
1079
|
+
}
|
|
1080
|
+
exchange(message, onData) {
|
|
1081
|
+
if (this.#failed)
|
|
1082
|
+
throw new Error("The C build's session failed and cannot be used again");
|
|
1083
|
+
if (message[0] === 88)
|
|
1084
|
+
return;
|
|
1085
|
+
this.#sink = onData;
|
|
1086
|
+
this.#input = message;
|
|
1087
|
+
this.#readOffset = 0;
|
|
1088
|
+
this.#stderr.length = 0;
|
|
1089
|
+
try {
|
|
1090
|
+
if (message[0] === 0) {
|
|
1091
|
+
this.#processStartupPacket();
|
|
1092
|
+
return;
|
|
1093
|
+
}
|
|
1094
|
+
this.#runMainLoop(message);
|
|
1095
|
+
} catch (error) {
|
|
1096
|
+
const status = exitStatusOf(error);
|
|
1097
|
+
if (status === undefined)
|
|
1098
|
+
throw error;
|
|
1099
|
+
this.#failed = true;
|
|
1100
|
+
const output = this.#stderr.join(`
|
|
1101
|
+
`).trim();
|
|
1102
|
+
throw new Error(`Postgres exited with status ${status} during an exchange: a FATAL error ended the C build's session${output ? `:
|
|
1103
|
+
${output}` : ""}`, { cause: error });
|
|
1104
|
+
} finally {
|
|
1105
|
+
this.#sink = undefined;
|
|
1106
|
+
this.#input = new Uint8Array(0);
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
#call(call) {
|
|
1110
|
+
const stack = this.#stack.save();
|
|
1111
|
+
try {
|
|
1112
|
+
return call();
|
|
1113
|
+
} catch (error) {
|
|
1114
|
+
this.#stack.restore(stack);
|
|
1115
|
+
throw error;
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
#processStartupPacket() {
|
|
1119
|
+
const mod = this.module;
|
|
1120
|
+
const result = this.#call(() => mod._ProcessStartupPacket(mod._pgl_getMyProcPort(), true, true));
|
|
1121
|
+
if (result !== 0)
|
|
1122
|
+
throw new Error("Cannot process the startup packet");
|
|
1123
|
+
this.#call(() => {
|
|
1124
|
+
mod._pgl_sendConnData();
|
|
1125
|
+
mod._pgl_pq_flush();
|
|
1126
|
+
});
|
|
1127
|
+
}
|
|
1128
|
+
#runMainLoop(message) {
|
|
1129
|
+
const mod = this.module;
|
|
1130
|
+
try {
|
|
1131
|
+
while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {
|
|
1132
|
+
const stack = this.#stack.save();
|
|
1133
|
+
try {
|
|
1134
|
+
mod._PostgresMainLoopOnce();
|
|
1135
|
+
} catch (error) {
|
|
1136
|
+
this.#stack.restore(stack);
|
|
1137
|
+
if (!isEmscriptenUnwind(error))
|
|
1138
|
+
throw error;
|
|
1139
|
+
if (mod._pgl_setPGliteExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {
|
|
1140
|
+
this.#call(() => mod._PostgresMainLongJmp());
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
this.#call(() => {
|
|
1145
|
+
mod._PostgresSendReadyForQueryIfNecessary();
|
|
1146
|
+
mod._pgl_pq_flush();
|
|
1147
|
+
});
|
|
1148
|
+
} catch (error) {
|
|
1149
|
+
this.#failed = true;
|
|
1150
|
+
throw error;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
shutdown() {
|
|
1154
|
+
const mod = this.module;
|
|
1155
|
+
try {
|
|
1156
|
+
preservingExitCode(() => {
|
|
1157
|
+
mod._pgl_setPGliteActive(0);
|
|
1158
|
+
this.#call(() => mod._pgl_run_atexit_funcs());
|
|
1159
|
+
});
|
|
1160
|
+
} catch (error) {
|
|
1161
|
+
const exit = error;
|
|
1162
|
+
if (!(exit.name === "ExitStatus" && exit.status === 0))
|
|
1163
|
+
throw error;
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
dispose(exitStatus) {
|
|
1167
|
+
if (this.#exited)
|
|
1168
|
+
return;
|
|
1169
|
+
this.#exited = true;
|
|
1170
|
+
for (const pointer of this.#functionPointers) {
|
|
1171
|
+
try {
|
|
1172
|
+
this.module.removeFunction(pointer);
|
|
1173
|
+
} catch {}
|
|
1174
|
+
}
|
|
1175
|
+
this.#functionPointers = [];
|
|
1176
|
+
try {
|
|
1177
|
+
preservingExitCode(() => this.module._emscripten_force_exit(exitStatus));
|
|
1178
|
+
} catch {}
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// packages/pgwasm-c/src/build.ts
|
|
1183
|
+
var C_BUILD_IDENTITY = {
|
|
1184
|
+
name: "c",
|
|
1185
|
+
dataFormat: ARTEFACT_RELEASE.dataFormat,
|
|
1186
|
+
claimsUnmarkedDirectories: true,
|
|
1187
|
+
release: ARTEFACT_RELEASE.name
|
|
1188
|
+
};
|
|
1189
|
+
var C_BUILD_CAPABILITIES = {
|
|
1190
|
+
sessions: 1,
|
|
1191
|
+
requiresCrossOriginIsolation: false,
|
|
1192
|
+
filesystems: ["memory", "idb", "file", "vfs"],
|
|
1193
|
+
synchronousExchange: true,
|
|
1194
|
+
blobDevice: true
|
|
1195
|
+
};
|
|
1196
|
+
|
|
1197
|
+
class CRunningPostgres {
|
|
1198
|
+
#instance;
|
|
1199
|
+
#mount;
|
|
1200
|
+
#sessionOpened = false;
|
|
1201
|
+
blob;
|
|
1202
|
+
constructor(instance, mount) {
|
|
1203
|
+
this.#instance = instance;
|
|
1204
|
+
this.#mount = mount;
|
|
1205
|
+
this.blob = {
|
|
1206
|
+
setReadSource: (data) => instance.setBlobReadSource(data),
|
|
1207
|
+
takeWritten: () => instance.takeBlobWritten()
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
async openSession() {
|
|
1211
|
+
if (this.#sessionOpened)
|
|
1212
|
+
throw new Error("The C build holds a single session, and it is open.");
|
|
1213
|
+
this.#sessionOpened = true;
|
|
1214
|
+
const instance = this.#instance;
|
|
1215
|
+
return {
|
|
1216
|
+
exchange: (message, onData) => instance.exchange(message, onData),
|
|
1217
|
+
onUnsolicited: undefined,
|
|
1218
|
+
close: async () => {}
|
|
1219
|
+
};
|
|
1220
|
+
}
|
|
1221
|
+
async persist(relaxed) {
|
|
1222
|
+
await this.#mount.persist(this.#instance.module, relaxed);
|
|
1223
|
+
}
|
|
1224
|
+
async readEntries() {
|
|
1225
|
+
return readDataDirEntries(this.#instance.module.FS);
|
|
1226
|
+
}
|
|
1227
|
+
async shutdown() {
|
|
1228
|
+
this.#instance.shutdown();
|
|
1229
|
+
}
|
|
1230
|
+
async release(options = {}) {
|
|
1231
|
+
try {
|
|
1232
|
+
if (options.afterFailedBoot)
|
|
1233
|
+
await this.#mount.cleanupFailedInit(this.#instance.module);
|
|
1234
|
+
else
|
|
1235
|
+
await this.#mount.close(this.#instance.module);
|
|
1236
|
+
} finally {
|
|
1237
|
+
this.#instance.dispose(options.afterFailedBoot ? 1 : 0);
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
class CMountedDataDirectory {
|
|
1243
|
+
#instance;
|
|
1244
|
+
#mount;
|
|
1245
|
+
#request;
|
|
1246
|
+
#resolved;
|
|
1247
|
+
#extensionBundles;
|
|
1248
|
+
constructor(instance, mount, request, resolved, extensionBundles) {
|
|
1249
|
+
this.#instance = instance;
|
|
1250
|
+
this.#mount = mount;
|
|
1251
|
+
this.#request = request;
|
|
1252
|
+
this.#resolved = resolved;
|
|
1253
|
+
this.#extensionBundles = extensionBundles;
|
|
1254
|
+
}
|
|
1255
|
+
get #FS() {
|
|
1256
|
+
return this.#instance.module.FS;
|
|
1257
|
+
}
|
|
1258
|
+
async readFile(path) {
|
|
1259
|
+
return readDataDirFile(this.#FS, path);
|
|
1260
|
+
}
|
|
1261
|
+
async createCluster() {
|
|
1262
|
+
const scratch = await PostgresInstance.create({
|
|
1263
|
+
glue: this.#resolved.artefacts,
|
|
1264
|
+
wasmModule: this.#resolved.postgresWasm(),
|
|
1265
|
+
fsBundle: this.#resolved.fsBundle(),
|
|
1266
|
+
user: this.#request.user,
|
|
1267
|
+
database: this.#request.database,
|
|
1268
|
+
debug: this.#request.debug
|
|
1269
|
+
});
|
|
1270
|
+
try {
|
|
1271
|
+
const result = await runInitdb({
|
|
1272
|
+
createInitdbModule: this.#resolved.artefacts.createInitdbModule,
|
|
1273
|
+
postgres: scratch,
|
|
1274
|
+
initdbWasm: await this.#resolved.initdbWasm(),
|
|
1275
|
+
debug: this.#request.debug,
|
|
1276
|
+
...this.#resolved.options.onInitdbCommand ? { onCommand: this.#resolved.options.onInitdbCommand } : {}
|
|
1277
|
+
});
|
|
1278
|
+
if (result.exitCode !== 0 && !result.stderr.includes("exists but is not empty")) {
|
|
1279
|
+
throw new Error(`initdb failed to create the data directory (exit ${result.exitCode}): ${result.stderr}`);
|
|
1280
|
+
}
|
|
1281
|
+
writeDataDirEntries(this.#FS, readDataDirEntries(scratch.module.FS));
|
|
1282
|
+
} finally {
|
|
1283
|
+
scratch.dispose(0);
|
|
1284
|
+
}
|
|
1285
|
+
}
|
|
1286
|
+
async writeEntries(entries) {
|
|
1287
|
+
writeDataDirEntries(this.#FS, entries);
|
|
1288
|
+
}
|
|
1289
|
+
async writeFile(path, data) {
|
|
1290
|
+
writeDataDirFile(this.#FS, path, data);
|
|
1291
|
+
}
|
|
1292
|
+
async persist() {
|
|
1293
|
+
await this.#mount.persist(this.#instance.module, false);
|
|
1294
|
+
}
|
|
1295
|
+
async start(options) {
|
|
1296
|
+
const log = (...args) => {
|
|
1297
|
+
if (this.#request.debug > 0)
|
|
1298
|
+
console.log(...args);
|
|
1299
|
+
};
|
|
1300
|
+
await installExtensionFiles(this.#instance.module, await this.#extensionBundles, log);
|
|
1301
|
+
this.#instance.startSingleMode([
|
|
1302
|
+
...DEFAULT_START_PARAMS,
|
|
1303
|
+
...this.#request.debug > 0 ? ["-d", String(this.#request.debug)] : [],
|
|
1304
|
+
...Object.entries(options.settings).flatMap(([name, value]) => ["-c", `${name}=${value}`])
|
|
1305
|
+
]);
|
|
1306
|
+
return new CRunningPostgres(this.#instance, this.#mount);
|
|
1307
|
+
}
|
|
1308
|
+
async release() {
|
|
1309
|
+
try {
|
|
1310
|
+
await this.#mount.cleanupFailedInit(this.#instance.module);
|
|
1311
|
+
} finally {
|
|
1312
|
+
this.#instance.dispose(1);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
function createCBuild(options = {}) {
|
|
1317
|
+
return createCBuildFrom(C_BUILD_IDENTITY, pinnedCBuildArtefacts, options);
|
|
1318
|
+
}
|
|
1319
|
+
function createCBuildFrom(identity, artefacts, options = {}) {
|
|
1320
|
+
const warmed = options.assets === undefined ? Promise.resolve(undefined) : options.assets.then((assets) => assets, () => {
|
|
1321
|
+
return;
|
|
1322
|
+
});
|
|
1323
|
+
const resolved = {
|
|
1324
|
+
artefacts,
|
|
1325
|
+
postgresWasm: async () => {
|
|
1326
|
+
const module = options.postgresWasmModule ?? (await warmed)?.postgresWasmModule;
|
|
1327
|
+
return module === undefined ? compileModule(artefacts.postgresWasm) : module;
|
|
1328
|
+
},
|
|
1329
|
+
initdbWasm: async () => {
|
|
1330
|
+
const module = options.initdbWasmModule ?? (await warmed)?.initdbWasmModule;
|
|
1331
|
+
return module === undefined ? compileModule(artefacts.initdbWasm) : module;
|
|
1332
|
+
},
|
|
1333
|
+
fsBundle: async () => {
|
|
1334
|
+
const bundle = options.fsBundle ?? (await warmed)?.fsBundle;
|
|
1335
|
+
return bundle === undefined ? loadBundle(artefacts.fsBundle) : bytesOf(bundle);
|
|
1336
|
+
},
|
|
1337
|
+
options
|
|
1338
|
+
};
|
|
1339
|
+
const prepared = Promise.allSettled([warmed, options.postgresWasmModule, options.fsBundle]).then(() => {
|
|
1340
|
+
return;
|
|
1341
|
+
});
|
|
1342
|
+
return {
|
|
1343
|
+
identity,
|
|
1344
|
+
capabilities: C_BUILD_CAPABILITIES,
|
|
1345
|
+
prepare: () => prepared,
|
|
1346
|
+
async boot(request) {
|
|
1347
|
+
const extensionBundles = Promise.all(request.extensions.map((extension) => fetchExtensionBundle(extension)));
|
|
1348
|
+
extensionBundles.catch(() => {
|
|
1349
|
+
return;
|
|
1350
|
+
});
|
|
1351
|
+
const assets = await warmed;
|
|
1352
|
+
if (options.postgresWasmModule === undefined && assets?.postgresWasmModule === undefined) {
|
|
1353
|
+
prefetch(artefacts.postgresWasm);
|
|
1354
|
+
}
|
|
1355
|
+
if (options.initdbWasmModule === undefined && assets?.initdbWasmModule === undefined) {
|
|
1356
|
+
prefetch(artefacts.initdbWasm);
|
|
1357
|
+
}
|
|
1358
|
+
const mount = mountFor(request.storage);
|
|
1359
|
+
await mount.acquire();
|
|
1360
|
+
let instance;
|
|
1361
|
+
try {
|
|
1362
|
+
instance = await PostgresInstance.create({
|
|
1363
|
+
glue: artefacts,
|
|
1364
|
+
wasmModule: resolved.postgresWasm(),
|
|
1365
|
+
fsBundle: resolved.fsBundle(),
|
|
1366
|
+
user: request.user,
|
|
1367
|
+
database: request.database,
|
|
1368
|
+
debug: request.debug,
|
|
1369
|
+
...mount.preRun ? { mountPreRun: mount.preRun } : {},
|
|
1370
|
+
...options.onPostgresModule ? { onModule: options.onPostgresModule } : {}
|
|
1371
|
+
});
|
|
1372
|
+
await mount.initialSync(instance.module);
|
|
1373
|
+
} catch (error) {
|
|
1374
|
+
try {
|
|
1375
|
+
await mount.cleanupFailedInit(instance?.module);
|
|
1376
|
+
} catch {}
|
|
1377
|
+
instance?.dispose(1);
|
|
1378
|
+
throw error;
|
|
1379
|
+
}
|
|
1380
|
+
return new CMountedDataDirectory(instance, mount, request, resolved, extensionBundles);
|
|
1381
|
+
}
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
var cBuild = createCBuild();
|
|
1385
|
+
export {
|
|
1386
|
+
C_BUILD_IDENTITY,
|
|
1387
|
+
cBuild,
|
|
1388
|
+
cBuildArtefacts,
|
|
1389
|
+
createCBuild,
|
|
1390
|
+
idbDatabaseName
|
|
1391
|
+
};
|
|
1392
|
+
|
|
1393
|
+
//# debugId=C0FF4DA1F6B3610364756E2164756E21
|