fix: авто-переподключение при потере IMAP-соединения (NoConnection)
Добавлен withAutoReconnect<T> в AccountManager — оборачивает все операции с провайдером. При ошибках NoConnection/ECONNRESET/ETIMEDOUT автоматически пересоздаёт провайдер, переподключается и повторяет операцию. Покрыты: listFolders, listMessages, fetchMessageBody, downloadAttachment, updateFlags, deleteMessages, searchMessages. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
parent
6950003c79
commit
2bf608b276
1 changed files with 69 additions and 19 deletions
|
|
@ -3,7 +3,7 @@ import { join } from 'node:path'
|
|||
import type { AccountConfig } from '@shared/types/account'
|
||||
import { AccountType } from '@shared/types/account'
|
||||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
||||
import type { MessageBody, MessageFlags } from '@shared/types/message'
|
||||
import type { MessageBody, MessageFlags, MessageEnvelope } from '@shared/types/message'
|
||||
import { ImapProvider } from '../providers/imap.provider'
|
||||
import { ExchangeProvider } from '../providers/exchange.provider'
|
||||
import { GmailProvider } from '../providers/gmail.provider'
|
||||
|
|
@ -14,6 +14,9 @@ interface AccountStoreSchema {
|
|||
accounts: Omit<AccountConfig, 'credentials'>[]
|
||||
}
|
||||
|
||||
// Коды ошибок imapflow при потере соединения
|
||||
const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'])
|
||||
|
||||
export class AccountManager {
|
||||
private providers = new Map<string, IEmailProvider>()
|
||||
private store: Store<AccountStoreSchema>
|
||||
|
|
@ -118,19 +121,22 @@ export class AccountManager {
|
|||
}
|
||||
|
||||
async listFolders(accountId: string): Promise<FolderListResult> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.listFolders()
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).listFolders()
|
||||
)
|
||||
}
|
||||
|
||||
async pollNewMessages(accountId: string): Promise<void> {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (provider) await provider.pollNewMessages()
|
||||
if (provider) await provider.pollNewMessages().catch(() => {})
|
||||
}
|
||||
|
||||
async searchMessages(accountId: string, query: string, limit: number): Promise<import('@shared/types/message').MessageEnvelope[]> {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (!provider) return []
|
||||
return provider.searchMessages(query, limit)
|
||||
async searchMessages(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
|
||||
return this.withAutoReconnect(accountId, () => {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (!provider) return Promise.resolve([])
|
||||
return provider.searchMessages(query, limit)
|
||||
})
|
||||
}
|
||||
|
||||
async listMessages(
|
||||
|
|
@ -140,8 +146,9 @@ export class AccountManager {
|
|||
limit: number,
|
||||
unseenOnly = false
|
||||
): Promise<MessageListResult> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.listMessages({ folderId, offset, limit, unseenOnly })
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).listMessages({ folderId, offset, limit, unseenOnly })
|
||||
)
|
||||
}
|
||||
|
||||
async fetchMessageBody(
|
||||
|
|
@ -149,8 +156,9 @@ export class AccountManager {
|
|||
folderId: string,
|
||||
messageId: string
|
||||
): Promise<MessageBody> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.fetchMessageBody(folderId, messageId)
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).fetchMessageBody(folderId, messageId)
|
||||
)
|
||||
}
|
||||
|
||||
async downloadAttachment(
|
||||
|
|
@ -159,8 +167,9 @@ export class AccountManager {
|
|||
messageId: string,
|
||||
attachmentId: string
|
||||
): Promise<Buffer> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.downloadAttachment(folderId, messageId, attachmentId)
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).downloadAttachment(folderId, messageId, attachmentId)
|
||||
)
|
||||
}
|
||||
|
||||
async updateFlags(
|
||||
|
|
@ -169,8 +178,9 @@ export class AccountManager {
|
|||
messageIds: string[],
|
||||
flags: Partial<MessageFlags>
|
||||
): Promise<void> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.updateFlags(folderId, messageIds, flags)
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).updateFlags(folderId, messageIds, flags)
|
||||
)
|
||||
}
|
||||
|
||||
async deleteMessages(
|
||||
|
|
@ -178,10 +188,51 @@ export class AccountManager {
|
|||
folderId: string,
|
||||
messageIds: string[]
|
||||
): Promise<void> {
|
||||
const provider = this.getProvider(accountId)
|
||||
return provider.deleteMessages(folderId, messageIds)
|
||||
return this.withAutoReconnect(accountId, () =>
|
||||
this.getProvider(accountId).deleteMessages(folderId, messageIds)
|
||||
)
|
||||
}
|
||||
|
||||
// ── Auto-reconnect ──────────────────────────────────────
|
||||
|
||||
private async withAutoReconnect<T>(accountId: string, fn: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await fn()
|
||||
} catch (err) {
|
||||
const code = (err as { code?: string }).code ?? ''
|
||||
if (RECONNECT_CODES.has(code)) {
|
||||
await this.reconnectAccount(accountId)
|
||||
return await fn()
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
private async reconnectAccount(accountId: string): Promise<void> {
|
||||
// Убиваем старый провайдер
|
||||
const old = this.providers.get(accountId)
|
||||
if (old) {
|
||||
old.offNewMail()
|
||||
try { await old.disconnect() } catch { /* уже отвалился */ }
|
||||
this.providers.delete(accountId)
|
||||
}
|
||||
|
||||
const accounts = this.store.get('accounts', [])
|
||||
const accMeta = accounts.find((a) => a.id === accountId)
|
||||
if (!accMeta) throw new Error('Account not found')
|
||||
|
||||
const credRaw = this.credentialStore.get(accountId)
|
||||
if (!credRaw) throw new Error('Credentials not found')
|
||||
|
||||
const config: AccountConfig = { ...accMeta, credentials: JSON.parse(credRaw) }
|
||||
const provider = this.createProvider(config)
|
||||
await provider.connect()
|
||||
this.providers.set(accountId, provider)
|
||||
this.setupNewMailListener(accountId, provider)
|
||||
}
|
||||
|
||||
// ── Private helpers ─────────────────────────────────────
|
||||
|
||||
private getProvider(accountId: string): IEmailProvider {
|
||||
const provider = this.providers.get(accountId)
|
||||
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
||||
|
|
@ -229,6 +280,5 @@ export class AccountManager {
|
|||
n.show()
|
||||
}
|
||||
})
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue