Add persistent IMAP IDLE watchers
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
+96
-2
@@ -12,12 +12,14 @@ const credentialsPath = () => path.join(app.getPath('userData'), 'mail-account.e
|
||||
const davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
||||
const backgroundSyncConcurrency = 2;
|
||||
const backgroundIdleConcurrency = 2;
|
||||
let accountStoreQueue = Promise.resolve();
|
||||
let backgroundSyncInProgress = false;
|
||||
let backgroundSyncRequested = false;
|
||||
const backgroundSyncGenerations = new Map();
|
||||
const backgroundSyncFailures = new Map();
|
||||
const flagSnapshots = new Map();
|
||||
const idleWatchers = new Map();
|
||||
|
||||
function updateAccountStore(update) {
|
||||
const operation = accountStoreQueue.then(async () => {
|
||||
@@ -48,6 +50,7 @@ function requestBackgroundSync(accountId = null, force = false) {
|
||||
if (force) {
|
||||
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
|
||||
}
|
||||
void reconcileIdleWatchers().catch(error => console.error('Could not reconcile IMAP IDLE watchers:', error));
|
||||
if (backgroundSyncInProgress) {
|
||||
if (accountId || force) backgroundSyncRequested = true;
|
||||
return;
|
||||
@@ -56,6 +59,89 @@ function requestBackgroundSync(accountId = null, force = false) {
|
||||
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
|
||||
}
|
||||
|
||||
function stopIdleWatcher(accountId) {
|
||||
const watcher = idleWatchers.get(accountId);
|
||||
if (!watcher) return;
|
||||
watcher.stopped = true;
|
||||
watcher.client?.close();
|
||||
idleWatchers.delete(accountId);
|
||||
}
|
||||
|
||||
function startIdleWatcher(account) {
|
||||
if (idleWatchers.has(account.id)) return;
|
||||
const watcher = {
|
||||
generation: backgroundSyncGenerations.get(account.id) || 0,
|
||||
stopped: false,
|
||||
client: null
|
||||
};
|
||||
idleWatchers.set(account.id, watcher);
|
||||
void runIdleWatcher(account.id, watcher).catch(error => {
|
||||
console.error(`IMAP IDLE watcher failed for ${account.email}:`, error);
|
||||
});
|
||||
}
|
||||
|
||||
async function runIdleWatcher(accountId, watcher) {
|
||||
let failures = 0;
|
||||
while (!watcher.stopped && backgroundSyncGenerations.get(accountId) === watcher.generation) {
|
||||
let client;
|
||||
try {
|
||||
const account = await readAccount(accountId);
|
||||
if (!account || watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||
client = imapClient(account, {
|
||||
autoIdleDelay: 10_000,
|
||||
maxIdleTime: 25 * 60 * 1000,
|
||||
socketTimeout: 30 * 60 * 1000
|
||||
});
|
||||
watcher.client = client;
|
||||
let signalDisconnected;
|
||||
const disconnected = new Promise(resolve => { signalDisconnected = resolve; });
|
||||
client.on('exists', event => {
|
||||
if (event.path.toLowerCase() === 'inbox' && event.count > event.prevCount) requestBackgroundSync();
|
||||
});
|
||||
client.on('flags', event => {
|
||||
if (event.path.toLowerCase() === 'inbox') requestBackgroundSync();
|
||||
});
|
||||
client.on('error', error => {
|
||||
if (!watcher.stopped) console.error(`IMAP IDLE connection failed for ${account.email}:`, error);
|
||||
signalDisconnected();
|
||||
});
|
||||
client.once('close', signalDisconnected);
|
||||
await client.connect();
|
||||
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||
await client.mailboxOpen('INBOX', { readOnly: true });
|
||||
const connectedAt = Date.now();
|
||||
await disconnected;
|
||||
if (Date.now() - connectedAt > 60_000) failures = 0;
|
||||
} catch (error) {
|
||||
if (!watcher.stopped) console.error(`IMAP IDLE watcher disconnected for ${accountId}:`, error);
|
||||
} finally {
|
||||
if (watcher.client === client) watcher.client = null;
|
||||
if (client?.usable) await client.logout().catch(() => client.close());
|
||||
else client?.close();
|
||||
}
|
||||
|
||||
if (watcher.stopped || backgroundSyncGenerations.get(accountId) !== watcher.generation) return;
|
||||
const retryDelay = Math.min(5 * 60 * 1000, 15_000 * (2 ** Math.min(failures, 5)));
|
||||
failures += 1;
|
||||
await new Promise(resolve => {
|
||||
const timer = setTimeout(resolve, retryDelay);
|
||||
timer.unref();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function reconcileIdleWatchers() {
|
||||
const store = (await readAccountStore()) || { accounts: [] };
|
||||
const desiredAccounts = store.accounts.slice(0, backgroundIdleConcurrency);
|
||||
const desiredIds = new Set(desiredAccounts.map(account => account.id));
|
||||
for (const [accountId, watcher] of idleWatchers) {
|
||||
if (!desiredIds.has(accountId) || watcher.generation !== (backgroundSyncGenerations.get(accountId) || 0)) {
|
||||
stopIdleWatcher(accountId);
|
||||
}
|
||||
}
|
||||
for (const account of desiredAccounts) startIdleWatcher(account);
|
||||
}
|
||||
|
||||
async function readDavStore() {
|
||||
try {
|
||||
const encrypted = await fs.readFile(davCredentialsPath());
|
||||
@@ -118,7 +204,7 @@ function normalizeAccount(input) {
|
||||
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
||||
}
|
||||
|
||||
function imapClient(account) {
|
||||
function imapClient(account, options = {}) {
|
||||
return new ImapFlow({
|
||||
host: account.imapHost,
|
||||
port: account.imapPort,
|
||||
@@ -129,7 +215,8 @@ function imapClient(account) {
|
||||
logger: false,
|
||||
connectionTimeout: 15000,
|
||||
greetingTimeout: 10000,
|
||||
socketTimeout: 20000
|
||||
socketTimeout: 20000,
|
||||
...options
|
||||
});
|
||||
}
|
||||
|
||||
@@ -848,6 +935,9 @@ app.whenReady().then(() => {
|
||||
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
||||
syncTimer.unref();
|
||||
requestBackgroundSync();
|
||||
powerMonitor.on('suspend', () => {
|
||||
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||
});
|
||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||
app.on('activate', () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||
@@ -857,3 +947,7 @@ app.whenReady().then(() => {
|
||||
app.on('window-all-closed', () => {
|
||||
if (process.platform !== 'darwin') app.quit();
|
||||
});
|
||||
|
||||
app.on('before-quit', () => {
|
||||
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user