108 lines
3.9 KiB
JavaScript
108 lines
3.9 KiB
JavaScript
function createIdleWatcherManager({
|
|
readAccountStore,
|
|
readAccount,
|
|
imapClient,
|
|
backgroundSyncGenerations,
|
|
concurrency = 2,
|
|
logError = (...args) => console.error(...args),
|
|
wait = delay => new Promise(resolve => {
|
|
const timer = setTimeout(resolve, delay);
|
|
timer.unref();
|
|
})
|
|
}) {
|
|
const idleWatchers = new Map();
|
|
let requestSync = () => {};
|
|
|
|
function setRequestBackgroundSync(callback) {
|
|
requestSync = callback;
|
|
}
|
|
|
|
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 => {
|
|
logError(`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) requestSync();
|
|
});
|
|
client.on('flags', event => {
|
|
if (event.path.toLowerCase() === 'inbox') requestSync();
|
|
});
|
|
client.on('error', error => {
|
|
if (!watcher.stopped) logError(`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) logError(`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 wait(retryDelay);
|
|
}
|
|
}
|
|
|
|
async function reconcileIdleWatchers() {
|
|
const store = (await readAccountStore()) || { accounts: [] };
|
|
const desiredAccounts = store.accounts.slice(0, concurrency);
|
|
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);
|
|
}
|
|
|
|
function stopAll() {
|
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
|
}
|
|
|
|
return { reconcileIdleWatchers, setRequestBackgroundSync, stopAll, stopIdleWatcher };
|
|
}
|
|
|
|
module.exports = { createIdleWatcherManager };
|