function createBackgroundSyncCoordinator({ readAccountStore, syncAccountMailboxes, backgroundSyncGenerations, backgroundSyncFailures, lastBackgroundSyncAt, flagSnapshots, reconcileIdleWatchers, sendMailSyncUpdate, showNewMailNotification, concurrency = 2, retryIntervalMs = 2 * 60 * 1000, now = Date.now, logError = (...args) => console.error(...args) }) { let backgroundSyncInProgress = false; let backgroundSyncRequested = false; async function syncAccountWithBackoff(account, periodicOnly = false) { if (periodicOnly) { const intervalMs = (Number(account.syncIntervalMinutes) || 2) * 60 * 1000; if (now() - (lastBackgroundSyncAt.get(account.id) || 0) < intervalMs) return; } const failure = backgroundSyncFailures.get(account.id); if (failure && now() < failure.retryAt) return; lastBackgroundSyncAt.set(account.id, now()); const generation = backgroundSyncGenerations.get(account.id) || 0; try { const result = await syncAccountMailboxes(account); if (backgroundSyncGenerations.get(account.id) !== generation) return; backgroundSyncFailures.delete(account.id); if (result.newCount || result.changedFolders.length) { const update = { accountId: account.id, newCount: result.newCount, foldersChanged: result.changedFolders }; sendMailSyncUpdate(update); showNewMailNotification(account, result.newCount); } } catch (error) { const attempts = (failure?.attempts || 0) + 1; const retryDelay = Math.min(30 * 60 * 1000, retryIntervalMs * (2 ** Math.min(attempts - 1, 4))); backgroundSyncFailures.set(account.id, { attempts, retryAt: now() + retryDelay }); logError(`Background mail sync failed for ${account.email}:`, error); if (!failure) sendMailSyncUpdate({ accountId: account.id, error: 'Background mail sync failed. Will retry automatically.' }); } } async function runBackgroundSync(periodicOnly = false) { if (backgroundSyncInProgress) { if (!periodicOnly) backgroundSyncRequested = true; return; } backgroundSyncInProgress = true; let onlyDueAccounts = periodicOnly; try { do { backgroundSyncRequested = false; const store = (await readAccountStore()) || { accounts: [] }; for (let index = 0; index < store.accounts.length; index += concurrency) { await Promise.all(store.accounts.slice(index, index + concurrency) .map(account => syncAccountWithBackoff(account, onlyDueAccounts))); } if (backgroundSyncRequested) onlyDueAccounts = false; } while (backgroundSyncRequested); } finally { backgroundSyncInProgress = false; if (backgroundSyncRequested) void runBackgroundSync().catch(error => logError('Background mail sync failed:', error)); } } function requestBackgroundSync(accountId = null, force = false) { if (accountId) { backgroundSyncGenerations.set(accountId, (backgroundSyncGenerations.get(accountId) || 0) + 1); backgroundSyncFailures.delete(accountId); flagSnapshots.delete(accountId); } if (force) { for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0; } void reconcileIdleWatchers().catch(error => logError('Could not reconcile IMAP IDLE watchers:', error)); if (backgroundSyncInProgress) { if (accountId || force) backgroundSyncRequested = true; return; } backgroundSyncRequested = true; void runBackgroundSync().catch(error => logError('Background mail sync failed:', error)); } return { requestBackgroundSync, runBackgroundSync, syncAccountWithBackoff }; } module.exports = { createBackgroundSyncCoordinator };