261 lines
9.8 KiB
JavaScript
261 lines
9.8 KiB
JavaScript
import { test } from 'node:test'
|
|
import assert from 'node:assert/strict'
|
|
import { mkdtempSync, rmSync } from 'node:fs'
|
|
import os from 'node:os'
|
|
import path from 'node:path'
|
|
import { openDb, seed } from '../server/db.js'
|
|
import { Service } from '../server/service.js'
|
|
import { readMailSettings, saveMailSettings } from '../server/mail-config.js'
|
|
import { InboundWorker } from '../server/inbound.js'
|
|
import { retryAt } from '../server/inbound-errors.js'
|
|
|
|
process.env.SMTP_ENCRYPTION_KEY = 'a9'.repeat(32)
|
|
function setup(file = ':memory:') {
|
|
const db = openDb(file)
|
|
seed(db)
|
|
const s = new Service(db),
|
|
admin = s.user('admin')
|
|
const c = readMailSettings(s, admin, 'support')
|
|
saveMailSettings(s, admin, 'support', {
|
|
...c,
|
|
imap: { ...c.imap, enabled: true, host: 'imap.example.invalid', username: 'support' },
|
|
imapPassword: 'imap-secret-for-test',
|
|
})
|
|
return { db, s, admin }
|
|
}
|
|
const mime = (uid, valid = true) =>
|
|
Buffer.from(
|
|
`From: Anna Beispiel <anna@example.org>\r\nTo: support@syncova.local\r\n${valid ? `Message-ID: <resilience-${uid}@example.org>\r\n` : ''}Date: Thu, 05 Nov 2026 14:13:00 +0100\r\nSubject: Importprobe ${uid}\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nBitte helfen.\r\n`,
|
|
)
|
|
function fake(messages, state = {}) {
|
|
state.requests ||= []
|
|
return () => ({
|
|
mailbox: { uidValidity: state.validity || 1n },
|
|
async connect() {},
|
|
async getMailboxLock() {
|
|
return { release() {} }
|
|
},
|
|
async search() {
|
|
return [...messages.keys()]
|
|
},
|
|
async fetchOne(uid, query) {
|
|
state.requests.push({ uid, type: query.size ? 'metadata' : 'source' })
|
|
if (query.size)
|
|
return {
|
|
size: state.sizes?.[uid] || messages.get(uid).length,
|
|
envelope: {
|
|
subject: `Kopf ${uid}`,
|
|
from: [{ name: 'Anna', address: 'anna@example.org' }],
|
|
to: [{ address: 'support@syncova.local' }],
|
|
date: new Date('2026-11-05T13:13:00Z'),
|
|
messageId: `<head-${uid}@example.org>`,
|
|
},
|
|
}
|
|
if (state.sourceErrors?.[uid]) throw state.sourceErrors[uid]
|
|
return { source: messages.get(uid) }
|
|
},
|
|
async messageFlagsAdd(uids) {
|
|
if (state.flagsError) throw state.flagsError
|
|
;(state.seen ||= []).push(uids)
|
|
},
|
|
async logout() {},
|
|
close() {},
|
|
})
|
|
}
|
|
const errors = (s) =>
|
|
s
|
|
.all("SELECT * FROM audits WHERE action='Nachricht konnte nicht importiert werden' ORDER BY id")
|
|
.map((a) => JSON.parse(a.after_value))
|
|
|
|
test('A failed message does not stop later imports and logs usable identity, cause and retry time', async () => {
|
|
const { db, s, admin } = setup()
|
|
try {
|
|
const state = {},
|
|
messages = new Map([
|
|
[1, mime(1, false)],
|
|
[2, mime(2)],
|
|
[3, mime(3)],
|
|
])
|
|
const worker = new InboundWorker(s, {
|
|
clientFactory: fake(messages, state),
|
|
clock: () => new Date('2030-01-01T00:00:00Z'),
|
|
})
|
|
const result = await worker.run('support')
|
|
assert.equal(result.imported, 2)
|
|
assert.equal(result.failed, 1)
|
|
assert.equal(result.pending, 1)
|
|
assert.deepEqual(state.seen, [2, 3])
|
|
assert.equal(s.get('SELECT count(*) n FROM inbound_receipts WHERE uid=1').n, 0)
|
|
const [error] = errors(s)
|
|
assert.equal(error.subject, 'Importprobe 1')
|
|
assert.equal(error.from, 'Anna Beispiel <anna@example.org>')
|
|
assert.equal(error.to, 'support@syncova.local')
|
|
assert.equal(error.date, '2026-11-05T13:13:00.000Z')
|
|
assert.match(error.reason, /Message-ID fehlt/)
|
|
assert.equal(error.stage, 'import')
|
|
assert.equal(error.uid, 1)
|
|
assert.equal(error.uidValidity, '1')
|
|
assert.equal(error.folder, 'INBOX')
|
|
assert.equal(error.nextRetry, '2030-01-01T00:01:00.000Z')
|
|
assert.match(error.continuation, /weiter/)
|
|
assert(!JSON.stringify(s.logs(admin)).includes('imap-secret-for-test'))
|
|
assert.equal(s.logs(s.user('mira')).length, 0)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
|
|
test('More than 100 bad messages cannot starve new mail, including after a database restart', async () => {
|
|
const folder = mkdtempSync(path.join(os.tmpdir(), 'syncova-inbound-resilience-'))
|
|
let db
|
|
try {
|
|
const initial = setup(path.join(folder, 'test.db'))
|
|
db = initial.db
|
|
const messages = new Map()
|
|
for (let uid = 1; uid <= 105; uid++) messages.set(uid, mime(uid, false))
|
|
messages.set(106, mime(106))
|
|
const clock = () => new Date('2030-01-01T00:00:00Z')
|
|
assert.equal(
|
|
(await new InboundWorker(initial.s, { clientFactory: fake(messages), clock }).run('support'))
|
|
.failed,
|
|
100,
|
|
)
|
|
db.close()
|
|
db = openDb(path.join(folder, 'test.db'))
|
|
const s = new Service(db),
|
|
state = {}
|
|
const worker = new InboundWorker(s, { clientFactory: fake(messages, state), clock })
|
|
const second = await worker.run('support')
|
|
assert.equal(second.imported, 1)
|
|
assert.equal(second.failed, 5)
|
|
assert.equal(second.pending, 105)
|
|
assert.equal(second.retried, 0)
|
|
assert.equal(state.requests.filter((r) => r.type === 'source').length, 6)
|
|
const manual = await worker.run('support', { retryFailed: true })
|
|
assert.equal(manual.retried, 10)
|
|
assert.equal(manual.failed, 10)
|
|
assert.equal(manual.pending, 105)
|
|
messages.set(107, mime(107))
|
|
assert.equal((await worker.run('support')).imported, 1)
|
|
} finally {
|
|
db?.close()
|
|
assert.equal(path.dirname(path.resolve(folder)), path.resolve(os.tmpdir()))
|
|
assert(path.basename(folder).startsWith('syncova-inbound-resilience-'))
|
|
rmSync(folder, { recursive: true, force: true })
|
|
}
|
|
})
|
|
|
|
test('Retry cooldown is persistent, grows, and recovery removes failure state without duplicate tickets', async () => {
|
|
const { db, s } = setup()
|
|
try {
|
|
let at = new Date('2030-01-01T00:00:00Z')
|
|
const messages = new Map([[1, mime(1, false)]]),
|
|
factory = fake(messages)
|
|
let worker = new InboundWorker(s, { clientFactory: factory, clock: () => at })
|
|
await worker.run('support')
|
|
worker = new InboundWorker(s, { clientFactory: factory, clock: () => at })
|
|
assert.equal((await worker.run('support')).failed, 0)
|
|
assert.equal(errors(s).length, 1)
|
|
at = new Date('2030-01-01T00:01:01Z')
|
|
assert.equal((await worker.run('support')).retried, 1)
|
|
assert.equal(errors(s)[1].attempts, 2)
|
|
assert.equal(errors(s)[1].nextRetry, '2030-01-01T00:06:01.000Z')
|
|
messages.set(1, mime(1))
|
|
const recovered = await worker.run('support', { retryFailed: true })
|
|
assert.equal(recovered.imported, 1)
|
|
assert.equal(recovered.pending, 0)
|
|
assert.equal(recovered.ok, true)
|
|
assert.equal(s.get('SELECT count(*) n FROM inbound_failures').n, 0)
|
|
assert.equal((await worker.run('support')).imported, 0)
|
|
assert.equal(
|
|
s.get("SELECT count(*) n FROM messages WHERE message_id='<resilience-1@example.org>'").n,
|
|
1,
|
|
)
|
|
assert.equal(s.get("SELECT error FROM queue_inbound WHERE queue_id='support'").error, null)
|
|
assert.equal(retryAt(99, at), '2030-01-02T00:01:01.000Z')
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
|
|
test('Oversize and failed downloads retain envelope identity without logging raw server errors or credentials', async () => {
|
|
const { db, s } = setup()
|
|
try {
|
|
const messages = new Map([
|
|
[1, mime(1)],
|
|
[2, mime(2)],
|
|
[3, mime(3)],
|
|
])
|
|
const state = {
|
|
sizes: { 1: 21 * 1024 * 1024 },
|
|
sourceErrors: {
|
|
2: Object.assign(new Error('raw-server-password=do-not-log'), { code: 'ECONNRESET' }),
|
|
},
|
|
}
|
|
const result = await new InboundWorker(s, { clientFactory: fake(messages, state) }).run(
|
|
'support',
|
|
)
|
|
assert.equal(result.imported, 1)
|
|
assert.equal(result.failed, 2)
|
|
const [large, download] = errors(s)
|
|
assert.equal(large.subject, 'Kopf 1')
|
|
assert.equal(large.code, 'MessageTooLarge')
|
|
assert.equal(large.size, 21 * 1024 * 1024)
|
|
assert.match(large.reason, /20 MiB/)
|
|
assert(!state.requests.some((r) => r.uid === 1 && r.type === 'source'))
|
|
assert.equal(download.subject, 'Kopf 2')
|
|
assert.equal(download.stage, 'download')
|
|
assert.equal(download.code, 'ECONNRESET')
|
|
assert(!JSON.stringify(s.all('SELECT * FROM audits')).includes('do-not-log'))
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
|
|
test('Read flag errors are separate from import failures and never block new mail or cause duplicate imports', async () => {
|
|
const { db, s } = setup()
|
|
try {
|
|
const messages = new Map([
|
|
[1, mime(1)],
|
|
[2, mime(2)],
|
|
]),
|
|
state = { flagsError: Object.assign(new Error('server refused'), { code: 'NO' }) }
|
|
const worker = new InboundWorker(s, { clientFactory: fake(messages, state) })
|
|
const first = await worker.run('support')
|
|
assert.equal(first.imported, 2)
|
|
assert.equal(first.failed, 0)
|
|
assert.equal(first.pending, 0)
|
|
assert.equal(first.flagFailed, 2)
|
|
assert.equal(errors(s).length, 0)
|
|
messages.set(3, mime(3))
|
|
assert.equal((await worker.run('support')).imported, 1)
|
|
state.flagsError = null
|
|
assert.equal((await worker.run('support')).imported, 0)
|
|
assert.equal(s.get('SELECT count(*) n FROM inbound_receipts').n, 3)
|
|
assert.equal(s.get('SELECT count(*) n FROM inbound_failures').n, 0)
|
|
assert.equal(s.get("SELECT error FROM queue_inbound WHERE queue_id='support'").error, null)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|
|
|
|
test('Failure cooldown does not cross a changed UIDVALIDITY', async () => {
|
|
const { db, s } = setup()
|
|
try {
|
|
const messages = new Map([[1, mime(1, false)]]),
|
|
state = { validity: 1n }
|
|
const clock = () => new Date('2030-01-01T00:00:00Z')
|
|
await new InboundWorker(s, { clientFactory: fake(messages, state), clock }).run('support')
|
|
messages.set(1, mime(1))
|
|
state.validity = 2n
|
|
const result = await new InboundWorker(s, { clientFactory: fake(messages, state), clock }).run(
|
|
'support',
|
|
)
|
|
assert.equal(result.imported, 1)
|
|
assert.equal(result.retried, 0)
|
|
assert.equal(result.pending, 0)
|
|
} finally {
|
|
db.close()
|
|
}
|
|
})
|