syncova-ticket/server/worker.js
Weapie 0e8be73fec
All checks were successful
Tests und Docker-Image / Tests und Frontend-Build (push) Successful in 44s
Tests und Docker-Image / Leeres Produktionsimage bauen und veröffentlichen (push) Successful in 2m0s
Document Syncova with demo screenshots and harden production deployment
2026-11-03 18:10:13 +01:00

177 lines
5.9 KiB
JavaScript

import { smtpTransport } from './mail-config.js'
import { InboundWorker } from './inbound.js'
import { uid, now } from './db.js'
export class Worker {
constructor(service, { transportFactory, inboundOptions } = {}) {
this.s = service
this.busy = false
this.inbound = new InboundWorker(service, inboundOptions)
this.transportFactory = transportFactory
// An interrupted SMTP transaction may already have been accepted. Never silently resend it.
this.s.run(
"UPDATE outbox SET state='uncertain',error='Versand beim Neustart unbestätigt; Zustellung am Mailserver prüfen.' WHERE state='sending'",
)
}
async tick() {
if (this.busy) return
this.busy = true
try {
this.s.due()
for (const job of this.s.all(
"SELECT * FROM outbox WHERE state='pending' AND next_at<=? ORDER BY next_at LIMIT 20",
now(),
)) {
let t
if (job.message_id)
t = this.s.get(
'SELECT t.* FROM tickets t JOIN messages m ON m.ticket_id=t.id WHERE m.id=?',
job.message_id,
)
if (job.notification_id) {
const n = this.s.get('SELECT * FROM notifications WHERE id=?', job.notification_id)
t = this.s.get('SELECT * FROM tickets WHERE id=?', n.ticket_id)
const u = this.s.get('SELECT * FROM users WHERE id=? AND active=1', n.user_id)
if (!u || !this.s.can(u, t.queue_id, 'view') || !JSON.parse(u.prefs)[n.event]?.email) {
this.s.run("UPDATE outbox SET state='cancelled' WHERE id=?", job.id)
continue
}
}
const payload = JSON.parse(job.payload)
const attachments = job.message_id
? this.s
.all('SELECT name,mime,content FROM attachments WHERE message_id=?', job.message_id)
.map((a) => ({ filename: a.name, contentType: a.mime, content: a.content }))
: []
if (
job.message_id &&
!this.s.queue(t.queue_id).addresses.some((a) => a.outgoing && a.email === payload.from)
) {
this.s.run(
"UPDATE outbox SET state='blocked',error='Absender nach Queue-Wechsel nicht mehr erlaubt' WHERE id=?",
job.id,
)
continue
}
let transport
try {
transport = smtpTransport(this.s, t.queue_id, this.transportFactory)
} catch (error) {
this.s.run(
"UPDATE outbox SET state='blocked',error=? WHERE id=?",
error.status === 409
? error.message
: 'SMTP-Konfiguration oder Verschlüsselungsschlüssel ungültig; Queue-Konfiguration prüfen.',
job.id,
)
this.s.audit(
'Versandprozess',
'SMTP-Konfiguration nicht verwendbar',
job.id,
null,
{ state: 'blocked' },
null,
t.queue_id,
)
continue
}
if (!transport) {
this.s.tx(() => {
this.s.run(
'INSERT OR IGNORE INTO dev_mail VALUES(?,?,?)',
job.id,
JSON.stringify({
...payload,
...(attachments.length
? {
attachments: attachments.map((a) => ({
...a,
content: a.content.toString('base64'),
encoding: 'base64',
})),
}
: {}),
}),
now(),
)
this.finish(job, t, 'development')
})
continue
}
this.s.run("UPDATE outbox SET state='sending',attempts=attempts+1 WHERE id=?", job.id)
try {
await transport.sendMail({
...payload,
attachments,
headers: { 'Auto-Submitted': 'auto-generated', 'X-Auto-Response-Suppress': 'All' },
})
this.s.tx(() => this.finish(job, t, 'smtp'))
} catch (e) {
const definite =
['EAUTH', 'ECONNECTION', 'EDNS', 'ETLS'].includes(e.code) || e.responseCode >= 400
const state = definite ? 'pending' : 'uncertain'
this.s.run(
'UPDATE outbox SET state=?,error=?,next_at=? WHERE id=?',
state,
'Versand fehlgeschlagen; Serverkonfiguration oder Zustellung prüfen.',
new Date(
Date.now() + Math.min(3600000, 30000 * 2 ** Math.min(job.attempts, 7)),
).toISOString(),
job.id,
)
this.s.audit(
'Versandprozess',
'E-Mail-Versand fehlgeschlagen',
job.id,
null,
{ state, code: String(e.code || 'unknown') },
null,
t?.queue_id || null,
)
} finally {
transport.close?.()
}
}
} catch (e) {
this.s.audit('Hintergrundprozess', 'Automatisierung fehlgeschlagen', 'worker', null, {
error: e instanceof Error ? e.name : 'Error',
})
} finally {
this.busy = false
}
}
finish(job, t, adapter) {
this.s.run("UPDATE outbox SET state='sent',error=NULL WHERE id=?", job.id)
if (job.message_id) {
this.s.run("UPDATE messages SET delivery='sent' WHERE id=?", job.message_id)
this.s.audit(
'Versandprozess',
'E-Mail versendet',
job.message_id,
null,
{ adapter },
t.id,
t.queue_id,
)
}
}
async pollImap() {
try {
await this.inbound.due()
} catch (e) {
this.s.audit('Abrufprozess', 'Abrufzeitplan fehlgeschlagen', 'scheduler', null, {
error: e.name,
})
}
}
start() {
this.tick()
this.pollImap()
this.timer = setInterval(() => this.tick(), 5000)
this.imapTimer = setInterval(() => this.pollImap(), 1000)
}
stop() {
clearInterval(this.timer)
clearInterval(this.imapTimer)
}
}