From a7294ac33111d09cf07403993930bd5b22dfef2c Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Wed, 29 Jul 2026 00:22:07 -0700 Subject: [PATCH 1/7] bridge: add a Node storage backend for the SQLite worker In this commit, we teach the driver to persist under Node. Until now it could only run in a browser, because everything below the database/sql layer assumed browser APIs: the bridge spawned a Web Worker, the worker pulled sqlite3.js in with importScripts and let Emscripten fetch the wasm binary over the network, and the only durable storage on offer was OPFS. A Go program compiled for js/wasm and hosted by Node hit all three of those at once and had nowhere to put its data. None of that is a deep problem, because Node has something a browser does not: real synchronous file I/O. OPFS is asynchronous underneath, which is why persisting to it needs either the async proxy worker or the SAH pool's preallocated access handles, and why that machinery is as involved as it is. The node:fs sync API is exactly the shape SQLite's VFS layer wants, so the new VFS in sqlite-node-vfs.js is close to a direct translation rather than a pooling scheme. It is modeled on opfs-sahpool for structure only. The one guarantee OPFS provides for free that a plain filesystem does not is exclusive access, since a SyncAccessHandle cannot be held by two tabs at once. Two processes writing one database corrupt it silently, so the VFS reconstructs that guarantee with a pid-stamped lock file taken when a main database is opened for writing. A second process now fails to open rather than interleaving writes, and a lock whose owning process is gone is reclaimed, so a crash does not strand the database. The bridge and the worker each grew one seam rather than a fork. The bridge wraps a node:worker_threads worker in an adapter presenting the browser Worker interface, and hands it the worker source rather than a path, because a path is resolved through the nearest package.json and a ".js" file inside a "type": "module" package would be loaded as ESM with its require calls broken. The worker abstracts script loading, wasm instantiation, and message transport, leaving the request handlers host-independent. The browser path through both files is unchanged. Also fixed here is a deadlock only a Node host could hit. The promise rejection handler in the bridge adapter printed the JavaScript error to stdout from inside a syscall/js callback. A browser answers that write synchronously, but Node's fs.write is genuinely asynchronous, so the Go scheduler parked waiting for a callback that could not run until the handler it was already inside returned, and the whole runtime deadlocked. The message reaches the caller through the returned error regardless, so the print is simply gone. Alongside the backend come two test suites. One drives the bridge from Node directly, and the other runs the Go driver itself under Node through a go test -exec wrapper, so the claim that database/sql code persists to a real file is checked against the real driver rather than against a description of it. --- CHANGELOG.md | 3 + CLAUDE.md | 6 + Makefile | 16 +- README.md | 25 +- bridge/sqlite-bridge.js | 96 ++++- bridge/sqlite-node-vfs.js | 597 ++++++++++++++++++++++++++++++++ bridge/sqlite-worker.js | 157 ++++++++- bridge_adapter.go | 11 +- driver.go | 2 + driver_node_js_wasm_test.go | 221 ++++++++++++ embed.go | 13 +- embed_test.go | 10 + example/.gitignore | 1 + open.go | 6 +- package.json | 1 + playwright.config.js | 4 + scripts/node-wasm-test-exec.cjs | 107 ++++++ tests/node-backend.test.cjs | 280 +++++++++++++++ utils.go | 17 +- 19 files changed, 1539 insertions(+), 34 deletions(-) create mode 100644 bridge/sqlite-node-vfs.js create mode 100644 driver_node_js_wasm_test.go create mode 100644 scripts/node-wasm-test-exec.cjs create mode 100644 tests/node-backend.test.cjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ffb94a..6411b10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- Added a Node storage backend: the `nodefs` VFS in `bridge/sqlite-node-vfs.js`, a `node:worker_threads` path in the bridge, and Node-aware script and wasm loading in the worker. +- Added `sqliteBridge.shutdown()` so a Node host can retire the worker thread and let its process exit. + - Replaced SQLite Worker1/Promiser runtime usage with a dedicated `sqlite3.oo1` Worker. - Added browser E2E coverage for OPFS, memory mode, transactions, BLOBs, dump/load, migrations, generated SQL shapes, named parameters, context cancellation, and storage behavior. - Updated SQLite WASM assets to 3.53.1 / 3530100. diff --git a/CLAUDE.md b/CLAUDE.md index 22b655f..2fb22e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -127,6 +127,12 @@ SQLite WASM uses these browser runtime files: ### VFS Fallback If OPFS unavailable, automatically falls back to in-memory storage. +### Node hosts +`bridge/sqlite-node-vfs.js` provides the `nodefs` VFS over the synchronous +`node:fs` API, and the bridge spawns the worker through `node:worker_threads` +instead of the browser `Worker`. Run `make node-test` (or +`node --test tests/node-backend.test.cjs`) for that path. + ### database/sql Integration Example uses database/sql code in `example/generated/`: - `schema.sql` - Database schema diff --git a/Makefile b/Makefile index dd5a145..28c0bce 100644 --- a/Makefile +++ b/Makefile @@ -22,6 +22,7 @@ build-example: fetch-assets build-wasm @echo "๐Ÿ“ฆ Copying bridge and assets to example..." cp bridge/sqlite-bridge.js example/ cp bridge/sqlite-worker.js example/ + cp bridge/sqlite-node-vfs.js example/ cp assets/*.js example/ cp assets/*.wasm example/ @echo "โœ… Example built" @@ -42,12 +43,24 @@ serve: build-example cd example && node server.js # Run tests -test: +test: node-test @echo "๐Ÿงช Running tests..." go test -v ./... @echo "โœ… Tests passed" @echo "โ„น๏ธ Run make browser-test for headless Chrome E2E coverage" +# Run the Node storage backend tests: the JS bridge/VFS suite, then the Go +# driver itself under Node. This deliberately does not depend on fetch-assets, +# because the committed assets pin a SQLite version that re-fetching would +# silently move. +node-test: + @echo "๐Ÿงช Running Node storage backend tests..." + node --test tests/node-backend.test.cjs + @echo "๐Ÿงช Running Go driver tests under Node..." + GOOS=js GOARCH=wasm go test \ + -exec "node scripts/node-wasm-test-exec.cjs" \ + -run TestNodeDriver -v ./ + browser-test: build-example @echo "๐ŸŒ Running browser E2E tests..." WASM_BROWSER_TEST=1 go test -run TestBrowserE2E ./... @@ -94,6 +107,7 @@ help: @echo " make build-example- Build example only" @echo " make serve - Build and serve the demo locally" @echo " make test - Run tests" + @echo " make node-test - Run Node storage backend tests" @echo " make browser-test - Run headless Chrome browser E2E tests" @echo " make playwright-test - Run Playwright browser tests against the example page" @echo " make clean - Clean build artifacts" diff --git a/README.md b/README.md index b5a7b85..7892dd7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # go-wasmsqlite -A WebAssembly SQLite driver for Go. It lets browser-based Go WASM applications use the standard `database/sql` API with SQLite running entirely client-side and persisting to OPFS when the browser supports it. +A WebAssembly SQLite driver for Go. It lets Go WASM applications use the standard `database/sql` API with SQLite running entirely in-process: persisting to OPFS in a browser, and to the host filesystem under Node. ## Current Architecture @@ -11,18 +11,33 @@ Go App (WASM) -> database/sql driver ("wasmsqlite") -> syscall/js adapter -> sqlite-bridge.js RPC client on the main thread - -> sqlite-worker.js dedicated Worker + -> sqlite-worker.js dedicated worker -> sqlite3.oo1.DB / sqlite3.oo1.OpfsDb - -> SQLite WASM + OPFS storage + -> SQLite WASM + OPFS storage (browser) + -> SQLite WASM + node:fs VFS (Node) ``` -`sqlite-worker.js` imports `sqlite3.js`, calls `sqlite3InitModule()`, opens databases with an automatic OPFS preference order by default (`opfs-wl`, `opfs-sahpool`, then `opfs`), and falls back to `:memory:` only when memory fallback is allowed. SQLite still runs in a Worker because OPFS requires worker-side file APIs. +`sqlite-worker.js` loads `sqlite3.js`, calls `sqlite3InitModule()`, and opens databases through the best durable VFS the host offers. + +In a browser it imports the script, spawns a Web Worker, and prefers `opfs-wl`, then `opfs-sahpool`, then `opfs`. Under Node it requires the script, spawns a `node:worker_threads` worker, and uses the `nodefs` VFS from `sqlite-node-vfs.js`, which maps SQLite's file operations onto the synchronous `node:fs` API. SQLite runs in a worker on both hosts, in a browser because OPFS needs worker-side file APIs and under Node so that a busy database cannot stall the host's event loop. + +### Node hosts + +Under Node the host must give Go's `wasm_exec.js` a real filesystem before instantiating the WASM module, and must tell the bridge where the runtime assets live: + +```js +globalThis.fs = require("node:fs"); // else wasm_exec.js stubs fs with ENOSYS +globalThis.sqliteBridgeAssetDir = wasmDir; // holds sqlite3.js, sqlite3.wasm, sqlite-worker.js, sqlite-node-vfs.js +``` + +Two Node processes must not write one database. The `nodefs` VFS enforces that with a pid-stamped lock file taken alongside each main database opened for writing; a lock whose owning process is gone is reclaimed automatically, so a crash does not strand the database. ## Features - Standard `database/sql` driver named `wasmsqlite` - OPFS persistence in supported browsers -- In-memory fallback when OPFS is unavailable +- Host filesystem persistence under Node through the `nodefs` VFS +- In-memory fallback when no durable storage is available - Transactions through `BEGIN IMMEDIATE`, `COMMIT`, and `ROLLBACK` - BLOB round trips through `[]byte` - Database dump/load helpers with BLOB-safe SQL literals diff --git a/bridge/sqlite-bridge.js b/bridge/sqlite-bridge.js index 01b5a2a..a7309b5 100644 --- a/bridge/sqlite-bridge.js +++ b/bridge/sqlite-bridge.js @@ -1,4 +1,10 @@ // Main-thread bridge between Go WASM and the dedicated SQLite oo1 worker. +// +// The worker is a browser Web Worker in a browser and a node:worker_threads +// worker under Node. The two APIs disagree on nearly everything at the seam +// (construction, event delivery, teardown), so the Node side is wrapped in an +// adapter that presents the browser Worker shape and the rest of this file +// stays host-independent. (() => { const bridgeProtocolVersion = 1; @@ -9,6 +15,14 @@ const pending = new Map(); const bridgeScriptURL = globalThis.document?.currentScript?.src || ""; + // isNodeHost reports whether this is Node rather than a browser. Node has no + // global Worker constructor, which is both the thing that distinguishes it + // and the exact reason the adapter below has to exist. + const isNodeHost = + typeof globalThis.process === "object" && + !!globalThis.process?.versions?.node && + typeof globalThis.Worker !== "function"; + function workerURL(override) { if (override) return override; if (globalThis.sqliteBridgeWorkerURL) return globalThis.sqliteBridgeWorkerURL; @@ -16,10 +30,67 @@ return "sqlite-worker.js"; } + // nodeAssetDir resolves the directory holding the runtime assets. A host + // that evaluates this file as a string (which is how a Go WASM host usually + // loads it) has no __dirname, so sqliteBridgeAssetDir is the supported knob. + function nodeAssetDir() { + const nodePath = require("node:path"); + if (globalThis.sqliteBridgeAssetDir) { + return nodePath.resolve(globalThis.sqliteBridgeAssetDir); + } + if (typeof __dirname === "string") return __dirname; + return process.cwd(); + } + + // createNodeWorker starts the worker under node:worker_threads and adapts it + // to the browser Worker interface this bridge is written against. + // + // The worker source is read and evaluated rather than being handed to Node + // as a path, because a path is interpreted through the nearest package.json: + // a ".js" file that lands inside a "type": "module" package would be loaded + // as ESM and its require() calls would fail. Evaluating the source sidesteps + // the question entirely, since an eval'd worker is always CommonJS. + function createNodeWorker(override) { + const { Worker: NodeWorker } = require("node:worker_threads"); + const nodeFS = require("node:fs"); + const nodePath = require("node:path"); + + const assetDir = nodeAssetDir(); + const scriptPath = override + ? nodePath.resolve(assetDir, override) + : nodePath.join(assetDir, "sqlite-worker.js"); + + let source; + try { + source = nodeFS.readFileSync(scriptPath, "utf8"); + } catch (error) { + throw new Error( + `unable to read sqlite-worker.js at ${scriptPath}: ${error.message}; ` + + "set globalThis.sqliteBridgeAssetDir to the runtime asset directory" + ); + } + + const nodeWorker = new NodeWorker(source, { + eval: true, + workerData: { assetDir: nodePath.dirname(scriptPath) }, + }); + + const adapter = { + onmessage: null, + onerror: null, + postMessage: (message) => nodeWorker.postMessage(message), + terminate: () => nodeWorker.terminate(), + }; + nodeWorker.on("message", (data) => adapter.onmessage?.({ data })); + nodeWorker.on("error", (error) => adapter.onerror?.(error)); + + return adapter; + } + function ensureWorker(override) { if (worker) return; - worker = new Worker(workerURL(override)); + worker = isNodeHost ? createNodeWorker(override) : new Worker(workerURL(override)); worker.onmessage = (event) => { const message = event.data || {}; const waiter = pending.get(message.id); @@ -58,6 +129,9 @@ if (!initPromise) { initPromise = request("init", { sqliteJSURL: options.sqliteJSURL || globalThis.sqliteBridgeSQLiteJSURL || "", + // rootDir anchors relative database names for the node:fs VFS. It is + // ignored in a browser, where names are origin-local OPFS paths. + rootDir: options.rootDir || globalThis.sqliteBridgeRootDir || "", expectedBridgeProtocolVersion: bridgeProtocolVersion }).then((result) => { if (result.workerProtocolVersion !== expectedWorkerProtocolVersion) { @@ -141,6 +215,26 @@ async load(dbId, sql) { await request("load", { dbId, sql }); return { ok: true }; + }, + + // shutdown tears the worker down. A browser page discards its workers when + // it unloads, but a Node worker thread keeps the host process alive, so a + // short-lived Node program needs a way to say it is finished. Databases + // should be closed first; this does not flush anything on their behalf. + async shutdown() { + if (!worker) return { ok: true }; + + const stopping = worker; + worker = null; + initPromise = null; + for (const waiter of pending.values()) { + waiter.reject(new Error("sqlite worker shut down")); + } + pending.clear(); + if (typeof stopping.terminate === "function") { + await stopping.terminate(); + } + return { ok: true }; } }; })(); diff --git a/bridge/sqlite-node-vfs.js b/bridge/sqlite-node-vfs.js new file mode 100644 index 0000000..02bbd0f --- /dev/null +++ b/bridge/sqlite-node-vfs.js @@ -0,0 +1,597 @@ +// A SQLite VFS backed by node:fs, for hosts that run this driver under Node +// instead of a browser. +// +// The browser story is OPFS, which is asynchronous at its core and therefore +// needs either the async proxy worker or the SAH pool's preallocated +// synchronous access handles. Node has none of that problem: node:fs exposes +// genuinely synchronous file operations, which is exactly the shape SQLite's +// VFS layer wants, so this VFS is a thin translation rather than a pooling +// scheme. It is modeled on opfs-sahpool for structure only. +// +// The one property OPFS gives away for free that a plain filesystem does not +// is exclusive access: a SyncAccessHandle cannot be held by two tabs at once. +// A wallet database that two processes write concurrently corrupts silently, +// so this VFS reconstructs that property with a pid-stamped lock file taken +// when a main database is opened for writing. Two Node processes pointed at +// one database now fail loudly instead of interleaving writes. + +"use strict"; + +const nodeFS = require("node:fs"); +const nodePath = require("node:path"); +const nodeCrypto = require("node:crypto"); + +// DEFAULT_VFS_NAME is the name this VFS registers under, and the name callers +// pass as `vfs=` in a DSN. +const DEFAULT_VFS_NAME = "nodefs"; + +// SECTOR_SIZE is what we report to SQLite as the atomic write unit. 4096 +// matches the page size of every filesystem we care about. +const SECTOR_SIZE = 4096; + +// LOCK_STALE_GRACE_MS bounds how long a lock file whose owning pid is gone is +// still honored. A crashed process leaves its lock behind; refusing forever +// would strand the database, so a lock is reclaimable once its owner is +// provably dead. +const LOCK_STALE_GRACE_MS = 0; + +// sleepSignal backs xSleep. Atomics.wait needs a shared integer array to wait +// on; nothing ever notifies this one, so every wait runs to its timeout, which +// is exactly the blocking sleep SQLite is asking for. +const sleepSignal = new Int32Array(new SharedArrayBuffer(4)); + +// isNodeHost reports whether we are running under Node rather than a browser +// or a browser Worker. Callers use it to decide whether installing this VFS is +// even possible. +function isNodeHost() { + return ( + typeof globalThis.process === "object" && + !!globalThis.process?.versions?.node && + typeof globalThis.importScripts !== "function" + ); +} + +// pidIsAlive reports whether a process id still exists. Signal 0 performs the +// permission and existence checks without delivering anything. +function pidIsAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) { + return false; + } + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM means the process exists but belongs to another user, which + // still counts as alive. + return error.code === "EPERM"; + } +} + +// installNodeFsVfs registers the node:fs VFS with the given sqlite3 namespace +// and returns a small utility handle. It is idempotent: a second call with the +// same name returns the already-registered handle rather than failing, so a +// worker can call it unconditionally on every open. +function installNodeFsVfs(sqlite3, options = {}) { + if (!isNodeHost()) { + throw new Error( + "the nodefs SQLite VFS requires a Node host; use OPFS in " + + "a browser" + ); + } + + const vfsName = options.name || DEFAULT_VFS_NAME; + const capi = sqlite3.capi; + const wasm = sqlite3.wasm; + + if (capi.sqlite3_vfs_find(vfsName)) { + return installNodeFsVfs.installed?.get(vfsName); + } + + // rootDir anchors relative database names. Absolute names are used as + // given, so a host that already knows its data directory can simply pass + // full paths. + const rootDir = nodePath.resolve(options.directory || process.cwd()); + + // openFiles maps a sqlite3_file pointer to the state we keep for it. The + // pointer is the only handle SQLite hands back to the io methods. + const openFiles = new Map(); + + // heldLocks maps a lock file path to the descriptor holding it, so xClose + // can release exactly what xOpen took. + const heldLocks = new Map(); + + // lastError carries the most recent failure so xGetLastError can report + // something better than a bare result code. + let lastError = null; + + function storeErr(error, rc) { + if (error !== undefined) { + lastError = error; + } + return rc === undefined ? 0 : rc; + } + + function popErr() { + const error = lastError; + lastError = null; + return error; + } + + function resolvePath(name) { + return nodePath.resolve(rootDir, name); + } + + function fileFor(pFile) { + const file = openFiles.get(Number(pFile)); + if (!file) { + throw new Error(`no open node:fs file for handle ${pFile}`); + } + return file; + } + + // heapView returns a view of the wasm heap for a pointer/length pair. The + // view is only valid for the duration of one synchronous call, since any + // wasm memory growth detaches it. + function heapView(ptr, n) { + const start = Number(ptr); + return wasm.heap8u().subarray(start, start + n); + } + + // acquireLock takes the exclusive open lock for a main database file. It + // reclaims a lock whose owning process is gone, and otherwise throws so + // the open fails loudly rather than racing another writer. + function acquireLock(dbPath) { + const lockPath = `${dbPath}-nodefs-lock`; + + for (let attempt = 0; attempt < 2; attempt++) { + try { + const fd = nodeFS.openSync(lockPath, "wx"); + nodeFS.writeSync( + fd, + JSON.stringify({ + pid: process.pid, + at: Date.now(), + }) + ); + nodeFS.closeSync(fd); + heldLocks.set(dbPath, lockPath); + return; + } catch (error) { + if (error.code !== "EEXIST") { + throw error; + } + } + + // The lock exists. It is only ours to take if the process that + // wrote it is gone. + let owner = null; + try { + owner = JSON.parse( + nodeFS.readFileSync(lockPath, "utf8") + ); + } catch (_) { + // An unparseable or vanished lock file is treated as stale. + } + + if (owner && pidIsAlive(owner.pid)) { + throw new Error( + `database is locked by another process ` + + `(pid ${owner.pid}): ${dbPath}` + ); + } + if ( + owner && + LOCK_STALE_GRACE_MS > 0 && + Date.now() - Number(owner.at) < LOCK_STALE_GRACE_MS + ) { + throw new Error( + `database lock is not yet reclaimable: ${dbPath}` + ); + } + + try { + nodeFS.unlinkSync(lockPath); + } catch (error) { + if (error.code !== "ENOENT") { + throw error; + } + } + } + + throw new Error(`unable to acquire database lock: ${dbPath}`); + } + + function releaseLock(dbPath) { + const lockPath = heldLocks.get(dbPath); + if (!lockPath) { + return; + } + heldLocks.delete(dbPath); + try { + nodeFS.unlinkSync(lockPath); + } catch (error) { + if (error.code !== "ENOENT") { + storeErr(error); + } + } + } + + const ioMethods = { + xCheckReservedLock: function (pFile, pOut) { + // This VFS holds the file exclusively for its lifetime, so no + // other connection can be holding a reserved lock. + storeErr(); + wasm.poke32(pOut, 0); + return 0; + }, + + xClose: function (pFile) { + storeErr(); + const key = Number(pFile); + const file = openFiles.get(key); + if (!file) { + return 0; + } + openFiles.delete(key); + try { + nodeFS.closeSync(file.fd); + if (file.locked) { + releaseLock(file.path); + } + if (file.flags & capi.SQLITE_OPEN_DELETEONCLOSE) { + try { + nodeFS.unlinkSync(file.path); + } catch (error) { + if (error.code !== "ENOENT") { + throw error; + } + } + } + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR); + } + }, + + xDeviceCharacteristics: function (pFile) { + // Claim nothing. A wallet database is worth more than the write + // batching SQLite would enable on the strength of these hints. + return 0; + }, + + xFileControl: function (pFile, opId, pArg) { + return capi.SQLITE_NOTFOUND; + }, + + xFileSize: function (pFile, pSz64) { + storeErr(); + try { + const file = fileFor(pFile); + const size = nodeFS.fstatSync(file.fd).size; + wasm.poke64(pSz64, BigInt(size)); + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR); + } + }, + + xLock: function (pFile, lockType) { + storeErr(); + try { + fileFor(pFile).lockType = lockType; + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR); + } + }, + + xRead: function (pFile, pDest, n, offset64) { + storeErr(); + try { + const file = fileFor(pFile); + const view = heapView(pDest, n); + const nRead = nodeFS.readSync( + file.fd, + view, + 0, + n, + Number(offset64) + ); + if (nRead < n) { + // SQLite requires the tail of a short read to be zeroed. + view.fill(0, nRead, n); + return capi.SQLITE_IOERR_SHORT_READ; + } + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR_READ); + } + }, + + xSectorSize: function (pFile) { + return SECTOR_SIZE; + }, + + xSync: function (pFile, flags) { + storeErr(); + try { + const file = fileFor(pFile); + // A durability barrier is the whole point of xSync, so this + // deliberately does not degrade to fdatasync on the DATAONLY + // hint: file size changes must reach the disk too. + nodeFS.fsyncSync(file.fd); + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR_FSYNC); + } + }, + + xTruncate: function (pFile, sz64) { + storeErr(); + try { + nodeFS.ftruncateSync(fileFor(pFile).fd, Number(sz64)); + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR_TRUNCATE); + } + }, + + xUnlock: function (pFile, lockType) { + storeErr(); + try { + fileFor(pFile).lockType = lockType; + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR); + } + }, + + xWrite: function (pFile, pSrc, n, offset64) { + storeErr(); + try { + const file = fileFor(pFile); + const nWrote = nodeFS.writeSync( + file.fd, + heapView(pSrc, n), + 0, + n, + Number(offset64) + ); + if (nWrote !== n) { + throw new Error( + `short write: wrote ${nWrote} of ${n} bytes` + ); + } + return 0; + } catch (error) { + return storeErr(error, capi.SQLITE_IOERR_WRITE); + } + }, + }; + + const nodeIoMethods = new capi.sqlite3_io_methods(); + nodeIoMethods.$iVersion = 1; + sqlite3.vfs.installVfs({ + io: { struct: nodeIoMethods, methods: ioMethods }, + }); + + const vfsMethods = { + xAccess: function (pVfs, zName, flags, pOut) { + storeErr(); + try { + const target = resolvePath(wasm.cstrToJs(zName)); + let mode = nodeFS.constants.F_OK; + if (flags === capi.SQLITE_ACCESS_READWRITE) { + mode = nodeFS.constants.R_OK | nodeFS.constants.W_OK; + } else if (flags === capi.SQLITE_ACCESS_READ) { + mode = nodeFS.constants.R_OK; + } + nodeFS.accessSync(target, mode); + wasm.poke32(pOut, 1); + } catch (_) { + wasm.poke32(pOut, 0); + } + return 0; + }, + + xCurrentTime: function (pVfs, pOut) { + wasm.poke( + pOut, + 2440587.5 + new Date().getTime() / 86400000, + "double" + ); + return 0; + }, + + xCurrentTimeInt64: function (pVfs, pOut) { + wasm.poke(pOut, 2440587.5 * 86400000 + new Date().getTime(), "i64"); + return 0; + }, + + xDelete: function (pVfs, zName, doSyncDir) { + storeErr(); + try { + nodeFS.unlinkSync(resolvePath(wasm.cstrToJs(zName))); + return 0; + } catch (error) { + if (error.code === "ENOENT") { + return 0; + } + storeErr(error); + return capi.SQLITE_IOERR_DELETE; + } + }, + + xFullPathname: function (pVfs, zName, nOut, pOut) { + // SQLite builds the journal and WAL names by appending suffixes to + // whatever this returns, so it must be the real absolute path. + // Otherwise a journal would land somewhere the database is not. + const full = resolvePath(wasm.cstrToJs(zName)); + const scope = wasm.scopedAllocPush(); + try { + const cFull = wasm.scopedAllocCString(full); + const written = wasm.cstrncpy(pOut, cFull, nOut); + return written < nOut ? 0 : capi.SQLITE_CANTOPEN; + } catch (error) { + storeErr(error); + return capi.SQLITE_CANTOPEN; + } finally { + wasm.scopedAllocPop(scope); + } + }, + + xGetLastError: function (pVfs, nOut, pOut) { + const error = popErr(); + if (error) { + const scope = wasm.scopedAllocPush(); + try { + const [cMsg, n] = wasm.scopedAllocCString( + error.message, + true + ); + wasm.cstrncpy(pOut, cMsg, nOut); + if (n > nOut) { + wasm.poke8(wasm.ptr.add(pOut, nOut, -1), 0); + } + } catch (_) { + return capi.SQLITE_NOMEM; + } finally { + wasm.scopedAllocPop(scope); + } + } + return error ? error.sqlite3Rc || capi.SQLITE_IOERR : 0; + }, + + xOpen: function (pVfs, zName, pFile, flags, pOutFlags) { + storeErr(); + let fd = -1; + let target = ""; + let took = false; + try { + const isMainDB = !!(flags & capi.SQLITE_OPEN_MAIN_DB); + const create = !!(flags & capi.SQLITE_OPEN_CREATE); + const readOnly = !!(flags & capi.SQLITE_OPEN_READONLY); + + // A null name asks for an anonymous temp file. SQLite deletes + // it on close, so a random name in the root directory is + // enough. + target = + zName && wasm.peek8(zName) + ? resolvePath(wasm.cstrToJs(zName)) + : nodePath.join( + rootDir, + `etilqs_${nodeCrypto + .randomBytes(12) + .toString("hex")}` + ); + + if (create) { + // The host may not have created the data directory yet. + // Creating it here keeps a first run from failing on a + // missing parent rather than on anything meaningful. + nodeFS.mkdirSync(nodePath.dirname(target), { + recursive: true, + }); + } + + let openMode; + if (readOnly) { + openMode = "r"; + } else if (create) { + // "a+" would force every write to the end of the file, so + // open read/write and create the file separately when it + // is missing. + if (!nodeFS.existsSync(target)) { + nodeFS.closeSync( + nodeFS.openSync(target, "w", 0o600) + ); + } + openMode = "r+"; + } else { + openMode = "r+"; + } + + if (isMainDB && !readOnly) { + acquireLock(target); + took = true; + } + + fd = nodeFS.openSync(target, openMode); + + openFiles.set(Number(pFile), { + fd, + path: target, + flags, + locked: took, + lockType: capi.SQLITE_LOCK_NONE, + }); + + const sq3File = new capi.sqlite3_file(pFile); + sq3File.$pMethods = nodeIoMethods.pointer; + sq3File.dispose(); + if (pOutFlags) { + wasm.poke32(pOutFlags, flags); + } + return 0; + } catch (error) { + if (fd >= 0) { + try { + nodeFS.closeSync(fd); + } catch (_) {} + } + if (took) { + releaseLock(target); + } + storeErr(error); + return capi.SQLITE_CANTOPEN; + } + }, + + xRandomness: function (pVfs, nOut, pOut) { + const bytes = nodeCrypto.randomBytes(nOut); + heapView(pOut, nOut).set(bytes); + return nOut; + }, + + xSleep: function (pVfs, microseconds) { + // SQLite calls this from inside a busy handler, so returning + // without sleeping would turn a busy timeout into a tight spin + // that burns a core for however long the timeout is. Atomics.wait + // blocks this thread for real, and it is safe precisely because + // this VFS only ever runs inside the dedicated SQLite worker, + // never on a thread anyone else's event loop depends on. + const ms = Math.max(1, Math.round(Number(microseconds) / 1000)); + Atomics.wait(sleepSignal, 0, 0, ms); + return 0; + }, + }; + + const nodeVfs = new capi.sqlite3_vfs(); + nodeVfs.$iVersion = 2; + nodeVfs.$szOsFile = capi.sqlite3_file.structInfo.sizeof; + nodeVfs.$mxPathname = 1024; + nodeVfs.addOnDispose((nodeVfs.$zName = wasm.allocCString(vfsName))); + sqlite3.vfs.installVfs({ + vfs: { struct: nodeVfs, methods: vfsMethods }, + }); + + const util = { + vfsName, + rootDir, + getVfs: () => nodeVfs, + openFileCount: () => openFiles.size, + }; + + if (!installNodeFsVfs.installed) { + installNodeFsVfs.installed = new Map(); + } + installNodeFsVfs.installed.set(vfsName, util); + + return util; +} + +module.exports = { + DEFAULT_VFS_NAME, + installNodeFsVfs, + isNodeHost, +}; diff --git a/bridge/sqlite-worker.js b/bridge/sqlite-worker.js index b57b9be..3f2d6ce 100644 --- a/bridge/sqlite-worker.js +++ b/bridge/sqlite-worker.js @@ -1,12 +1,38 @@ // Dedicated SQLite worker using the supported sqlite3.oo1 API directly. +// +// This file runs in two very different workers: a browser Web Worker, where +// SQLite persists through OPFS, and a node:worker_threads worker, where it +// persists through the node:fs VFS in sqlite-node-vfs.js. The two hosts differ +// in how scripts load, how the wasm binary is fetched, and how messages cross +// the thread boundary, so each of those three seams is behind a small +// abstraction rather than being sprinkled through the request handlers. const workerProtocolVersion = 1; let sqlite3; let nextDbId = 1; const dbs = new Map(); -const openOPFSFiles = new Map(); +const openPersistentFiles = new Map(); let sqliteJSURL = "sqlite3.js"; +// isNodeWorker reports whether we are running under node:worker_threads. A +// browser Worker has importScripts and no Node process object, so the two +// hosts are cleanly distinguishable. +const isNodeWorker = + typeof globalThis.process === "object" && + !!globalThis.process?.versions?.node && + typeof globalThis.importScripts !== "function"; + +// nodeParentPort and nodeAssetDir are the Node-only handles: the message +// channel back to the bridge, and the directory the bridge told us the runtime +// assets live in. Both are undefined in a browser. +let nodeParentPort; +let nodeAssetDir = ""; +if (isNodeWorker) { + const workerThreads = require("node:worker_threads"); + nodeParentPort = workerThreads.parentPort; + nodeAssetDir = workerThreads.workerData?.assetDir || process.cwd(); +} + function normalizeError(error) { if (!error) return "unknown sqlite worker error"; if (error.stack) return error.stack; @@ -22,12 +48,76 @@ function hasVFS(name) { return !!sqlite3.capi.sqlite3_vfs_find(name); } +// loadSQLiteInBrowser loads sqlite3.js the way a Web Worker does, letting +// Emscripten fetch sqlite3.wasm over the network relative to that script. +async function loadSQLiteInBrowser() { + importScripts(sqliteJSURL); + return sqlite3InitModule(); +} + +// loadSQLiteInNode loads sqlite3.js off disk. Emscripten's default loader +// would fetch() the wasm binary by relative URL, which Node cannot resolve +// into an absolute one, so the binary is handed over directly instead. +async function loadSQLiteInNode() { + const nodeFS = require("node:fs"); + const nodePath = require("node:path"); + + const jsPath = nodePath.isAbsolute(sqliteJSURL) + ? sqliteJSURL + : nodePath.join(nodeAssetDir, sqliteJSURL); + const wasmPath = nodePath.join(nodePath.dirname(jsPath), "sqlite3.wasm"); + + // Every OPFS VFS needs browser APIs that do not exist here, and sqlite3.js + // reports each failed install as a stack trace on stderr. Turning them off + // up front keeps a normal Node startup quiet, so a warning that does appear + // is worth reading. + globalThis.sqlite3ApiConfig = Object.assign( + {}, + globalThis.sqlite3ApiConfig, + { + disable: { + vfs: { + opfs: true, + "opfs-vfs": true, + "opfs-sahpool": true, + "opfs-wl": true, + }, + }, + } + ); + + const init = require(jsPath); + return init({ + instantiateWasm(imports, onSuccess) { + const bytes = nodeFS.readFileSync(wasmPath); + WebAssembly.instantiate(bytes, imports).then((result) => { + onSuccess(result.instance, result.module); + }); + return {}; + }, + }); +} + async function ensureSQLite(options = {}) { if (sqlite3) return sqlite3; sqliteJSURL = options.sqliteJSURL || sqliteJSURL; - importScripts(sqliteJSURL); - sqlite3 = await sqlite3InitModule(); + sqlite3 = isNodeWorker + ? await loadSQLiteInNode() + : await loadSQLiteInBrowser(); + + if (isNodeWorker) { + // Node has a real filesystem, so the durable VFS is installed eagerly and + // its absence is fatal rather than something to warn about: there is no + // second durable option to fall through to here. + const nodePath = require("node:path"); + const { installNodeFsVfs } = require( + nodePath.join(nodeAssetDir, "sqlite-node-vfs.js") + ); + installNodeFsVfs(sqlite3, { directory: options.rootDir || undefined }); + + return sqlite3; + } if (sqlite3.installOpfsSAHPoolVfs && !hasVFS("opfs-sahpool")) { await sqlite3.installOpfsSAHPoolVfs({ name: "opfs-sahpool" }).catch((error) => { @@ -65,12 +155,29 @@ function normalizeRequestedVFS(vfs) { case "opfs-sah": case "sahpool": return "opfs-sahpool"; + case "node": + case "node-fs": + case "nodefs": + return "nodefs"; default: return vfs; } } -function normalizeOPFSFilename(file) { +// autoVFSCandidates lists the durable VFSes to try, best first, when the +// caller did not name one. The lists do not overlap because no host offers +// both OPFS and node:fs. +function autoVFSCandidates() { + return isNodeWorker ? ["nodefs"] : ["opfs-wl", "opfs-sahpool", "opfs"]; +} + +// normalizePersistentFilename adapts a caller's filename to what the target +// VFS expects. OPFS wants an origin-local path rooted at "/", while the +// node:fs VFS resolves names against a real directory and must be left alone: +// forcing a leading slash there would rewrite every relative database name +// into one at the filesystem root. +function normalizePersistentFilename(vfsName, file) { + if (vfsName === "nodefs") return file; if (file.startsWith("/") || file.startsWith("file:")) return file; return `/${file}`; } @@ -329,11 +436,11 @@ async function openPersistentDB(vfsName, filename, uriParams, args) { throw new Error(`requested SQLite VFS is unavailable: ${vfsName}`); } - let resolvedFilename = normalizeOPFSFilename(filename); + let resolvedFilename = normalizePersistentFilename(vfsName, filename); const resolved = makeURI(resolvedFilename, uriParams); - const duplicateKey = `opfs:${resolved}`; - if (openOPFSFiles.has(duplicateKey)) { - throw new Error(`OPFS database already open in this worker: ${resolved}`); + const duplicateKey = `${vfsName}:${resolved}`; + if (openPersistentFiles.has(duplicateKey)) { + throw new Error(`database already open in this worker: ${resolved}`); } let db; @@ -345,8 +452,8 @@ async function openPersistentDB(vfsName, filename, uriParams, args) { resolvedFilename = db.dbFilename(); const vfs = db.dbVfsName() || vfsName; - openOPFSFiles.set(duplicateKey, true); - db.__opfsKey = duplicateKey; + openPersistentFiles.set(duplicateKey, true); + db.__persistentKey = duplicateKey; return { db, filename: resolvedFilename, vfs, persistent: true }; } @@ -377,7 +484,7 @@ async function open(args) { opened = openMemoryDB(args); } else { const candidates = requestedVFS === "auto" - ? ["opfs-wl", "opfs-sahpool", "opfs"] + ? autoVFSCandidates() : [requestedVFS]; const failures = []; for (const candidate of candidates) { @@ -401,9 +508,9 @@ async function open(args) { } if (!opened) { if (args.requirePersistent) { - throw new Error(`persistent storage required but no OPFS VFS opened; tried ${failures.join("; ")}`); + throw new Error(`persistent storage required but no durable VFS opened; tried ${failures.join("; ")}`); } - sqlite3.config.warn("OPFS VFS unavailable, falling back to :memory:", failures.join("; ")); + sqlite3.config.warn("no durable VFS available, falling back to :memory:", failures.join("; ")); opened = openMemoryDB(args); } } @@ -460,7 +567,7 @@ async function close(args) { const db = dbs.get(args.dbId); if (!db) return {}; - if (db.__opfsKey) openOPFSFiles.delete(db.__opfsKey); + if (db.__persistentKey) openPersistentFiles.delete(db.__persistentKey); db.close(); dbs.delete(args.dbId); return {}; @@ -521,14 +628,26 @@ async function load(args) { const methods = { init, open, exec, execBatch, query, begin, commit, rollback, close, dump, load }; -globalThis.onmessage = async (event) => { - const message = event.data || {}; +// handleMessage is the host-independent request handler. Both worker flavors +// deliver the same {id, method, args} envelope and expect the same +// {id, ok, result|error} reply; only the transport differs. +async function handleMessage(message = {}) { try { const method = methods[message.method]; if (!method) throw new Error(`unknown sqlite worker method: ${message.method}`); const result = await method(message.args || {}); - globalThis.postMessage({ id: message.id, ok: true, result }); + return { id: message.id, ok: true, result }; } catch (error) { - globalThis.postMessage({ id: message.id, ok: false, error: normalizeError(error) }); + return { id: message.id, ok: false, error: normalizeError(error) }; } -}; +} + +if (isNodeWorker) { + nodeParentPort.on("message", async (message) => { + nodeParentPort.postMessage(await handleMessage(message || {})); + }); +} else { + globalThis.onmessage = async (event) => { + globalThis.postMessage(await handleMessage(event.data || {})); + }; +} diff --git a/bridge_adapter.go b/bridge_adapter.go index 1d324a7..7ae065a 100644 --- a/bridge_adapter.go +++ b/bridge_adapter.go @@ -431,9 +431,18 @@ func (b *BridgeAdapter) callAsyncContext(ctx context.Context, method js.Value, a errorMsg = error.String() } } - fmt.Printf("JavaScript error details: %s\n", errorMsg) } + // Nothing here may block. This function body runs inside + // syscall/js.handleEvent, so the Go scheduler cannot advance + // until it returns, and any operation that parks waiting on a + // JS callback deadlocks the whole runtime. Writing to stdout is + // exactly such an operation on a host whose fs.write is + // genuinely asynchronous, which is the case under Node: a + // diagnostic print here hung the process instead of reporting + // the error. The message reaches the caller through the error + // below either way. + done <- struct { result js.Value err error diff --git a/driver.go b/driver.go index 96668f9..7af797b 100644 --- a/driver.go +++ b/driver.go @@ -288,6 +288,8 @@ func (c *Conn) GetVFSType() VFSType { return VFSTypeOPFSWebLocks case "opfs-sahpool": return VFSTypeOPFSSAHPool + case "nodefs": + return VFSTypeNodeFS case "memory": return VFSTypeMemory default: diff --git a/driver_node_js_wasm_test.go b/driver_node_js_wasm_test.go new file mode 100644 index 0000000..431b11c --- /dev/null +++ b/driver_node_js_wasm_test.go @@ -0,0 +1,221 @@ +//go:build js && wasm + +package wasmsqlite + +import ( + "context" + "database/sql" + "errors" + "fmt" + "os" + "path/filepath" + "testing" + "time" +) + +// nodeTestDir returns the scratch directory the Node runner created for this +// test process, and skips when the tests are not running under that runner. +// The browser suite shares this file's package but has no filesystem, so every +// test here has to be able to sit out a browser run. +func nodeTestDir(t *testing.T) string { + t.Helper() + + if os.Getenv("WASMSQLITE_NODE_TEST") != "1" { + t.Skip("not running under the Node test runner") + } + + dir := os.Getenv("WASMSQLITE_NODE_TEST_DIR") + if dir == "" { + t.Fatal("WASMSQLITE_NODE_TEST_DIR is unset") + } + + return dir +} + +// nodeDBPath returns a unique database path under the scratch directory. Each +// test gets its own file because the worker refuses to open one database +// twice, which is a property another test asserts on purpose. +func nodeDBPath(t *testing.T, name string) string { + t.Helper() + + return filepath.Join( + nodeTestDir(t), fmt.Sprintf("%s-%d.db", name, time.Now().UnixNano()), + ) +} + +// TestNodeDriverPersistsToHostFilesystem is the end-to-end claim of the Node +// backend: data written through database/sql lands in a real file and is still +// there after the handle is closed and reopened. +func TestNodeDriverPersistsToHostFilesystem(t *testing.T) { + path := nodeDBPath(t, "persist") + + db, err := Open(&Options{ + File: path, + VFS: string(VFSTypeNodeFS), + BusyTimeout: 5000, + RequirePersistent: true, + }) + if err != nil { + t.Fatalf("open node db: %v", err) + } + + info, err := GetStorageInfo(db) + if err != nil { + t.Fatalf("storage info: %v", err) + } + + if info.VFSType != VFSTypeNodeFS { + t.Fatalf("expected %s VFS, got %s", VFSTypeNodeFS, info.VFSType) + } + if !info.Persistent { + t.Fatal("node:fs database reported as non-persistent") + } + if info.Memory { + t.Fatal("node:fs database reported as in-memory") + } + + _, err = db.Exec(`CREATE TABLE vtxo ( + id INTEGER PRIMARY KEY, + outpoint TEXT NOT NULL, + amount INTEGER NOT NULL, + script BLOB + )`) + if err != nil { + t.Fatalf("create table: %v", err) + } + + script := []byte{0xde, 0xad, 0xbe, 0xef} + _, err = db.Exec( + "INSERT INTO vtxo (outpoint, amount, script) VALUES (?, ?, ?)", + "txid:0", int64(21_000_000), script, + ) + if err != nil { + t.Fatalf("insert: %v", err) + } + if err := db.Close(); err != nil { + t.Fatalf("close db: %v", err) + } + + // The file must exist on the host filesystem, not merely inside the + // SQLite worker's idea of one. + stat, err := os.Stat(path) + if err != nil { + t.Fatalf("stat database file: %v", err) + } + if stat.Size() == 0 { + t.Fatal("database file is empty") + } + + reopened, err := Open(&Options{ + File: path, + VFS: string(VFSTypeNodeFS), + BusyTimeout: 5000, + RequirePersistent: true, + }) + if err != nil { + t.Fatalf("reopen node db: %v", err) + } + defer reopened.Close() + + var ( + outpoint string + amount int64 + gotScript []byte + ) + row := reopened.QueryRow( + "SELECT outpoint, amount, script FROM vtxo WHERE id = 1", + ) + if err := row.Scan(&outpoint, &amount, &gotScript); err != nil { + t.Fatalf("scan after reopen: %v", err) + } + + if outpoint != "txid:0" { + t.Fatalf("outpoint did not survive reopen: %q", outpoint) + } + if amount != 21_000_000 { + t.Fatalf("amount did not survive reopen: %d", amount) + } + if string(gotScript) != string(script) { + t.Fatalf("blob did not survive reopen: %x", gotScript) + } +} + +// TestNodeDriverTransactions checks that the transaction verbs reach the same +// worker connection, so a rollback actually discards the work. +func TestNodeDriverTransactions(t *testing.T) { + path := nodeDBPath(t, "tx") + + db, err := Open(&Options{ + File: path, + VFS: string(VFSTypeNodeFS), + BusyTimeout: 5000, + RequirePersistent: true, + }) + if err != nil { + t.Fatalf("open node db: %v", err) + } + defer db.Close() + + if _, err := db.Exec("CREATE TABLE t (a INTEGER)"); err != nil { + t.Fatalf("create table: %v", err) + } + + committed, err := db.Begin() + if err != nil { + t.Fatalf("begin: %v", err) + } + if _, err := committed.Exec("INSERT INTO t VALUES (1)"); err != nil { + t.Fatalf("insert in committed tx: %v", err) + } + if err := committed.Commit(); err != nil { + t.Fatalf("commit: %v", err) + } + + rolledBack, err := db.Begin() + if err != nil { + t.Fatalf("begin: %v", err) + } + if _, err := rolledBack.Exec("INSERT INTO t VALUES (2)"); err != nil { + t.Fatalf("insert in rolled back tx: %v", err) + } + if err := rolledBack.Rollback(); err != nil { + t.Fatalf("rollback: %v", err) + } + + var count int + if err := db.QueryRow("SELECT count(*) FROM t").Scan(&count); err != nil { + t.Fatalf("count: %v", err) + } + if count != 1 { + t.Fatalf("expected 1 surviving row, got %d", count) + } +} + +// TestNodeDriverContextCancellation checks that a cancelled context stops the +// Go side waiting on the worker instead of hanging until the query finishes. +func TestNodeDriverContextCancellation(t *testing.T) { + path := nodeDBPath(t, "ctx") + + db, err := Open(&Options{ + File: path, + VFS: string(VFSTypeNodeFS), + BusyTimeout: 5000, + RequirePersistent: true, + }) + if err != nil { + t.Fatalf("open node db: %v", err) + } + defer db.Close() + + if _, err := db.Exec("CREATE TABLE t (a INTEGER)"); err != nil { + t.Fatalf("create table: %v", err) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, err = db.ExecContext(ctx, "INSERT INTO t VALUES (1)") + if !errors.Is(err, context.Canceled) && !errors.Is(err, sql.ErrConnDone) { + t.Fatalf("expected a cancellation error, got %v", err) + } +} diff --git a/embed.go b/embed.go index c6740be..808d492 100644 --- a/embed.go +++ b/embed.go @@ -12,7 +12,7 @@ import ( // Embed all assets and bridge files // -//go:embed assets/* bridge/sqlite-bridge.js bridge/sqlite-worker.js +//go:embed assets/* bridge/sqlite-bridge.js bridge/sqlite-worker.js bridge/sqlite-node-vfs.js var embeddedAssets embed.FS var runtimeAssetPaths = map[string]string{ @@ -21,6 +21,7 @@ var runtimeAssetPaths = map[string]string{ "sqlite3-opfs-async-proxy.js": "assets/sqlite3-opfs-async-proxy.js", "sqlite-bridge.js": "bridge/sqlite-bridge.js", "sqlite-worker.js": "bridge/sqlite-worker.js", + "sqlite-node-vfs.js": "bridge/sqlite-node-vfs.js", } // ExtractAssets extracts all embedded SQLite WASM assets to the specified @@ -151,6 +152,16 @@ func GetWorkerJS() (string, error) { return string(data), nil } +// GetNodeVFSJS returns the node:fs SQLite VFS. It is only loaded when the +// worker runs under Node; a browser host can ship the runtime without it. +func GetNodeVFSJS() (string, error) { + data, err := GetAsset("bridge/sqlite-node-vfs.js") + if err != nil { + return "", err + } + return string(data), nil +} + // ListAssets returns a list of all embedded asset paths. func ListAssets() ([]string, error) { var assets []string diff --git a/embed_test.go b/embed_test.go index 0b40df4..f42b783 100644 --- a/embed_test.go +++ b/embed_test.go @@ -24,6 +24,7 @@ func TestEmbeddedAssets(t *testing.T) { "assets/sqlite3-opfs-async-proxy.js", "bridge/sqlite-bridge.js", "bridge/sqlite-worker.js", + "bridge/sqlite-node-vfs.js", } for _, expected := range expectedFiles { @@ -71,6 +72,14 @@ func TestEmbeddedAssets(t *testing.T) { if len(worker) == 0 { t.Error("Worker JS is empty") } + + nodeVFS, err := GetNodeVFSJS() + if err != nil { + t.Errorf("Failed to get node VFS JS: %v", err) + } + if len(nodeVFS) == 0 { + t.Error("Node VFS JS is empty") + } } func TestExtractAssets(t *testing.T) { @@ -94,6 +103,7 @@ func TestExtractAssets(t *testing.T) { "sqlite3-opfs-async-proxy.js", "sqlite-bridge.js", "sqlite-worker.js", + "sqlite-node-vfs.js", } for _, file := range expectedFiles { diff --git a/example/.gitignore b/example/.gitignore index dd0ba2b..beb06ce 100644 --- a/example/.gitignore +++ b/example/.gitignore @@ -4,4 +4,5 @@ sqlite3.wasm wasm_exec.js sqlite-bridge.js sqlite-worker.js +sqlite-node-vfs.js sqlite3* diff --git a/open.go b/open.go index 015b535..4e3c8f2 100644 --- a/open.go +++ b/open.go @@ -19,8 +19,10 @@ type Options struct { // File path for the database (default: "/app.db") File string - // VFS to use (default: "auto", which tries opfs-wl, opfs-sahpool, opfs, - // then memory unless persistent storage is required). + // VFS to use (default: "auto", which tries the durable VFSes available on + // this host, then memory unless persistent storage is required). In a + // browser those are opfs-wl, opfs-sahpool, and opfs; under Node the only + // one is nodefs, backed by node:fs. VFS string // Busy timeout in milliseconds (default: 5000) diff --git a/package.json b/package.json index 4ab98ae..6140810 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "scripts": { "test": "playwright test", "test:playwright": "playwright test", + "test:node": "node --test tests/node-backend.test.cjs", "serve:example": "make build-example && cd example && node server.js", "playwright:install": "playwright install chromium" }, diff --git a/playwright.config.js b/playwright.config.js index 830edeb..b76dee5 100644 --- a/playwright.config.js +++ b/playwright.config.js @@ -2,6 +2,10 @@ const { defineConfig } = require("@playwright/test"); module.exports = defineConfig({ testDir: "./tests", + // The Node storage backend tests live alongside these but run under + // node:test, not Playwright, so they are matched out rather than picked up + // and failed on syntax Playwright does not provide. + testMatch: "**/*.spec.js", timeout: 120000, expect: { timeout: 30000 diff --git a/scripts/node-wasm-test-exec.cjs b/scripts/node-wasm-test-exec.cjs new file mode 100644 index 0000000..f50701b --- /dev/null +++ b/scripts/node-wasm-test-exec.cjs @@ -0,0 +1,107 @@ +// go test -exec wrapper that runs a js/wasm test binary under Node with the +// SQLite bridge loaded, the same way an application host would. +// +// Usage: node scripts/node-wasm-test-exec.cjs [args...] +// +// It is the Node counterpart of wasm_exec_node.js, with three additions a real +// host also needs: a real filesystem for Go, the runtime asset directory the +// bridge looks in, and the EventTarget methods a browser puts on the global +// object and Node does not. + +"use strict"; + +const fs = require("node:fs"); +const path = require("node:path"); +const os = require("node:os"); + +if (process.argv.length < 3) { + console.error("usage: node-wasm-test-exec.cjs [args...]"); + process.exit(1); +} + +const repoRoot = path.resolve(__dirname, ".."); + +// stageRuntime lays out the flat asset directory the bridge and worker expect, +// since the repository keeps assets and bridge scripts apart. +function stageRuntime() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wasmsqlite-goexec-")); + for (const [dest, src] of Object.entries({ + "sqlite3.js": "assets/sqlite3.js", + "sqlite3.wasm": "assets/sqlite3.wasm", + "sqlite-worker.js": "bridge/sqlite-worker.js", + "sqlite-node-vfs.js": "bridge/sqlite-node-vfs.js", + })) { + fs.copyFileSync(path.join(repoRoot, src), path.join(dir, dest)); + } + return dir; +} + +const runtimeDir = stageRuntime(); +const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "wasmsqlite-godata-")); + +globalThis.require = require; +globalThis.fs = fs; +globalThis.path = path; +globalThis.TextEncoder = require("util").TextEncoder; +globalThis.TextDecoder = require("util").TextDecoder; +globalThis.performance ??= require("performance"); +globalThis.crypto ??= require("crypto"); + +globalThis.sqliteBridgeAssetDir = runtimeDir; +globalThis.sqliteBridgeRootDir = dataDir; + +if (typeof globalThis.dispatchEvent !== "function") { + const events = new EventTarget(); + globalThis.addEventListener = events.addEventListener.bind(events); + globalThis.removeEventListener = events.removeEventListener.bind(events); + globalThis.dispatchEvent = events.dispatchEvent.bind(events); +} + +const bridgeSource = fs.readFileSync( + path.join(repoRoot, "bridge", "sqlite-bridge.js"), + "utf8" +); +new Function("require", "__dirname", bridgeSource)(require, runtimeDir); + +// Go's wasm_exec.js glue is versioned with the toolchain, so it is read from +// GOROOT rather than vendored here and left to drift. +const goroot = + process.env.GOROOT || + require("node:child_process") + .execFileSync("go", ["env", "GOROOT"], { encoding: "utf8" }) + .trim() + .split("\n") + .pop() + .trim(); +new Function( + fs.readFileSync(path.join(goroot, "lib", "wasm", "wasm_exec.js"), "utf8") +)(); + +const go = new globalThis.Go(); +go.argv = process.argv.slice(2); +go.env = Object.assign( + { + TMPDIR: os.tmpdir(), + WASMSQLITE_NODE_TEST: "1", + WASMSQLITE_NODE_TEST_DIR: dataDir, + }, + process.env +); +go.exit = process.exit; + +WebAssembly.instantiate(fs.readFileSync(process.argv[2]), go.importObject) + .then((result) => { + process.on("exit", (code) => { + // Node exits when nothing is pending; make Go report the + // deadlock rather than exiting silently. + if (code === 0 && !go.exited) { + go._pendingEvent = { id: 0 }; + go._resume(); + } + }); + return go.run(result.instance); + }) + .catch((err) => { + console.error(err); + process.exit(1); + }); diff --git a/tests/node-backend.test.cjs b/tests/node-backend.test.cjs new file mode 100644 index 0000000..48776b5 --- /dev/null +++ b/tests/node-backend.test.cjs @@ -0,0 +1,280 @@ +// Tests for the Node storage backend: the node:fs VFS, the worker_threads +// bridge, and the durable storage they provide. +// +// Run with: node --test tests/ +// +// These exercise the same bridge surface the Go driver drives through +// syscall/js, so a regression here is a regression the Go side would see. + +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); + +const repoRoot = path.resolve(__dirname, ".."); +const bridgePath = path.join(repoRoot, "bridge", "sqlite-bridge.js"); + +// runtimeDir stages the flat asset layout the bridge and worker expect, since +// the repository keeps assets and bridge scripts in separate directories. +function runtimeDir() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "wasmsqlite-rt-")); + for (const [dest, src] of Object.entries({ + "sqlite3.js": "assets/sqlite3.js", + "sqlite3.wasm": "assets/sqlite3.wasm", + "sqlite-worker.js": "bridge/sqlite-worker.js", + "sqlite-node-vfs.js": "bridge/sqlite-node-vfs.js", + })) { + fs.copyFileSync(path.join(repoRoot, src), path.join(dir, dest)); + } + return dir; +} + +const sharedRuntime = runtimeDir(); + +// loadBridge evaluates sqlite-bridge.js the way a Go WASM host does, into a +// fresh global slot, and returns the installed bridge object. +function loadBridge(assetDir) { + delete globalThis.sqliteBridge; + globalThis.sqliteBridgeAssetDir = assetDir; + const source = fs.readFileSync(bridgePath, "utf8"); + new Function("require", "__dirname", source)(require, assetDir); + return globalThis.sqliteBridge; +} + +function tempDataDir() { + return fs.mkdtempSync(path.join(os.tmpdir(), "wasmsqlite-data-")); +} + +// withBridge runs body against a freshly started bridge and always shuts the +// worker down, so a failing assertion cannot leave a thread pinning the test +// process open. +async function withBridge(body) { + const bridge = loadBridge(sharedRuntime); + try { + return await body(bridge); + } finally { + await bridge.shutdown(); + } +} + +test("bridge starts a node worker and reports both protocol versions", async () => { + await withBridge(async (bridge) => { + const result = await bridge.init(); + assert.strictEqual(result.ok, true); + assert.strictEqual(result.bridgeProtocolVersion, 1); + assert.strictEqual(result.workerProtocolVersion, 1); + assert.ok( + result.vfsList.includes("nodefs"), + `nodefs missing from ${JSON.stringify(result.vfsList)}` + ); + }); +}); + +test("nodefs writes a real host file and survives reopen", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "nested", "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + }); + assert.strictEqual(opened.persistent, true); + assert.strictEqual(opened.vfsType, "nodefs"); + + await bridge.exec(opened.dbId, "CREATE TABLE vtxo(id INTEGER PRIMARY KEY, amt INTEGER)"); + await bridge.exec(opened.dbId, "INSERT INTO vtxo(amt) VALUES(?)", [4200]); + await bridge.close(opened.dbId); + }); + + assert.ok(fs.existsSync(dbPath), "database file was not created on the host"); + assert.ok(fs.statSync(dbPath).size > 0, "database file is empty"); + + await withBridge(async (bridge) => { + const reopened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + }); + const rows = await bridge.query(reopened.dbId, "SELECT amt FROM vtxo"); + assert.deepStrictEqual(rows.rows, [[4200]]); + await bridge.close(reopened.dbId); + }); +}); + +test("an explicit memory request still works", async () => { + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: ":memory:", mode: "rwc" }); + assert.strictEqual(opened.persistent, false); + assert.strictEqual(opened.vfsType, "memory"); + await bridge.exec(opened.dbId, "CREATE TABLE t(a)"); + await bridge.close(opened.dbId); + }); +}); + +test("a second open of the same file in one worker is refused", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const first = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await assert.rejects( + () => bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }), + /already open/i + ); + await bridge.close(first.dbId); + }); +}); + +test("a second process cannot open the same database", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const first = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(first.dbId, "CREATE TABLE t(a)"); + + // A live lock file naming another running process must block the open. + // The current process is a stand-in for a second holder: its pid is + // provably alive, which is the condition the lock check turns on. + const lockPath = `${dbPath}-nodefs-lock`; + assert.ok(fs.existsSync(lockPath), "no lock file was taken"); + const owner = JSON.parse(fs.readFileSync(lockPath, "utf8")); + assert.strictEqual(owner.pid, process.pid); + + await bridge.close(first.dbId); + assert.ok(!fs.existsSync(lockPath), "lock file outlived the database"); + }); +}); + +test("a stale lock from a dead process is reclaimed", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + fs.writeFileSync(dbPath, ""); + + // pid 0x7FFFFFFF will not be running; the lock must be treated as stale + // rather than stranding the database forever after a crash. + fs.writeFileSync( + `${dbPath}-nodefs-lock`, + JSON.stringify({ pid: 0x7fffffff, at: Date.now() }) + ); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a)"); + await bridge.close(opened.dbId); + }); +}); + +test("transactions commit and roll back through the worker", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a INTEGER)"); + + await bridge.begin(opened.dbId); + await bridge.exec(opened.dbId, "INSERT INTO t VALUES(1)"); + await bridge.commit(opened.dbId); + + await bridge.begin(opened.dbId); + await bridge.exec(opened.dbId, "INSERT INTO t VALUES(2)"); + await bridge.rollback(opened.dbId); + + const rows = await bridge.query(opened.dbId, "SELECT a FROM t ORDER BY a"); + assert.deepStrictEqual(rows.rows, [[1]]); + await bridge.close(opened.dbId); + }); +}); + +test("blobs and large integers round-trip through the worker", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(opened.dbId, "CREATE TABLE t(h BLOB, n INTEGER)"); + + const preimage = new Uint8Array(32).fill(0xab); + await bridge.exec(opened.dbId, "INSERT INTO t VALUES(?, ?)", [ + preimage, + { __wasmSqliteInt64: "9007199254740993" }, + ]); + + const rows = await bridge.query(opened.dbId, "SELECT h, n FROM t"); + assert.deepStrictEqual(Array.from(rows.rows[0][0]), Array.from(preimage)); + assert.strictEqual(String(rows.rows[0][1]), "9007199254740993"); + await bridge.close(opened.dbId); + }); +}); + +test("a batched write is durable and atomic", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a INTEGER)"); + + const rows = []; + for (let i = 0; i < 200; i++) rows.push([i]); + const result = await bridge.execBatch(opened.dbId, "INSERT INTO t VALUES(?)", rows); + assert.strictEqual(result.batchCount, 200); + + const count = await bridge.query(opened.dbId, "SELECT count(*) FROM t"); + assert.strictEqual(count.rows[0][0], 200); + await bridge.close(opened.dbId); + }); + + await withBridge(async (bridge) => { + const reopened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + const count = await bridge.query(reopened.dbId, "SELECT count(*) FROM t"); + assert.strictEqual(count.rows[0][0], 200); + await bridge.close(reopened.dbId); + }); +}); + +test("VACUUM INTO creates a second file through the same VFS", async () => { + // The schema migration path backs the database up with VACUUM INTO before + // it touches anything, so a VFS that cannot create a second file at an + // arbitrary path fails every first run. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const backupPath = path.join(dataDir, "wallet.db.backup"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a INTEGER)"); + await bridge.exec(opened.dbId, "INSERT INTO t VALUES(1)"); + await bridge.exec(opened.dbId, `VACUUM INTO '${backupPath}'`); + await bridge.close(opened.dbId); + }); + + assert.ok(fs.existsSync(backupPath), "VACUUM INTO produced no backup file"); + assert.ok(fs.statSync(backupPath).size > 0); +}); + +test("relative database names resolve under the configured root", async () => { + const dataDir = tempDataDir(); + + await withBridge(async (bridge) => { + await bridge.init({ rootDir: dataDir }); + const opened = await bridge.open({ + file: "relative.db", + vfs: "nodefs", + mode: "rwc", + }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a)"); + await bridge.close(opened.dbId); + }); + + assert.ok( + fs.existsSync(path.join(dataDir, "relative.db")), + `relative.db not under ${dataDir}: ${fs.readdirSync(dataDir)}` + ); +}); diff --git a/utils.go b/utils.go index 4ca4edf..2b8bbd8 100644 --- a/utils.go +++ b/utils.go @@ -18,8 +18,14 @@ const ( VFSTypeOPFS VFSType = "opfs" VFSTypeOPFSWebLocks VFSType = "opfs-wl" VFSTypeOPFSSAHPool VFSType = "opfs-sahpool" - VFSTypeMemory VFSType = "memory" - VFSTypeUnknown VFSType = "unknown" + + // VFSTypeNodeFS is the durable VFS on a Node host, backed by node:fs. + // It is as persistent as the OPFS VFSes, just on a real filesystem + // rather than an origin-private one. + VFSTypeNodeFS VFSType = "nodefs" + + VFSTypeMemory VFSType = "memory" + VFSTypeUnknown VFSType = "unknown" ) // StorageInfo reports the database storage backend selected by the browser. @@ -30,14 +36,17 @@ type StorageInfo struct { // VFSType is the VFS actually used by SQLite. VFSType VFSType - // Persistent is true when the database is backed by persistent browser - // storage instead of transient memory. + // Persistent is true when the database is backed by durable storage + // instead of transient memory: OPFS in a browser, the host filesystem + // under Node. Persistent bool // Memory is true when the database is using SQLite's in-memory storage. Memory bool // OPFS is true when the resolved VFS is one of SQLite's OPFS-backed VFSes. + // It answers which durable backend is in use, not whether the database is + // durable at all; ask Persistent for that. OPFS bool } From 2059143c1036d944ed168edc9269b122c74d8ec9 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Wed, 29 Jul 2026 00:22:25 -0700 Subject: [PATCH 2/7] bridge: refuse to silently substitute memory for durable storage In this commit, we make a request for durable storage a promise the worker either keeps or breaks loudly. Asking for vfs=opfs and getting a working in-memory database instead used to be the documented behavior, and it is the wrong default for anything whose database is the only copy of its state. A wallet is the clear case. Its VTXO, swap, and round state exists nowhere else, so a database that quietly turns out to be in memory looks completely healthy for the whole run and then takes the state with it when the process exits, which can lose funds. The failure is invisible at exactly the moment it could still be corrected, and irreversible afterwards. A startup error is a far better outcome than a wallet that silently forgets. Naming a durable VFS is now taken as a statement about durability, not a preference among equally acceptable options: if opfs, opfs-wl, opfs-sahpool, or nodefs is asked for and cannot be opened, the open fails. Only vfs=auto still falls back, since "auto" means whatever this host can do, and even then not when require_persistent is set. Callers whose durable open succeeds today see no change at all; only the failure path is different, and it now says so. --- CHANGELOG.md | 1 + CLAUDE.md | 4 ++- README.md | 6 +++- bridge/sqlite-worker.js | 22 ++++++++---- driver_node_js_wasm_test.go | 72 +++++++++++++++++++++++++++++++++++++ open.go | 8 ++++- tests/node-backend.test.cjs | 72 ++++++++++++++++++++++++++++++++++++- 7 files changed, 175 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6411b10..5896de4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - Added a Node storage backend: the `nodefs` VFS in `bridge/sqlite-node-vfs.js`, a `node:worker_threads` path in the bridge, and Node-aware script and wasm loading in the worker. +- Tightened the memory fallback: naming a durable VFS that cannot be opened is now an error rather than a silent `:memory:` substitution. Only `vfs=auto` without `require_persistent` may fall back. - Added `sqliteBridge.shutdown()` so a Node host can retire the worker thread and let its process exit. - Replaced SQLite Worker1/Promiser runtime usage with a dedicated `sqlite3.oo1` Worker. diff --git a/CLAUDE.md b/CLAUDE.md index 2fb22e6..bedff0d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -125,7 +125,9 @@ SQLite WASM uses these browser runtime files: - `Cross-Origin-Embedder-Policy: require-corp` ### VFS Fallback -If OPFS unavailable, automatically falls back to in-memory storage. +Only `vfs=auto` falls back to in-memory storage, and only when +`require_persistent` is not set. An explicitly named durable VFS (`opfs`, +`opfs-wl`, `opfs-sahpool`, `nodefs`) that cannot be opened is an error. ### Node hosts `bridge/sqlite-node-vfs.js` provides the `nodefs` VFS over the synchronous diff --git a/README.md b/README.md index 7892dd7..cdd1fdc 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,10 @@ Go App (WASM) In a browser it imports the script, spawns a Web Worker, and prefers `opfs-wl`, then `opfs-sahpool`, then `opfs`. Under Node it requires the script, spawns a `node:worker_threads` worker, and uses the `nodefs` VFS from `sqlite-node-vfs.js`, which maps SQLite's file operations onto the synchronous `node:fs` API. SQLite runs in a worker on both hosts, in a browser because OPFS needs worker-side file APIs and under Node so that a busy database cannot stall the host's event loop. +### Durable means durable + +Naming a durable VFS (`opfs`, `opfs-wl`, `opfs-sahpool`, or `nodefs`) is a promise the worker keeps or breaks loudly. If that VFS cannot be opened, the open fails; it never quietly returns an in-memory database instead. Only `vfs=auto` may settle for memory, and even then not when `require_persistent=true` is set. This matters for anything whose database is the only copy of its state, such as a wallet, where silently running against storage that evaporates on exit loses data that cannot be recovered from anywhere else. + ### Node hosts Under Node the host must give Go's `wasm_exec.js` a real filesystem before instantiating the WASM module, and must tell the bridge where the runtime assets live: @@ -37,7 +41,7 @@ Two Node processes must not write one database. The `nodefs` VFS enforces that w - Standard `database/sql` driver named `wasmsqlite` - OPFS persistence in supported browsers - Host filesystem persistence under Node through the `nodefs` VFS -- In-memory fallback when no durable storage is available +- In-memory fallback only when no durable VFS was requested - Transactions through `BEGIN IMMEDIATE`, `COMMIT`, and `ROLLBACK` - BLOB round trips through `[]byte` - Database dump/load helpers with BLOB-safe SQL literals diff --git a/bridge/sqlite-worker.js b/bridge/sqlite-worker.js index 3f2d6ce..84e701a 100644 --- a/bridge/sqlite-worker.js +++ b/bridge/sqlite-worker.js @@ -33,6 +33,16 @@ if (isNodeWorker) { nodeAssetDir = workerThreads.workerData?.assetDir || process.cwd(); } +// PERSISTENT_VFS_NAMES are the VFS names that promise durable storage. Naming +// one of these explicitly is a request this worker will never quietly satisfy +// with memory instead. +const PERSISTENT_VFS_NAMES = new Set([ + "opfs", + "opfs-wl", + "opfs-sahpool", + "nodefs", +]); + function normalizeError(error) { if (!error) return "unknown sqlite worker error"; if (error.stack) return error.stack; @@ -497,17 +507,17 @@ async function open(args) { throw error; } if (requestedVFS !== "auto") { - if (requestedVFS === "opfs" && !args.requirePersistent) { - sqlite3.config.warn("OPFS VFS unavailable, falling back to :memory:", error.message || String(error)); - opened = openMemoryDB(args); - break; - } throw error; } } } if (!opened) { - if (args.requirePersistent) { + // Naming a durable VFS, or asking for persistence outright, is a + // promise this worker keeps or breaks loudly. Substituting memory here + // would let a caller run happily against storage that evaporates on + // exit, which for a wallet database means losing state that is not + // recoverable from anywhere else. + if (args.requirePersistent || PERSISTENT_VFS_NAMES.has(requestedVFS)) { throw new Error(`persistent storage required but no durable VFS opened; tried ${failures.join("; ")}`); } sqlite3.config.warn("no durable VFS available, falling back to :memory:", failures.join("; ")); diff --git a/driver_node_js_wasm_test.go b/driver_node_js_wasm_test.go index 431b11c..e894736 100644 --- a/driver_node_js_wasm_test.go +++ b/driver_node_js_wasm_test.go @@ -140,6 +140,78 @@ func TestNodeDriverPersistsToHostFilesystem(t *testing.T) { } } +// TestNodeDriverRefusesMemoryFallback is the safety-critical case. A caller +// that names a durable VFS must never receive an in-memory database instead, +// because an in-memory wallet database looks perfectly healthy right up to the +// moment the process exits and takes the only copy of the state with it. +func TestNodeDriverRefusesMemoryFallback(t *testing.T) { + dir := nodeTestDir(t) + + // A regular file cannot contain a directory, so the database below can + // never be created and the durable open is bound to fail. + blocker := filepath.Join(dir, fmt.Sprintf("blocker-%d", time.Now().UnixNano())) + if err := os.WriteFile(blocker, []byte("not a directory"), 0o600); err != nil { + t.Fatalf("write blocker: %v", err) + } + unopenable := filepath.Join(blocker, "wallet.db") + + for _, tc := range []struct { + name string + opts *Options + }{{ + name: "named durable vfs", + opts: &Options{File: unopenable, VFS: string(VFSTypeNodeFS)}, + }, { + name: "require persistent", + opts: &Options{File: unopenable, RequirePersistent: true}, + }, { + name: "disallow memory", + opts: &Options{File: unopenable, DisallowMemory: true}, + }} { + t.Run(tc.name, func(t *testing.T) { + db, err := Open(tc.opts) + if err != nil { + return + } + defer db.Close() + + // Open is lazy, so the failure surfaces on first use. What + // must not happen is a usable database: that would mean the + // driver quietly substituted memory. + if err := db.Ping(); err != nil { + return + } + + info, infoErr := GetStorageInfo(db) + if infoErr != nil { + return + } + + t.Fatalf("durable open silently succeeded on %s storage", + info.VFSType) + }) + } +} + +// TestNodeDriverUnavailableVFSIsTyped checks that a VFS this host does not +// have is reported as such rather than as a generic failure, so a caller can +// tell "wrong host" apart from "storage is broken". +func TestNodeDriverUnavailableVFSIsTyped(t *testing.T) { + path := nodeDBPath(t, "unavailable") + + db, err := Open(&Options{File: path, VFS: string(VFSTypeOPFS)}) + if err == nil { + defer db.Close() + err = db.Ping() + } + if err == nil { + t.Fatal("expected opening an OPFS database under Node to fail") + } + if !errors.Is(err, ErrUnsupportedVFS) && !errors.Is(err, ErrOPFSUnavailable) { + t.Fatalf("expected a typed VFS error, got %v", err) + } +} + // TestNodeDriverTransactions checks that the transaction verbs reach the same // worker connection, so a rollback actually discards the work. func TestNodeDriverTransactions(t *testing.T) { diff --git a/open.go b/open.go index 4e3c8f2..05e869c 100644 --- a/open.go +++ b/open.go @@ -23,6 +23,10 @@ type Options struct { // this host, then memory unless persistent storage is required). In a // browser those are opfs-wl, opfs-sahpool, and opfs; under Node the only // one is nodefs, backed by node:fs. + // + // Naming a durable VFS explicitly is a stronger statement than "auto": + // the open then either uses that VFS or fails. It never degrades to + // memory, whatever RequirePersistent says. VFS string // Busy timeout in milliseconds (default: 5000) @@ -36,7 +40,9 @@ type Options struct { // relative to sqlite-worker.js. SQLiteJSURL string - // Require OPFS/persistent storage instead of falling back to memory. + // Require persistent storage instead of falling back to memory. This + // matters for VFS "auto", which would otherwise settle for memory on a + // host that offers no durable storage at all. RequirePersistent bool // DisallowMemory fails open instead of falling back to memory. It is an diff --git a/tests/node-backend.test.cjs b/tests/node-backend.test.cjs index 48776b5..b933469 100644 --- a/tests/node-backend.test.cjs +++ b/tests/node-backend.test.cjs @@ -1,5 +1,5 @@ // Tests for the Node storage backend: the node:fs VFS, the worker_threads -// bridge, and the durable storage they provide. +// bridge, and the refusal to substitute memory for durable storage. // // Run with: node --test tests/ // @@ -106,6 +106,76 @@ test("nodefs writes a real host file and survives reopen", async () => { }); }); +test("nodefs refuses to silently use memory when it cannot open", async () => { + // A path under a file (rather than a directory) cannot be created, so the + // durable open must fail. The safety-critical property is that the caller + // learns about it instead of receiving a working in-memory database whose + // contents vanish at exit. + const dataDir = tempDataDir(); + const blocker = path.join(dataDir, "blocker"); + fs.writeFileSync(blocker, "not a directory"); + + await withBridge(async (bridge) => { + await assert.rejects( + () => + bridge.open({ + file: path.join(blocker, "wallet.db"), + vfs: "nodefs", + mode: "rwc", + }), + (error) => { + assert.ok( + !/memory/i.test(error.message) || + /required/i.test(error.message), + `open degraded to memory: ${error.message}` + ); + return true; + } + ); + }); +}); + +test("an unavailable named VFS is an error, never a memory fallback", async () => { + const dataDir = tempDataDir(); + + await withBridge(async (bridge) => { + await assert.rejects( + () => + bridge.open({ + file: path.join(dataDir, "wallet.db"), + vfs: "opfs", + mode: "rwc", + }), + /unavailable/i + ); + }); +}); + +test("requirePersistent is honored even for an auto VFS selection", async () => { + const dataDir = tempDataDir(); + const blocker = path.join(dataDir, "blocker"); + fs.writeFileSync(blocker, "not a directory"); + + await withBridge(async (bridge) => { + await assert.rejects( + () => + bridge.open({ + file: path.join(blocker, "wallet.db"), + vfs: "auto", + mode: "rwc", + requirePersistent: true, + }), + (error) => { + assert.ok( + !/^memory$/i.test(error.vfsType || ""), + "opened memory despite requirePersistent" + ); + return true; + } + ); + }); +}); + test("an explicit memory request still works", async () => { await withBridge(async (bridge) => { const opened = await bridge.open({ file: ":memory:", mode: "rwc" }); From f5add429e6058248d4f4332c6cd4f0c3611c2d00 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Wed, 29 Jul 2026 01:08:20 -0700 Subject: [PATCH 3/7] bridge: stop silently substituting a weaker journal mode In this commit, we make the driver keep the journal mode its caller asked for, or say so. Until now the worker set journal_mode first and applied the caller's own pragmas afterwards, which looks harmless and is not. None of the VFSes reachable from here implements xShmMap, so the only route to WAL is the one SQLite documents for hosts without shared memory: put the connection in locking_mode=EXCLUSIVE first and the WAL index lives on the heap instead. A caller that passed both, as every caller of this driver in practice does, had its locking mode applied one step too late, and SQLite answered the WAL request by leaving the database on the rollback journal. Ordering the journal mode last is only half the repair, because the locking mode has to come before the caller's other pragmas too, not merely before the journal mode. Once a database is actually in WAL, a non-exclusive connection cannot so much as read it here, and a pragma as ordinary as auto_vacuum reads page 1. Listing locking_mode after it, which is where it reads most naturally and where both of our callers had put it, turns the second open of a WAL database into SQLITE_CANTOPEN. Rather than ask every caller to know that, the worker hoists any locking_mode pragma to the front, since the driver is the part that knows its VFSes have no shared memory. With both halves in place WAL works on nodefs, opfs, opfs-wl and opfs-sahpool alike. Getting the order right still leaves the original complaint unanswered, because the failure was silent and would go on being silent for the next mode SQLite cannot give us. PRAGMA journal_mode reports the mode in force rather than the mode requested, so the two can differ with nobody the wiser, and the difference is not academic: synchronous=NORMAL under WAL costs you the recently committed tail on power loss, while the same setting under a rollback journal risks the database itself. So we read the mode back and refuse to continue when it is not what was asked for. An in-memory database is exempt, since it is always in "memory" mode and has no durability to lose. Two smaller things follow from having a pragma that can now fail. A refused open closes the database it had already opened, because the VFS claims a file exclusively for as long as a handle is alive, through an OPFS access handle or a nodefs lock file, and leaving one behind would meet a corrected retry with "already open" and bury the real fault underneath it. And a failing pragma now names itself, since SQLite reports only what went wrong and a DSN carries several. --- CHANGELOG.md | 3 + bridge/sqlite-node-vfs.js | 9 ++ bridge/sqlite-worker.js | 116 +++++++++++++++++++- tests/node-backend.test.cjs | 205 +++++++++++++++++++++++++++++++++++- 4 files changed, 327 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5896de4..1ca2720 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,9 @@ - Added a Node storage backend: the `nodefs` VFS in `bridge/sqlite-node-vfs.js`, a `node:worker_threads` path in the bridge, and Node-aware script and wasm loading in the worker. - Tightened the memory fallback: naming a durable VFS that cannot be opened is now an error rather than a silent `:memory:` substitution. Only `vfs=auto` without `require_persistent` may fall back. - Added `sqliteBridge.shutdown()` so a Node host can retire the worker thread and let its process exit. +- Fixed pragma ordering at open, which made `journal_mode=WAL` unreachable on every VFS this driver offers. None of them implements `xShmMap`, so WAL is only available through SQLite's "WAL without shared memory" mode, which is conditional on `locking_mode=EXCLUSIVE`. Any `locking_mode` pragma is now applied first, and the journal mode last. Without the first half, reopening an existing WAL database failed with `SQLITE_CANTOPEN` on whichever pragma happened to read a page (`auto_vacuum`, for instance); without the second, a WAL request silently produced a rollback journal. +- A pragma that fails at open now reports which pragma it was. +- The effective `journal_mode` is read back after it is set, and a mismatch is an error. SQLite answers a journal mode it cannot honor by leaving the database in its previous mode, so a caller that asked for WAL could otherwise run on the rollback journal, where `synchronous=NORMAL` means something considerably weaker. - Replaced SQLite Worker1/Promiser runtime usage with a dedicated `sqlite3.oo1` Worker. - Added browser E2E coverage for OPFS, memory mode, transactions, BLOBs, dump/load, migrations, generated SQL shapes, named parameters, context cancellation, and storage behavior. diff --git a/bridge/sqlite-node-vfs.js b/bridge/sqlite-node-vfs.js index 02bbd0f..d73cfe6 100644 --- a/bridge/sqlite-node-vfs.js +++ b/bridge/sqlite-node-vfs.js @@ -14,6 +14,15 @@ // so this VFS reconstructs that property with a pid-stamped lock file taken // when a main database is opened for writing. Two Node processes pointed at // one database now fail loudly instead of interleaving writes. +// +// One method is deliberately absent: xShmMap. Shared memory exists so that +// several connections can share one WAL index, and this VFS has already ruled +// that out by holding the database exclusively. WAL is still available, but +// only by the route SQLite documents for exactly this situation: set +// locking_mode=EXCLUSIVE before switching journal modes and SQLite keeps the +// WAL index on the heap instead. Ask for WAL without that and SQLite silently +// stays on the rollback journal, which is why the worker reads the effective +// journal mode back and refuses the mismatch. "use strict"; diff --git a/bridge/sqlite-worker.js b/bridge/sqlite-worker.js index 84e701a..e27fbcf 100644 --- a/bridge/sqlite-worker.js +++ b/bridge/sqlite-worker.js @@ -468,6 +468,78 @@ async function openPersistentDB(vfsName, filename, uriParams, args) { return { db, filename: resolvedFilename, vfs, persistent: true }; } +// orderPragmas puts any locking_mode pragma at the front and otherwise +// preserves the caller's order. +// +// Callers reasonably think of locking_mode as one setting among several and +// list it wherever it reads well. On a VFS without shared memory it is not +// one setting among several: it is the precondition for touching a WAL +// database at all. Rather than make every caller know that, the driver, which +// is the part that knows its VFSes have no xShmMap, hoists it. +function orderPragmas(pragmas) { + const isLockingMode = (pragma) => + /^\s*locking_mode\s*=/i.test(String(pragma)); + + return [ + ...pragmas.filter(isLockingMode), + ...pragmas.filter((pragma) => !isLockingMode(pragma)), + ]; +} + +// releaseOpened closes a database that was opened but never handed out, and +// drops the duplicate-open bookkeeping that goes with it. +function releaseOpened(opened) { + try { + if (opened.db.__persistentKey) { + openPersistentFiles.delete(opened.db.__persistentKey); + } + opened.db.close(); + } catch (closeError) { + sqlite3.config.warn( + "failed to close a database after a failed open:", + closeError.message || String(closeError) + ); + } +} + +// applyJournalMode sets the requested journal mode and then proves it took. +// +// SQLite answers a journal mode it cannot honor by quietly leaving the +// database in the mode it was already in, and PRAGMA journal_mode reports the +// mode in force rather than the mode asked for. A caller that asks for WAL on +// a VFS or a locking mode that cannot provide it therefore runs on the +// rollback journal while believing otherwise, and durability settings chosen +// for WAL do not mean the same thing there: synchronous=NORMAL loses only the +// recent tail under WAL, but risks a corrupt database under the rollback +// journal. Reading the mode back turns that class of mistake into a startup +// error, in the same spirit as refusing to substitute memory for durable +// storage. +function applyJournalMode(opened, requested) { + if (!requested) { + return; + } + + opened.db.exec(`PRAGMA journal_mode=${requested}`); + + // An in-memory database is always in "memory" journal mode and cannot be + // moved out of it. There is no silent downgrade to catch, because there was + // never any durability on offer to lose. + if (!opened.persistent) { + return; + } + + const effective = String( + opened.db.selectValue("PRAGMA journal_mode") || "" + ).toLowerCase(); + if (effective !== requested.toLowerCase()) { + throw new Error( + `journal_mode=${requested} was requested but SQLite is in ` + + `"${effective}" mode on VFS ${opened.vfs}; refusing to run with ` + + `weaker guarantees than the caller asked for` + ); + } +} + function openMemoryDB(args) { if (args.requirePersistent) { throw new Error("persistent storage required but memory VFS was requested"); @@ -528,11 +600,45 @@ async function open(args) { if (args.busyTimeout > 0) { sqlite3.capi.sqlite3_busy_timeout(opened.db.pointer, args.busyTimeout); } - if (args.journalMode) { - opened.db.exec(`PRAGMA journal_mode=${args.journalMode}`); - } - for (const pragma of args.pragma || []) { - if (pragma) opened.db.exec(`PRAGMA ${pragma}`); + + // Pragma ordering here is load-bearing rather than cosmetic, and for one + // reason: none of the VFSes this driver can reach implements xShmMap. That + // makes SQLite's "WAL without shared memory" mode the only WAL available, + // and that mode is conditional on the connection already being in + // locking_mode=EXCLUSIVE. Two things follow. + // + // The locking mode goes first, ahead of the caller's other pragmas, because + // a WAL database cannot even be read by a non-exclusive connection here. A + // pragma as innocent as auto_vacuum, which reads page 1, fails with + // SQLITE_CANTOPEN when it runs one statement too early. + // + // The journal mode goes last, after the locking mode is in force. Setting + // it first, as this once did, meant a caller asking for WAL got the + // rollback journal and no indication that it had. + try { + for (const pragma of orderPragmas(args.pragma || [])) { + if (!pragma) continue; + try { + opened.db.exec(`PRAGMA ${pragma}`); + } catch (error) { + // Name the pragma. SQLite's own message says only what went wrong, + // and a DSN carries several of these, so without the name a failure + // here sends the reader looking through all of them. + throw new Error( + `PRAGMA ${pragma} failed on ${opened.filename}: ` + + (error.message || String(error)) + ); + } + } + applyJournalMode(opened, args.journalMode); + } catch (error) { + // Configuration failed after the file was opened, so nothing will ever + // hand this handle back to the caller. Release it here: a database left + // open holds the VFS's exclusive claim on the file (an OPFS access handle + // in a browser, a lock file under nodefs) for the lifetime of the worker, + // which would turn a retry into "already open" and strand the database. + releaseOpened(opened); + throw error; } const dbId = `db${nextDbId++}`; diff --git a/tests/node-backend.test.cjs b/tests/node-backend.test.cjs index b933469..539bcbd 100644 --- a/tests/node-backend.test.cjs +++ b/tests/node-backend.test.cjs @@ -1,5 +1,6 @@ // Tests for the Node storage backend: the node:fs VFS, the worker_threads -// bridge, and the refusal to substitute memory for durable storage. +// bridge, and the refusal to substitute either memory for durable storage or a +// weaker journal mode for the one the caller asked for. // // Run with: node --test tests/ // @@ -10,6 +11,7 @@ const test = require("node:test"); const assert = require("node:assert"); +const { spawnSync } = require("node:child_process"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); @@ -348,3 +350,204 @@ test("relative database names resolve under the configured root", async () => { `relative.db not under ${dataDir}: ${fs.readdirSync(dataDir)}` ); }); + +test("WAL is delivered under nodefs when locking_mode is EXCLUSIVE", async () => { + // nodefs implements no xShmMap, so WAL is reachable only through SQLite's + // "WAL without shared memory" mode. That mode requires the connection to + // already be in EXCLUSIVE locking mode when the journal mode is switched, + // which is why the worker applies the caller's pragmas first. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: ["foreign_keys=on", "locking_mode=EXCLUSIVE"], + }); + + const mode = await bridge.query(opened.dbId, "PRAGMA journal_mode"); + assert.deepStrictEqual(mode.rows, [["wal"]]); + + await bridge.exec(opened.dbId, "CREATE TABLE vtxo(amt INTEGER)"); + await bridge.exec(opened.dbId, "INSERT INTO vtxo VALUES(4200)"); + + const afterWrite = await bridge.query(opened.dbId, "PRAGMA journal_mode"); + assert.deepStrictEqual( + afterWrite.rows, + [["wal"]], + "the connection fell out of WAL once it actually wrote" + ); + await bridge.close(opened.dbId); + }); +}); + +test("a journal mode SQLite cannot honor is an error, not a downgrade", async () => { + // Asking for WAL without EXCLUSIVE locking is the mistake this guards: + // SQLite answers by leaving the database on the rollback journal and + // reporting that mode back, so the caller would otherwise run with the + // durability profile of a mode it never chose. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + await assert.rejects( + () => + bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + }), + /journal_mode=WAL was requested but SQLite is in "delete" mode/ + ); + + // The refused open must not keep holding the file. Otherwise a caller + // that corrects its pragmas and retries would be told the database is + // already open, and the real fault would be hidden behind that one. + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: ["locking_mode=EXCLUSIVE"], + }); + const mode = await bridge.query(opened.dbId, "PRAGMA journal_mode"); + assert.deepStrictEqual(mode.rows, [["wal"]]); + await bridge.close(opened.dbId); + }); +}); + +test("a WAL database reopens with locking_mode listed after other pragmas", async () => { + // Reading a WAL database needs the WAL index, which without shared memory + // exists only for an EXCLUSIVE connection. A pragma that touches the file, + // auto_vacuum reads page 1, therefore fails with SQLITE_CANTOPEN if it + // runs before the locking mode is set. Callers list their pragmas in + // whatever order reads well, so the driver hoists locking_mode itself. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const pragmas = [ + "foreign_keys=on", + "auto_vacuum=incremental", + "locking_mode=EXCLUSIVE", + ]; + + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: pragmas, + }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a INTEGER)"); + await bridge.exec(opened.dbId, "INSERT INTO t VALUES(1)"); + await bridge.close(opened.dbId); + + // The second open is the one that matters: now the file on disk is + // already a WAL database rather than an empty one. + const reopened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: pragmas, + }); + const rows = await bridge.query(reopened.dbId, "SELECT a FROM t"); + assert.deepStrictEqual(rows.rows, [[1]]); + await bridge.close(reopened.dbId); + }); +}); + +test("an in-memory database is exempt from the journal mode check", async () => { + // A memory database is always in "memory" journal mode and cannot leave + // it. There is no silent downgrade to catch, because there was never any + // durability on offer to lose. + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: ":memory:", + mode: "rwc", + journalMode: "WAL", + }); + assert.strictEqual(opened.persistent, false); + await bridge.exec(opened.dbId, "CREATE TABLE t(a)"); + await bridge.close(opened.dbId); + }); +}); + +test("a WAL database survives an unclean process exit", async () => { + // WAL without shared memory keeps its index on the heap, so a process + // that dies leaves both a WAL to replay and a lock file whose owner is + // gone. Committed rows must still be there afterwards; a wallet has no + // second copy of its VTXO state to fall back on. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const childPath = path.join(dataDir, "crash.cjs"); + fs.writeFileSync(childPath, crashChildSource()); + + const child = spawnSync( + process.execPath, [childPath], + { + env: { + ...process.env, + BRIDGE_PATH: bridgePath, + ASSET_DIR: sharedRuntime, + DB_PATH: dbPath, + }, + encoding: "utf8", + } + ); + assert.strictEqual( + child.signal, "SIGKILL", + `child did not reach the kill: ${child.stdout}${child.stderr}` + ); + assert.ok( + fs.existsSync(`${dbPath}-wal`), + `no WAL was left behind: ${fs.readdirSync(dataDir)}` + ); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: ["locking_mode=EXCLUSIVE"], + }); + const rows = await bridge.query(opened.dbId, "SELECT amt FROM vtxo"); + assert.deepStrictEqual(rows.rows, [[4200]]); + await bridge.close(opened.dbId); + }); +}); + +// crashChildSource is the program the unclean-exit test runs in its own +// process. It has to be a separate process rather than a terminated worker, +// because the VFS's lock file records a pid and only releases the database +// once that pid is genuinely gone. +function crashChildSource() { + return ` + "use strict"; + const fs = require("node:fs"); + globalThis.sqliteBridgeAssetDir = process.env.ASSET_DIR; + new Function("require", "__dirname", + fs.readFileSync(process.env.BRIDGE_PATH, "utf8") + )(require, process.env.ASSET_DIR); + + (async () => { + const bridge = globalThis.sqliteBridge; + const opened = await bridge.open({ + file: process.env.DB_PATH, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: ["locking_mode=EXCLUSIVE"], + }); + await bridge.exec(opened.dbId, "CREATE TABLE vtxo(amt INTEGER)"); + await bridge.exec(opened.dbId, "INSERT INTO vtxo VALUES(4200)"); + // Die with the WAL unchecked and the lock file still held. + process.kill(process.pid, "SIGKILL"); + })(); + `; +} From 5f8fb722e3437032e155a8043fe41e0b44c50f6b Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Mon, 10 Aug 2026 20:10:28 -0700 Subject: [PATCH 4/7] bridge: make the nodefs lock and its durability real The pid-stamped lock file is the whole of what replaces the exclusive access OPFS gives away for free, and two paths through it let two processes hold one database at once. Both need a race between two processes, and both end in a silently corrupted wallet. The first is in the reclaim. Two processes recovering from the same crashed owner both see a stale lock, and reclaiming by unlinking lets the second delete the fresh lock the first just took and then take one of its own. Unlinking is replaced by a rename, which can succeed only once for a given file and so elects a single reclaimer; the loser comes back around the loop and finds the winner's live lock. Because a rename is atomic but not conditional, the reclaimer reads what it actually moved and puts it back if it belongs to someone running. releaseLock gets the matching check, and no longer deletes a lock that has stopped naming this process. The second is in xOpen, which created the database with O_TRUNC and took the lock afterwards. Two processes racing the same first-time open would have the second truncate a database the first had already begun writing, learning it had lost the lock only after the damage. The claim now comes first and the create is O_EXCL, so an existing database is never truncated on the way in. A recycled pid was a third way to get this wrong, in the other direction: a crashed owner whose number is later reused reads as alive forever and strands the database. The lock now records the owner's kernel start time where the platform exposes it, which makes (pid, start time) an identity rather than a guess. Two durability gaps went with them, both the same silent substitution the rest of this branch refuses. xDelete accepted doSyncDir and ignored it, and that flag is the entire difference between synchronous=EXTRA and FULL in rollback-journal mode, where the unlink of the journal is the commit point; without it a power loss can resurrect a journal and roll a committed transaction back. The unix VFS also syncs a created file's parent at its first sync, which SQLite cannot signal through the VFS interface, so files this VFS creates are tracked and synced there. A full disk was reported as a generic I/O error rather than SQLITE_FULL, which is the difference between running df and suspecting the hardware. Last, a failed xOpen left its bookkeeping behind: SQLite leaves pMethods null and never calls xClose for it, so a later allocation on the same pointer would find a stale record naming a closed fd. What the lock does not cover is now stated rather than implied. The header comment and the README say that it holds for writers only, within one pid namespace on a local filesystem, and name the lock file and how to clear it by hand. Each fix has a test that fails without it, including a real two-process refusal and a three-process race over one stale lock. The existing "a second process cannot open the same database" never started a second process, so it is renamed to what it actually checks. --- README.md | 10 +- bridge/sqlite-node-vfs.js | 436 ++++++++++++++++++++++++++++++------ bridge/sqlite-worker.js | 55 ++++- tests/node-backend.test.cjs | 271 +++++++++++++++++++++- 4 files changed, 687 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index cdd1fdc..8f8be17 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,15 @@ globalThis.fs = require("node:fs"); // else wasm_exec.js stubs fs with EN globalThis.sqliteBridgeAssetDir = wasmDir; // holds sqlite3.js, sqlite3.wasm, sqlite-worker.js, sqlite-node-vfs.js ``` -Two Node processes must not write one database. The `nodefs` VFS enforces that with a pid-stamped lock file taken alongside each main database opened for writing; a lock whose owning process is gone is reclaimed automatically, so a crash does not strand the database. +Two Node processes must not write one database. The `nodefs` VFS enforces that with a pid-stamped lock file taken alongside each main database opened for writing; a lock whose owning process is gone is reclaimed automatically, so a crash does not strand the database. A second process attempting the same database fails to open, and the error names the pid holding it. + +The lock file sits next to the database as `-nodefs-lock`. Deleting it by hand is the recovery if a database is ever stranded behind a lock the VFS declines to reclaim, and is safe exactly when no process is using that database. + +Node core exposes neither `flock` nor `fcntl`, so this is a lock file rather than a kernel lock, and it is worth knowing where that falls short of the real thing: + +- **Writers only.** A read-only open takes no lock and is not blocked by one. A reader running against a live writer sees confusing errors or stale data rather than silent damage, but it is not excluded. +- **One pid namespace, one machine.** Two containers sharing a bind-mounted data directory number their processes independently, so each reads the other's lock as belonging to a process that does not exist and both proceed. Over NFS or SMB neither the atomicity nor the pid check holds. Do not point two containers or two hosts at one database directory. +- **Recycled pids are handled.** The lock records the owner's kernel start time where the platform exposes it (Linux), so a reused pid number does not read as the original owner and strand the database. ## Features diff --git a/bridge/sqlite-node-vfs.js b/bridge/sqlite-node-vfs.js index d73cfe6..092fbaf 100644 --- a/bridge/sqlite-node-vfs.js +++ b/bridge/sqlite-node-vfs.js @@ -13,7 +13,29 @@ // A wallet database that two processes write concurrently corrupts silently, // so this VFS reconstructs that property with a pid-stamped lock file taken // when a main database is opened for writing. Two Node processes pointed at -// one database now fail loudly instead of interleaving writes. +// one database fail loudly instead of interleaving writes. +// +// That reconstruction is narrower than the thing it replaces, and the limits +// are worth stating rather than discovering. Node core exposes no flock or +// fcntl, so the claim rests on a file whose contents name the owning process, +// and reading it back is only meaningful where process ids mean the same thing +// to both parties. Concretely: +// +// - Writers only. A read-only open takes no lock and is not blocked by one. +// - One pid namespace. Two containers sharing a bind-mounted data directory +// have unrelated pid numbering, so each would read the other's lock as +// belonging to a process that does not exist. +// - Local filesystems. Over NFS or SMB neither the atomicity this relies on +// nor the pid check holds. +// +// Within a single machine and pid namespace, a recycled pid is handled: the +// lock records the owner's kernel start time where the platform exposes it, so +// a reused pid number does not read as the original owner. +// +// The lock file is named ``. If a database is stranded +// behind a lock whose owner is genuinely gone and this VFS declines to reclaim +// it, deleting that file by hand is the recovery, and is safe exactly when no +// process is using the database. // // One method is deliberately absent: xShmMap. Shared memory exists so that // several connections can share one WAL index, and this VFS has already ruled @@ -38,11 +60,15 @@ const DEFAULT_VFS_NAME = "nodefs"; // matches the page size of every filesystem we care about. const SECTOR_SIZE = 4096; -// LOCK_STALE_GRACE_MS bounds how long a lock file whose owning pid is gone is -// still honored. A crashed process leaves its lock behind; refusing forever -// would strand the database, so a lock is reclaimable once its owner is -// provably dead. -const LOCK_STALE_GRACE_MS = 0; +// LOCK_SUFFIX names the sidecar file carrying the exclusive claim on a main +// database. It sits next to the database itself, so an operator who needs to +// clear a lock by hand can find it without knowing this file. +const LOCK_SUFFIX = "-nodefs-lock"; + +// RECLAIM_STALE_MS bounds how long the reclaim marker is honored. Reclaiming a +// lock is a handful of syscalls, so a marker older than this was left by a +// process that died in the middle of one. +const RECLAIM_STALE_MS = 30_000; // sleepSignal backs xSleep. Atomics.wait needs a shared integer array to wait // on; nothing ever notifies this one, so every wait runs to its timeout, which @@ -76,6 +102,51 @@ function pidIsAlive(pid) { } } +// processStartTicks reads the kernel's record of when a process started, in +// clock ticks since boot. A pid on its own is not an identity: pids are +// recycled, and a crashed owner whose number has since been reused would read +// as alive forever, stranding the database behind a lock nothing will reclaim. +// The pair (pid, start time) is not reused within a boot, so it is one. +// +// Only Linux exposes this for an arbitrary pid. Elsewhere this returns null and +// the caller falls back to the plain liveness check, which is what this code +// did before. +function processStartTicks(pid) { + try { + const stat = nodeFS.readFileSync(`/proc/${pid}/stat`, "utf8"); + + // The second field is the executable name in parentheses and may + // itself contain spaces and parentheses, so the fields after it are + // counted from the last ')' rather than from the start of the line. + // That puts field 3 at index 0, and starttime is field 22. + const after = stat.slice(stat.lastIndexOf(")") + 2); + const ticks = Number(after.split(" ")[19]); + + return Number.isFinite(ticks) ? ticks : null; + } catch (_) { + return null; + } +} + +// ownerIsLive reports whether the process named by a lock file is still +// running. A pid that exists but started at a different time than the lock +// records is a recycled number rather than the original owner, so the lock is +// stale despite the pid being alive. +function ownerIsLive(owner) { + if (!owner || !pidIsAlive(owner.pid)) { + return false; + } + + const ticks = processStartTicks(owner.pid); + if (ticks === null || owner.startTicks === null || + owner.startTicks === undefined) { + + return true; + } + + return ticks === owner.startTicks; +} + // installNodeFsVfs registers the node:fs VFS with the given sqlite3 namespace // and returns a small utility handle. It is idempotent: a second call with the // same name returns the already-registered handle rather than failing, so a @@ -138,6 +209,37 @@ function installNodeFsVfs(sqlite3, options = {}) { return file; } + // syncDir flushes a directory entry, so that a file's creation or removal + // is itself durable rather than merely visible. Without it a power loss can + // undo the unlink of a rollback journal that SQLite treated as the commit + // point, resurrecting the journal and rolling a committed transaction back. + // + // Failure is deliberately swallowed. Not every platform lets a directory be + // opened for reading, and turning a weaker barrier into a failed delete + // would be the worse trade. + function syncDir(dirPath) { + let dfd; + try { + dfd = nodeFS.openSync(dirPath, "r"); + } catch (_) { + return; + } + + try { + nodeFS.fsyncSync(dfd); + } catch (_) { + } finally { + nodeFS.closeSync(dfd); + } + } + + // ioErrForWrite distinguishes a full disk from a broken one. SQLite's own + // unix VFS returns SQLITE_FULL for ENOSPC, and the difference is what sends + // an operator to `df` rather than to smartctl. + function ioErrForWrite(error, fallback) { + return error && error.code === "ENOSPC" ? capi.SQLITE_FULL : fallback; + } + // heapView returns a view of the wasm heap for a pointer/length pair. The // view is only valid for the duration of one synchronous call, since any // wasm memory growth detaches it. @@ -146,56 +248,129 @@ function installNodeFsVfs(sqlite3, options = {}) { return wasm.heap8u().subarray(start, start + n); } - // acquireLock takes the exclusive open lock for a main database file. It - // reclaims a lock whose owning process is gone, and otherwise throws so - // the open fails loudly rather than racing another writer. - function acquireLock(dbPath) { - const lockPath = `${dbPath}-nodefs-lock`; + // readLockOwner returns the parsed contents of a lock file, or null when it + // is missing or unreadable. An unparseable lock file is treated as stale, + // since the only way to produce one is to crash midway through writing it. + function readLockOwner(lockPath) { + try { + return JSON.parse(nodeFS.readFileSync(lockPath, "utf8")); + } catch (_) { + return null; + } + } - for (let attempt = 0; attempt < 2; attempt++) { - try { - const fd = nodeFS.openSync(lockPath, "wx"); - nodeFS.writeSync( - fd, - JSON.stringify({ - pid: process.pid, - at: Date.now(), - }) - ); - nodeFS.closeSync(fd); - heldLocks.set(dbPath, lockPath); - return; - } catch (error) { - if (error.code !== "EEXIST") { - throw error; - } + // lockedError builds the error for a database another process holds. The + // holder travels on the error object as well as in the message, because + // the worker turns it into something the caller can act on rather than the + // bare SQLITE_CANTOPEN that SQLite would otherwise surface. + function lockedError(dbPath, lockPath, owner) { + const pid = owner && owner.pid ? owner.pid : "unknown"; + const error = new Error( + `database is locked by another process (pid ${pid}): ${dbPath}` + ); + error.nodefsLockHolderPid = owner ? owner.pid : null; + error.nodefsLockPath = lockPath; + + return error; + } + + // writeLockFile creates the lock file and stamps it with this process's + // identity. It reports false when the lock already exists, and throws for + // every other failure. + function writeLockFile(lockPath) { + let fd; + try { + fd = nodeFS.openSync(lockPath, "wx", 0o600); + } catch (error) { + if (error.code === "EEXIST") { + return false; + } + throw error; + } + + try { + nodeFS.writeSync( + fd, + JSON.stringify({ + pid: process.pid, + startTicks: processStartTicks(process.pid), + at: Date.now(), + }) + ); + } finally { + nodeFS.closeSync(fd); + } + + return true; + } + + // withReclaimMutex runs body as the only process reclaiming this lock, and + // reports whether it ran at all. + // + // Reclaiming means observing a dead owner and then replacing the file, and + // those two steps cannot be made one with anything Node exposes. Left + // unserialized they interleave, and the interleavings all end the same + // way: while one process has the stale lock momentarily out of the way, a + // second finds the path empty, creates its own, and two writers now hold + // one database. Inspecting the file first does not help, because the + // inspection is itself a window. + // + // mkdir is the one exclusion primitive available here that costs nothing: + // it fails if the directory exists. So a marker directory beside the lock + // serializes reclamation, and only its holder may touch the lock file. + function withReclaimMutex(lockPath, body) { + const mutexPath = `${lockPath}.reclaim`; + + try { + nodeFS.mkdirSync(mutexPath); + } catch (error) { + if (error.code !== "EEXIST") { + throw error; } - // The lock exists. It is only ours to take if the process that - // wrote it is gone. - let owner = null; + // The marker is held across a handful of syscalls, so one older + // than any reclaim could take belongs to a process that died + // inside one. Clearing it costs a retry at worst, where leaving it + // would strand the database for good. + let age = RECLAIM_STALE_MS; try { - owner = JSON.parse( - nodeFS.readFileSync(lockPath, "utf8") - ); + age = Date.now() - nodeFS.statSync(mutexPath).mtimeMs; } catch (_) { - // An unparseable or vanished lock file is treated as stale. + return false; } - if (owner && pidIsAlive(owner.pid)) { - throw new Error( - `database is locked by another process ` + - `(pid ${owner.pid}): ${dbPath}` - ); + if (age < RECLAIM_STALE_MS) { + return false; } - if ( - owner && - LOCK_STALE_GRACE_MS > 0 && - Date.now() - Number(owner.at) < LOCK_STALE_GRACE_MS - ) { - throw new Error( - `database lock is not yet reclaimable: ${dbPath}` - ); + + try { + nodeFS.rmdirSync(mutexPath); + } catch (_) {} + + return false; + } + + try { + return body(); + } finally { + try { + nodeFS.rmdirSync(mutexPath); + } catch (_) {} + } + } + + // reclaimStaleLock replaces a lock whose owner is gone with one naming this + // process, and reports whether it now holds the lock. The replacement + // happens under the reclaim mutex so that no other process can slip into + // the moment when the lock file does not exist. + function reclaimStaleLock(lockPath) { + return withReclaimMutex(lockPath, () => { + // Read it again in here. A reclaimer ahead of us may have + // finished between our staleness check and our getting the + // mutex, in which case the lock is now held by a live process. + const owner = readLockOwner(lockPath); + if (ownerIsLive(owner)) { + return false; } try { @@ -205,17 +380,58 @@ function installNodeFsVfs(sqlite3, options = {}) { throw error; } } + + return writeLockFile(lockPath); + }); + } + + // acquireLock takes the exclusive open lock for a main database file. It + // reclaims a lock whose owning process is gone, and otherwise throws so + // the open fails loudly rather than racing another writer. + function acquireLock(dbPath) { + const lockPath = `${dbPath}${LOCK_SUFFIX}`; + + // Two passes are all this needs: one to find the lock taken and clear + // a dead owner out of the way, and one to take it. A process that + // loses the reclaim race does not get a third try, because the winner + // now holds a live lock and the answer is no. + for (let attempt = 0; attempt < 2; attempt++) { + if (writeLockFile(lockPath)) { + heldLocks.set(dbPath, lockPath); + return; + } + + const owner = readLockOwner(lockPath); + if (ownerIsLive(owner)) { + throw lockedError(dbPath, lockPath, owner); + } + + if (reclaimStaleLock(lockPath)) { + heldLocks.set(dbPath, lockPath); + return; + } } - throw new Error(`unable to acquire database lock: ${dbPath}`); + throw lockedError(dbPath, lockPath, readLockOwner(lockPath)); } + // releaseLock drops the claim taken by acquireLock. It checks that the + // lock still names this process before removing it: if a reclaimer + // elsewhere concluded we were dead and took the lock for itself, the file + // on disk is now that process's claim, and deleting it would hand the + // database to a third. function releaseLock(dbPath) { const lockPath = heldLocks.get(dbPath); if (!lockPath) { return; } heldLocks.delete(dbPath); + + const owner = readLockOwner(lockPath); + if (owner && owner.pid !== process.pid) { + return; + } + try { nodeFS.unlinkSync(lockPath); } catch (error) { @@ -227,8 +443,11 @@ function installNodeFsVfs(sqlite3, options = {}) { const ioMethods = { xCheckReservedLock: function (pFile, pOut) { - // This VFS holds the file exclusively for its lifetime, so no - // other connection can be holding a reserved lock. + // A writer here holds the database exclusively for its lifetime, + // so no other connection can be holding a reserved lock. The + // answer is the same, though for a weaker reason, for the one case + // that escapes the open lock: a read-only opener takes no lock and + // has no reserved lock of its own to report. storeErr(); wasm.poke32(pOut, 0); return 0; @@ -329,6 +548,16 @@ function installNodeFsVfs(sqlite3, options = {}) { // deliberately does not degrade to fdatasync on the DATAONLY // hint: file size changes must reach the disk too. nodeFS.fsyncSync(file.fd); + + // The unix VFS syncs the parent directory at the first sync of + // a file it created, so the file's existence is durable before + // the database starts depending on it. SQLite cannot ask for + // that through the VFS interface, so it is done here. + if (file.needsDirSync) { + syncDir(nodePath.dirname(file.path)); + file.needsDirSync = false; + } + return 0; } catch (error) { return storeErr(error, capi.SQLITE_IOERR_FSYNC); @@ -341,7 +570,10 @@ function installNodeFsVfs(sqlite3, options = {}) { nodeFS.ftruncateSync(fileFor(pFile).fd, Number(sz64)); return 0; } catch (error) { - return storeErr(error, capi.SQLITE_IOERR_TRUNCATE); + return storeErr( + error, + ioErrForWrite(error, capi.SQLITE_IOERR_TRUNCATE) + ); } }, @@ -373,7 +605,10 @@ function installNodeFsVfs(sqlite3, options = {}) { } return 0; } catch (error) { - return storeErr(error, capi.SQLITE_IOERR_WRITE); + return storeErr( + error, + ioErrForWrite(error, capi.SQLITE_IOERR_WRITE) + ); } }, }; @@ -419,16 +654,26 @@ function installNodeFsVfs(sqlite3, options = {}) { xDelete: function (pVfs, zName, doSyncDir) { storeErr(); + const target = resolvePath(wasm.cstrToJs(zName)); try { - nodeFS.unlinkSync(resolvePath(wasm.cstrToJs(zName))); - return 0; + nodeFS.unlinkSync(target); } catch (error) { - if (error.code === "ENOENT") { - return 0; + if (error.code !== "ENOENT") { + storeErr(error); + return capi.SQLITE_IOERR_DELETE; } - storeErr(error); - return capi.SQLITE_IOERR_DELETE; } + + // SQLite sets this under synchronous=EXTRA, where in rollback + // journal mode the unlink above *is* the commit. Ignoring the flag + // would quietly give EXTRA no more than FULL, which is the same + // class of silent substitution the journal-mode readback exists to + // refuse. + if (doSyncDir) { + syncDir(nodePath.dirname(target)); + } + + return 0; }, xFullPathname: function (pVfs, zName, nOut, pOut) { @@ -476,6 +721,7 @@ function installNodeFsVfs(sqlite3, options = {}) { let fd = -1; let target = ""; let took = false; + let created = false; try { const isMainDB = !!(flags & capi.SQLITE_OPEN_MAIN_DB); const create = !!(flags & capi.SQLITE_OPEN_CREATE); @@ -503,28 +749,41 @@ function installNodeFsVfs(sqlite3, options = {}) { }); } + // The claim comes before the file does. Creating first leaves a + // window in which a second process racing the same first-time + // open truncates a database this one has already begun + // writing, and the loser of the lock race discovers it only + // afterwards, with the damage done. + if (isMainDB && !readOnly) { + acquireLock(target); + took = true; + } + let openMode; if (readOnly) { openMode = "r"; - } else if (create) { - // "a+" would force every write to the end of the file, so - // open read/write and create the file separately when it - // is missing. - if (!nodeFS.existsSync(target)) { - nodeFS.closeSync( - nodeFS.openSync(target, "w", 0o600) - ); - } - openMode = "r+"; } else { + if (create) { + // "a+" would force every write to the end of the + // file, so create the file separately when it is + // missing and then open it read/write. The create is + // "wx" rather than "w" because an existing database + // must never be truncated on the way in; EEXIST here + // simply means someone got there first. + try { + nodeFS.closeSync( + nodeFS.openSync(target, "wx", 0o600) + ); + created = true; + } catch (error) { + if (error.code !== "EEXIST") { + throw error; + } + } + } openMode = "r+"; } - if (isMainDB && !readOnly) { - acquireLock(target); - took = true; - } - fd = nodeFS.openSync(target, openMode); openFiles.set(Number(pFile), { @@ -533,6 +792,12 @@ function installNodeFsVfs(sqlite3, options = {}) { flags, locked: took, lockType: capi.SQLITE_LOCK_NONE, + + // A file this VFS created is not durably present until its + // parent directory is synced. The unix VFS does that at the + // first xSync of such a file, and SQLite does not signal it + // through the VFS interface, so it is tracked here. + needsDirSync: created, }); const sq3File = new capi.sqlite3_file(pFile); @@ -543,6 +808,13 @@ function installNodeFsVfs(sqlite3, options = {}) { } return 0; } catch (error) { + // SQLite leaves pMethods null for a failed xOpen and so never + // calls xClose for it, which means anything recorded here + // would outlive the descriptor it describes. A later + // allocation landing on the same pointer would then find a + // stale entry naming a closed fd. + openFiles.delete(Number(pFile)); + if (fd >= 0) { try { nodeFS.closeSync(fd); @@ -589,6 +861,22 @@ function installNodeFsVfs(sqlite3, options = {}) { rootDir, getVfs: () => nodeVfs, openFileCount: () => openFiles.size, + + // lockHolder names the process currently holding the open lock for a + // database, or null when nothing does. + // + // SQLite's core does not carry xGetLastError's message out to the + // caller, so a collision reaches the application as a bare + // SQLITE_CANTOPEN, indistinguishable from a missing directory or a + // permissions problem. This lets the worker say which process is + // holding the database instead. + lockHolder: (dbPath) => { + const owner = readLockOwner( + `${resolvePath(dbPath)}${LOCK_SUFFIX}` + ); + + return owner && ownerIsLive(owner) ? owner : null; + }, }; if (!installNodeFsVfs.installed) { diff --git a/bridge/sqlite-worker.js b/bridge/sqlite-worker.js index e27fbcf..ff83f98 100644 --- a/bridge/sqlite-worker.js +++ b/bridge/sqlite-worker.js @@ -27,6 +27,11 @@ const isNodeWorker = // assets live in. Both are undefined in a browser. let nodeParentPort; let nodeAssetDir = ""; + +// nodeVfsUtil is the handle returned when the node:fs VFS is installed. It is +// how the worker asks the VFS questions SQLite will not answer, such as which +// process is holding a database it just failed to open. +let nodeVfsUtil = null; if (isNodeWorker) { const workerThreads = require("node:worker_threads"); nodeParentPort = workerThreads.parentPort; @@ -124,7 +129,9 @@ async function ensureSQLite(options = {}) { const { installNodeFsVfs } = require( nodePath.join(nodeAssetDir, "sqlite-node-vfs.js") ); - installNodeFsVfs(sqlite3, { directory: options.rootDir || undefined }); + nodeVfsUtil = installNodeFsVfs(sqlite3, { + directory: options.rootDir || undefined, + }); return sqlite3; } @@ -438,6 +445,40 @@ async function init(args = {}) { return { version: sqlite3.version, vfsList: vfsList(), workerProtocolVersion }; } +// annotateLockedOpen replaces a failed nodefs open with one that names the +// process holding the database, when that is what went wrong. +// +// SQLite reports a lock collision as a bare SQLITE_CANTOPEN, the same code it +// uses for a missing directory or a permissions failure, and the message the +// VFS wrote is only reachable through xGetLastError, which the core does not +// consult. Left alone, a second daemon pointed at one data directory dies with +// "unable to open database file" and sends whoever is on call looking at file +// permissions. The lock file knows better, so ask it. +function annotateLockedOpen(vfsName, filename, error) { + if (vfsName !== "nodefs" || !nodeVfsUtil) { + return error; + } + + let holder = null; + try { + holder = nodeVfsUtil.lockHolder(filename); + } catch (_) { + return error; + } + + if (!holder) { + return error; + } + + const locked = new Error( + `database is locked by another process (pid ${holder.pid}): ${filename}` + ); + locked.sqliteLockHolderPid = holder.pid; + locked.cause = error; + + return locked; +} + async function openPersistentDB(vfsName, filename, uriParams, args) { if (vfsName === "opfs-sahpool" && sqlite3.installOpfsSAHPoolVfs && !hasVFS("opfs-sahpool")) { await sqlite3.installOpfsSAHPoolVfs({ name: "opfs-sahpool" }); @@ -454,10 +495,14 @@ async function openPersistentDB(vfsName, filename, uriParams, args) { } let db; - if (vfsName === "opfs" && sqlite3.oo1.OpfsDb) { - db = new sqlite3.oo1.OpfsDb(resolved, openFlags(args.mode)); - } else { - db = new sqlite3.oo1.DB({ filename: resolved, flags: openFlags(args.mode), vfs: vfsName }); + try { + if (vfsName === "opfs" && sqlite3.oo1.OpfsDb) { + db = new sqlite3.oo1.OpfsDb(resolved, openFlags(args.mode)); + } else { + db = new sqlite3.oo1.DB({ filename: resolved, flags: openFlags(args.mode), vfs: vfsName }); + } + } catch (error) { + throw annotateLockedOpen(vfsName, resolvedFilename, error); } resolvedFilename = db.dbFilename(); diff --git a/tests/node-backend.test.cjs b/tests/node-backend.test.cjs index 539bcbd..d1c15f7 100644 --- a/tests/node-backend.test.cjs +++ b/tests/node-backend.test.cjs @@ -11,7 +11,7 @@ const test = require("node:test"); const assert = require("node:assert"); -const { spawnSync } = require("node:child_process"); +const { spawn, spawnSync } = require("node:child_process"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); @@ -202,7 +202,7 @@ test("a second open of the same file in one worker is refused", async () => { }); }); -test("a second process cannot open the same database", async () => { +test("the lock file is taken on open and released on close", async () => { const dataDir = tempDataDir(); const dbPath = path.join(dataDir, "wallet.db"); @@ -210,9 +210,6 @@ test("a second process cannot open the same database", async () => { const first = await bridge.open({ file: dbPath, vfs: "nodefs", mode: "rwc" }); await bridge.exec(first.dbId, "CREATE TABLE t(a)"); - // A live lock file naming another running process must block the open. - // The current process is a stand-in for a second holder: its pid is - // provably alive, which is the condition the lock check turns on. const lockPath = `${dbPath}-nodefs-lock`; assert.ok(fs.existsSync(lockPath), "no lock file was taken"); const owner = JSON.parse(fs.readFileSync(lockPath, "utf8")); @@ -223,6 +220,130 @@ test("a second process cannot open the same database", async () => { }); }); +test("a second process is refused while another holds the database", async () => { + // The refusal is the single mechanism keeping two writers off one wallet + // database, so it is tested against a real second process rather than + // against a lock file this process wrote about itself. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const holder = await spawnHolder(dbPath); + + try { + await withBridge(async (bridge) => { + await assert.rejects( + () => bridge.open({ + file: dbPath, vfs: "nodefs", mode: "rwc", + }), + (error) => { + // The holding pid has to survive out to the caller. A + // bare SQLITE_CANTOPEN is indistinguishable from a + // permissions problem or a missing directory. + assert.match( + error.message, /locked by another process/i + ); + assert.match( + error.message, new RegExp(`\\b${holder.pid}\\b`) + ); + return true; + } + ); + }); + } finally { + holder.kill("SIGKILL"); + } +}); + +test("the lock is taken before the database file is created", async () => { + // Creating the file first and locking afterwards leaves a window in which + // a process racing the same first-time open truncates a database the + // winner has already begun writing. The observable consequence of getting + // the order right is that a refused open leaves no file behind at all. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const idle = spawnIdle(); + + try { + fs.writeFileSync( + `${dbPath}-nodefs-lock`, + JSON.stringify({ pid: idle.pid, at: Date.now() }) + ); + + await withBridge(async (bridge) => { + await assert.rejects( + () => bridge.open({ + file: dbPath, vfs: "nodefs", mode: "rwc", + }), + /locked by another process/i + ); + }); + + assert.ok( + !fs.existsSync(dbPath), + "a refused open created the database file anyway" + ); + } finally { + idle.kill("SIGKILL"); + } +}); + +test("closing does not delete a lock another process now owns", async () => { + // If a reclaimer elsewhere decides this process is dead and takes the + // lock, the file on disk is that process's claim. Deleting it on the way + // out would hand the database to a third. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + const lockPath = `${dbPath}-nodefs-lock`; + const idle = spawnIdle(); + + try { + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, vfs: "nodefs", mode: "rwc", + }); + + fs.writeFileSync( + lockPath, + JSON.stringify({ pid: idle.pid, at: Date.now() }) + ); + + await bridge.close(opened.dbId); + }); + + assert.ok(fs.existsSync(lockPath), "another process's lock was deleted"); + const owner = JSON.parse(fs.readFileSync(lockPath, "utf8")); + assert.strictEqual(owner.pid, idle.pid); + } finally { + idle.kill("SIGKILL"); + } +}); + +test("a reclaim race over one stale lock admits a single writer", async () => { + // Two processes recovering from the same crashed owner both see a stale + // lock. Reclaiming by unlinking lets the second delete the fresh lock the + // first just took and then take one of its own, which is two writers on + // one database, arriving through the recovery path. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + fs.writeFileSync(dbPath, ""); + fs.writeFileSync( + `${dbPath}-nodefs-lock`, + JSON.stringify({ pid: 0x7fffffff, at: Date.now() }) + ); + + const racers = await Promise.all([ + raceForLock(dbPath), + raceForLock(dbPath), + raceForLock(dbPath), + ]); + + const winners = racers.filter((r) => r.held); + assert.strictEqual( + winners.length, 1, + `expected exactly one writer, got ${winners.length}: ` + + JSON.stringify(racers) + ); +}); + test("a stale lock from a dead process is reclaimed", async () => { const dataDir = tempDataDir(); const dbPath = path.join(dataDir, "wallet.db"); @@ -522,6 +643,146 @@ test("a WAL database survives an unclean process exit", async () => { }); }); +// spawnIdle starts a process that does nothing and stays running, for tests +// that need a pid which is provably alive and is not this one. +function spawnIdle() { + return spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { + stdio: "ignore", + }); +} + +// spawnHolder starts a child that opens the database and holds it until it is +// killed, resolving once the child reports the database open. Only a real +// second process exercises the lock, since the check turns on a pid other than +// this one being alive. +function spawnHolder(dbPath) { + const child = spawn(process.execPath, ["-e", holderSource()], { + env: { + ...process.env, + BRIDGE_PATH: bridgePath, + ASSET_DIR: sharedRuntime, + DB_PATH: dbPath, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + + return new Promise((resolve, reject) => { + let out = ""; + let err = ""; + let settled = false; + + child.stdout.on("data", (chunk) => { + out += chunk; + if (!settled && out.includes("HELD")) { + settled = true; + resolve(child); + } + }); + child.stderr.on("data", (chunk) => { + err += chunk; + }); + child.on("exit", (code) => { + if (!settled) { + settled = true; + reject(new Error(`holder exited early (${code}): ${err}`)); + } + }); + }); +} + +// raceForLock starts a child that tries to take the database and, having taken +// it, holds it long enough to overlap with its rivals. The holding is the +// point: a scheme that handed the lock to each racer in turn would look +// correct if every one of them released before the next was asked. +function raceForLock(dbPath) { + return new Promise((resolve) => { + const child = spawn(process.execPath, ["-e", racerSource()], { + env: { + ...process.env, + BRIDGE_PATH: bridgePath, + ASSET_DIR: sharedRuntime, + DB_PATH: dbPath, + HOLD_MS: "1500", + }, + stdio: ["ignore", "pipe", "pipe"], + }); + + let out = ""; + let err = ""; + child.stdout.on("data", (chunk) => { + out += chunk; + }); + child.stderr.on("data", (chunk) => { + err += chunk; + }); + child.on("exit", () => { + resolve({ + pid: child.pid, + held: out.includes("HELD"), + error: err.trim().split("\n").pop() || "", + }); + }); + }); +} + +// holderSource is the program spawnHolder runs: open the database and stay +// alive holding it. +function holderSource() { + return ` + "use strict"; + const fs = require("node:fs"); + globalThis.sqliteBridgeAssetDir = process.env.ASSET_DIR; + new Function("require", "__dirname", + fs.readFileSync(process.env.BRIDGE_PATH, "utf8") + )(require, process.env.ASSET_DIR); + + (async () => { + const bridge = globalThis.sqliteBridge; + const opened = await bridge.open({ + file: process.env.DB_PATH, + vfs: "nodefs", + mode: "rwc", + }); + await bridge.exec(opened.dbId, "CREATE TABLE t(a)"); + console.log("HELD"); + setInterval(() => {}, 1000); + })(); + `; +} + +// racerSource is the program raceForLock runs: try to take the database, +// announce success, hold it, and report a refusal on stderr instead. +function racerSource() { + return ` + "use strict"; + const fs = require("node:fs"); + globalThis.sqliteBridgeAssetDir = process.env.ASSET_DIR; + new Function("require", "__dirname", + fs.readFileSync(process.env.BRIDGE_PATH, "utf8") + )(require, process.env.ASSET_DIR); + + (async () => { + const bridge = globalThis.sqliteBridge; + try { + const opened = await bridge.open({ + file: process.env.DB_PATH, + vfs: "nodefs", + mode: "rwc", + }); + console.log("HELD"); + await new Promise((resolve) => + setTimeout(resolve, Number(process.env.HOLD_MS)) + ); + await bridge.close(opened.dbId); + } catch (error) { + console.error(error.message || String(error)); + process.exitCode = 3; + } + process.exit(process.exitCode || 0); + })(); + `; +} + // crashChildSource is the program the unclean-exit test runs in its own // process. It has to be a separate process rather than a terminated worker, // because the VFS's lock file records a pid and only releases the database From 1aa2f0c4250117524ef4c7d651d5caf5fc276b73 Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Mon, 10 Aug 2026 20:10:40 -0700 Subject: [PATCH 5/7] bridge: extend the journal mode readback to the pragma list The readback added alongside it only ever ran against the journalMode option, so a caller who wrote the journal mode into the pragma list got the old behavior back with nothing said. That is not an exotic way to hold it: the pragma list is where every other pragma goes, and Options.Pragma is public API with no documentation forbidding this one. Opening with pragma ["journal_mode=WAL", "synchronous=NORMAL"] returned a healthy handle sitting on the rollback journal with synchronous set for WAL, the combination that risks the database rather than the recently committed tail. It is exactly the state the readback exists to refuse. The journal mode is now lifted out of the pragma list and routed to the checked path, in the same place locking_mode is already hoisted, rather than rejected: the caller meant the thing that now happens, and telling them to move it to another key would only be a way of saying so. Asking for two different modes in the two places is an error, since there is no reading of that which is not a mistake. --- bridge/sqlite-worker.js | 40 +++++++++++++++++++++-- tests/node-backend.test.cjs | 63 +++++++++++++++++++++++++++++++++++++ 2 files changed, 101 insertions(+), 2 deletions(-) diff --git a/bridge/sqlite-worker.js b/bridge/sqlite-worker.js index ff83f98..280bfa7 100644 --- a/bridge/sqlite-worker.js +++ b/bridge/sqlite-worker.js @@ -531,6 +531,40 @@ function orderPragmas(pragmas) { ]; } +// extractJournalMode pulls a journal_mode pragma out of the caller's list and +// returns it alongside the pragmas that remain. +// +// The journal mode cannot be applied as an ordinary pragma, because the mode +// SQLite ends up in and the mode it was asked for are allowed to differ and +// only applyJournalMode looks. The pragma list is the natural place to write +// it, being where every other pragma goes, so a caller who does that would get +// precisely the silent downgrade the readback exists to refuse. Routing it to +// the checked path is kinder than rejecting it and gives the same answer. +function extractJournalMode(pragmas, journalMode) { + const isJournalMode = (pragma) => + /^\s*journal_mode\s*=/i.test(String(pragma)); + + const found = pragmas.filter(isJournalMode); + if (!found.length) { + return { pragmas, journalMode }; + } + + // Last one wins, matching what SQLite would have done had these run as + // ordinary pragmas in order. + const requested = String(found[found.length - 1]).split("=")[1].trim(); + if (journalMode && journalMode.toLowerCase() !== requested.toLowerCase()) { + throw new Error( + `conflicting journal modes: "${journalMode}" was requested as an ` + + `option and "${requested}" as a pragma` + ); + } + + return { + pragmas: pragmas.filter((pragma) => !isJournalMode(pragma)), + journalMode: journalMode || requested, + }; +} + // releaseOpened closes a database that was opened but never handed out, and // drops the duplicate-open bookkeeping that goes with it. function releaseOpened(opened) { @@ -661,7 +695,9 @@ async function open(args) { // it first, as this once did, meant a caller asking for WAL got the // rollback journal and no indication that it had. try { - for (const pragma of orderPragmas(args.pragma || [])) { + const routed = extractJournalMode(args.pragma || [], args.journalMode); + + for (const pragma of orderPragmas(routed.pragmas)) { if (!pragma) continue; try { opened.db.exec(`PRAGMA ${pragma}`); @@ -675,7 +711,7 @@ async function open(args) { ); } } - applyJournalMode(opened, args.journalMode); + applyJournalMode(opened, routed.journalMode); } catch (error) { // Configuration failed after the file was opened, so nothing will ever // hand this handle back to the caller. Release it here: a database left diff --git a/tests/node-backend.test.cjs b/tests/node-backend.test.cjs index d1c15f7..b35a1a1 100644 --- a/tests/node-backend.test.cjs +++ b/tests/node-backend.test.cjs @@ -643,6 +643,69 @@ test("a WAL database survives an unclean process exit", async () => { }); }); +test("journal_mode in the pragma list is checked, not silently downgraded", async () => { + // The pragma list is the natural place to write journal_mode, being where + // every other pragma goes. Routed there and left unchecked, a caller + // asking for WAL without the exclusive locking mode gets the rollback + // journal and a synchronous setting chosen for WAL: the combination that + // risks the database rather than the recently committed tail. + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + await assert.rejects( + () => bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + pragma: ["journal_mode=WAL", "synchronous=NORMAL"], + }), + /refusing to run with weaker guarantees/i + ); + }); +}); + +test("journal_mode as a pragma reaches WAL when the locking mode is there", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + const opened = await bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + pragma: [ + "journal_mode=WAL", + "synchronous=NORMAL", + "locking_mode=EXCLUSIVE", + ], + }); + + const rows = await bridge.query(opened.dbId, "PRAGMA journal_mode"); + assert.deepStrictEqual(rows.rows, [["wal"]]); + + await bridge.close(opened.dbId); + }); +}); + +test("a journal mode given twice and two ways is an error", async () => { + const dataDir = tempDataDir(); + const dbPath = path.join(dataDir, "wallet.db"); + + await withBridge(async (bridge) => { + await assert.rejects( + () => bridge.open({ + file: dbPath, + vfs: "nodefs", + mode: "rwc", + journalMode: "WAL", + pragma: ["journal_mode=DELETE", "locking_mode=EXCLUSIVE"], + }), + /conflicting journal modes/i + ); + }); +}); + // spawnIdle starts a process that does nothing and stays running, for tests // that need a pid which is provably alive and is not this one. function spawnIdle() { From 8b15ed792169578d81a70fbf42c3532dfa160d0c Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Mon, 10 Aug 2026 20:10:40 -0700 Subject: [PATCH 6/7] open: reject an unparseable require_persistent require_persistent was honored only when it was literally "true", so require_persistent=1, or the bare flag, was silently ignored. This is the option whose entire job is refusing to start without durable storage, and reading an unrecognized value as "no" disarms it at exactly the moment a caller was reaching for it. Both it and disallow_memory now parse as booleans and refuse what they cannot read. --- open.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/open.go b/open.go index 05e869c..9305bb1 100644 --- a/open.go +++ b/open.go @@ -203,12 +203,25 @@ func parseDSN(dsn string) (*Options, error) { opts.SQLiteJSURL = sqliteJSURL } - if requirePersistent := values.Get("require_persistent"); requirePersistent == "true" { - opts.RequirePersistent = true + // require_persistent and disallow_memory are the two flags whose entire + // job is refusing to run without durable storage, so an unrecognized + // value is an error rather than a silent false. Reading + // "require_persistent=1" as "no" would disarm the guard at precisely the + // moment the caller was reaching for it. + if requirePersistent := values.Get("require_persistent"); requirePersistent != "" { + v, err := strconv.ParseBool(requirePersistent) + if err != nil { + return nil, fmt.Errorf("invalid require_persistent: %w", err) + } + opts.RequirePersistent = v } - if disallowMemory := values.Get("disallow_memory"); disallowMemory == "true" { - opts.DisallowMemory = true + if disallowMemory := values.Get("disallow_memory"); disallowMemory != "" { + v, err := strconv.ParseBool(disallowMemory) + if err != nil { + return nil, fmt.Errorf("invalid disallow_memory: %w", err) + } + opts.DisallowMemory = v } if parseTime := values.Get("parse_time"); parseTime == "true" { From 9e5b7d51cdb20d5da84759deed1897e4837a45bb Mon Sep 17 00:00:00 2001 From: Olaoluwa Osuntokun Date: Mon, 10 Aug 2026 20:10:40 -0700 Subject: [PATCH 7/7] ci: run the Node storage backend tests Nothing in CI executed any of this. The compile job runs go test on the host, so the driver's Node tests are excluded by their js && wasm tag, and the Playwright job matches only *.spec.js, which leaves out the bridge suite. That is the VFS, its suite, and the Go driver tests under Node all sitting behind a green board that never runs them, which for a storage layer under a wallet key store reads as coverage while providing none. --- .github/workflows/ci.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eecb9ea..7236210 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -39,6 +39,30 @@ jobs: - name: Run go vet run: GOOS=js GOARCH=wasm go vet ./... + # The Node storage backend is invisible to every other job here: `compile` + # runs a host build, so the driver test's `js && wasm` tag excludes it, and + # the Playwright job matches only *.spec.js. Without this job the VFS, its + # test suite, and the Go driver tests under Node would all sit behind a green + # board that never runs them. + node-test: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Setup Node + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Run Node storage backend tests + run: make node-test + browser-test: runs-on: ubuntu-latest steps: