164 lines
7.5 KiB
TypeScript
164 lines
7.5 KiB
TypeScript
import { test } from 'node:test'
|
||
import assert from 'node:assert/strict'
|
||
import { ImapInboxWatcher } from '../src/main/services/inbox-watcher.ts'
|
||
import type { InboxClient, WatcherScheduler } from '../src/main/services/inbox-watcher.ts'
|
||
import type { MessageEnvelope } from '../src/shared/types/message.ts'
|
||
import type { MailCursor } from '../src/shared/types/mail-cursor.ts'
|
||
|
||
function message(uid: number): MessageEnvelope {
|
||
return { id: String(uid), folderId: 'INBOX', subject: 'Новое', date: '2026-11-17', from: { name: 'Автор', email: 'sender@example.org' }, to: [], cc: [], flags: { seen: false, flagged: false, answered: false, deleted: false }, hasAttachments: false, snippet: '' }
|
||
}
|
||
|
||
class TestScheduler implements WatcherScheduler {
|
||
readonly tasks: { interval: number; callback: () => void; active: boolean; repeated: boolean }[] = []
|
||
after(interval: number, callback: () => void): () => void {
|
||
const task = { interval, callback, active: true, repeated: false }
|
||
this.tasks.push(task)
|
||
return (): void => { task.active = false }
|
||
}
|
||
every(interval: number, callback: () => void): () => void {
|
||
const task = { interval, callback, active: true, repeated: true }
|
||
this.tasks.push(task)
|
||
return (): void => { task.active = false }
|
||
}
|
||
run(interval: number): void {
|
||
const task = this.tasks.find((item) => item.active && item.interval === interval)
|
||
assert.ok(task)
|
||
if (!task.repeated) task.active = false
|
||
task.callback()
|
||
}
|
||
}
|
||
|
||
class TestInboxClient implements InboxClient {
|
||
messages: MessageEnvelope[] = []
|
||
validity: string = '1'
|
||
nextUid: number = 1
|
||
active: number = 0
|
||
maximum: number = 0
|
||
closed: boolean = false
|
||
failure: Error | null = null
|
||
private change: () => void = (): void => {}
|
||
private disconnected: (error: Error) => void = (): void => {}
|
||
async connect(): Promise<void> { if (this.failure) throw this.failure }
|
||
async selectInbox(): Promise<MailCursor> { return { uidValidity: this.validity, nextUid: this.nextUid } }
|
||
async fetchAfter(uid: number, limit: number): Promise<MessageEnvelope[]> {
|
||
this.active++
|
||
this.maximum = Math.max(this.active, this.maximum)
|
||
await Promise.resolve()
|
||
this.active--
|
||
return this.messages.filter((item) => Number(item.id) > uid).slice(0, limit)
|
||
}
|
||
onChange(callback: () => void): void { this.change = callback }
|
||
onDisconnect(callback: (error: Error) => void): void { this.disconnected = callback }
|
||
close(): void { this.closed = true; this.disconnected(new Error('Закрыто')) }
|
||
emitChange(): void { this.change() }
|
||
disconnect(): void { this.disconnected(new Error('Обрыв соединения')) }
|
||
}
|
||
|
||
async function settle(): Promise<void> { for (let index: number = 0; index < 60; index++) await Promise.resolve() }
|
||
|
||
test('наблюдатель загружает все новые UID, включая первое письмо пустого ящика, без параллельных проверок', async (): Promise<void> => {
|
||
const client: TestInboxClient = new TestInboxClient()
|
||
const scheduler: TestScheduler = new TestScheduler()
|
||
const received: string[] = []
|
||
const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => client, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): never => { throw error }, scheduler)
|
||
watcher.start()
|
||
await settle()
|
||
client.messages = Array.from({ length: 250 }, (_, index: number): MessageEnvelope => ({ ...message(index + 1), flags: { ...message(index + 1).flags, seen: index % 2 === 0 } }))
|
||
for (let index: number = 0; index < 10; index++) client.emitChange()
|
||
await settle()
|
||
assert.equal(received.length, 250)
|
||
assert.equal(new Set<string>(received).size, 250)
|
||
assert.equal(received[0], '1')
|
||
assert.equal(received[249], '250')
|
||
assert.equal(client.maximum, 1)
|
||
watcher.stop()
|
||
assert.equal(scheduler.tasks.filter((task) => task.active).length, 0)
|
||
})
|
||
|
||
test('после переподключения догружает пропущенные UID и игнорирует события старого соединения', async (): Promise<void> => {
|
||
const first: TestInboxClient = new TestInboxClient()
|
||
const second: TestInboxClient = new TestInboxClient()
|
||
const clients: TestInboxClient[] = [first, second]
|
||
const scheduler: TestScheduler = new TestScheduler()
|
||
const received: string[] = []
|
||
const errors: string[] = []
|
||
const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => { const client = clients.shift(); assert.ok(client); return client }, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): void => { errors.push(error.message) }, scheduler)
|
||
watcher.start()
|
||
await settle()
|
||
first.messages = [message(1)]
|
||
first.emitChange()
|
||
await settle()
|
||
first.disconnect()
|
||
second.nextUid = 4
|
||
second.messages = [message(1), message(2), message(3)]
|
||
scheduler.run(1_000)
|
||
await settle()
|
||
first.emitChange()
|
||
await settle()
|
||
assert.deepEqual(received, ['1', '2', '3'])
|
||
assert.equal(errors.length, 1)
|
||
assert.equal(first.closed, true)
|
||
watcher.stop()
|
||
})
|
||
|
||
test('резервный таймер находит письма без события IDLE и остановка прекращает наблюдение', async (): Promise<void> => {
|
||
const client: TestInboxClient = new TestInboxClient()
|
||
const scheduler: TestScheduler = new TestScheduler()
|
||
const received: string[] = []
|
||
const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => client, (messages): void => { received.push(...messages.map((item) => item.id)) }, (error): never => { throw error }, scheduler)
|
||
watcher.start()
|
||
await settle()
|
||
client.messages = [message(1)]
|
||
scheduler.run(60_000)
|
||
await settle()
|
||
assert.deepEqual(received, ['1'])
|
||
watcher.stop()
|
||
client.messages.push(message(2))
|
||
client.emitChange()
|
||
await settle()
|
||
assert.deepEqual(received, ['1'])
|
||
})
|
||
|
||
test('смена UIDVALIDITY не создаёт уведомлений обо всём существующем ящике', async (): Promise<void> => {
|
||
const first: TestInboxClient = new TestInboxClient()
|
||
const second: TestInboxClient = new TestInboxClient()
|
||
second.validity = '2'
|
||
second.nextUid = 3
|
||
second.messages = [message(1), message(2)]
|
||
const clients: TestInboxClient[] = [first, second]
|
||
const scheduler: TestScheduler = new TestScheduler()
|
||
const received: string[] = []
|
||
const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => { const client = clients.shift(); assert.ok(client); return client }, (messages): void => { received.push(...messages.map((item) => item.id)) }, (): void => {}, scheduler)
|
||
watcher.start()
|
||
await settle()
|
||
watcher.restart()
|
||
await settle()
|
||
assert.deepEqual(received, [])
|
||
second.messages.push(message(3))
|
||
second.emitChange()
|
||
await settle()
|
||
assert.deepEqual(received, ['3'])
|
||
watcher.stop()
|
||
})
|
||
|
||
|
||
test('повторяет неудачные подключения с нарастающей паузой', async (): Promise<void> => {
|
||
const scheduler: TestScheduler = new TestScheduler()
|
||
const errors: string[] = []
|
||
const watcher: ImapInboxWatcher = new ImapInboxWatcher(() => {
|
||
const client: TestInboxClient = new TestInboxClient()
|
||
client.failure = new Error('Подключение недоступно')
|
||
return client
|
||
}, (): void => {}, (error): void => { errors.push(error.message) }, scheduler)
|
||
watcher.start()
|
||
await settle()
|
||
scheduler.run(1_000)
|
||
await settle()
|
||
scheduler.run(5_000)
|
||
await settle()
|
||
assert.equal(errors.length, 3)
|
||
assert.ok(scheduler.tasks.some((task) => task.active && task.interval === 30_000))
|
||
watcher.stop()
|
||
assert.equal(scheduler.tasks.filter((task) => task.active).length, 0)
|
||
})
|