From 485f464f13808d065ffb4fbab29b604913d98959 Mon Sep 17 00:00:00 2001 From: thecodrr Date: Thu, 18 Nov 2021 19:40:59 +0500 Subject: [PATCH] feat: acquire lock using syncMutex --- packages/core/api/sync/index.js | 15 ++------------- packages/core/database/backup.js | 7 ++----- 2 files changed, 4 insertions(+), 18 deletions(-) diff --git a/packages/core/api/sync/index.js b/packages/core/api/sync/index.js index 32969a42a..246f39722 100644 --- a/packages/core/api/sync/index.js +++ b/packages/core/api/sync/index.js @@ -52,7 +52,6 @@ export default class Sync { this._tokenManager = new TokenManager(this._db.storage); this._autoSyncTimeout = 0; this._autoSyncInterval = 5000; - this._locked = false; this.syncMutex = withTimeout( new Mutex(), @@ -100,23 +99,13 @@ export default class Sync { if (this.databaseUpdatedEvent) this.databaseUpdatedEvent.unsubscribe(); } - acquireLock() { + async acquireLock(callback) { this.stopAutoSync(); - this._locked = true; - } - - async releaseLock() { - this._locked = false; + await this.syncMutex.runExclusive(callback); await this.startAutoSync(); } - isLocked() { - return this._locked; - } - async _sync(full, force) { - if (this.isLocked()) return false; - let { lastSynced } = await this._performChecks(); if (force) lastSynced = 0; diff --git a/packages/core/database/backup.js b/packages/core/database/backup.js index 797c363e8..2bcbaa483 100644 --- a/packages/core/database/backup.js +++ b/packages/core/database/backup.js @@ -140,17 +140,14 @@ export default class Backup { }, ]; - try { - this._db.syncer.acquireLock(); + await this._db.syncer.acquireLock(async () => { if ( await this._migrator.migrate(collections, (id) => data[id], version) ) { await this._db.notes.repairReferences(); await this._db.notebooks.repairReferences(); } - } finally { - await this._db.syncer.releaseLock(); - } + }); } _validate(backup) {