From c31cf63108f396451cb720110f4faf040bc7e905 Mon Sep 17 00:00:00 2001 From: texuf Date: Mon, 20 Mar 2023 14:29:24 -0700 Subject: [PATCH] indexddb-local-backend - return the current sync to database promise if a sync is in flight MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit I’m trying to shutdown my matrix clients while using an indexdb, but awaiting the save() function has no effect because a previous sync was in flight. I ended up deleting the matrix client while the save was in flight and I saw a crash. signed-off-by Austin Ellis fix linter --- src/store/indexeddb-local-backend.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/store/indexeddb-local-backend.ts b/src/store/indexeddb-local-backend.ts index 7e84ad621a5..c754fe73423 100644 --- a/src/store/indexeddb-local-backend.ts +++ b/src/store/indexeddb-local-backend.ts @@ -130,7 +130,7 @@ export class LocalIndexedDBStoreBackend implements IIndexedDBBackend { private db?: IDBDatabase; private disconnected = true; private _isNewlyCreated = false; - private isPersisting = false; + private syncToDatabasePromise?: Promise; private pendingUserPresenceData: UserTuple[] = []; /** @@ -388,26 +388,34 @@ export class LocalIndexedDBStoreBackend implements IIndexedDBBackend { }); } + /** + * Sync users and all accumulated sync data to the database. + * If a previous sync is in flight, the new data will be added to the + * next sync and the current sync's promise will be returned. + * @param userTuples - The user tuples + * @returns Promise which resolves if the data was persisted. + */ public async syncToDatabase(userTuples: UserTuple[]): Promise { - if (this.isPersisting) { + if (this.syncToDatabasePromise) { logger.warn("Skipping syncToDatabase() as persist already in flight"); this.pendingUserPresenceData.push(...userTuples); - return; - } else { - userTuples.unshift(...this.pendingUserPresenceData); - this.isPersisting = true; - } + return this.syncToDatabasePromise; + } + userTuples.unshift(...this.pendingUserPresenceData); + this.syncToDatabasePromise = this.doSyncToDatabase(userTuples); + return this.syncToDatabasePromise; + } + private async doSyncToDatabase(userTuples: UserTuple[]): Promise { try { const syncData = this.syncAccumulator.getJSON(true); - await Promise.all([ this.persistUserPresenceEvents(userTuples), this.persistAccountData(syncData.accountData), this.persistSyncData(syncData.nextBatch, syncData.roomsData), ]); } finally { - this.isPersisting = false; + this.syncToDatabasePromise = undefined; } }