diff --git a/web/database/utils/constants.js b/web/database/utils/constants.js --- a/web/database/utils/constants.js +++ b/web/database/utils/constants.js @@ -5,8 +5,6 @@ export const CURRENT_USER_ID_KEY = 'current_user_id'; -export const DB_PERSIST_THROTTLE_WAIT_MS = 300; - export const DATABASE_WORKER_PATH = '/worker/database'; export const SQLJS_FILE_PATH = '/compiled/webworkers'; diff --git a/web/database/worker/db-worker.js b/web/database/worker/db-worker.js --- a/web/database/worker/db-worker.js +++ b/web/database/worker/db-worker.js @@ -1,7 +1,6 @@ // @flow import localforage from 'localforage'; -import _throttle from 'lodash/throttle.js'; import initSqlJs, { type SqliteDatabase } from 'sql.js'; import type { @@ -34,7 +33,6 @@ } from '../queries/storage-engine-queries.js'; import { CURRENT_USER_ID_KEY, - DB_PERSIST_THROTTLE_WAIT_MS, SQLITE_CONTENT, SQLITE_ENCRYPTION_KEY, } from '../utils/constants.js'; @@ -56,6 +54,9 @@ let sqliteDb: ?SqliteDatabase = null; let encryptionKey: ?CryptoKey = null; +let persistNeeded: boolean = false; +let persistInProgress: boolean = false; + async function initDatabase(sqljsFilePath: string, sqljsFilename: ?string) { encryptionKey = await localforage.getItem(SQLITE_ENCRYPTION_KEY); if (!encryptionKey) { @@ -134,6 +135,7 @@ } async function persist() { + persistInProgress = true; if (!sqliteDb) { throw new Error('Database not initialized'); } @@ -142,16 +144,23 @@ encryptionKey = await localforage.getItem(SQLITE_ENCRYPTION_KEY); } - const dbData = sqliteDb.export(); - if (!encryptionKey) { - throw new Error('Encryption key is missing'); + while (true) { + const dbData = sqliteDb.export(); + if (!encryptionKey) { + throw new Error('Encryption key is missing'); + } + const encryptedData = await encryptDatabaseFile(dbData, encryptionKey); + await localforage.setItem(SQLITE_CONTENT, encryptedData); + + if (persistNeeded) { + persistNeeded = false; + } else { + persistInProgress = false; + break; + } } - const encryptedData = await encryptDatabaseFile(dbData, encryptionKey); - await localforage.setItem(SQLITE_CONTENT, encryptedData); } -const throttledPersist = _throttle(persist, DB_PERSIST_THROTTLE_WAIT_MS); - async function processAppRequest( message: WorkerRequestMessage, ): Promise { @@ -228,7 +237,14 @@ removePersistStorageItem(sqliteDb, message.key); } - throttledPersist(); + if (persistInProgress) { + // persist process is running, it will need to be scheduled again + persistNeeded = true; + } else { + // persist process is not running, scheduling for the first time + persist(); + } + return undefined; }