From dc026c44a1ad5fac194a5a79add5c6cb5d4ee678 Mon Sep 17 00:00:00 2001 From: Zhihe Li Date: Fri, 29 Aug 2025 15:30:07 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Handle=20corrupted=20sql?= =?UTF-8?q?ite=20DB=20(#2976)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: 🎸 Handle corrupted sqlite DB --- addons/api/addon/handlers/sqlite-handler.js | 4 ++-- addons/api/addon/workers/sqlite-worker.js | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/addons/api/addon/handlers/sqlite-handler.js b/addons/api/addon/handlers/sqlite-handler.js index 1456076ad..c7f87ec6b 100644 --- a/addons/api/addon/handlers/sqlite-handler.js +++ b/addons/api/addon/handlers/sqlite-handler.js @@ -182,8 +182,8 @@ export default class SqliteHandler { // If we get an invalid list token, we'll delete the token and // clear the DB and try again without a token. if ( - err?.errors[0].status === 400 && - err?.errors[0].code === 'invalid list token' + err?.errors?.[0].status === 400 && + err?.errors?.[0].code === 'invalid list token' ) { await this.sqlite.deleteResource(type); // Delete all tokens of the same resource type so we don't keep clearing the DB. diff --git a/addons/api/addon/workers/sqlite-worker.js b/addons/api/addon/workers/sqlite-worker.js index fd7ad8b3a..7b603853b 100644 --- a/addons/api/addon/workers/sqlite-worker.js +++ b/addons/api/addon/workers/sqlite-worker.js @@ -27,6 +27,10 @@ const MAX_HOST_PARAMETERS = 32766; const SCHEMA_VERSION = 1; const isSecure = self.isSecureContext; +// Error code for sqlite corruption errors. +// See https://sqlite.org/rescode.html#corrupt +const SQLITE_CORRUPT = 11; + const methods = { initializeSQLite: async () => { sqlite3 = await sqlite3InitModule({ @@ -65,7 +69,7 @@ const methods = { setupDb(); done = true; - } catch (err) { + } catch (/** @type {import('@sqlite.org/sqlite-wasm').SQLite3Error} */ err) { // If we get a SQLite3Error and the pool is at capacity, we'll assume the error is // because we hit the cap so we add more capacity and see if that solves it. if ( @@ -81,7 +85,13 @@ const methods = { } } else { console.error('SQLite initialization error:', err); - throw err; + + // We might have gotten ourselves into a bad state which corrupted the DB so clear it out and retry + if (err?.resultCode === SQLITE_CORRUPT) { + poolUtil.unlink(`/${dbName}`); + } else { + throw err; + } } } }