Add persistent IMAP IDLE watchers
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -24,7 +24,7 @@
|
|||||||
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
- [x] Fix automatic mail sync so the message list refreshes when new mail arrives.
|
||||||
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
- [x] Sync all connected accounts' mailboxes in the Electron main process at launch/resume and periodically in the background.
|
||||||
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
- [x] Track `UIDVALIDITY`, the last processed UID, and `HIGHESTMODSEQ` per account and folder; fall back to checking message flags when mod-sequences are unavailable.
|
||||||
- [ ] Add persistent IMAP IDLE watchers; bounded periodic polling currently provides updates and reconnect/backoff.
|
- [x] Add persistent IMAP IDLE watchers for up to two accounts, with reconnect backoff and periodic polling as a fallback for other accounts and servers without IDLE support.
|
||||||
- [ ] Add push mail support.
|
- [ ] Add push mail support.
|
||||||
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
|
- [x] Prevent overlapping sync runs, limit concurrent account connections, and invalidate in-flight results when an account is edited or removed.
|
||||||
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
- [x] Send updates to the renderer over IPC and show native notifications for new inbox mail.
|
||||||
|
|||||||
+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 davCredentialsPath = () => path.join(app.getPath('userData'), 'dav-accounts.enc');
|
||||||
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
const backgroundSyncIntervalMs = 2 * 60 * 1000;
|
||||||
const backgroundSyncConcurrency = 2;
|
const backgroundSyncConcurrency = 2;
|
||||||
|
const backgroundIdleConcurrency = 2;
|
||||||
let accountStoreQueue = Promise.resolve();
|
let accountStoreQueue = Promise.resolve();
|
||||||
let backgroundSyncInProgress = false;
|
let backgroundSyncInProgress = false;
|
||||||
let backgroundSyncRequested = false;
|
let backgroundSyncRequested = false;
|
||||||
const backgroundSyncGenerations = new Map();
|
const backgroundSyncGenerations = new Map();
|
||||||
const backgroundSyncFailures = new Map();
|
const backgroundSyncFailures = new Map();
|
||||||
const flagSnapshots = new Map();
|
const flagSnapshots = new Map();
|
||||||
|
const idleWatchers = new Map();
|
||||||
|
|
||||||
function updateAccountStore(update) {
|
function updateAccountStore(update) {
|
||||||
const operation = accountStoreQueue.then(async () => {
|
const operation = accountStoreQueue.then(async () => {
|
||||||
@@ -48,6 +50,7 @@ function requestBackgroundSync(accountId = null, force = false) {
|
|||||||
if (force) {
|
if (force) {
|
||||||
for (const failure of backgroundSyncFailures.values()) failure.retryAt = 0;
|
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 (backgroundSyncInProgress) {
|
||||||
if (accountId || force) backgroundSyncRequested = true;
|
if (accountId || force) backgroundSyncRequested = true;
|
||||||
return;
|
return;
|
||||||
@@ -56,6 +59,89 @@ function requestBackgroundSync(accountId = null, force = false) {
|
|||||||
void runBackgroundSync().catch(error => console.error('Background mail sync failed:', error));
|
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() {
|
async function readDavStore() {
|
||||||
try {
|
try {
|
||||||
const encrypted = await fs.readFile(davCredentialsPath());
|
const encrypted = await fs.readFile(davCredentialsPath());
|
||||||
@@ -118,7 +204,7 @@ function normalizeAccount(input) {
|
|||||||
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
return { email, password, displayName, imapHost, smtpHost, imapPort: 143, smtpPort: 587 };
|
||||||
}
|
}
|
||||||
|
|
||||||
function imapClient(account) {
|
function imapClient(account, options = {}) {
|
||||||
return new ImapFlow({
|
return new ImapFlow({
|
||||||
host: account.imapHost,
|
host: account.imapHost,
|
||||||
port: account.imapPort,
|
port: account.imapPort,
|
||||||
@@ -129,7 +215,8 @@ function imapClient(account) {
|
|||||||
logger: false,
|
logger: false,
|
||||||
connectionTimeout: 15000,
|
connectionTimeout: 15000,
|
||||||
greetingTimeout: 10000,
|
greetingTimeout: 10000,
|
||||||
socketTimeout: 20000
|
socketTimeout: 20000,
|
||||||
|
...options
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -848,6 +935,9 @@ app.whenReady().then(() => {
|
|||||||
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
const syncTimer = setInterval(() => requestBackgroundSync(), backgroundSyncIntervalMs);
|
||||||
syncTimer.unref();
|
syncTimer.unref();
|
||||||
requestBackgroundSync();
|
requestBackgroundSync();
|
||||||
|
powerMonitor.on('suspend', () => {
|
||||||
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||||
|
});
|
||||||
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
powerMonitor.on('resume', () => requestBackgroundSync(null, true));
|
||||||
app.on('activate', () => {
|
app.on('activate', () => {
|
||||||
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
if (BrowserWindow.getAllWindows().length === 0) createWindow();
|
||||||
@@ -857,3 +947,7 @@ app.whenReady().then(() => {
|
|||||||
app.on('window-all-closed', () => {
|
app.on('window-all-closed', () => {
|
||||||
if (process.platform !== 'darwin') app.quit();
|
if (process.platform !== 'darwin') app.quit();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.on('before-quit', () => {
|
||||||
|
for (const accountId of idleWatchers.keys()) stopIdleWatcher(accountId);
|
||||||
|
});
|
||||||
|
|||||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.1.15",
|
"version": "0.1.16",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.1.15",
|
"version": "0.1.16",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"ical.js": "^2.2.1",
|
"ical.js": "^2.2.1",
|
||||||
"imapflow": "2.2.1",
|
"imapflow": "2.2.1",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ep-mail",
|
"name": "ep-mail",
|
||||||
"version": "0.1.15",
|
"version": "0.1.16",
|
||||||
"private": true,
|
"private": true,
|
||||||
"description": "Eternity Project mail client",
|
"description": "Eternity Project mail client",
|
||||||
"author": "Eternity Project",
|
"author": "Eternity Project",
|
||||||
|
|||||||
Reference in New Issue
Block a user