From 92770bde273bdf91479a92f4bd9f62c65e916654 Mon Sep 17 00:00:00 2001 From: jheer Date: Tue, 30 Jan 2024 15:54:30 -0800 Subject: [PATCH] feat: Avoid race condition in wasm loader. --- packages/core/src/connectors/wasm.js | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/packages/core/src/connectors/wasm.js b/packages/core/src/connectors/wasm.js index 52071e6c..b325fcc4 100644 --- a/packages/core/src/connectors/wasm.js +++ b/packages/core/src/connectors/wasm.js @@ -4,16 +4,28 @@ export function wasmConnector(options = {}) { const { duckdb, connection, ...opts } = options; let db = duckdb; let con = connection; + let loadPromise; + + function load() { + if (!loadPromise) { + // use a loading promise to avoid race conditions + // synchronizes multiple callees on the same load + loadPromise = (db + ? Promise.resolve(db) + : initDatabase(opts).then(result => db = result)) + .then(db => db.connect()) + .then(result => con = result); + } + return loadPromise; + } async function getDuckDB() { - if (!db) db = await initDatabase(opts); + if (!db) await load(); return db; } async function getConnection() { - if (!con) { - con = await (await getDuckDB()).connect(); - } + if (!con) await load(); return con; }