diff --git a/.github/workflows/build-wasm-no-docker.yaml b/.github/workflows/build-wasm-no-docker.yaml index 4cbceebb..a23faffb 100644 --- a/.github/workflows/build-wasm-no-docker.yaml +++ b/.github/workflows/build-wasm-no-docker.yaml @@ -37,10 +37,10 @@ jobs: run: | sudo apt-get update sudo apt-get install cmake python3 python3-pip - git clone --branch 3.1.59 --depth 1 https://github.com/emscripten-core/emsdk.git + git clone --branch 6.0.3 --depth 1 https://github.com/emscripten-core/emsdk.git cd emsdk - ./emsdk install 3.1.59 - ./emsdk activate 3.1.59 + ./emsdk install 6.0.3 + ./emsdk activate 6.0.3 source ./emsdk_env.sh working-directory: versions/18 - name: Build with Emscripten 🏗 diff --git a/scripts/copy-templates.js b/scripts/copy-templates.js index 58930386..26aba149 100755 --- a/scripts/copy-templates.js +++ b/scripts/copy-templates.js @@ -66,7 +66,7 @@ const TEMPLATE_FILES = [ { src: 'wasm_wrapper.c', dest: 'src/wasm_wrapper.c', header: HEADER, hasFullVariant: true }, { src: 'libpg-query.d.ts', dest: 'src/libpg-query.d.ts', header: HEADER, hasFullVariant: true }, { src: 'index.ts', dest: 'src/index.ts', header: HEADER, hasFullVariant: true }, - { src: 'pre.js', dest: 'src/pre.js', header: HEADER, hasFullVariant: false } + { src: 'pre.js', dest: 'src/pre.js', header: HEADER, appendFullVariant: true } ]; const SLIM_EXPORTED_FUNCTIONS = "['_malloc','_free','_wasm_parse_query_raw','_wasm_free_parse_result']"; @@ -96,6 +96,9 @@ function copyTemplates() { // Read template content let content = fs.readFileSync(srcPath, 'utf8'); + if (config.fullApi && file.appendFullVariant) { + content += '\n' + fs.readFileSync(path.join(templatesDir, 'full', file.src), 'utf8'); + } // Add header if specified if (file.header) { diff --git a/templates/full/index.ts b/templates/full/index.ts index 1caa6833..9e254ceb 100644 --- a/templates/full/index.ts +++ b/templates/full/index.ts @@ -117,9 +117,11 @@ export function formatSqlError( import PgQueryModule from './libpg-query.js'; interface WasmModule { + compiledWasm: WasmCompiledModule; _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_query_raw: (queryPtr: number) => number; _wasm_free_parse_result: (ptr: number) => void; @@ -135,49 +137,36 @@ interface WasmModule { } let wasmModule: WasmModule; - -// After a WASM call throws, the instance is stale: async calls wait for its -// replacement, while sync calls, which cannot wait, keep using it until the -// replacement is ready. One replacement loads at a time; the next call retries -// a failed load. -let stale = false; +let compiledWasm: WasmCompiledModule | undefined; let loading: Promise | undefined; -// Counts WASM calls that threw, so cleanup skips an instance that threw mid-call. +// Invalidation skips cleanup through pointers that belong to a failed instance. let failures = 0; -// Sync calls stop using a stale instance after this many failures on it: past -// about 45, a stack overflow can make the next one spin forever. -const MAX_STALE_FAILURES = 10; -let staleFailures = 0; -// Set by loadModule({ wasm }); instances are then created from it instead of the file. -let provided: WasmCompiledModule | undefined; - -function createModule(): Promise { - const module = provided; - if (!module) return PgQueryModule(); - return new Promise((resolve, reject) => { - PgQueryModule({ - instantiateWasm(imports: any, receive: (instance: any) => void) { - WebAssembly.instantiate(module, imports).then(receive, reject); - return {}; - }, - }).then(resolve, reject); - }); +// Dropped instances can remain live until the current synchronous run yields. +const LARGE_HEAP_BYTES = 512 * 1024 * 1024; +let largeFailures = 0; +let memoryLimitError: Error | undefined; +let largeHeapYield: Promise | undefined; + +function createSync(module: WasmCompiledModule): WasmModule { + const options: Partial & { readySync?: boolean; initError?: unknown } = { + compiledWasm: module, + }; + PgQueryModule(options).catch(() => {}); + if (!options.readySync) { + throw new Error('Could not start a fresh WASM instance', { cause: options.initError }); + } + return options as WasmModule; } function instantiate(): Promise { if (loading) return loading; - const promise = createModule().then( - (module: WasmModule) => { - wasmModule = module; - stale = false; - staleFailures = 0; - loading = undefined; - }, - (error: unknown) => { - loading = undefined; - throw error; + const promise = Promise.resolve().then(async () => { + while (!wasmModule && largeHeapYield) await largeHeapYield; + if (!wasmModule) { + wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); + compiledWasm = wasmModule.compiledWasm; } - ); + }).finally(() => { loading = undefined; }); loading = promise; // Rejects only for the callers awaiting it. promise.catch(() => {}); @@ -186,6 +175,29 @@ function instantiate(): Promise { instantiate(); +function invalidateModule(error: unknown): void { + if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + // Async callers can give V8 a task to release the dropped heap before allocating again. + largeHeapYield ??= new Promise((resolve) => setTimeout(() => { + largeHeapYield = undefined; + resolve(); + }, 0)); + if (++largeFailures === 1) { + queueMicrotask(() => { + largeFailures = 0; + memoryLimitError = undefined; + }); + } else { + memoryLimitError = new Error( + 'WASM memory limit hit repeatedly in one synchronous run; yield (await) before retrying', + { cause: error } + ); + } + } + failures++; + wasmModule = undefined; +} + // An exception out of a WASM call (V8 stack overflow on deeply nested SQL, a // trap, or exit() once the heap limit is hit) skips libpg_query's cleanup and // leaves the instance corrupt, so replace it with a fresh one. @@ -195,19 +207,24 @@ function callWasm(fn: () => number): number { try { return fn(); } catch (error) { - failures++; - stale = true; - if (++staleFailures >= MAX_STALE_FAILURES) wasmModule = undefined; - instantiate(); if (proc) proc.exitCode = exitCode; - if (error instanceof Error) throw error; + if (error instanceof Error) { + invalidateModule(error); + throw error; + } const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) : error; - throw new Error( + // Emscripten's ExitStatus keeps its loader closure and WASM heap alive. + const cause = typeof error === 'object' && error !== null && 'name' in error && error.name === 'ExitStatus' + ? { ...error } + : error; + const wrapped = new Error( `libpg_query terminated (${reason}), most likely out of WASM memory; parse large inputs in smaller pieces`, - { cause: error } + { cause } ); + invalidateModule(wrapped); + throw wrapped; } } @@ -215,20 +232,16 @@ function callWasm(fn: () => number): number { // keeps going, but the instance's heap stays grown to the size it reached (WASM // memory never shrinks), so load a fresh instance and let this one be freed. function outOfMemoryError(): Error { - stale = true; - instantiate(); - return new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); -} - -function throwIfErrorString(resultStr: string): void { - if (resultStr === 'out of memory') throw outOfMemoryError(); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR') || resultStr.startsWith('stack depth limit exceeded')) { - throw new Error(resultStr); - } + const error = new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); + invalidateModule(error); + return error; } function ensureLoaded() { - if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); + if (wasmModule) return; + if (memoryLimitError) throw memoryLimitError; + if (!compiledWasm) throw new Error("WASM module not initialized. Call `loadModule()` first."); + wasmModule = createSync(compiledWasm); } type WasmCompiledModule = typeof globalThis extends { @@ -250,20 +263,22 @@ export interface LoadModuleOptions { export async function loadModule(...args: [options?: LoadModuleOptions]): Promise { const wasm = args[0]?.wasm; if (wasm !== undefined) { - provided = wasm instanceof WebAssembly.Module + const module = wasm instanceof WebAssembly.Module ? wasm : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); - stale = true; + if (largeHeapYield) await largeHeapYield; + wasmModule = createSync(module); + compiledWasm = module; } - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); } function awaitInit Promise>(fn: T): T { return (async (...args: Parameters) => { // Re-checked after every await: another call may have failed in between. - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); return fn(...args); }) as T; } @@ -300,6 +315,49 @@ function ptrToString(ptr: number): string { return wasmModule.UTF8ToString(ptr); } +type DetailedOperation = '_wasm_fingerprint' | '_wasm_normalize_query' | '_wasm_scan'; + +function callDetailed(query: string, operation: DetailedOperation): string { + const queryPtr = stringToPtr(query); + const failuresBefore = failures; + let resultPtr = 0; + + try { + resultPtr = callWasm(() => wasmModule[operation](queryPtr)); + if (!resultPtr) throw outOfMemoryError(); + + // WasmDetailedResult uses 32-bit fields and pointers. + if (wasmModule.getValue(resultPtr, 'i32')) { + const readString = (offset: number) => { + const ptr = wasmModule.getValue(resultPtr + offset, 'i32'); + return ptr ? wasmModule.UTF8ToString(ptr) : undefined; + }; + const message = readString(4) ?? 'Unknown error'; + if (message === 'out of memory') throw outOfMemoryError(); + + const lineno = wasmModule.getValue(resultPtr + 16, 'i32'); + const cursorpos = wasmModule.getValue(resultPtr + 20, 'i32'); + const context = readString(24); + throw new SqlError(message, { + message, + cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, + fileName: readString(12), + functionName: readString(8), + lineNumber: lineno > 0 ? lineno : undefined, + ...(context !== undefined ? { context } : {}) + }); + } + return wasmModule.UTF8ToString(wasmModule.getValue(resultPtr + 28, 'i32')); + } finally { + if (failures === failuresBefore) { + wasmModule._free(queryPtr); + if (resultPtr) { + wasmModule._wasm_free_detailed_result(resultPtr); + } + } + } +} + export const parse = awaitInit(async (query: string): Promise => { // Input validation if (query === null || query === undefined) { @@ -390,54 +448,16 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); }); export const normalize = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); }); // Sync versions export function parseSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } + ensureLoaded(); // Input validation if (query === null || query === undefined) { @@ -502,9 +522,6 @@ export function parseSync(query: string): ParseResult { } export function parsePlPgSQLSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -531,98 +548,17 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); } export const scan = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return JSON.parse(callDetailed(query, '_wasm_scan')); }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } -} \ No newline at end of file + return JSON.parse(callDetailed(query, '_wasm_scan')); +} diff --git a/templates/full/libpg-query.d.ts b/templates/full/libpg-query.d.ts index 731e1a99..7fcbfb0d 100644 --- a/templates/full/libpg-query.d.ts +++ b/templates/full/libpg-query.d.ts @@ -3,10 +3,12 @@ declare module './libpg-query.js' { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_plpgsql: (queryPtr: number) => number; _wasm_fingerprint: (queryPtr: number) => number; _wasm_normalize_query: (queryPtr: number) => number; + _wasm_scan: (queryPtr: number) => number; lengthBytesUTF8: (str: string) => number; stringToUTF8: (str: string, ptr: number, len: number) => void; UTF8ToString: (ptr: number) => string; diff --git a/templates/full/pre.js b/templates/full/pre.js new file mode 100644 index 00000000..55c16c03 --- /dev/null +++ b/templates/full/pre.js @@ -0,0 +1,23 @@ +// Keep the module from the pinned Emscripten factory's own asset load. +if (!Module['compiledWasm']) { + var instantiateFromAsset = instantiateAsync; + instantiateAsync = async (...args) => { + var result = await instantiateFromAsset(...args); + Module['compiledWasm'] = result.module; + return result; + }; +} else { + Module['instantiateWasm'] = (imports, receive) => { + try { + receive(new WebAssembly.Instance(Module['compiledWasm'], imports)); + // This build has no main or startup hooks. Initialize libc and stdio + // now, then skip the deferred run() so it cannot initialize them twice. + initRuntime(); + run = () => {}; + Module['readySync'] = true; + } catch (error) { + Module['initError'] = error; + throw error; + } + }; +} diff --git a/templates/full/wasm_wrapper.c b/templates/full/wasm_wrapper.c index 87f96c1f..6a5768ec 100644 --- a/templates/full/wasm_wrapper.c +++ b/templates/full/wasm_wrapper.c @@ -104,53 +104,6 @@ char* wasm_parse_plpgsql(const char* input) { return wrapped_result; } -EMSCRIPTEN_KEEPALIVE -char* wasm_fingerprint(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryFingerprintResult result = pg_query_fingerprint(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_fingerprint_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* fingerprint_str = safe_strdup(result.fingerprint_str); - pg_query_free_fingerprint_result(result); - return fingerprint_str; -} - -EMSCRIPTEN_KEEPALIVE -char* wasm_normalize_query(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryNormalizeResult result = pg_query_normalize(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_normalize_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* normalized = safe_strdup(result.normalized_query); - pg_query_free_normalize_result(result); - - if (!normalized) { - return safe_strdup("Memory allocation failed"); - } - - return normalized; -} - - - - - typedef struct { int has_error; char* message; @@ -230,6 +183,65 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } +// Takes ownership of data and copies any error before libpg_query frees it. +static WasmDetailedResult* make_detailed_result(char* data, const PgQueryError* error) { + if (!data && !error) return NULL; + + WasmDetailedResult* result = calloc(1, sizeof(WasmDetailedResult)); + if (!result) { + free(data); + return NULL; + } + + result->data = data; + if (error) { + result->has_error = 1; + result->message = safe_strdup(error->message); + result->funcname = safe_strdup(error->funcname); + result->filename = safe_strdup(error->filename); + result->lineno = error->lineno; + result->cursorpos = error->cursorpos; + result->context = safe_strdup(error->context); + if ((error->message && !result->message) || + (error->funcname && !result->funcname) || + (error->filename && !result->filename) || + (error->context && !result->context)) { + wasm_free_detailed_result(result); + return NULL; + } + } else { + result->data_len = strlen(data); + } + return result; +} + +static WasmDetailedResult* invalid_input_result(void) { + const PgQueryError error = { .message = "Invalid input: query cannot be null or empty" }; + return make_detailed_result(NULL, &error); +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_fingerprint(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryFingerprintResult result = pg_query_fingerprint(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.fingerprint_str), result.error); + pg_query_free_fingerprint_result(result); + return detailed; +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_normalize_query(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryNormalizeResult result = pg_query_normalize(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.normalized_query), result.error); + pg_query_free_normalize_result(result); + return detailed; +} + static const char* get_token_name(PgQueryToken token_type) { // Map some common token types to readable names // Note: This is a simplified mapping - full enum lookup would require more complexity @@ -285,10 +297,6 @@ static size_t scan_json_escaped_length(const char* text, int length) { } static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { - if (!scan_result || !original_sql) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); - } - // Reserve space for each token's escaped text and fixed JSON fields. size_t estimated_size = 1024; for (int i = 0; i < scan_result->n_tokens; i++) { @@ -297,17 +305,17 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (token_length < 0) token_length = 0; size_t escaped_length = scan_json_escaped_length(&original_sql[token->start], token_length); if (escaped_length > SIZE_MAX - 200) { - return safe_strdup("out of memory"); + return NULL; } size_t token_size = escaped_length + 200; if (estimated_size > SIZE_MAX - token_size) { - return safe_strdup("out of memory"); + return NULL; } estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("out of memory"); + return NULL; } // Start building JSON @@ -323,7 +331,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c char* token_text = safe_malloc((size_t) token_length + 1); if (!token_text) { free(json); - return safe_strdup("out of memory"); + return NULL; } if (token_length > 0) { @@ -337,7 +345,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (!escaped_text) { free(token_text); free(json); - return safe_strdup("out of memory"); + return NULL; } size_t escaped_pos = 0; @@ -395,24 +403,14 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c } EMSCRIPTEN_KEEPALIVE -char* wasm_scan(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - +WasmDetailedResult* wasm_scan(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_tokens_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* json_result = build_scan_json(&result, input); - + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : build_scan_json(&result, input), result.error); pg_query_free_scan_tokens_result(result); - - return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); + return detailed; } EMSCRIPTEN_KEEPALIVE diff --git a/versions/18/README_ERROR_HANDLING.md b/versions/18/README_ERROR_HANDLING.md index c9f23c65..522f6397 100644 --- a/versions/18/README_ERROR_HANDLING.md +++ b/versions/18/README_ERROR_HANDLING.md @@ -6,7 +6,7 @@ Version 18 includes enhanced error handling that provides detailed information a ## Error Details -When a parsing error occurs, the error object now includes a `sqlDetails` property with the following information: +PostgreSQL errors from `parse`, `fingerprint`, `normalize`, and `scan` (including their sync variants) throw a `SqlError` with a `sqlDetails` property: ```typescript interface SqlErrorDetails { diff --git a/versions/18/src/index.ts b/versions/18/src/index.ts index 5082f7f9..5c2a9a18 100644 --- a/versions/18/src/index.ts +++ b/versions/18/src/index.ts @@ -124,9 +124,11 @@ export function formatSqlError( import PgQueryModule from './libpg-query.js'; interface WasmModule { + compiledWasm: WasmCompiledModule; _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_query_raw: (queryPtr: number) => number; _wasm_free_parse_result: (ptr: number) => void; @@ -142,49 +144,36 @@ interface WasmModule { } let wasmModule: WasmModule; - -// After a WASM call throws, the instance is stale: async calls wait for its -// replacement, while sync calls, which cannot wait, keep using it until the -// replacement is ready. One replacement loads at a time; the next call retries -// a failed load. -let stale = false; +let compiledWasm: WasmCompiledModule | undefined; let loading: Promise | undefined; -// Counts WASM calls that threw, so cleanup skips an instance that threw mid-call. +// Invalidation skips cleanup through pointers that belong to a failed instance. let failures = 0; -// Sync calls stop using a stale instance after this many failures on it: past -// about 45, a stack overflow can make the next one spin forever. -const MAX_STALE_FAILURES = 10; -let staleFailures = 0; -// Set by loadModule({ wasm }); instances are then created from it instead of the file. -let provided: WasmCompiledModule | undefined; - -function createModule(): Promise { - const module = provided; - if (!module) return PgQueryModule(); - return new Promise((resolve, reject) => { - PgQueryModule({ - instantiateWasm(imports: any, receive: (instance: any) => void) { - WebAssembly.instantiate(module, imports).then(receive, reject); - return {}; - }, - }).then(resolve, reject); - }); +// Dropped instances can remain live until the current synchronous run yields. +const LARGE_HEAP_BYTES = 512 * 1024 * 1024; +let largeFailures = 0; +let memoryLimitError: Error | undefined; +let largeHeapYield: Promise | undefined; + +function createSync(module: WasmCompiledModule): WasmModule { + const options: Partial & { readySync?: boolean; initError?: unknown } = { + compiledWasm: module, + }; + PgQueryModule(options).catch(() => {}); + if (!options.readySync) { + throw new Error('Could not start a fresh WASM instance', { cause: options.initError }); + } + return options as WasmModule; } function instantiate(): Promise { if (loading) return loading; - const promise = createModule().then( - (module: WasmModule) => { - wasmModule = module; - stale = false; - staleFailures = 0; - loading = undefined; - }, - (error: unknown) => { - loading = undefined; - throw error; + const promise = Promise.resolve().then(async () => { + while (!wasmModule && largeHeapYield) await largeHeapYield; + if (!wasmModule) { + wasmModule = compiledWasm ? createSync(compiledWasm) : await PgQueryModule(); + compiledWasm = wasmModule.compiledWasm; } - ); + }).finally(() => { loading = undefined; }); loading = promise; // Rejects only for the callers awaiting it. promise.catch(() => {}); @@ -193,6 +182,29 @@ function instantiate(): Promise { instantiate(); +function invalidateModule(error: unknown): void { + if (wasmModule.HEAPU8.length > LARGE_HEAP_BYTES) { + // Async callers can give V8 a task to release the dropped heap before allocating again. + largeHeapYield ??= new Promise((resolve) => setTimeout(() => { + largeHeapYield = undefined; + resolve(); + }, 0)); + if (++largeFailures === 1) { + queueMicrotask(() => { + largeFailures = 0; + memoryLimitError = undefined; + }); + } else { + memoryLimitError = new Error( + 'WASM memory limit hit repeatedly in one synchronous run; yield (await) before retrying', + { cause: error } + ); + } + } + failures++; + wasmModule = undefined; +} + // An exception out of a WASM call (V8 stack overflow on deeply nested SQL, a // trap, or exit() once the heap limit is hit) skips libpg_query's cleanup and // leaves the instance corrupt, so replace it with a fresh one. @@ -202,19 +214,24 @@ function callWasm(fn: () => number): number { try { return fn(); } catch (error) { - failures++; - stale = true; - if (++staleFailures >= MAX_STALE_FAILURES) wasmModule = undefined; - instantiate(); if (proc) proc.exitCode = exitCode; - if (error instanceof Error) throw error; + if (error instanceof Error) { + invalidateModule(error); + throw error; + } const reason = typeof error === 'object' && error !== null ? ((error as any).message ?? (error as any).constructor?.name) : error; - throw new Error( + // Emscripten's ExitStatus keeps its loader closure and WASM heap alive. + const cause = typeof error === 'object' && error !== null && 'name' in error && error.name === 'ExitStatus' + ? { ...error } + : error; + const wrapped = new Error( `libpg_query terminated (${reason}), most likely out of WASM memory; parse large inputs in smaller pieces`, - { cause: error } + { cause } ); + invalidateModule(wrapped); + throw wrapped; } } @@ -222,20 +239,16 @@ function callWasm(fn: () => number): number { // keeps going, but the instance's heap stays grown to the size it reached (WASM // memory never shrinks), so load a fresh instance and let this one be freed. function outOfMemoryError(): Error { - stale = true; - instantiate(); - return new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); -} - -function throwIfErrorString(resultStr: string): void { - if (resultStr === 'out of memory') throw outOfMemoryError(); - if (resultStr.startsWith('syntax error') || resultStr.startsWith('deparse error') || resultStr.startsWith('ERROR') || resultStr.startsWith('stack depth limit exceeded')) { - throw new Error(resultStr); - } + const error = new Error('libpg_query ran out of WASM memory (heap limit is WASM_MAXIMUM_MEMORY, 1 GiB); parse large inputs in smaller pieces'); + invalidateModule(error); + return error; } function ensureLoaded() { - if (!wasmModule) throw new Error("WASM module not initialized. Call `loadModule()` first."); + if (wasmModule) return; + if (memoryLimitError) throw memoryLimitError; + if (!compiledWasm) throw new Error("WASM module not initialized. Call `loadModule()` first."); + wasmModule = createSync(compiledWasm); } type WasmCompiledModule = typeof globalThis extends { @@ -257,20 +270,22 @@ export interface LoadModuleOptions { export async function loadModule(...args: [options?: LoadModuleOptions]): Promise { const wasm = args[0]?.wasm; if (wasm !== undefined) { - provided = wasm instanceof WebAssembly.Module + const module = wasm instanceof WebAssembly.Module ? wasm : await WebAssembly.compile(wasm as ArrayBuffer | ArrayBufferView); // An instance loaded from the file, or still loading, is replaced by one from `wasm`. await loading?.catch(() => {}); - stale = true; + if (largeHeapYield) await largeHeapYield; + wasmModule = createSync(module); + compiledWasm = module; } - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); } function awaitInit Promise>(fn: T): T { return (async (...args: Parameters) => { // Re-checked after every await: another call may have failed in between. - while (!wasmModule || stale) await instantiate(); + while (!wasmModule) await instantiate(); return fn(...args); }) as T; } @@ -307,6 +322,49 @@ function ptrToString(ptr: number): string { return wasmModule.UTF8ToString(ptr); } +type DetailedOperation = '_wasm_fingerprint' | '_wasm_normalize_query' | '_wasm_scan'; + +function callDetailed(query: string, operation: DetailedOperation): string { + const queryPtr = stringToPtr(query); + const failuresBefore = failures; + let resultPtr = 0; + + try { + resultPtr = callWasm(() => wasmModule[operation](queryPtr)); + if (!resultPtr) throw outOfMemoryError(); + + // WasmDetailedResult uses 32-bit fields and pointers. + if (wasmModule.getValue(resultPtr, 'i32')) { + const readString = (offset: number) => { + const ptr = wasmModule.getValue(resultPtr + offset, 'i32'); + return ptr ? wasmModule.UTF8ToString(ptr) : undefined; + }; + const message = readString(4) ?? 'Unknown error'; + if (message === 'out of memory') throw outOfMemoryError(); + + const lineno = wasmModule.getValue(resultPtr + 16, 'i32'); + const cursorpos = wasmModule.getValue(resultPtr + 20, 'i32'); + const context = readString(24); + throw new SqlError(message, { + message, + cursorPosition: cursorpos > 0 ? cursorpos - 1 : 0, + fileName: readString(12), + functionName: readString(8), + lineNumber: lineno > 0 ? lineno : undefined, + ...(context !== undefined ? { context } : {}) + }); + } + return wasmModule.UTF8ToString(wasmModule.getValue(resultPtr + 28, 'i32')); + } finally { + if (failures === failuresBefore) { + wasmModule._free(queryPtr); + if (resultPtr) { + wasmModule._wasm_free_detailed_result(resultPtr); + } + } + } +} + export const parse = awaitInit(async (query: string): Promise => { // Input validation if (query === null || query === undefined) { @@ -397,54 +455,16 @@ export const parsePlPgSQL = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); }); export const normalize = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); }); // Sync versions export function parseSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } + ensureLoaded(); // Input validation if (query === null || query === undefined) { @@ -509,9 +529,6 @@ export function parseSync(query: string): ParseResult { } export function parsePlPgSQLSync(query: string): ParseResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } const queryPtr = stringToPtr(query); const failuresBefore = failures; let resultPtr = 0; @@ -538,98 +555,17 @@ export function parsePlPgSQLSync(query: string): ParseResult { } export function fingerprintSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_fingerprint(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_fingerprint'); } export function normalizeSync(query: string): string { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_normalize_query(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return resultStr; - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return callDetailed(query, '_wasm_normalize_query'); } export const scan = awaitInit(async (query: string): Promise => { - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } + return JSON.parse(callDetailed(query, '_wasm_scan')); }); export function scanSync(query: string): ScanResult { - if (!wasmModule) { - throw new Error('WASM module not initialized. Call loadModule() first.'); - } - const queryPtr = stringToPtr(query); - const failuresBefore = failures; - let resultPtr = 0; - - try { - resultPtr = callWasm(() => wasmModule._wasm_scan(queryPtr)); - const resultStr = ptrToString(resultPtr); - - throwIfErrorString(resultStr); - - return JSON.parse(resultStr); - } finally { - if (failures === failuresBefore) { - wasmModule._free(queryPtr); - if (resultPtr) { - wasmModule._wasm_free_string(resultPtr); - } - } - } -} \ No newline at end of file + return JSON.parse(callDetailed(query, '_wasm_scan')); +} diff --git a/versions/18/src/libpg-query.d.ts b/versions/18/src/libpg-query.d.ts index 152d8414..a556fa66 100644 --- a/versions/18/src/libpg-query.d.ts +++ b/versions/18/src/libpg-query.d.ts @@ -10,10 +10,12 @@ declare module './libpg-query.js' { _malloc: (size: number) => number; _free: (ptr: number) => void; _wasm_free_string: (ptr: number) => void; + _wasm_free_detailed_result: (ptr: number) => void; _wasm_parse_query: (queryPtr: number) => number; _wasm_parse_plpgsql: (queryPtr: number) => number; _wasm_fingerprint: (queryPtr: number) => number; _wasm_normalize_query: (queryPtr: number) => number; + _wasm_scan: (queryPtr: number) => number; lengthBytesUTF8: (str: string) => number; stringToUTF8: (str: string, ptr: number, len: number) => void; UTF8ToString: (ptr: number) => string; diff --git a/versions/18/src/pre.js b/versions/18/src/pre.js index c2ec5361..0ea6f2c2 100644 --- a/versions/18/src/pre.js +++ b/versions/18/src/pre.js @@ -12,3 +12,27 @@ // `loadModule({ wasm })` can use the bytes it was given. if (ENVIRONMENT_IS_NODE && typeof __dirname == 'undefined') ENVIRONMENT_IS_NODE = false; if (ENVIRONMENT_IS_WORKER && !globalThis.self?.location) ENVIRONMENT_IS_WORKER = false; + +// Keep the module from the pinned Emscripten factory's own asset load. +if (!Module['compiledWasm']) { + var instantiateFromAsset = instantiateAsync; + instantiateAsync = async (...args) => { + var result = await instantiateFromAsset(...args); + Module['compiledWasm'] = result.module; + return result; + }; +} else { + Module['instantiateWasm'] = (imports, receive) => { + try { + receive(new WebAssembly.Instance(Module['compiledWasm'], imports)); + // This build has no main or startup hooks. Initialize libc and stdio + // now, then skip the deferred run() so it cannot initialize them twice. + initRuntime(); + run = () => {}; + Module['readySync'] = true; + } catch (error) { + Module['initError'] = error; + throw error; + } + }; +} diff --git a/versions/18/src/wasm_wrapper.c b/versions/18/src/wasm_wrapper.c index 9bd1c24b..17c86e7c 100644 --- a/versions/18/src/wasm_wrapper.c +++ b/versions/18/src/wasm_wrapper.c @@ -111,53 +111,6 @@ char* wasm_parse_plpgsql(const char* input) { return wrapped_result; } -EMSCRIPTEN_KEEPALIVE -char* wasm_fingerprint(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryFingerprintResult result = pg_query_fingerprint(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_fingerprint_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* fingerprint_str = safe_strdup(result.fingerprint_str); - pg_query_free_fingerprint_result(result); - return fingerprint_str; -} - -EMSCRIPTEN_KEEPALIVE -char* wasm_normalize_query(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - - PgQueryNormalizeResult result = pg_query_normalize(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_normalize_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* normalized = safe_strdup(result.normalized_query); - pg_query_free_normalize_result(result); - - if (!normalized) { - return safe_strdup("Memory allocation failed"); - } - - return normalized; -} - - - - - typedef struct { int has_error; char* message; @@ -237,6 +190,65 @@ void wasm_free_detailed_result(WasmDetailedResult* result) { } } +// Takes ownership of data and copies any error before libpg_query frees it. +static WasmDetailedResult* make_detailed_result(char* data, const PgQueryError* error) { + if (!data && !error) return NULL; + + WasmDetailedResult* result = calloc(1, sizeof(WasmDetailedResult)); + if (!result) { + free(data); + return NULL; + } + + result->data = data; + if (error) { + result->has_error = 1; + result->message = safe_strdup(error->message); + result->funcname = safe_strdup(error->funcname); + result->filename = safe_strdup(error->filename); + result->lineno = error->lineno; + result->cursorpos = error->cursorpos; + result->context = safe_strdup(error->context); + if ((error->message && !result->message) || + (error->funcname && !result->funcname) || + (error->filename && !result->filename) || + (error->context && !result->context)) { + wasm_free_detailed_result(result); + return NULL; + } + } else { + result->data_len = strlen(data); + } + return result; +} + +static WasmDetailedResult* invalid_input_result(void) { + const PgQueryError error = { .message = "Invalid input: query cannot be null or empty" }; + return make_detailed_result(NULL, &error); +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_fingerprint(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryFingerprintResult result = pg_query_fingerprint(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.fingerprint_str), result.error); + pg_query_free_fingerprint_result(result); + return detailed; +} + +EMSCRIPTEN_KEEPALIVE +WasmDetailedResult* wasm_normalize_query(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + + PgQueryNormalizeResult result = pg_query_normalize(input); + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : safe_strdup(result.normalized_query), result.error); + pg_query_free_normalize_result(result); + return detailed; +} + static const char* get_token_name(PgQueryToken token_type) { // Map some common token types to readable names // Note: This is a simplified mapping - full enum lookup would require more complexity @@ -292,10 +304,6 @@ static size_t scan_json_escaped_length(const char* text, int length) { } static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const char* original_sql) { - if (!scan_result || !original_sql) { - return safe_strdup("{\"version\":0,\"tokens\":[]}"); - } - // Reserve space for each token's escaped text and fixed JSON fields. size_t estimated_size = 1024; for (int i = 0; i < scan_result->n_tokens; i++) { @@ -304,17 +312,17 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (token_length < 0) token_length = 0; size_t escaped_length = scan_json_escaped_length(&original_sql[token->start], token_length); if (escaped_length > SIZE_MAX - 200) { - return safe_strdup("out of memory"); + return NULL; } size_t token_size = escaped_length + 200; if (estimated_size > SIZE_MAX - token_size) { - return safe_strdup("out of memory"); + return NULL; } estimated_size += token_size; } char* json = safe_malloc(estimated_size); if (!json) { - return safe_strdup("out of memory"); + return NULL; } // Start building JSON @@ -330,7 +338,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c char* token_text = safe_malloc((size_t) token_length + 1); if (!token_text) { free(json); - return safe_strdup("out of memory"); + return NULL; } if (token_length > 0) { @@ -344,7 +352,7 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c if (!escaped_text) { free(token_text); free(json); - return safe_strdup("out of memory"); + return NULL; } size_t escaped_pos = 0; @@ -402,24 +410,14 @@ static char* build_scan_json(const PgQueryScanTokensResult *scan_result, const c } EMSCRIPTEN_KEEPALIVE -char* wasm_scan(const char* input) { - if (!validate_input(input)) { - return safe_strdup("Invalid input: query cannot be null or empty"); - } - +WasmDetailedResult* wasm_scan(const char* input) { + if (!validate_input(input)) return invalid_input_result(); + PgQueryScanTokensResult result = pg_query_scan_tokens(input); - - if (result.error) { - char* error_msg = safe_strdup(result.error->message); - pg_query_free_scan_tokens_result(result); - return error_msg ? error_msg : safe_strdup("Memory allocation failed"); - } - - char* json_result = build_scan_json(&result, input); - + WasmDetailedResult* detailed = make_detailed_result( + result.error ? NULL : build_scan_json(&result, input), result.error); pg_query_free_scan_tokens_result(result); - - return json_result ? json_result : safe_strdup("{\"version\":0,\"tokens\":[]}"); + return detailed; } EMSCRIPTEN_KEEPALIVE diff --git a/versions/18/test/load-module.test.js b/versions/18/test/load-module.test.js index 256afd07..9e37311f 100644 --- a/versions/18/test/load-module.test.js +++ b/versions/18/test/load-module.test.js @@ -73,17 +73,21 @@ describe('loadModule({ wasm }) when the wrapper cannot read libpg-query.wasm', { assert.deepEqual(result, { fromModule: 1, fromView: 2 }); }); - it('creates the replacement from the bytes after out-of-memory failures', () => { + it('recovers from supplied bytes and caps repeated OOMs until the caller yields', () => { const result = withoutWasmFile(` await lib.loadModule({ wasm: bytes }); const huge = 'SELECT 1;\\n'.repeat(5000000); const messages = []; - for (let i = 0; i < 3; i++) { + for (let i = 0; i < 2; i++) { try { lib.parseSync(huge); } catch (e) { messages.push(e.message); } } - return { messages, after: (await lib.parse('SELECT 1')).stmts.length }; + let capped; + try { lib.parseSync('SELECT 1'); } catch (e) { capped = e.message; } + return { messages, capped, after: (await lib.parse('SELECT 1')).stmts.length }; `); - assert.equal(result.messages.length, 3); + assert.equal(result.messages.length, 2); + for (const message of result.messages) assert.match(message, /out of WASM memory/); + assert.match(result.capped, /yield \(await\) before retrying/); assert.equal(result.after, 1); }); diff --git a/versions/18/test/pg18.test.js b/versions/18/test/pg18.test.js index ddcd446f..c8dd1dae 100644 --- a/versions/18/test/pg18.test.js +++ b/versions/18/test/pg18.test.js @@ -1,6 +1,9 @@ const { describe, it, before } = require("node:test"); const assert = require("node:assert"); -const { parse, parseSync, parsePlPgSQL, scan, loadModule } = require("../"); +const { + parse, parseSync, parsePlPgSQL, scan, scanSync, loadModule, SqlError, + fingerprint, fingerprintSync, normalize, normalizeSync +} = require("../"); describe("PostgreSQL 18 syntax", () => { before(async () => { @@ -67,3 +70,47 @@ describe("PostgreSQL 18 syntax", () => { assert.ok(texts.includes("NEW")); }); }); + +describe("PostgreSQL 18 structured SQL errors", () => { + before(async () => { + await loadModule(); + }); + + const lexerError = { + sql: "SELECT 'abc", + message: /unterminated quoted string/, + fileName: /scan\.l$/, + cursorPosition: 7 + }; + const grammarError = { + sql: "SELECT percentile_cont(p ORDER BY p) WITHIN GROUP (ORDER BY x) FROM t", + message: /cannot use multiple ORDER BY clauses with WITHIN GROUP/, + fileName: /gram\.y$/ + }; + + for (const [run, runSync, cases] of [ + [fingerprint, fingerprintSync, [lexerError, grammarError]], + [normalize, normalizeSync, [lexerError, grammarError]], + [scan, scanSync, [lexerError]] + ]) { + it(`${runSync.name} throws and its async counterpart rejects with SqlError`, async () => { + for (const { sql, message, fileName, cursorPosition } of cases) { + const checkError = (error) => { + assert.ok(error instanceof SqlError); + assert.match(error.message, message); + const details = error.sqlDetails; + assert.equal(details.message, error.message); + assert.match(details.fileName, fileName); + assert.ok(details.functionName); + assert.ok(details.lineNumber > 0); + if (cursorPosition !== undefined) { + assert.equal(details.cursorPosition, cursorPosition); + } + return true; + }; + assert.throws(() => runSync(sql), checkError); + await assert.rejects(run(sql), checkError); + } + }); + } +}); diff --git a/versions/18/test/wasm-recovery.test.js b/versions/18/test/wasm-recovery.test.js index 48462e16..b9cfb05a 100644 --- a/versions/18/test/wasm-recovery.test.js +++ b/versions/18/test/wasm-recovery.test.js @@ -22,9 +22,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(parseSync('SELECT 1').stmts.length, 1); }); - // libpg_query checks stack depth itself, so deeply nested SQL is a clean error - // and the instance is kept. The 10-failure cap on a stale instance is covered - // by the injected throws in 'Recovery from a throw in each entry point'. + // PG 18 reports deep nesting as a regular SQL error rather than a WASM trap. it('returns a stack depth error for deeply nested SQL and keeps the instance', async () => { await loadModule(); for (let i = 0; i < 60; i++) { @@ -33,7 +31,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(parseSync('SELECT 1').stmts.length, 1); }); - it('frees each replaced instance, so WASM memory stays at one instance', () => { + it('frees replaced WASM heaps even when callers keep the errors', () => { const script = `const lib = require(${JSON.stringify(require.resolve('../wasm/index.cjs'))}); (async () => { await lib.loadModule(); @@ -46,14 +44,20 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await lib.loadModule(); } const huge = 'SELECT 1;\\n'.repeat(5000000); - for (let i = 0; i < 2; i++) { - try { await lib.parse(huge); } catch {} - } + let yielded = false; + setTimeout(() => { yielded = true; }, 0); + const errors = []; + try { await lib.parse(huge); } catch (error) { errors.push(error); } await lib.loadModule(); + if (!yielded) throw new Error('Async recovery did not yield after a large heap failure'); + try { lib.normalizeSync(huge); } catch (error) { errors.push(error); } lib.parseSync('SELECT 1'); // V8 frees a dropped instance's memory on a later task, not in the same microtask run. await new Promise((resolve) => setTimeout(resolve, 0)); gc(); gc(); + if (errors.length !== 2 || errors.some((error) => !error.message.includes('out of WASM memory'))) { + throw new Error('Expected two WASM memory failures'); + } process.stdout.write('\\ngrown=' + (process.memoryUsage().external - base)); })();`; // A non-zero exit code (libpg_query's exit() leaking out) makes execFileSync throw. @@ -63,7 +67,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { stdio: ['ignore', 'pipe', 'ignore'], }); const grown = Number(output.match(/^grown=(-?\d+)$/m)?.[1]); - assert.ok(grown < 32 * 1024 * 1024, `WASM memory grew by ${grown} bytes after 32 replacements`); + assert.ok(grown < 32 * 1024 * 1024, `WASM memory grew by ${grown} bytes after recovery`); }); it('lets a call queued behind a failing one wait for the fresh instance', async () => { @@ -77,15 +81,31 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.equal(queued.value.stmts.length, 1); }); - it('throws an Error and keeps process.exitCode when the memory limit is hit', async () => { + it('waits for a large heap when sync parsing fails after async recovery is queued', async () => { + const isolated = loadTrapping(); + await isolated.loadModule(); + isolated.trapNext(); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + const queued = isolated.parse('SELECT 1'); + + let yielded = false; + setTimeout(() => { yielded = true; }, 0); + isolated.trapNext(1024 ** 3); + assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + + assert.equal((await queued).stmts.length, 1); + assert.equal(yielded, true, 'async recovery skipped the large-heap yield'); + }); + + it('throws an Error and recovers synchronously when the memory limit is hit', () => { const exitCode = process.exitCode; - await assert.rejects(parse('SELECT 1;\n'.repeat(5000000)), (error) => { + assert.throws(() => parseSync('SELECT 1;\n'.repeat(5000000)), (error) => { assert.ok(error instanceof Error); assert.match(error.message, /out of WASM memory/); return true; }); assert.equal(process.exitCode, exitCode); - assert.equal((await parse('SELECT 1')).stmts.length, 1); + assert.equal(parseSync('SELECT 1').stmts.length, 1); }); for (const name of ['parsePlPgSQL', 'fingerprint', 'normalize', 'scan']) { @@ -107,7 +127,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await isolated.loadModule(); isolated.trapNext(); await assert.rejects(isolated.parse('SELECT 1'), RangeError); - await new Promise((resolve) => setImmediate(resolve)); + await assert.rejects(isolated.parse('SELECT 1'), /Could not start a fresh WASM instance/); assert.equal((await isolated.parse('SELECT 1')).stmts.length, 1); assert.equal(loads, 3); }); @@ -118,7 +138,7 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { await isolated.loadModule(); isolated.trapNext(); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - await assert.rejects(isolated.loadModule(), /simulated load failure/); + await assert.rejects(isolated.loadModule(), (error) => error.cause?.message === 'simulated load failure'); await isolated.loadModule(); assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); assert.equal(loads, 3); @@ -139,19 +159,16 @@ describe('Recovery after the WASM parser throws', { timeout: 120000 }, () => { assert.deepEqual(results, expected); }); - it('retries a failed fresh load on the next failure, for callers that never await', async () => { + it('retries a failed fresh load on the next sync call without awaiting', async () => { let loads = 0; const isolated = loadTrapping(() => ++loads === 2); await isolated.loadModule(); isolated.trapNext(); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - await new Promise((resolve) => setImmediate(resolve)); + assert.throws(() => isolated.parseSync('SELECT 1'), (error) => error.cause?.message === 'simulated load failure'); assert.equal(loads, 2); - isolated.trapNext(); - assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - assert.equal(loads, 3); - await isolated.loadModule(); assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); + assert.equal(loads, 3); }); it('makes loadModule() wait again when a queued call breaks the fresh instance', async () => { @@ -196,9 +213,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => let used; let frees = 0; let throwNext; - const isolated = loadIsolated(async (real, ...args) => { + const isolated = loadIsolated((module) => { const id = ++loads; - const module = await real(...args); const free = module._free; module._free = (ptr) => { frees++; @@ -215,7 +231,6 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => throw thrown; }; } - return module; }); async function failOnce(name, query, thrown) { @@ -227,7 +242,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => throwNext = thrown; let caught; try { - await isolated[name](query); + if (name.endsWith('Sync')) isolated[name](query); + else await isolated[name](query); } catch (error) { caught = error; } finally { @@ -236,45 +252,28 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => } assert.equal(exitCodeAfter, 0, `${name} changed process.exitCode`); assert.equal(frees, freesBefore, `${name} freed memory in the instance that threw`); - assert.equal(loads, loadsBefore + 1, `${name} did not start a fresh instance`); const stale = used; const syncName = name.endsWith('Sync') ? name : 'parseSync'; - assert.ok(isolated[syncName](query), `${syncName} failed while the fresh instance loads`); - assert.equal(used, stale, 'a sync call did not run on the stale instance'); + assert.ok(isolated[syncName](query), `${syncName} failed immediately after a trap`); + assert.notEqual(used, stale, 'a sync call ran on the failed instance'); + assert.equal(loads, loadsBefore + 1, 'expected exactly one replacement'); assert.ok(frees > freesBefore, 'a successful call did not free its memory'); - // A sync caller gets the fresh instance once it awaits loadModule(); async calls wait by themselves. - if (name.endsWith('Sync')) await isolated.loadModule(); assert.ok(await isolated[name](query), `${name} failed after recovery`); assert.equal(used, loads, `${name} ran on the stale instance, not the fresh one`); return caught; } - it('starts one fresh instance for many failures in one synchronous loop', async () => { + it('replaces each failed instance in one synchronous loop', async () => { await isolated.loadModule(); const loadsBefore = loads; - for (let i = 0; i < 5; i++) { - throwNext = new RangeError('Maximum call stack size exceeded'); - assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - } - assert.equal(loads, loadsBefore + 1); - await isolated.loadModule(); - assert.ok(isolated.parseSync('SELECT 1')); - assert.equal(used, loads); - }); - - it('stops sync calls on a stale instance after 10 failures until the fresh one loads', async () => { - await isolated.loadModule(); - for (let i = 0; i < 9; i++) { + for (let i = 0; i < 60; i++) { throwNext = new RangeError('Maximum call stack size exceeded'); assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); + const failed = used; + assert.equal(isolated.parseSync('SELECT 1').stmts.length, 1); + assert.notEqual(used, failed); } - assert.ok(isolated.parseSync('SELECT 1')); - throwNext = new RangeError('Maximum call stack size exceeded'); - assert.throws(() => isolated.parseSync('SELECT 1'), RangeError); - assert.throws(() => isolated.parseSync('SELECT 1'), /Call `?loadModule\(\)`? first/); - await isolated.loadModule(); - assert.ok(isolated.parseSync('SELECT 1')); - assert.equal(used, loads); + assert.equal(loads, loadsBefore + 60); }); it('makes loadModule() and queued calls wait again when a queued call breaks the fresh instance', async () => { @@ -312,6 +311,19 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => assert.match(caught.message, /libpg_query terminated \(EmscriptenSjLj\)/); }); + for (const name of ['fingerprintSync', 'normalizeSync', 'scanSync']) { + it(`${name}: throws SqlError on a fresh instance without discarding it`, async () => { + await isolated.loadModule(); + const loadsBefore = loads; + throwNext = new RangeError('WASM trap'); + assert.throws(() => isolated[name]('SELECT 1'), RangeError); + assert.throws(() => isolated[name]("SELECT 'abc"), isolated.SqlError); + assert.equal(used, loadsBefore + 1); + assert.ok(isolated[name]('SELECT 1')); + assert.equal(loads, loadsBefore + 1); + }); + } + for (const [name, query] of entryPoints) { const skip = typeof isolated[name] !== 'function' && 'not in this build'; @@ -325,7 +337,8 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => const caught = await failOnce(name, query, thrown); assert.ok(caught instanceof Error); assert.match(caught.message, /out of WASM memory/); - assert.equal(caught.cause, thrown); + assert.notEqual(caught.cause, thrown); + assert.deepEqual(caught.cause, thrown); }); } }); @@ -334,29 +347,41 @@ describe('Recovery from a throw in each entry point', { timeout: 120000 }, () => // for a WASM trap now that libpg_query returns stack depth errors instead. // failLoad() is called on each load; a true result rejects that load. function loadTrapping(failLoad) { - let trap = false; - const isolated = loadIsolated(async (real, ...args) => { - if (failLoad()) throw new Error('simulated load failure'); - const module = await real(...args); + let trapHeapSize; + const isolated = loadIsolated((module) => { const parseRaw = module._wasm_parse_query_raw; module._wasm_parse_query_raw = (...callArgs) => { - if (!trap) return parseRaw(...callArgs); - trap = false; + if (trapHeapSize === undefined) return parseRaw(...callArgs); + if (trapHeapSize) module.HEAPU8 = { length: trapHeapSize }; + trapHeapSize = undefined; throw new RangeError('Maximum call stack size exceeded'); }; - return module; - }); - isolated.trapNext = () => { trap = true; }; + }, failLoad); + isolated.trapNext = (heapSize = 0) => { trapHeapSize = heapSize; }; return isolated; } // A copy of the wrapper whose WASM factory is wrapped, leaving the shared copy alone. -function loadIsolated(wrapFactory) { +function loadIsolated(decorate, failLoad = () => false) { const indexPath = require.resolve('../wasm/index.cjs'); const factory = require.cache[require.resolve('../wasm/libpg-query.js')]; const shared = require.cache[indexPath]; const realFactory = factory.exports; - factory.exports = (...args) => wrapFactory(realFactory, ...args); + factory.exports = (options = {}) => { + if (failLoad()) { + options.initError = new Error('simulated load failure'); + return Promise.reject(options.initError); + } + const loading = realFactory(options); + if (options.readySync) { + decorate(options); + return loading; + } + return loading.then((module) => { + decorate(module); + return module; + }); + }; delete require.cache[indexPath]; try { return require(indexPath);