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 type { AccountConfig } from '@shared/types/account'
|
||||||
import { AccountType } from '@shared/types/account'
|
import { AccountType } from '@shared/types/account'
|
||||||
import type { IEmailProvider, FolderListResult, MessageListResult } from '@shared/types/provider'
|
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 { ImapProvider } from '../providers/imap.provider'
|
||||||
import { ExchangeProvider } from '../providers/exchange.provider'
|
import { ExchangeProvider } from '../providers/exchange.provider'
|
||||||
import { GmailProvider } from '../providers/gmail.provider'
|
import { GmailProvider } from '../providers/gmail.provider'
|
||||||
|
|
@ -14,6 +14,9 @@ interface AccountStoreSchema {
|
||||||
accounts: Omit<AccountConfig, 'credentials'>[]
|
accounts: Omit<AccountConfig, 'credentials'>[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Коды ошибок imapflow при потере соединения
|
||||||
|
const RECONNECT_CODES = new Set(['NoConnection', 'ECONNRESET', 'ECONNREFUSED', 'ETIMEDOUT', 'ENOTFOUND'])
|
||||||
|
|
||||||
export class AccountManager {
|
export class AccountManager {
|
||||||
private providers = new Map<string, IEmailProvider>()
|
private providers = new Map<string, IEmailProvider>()
|
||||||
private store: Store<AccountStoreSchema>
|
private store: Store<AccountStoreSchema>
|
||||||
|
|
@ -118,19 +121,22 @@ export class AccountManager {
|
||||||
}
|
}
|
||||||
|
|
||||||
async listFolders(accountId: string): Promise<FolderListResult> {
|
async listFolders(accountId: string): Promise<FolderListResult> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.listFolders()
|
this.getProvider(accountId).listFolders()
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async pollNewMessages(accountId: string): Promise<void> {
|
async pollNewMessages(accountId: string): Promise<void> {
|
||||||
const provider = this.providers.get(accountId)
|
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[]> {
|
async searchMessages(accountId: string, query: string, limit: number): Promise<MessageEnvelope[]> {
|
||||||
|
return this.withAutoReconnect(accountId, () => {
|
||||||
const provider = this.providers.get(accountId)
|
const provider = this.providers.get(accountId)
|
||||||
if (!provider) return []
|
if (!provider) return Promise.resolve([])
|
||||||
return provider.searchMessages(query, limit)
|
return provider.searchMessages(query, limit)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async listMessages(
|
async listMessages(
|
||||||
|
|
@ -140,8 +146,9 @@ export class AccountManager {
|
||||||
limit: number,
|
limit: number,
|
||||||
unseenOnly = false
|
unseenOnly = false
|
||||||
): Promise<MessageListResult> {
|
): Promise<MessageListResult> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.listMessages({ folderId, offset, limit, unseenOnly })
|
this.getProvider(accountId).listMessages({ folderId, offset, limit, unseenOnly })
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fetchMessageBody(
|
async fetchMessageBody(
|
||||||
|
|
@ -149,8 +156,9 @@ export class AccountManager {
|
||||||
folderId: string,
|
folderId: string,
|
||||||
messageId: string
|
messageId: string
|
||||||
): Promise<MessageBody> {
|
): Promise<MessageBody> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.fetchMessageBody(folderId, messageId)
|
this.getProvider(accountId).fetchMessageBody(folderId, messageId)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async downloadAttachment(
|
async downloadAttachment(
|
||||||
|
|
@ -159,8 +167,9 @@ export class AccountManager {
|
||||||
messageId: string,
|
messageId: string,
|
||||||
attachmentId: string
|
attachmentId: string
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.downloadAttachment(folderId, messageId, attachmentId)
|
this.getProvider(accountId).downloadAttachment(folderId, messageId, attachmentId)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateFlags(
|
async updateFlags(
|
||||||
|
|
@ -169,8 +178,9 @@ export class AccountManager {
|
||||||
messageIds: string[],
|
messageIds: string[],
|
||||||
flags: Partial<MessageFlags>
|
flags: Partial<MessageFlags>
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.updateFlags(folderId, messageIds, flags)
|
this.getProvider(accountId).updateFlags(folderId, messageIds, flags)
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteMessages(
|
async deleteMessages(
|
||||||
|
|
@ -178,10 +188,51 @@ export class AccountManager {
|
||||||
folderId: string,
|
folderId: string,
|
||||||
messageIds: string[]
|
messageIds: string[]
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const provider = this.getProvider(accountId)
|
return this.withAutoReconnect(accountId, () =>
|
||||||
return provider.deleteMessages(folderId, messageIds)
|
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 {
|
private getProvider(accountId: string): IEmailProvider {
|
||||||
const provider = this.providers.get(accountId)
|
const provider = this.providers.get(accountId)
|
||||||
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
if (!provider) throw new Error(`Account ${accountId} is not connected`)
|
||||||
|
|
@ -229,6 +280,5 @@ export class AccountManager {
|
||||||
n.show()
|
n.show()
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue