feat: adopt async SQLite and improve messaging and runtime diagnostics
This commit is contained in:
1 parent
effeb66554
commit
e699351f90
171 files changed
+5424
-3176
No files matched your search
@@ -0,0 +1,78 @@
|
||||
import path from 'node:path';
|
||||
import { loadNative, type BindValue, type NativeDatabase, type NativeStatement, type Row } from './native';
|
||||
|
||||
export type { BindValue } from './native';
|
||||
|
||||
/** Promises adapt native completion callbacks; SQLite work stays on native workers. */
|
||||
export async function openDatabase(filename: string, readOnly: boolean): Promise<Database> {
|
||||
if (process.permission && filename !== ':memory:') {
|
||||
const file = path.resolve(filename);
|
||||
const checks: ['fs.read' | 'fs.write', string][] = [['fs.read', file]];
|
||||
if (!readOnly) checks.push(['fs.write', file], ['fs.write', path.dirname(file)]);
|
||||
for (const [scope, resource] of checks) {
|
||||
if (!process.permission.has(scope, resource)) {
|
||||
throw new Error(`SQLite permission denied: ${scope} ${resource}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const binding = loadNative();
|
||||
const mode = (readOnly ? binding.OPEN_READONLY : binding.OPEN_READWRITE | binding.OPEN_CREATE) | binding.OPEN_FULLMUTEX;
|
||||
return new Promise((resolve, reject) => {
|
||||
new binding.Database(filename, mode, function (error) {
|
||||
if (error) reject(error);
|
||||
else resolve(new Database(this));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export class Database {
|
||||
constructor(private readonly native: NativeDatabase) {}
|
||||
|
||||
exec(sql: string): Promise<void> {
|
||||
return new Promise((resolve, reject) => this.native.exec(sql, error => error ? reject(error) : resolve()));
|
||||
}
|
||||
|
||||
prepare(sql: string): Promise<Statement> {
|
||||
const binding = loadNative();
|
||||
return new Promise((resolve, reject) => {
|
||||
new binding.Statement(this.native, sql, function (error) {
|
||||
if (error) reject(error);
|
||||
else resolve(new Statement(this));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return new Promise((resolve, reject) => this.native.close(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
export class Statement {
|
||||
constructor(private readonly native: NativeStatement) {}
|
||||
|
||||
run(parameters: BindValue[]): Promise<{ changes: number; lastIDBigInt: bigint }> {
|
||||
return new Promise((resolve, reject) => this.native.run(parameters, error => {
|
||||
if (error) { reject(error); return; }
|
||||
const { changes, lastIDBigInt } = this.native;
|
||||
if (changes === undefined || lastIDBigInt === undefined) {
|
||||
reject(new Error('SQLite native run completed without its result metadata'));
|
||||
} else resolve({ changes, lastIDBigInt });
|
||||
}));
|
||||
}
|
||||
|
||||
get(parameters: BindValue[]): Promise<Row | undefined> {
|
||||
return new Promise((resolve, reject) => this.native.get(parameters, (error, row) => error ? reject(error) : resolve(row)));
|
||||
}
|
||||
|
||||
all(parameters: BindValue[]): Promise<Row[]> {
|
||||
return new Promise((resolve, reject) => this.native.all(parameters, (error, rows) => error ? reject(error) : resolve(rows)));
|
||||
}
|
||||
|
||||
reset(): Promise<void> {
|
||||
return new Promise((resolve, reject) => this.native.reset(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
|
||||
finalize(): Promise<void> {
|
||||
return new Promise((resolve, reject) => this.native.finalize(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { openDatabase, type Database, type Statement, type BindValue } from './driver';
|
||||
|
||||
export type SqliteValue = BindValue;
|
||||
export type SqliteRow = Record<string, unknown>;
|
||||
const MAX_PENDING_OPERATIONS = 2048;
|
||||
const context = new AsyncLocalStorage<{ database: SqliteDatabase; active: boolean }>();
|
||||
|
||||
/** Owns one native asynchronous connection. Serialize whole store operations,
|
||||
* not only statements, so unrelated calls cannot enter another call's transaction.
|
||||
*/
|
||||
export class SqliteDatabase {
|
||||
readonly initialization: Promise<void>;
|
||||
private database!: Database;
|
||||
private opened = false;
|
||||
private tail: Promise<unknown>;
|
||||
private readonly statements = new Map<string, Statement>();
|
||||
private pending = 0;
|
||||
private closing: Promise<void> | null = null;
|
||||
|
||||
constructor(filename: string, options: { readOnly?: boolean; busyTimeout?: number } = {}) {
|
||||
this.initialization = (async () => {
|
||||
if (!options.readOnly && filename !== ':memory:') {
|
||||
await mkdir(path.dirname(filename), { recursive: true });
|
||||
}
|
||||
this.database = await openDatabase(filename, options.readOnly ?? false);
|
||||
this.opened = true;
|
||||
try {
|
||||
await this.database.exec(`PRAGMA busy_timeout = ${options.busyTimeout ?? 1000}`);
|
||||
await this.database.exec('PRAGMA foreign_keys = ON');
|
||||
if (!options.readOnly) {
|
||||
await this.database.exec('PRAGMA journal_mode = WAL');
|
||||
await this.database.exec('PRAGMA synchronous = NORMAL');
|
||||
}
|
||||
} catch (error) {
|
||||
try { await this.database.close(); this.opened = false; }
|
||||
catch (closeError) { throw new AggregateError([error, closeError], 'SQLite initialization and cleanup failed', { cause: error }); }
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
this.tail = this.initialization.catch(() => undefined);
|
||||
}
|
||||
|
||||
serial<T>(operation: () => T | Promise<T>): Promise<T> {
|
||||
const current = context.getStore();
|
||||
if (current?.database === this && current.active) return Promise.resolve().then(operation);
|
||||
if (this.closing) return Promise.reject(new Error('SQLite database is closing'));
|
||||
if (this.pending >= MAX_PENDING_OPERATIONS) return Promise.reject(new Error('SQLite operation queue is full'));
|
||||
this.pending++;
|
||||
const work = this.tail.then(async () => {
|
||||
await this.initialization;
|
||||
const scope = { database: this, active: true };
|
||||
try { return await context.run(scope, operation); }
|
||||
finally { scope.active = false; }
|
||||
});
|
||||
this.tail = work.then(() => undefined, () => undefined).finally(() => { this.pending--; });
|
||||
return work;
|
||||
}
|
||||
|
||||
prepare(sql: string): SqliteStatement { return new SqliteStatement(this, sql); }
|
||||
|
||||
exec(sql: string): Promise<void> {
|
||||
return this.serial(() => this.database.exec(sql));
|
||||
}
|
||||
|
||||
/** Preparation and statement execution both happen in the driver's native workers. */
|
||||
execute<T>(sql: string, operation: (statement: Statement) => Promise<T>): Promise<T> {
|
||||
return this.serial(async () => {
|
||||
let statement = this.statements.get(sql);
|
||||
if (!statement) {
|
||||
statement = await this.database.prepare(sql);
|
||||
this.statements.set(sql, statement);
|
||||
}
|
||||
try { return await operation(statement); }
|
||||
finally {
|
||||
// get() may stop on SQLITE_ROW. Release its read snapshot before the
|
||||
// next operation or another connection's commit causes BUSY_SNAPSHOT.
|
||||
await statement.reset();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
if (this.closing) return this.closing;
|
||||
this.closing = (async () => {
|
||||
await this.tail;
|
||||
// The initialization promise reports startup failures. Cleanup must still
|
||||
// release a partially initialized connection without repeating that error.
|
||||
await this.initialization.catch(() => undefined);
|
||||
if (!this.opened) return;
|
||||
const results = await Promise.allSettled([...this.statements.values()].map(statement => statement.finalize()));
|
||||
this.statements.clear();
|
||||
const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
||||
try { await this.database.close(); this.opened = false; } catch (error) { errors.push(error); }
|
||||
if (errors.length) throw new AggregateError(errors, 'SQLite close failed');
|
||||
})();
|
||||
void this.closing.catch(() => { this.closing = null; });
|
||||
return this.closing;
|
||||
}
|
||||
}
|
||||
|
||||
/** A lazy SQL descriptor: creating it does not touch SQLite or block JavaScript. */
|
||||
export class SqliteStatement {
|
||||
constructor(private readonly database: SqliteDatabase, readonly sourceSQL: string) {}
|
||||
|
||||
run(...values: SqliteValue[]): Promise<{ changes: number; lastInsertRowid: number | bigint }> {
|
||||
const parameters = structuredClone(values);
|
||||
return this.database.execute(this.sourceSQL, async statement => {
|
||||
const result = await statement.run(parameters);
|
||||
return { changes: result.changes, lastInsertRowid: result.lastIDBigInt };
|
||||
});
|
||||
}
|
||||
|
||||
get(...values: SqliteValue[]): Promise<SqliteRow | undefined> {
|
||||
const parameters = structuredClone(values);
|
||||
return this.database.execute(this.sourceSQL, statement => statement.get(parameters));
|
||||
}
|
||||
|
||||
all(...values: SqliteValue[]): Promise<SqliteRow[]> {
|
||||
const parameters = structuredClone(values);
|
||||
return this.database.execute(this.sourceSQL, statement => statement.all(parameters));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// Upgrade these together with package.json, then rerun the native and bundle tests.
|
||||
export const DRIVER_VERSION = '9.1.0';
|
||||
export const NATIVE_INTERFACE_VERSION = 1;
|
||||
export const REQUIRED_NAPI_VERSION = 10;
|
||||
export const RELEASE_PREBUILDS = './native/sqlite/prebuilds/';
|
||||
|
||||
export function prebuildFiles(target: string): string[] {
|
||||
if (!/^(win32|linux|darwin)-(x64|arm64)$/.test(target)) {
|
||||
throw new Error(`Unsupported SQLite target: ${target}`);
|
||||
}
|
||||
return (target.startsWith('linux-')
|
||||
? ['@appthreat+sqlite3.glibc.node', '@appthreat+sqlite3.musl.node']
|
||||
: ['@appthreat+sqlite3.node']).map(file => `${target}/${file}`);
|
||||
}
|
||||
|
||||
export function runtimePrebuild(platform: string, arch: string, libc?: 'glibc' | 'musl'): string {
|
||||
const target = `${platform}-${arch}`;
|
||||
const files = prebuildFiles(target);
|
||||
if (platform !== 'linux') return files[0];
|
||||
if (!libc) throw new Error('SQLite requires an explicit Linux libc selection');
|
||||
return `${target}/@appthreat+sqlite3.${libc}.node`;
|
||||
}
|
||||
|
||||
export function assertRuntime(node: string, napi: string | undefined): void {
|
||||
if (!(Number.parseInt(node, 10) >= 24) || !(Number(napi) >= REQUIRED_NAPI_VERSION)) {
|
||||
throw new Error(`SQLite requires Node >=24 and Node-API >=${REQUIRED_NAPI_VERSION}; got Node ${node}, Node-API ${napi ?? 'unavailable'}`);
|
||||
}
|
||||
}
|
||||
|
||||
export function runtimeLibc(report: object): 'glibc' | 'musl' {
|
||||
if (!('header' in report) || !report.header || typeof report.header !== 'object') {
|
||||
throw new Error('Cannot determine SQLite libc: Node diagnostic report has no header');
|
||||
}
|
||||
return 'glibcVersionRuntime' in report.header && typeof report.header.glibcVersionRuntime === 'string'
|
||||
&& report.header.glibcVersionRuntime.length > 0 ? 'glibc' : 'musl';
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { assertRuntime, NATIVE_INTERFACE_VERSION, RELEASE_PREBUILDS, runtimeLibc, runtimePrebuild } from './layout';
|
||||
|
||||
// Only the callback ABI used by SnowLuma is exposed. No upstream JavaScript,
|
||||
// convenience methods, synchronous SQL methods or node-gyp resolver are loaded.
|
||||
export type BindValue = string | number | bigint | boolean | null | undefined
|
||||
| Uint8Array | ArrayBuffer | DataView | Date | RegExp;
|
||||
export type Row = Record<string, unknown>;
|
||||
type Done = (error: Error | null) => void;
|
||||
|
||||
export interface NativeDatabase {
|
||||
exec(sql: string, callback: Done): void;
|
||||
close(callback: Done): void;
|
||||
}
|
||||
|
||||
export interface NativeStatement {
|
||||
run(parameters: BindValue[], callback: Done): void;
|
||||
get(parameters: BindValue[], callback: (error: Error | null, row: Row | undefined) => void): void;
|
||||
all(parameters: BindValue[], callback: (error: Error | null, rows: Row[]) => void): void;
|
||||
reset(callback: Done): void;
|
||||
finalize(callback: Done): void;
|
||||
readonly changes: number | undefined;
|
||||
readonly lastIDBigInt: bigint | undefined;
|
||||
}
|
||||
|
||||
interface NativeBinding {
|
||||
NATIVE_INTERFACE_VERSION: number;
|
||||
OPEN_READONLY: number;
|
||||
OPEN_READWRITE: number;
|
||||
OPEN_CREATE: number;
|
||||
OPEN_FULLMUTEX: number;
|
||||
Database: new (filename: string, mode: number, callback: (this: NativeDatabase, error: Error | null) => void) => NativeDatabase;
|
||||
Statement: new (database: NativeDatabase, sql: string, callback: (this: NativeStatement, error: Error | null) => void) => NativeStatement;
|
||||
}
|
||||
|
||||
function assertBinding(value: unknown): asserts value is NativeBinding {
|
||||
if (!value || typeof value !== 'object'
|
||||
|| !('NATIVE_INTERFACE_VERSION' in value) || value.NATIVE_INTERFACE_VERSION !== NATIVE_INTERFACE_VERSION
|
||||
|| !('Database' in value) || typeof value.Database !== 'function'
|
||||
|| !('Statement' in value) || typeof value.Statement !== 'function'
|
||||
|| !('OPEN_READONLY' in value) || value.OPEN_READONLY !== 1
|
||||
|| !('OPEN_READWRITE' in value) || value.OPEN_READWRITE !== 2
|
||||
|| !('OPEN_CREATE' in value) || value.OPEN_CREATE !== 4
|
||||
|| !('OPEN_FULLMUTEX' in value) || value.OPEN_FULLMUTEX !== 0x10000) {
|
||||
throw new Error(`SQLite native interface mismatch; expected interface ${NATIVE_INTERFACE_VERSION}`);
|
||||
}
|
||||
}
|
||||
|
||||
declare const __SNOWLUMA_SQLITE_RELEASE__: boolean;
|
||||
let binding: NativeBinding | undefined;
|
||||
|
||||
export function loadNative(): NativeBinding {
|
||||
if (binding) return binding;
|
||||
assertRuntime(process.versions.node, process.versions.napi);
|
||||
const libc = process.platform === 'linux'
|
||||
? runtimeLibc(process.report.getReport())
|
||||
: undefined;
|
||||
const file = runtimePrebuild(process.platform, process.arch, libc);
|
||||
// Vite makes the release branch constant. A missing release binary must fail,
|
||||
// never fall back to another install, the working directory or a local build.
|
||||
const root = typeof __SNOWLUMA_SQLITE_RELEASE__ !== 'undefined' && __SNOWLUMA_SQLITE_RELEASE__
|
||||
? fileURLToPath(new URL(RELEASE_PREBUILDS, import.meta.url))
|
||||
: path.join(path.dirname(createRequire(import.meta.url).resolve('@appthreat/sqlite3/package.json')), 'prebuilds');
|
||||
const filename = path.join(root, file);
|
||||
try {
|
||||
const module: { exports: unknown } = { exports: {} };
|
||||
process.dlopen(module, filename);
|
||||
assertBinding(module.exports);
|
||||
// The native constructors emit open/close/error events even when callbacks
|
||||
// are supplied, and expect EventEmitter methods on their prototypes.
|
||||
Object.assign(module.exports.Database.prototype, EventEmitter.prototype);
|
||||
Object.assign(module.exports.Statement.prototype, EventEmitter.prototype);
|
||||
binding = module.exports;
|
||||
return binding;
|
||||
} catch (cause) {
|
||||
throw new Error(`Failed to load SQLite native addon: ${filename}`, { cause });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import fs from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import path from 'node:path';
|
||||
import type { Plugin } from 'vite';
|
||||
import { DRIVER_VERSION, NATIVE_INTERFACE_VERSION, prebuildFiles } from './layout.ts';
|
||||
|
||||
/** Upstream is a locked prebuild source, never a runtime JS or installer dependency. */
|
||||
export function sqliteBuildPlugin(target: string): Plugin {
|
||||
const require = createRequire(import.meta.url);
|
||||
const driverRoot = path.dirname(require.resolve('@appthreat/sqlite3/package.json'));
|
||||
const metadata: unknown = JSON.parse(fs.readFileSync(path.join(driverRoot, 'package.json'), 'utf8'));
|
||||
if (!metadata || typeof metadata !== 'object' || !('version' in metadata) || metadata.version !== DRIVER_VERSION) {
|
||||
throw new Error(`SQLite prebuild version mismatch; expected @appthreat/sqlite3 ${DRIVER_VERSION}`);
|
||||
}
|
||||
const files = prebuildFiles(target).map(file => `prebuilds/${file}`);
|
||||
const assets = [
|
||||
...files.map(file => ({ file, source: path.join(driverRoot, file) })),
|
||||
{ file: 'LICENSE.sqlite3', source: path.join(driverRoot, 'LICENSE') },
|
||||
];
|
||||
for (const asset of assets) {
|
||||
if (!fs.statSync(asset.source, { throwIfNoEntry: false })?.isFile()) {
|
||||
throw new Error(`Missing SQLite release input for ${target}: ${asset.source}`);
|
||||
}
|
||||
}
|
||||
return {
|
||||
name: 'snowluma-sqlite-prebuilds',
|
||||
config: () => ({ define: { __SNOWLUMA_SQLITE_RELEASE__: 'true' } }),
|
||||
generateBundle() {
|
||||
for (const asset of assets) {
|
||||
this.emitFile({ type: 'asset', fileName: `native/sqlite/${asset.file}`, source: fs.readFileSync(asset.source) });
|
||||
}
|
||||
this.emitFile({
|
||||
type: 'asset', fileName: 'native/sqlite/manifest.json',
|
||||
source: JSON.stringify({
|
||||
package: '@appthreat/sqlite3', version: DRIVER_VERSION,
|
||||
nativeInterface: NATIVE_INTERFACE_VERSION, target, files,
|
||||
}, null, 2) + '\n',
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user