@pgxsinkit/pgwasm-c 0.6.2 → 0.6.3
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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vfs-mount.d.ts","sources":["../../src/host/vfs-mount.ts"],"names":[],"mappings":"AAGA,OAAO,
|
|
1
|
+
{"version":3,"file":"vfs-mount.d.ts","sources":["../../src/host/vfs-mount.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,cAAc,EAAe,MAAM,sBAAsB,CAAC;AAExE,OAAO,KAAK,EAAE,wBAAwB,EAAoC,cAAc,EAAE,MAAM,cAAc,CAAC;AAgB/G;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,EAAE,cAAc,GAAG,wBAAwB,CA6OzG"}
|
package/dist/index.js.map
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PGDATA } from \"../paths\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/**\n * The data directory as a directory on disk, through Emscripten's NODEFS (Bun). Writes go straight to\n * the host filesystem, so there is nothing to persist; closing flushes the runtime's streams.\n */\nexport class FileMount implements StorageMount {\n readonly #path: string;\n #root: string | undefined;\n\n constructor(path: string) {\n this.#path = path;\n }\n\n async acquire(): Promise<void> {\n // Loaded lazily so the browser bundle carries no static `node:` import; this storage is Bun's.\n const [{ mkdirSync }, { resolve }] = await Promise.all([import(\"node:fs\"), import(\"node:path\")]);\n this.#root = resolve(this.#path);\n mkdirSync(this.#root, { recursive: true });\n }\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n if (this.#root === undefined) throw new Error(\"the file mount was not acquired\");\n module.FS.mkdir(PGDATA);\n module.FS.mount(module.FS.filesystems.NODEFS, { root: this.#root }, PGDATA);\n };\n }\n\n async initialSync(): Promise<void> {}\n\n async persist(): Promise<void> {}\n\n async close(module: PostgresModule | undefined): Promise<void> {\n module?.FS.quit();\n }\n\n async cleanupFailedInit(): Promise<void> {}\n}\n",
|
|
15
15
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport { StorageInUseError, UnsupportedFeatureError } from \"@pgxsinkit/pgwasm\";\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PG_ROOT, PGDATA } from \"../paths\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/**\n * The IndexedDB database behind `idb://<name>`: `/pgwasm/<name>`. IDBFS names the database after its\n * mount point, so this is both. It is a store's identity: a change to it (as the root rename in 18.6.2)\n * opens a new, empty store and leaves the old database behind, never deleted here.\n */\nexport function idbDatabaseName(name: string): string {\n return `${PG_ROOT}/${name}`;\n}\n\n/** The Web Lock that guards `idb://<name>` against a second open: `pgwasm-idbfs:/pgwasm/<name>`. */\nexport function idbLockName(name: string): string {\n return `pgwasm-idbfs:${idbDatabaseName(name)}`;\n}\n\n/** The slice of the Web Locks API this mount uses. */\ninterface LockManagerLike {\n request(\n name: string,\n options: { mode: \"exclusive\"; ifAvailable: boolean },\n callback: (lock: unknown) => Promise<void>,\n ): Promise<void>;\n}\n\n/**\n * The data directory in IndexedDB, through Emscripten's IDBFS: the whole directory lives in memory and\n * is synced to an IndexedDB database named after its mount point, `/pgwasm/<name>`.\n *\n * One open per database: a Web Lock named after the database guards it, so a second open fails with\n * {@link StorageInUseError}. Both names come from {@link idbDatabaseName} and {@link idbLockName} only.\n *\n * Deliberately no exclusive persist: a relaxed persist is a background snapshot that statements run\n * beside (measured: an exclusive lane made relaxed as slow as strict, ~80 ms per statement). A crash\n * during a snapshot can lose its tail, which is relaxed durability's documented loss window.\n */\nexport class IdbMount implements StorageMount {\n readonly #name: string;\n #releaseHeldLock: (() => void) | undefined;\n #lockRequest: Promise<void> | undefined;\n\n constructor(name: string) {\n this.#name = name;\n }\n\n get #mountPoint(): string {\n return idbDatabaseName(this.#name);\n }\n\n async acquire(): Promise<void> {\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks;\n if (!locks) {\n throw new UnsupportedFeatureError(\"IndexedDB storage needs the Web Locks API, which this context lacks.\");\n }\n let resolveAcquired!: (acquired: boolean) => void;\n let rejectAcquired!: (reason: unknown) => void;\n const acquired = new Promise<boolean>((resolve, reject) => {\n resolveAcquired = resolve;\n rejectAcquired = reject;\n });\n let releaseLock!: () => void;\n const held = new Promise<void>((resolve) => {\n releaseLock = resolve;\n });\n const lockRequest = locks.request(\n idbLockName(this.#name),\n { mode: \"exclusive\", ifAvailable: true },\n async (lock) => {\n resolveAcquired(lock !== null);\n if (lock !== null) await held;\n },\n );\n this.#lockRequest = lockRequest;\n lockRequest.catch(rejectAcquired);\n if (!(await acquired)) {\n await lockRequest;\n this.#lockRequest = undefined;\n throw new StorageInUseError(`The IndexedDB store \"${this.#name}\" is already open.`);\n }\n this.#releaseHeldLock = releaseLock;\n }\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n const FS = module.FS;\n if (!FS.analyzePath(this.#mountPoint).exists) FS.mkdirTree(this.#mountPoint);\n // The pinned FS.doTruncate passes a legacy `timestamp` that MEMFS ignores. IDBFS compares\n // mtimes when syncing, so a successful truncate must mark its changed bytes for persistence.\n const doTruncate = FS.doTruncate.bind(FS);\n FS.doTruncate = (stream, node, length) => {\n doTruncate(stream, node, length);\n node.mtime = node.ctime = Date.now();\n };\n FS.mount(FS.filesystems.IDBFS, {}, this.#mountPoint);\n FS.symlink(this.#mountPoint, PGDATA);\n };\n }\n\n async initialSync(module: PostgresModule): Promise<void> {\n await this.#syncfs(module, true);\n }\n\n async persist(module: PostgresModule): Promise<void> {\n await this.#syncfs(module, false);\n }\n\n async close(module: PostgresModule | undefined): Promise<void> {\n await this.#closeAndRelease(module);\n }\n\n async cleanupFailedInit(module: PostgresModule | undefined): Promise<void> {\n await this.#closeAndRelease(module);\n }\n\n async #closeAndRelease(module: PostgresModule | undefined): Promise<void> {\n try {\n if (module) {\n // IDBDatabase.close() returns at once; the database closes when its transactions finish. Deleting\n // it right after needs the caller to wait for that.\n module.FS.filesystems.IDBFS.dbs[this.#mountPoint]?.close();\n module.FS.quit();\n }\n } finally {\n const release = this.#releaseHeldLock;\n const request = this.#lockRequest;\n this.#releaseHeldLock = undefined;\n this.#lockRequest = undefined;\n release?.();\n await request;\n }\n }\n\n async #syncfs(module: PostgresModule, populate: boolean): Promise<void> {\n const timestampFloor = Date.now();\n await new Promise<void>((resolve, reject) => {\n module.FS.syncfs(populate, (error) => {\n if (error) {\n reject(error instanceof Error ? error : new Error(`IDBFS sync failed: ${JSON.stringify(error)}`));\n } else resolve();\n });\n });\n // IDBFS compares millisecond mtimes only: a later write must not reuse a timestamp this sync may have\n // persisted. This spins only when the whole sync fit inside one clock millisecond.\n const waitStartedAt = performance.now();\n while (Date.now() === timestampFloor) {\n if (performance.now() - waitStartedAt >= 1000) {\n throw new Error(\"IDBFS cannot guarantee a distinct MEMFS timestamp\");\n }\n await new Promise((resolve) => setTimeout(resolve, 0));\n }\n }\n}\n",
|
|
16
16
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { PostgresModule } from \"../emscripten\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/** The data directory in the module's own memory (MEMFS): gone when the database closes. */\nexport class MemoryMount implements StorageMount {\n readonly preRun = undefined;\n\n async acquire(): Promise<void> {}\n\n async initialSync(): Promise<void> {}\n\n async persist(): Promise<void> {}\n\n async close(module: PostgresModule | undefined): Promise<void> {\n module?.FS.quit();\n }\n\n async cleanupFailedInit(): Promise<void> {}\n}\n",
|
|
17
|
-
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport {
|
|
17
|
+
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport { type BaseFilesystem, ERRNO_CODES } from \"@pgxsinkit/pgwasm/fs\";\n\nimport type { EmscriptenFilesystemType, EmscriptenNode, EmscriptenStream, PostgresModule } from \"./emscripten\";\n\n/** The node attributes Emscripten passes to `setattr`. */\ninterface NodeAttributes {\n mode?: number;\n size?: number;\n timestamp?: number;\n atime?: number;\n mtime?: number;\n}\n\n/** A Uint8Array over exactly the bytes of `buffer` (Emscripten hands the heap as an Int8Array). */\nfunction asBytes(buffer: ArrayBufferView): Uint8Array {\n return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);\n}\n\n/**\n * An Emscripten filesystem over a pgwasm {@link BaseFilesystem}: each node and stream operation becomes a\n * call on the filesystem, by path relative to the mount. A thrown error becomes an errno for Postgres —\n * its `code` when it has one, `EIO` when it does not (a DOMException, a plain Error from the storage):\n * rethrown, it would unwind the engine mid-syscall instead of failing that syscall.\n */\nexport function createVfsFilesystem(module: PostgresModule, vfs: BaseFilesystem): EmscriptenFilesystemType {\n const FS = module.FS;\n const log = vfs.debug ? console.log : undefined;\n\n const tryOperation = <T>(fn: () => T, op: string, path: string | (() => string)): T => {\n try {\n return fn();\n } catch (error) {\n // Already an errno (a filesystem may throw Emscripten's own error).\n if (error instanceof FS.ErrnoError) throw error;\n const code = (error as { code?: unknown } | null)?.code;\n const errno = !code ? ERRNO_CODES.EIO : code === \"UNKNOWN\" ? ERRNO_CODES.EINVAL : code;\n const message = (error as { message?: unknown } | null)?.message;\n vfs.recordSyscallError(\n op,\n typeof path === \"function\" ? path() : path,\n typeof errno === \"number\" ? errno : -1,\n typeof message === \"string\" ? message : String(code ?? error),\n );\n throw new FS.ErrnoError(typeof errno === \"number\" ? errno : ERRNO_CODES.EIO);\n }\n };\n\n const realPath = (node: EmscriptenNode): string => {\n const parts: string[] = [];\n let current = node;\n while (current.parent !== current) {\n parts.push(current.name);\n current = current.parent;\n }\n parts.push(current.mount.opts.root ?? \"\");\n parts.reverse();\n return parts.join(\"/\");\n };\n\n const createNode = (parent: EmscriptenNode | null, name: string, mode: number): EmscriptenNode => {\n if (!FS.isDir(mode) && !FS.isFile(mode)) {\n throw new FS.ErrnoError(ERRNO_CODES.EINVAL);\n }\n const node = FS.createNode(parent, name, mode);\n node.node_ops = nodeOps;\n node.stream_ops = streamOps;\n return node;\n };\n\n const getMode = (path: string): number => tryOperation(() => vfs.lstat(path).mode, \"getMode\", path);\n\n const nodeOps = {\n getattr(node: EmscriptenNode) {\n const path = realPath(node);\n log?.(\"getattr\", path);\n return tryOperation(\n () => {\n const stats = vfs.lstat(path);\n return {\n ...stats,\n dev: 0,\n ino: node.id,\n nlink: 1,\n rdev: node.rdev,\n atime: new Date(stats.atime),\n mtime: new Date(stats.mtime),\n ctime: new Date(stats.ctime),\n };\n },\n \"getattr\",\n path,\n );\n },\n setattr(node: EmscriptenNode, attr: NodeAttributes): void {\n const path = realPath(node);\n log?.(\"setattr\", path, attr);\n tryOperation(\n () => {\n if (attr.mode !== undefined) vfs.chmod(path, attr.mode);\n if (attr.size !== undefined) vfs.truncate(path, attr.size);\n const atime = attr.atime ?? attr.timestamp;\n const mtime = attr.mtime ?? attr.timestamp;\n if (atime !== undefined || mtime !== undefined) {\n const previous = atime === undefined || mtime === undefined ? vfs.lstat(path) : undefined;\n vfs.utimes(path, atime ?? previous!.atime, mtime ?? previous!.mtime);\n }\n },\n \"setattr\",\n path,\n );\n },\n lookup(parent: EmscriptenNode, name: string): EmscriptenNode {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"lookup\", path);\n return createNode(parent, name, getMode(path));\n },\n mknod(parent: EmscriptenNode, name: string, mode: number): EmscriptenNode {\n const node = createNode(parent, name, mode);\n const path = realPath(node);\n log?.(\"mknod\", path, mode);\n return tryOperation(\n () => {\n if (FS.isDir(node.mode)) {\n vfs.mkdir(path, { mode });\n } else {\n vfs.writeFile(path, \"\", { mode });\n }\n return node;\n },\n \"mknod\",\n path,\n );\n },\n rename(oldNode: EmscriptenNode, newDir: EmscriptenNode, newName: string): void {\n const oldPath = realPath(oldNode);\n const newPath = `${realPath(newDir)}/${newName}`;\n log?.(\"rename\", oldPath, newPath);\n tryOperation(() => vfs.rename(oldPath, newPath), \"rename\", oldPath);\n oldNode.name = newName;\n },\n unlink(parent: EmscriptenNode, name: string): void {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"unlink\", path);\n try {\n vfs.unlink(path);\n } catch (error) {\n // An unlink failure is not reported to Postgres, only recorded.\n const code = (error as { code?: unknown } | null)?.code;\n if (code) {\n const message = (error as { message?: unknown } | null)?.message;\n vfs.recordSyscallError(\n \"unlink\",\n path,\n typeof code === \"number\" ? code : -1,\n typeof message === \"string\" ? message : JSON.stringify(code),\n );\n }\n }\n },\n rmdir(parent: EmscriptenNode, name: string): void {\n const path = `${realPath(parent)}/${name}`;\n log?.(\"rmdir\", path);\n tryOperation(() => vfs.rmdir(path), \"rmdir\", path);\n },\n readdir(node: EmscriptenNode): string[] {\n const path = realPath(node);\n log?.(\"readdir\", path);\n return tryOperation(() => vfs.readdir(path), \"readdir\", path);\n },\n symlink(): never {\n throw new FS.ErrnoError(63); // EPERM: not supported\n },\n readlink(): never {\n throw new FS.ErrnoError(63);\n },\n };\n\n const streamOps = {\n open(stream: EmscriptenStream): void {\n const path = realPath(stream.node);\n log?.(\"open\", path);\n tryOperation(\n () => {\n if (FS.isFile(stream.node.mode)) {\n stream.shared.refcount = 1;\n stream.nfd = vfs.open(path);\n }\n },\n \"open\",\n path,\n );\n },\n close(stream: EmscriptenStream): void {\n log?.(\"close\", realPath(stream.node));\n tryOperation(\n () => {\n if (FS.isFile(stream.node.mode) && stream.nfd !== undefined && --stream.shared.refcount === 0) {\n vfs.close(stream.nfd);\n }\n },\n \"close\",\n () => realPath(stream.node),\n );\n },\n dup(stream: EmscriptenStream): void {\n stream.shared.refcount++;\n },\n read(stream: EmscriptenStream, buffer: ArrayBufferView, offset: number, length: number, position: number): number {\n if (length === 0) return 0;\n const fd = stream.nfd ?? -1;\n return tryOperation(\n () => vfs.read(fd, asBytes(buffer), offset, length, position),\n \"read\",\n () => realPath(stream.node),\n );\n },\n write(stream: EmscriptenStream, buffer: ArrayBufferView, offset: number, length: number, position: number): number {\n const fd = stream.nfd ?? -1;\n return tryOperation(\n () => vfs.write(fd, asBytes(buffer), offset, length, position),\n \"write\",\n () => realPath(stream.node),\n );\n },\n llseek(stream: EmscriptenStream, offset: number, whence: number): number {\n let position = offset;\n if (whence === 1) {\n position += stream.position;\n } else if (whence === 2 && FS.isFile(stream.node.mode)) {\n const fd = stream.nfd ?? -1;\n tryOperation(\n () => {\n position += vfs.fstat(fd).size;\n },\n \"llseek\",\n () => realPath(stream.node),\n );\n }\n if (position < 0) throw new FS.ErrnoError(ERRNO_CODES.EINVAL);\n return position;\n },\n mmap(): never {\n // The runtime exports no mmapAlloc; Postgres does not map data-directory files.\n throw new FS.ErrnoError(ERRNO_CODES.ENODEV);\n },\n msync(): number {\n return 0;\n },\n };\n\n return {\n mount(): EmscriptenNode {\n return createNode(null, \"/\", 0o40000 | 0o777);\n },\n syncfs(_mount: unknown, _populate: unknown, done: (error: unknown) => void): void {\n done(null);\n },\n createNode,\n node_ops: nodeOps,\n stream_ops: streamOps,\n };\n}\n",
|
|
18
18
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { BaseFilesystem } from \"@pgxsinkit/pgwasm/fs\";\n\nimport type { PostgresModule } from \"../emscripten\";\nimport { PGDATA } from \"../paths\";\nimport { createVfsFilesystem } from \"../vfs-mount\";\nimport type { StorageMount } from \"./storage-mount\";\n\n/** The data directory on a pgwasm filesystem (`createPgwasm({ fs })`), mounted through an adapter. */\nexport class VfsMount implements StorageMount {\n readonly #vfs: BaseFilesystem;\n\n constructor(vfs: BaseFilesystem) {\n this.#vfs = vfs;\n }\n\n async acquire(): Promise<void> {}\n\n get preRun(): (module: PostgresModule) => void {\n return (module) => {\n module.FS.mkdir(PGDATA);\n module.FS.mount(createVfsFilesystem(module, this.#vfs), {}, PGDATA);\n };\n }\n\n async initialSync(): Promise<void> {\n await this.#vfs.initialSyncFs();\n }\n\n async persist(_module: PostgresModule, relaxed: boolean): Promise<void> {\n await this.#vfs.syncToFs(relaxed);\n }\n\n async close(): Promise<void> {\n await this.#vfs.closeFs();\n }\n\n async cleanupFailedInit(): Promise<void> {\n await this.#vfs.cleanupFailedInit();\n }\n}\n",
|
|
19
19
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { StorageRequest } from \"@pgxsinkit/pgwasm/build\";\n\nimport { FileMount } from \"./file\";\nimport { IdbMount } from \"./idb\";\nimport { MemoryMount } from \"./memory\";\nimport type { StorageMount } from \"./storage-mount\";\nimport { VfsMount } from \"./vfs\";\n\nexport type { StorageMount } from \"./storage-mount\";\n\n/** The mount for a storage request. */\nexport function mountFor(storage: StorageRequest): StorageMount {\n switch (storage.kind) {\n case \"memory\":\n return new MemoryMount();\n case \"idb\":\n return new IdbMount(storage.name);\n case \"file\":\n return new FileMount(storage.path);\n case \"vfs\":\n return new VfsMount(storage.vfs);\n }\n}\n",
|
|
20
20
|
"// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL\n// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.\n\nimport type { DebugLevel } from \"@pgxsinkit/pgwasm/build\";\n\nimport type { CBuildArtefactSet } from \"../artefacts\";\nimport type { EmscriptenStream, ModuleOverrides, PostgresModule } from \"./emscripten\";\nimport { preservingExitCode } from \"./exit-code\";\nimport { ICU_DATA_PATH, INITDB_EXE_PATH, LOCALE_LIST_PATH, PGDATA, POSTGRES_EXE_PATH } from \"./paths\";\n\n/** Postgres' error longjmp, intercepted by the host: keep in sync with pgwasmc.c's POSTGRES_MAIN_LONGJMP. */\nconst POSTGRES_MAIN_LONGJMP = 100;\n/** The exit status single-user mode reports when it started and stays alive: the C build's `PGWASM_EXIT_ALIVE`. */\nconst PGWASM_EXIT_ALIVE = 99;\nconst INITIAL_MEMORY_PAGES = 2048;\nconst MAXIMUM_MEMORY_PAGES = 32768;\n\n/** The single-user-mode arguments every start begins with. */\nexport const DEFAULT_START_PARAMS: readonly string[] = [\n \"--single\", // single-user mode (must come first)\n \"-F\", // fsync off: the host persists storage itself\n \"-O\", // allow system table structure changes\n \"-j\", // no newline as the interactive query delimiter\n \"-c\",\n \"search_path=public\",\n \"-c\",\n \"exit_on_error=false\",\n \"-c\",\n \"log_checkpoints=false\",\n \"-c\",\n \"max_worker_processes=0\",\n \"-c\",\n \"max_parallel_workers=0\",\n \"-c\",\n \"max_parallel_workers_per_gather=0\",\n \"-c\",\n \"io_method=sync\",\n \"-c\",\n \"max_parallel_maintenance_workers=0\",\n];\n\n/**\n * Whether `error` is one of the exceptions the Emscripten runtime throws on purpose to unwind the wasm\n * stack back to the main loop, which handles them:\n * - `'unwind'` from emscripten_exit_with_live_runtime(): how pgwasm_longjmp (pgwasmc.c) delivers Postgres'\n * siglongjmp to its main-loop error handler, and how a Terminate message ends the loop;\n * - what an emscripten-mode longjmp throws, should one pass every invoke_* frame: an instance of the\n * glue's (unexported) `EmscriptenSjLj` class on Emscripten 6.0.10 (pgwasm-postgres 18.6.1 onwards), a\n * number on Emscripten 3.1.74 (18.3.0 and 18.6.0). Both are recognised, so the host works with either.\n *\n * An `ExitStatus` (from exit()/proc_exit(): a FATAL error) is not: the backend's exit callbacks have\n * already torn its session down, so the loop cannot resume on it (see {@link exitStatusOf}).\n */\nexport function isEmscriptenUnwind(error: unknown): boolean {\n if (error === \"unwind\" || typeof error === \"number\") return true;\n if (typeof error !== \"object\" || error === null) return false;\n return (error as { constructor?: { name?: unknown } }).constructor?.name === \"EmscriptenSjLj\";\n}\n\nconst invalidBundleSize = (actual: number, expected: number): Error =>\n new Error(`Invalid filesystem bundle size: ${actual} !== ${expected}`);\n\n/** The status of the `ExitStatus` the runtime throws from exit()/proc_exit(), or undefined for anything else. */\nexport function exitStatusOf(error: unknown): number | undefined {\n if (typeof error !== \"object\" || error === null || (error as { name?: unknown }).name !== \"ExitStatus\") {\n return undefined;\n }\n const status = (error as { status?: unknown }).status;\n return typeof status === \"number\" ? status : -1;\n}\n\n/**\n * The wasm's shadow stack pointer: the C stack in linear memory, which the glue exports neither\n * `stackSave` nor `stackRestore` for. A throw that unwinds wasm frames (an ERROR's intercepted\n * siglongjmp, a FATAL's exit) skips their epilogues, so the pointer stays where the deepest of them left\n * it. Unrestored, every ERROR leaked that much stack (about 1.2 kB for `SELECT 1/0`), until\n * `max_stack_depth` refused every statement (from about the 1,700th error in one instance). The host\n * restores it to where the call started, as Postgres' own siglongjmp to PostgresMain would.\n */\ninterface ShadowStack {\n save(): number;\n restore(pointer: number): void;\n}\n\nfunction shadowStackOf(instance: WebAssembly.Instance): ShadowStack {\n const current = instance.exports[\"emscripten_stack_get_current\"];\n const restore = instance.exports[\"_emscripten_stack_restore\"];\n if (typeof current !== \"function\" || typeof restore !== \"function\") {\n throw new Error(\n \"The Postgres module exports no emscripten_stack_get_current or _emscripten_stack_restore: the host cannot restore its stack after an error\",\n );\n }\n return {\n save: () => (current as () => number)(),\n restore: (pointer) => (restore as (pointer: number) => void)(pointer),\n };\n}\n\nexport interface PostgresInstanceConfig {\n /** The Postgres glue (`postgres.js`) and the size of the filesystem bundle it was packaged with. */\n readonly glue: Pick<CBuildArtefactSet, \"createPostgresModule\" | \"fsBundleBytes\">;\n readonly wasmModule: Promise<WebAssembly.Module>;\n /** The filesystem bundle, a copy of its own for this instance. */\n readonly fsBundle: Promise<ArrayBuffer>;\n readonly user: string;\n readonly database: string;\n readonly debug: DebugLevel;\n /** preRun steps that mount storage over the data directory; run after the filesystem bundle loads. */\n readonly mountPreRun?: (module: PostgresModule) => void;\n /** @internal A test's view of the module. */\n readonly onModule?: (module: PostgresModule) => void;\n}\n\n/**\n * One Emscripten instance of the Postgres module and the host state around it: the socket callbacks\n * the wire goes through, the `/dev/blob` device, and the external-command hooks.\n */\nexport class PostgresInstance {\n readonly module: PostgresModule;\n readonly #debug: DebugLevel;\n readonly #stack: ShadowStack;\n // Frontend bytes being fed to Postgres, and how far it has read them.\n #input: Uint8Array = new Uint8Array(0);\n #readOffset = 0;\n // Where backend bytes go during an exchange.\n #sink: ((chunk: Uint8Array) => void) | undefined;\n #blobReadSource: Uint8Array | undefined;\n #blobWritten: Uint8Array<ArrayBuffer>[] | undefined;\n #externalCommandStream: number | null = null;\n #functionPointers: number[] = [];\n #failed = false;\n #exited = false;\n // The last lines Postgres wrote to stderr (since the exchange began, during one), for the error when it\n // fails to start or exits.\n readonly #stderr: string[] = [];\n\n private constructor(module: PostgresModule, debug: DebugLevel, stack: ShadowStack) {\n this.module = module;\n this.#debug = debug;\n this.#stack = stack;\n }\n\n static async create(config: PostgresInstanceConfig): Promise<PostgresInstance> {\n const [wasmModule, fsBundle] = await Promise.all([config.wasmModule, config.fsBundle]);\n // Checked before the glue runs. Emscripten 6's file packager (pgwasm-postgres 18.6.1 onwards) loads the\n // bundle in an async function it never awaits, so a throw from getPreloadedPackage no longer rejects the\n // factory: it is an unhandled rejection, and the boot fails later on a missing bundle file with an\n // unrelated filesystem error.\n const { createPostgresModule, fsBundleBytes } = config.glue;\n if (fsBundle.byteLength !== fsBundleBytes) throw invalidBundleSize(fsBundle.byteLength, fsBundleBytes);\n let host: PostgresInstance | undefined;\n let stack: ShadowStack | undefined;\n const pendingHost = (module: PostgresModule): PostgresInstance => {\n // The runtime runs no preRun step before the instance it waits on (instantiateWasm) is ready.\n if (stack === undefined) throw new Error(\"The Postgres module initialised before its wasm instance\");\n host ??= new PostgresInstance(module, config.debug, stack);\n return host;\n };\n let rejectInstantiation: (error: unknown) => void = () => undefined;\n const instantiationFailed = new Promise<never>((_, reject) => {\n rejectInstantiation = reject;\n });\n\n const log = (text: string) => {\n if (config.debug > 0) console.debug(text);\n };\n const logError = (text: string) => {\n if (host) host.#recordStderr(text);\n if (config.debug > 0) console.error(text);\n };\n\n // Emscripten runs preRun callbacks in the order listed (3.1.74, before pgwasm-postgres 18.6.1, ran them\n // in reverse). The build's pre-js loads the filesystem bundle before the first of them, so every one\n // sees the bundle's files. They touch disjoint state (the runtime hook, /dev/blob, the environment, the\n // bundle's files outside the data directory, then the storage mount over the data directory), so none\n // depends on the order of the others.\n const preRun: ((module: PostgresModule) => void)[] = [\n (module) => {\n module.onRuntimeInitialized = () => pendingHost(module).#onRuntimeInitialized();\n },\n (module) => pendingHost(module).#registerBlobDevice(),\n (module) => {\n const env = module.ENV;\n env[\"HOME\"] = \"/home/postgres\";\n env[\"USER\"] = \"postgres\";\n env[\"LOGNAME\"] = \"postgres\";\n env[\"PGDATA\"] = PGDATA;\n env[\"PGUSER\"] = config.user;\n env[\"PGDATABASE\"] = config.database;\n env[\"LANG\"] = \"en_US.UTF-8\";\n env[\"LC_COLLATE\"] = \"en_US.UTF-8\";\n env[\"LC_CTYPE\"] = \"en_US.UTF-8\";\n env[\"TZ\"] = \"UTC\";\n env[\"PGTZ\"] = \"UTC\";\n env[\"PGCLIENTENCODING\"] = \"UTF8\";\n env[\"ICU_DATA\"] = ICU_DATA_PATH;\n },\n (module) => {\n module.FS.chmod(\"/home/postgres/.pgpass\", 0o600); // libpq ignores a .pgpass others can read\n module.FS.chmod(INITDB_EXE_PATH, 0o555);\n module.FS.chmod(POSTGRES_EXE_PATH, 0o555);\n },\n ];\n if (config.mountPreRun) preRun.push(config.mountPreRun);\n\n const overrides: ModuleOverrides<PostgresModule> = {\n thisProgram: POSTGRES_EXE_PATH,\n arguments: config.debug > 0 ? [\"-d\", String(config.debug)] : [],\n noExitRuntime: true,\n wasmMemory: new WebAssembly.Memory({ initial: INITIAL_MEMORY_PAGES, maximum: MAXIMUM_MEMORY_PAGES }),\n // A stdin that is always at EOF, so a browser never prompts.\n stdin: () => null,\n print: log,\n printErr: logError,\n instantiateWasm: (imports, successCallback) => {\n WebAssembly.instantiate(wasmModule, imports).then(\n (instance) => {\n try {\n stack = shadowStackOf(instance);\n } catch (error) {\n rejectInstantiation(error);\n return;\n }\n successCallback(instance, wasmModule);\n },\n (error: unknown) => rejectInstantiation(error),\n );\n return {};\n },\n getPreloadedPackage: (name, size) => {\n if (name !== \"postgres.data\") throw new Error(`Unknown filesystem package: ${name}`);\n if (fsBundle.byteLength !== size) {\n // Unreachable while the glue and the pins agree; if they ever do not, fail the boot with this error.\n const error = invalidBundleSize(fsBundle.byteLength, size);\n rejectInstantiation(error);\n throw error;\n }\n return fsBundle;\n },\n preRun,\n };\n\n const module = await Promise.race([createPostgresModule(overrides), instantiationFailed]);\n const instance = pendingHost(module);\n config.onModule?.(module);\n return instance;\n }\n\n #recordStderr(text: string): void {\n this.#stderr.push(text);\n if (this.#stderr.length > 20) this.#stderr.shift();\n }\n\n #log(...args: unknown[]): void {\n if (this.#debug > 0) console.log(...args);\n }\n\n #addFunction(fn: (...args: number[]) => number | void, signature: string): number {\n const pointer = this.module.addFunction(fn, signature);\n this.#functionPointers.push(pointer);\n return pointer;\n }\n\n #onRuntimeInitialized(): void {\n const mod = this.module;\n // system() never runs a command: it is logged and fails.\n mod._pgwasm_set_system_fn(\n this.#addFunction((command: number) => {\n this.#log(`Postgres tried to execute ${mod.UTF8ToString(command)}, returning 1.`);\n return 1;\n }, \"pi\"),\n );\n mod._pgwasm_set_popen_fn(\n this.#addFunction((command: number, mode: number) => {\n this.#externalCommandStream = this.#handleExternalCommand(mod.UTF8ToString(command), mod.UTF8ToString(mode));\n return this.#externalCommandStream;\n }, \"ppp\"),\n );\n mod._pgwasm_set_pclose_fn(\n this.#addFunction((stream: number) => {\n if (stream !== this.#externalCommandStream) throw new Error(`Unhandled pclose ${stream}`);\n mod._fclose(stream);\n this.#externalCommandStream = null;\n }, \"pi\"),\n );\n // Backend bytes: handed to the exchange's sink as a view of the heap, valid during the call.\n const write = this.#addFunction((pointer: number, length: number) => {\n this.#sink?.(this.module.HEAPU8.subarray(pointer, pointer + length));\n return length;\n }, \"iii\");\n // Frontend bytes: copied into the heap from the message being exchanged.\n const read = this.#addFunction((pointer: number, maxLength: number) => {\n const length = Math.min(this.#input.length - this.#readOffset, maxLength);\n this.module.HEAPU8.set(this.#input.subarray(this.#readOffset, this.#readOffset + length), pointer);\n this.#readOffset += length;\n return length;\n }, \"iii\");\n mod._pgwasm_set_rw_cbs(read, write);\n }\n\n #handleExternalCommand(command: string, mode: string): number {\n if (command.startsWith(\"locale -a\") && mode === \"r\") {\n return this.module._fopen(\n this.module.stringToUTF8OnStack(LOCALE_LIST_PATH),\n this.module.stringToUTF8OnStack(mode),\n );\n }\n throw new Error(`Unhandled external command: ${command}`);\n }\n\n /** `/dev/blob`: what `COPY … FROM '/dev/blob'` reads and `COPY … TO '/dev/blob'` writes. */\n #registerBlobDevice(): void {\n const FS = this.module.FS;\n const device = FS.makedev(64, 0);\n FS.registerDevice(device, {\n open: () => undefined,\n close: () => undefined,\n read: (_stream, buffer, offset, length, position) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to read from\");\n if (position >= contents.length) return 0;\n const size = Math.min(contents.length - position, length);\n buffer.set(contents.subarray(position, position + size), offset);\n return size;\n },\n write: (_stream, buffer, offset, length) => {\n this.#blobWritten ??= [];\n this.#blobWritten.push(new Uint8Array(buffer.subarray(offset, offset + length)));\n return length;\n },\n llseek: (stream: EmscriptenStream, offset: number, whence: number) => {\n const contents = this.#blobReadSource;\n if (!contents) throw new Error(\"No /dev/blob File or Blob provided to llseek\");\n let position = offset;\n if (whence === 1) position += stream.position;\n else if (whence === 2) position = contents.length;\n if (position < 0) throw new FS.ErrnoError(28);\n return position;\n },\n });\n FS.mkdev(\"/dev/blob\", device);\n }\n\n setBlobReadSource(data: Uint8Array | undefined): void {\n this.#blobReadSource = data;\n }\n\n takeBlobWritten(): Uint8Array<ArrayBuffer>[] | undefined {\n const written = this.#blobWritten;\n this.#blobWritten = undefined;\n return written;\n }\n\n /** Run `callMain`, leaving the host's exit code as it was. */\n callMain(args: string[]): number {\n return preservingExitCode(() => this.module.callMain(args));\n }\n\n /** Start Postgres in single-user mode on the data directory. */\n startSingleMode(startParams: readonly string[]): void {\n const mod = this.module;\n mod._pgwasm_setPostgresActive(1);\n this.callMain([...startParams, \"-D\", PGDATA, mod.ENV[\"PGDATABASE\"] ?? \"postgres\"]);\n const exitStatus = mod._pgwasm_setPostgresExitStatus(-3);\n if (exitStatus !== PGWASM_EXIT_ALIVE) {\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres failed to start (single-user mode exit status ${exitStatus})${output ? `:\\n${output}` : \"\"}`,\n );\n }\n mod._pgwasm_startPostgres();\n }\n\n /**\n * One exchange on the single session: feed `message` to Postgres and hand every backend byte it\n * produces to `onData`, synchronously. A startup packet (first byte 0) is processed as one; a\n * Terminate (`X`) is ignored, as the session ends with the instance. A throw that is not Postgres'\n * own error unwind means the wasm stack was abandoned mid-function, and an exit (a FATAL error) means\n * the backend tore its session down: either fails the session, which refuses every later exchange.\n */\n exchange(message: Uint8Array, onData: (chunk: Uint8Array) => void): void {\n if (this.#failed) throw new Error(\"The C build's session failed and cannot be used again\");\n if (message[0] === 0x58) return; // Terminate\n this.#sink = onData;\n this.#input = message;\n this.#readOffset = 0;\n this.#stderr.length = 0;\n try {\n if (message[0] === 0) {\n this.#processStartupPacket();\n return;\n }\n this.#runMainLoop(message);\n } catch (error) {\n const status = exitStatusOf(error);\n if (status === undefined) throw error;\n this.#failed = true;\n const output = this.#stderr.join(\"\\n\").trim();\n throw new Error(\n `Postgres exited with status ${status} during an exchange: a FATAL error ended the C build's session${output ? `:\\n${output}` : \"\"}`,\n { cause: error },\n );\n } finally {\n this.#sink = undefined;\n this.#input = new Uint8Array(0);\n }\n }\n\n /**\n * A call into the backend that may unwind (an ERROR's intercepted siglongjmp, a FATAL's exit):\n * should it throw, the shadow stack pointer is restored to where it began (see {@link ShadowStack}).\n */\n #call<T>(call: () => T): T {\n const stack = this.#stack.save();\n try {\n return call();\n } catch (error) {\n this.#stack.restore(stack);\n throw error;\n }\n }\n\n #processStartupPacket(): void {\n const mod = this.module;\n const result = this.#call(() => mod._ProcessStartupPacket(mod._pgwasm_getMyProcPort()));\n if (result !== 0) throw new Error(\"Cannot process the startup packet\");\n this.#call(() => {\n mod._pgwasm_sendConnData();\n mod._pgwasm_pq_flush();\n });\n }\n\n #runMainLoop(message: Uint8Array): void {\n const mod = this.module;\n try {\n // One message may carry several batched statements; the loop returns after each.\n while (this.#readOffset < message.length || mod._pq_buffer_remaining_data() > 0) {\n const stack = this.#stack.save();\n try {\n mod._PostgresMainLoopOnce();\n } catch (error) {\n // First, as Postgres' own siglongjmp to PostgresMain would: the throw skipped the epilogues of\n // every frame it abandoned (see ShadowStack).\n this.#stack.restore(stack);\n if (!isEmscriptenUnwind(error)) throw error;\n if (mod._pgwasm_setPostgresExitStatus(-2) === POSTGRES_MAIN_LONGJMP) {\n // Postgres raised an error: its siglongjmp into main was intercepted, and its error handling\n // runs here before the loop resumes with the rest of the batch.\n this.#call(() => mod._PostgresMainLongJmp());\n }\n }\n }\n this.#call(() => {\n mod._PostgresSendReadyForQueryIfNecessary();\n mod._pgwasm_pq_flush();\n });\n } catch (error) {\n this.#failed = true;\n throw error;\n }\n }\n\n /** Postgres' clean exit: its atexit callbacks. An exit status of 0 is the normal outcome. */\n shutdown(): void {\n const mod = this.module;\n try {\n preservingExitCode(() => {\n mod._pgwasm_setPostgresActive(0);\n this.#call(() => mod._pgwasm_run_atexit_funcs());\n });\n } catch (error) {\n const exit = error as { name?: unknown; status?: unknown };\n if (!(exit.name === \"ExitStatus\" && exit.status === 0)) throw error;\n }\n }\n\n /** Release the callbacks and exit the runtime, which `noExitRuntime` otherwise keeps alive. */\n dispose(exitStatus: number): void {\n if (this.#exited) return;\n this.#exited = true;\n for (const pointer of this.#functionPointers) {\n try {\n this.module.removeFunction(pointer);\n } catch {\n // continue releasing\n }\n }\n this.#functionPointers = [];\n try {\n preservingExitCode(() => this.module._emscripten_force_exit(exitStatus));\n } catch {\n // The runtime reports a forced exit by throwing ExitStatus.\n }\n }\n}\n",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pgxsinkit/pgwasm-c",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.3",
|
|
4
4
|
"license": "PostgreSQL",
|
|
5
5
|
"files": [
|
|
6
6
|
"artefacts",
|
|
@@ -47,7 +47,7 @@
|
|
|
47
47
|
"build": "bun --cwd ../.. run build:public-packages"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@pgxsinkit/pgwasm": "0.6.
|
|
50
|
+
"@pgxsinkit/pgwasm": "0.6.3"
|
|
51
51
|
},
|
|
52
52
|
"repository": {
|
|
53
53
|
"type": "git",
|
package/src/host/vfs-mount.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Began as a copy of `@electric-sql/pglite` (taken under its PostgreSQL License option, © ElectricSQL
|
|
2
2
|
// — see NOTICE). Owned outright (ADR-0062); compatibility with PGlite is an anti-goal — evolve freely.
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { type BaseFilesystem, ERRNO_CODES } from "@pgxsinkit/pgwasm/fs";
|
|
5
5
|
|
|
6
6
|
import type { EmscriptenFilesystemType, EmscriptenNode, EmscriptenStream, PostgresModule } from "./emscripten";
|
|
7
7
|
|