2016-11-29 09:33:14 +08:00
|
|
|
import _ from 'underscore';
|
2016-12-02 01:04:37 +08:00
|
|
|
import {AccountStore, Actions} from 'nylas-exports'
|
2016-11-29 09:33:14 +08:00
|
|
|
import NylasSyncWorker from './nylas-sync-worker';
|
|
|
|
|
|
|
|
export default class NylasSyncWorkerPool {
|
|
|
|
constructor() {
|
|
|
|
this._workers = [];
|
2016-12-01 06:55:09 +08:00
|
|
|
AccountStore.listen(this._determineWorkerPool, this);
|
|
|
|
this._determineWorkerPool();
|
2016-12-02 01:04:37 +08:00
|
|
|
Actions.refreshAllSyncWorkers.listen(this._refreshAllWorkers, this)
|
|
|
|
}
|
|
|
|
|
|
|
|
_refreshAllWorkers() {
|
|
|
|
for (const worker of this._workers) {
|
|
|
|
worker.refresh()
|
|
|
|
}
|
2016-11-29 09:33:14 +08:00
|
|
|
}
|
|
|
|
|
2016-12-01 06:55:09 +08:00
|
|
|
_existingWorkerForAccount(account) {
|
|
|
|
return _.find(this._workers, c => c.account().id === account.id);
|
2016-11-29 09:33:14 +08:00
|
|
|
}
|
|
|
|
|
2016-12-01 06:55:09 +08:00
|
|
|
_determineWorkerPool() {
|
2016-12-23 04:42:45 +08:00
|
|
|
// we need a function lock on this because on bootup, many legitimate
|
|
|
|
// events coming in may result in this function being called multiple times
|
|
|
|
// in quick succession, which can cause us to start multiple syncs for the
|
|
|
|
// same account
|
|
|
|
if (this._isBuildingWorkers) return;
|
|
|
|
this._isBuildingWorkers = true;
|
2016-12-01 06:55:09 +08:00
|
|
|
if (NylasEnv.inSpecMode()) { return; }
|
|
|
|
const origWorkers = this._workers;
|
|
|
|
const currentWorkers = []
|
|
|
|
Promise.each(AccountStore.accounts(), (account) => {
|
|
|
|
const existingWorker = this._existingWorkerForAccount(account)
|
|
|
|
if (existingWorker) {
|
|
|
|
currentWorkers.push(existingWorker);
|
|
|
|
return Promise.resolve()
|
|
|
|
}
|
|
|
|
|
|
|
|
const newWorker = new NylasSyncWorker(account);
|
|
|
|
return newWorker.loadStateFromDatabase().then(() => {
|
|
|
|
newWorker.start()
|
|
|
|
currentWorkers.push(newWorker);
|
|
|
|
})
|
|
|
|
}).then(() => {
|
|
|
|
const oldWorkers = _.difference(origWorkers, currentWorkers);
|
|
|
|
for (const worker of oldWorkers) { worker.cleanup() }
|
|
|
|
this._workers = currentWorkers;
|
2016-12-23 04:42:45 +08:00
|
|
|
}).finally(() => {
|
|
|
|
this._isBuildingWorkers = false;
|
2016-12-01 06:55:09 +08:00
|
|
|
})
|
2016-11-29 09:33:14 +08:00
|
|
|
}
|
|
|
|
}
|