Keep IMAP imports progressing and expose actionable mail errors
This commit is contained in:
parent
d879049cfc
commit
cbf2e9f139
@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
## Aktueller Stand
|
## Aktueller Stand
|
||||||
|
|
||||||
|
- Robuster IMAP-Import: neue Mails werden auch bei mehr als 100 fehlerhaften Nachrichten weiter verarbeitet, persistente Wiederholungen mit wachsendem Abstand und getrennte Behandlung fehlgeschlagener Gelesen-Markierungen.
|
||||||
|
- Verständliche Importfehler im Systemprotokoll mit Maildaten, Ursache, Verarbeitungsschritt, Versuch und nächstem Wiederholungszeitpunkt.
|
||||||
- Favicon mit dem lila Markenzeichen und weißem Ebenen-Symbol aus der Navigation.
|
- Favicon mit dem lila Markenzeichen und weißem Ebenen-Symbol aus der Navigation.
|
||||||
- Scrollbare Sidebar-Navigation für viele Queues; begrenzte, horizontal scrollbar erreichbare Queue-Auswahl in den Einstellungen und kompakte Darstellung langer Queue-Namen.
|
- Scrollbare Sidebar-Navigation für viele Queues; begrenzte, horizontal scrollbar erreichbare Queue-Auswahl in den Einstellungen und kompakte Darstellung langer Queue-Namen.
|
||||||
- Serverseitige Ticket-Pagination mit 25/50/100 Einträgen, SQL-Filtern und stabiler Sortierung nach Ticketnummer, Datum oder Betreff. Vorschauen und Tags werden nur für die aktuelle Seite geladen.
|
- Serverseitige Ticket-Pagination mit 25/50/100 Einträgen, SQL-Filtern und stabiler Sortierung nach Ticketnummer, Datum oder Betreff. Vorschauen und Tags werden nur für die aktuelle Seite geladen.
|
||||||
|
|||||||
11
README.md
11
README.md
@ -256,6 +256,17 @@ Alles liegt unter **Einstellungen → Queue → Mail-Einstellungen**. Dafür ist
|
|||||||
|
|
||||||
Beispiele: `*/5 * * * *` alle fünf Minuten; `0 8-18 * * 1-5` werktags stündlich zwischen 8 und 18 Uhr. Jeder Queue-Zeitplan ist unabhängig. Gleichzeitige Abrufe derselben Queue werden verhindert; UID-Deduplizierung und nächster Abruf bleiben nach Neustarts erhalten.
|
Beispiele: `*/5 * * * *` alle fünf Minuten; `0 8-18 * * 1-5` werktags stündlich zwischen 8 und 18 Uhr. Jeder Queue-Zeitplan ist unabhängig. Gleichzeitige Abrufe derselben Queue werden verhindert; UID-Deduplizierung und nächster Abruf bleiben nach Neustarts erhalten.
|
||||||
|
|
||||||
|
**Einzelne Importfehler stoppen den übrigen Abruf nicht.** Pro Durchlauf werden bis zu 100 noch nicht verarbeitete Nachrichten und zusätzlich bis zu 10 vorgemerkte Fehlerfälle versucht. Fehlgeschlagene Mails bleiben unverändert im Postfach. Ihre Wiederholungsplanung wird dauerhaft gespeichert und verwendet wachsende Wartezeiten von 1, 5 und 30 Minuten, danach 2 Stunden und schließlich maximal 24 Stunden. Der Versuch erfolgt frühestens nach dieser Wartezeit beim nächsten Queue-Abruf. Neue Mails erhalten weiterhin ihre eigenen Plätze; auch mehr als 100 fehlerhafte Mails blockieren dadurch keine späteren Nachrichten. **Speichern & jetzt abrufen** versucht zusätzlich bis zu 10 Fehlerfälle vor Ablauf der Wartezeit erneut.
|
||||||
|
|
||||||
|
Im **Systemprotokoll** stehen bei neuen Importfehlern Betreff, Absender, An-/Cc-Empfänger, Mail-Datum, Queue/Ordner, IMAP-UID, Message-ID und Größe, soweit bereits lesbar. Fehlerursache, Verarbeitungsschritt, Versuchszähler und frühester Wiederholungszeitpunkt werden direkt angezeigt. Bei einer zu großen Nachricht werden die Kopfzeilen bereits vor dem Download gelesen. Nicht verfügbare Angaben werden entsprechend ausgewiesen; ältere Protokolleinträge lassen sich nicht rückwirkend ergänzen. Mailtexte, Anhänge, Zugangsdaten und rohe Serverfehlermeldungen werden dabei nicht protokolliert. Ein fehlgeschlagenes Setzen des Gelesen-Flags wird getrennt gemeldet und löst keinen erneuten Ticketimport aus. Verbindungs- oder Datenbankausfälle können einen gesamten Abruf unterbrechen; der nächste reguläre Versuch bleibt eingeplant.
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Importfehler im Systemprotokoll ansehen</summary>
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>SMTP, IMAP und Cron-Konfiguration ansehen</summary>
|
<summary>SMTP, IMAP und Cron-Konfiguration ansehen</summary>
|
||||||
|
|
||||||
|
|||||||
BIN
docs/images/mail-import-errors.jpg
Normal file
BIN
docs/images/mail-import-errors.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
@ -7,7 +7,7 @@
|
|||||||
"dev": "concurrently -k \"node --watch server/index.js\" \"vite --host 127.0.0.1\"",
|
"dev": "concurrently -k \"node --watch server/index.js\" \"vite --host 127.0.0.1\"",
|
||||||
"start": "node server/index.js",
|
"start": "node server/index.js",
|
||||||
"build": "panda codegen && tsc --noEmit && vite build",
|
"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",
|
"prepare": "panda codegen",
|
||||||
"test:docker": "node tests/docker-smoke.mjs",
|
"test:docker": "node tests/docker-smoke.mjs",
|
||||||
"test:image": "node tests/image-smoke.mjs",
|
"test:image": "node tests/image-smoke.mjs",
|
||||||
|
|||||||
@ -236,7 +236,9 @@ export function createApp(db) {
|
|||||||
})
|
})
|
||||||
app.post('/api/queues/:id/mail/fetch', async (req, res) => {
|
app.post('/api/queues/:id/mail/fetch', async (req, res) => {
|
||||||
s.require(req.user, req.params.id, 'queue')
|
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) =>
|
app.put('/api/queues/:id/statuses', (req, res) =>
|
||||||
res.json(s.saveStatuses(req.user, req.params.id, req.body.statuses, req.body.mapping)),
|
res.json(s.saveStatuses(req.user, req.params.id, req.body.statuses, req.body.mapping)),
|
||||||
|
|||||||
@ -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_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 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_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 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 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);
|
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);
|
||||||
|
|||||||
71
server/inbound-errors.js
Normal file
71
server/inbound-errors.js
Normal file
@ -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 }
|
||||||
|
}
|
||||||
@ -4,6 +4,7 @@ import { CronExpressionParser } from 'cron-parser'
|
|||||||
import { encryptSecret, decryptSecret } from './secrets.js'
|
import { encryptSecret, decryptSecret } from './secrets.js'
|
||||||
import { HttpError } from './service.js'
|
import { HttpError } from './service.js'
|
||||||
import { now } from './db.js'
|
import { now } from './db.js'
|
||||||
|
import { mailIdentity, mailFailure, retryAt } from './inbound-errors.js'
|
||||||
export function nextFetch(config, at = new Date()) {
|
export function nextFetch(config, at = new Date()) {
|
||||||
if (!config.enabled) return null
|
if (!config.enabled) return null
|
||||||
if (config.schedule.mode === 'interval')
|
if (config.schedule.mode === 'interval')
|
||||||
@ -230,7 +231,7 @@ export class InboundWorker {
|
|||||||
}
|
}
|
||||||
await Promise.all(jobs)
|
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.')
|
if (this.running.has(id)) throw new HttpError(409, 'Für diese Queue läuft bereits ein Abruf.')
|
||||||
const row = ensure(this.s, id),
|
const row = ensure(this.s, id),
|
||||||
config = JSON.parse(row.config)
|
config = JSON.parse(row.config)
|
||||||
@ -238,7 +239,10 @@ export class InboundWorker {
|
|||||||
this.running.add(id)
|
this.running.add(id)
|
||||||
let client,
|
let client,
|
||||||
imported = 0,
|
imported = 0,
|
||||||
failed = 0
|
failed = 0,
|
||||||
|
pending = 0,
|
||||||
|
flagFailed = 0,
|
||||||
|
retried = 0
|
||||||
const started = this.clock().toISOString()
|
const started = this.clock().toISOString()
|
||||||
this.s.run(
|
this.s.run(
|
||||||
'UPDATE queue_inbound SET last_run=?,next_run=? WHERE queue_id=? AND revision=?',
|
'UPDATE queue_inbound SET last_run=?,next_run=? WHERE queue_id=? AND revision=?',
|
||||||
@ -252,9 +256,9 @@ export class InboundWorker {
|
|||||||
await client.connect()
|
await client.connect()
|
||||||
const lock = await client.getMailboxLock(config.folder)
|
const lock = await client.getMailboxLock(config.folder)
|
||||||
try {
|
try {
|
||||||
const addresses = this.s
|
const queue = this.s.queue(id)
|
||||||
.queue(id)
|
const addresses = queue.addresses
|
||||||
.addresses.filter((a) => a.incoming)
|
.filter((a) => a.incoming)
|
||||||
.map((a) => a.email.toLowerCase())
|
.map((a) => a.email.toLowerCase())
|
||||||
.sort()
|
.sort()
|
||||||
const validity = String(client.mailbox.uidValidity),
|
const validity = String(client.mailbox.uidValidity),
|
||||||
@ -290,22 +294,78 @@ export class InboundWorker {
|
|||||||
storedReceipts.filter((r) => r.outcome !== 'skipped').map((r) => r.uid),
|
storedReceipts.filter((r) => r.outcome !== 'skipped').map((r) => r.uid),
|
||||||
)
|
)
|
||||||
const known = ids.filter((uid) => processed.has(uid))
|
const known = ids.filter((uid) => processed.has(uid))
|
||||||
if (config.markRead && known.length)
|
const markRead = async (uids, identity = {}) => {
|
||||||
await client.messageFlagsAdd(known.slice(0, 100), ['\\Seen'], { uid: true })
|
if (!config.markRead) return
|
||||||
for (const uid of ids.filter((uid) => !receipts.has(uid)).slice(0, 100)) {
|
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 (
|
if (
|
||||||
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
this.s.get('SELECT revision FROM queue_inbound WHERE queue_id=?', id).revision !==
|
||||||
row.revision
|
row.revision
|
||||||
)
|
)
|
||||||
break
|
break
|
||||||
|
let meta,
|
||||||
|
parsed,
|
||||||
|
size,
|
||||||
|
stage = 'metadata'
|
||||||
|
if (failures.has(uid)) retried++
|
||||||
try {
|
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
|
if (!meta) continue
|
||||||
|
size = meta.size
|
||||||
if (meta.size > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
if (meta.size > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
||||||
|
stage = 'download'
|
||||||
const message = await client.fetchOne(uid, { source: true }, { uid: true })
|
const message = await client.fetchOne(uid, { source: true }, { uid: true })
|
||||||
if (!message) continue
|
if (!message) continue
|
||||||
|
size = message.source.length
|
||||||
if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
if (message.source.length > 20 * 1024 * 1024) throw Error('MessageTooLarge')
|
||||||
|
stage = 'parse'
|
||||||
const p = await simpleParser(message.source, { keepCidLinks: true })
|
const p = await simpleParser(message.source, { keepCidLinks: true })
|
||||||
|
parsed = p
|
||||||
const to = [...(p.to?.value || []), ...(p.cc?.value || [])]
|
const to = [...(p.to?.value || []), ...(p.cc?.value || [])]
|
||||||
.map((x) => x.address)
|
.map((x) => x.address)
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
@ -321,6 +381,13 @@ export class InboundWorker {
|
|||||||
mailboxKey,
|
mailboxKey,
|
||||||
uid,
|
uid,
|
||||||
)
|
)
|
||||||
|
this.s.run(
|
||||||
|
'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
|
||||||
|
id,
|
||||||
|
mailboxKey,
|
||||||
|
uid,
|
||||||
|
)
|
||||||
|
failures.delete(uid)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
const data = {
|
const data = {
|
||||||
@ -343,6 +410,7 @@ export class InboundWorker {
|
|||||||
contentId: a.contentId || a.cid,
|
contentId: a.contentId || a.cid,
|
||||||
})),
|
})),
|
||||||
}
|
}
|
||||||
|
stage = 'import'
|
||||||
const result = this.s.tx(() => {
|
const result = this.s.tx(() => {
|
||||||
const r = this.s.ingest(data, id)
|
const r = this.s.ingest(data, id)
|
||||||
this.s.run(
|
this.s.run(
|
||||||
@ -351,43 +419,85 @@ export class InboundWorker {
|
|||||||
mailboxKey,
|
mailboxKey,
|
||||||
uid,
|
uid,
|
||||||
)
|
)
|
||||||
|
this.s.run(
|
||||||
|
'DELETE FROM inbound_failures WHERE queue_id=? AND mailbox_key=? AND uid=?',
|
||||||
|
id,
|
||||||
|
mailboxKey,
|
||||||
|
uid,
|
||||||
|
)
|
||||||
return r
|
return r
|
||||||
})
|
})
|
||||||
|
failures.delete(uid)
|
||||||
if (!result.ignored && !result.duplicate) imported++
|
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) {
|
} catch (e) {
|
||||||
failed++
|
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(
|
this.s.audit(
|
||||||
actor,
|
actor,
|
||||||
'Nachricht konnte nicht importiert werden',
|
'Nachricht konnte nicht importiert werden',
|
||||||
`${id}:${uid}`,
|
`${id}:${uid}`,
|
||||||
null,
|
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,
|
null,
|
||||||
id,
|
id,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
pending = ids.filter((uid) => !receipts.has(uid) && failures.has(uid)).length
|
||||||
} finally {
|
} finally {
|
||||||
lock.release()
|
lock.release()
|
||||||
}
|
}
|
||||||
await client.logout()
|
await client.logout()
|
||||||
this.s.run(
|
this.s.run(
|
||||||
'UPDATE queue_inbound SET last_success=?,error=?,next_run=? WHERE queue_id=? AND revision=?',
|
'UPDATE queue_inbound SET last_success=?,error=?,next_run=? WHERE queue_id=? AND revision=?',
|
||||||
failed ? row.last_success : this.clock().toISOString(),
|
pending || flagFailed ? row.last_success : this.clock().toISOString(),
|
||||||
failed
|
pending || flagFailed
|
||||||
? `${failed} Nachricht(en) konnten nicht verarbeitet werden. Systemprotokoll prüfen.`
|
? `${pending} Nachricht(en) warten auf erneuten Import; ${flagFailed} Fehler bei der Gelesen-Markierung. Weitere Mails werden weiter abgerufen. Systemprotokoll prüfen.`
|
||||||
: null,
|
: null,
|
||||||
nextFetch(config, this.clock()),
|
nextFetch(config, this.clock()),
|
||||||
id,
|
id,
|
||||||
row.revision,
|
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 {
|
return {
|
||||||
ok: !failed,
|
ok: !pending && !flagFailed,
|
||||||
imported,
|
imported,
|
||||||
failed,
|
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) {
|
} catch (e) {
|
||||||
this.s.run(
|
this.s.run(
|
||||||
@ -402,7 +512,7 @@ export class InboundWorker {
|
|||||||
'Postfachabruf fehlgeschlagen',
|
'Postfachabruf fehlgeschlagen',
|
||||||
id,
|
id,
|
||||||
null,
|
null,
|
||||||
{ code: String(e.code || e.name || 'Error') },
|
{ ...mailFailure(e, 'connection'), folder: config.folder, imported, failed },
|
||||||
null,
|
null,
|
||||||
id,
|
id,
|
||||||
)
|
)
|
||||||
|
|||||||
@ -917,6 +917,7 @@ export class Service {
|
|||||||
this.run('DELETE FROM queue_tags WHERE queue_id=?', id)
|
this.run('DELETE FROM queue_tags WHERE queue_id=?', id)
|
||||||
this.run('DELETE FROM queue_inbound 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_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 statuses SET active=0 WHERE queue_id=?', id)
|
||||||
this.run(
|
this.run(
|
||||||
"UPDATE queues SET deleted_at=?,addresses='[]',signatures='[]' WHERE id=?",
|
"UPDATE queues SET deleted_at=?,addresses='[]',signatures='[]' WHERE id=?",
|
||||||
|
|||||||
@ -224,7 +224,11 @@ export function InboundSettings({ config: c, update, password, setPassword, busy
|
|||||||
</div>
|
</div>
|
||||||
<p className="cron-help">
|
<p className="cron-help">
|
||||||
Der Abruf läuft im Syncova-Serverprozess. Der Server muss gestartet sein; nach einem
|
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.
|
||||||
</p>
|
</p>
|
||||||
</>
|
</>
|
||||||
)
|
)
|
||||||
|
|||||||
86
src/MailImportLog.tsx
Normal file
86
src/MailImportLog.tsx
Normal file
@ -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 (
|
||||||
|
<p className="mail-run-summary">
|
||||||
|
{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`}
|
||||||
|
</p>
|
||||||
|
)
|
||||||
|
if (
|
||||||
|
![
|
||||||
|
'Nachricht konnte nicht importiert werden',
|
||||||
|
'Gelesen-Markierung fehlgeschlagen',
|
||||||
|
'Postfachabruf fehlgeschlagen',
|
||||||
|
].includes(entry.action)
|
||||||
|
)
|
||||||
|
return null
|
||||||
|
const stages: Record<string, string> = {
|
||||||
|
metadata: 'Nachrichtenkopf lesen',
|
||||||
|
download: 'Nachricht herunterladen',
|
||||||
|
parse: 'MIME-Inhalt lesen',
|
||||||
|
import: 'Ticket speichern',
|
||||||
|
markRead: 'Als gelesen markieren',
|
||||||
|
connection: 'Postfachverbindung',
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="mail-import-log">
|
||||||
|
<p className="mail-import-reason">
|
||||||
|
{info.reason ||
|
||||||
|
'Älterer Protokolleintrag ohne Fehlerbeschreibung. Neue Importversuche protokollieren die Maildaten und die Ursache.'}
|
||||||
|
</p>
|
||||||
|
<dl>
|
||||||
|
{[
|
||||||
|
['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]) => (
|
||||||
|
<div key={label}>
|
||||||
|
<dt>{label}</dt>
|
||||||
|
<dd>{value}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
{info.continuation && <p>{info.continuation}</p>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -22,6 +22,7 @@ import { SignatureBodyEditor } from './HtmlPreview'
|
|||||||
import { QueueMailSettings } from './QueueMailSettings'
|
import { QueueMailSettings } from './QueueMailSettings'
|
||||||
import { ReplyTemplateEditor } from './ReplyTemplates'
|
import { ReplyTemplateEditor } from './ReplyTemplates'
|
||||||
import { QueueTagsEditor } from './TicketOrganization'
|
import { QueueTagsEditor } from './TicketOrganization'
|
||||||
|
import { MailImportLog } from './MailImportLog'
|
||||||
type D = any
|
type D = any
|
||||||
const behaviorNames: D = {
|
const behaviorNames: D = {
|
||||||
new: 'Neue Anfrage',
|
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.actor_name || boot.users.find((u: D) => u.id === a.actor)?.name || a.actor} ·{' '}
|
||||||
{a.entity}
|
{a.entity}
|
||||||
</small>
|
</small>
|
||||||
|
<MailImportLog entry={a} />
|
||||||
</div>
|
</div>
|
||||||
<details>
|
<details>
|
||||||
<summary>Details</summary>
|
<summary>Details</summary>
|
||||||
|
|||||||
@ -1556,6 +1556,34 @@ main {
|
|||||||
color: var(--muted);
|
color: var(--muted);
|
||||||
font-size: 10px;
|
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 {
|
.log-entry details {
|
||||||
max-width: 65%;
|
max-width: 65%;
|
||||||
}
|
}
|
||||||
|
|||||||
260
tests/inbound-resilience.test.js
Normal file
260
tests/inbound-resilience.test.js
Normal file
@ -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 <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()
|
||||||
|
}
|
||||||
|
})
|
||||||
Loading…
Reference in New Issue
Block a user