SMTP, IMAP und Cron-Konfiguration ansehen
diff --git a/docs/images/mail-import-errors.jpg b/docs/images/mail-import-errors.jpg
new file mode 100644
index 0000000..f0642b3
Binary files /dev/null and b/docs/images/mail-import-errors.jpg differ
diff --git a/package.json b/package.json
index 20d8f14..16e7002 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
"dev": "concurrently -k \"node --watch server/index.js\" \"vite --host 127.0.0.1\"",
"start": "node server/index.js",
"build": "panda codegen && tsc --noEmit && vite build",
- "test": "node --test tests/service.test.js tests/mail-connections.test.js tests/collaboration.test.js tests/organization.test.js tests/pagination.test.js",
+ "test": "node --test tests/service.test.js tests/mail-connections.test.js tests/collaboration.test.js tests/organization.test.js tests/pagination.test.js tests/inbound-resilience.test.js",
"prepare": "panda codegen",
"test:docker": "node tests/docker-smoke.mjs",
"test:image": "node tests/image-smoke.mjs",
diff --git a/server/app.js b/server/app.js
index c07e473..59b0942 100644
--- a/server/app.js
+++ b/server/app.js
@@ -236,7 +236,9 @@ export function createApp(db) {
})
app.post('/api/queues/:id/mail/fetch', async (req, res) => {
s.require(req.user, req.params.id, 'queue')
- res.json(await app.locals.worker.inbound.run(req.params.id, { actor: req.user.id }))
+ res.json(
+ await app.locals.worker.inbound.run(req.params.id, { actor: req.user.id, retryFailed: true }),
+ )
})
app.put('/api/queues/:id/statuses', (req, res) =>
res.json(s.saveStatuses(req.user, req.params.id, req.body.statuses, req.body.mapping)),
diff --git a/server/db.js b/server/db.js
index eb5f668..da4369f 100644
--- a/server/db.js
+++ b/server/db.js
@@ -50,6 +50,7 @@ export function openDb(file = process.env.DB_PATH || 'data/syncova.db') {
CREATE TABLE IF NOT EXISTS queue_mail(queue_id TEXT PRIMARY KEY REFERENCES queues(id),smtp TEXT NOT NULL,password TEXT NOT NULL DEFAULT '',acknowledgement TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS queue_inbound(queue_id TEXT PRIMARY KEY REFERENCES queues(id),config TEXT NOT NULL,password TEXT NOT NULL DEFAULT '',next_run TEXT,last_run TEXT,last_success TEXT,error TEXT,revision INTEGER NOT NULL DEFAULT 0);
CREATE TABLE IF NOT EXISTS inbound_receipts(queue_id TEXT REFERENCES queues(id),mailbox_key TEXT NOT NULL,uid INTEGER NOT NULL,outcome TEXT NOT NULL DEFAULT 'imported',PRIMARY KEY(queue_id,mailbox_key,uid));
+ CREATE TABLE IF NOT EXISTS inbound_failures(queue_id TEXT NOT NULL REFERENCES queues(id),mailbox_key TEXT NOT NULL,uid INTEGER NOT NULL,attempts INTEGER NOT NULL,next_retry TEXT NOT NULL,PRIMARY KEY(queue_id,mailbox_key,uid));
CREATE TABLE IF NOT EXISTS manual_requests(user_id TEXT REFERENCES users(id),request_key TEXT NOT NULL,ticket_id INTEGER REFERENCES tickets(id),PRIMARY KEY(user_id,request_key));
CREATE TABLE IF NOT EXISTS statuses(id TEXT PRIMARY KEY,queue_id TEXT REFERENCES queues(id),name TEXT NOT NULL,color TEXT NOT NULL,behavior TEXT NOT NULL,position INTEGER NOT NULL,active INTEGER NOT NULL DEFAULT 1);
CREATE TABLE IF NOT EXISTS tickets(id INTEGER PRIMARY KEY AUTOINCREMENT,subject TEXT NOT NULL,customer TEXT NOT NULL,customer_name TEXT NOT NULL,queue_id TEXT REFERENCES queues(id),status_id TEXT REFERENCES statuses(id),assignee TEXT REFERENCES users(id),due_at TEXT,timezone TEXT,revision INTEGER NOT NULL DEFAULT 0,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
diff --git a/server/inbound-errors.js b/server/inbound-errors.js
new file mode 100644
index 0000000..7467ed1
--- /dev/null
+++ b/server/inbound-errors.js
@@ -0,0 +1,71 @@
+import { HttpError } from './service.js'
+import { validEmail } from './recipients.js'
+
+const clean = (value, limit = 500) =>
+ String(value || '')
+ .replace(/[\x00-\x1f\x7f]/g, ' ')
+ .trim()
+ .slice(0, limit)
+export const retryAt = (attempts, at) =>
+ new Date(+at + [60, 300, 1800, 7200, 86400][Math.min(attempts - 1, 4)] * 1000).toISOString()
+
+export function mailIdentity(envelope = {}, parsed, size) {
+ envelope ||= {}
+ const date = parsed?.date || envelope.date
+ const subject = parsed ? parsed.subject || '' : envelope.subject
+ return {
+ subject: subject === undefined ? '' : clean(subject) || '(Ohne Betreff)',
+ from: clean(
+ (parsed?.from?.value || envelope.from || [])
+ .map((a) => (a.name && a.address ? `${a.name} <${a.address}>` : a.address || a.name))
+ .join(', '),
+ ),
+ to: clean(
+ [...(parsed?.to?.value || envelope.to || []), ...(parsed?.cc?.value || envelope.cc || [])]
+ .slice(0, 20)
+ .map((a) => a.address || a.name)
+ .join(', '),
+ 1000,
+ ),
+ date: date && Number.isFinite(+new Date(date)) ? new Date(date).toISOString() : null,
+ messageId: clean(parsed ? parsed.messageId : envelope.messageId, 998),
+ size: Number.isFinite(size) ? size : null,
+ }
+}
+
+export function mailFailure(error, stage, parsed) {
+ const rawCode =
+ error instanceof HttpError
+ ? `HTTP_${error.status}`
+ : String(error.code || error.name || 'Error')
+ const code = /^[a-z0-9_.-]{1,80}$/i.test(rawCode) ? rawCode : 'Error'
+ let reason
+ if (error.message === 'MessageTooLarge')
+ reason = 'Nachricht überschreitet das Importlimit von 20 MiB.'
+ else if (error instanceof HttpError && error.status < 500) {
+ reason = clean(error.message)
+ if (error.message === 'Ungültige E-Mail.' && parsed) {
+ const issues = []
+ if (!parsed.messageId) issues.push('Message-ID fehlt')
+ else if (parsed.messageId.length > 998) issues.push('Message-ID ist zu lang')
+ if (!validEmail(parsed.from?.value[0]?.address || ''))
+ issues.push('Absenderadresse fehlt oder ist ungültig')
+ if (issues.length) reason = `Ungültige E-Mail: ${issues.join('; ')}.`
+ }
+ } else if (/^(ETIMEDOUT|ETIMEOUT|ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|EAI_AGAIN)$/.test(code))
+ reason = 'Verbindung zum Mailserver unterbrochen oder nicht erreichbar.'
+ else if (code.startsWith('SQLITE_'))
+ reason = 'Nachricht konnte nicht in der Datenbank gespeichert werden.'
+ else
+ reason =
+ {
+ metadata: 'Nachrichtenkopf oder Größe konnte nicht vom Mailserver gelesen werden.',
+ download: 'Originalnachricht konnte nicht vollständig vom Mailserver geladen werden.',
+ parse: 'MIME-Inhalt der Nachricht konnte nicht gelesen werden.',
+ import: 'Nachricht konnte nicht als Ticket gespeichert werden.',
+ markRead: 'Nachricht wurde verarbeitet, konnte aber nicht als gelesen markiert werden.',
+ connection:
+ 'Postfach konnte nicht vollständig abgerufen werden. Verbindung, Zugangsdaten und Ordner prüfen.',
+ }[stage] || 'Nachricht konnte nicht verarbeitet werden.'
+ return { code: error.message === 'MessageTooLarge' ? 'MessageTooLarge' : code, reason, stage }
+}
diff --git a/server/inbound.js b/server/inbound.js
index 0f287b0..a21dabb 100644
--- a/server/inbound.js
+++ b/server/inbound.js
@@ -4,6 +4,7 @@ import { CronExpressionParser } from 'cron-parser'
import { encryptSecret, decryptSecret } from './secrets.js'
import { HttpError } from './service.js'
import { now } from './db.js'
+import { mailIdentity, mailFailure, retryAt } from './inbound-errors.js'
export function nextFetch(config, at = new Date()) {
if (!config.enabled) return null
if (config.schedule.mode === 'interval')
@@ -230,7 +231,7 @@ export class InboundWorker {
}
await Promise.all(jobs)
}
- async run(id, { actor = 'IMAP-Abrufprozess' } = {}) {
+ async run(id, { actor = 'IMAP-Abrufprozess', retryFailed = false } = {}) {
if (this.running.has(id)) throw new HttpError(409, 'Für diese Queue läuft bereits ein Abruf.')
const row = ensure(this.s, id),
config = JSON.parse(row.config)
@@ -238,7 +239,10 @@ export class InboundWorker {
this.running.add(id)
let client,
imported = 0,
- failed = 0
+ failed = 0,
+ pending = 0,
+ flagFailed = 0,
+ retried = 0
const started = this.clock().toISOString()
this.s.run(
'UPDATE queue_inbound SET last_run=?,next_run=? WHERE queue_id=? AND revision=?',
@@ -252,9 +256,9 @@ export class InboundWorker {
await client.connect()
const lock = await client.getMailboxLock(config.folder)
try {
- const addresses = this.s
- .queue(id)
- .addresses.filter((a) => a.incoming)
+ const queue = this.s.queue(id)
+ const addresses = queue.addresses
+ .filter((a) => a.incoming)
.map((a) => a.email.toLowerCase())
.sort()
const validity = String(client.mailbox.uidValidity),
@@ -290,22 +294,78 @@ export class InboundWorker {
storedReceipts.filter((r) => r.outcome !== 'skipped').map((r) => r.uid),
)
const known = ids.filter((uid) => processed.has(uid))
- if (config.markRead && known.length)
- await client.messageFlagsAdd(known.slice(0, 100), ['\\Seen'], { uid: true })
- for (const uid of ids.filter((uid) => !receipts.has(uid)).slice(0, 100)) {
+ const markRead = async (uids, identity = {}) => {
+ if (!config.markRead) return
+ try {
+ await client.messageFlagsAdd(uids, ['\\Seen'], { uid: true })
+ } catch (e) {
+ flagFailed++
+ this.s.audit(
+ actor,
+ 'Gelesen-Markierung fehlgeschlagen',
+ id,
+ null,
+ {
+ ...mailFailure(e, 'markRead'),
+ ...identity,
+ queue: queue.name,
+ folder: config.folder,
+ uid: uids,
+ uidValidity: validity,
+ continuation:
+ 'Bereits verarbeitet; kein erneuter Ticketimport. Markierung wird beim nächsten Abruf erneut versucht.',
+ },
+ null,
+ id,
+ )
+ }
+ }
+ if (known.length) await markRead(known.slice(0, 100))
+ const failures = new Map(
+ this.s
+ .all(
+ 'SELECT uid,attempts,next_retry FROM inbound_failures WHERE queue_id=? AND mailbox_key=?',
+ id,
+ mailboxKey,
+ )
+ .map((f) => [f.uid, f]),
+ )
+ const fresh = ids.filter((uid) => !receipts.has(uid) && !failures.has(uid)).slice(0, 100)
+ const retries = ids
+ .filter(
+ (uid) =>
+ !receipts.has(uid) &&
+ failures.has(uid) &&
+ (retryFailed || failures.get(uid).next_retry <= this.clock().toISOString()),
+ )
+ .sort(
+ (a, b) => failures.get(a).next_retry.localeCompare(failures.get(b).next_retry) || a - b,
+ )
+ .slice(0, 10)
+ for (const uid of [...fresh, ...retries]) {
if (
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
row.revision
)
break
+ let meta,
+ parsed,
+ size,
+ stage = 'metadata'
+ if (failures.has(uid)) retried++
try {
- const meta = await client.fetchOne(uid, { size: true }, { uid: true })
+ meta = await client.fetchOne(uid, { size: true, envelope: true }, { uid: true })
if (!meta) continue
+ size = meta.size
if (meta.size > 20 * 1024 * 1024) throw Error('MessageTooLarge')
+ stage = 'download'
const message = await client.fetchOne(uid, { source: true }, { uid: true })
if (!message) continue
+ size = message.source.length
if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge')
+ stage = 'parse'
const p = await simpleParser(message.source, { keepCidLinks: true })
+ parsed = p
const to = [...(p.to?.value || []), ...(p.cc?.value || [])]
.map((x) => x.address)
.filter(Boolean)
@@ -321,6 +381,13 @@ export class InboundWorker {
mailboxKey,
uid,
)
+ this.s.run(
+ 'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
+ id,
+ mailboxKey,
+ uid,
+ )
+ failures.delete(uid)
continue
}
const data = {
@@ -343,6 +410,7 @@ export class InboundWorker {
contentId: a.contentId || a.cid,
})),
}
+ stage = 'import'
const result = this.s.tx(() => {
const r = this.s.ingest(data, id)
this.s.run(
@@ -351,43 +419,85 @@ export class InboundWorker {
mailboxKey,
uid,
)
+ this.s.run(
+ 'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
+ id,
+ mailboxKey,
+ uid,
+ )
return r
})
+ failures.delete(uid)
if (!result.ignored && !result.duplicate) imported++
- if (config.markRead) await client.messageFlagsAdd(uid, ['\\Seen'], { uid: true })
+ await markRead(uid, mailIdentity(meta.envelope, parsed, size))
} catch (e) {
failed++
+ const attempts = (failures.get(uid)?.attempts || 0) + 1
+ const nextRetry = retryAt(attempts, this.clock())
+ this.s.run(
+ `INSERT INTO inbound_failures VALUES(?,?,?,?,?) ON CONFLICT(queue_id,mailbox_key,uid)
+ DO UPDATE SET attempts=excluded.attempts,next_retry=excluded.next_retry`,
+ id,
+ mailboxKey,
+ uid,
+ attempts,
+ nextRetry,
+ )
+ failures.set(uid, { attempts, next_retry: nextRetry })
this.s.audit(
actor,
'Nachricht konnte nicht importiert werden',
`${id}:${uid}`,
null,
- { code: String(e.code || e.name || 'Error') },
+ {
+ ...mailIdentity(meta?.envelope, parsed, size),
+ ...mailFailure(e, stage, parsed),
+ queue: queue.name,
+ folder: config.folder,
+ uid,
+ uidValidity: validity,
+ attempts,
+ nextRetry,
+ continuation:
+ 'Abruf läuft mit den übrigen Nachrichten weiter. Diese Mail bleibt unverändert im Postfach und wird separat erneut versucht.',
+ },
null,
id,
)
}
}
+ pending = ids.filter((uid) => !receipts.has(uid) && failures.has(uid)).length
} finally {
lock.release()
}
await client.logout()
this.s.run(
'UPDATE queue_inbound SET last_success=?,error=?,next_run=? WHERE queue_id=? AND revision=?',
- failed ? row.last_success : this.clock().toISOString(),
- failed
- ? `${failed} Nachricht(en) konnten nicht verarbeitet werden. Systemprotokoll prüfen.`
+ pending || flagFailed ? row.last_success : this.clock().toISOString(),
+ pending || flagFailed
+ ? `${pending} Nachricht(en) warten auf erneuten Import; ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Mails werden weiter abgerufen. Systemprotokoll prüfen.`
: null,
nextFetch(config, this.clock()),
id,
row.revision,
)
- this.s.audit(actor, 'Postfach abgerufen', id, null, { imported, failed }, null, id)
+ this.s.audit(
+ actor,
+ 'Postfach abgerufen',
+ id,
+ null,
+ { imported, failed, pending, retried, flagFailed },
+ null,
+ id,
+ )
return {
- ok: !failed,
+ ok: !pending && !flagFailed,
imported,
failed,
- message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${failed} Fehler.`,
+ pending,
+ retried,
+ flagFailed,
+ message: `Abruf abgeschlossen: ${imported} neue Nachricht(en), ${failed} Importfehler, ${pending} zur Wiederholung vorgemerkt, ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Nachrichten werden nach Zeitplan abgerufen.`,
}
} catch (e) {
this.s.run(
@@ -402,7 +512,7 @@ export class InboundWorker {
'Postfachabruf fehlgeschlagen',
id,
null,
- { code: String(e.code || e.name || 'Error') },
+ { ...mailFailure(e, 'connection'), folder: config.folder, imported, failed },
null,
id,
)
diff --git a/server/service.js b/server/service.js
index 5998dad..d8d3ca5 100644
--- a/server/service.js
+++ b/server/service.js
@@ -917,6 +917,7 @@ export class Service {
this.run('DELETE FROM queue_tags WHERE queue_id=?', id)
this.run('DELETE FROM queue_inbound WHERE queue_id=?', id)
this.run('DELETE FROM inbound_receipts WHERE queue_id=?', id)
+ this.run('DELETE FROM inbound_failures WHERE queue_id=?', id)
this.run('UPDATE statuses SET active=0 WHERE queue_id=?', id)
this.run(
"UPDATE queues SET deleted_at=?,addresses='[]',signatures='[]' WHERE id=?",
diff --git a/src/InboundSettings.tsx b/src/InboundSettings.tsx
index 4ca4c5e..50daa70 100644
--- a/src/InboundSettings.tsx
+++ b/src/InboundSettings.tsx
@@ -224,7 +224,11 @@ export function InboundSettings({ config: c, update, password, setPassword, busy
Der Abruf läuft im Syncova-Serverprozess. Der Server muss gestartet sein; nach einem
- Neustart wird ein überfälliger Abruf einmal nachgeholt.
+ Neustart wird ein überfälliger Abruf einmal nachgeholt. Einzelne Importfehler stoppen den
+ Abruf nicht. Pro Durchlauf werden bis zu 100 neue Nachrichten und zusätzlich bis zu 10
+ fehlgeschlagene Mails verarbeitet. Wiederholungen erfolgen mit wachsendem Abstand; „Jetzt
+ abrufen“ versucht bis zu 10 vorgemerkte Mails auch vor Ablauf der Wartezeit erneut.
+ Einzelheiten stehen im Systemprotokoll.
>
)
diff --git a/src/MailImportLog.tsx b/src/MailImportLog.tsx
new file mode 100644
index 0000000..25f0da1
--- /dev/null
+++ b/src/MailImportLog.tsx
@@ -0,0 +1,86 @@
+import { date } from './api'
+
+export function MailImportLog({ entry }: { entry: any }) {
+ let info: any
+ try {
+ info = JSON.parse(entry.after_value || 'null')
+ } catch {
+ return null
+ }
+ if (!info) return null
+ if (entry.action === 'Postfach abgerufen')
+ return (
+
+ {info.imported || 0} neu importiert · {info.failed || 0} Importfehler
+ {info.pending != null && ` · ${info.pending} zur Wiederholung vorgemerkt`}
+ {!!info.flagFailed && ` · ${info.flagFailed} Fehler bei der Gelesen-Markierung`}
+
+ )
+ if (
+ ![
+ 'Nachricht konnte nicht importiert werden',
+ 'Gelesen-Markierung fehlgeschlagen',
+ 'Postfachabruf fehlgeschlagen',
+ ].includes(entry.action)
+ )
+ return null
+ const stages: Record = {
+ metadata: 'Nachrichtenkopf lesen',
+ download: 'Nachricht herunterladen',
+ parse: 'MIME-Inhalt lesen',
+ import: 'Ticket speichern',
+ markRead: 'Als gelesen markieren',
+ connection: 'Postfachverbindung',
+ }
+ return (
+
+
+ {info.reason ||
+ 'Älterer Protokolleintrag ohne Fehlerbeschreibung. Neue Importversuche protokollieren die Maildaten und die Ursache.'}
+
+
+ {[
+ ['Betreff', info.stage === 'connection' ? null : info.subject || 'Nicht verfügbar'],
+ ['Absender', info.stage === 'connection' ? null : info.from || 'Nicht verfügbar'],
+ ['Empfänger (An/Cc)', info.to],
+ [
+ 'Mail-Datum',
+ info.stage === 'connection' ? null : info.date ? date(info.date) : 'Nicht verfügbar',
+ ],
+ [
+ 'Queue / Ordner',
+ [info.queue || entry.queue_id, info.folder].filter(Boolean).join(' / '),
+ ],
+ [
+ 'IMAP-UID',
+ Array.isArray(info.uid)
+ ? info.uid.join(', ')
+ : info.uid || entry.entity.split(':').slice(1).join(':'),
+ ],
+ ['Message-ID', info.messageId],
+ [
+ 'Größe',
+ info.size != null
+ ? info.size < 1024
+ ? `${info.size} Byte`
+ : info.size < 1024 * 1024
+ ? `${(info.size / 1024).toLocaleString('de-DE', { maximumFractionDigits: 1 })} KiB`
+ : `${(info.size / 1024 / 1024).toLocaleString('de-DE', { maximumFractionDigits: 2 })} MiB`
+ : null,
+ ],
+ ['Fehlerschritt / Code', [stages[info.stage], info.code].filter(Boolean).join(' · ')],
+ ['Versuch', info.attempts],
+ ['Frühestens erneut', info.nextRetry ? date(info.nextRetry) : null],
+ ]
+ .filter(([, value]) => value != null && value !== '')
+ .map(([label, value]) => (
+
+
- {label}
+ - {value}
+
+ ))}
+
+ {info.continuation &&
{info.continuation}
}
+
+ )
+}
diff --git a/src/Settings.tsx b/src/Settings.tsx
index cf8cc54..4136773 100644
--- a/src/Settings.tsx
+++ b/src/Settings.tsx
@@ -22,6 +22,7 @@ import { SignatureBodyEditor } from './HtmlPreview'
import { QueueMailSettings } from './QueueMailSettings'
import { ReplyTemplateEditor } from './ReplyTemplates'
import { QueueTagsEditor } from './TicketOrganization'
+import { MailImportLog } from './MailImportLog'
type D = any
const behaviorNames: D = {
new: 'Neue Anfrage',
@@ -238,6 +239,7 @@ export function SettingsPage({ page, boot, refresh, run, can }: D) {
{a.actor_name || boot.users.find((u: D) => u.id === a.actor)?.name || a.actor} ·{' '}
{a.entity}
+
Details
diff --git a/src/styles.css b/src/styles.css
index f37bd81..9ec8d54 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -1556,6 +1556,34 @@ main {
color: var(--muted);
font-size: 10px;
}
+.log-entry > div {
+ min-width: 0;
+ flex: 1;
+}
+.mail-import-log {
+ margin-top: 12px;
+ overflow-wrap: anywhere;
+}
+.settings-card .mail-import-log p,
+.settings-card .mail-run-summary {
+ margin: 8px 0;
+}
+.mail-import-reason {
+ font-weight: 600;
+}
+.mail-import-log dl {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(min(260px, 100%), 1fr));
+ gap: 10px 24px;
+ margin: 12px 0;
+}
+.mail-import-log dt {
+ color: var(--muted);
+ font-size: 11px;
+}
+.mail-import-log dd {
+ margin: 2px 0 0;
+}
.log-entry details {
max-width: 65%;
}
diff --git a/tests/inbound-resilience.test.js b/tests/inbound-resilience.test.js
new file mode 100644
index 0000000..3273f4d
--- /dev/null
+++ b/tests/inbound-resilience.test.js
@@ -0,0 +1,260 @@
+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 \r\nTo: support@syncova.local\r\n${valid ? `Message-ID: \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: ``,
+ },
+ }
+ 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 ')
+ 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=''").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()
+ }
+})