aero-mail/src/main/services/inbox-watcher.ts

160 lines
5.6 KiB
TypeScript

import type { MessageEnvelope } from '@shared/types/message'
import type { MailCursor } from '@shared/types/mail-cursor'
export interface InboxClient {
connect(): Promise<void>
selectInbox(): Promise<MailCursor>
fetchAfter(uid: number, limit: number): Promise<MessageEnvelope[]>
onChange(callback: () => void): void
onDisconnect(callback: (error: Error) => void): void
close(): void
}
export interface WatcherScheduler {
after(milliseconds: number, callback: () => void): () => void
every(milliseconds: number, callback: () => void): () => void
}
export interface InboxWatcher {
start(): void
stop(): void
restart(): void
}
const RETRY_DELAYS: number[] = [1_000, 5_000, 30_000, 60_000]
export class ImapInboxWatcher implements InboxWatcher {
private client: InboxClient | null = null
private cursor: { uidValidity: string; lastUid: number } | null = null
private stopped: boolean = true
private ready: boolean = false
private generation: number = 0
private retries: number = 0
private checking: Promise<void> | null = null
private checkAgain: boolean = false
private cancelRetry: (() => void) | null = null
private cancelPoll: (() => void) | null = null
private readonly createClient: () => InboxClient
private readonly publish: (messages: MessageEnvelope[]) => void
private readonly reportError: (error: Error) => void
private readonly scheduler: WatcherScheduler
constructor(
createClient: () => InboxClient,
publish: (messages: MessageEnvelope[]) => void,
reportError: (error: Error) => void,
scheduler: WatcherScheduler
) {
this.createClient = createClient
this.publish = publish
this.reportError = reportError
this.scheduler = scheduler
}
start(): void {
if (!this.stopped) return
this.stopped = false
void this.connect()
}
stop(): void {
this.stopped = true
this.generation++
this.ready = false
this.checkAgain = false
this.cancelRetry?.()
this.cancelPoll?.()
this.cancelRetry = null
this.cancelPoll = null
const client: InboxClient | null = this.client
this.client = null
client?.close()
}
restart(): void {
this.stop()
this.start()
}
private isCurrent(client: InboxClient, generation: number): boolean {
return !this.stopped && this.client === client && this.generation === generation
}
private async connect(): Promise<void> {
const generation: number = ++this.generation
let client: InboxClient
try { client = this.createClient() } catch (error: unknown) {
this.retry(error instanceof Error ? error : new Error(String(error)))
return
}
this.client = client
client.onChange((): void => { if (this.isCurrent(client, generation)) void this.check(client, generation) })
client.onDisconnect((error: Error): void => { if (this.isCurrent(client, generation)) this.fail(client, generation, error) })
try {
await client.connect()
if (!this.isCurrent(client, generation)) return
const mailbox: MailCursor = await client.selectInbox()
if (!this.isCurrent(client, generation)) return
if (this.cursor?.uidValidity !== mailbox.uidValidity) this.cursor = { uidValidity: mailbox.uidValidity, lastUid: mailbox.nextUid - 1 }
this.ready = true
this.retries = 0
this.cancelPoll = this.scheduler.every(60_000, (): void => { void this.check(client, generation) })
await this.check(client, generation)
} catch (error: unknown) {
this.fail(client, generation, error instanceof Error ? error : new Error(String(error)))
}
}
private check(client: InboxClient, generation: number): Promise<void> {
if (!this.isCurrent(client, generation)) return Promise.resolve()
this.checkAgain = true
if (!this.ready) return Promise.resolve()
if (this.checking) return this.checking
const pending: Promise<void> = this.drain(client, generation).catch((error: unknown): void => {
this.fail(client, generation, error instanceof Error ? error : new Error(String(error)))
}).finally((): void => {
if (this.checking === pending) this.checking = null
if (this.client && this.ready && this.checkAgain) void this.check(this.client, this.generation)
})
this.checking = pending
return pending
}
private async drain(client: InboxClient, generation: number): Promise<void> {
while (this.isCurrent(client, generation) && this.cursor && this.checkAgain) {
this.checkAgain = false
while (this.isCurrent(client, generation) && this.cursor) {
const afterUid: number = this.cursor.lastUid
const messages: MessageEnvelope[] = await client.fetchAfter(afterUid, 100)
if (!this.isCurrent(client, generation)) return
const fresh: MessageEnvelope[] = messages.filter((message) => Number(message.id) > afterUid)
.sort((first, second) => Number(first.id) - Number(second.id))
if (!fresh.length) break
this.publish(fresh)
this.cursor = { ...this.cursor, lastUid: Number(fresh[fresh.length - 1].id) }
}
}
}
private fail(client: InboxClient, generation: number, error: Error): void {
if (!this.isCurrent(client, generation)) return
this.generation++
this.client = null
this.ready = false
this.cancelPoll?.()
this.cancelPoll = null
client.close()
this.retry(error)
}
private retry(error: Error): void {
this.reportError(error)
if (this.stopped) return
const delay: number = RETRY_DELAYS[Math.min(this.retries++, RETRY_DELAYS.length - 1)]
this.cancelRetry = this.scheduler.after(delay, (): void => {
this.cancelRetry = null
if (!this.stopped) void this.connect()
})
}
}