82 lines
2.4 KiB
TypeScript
82 lines
2.4 KiB
TypeScript
import { query } from "../lib/db";
|
|
import { sendStored, type SendFailure } from "../lib/transport";
|
|
import type { StoredPayload } from "../lib/queue";
|
|
|
|
const MAX_ATTEMPTS = 5;
|
|
const POLL_MS = 1000;
|
|
|
|
type Claimed = {
|
|
id: string;
|
|
attempts: number;
|
|
payload: StoredPayload;
|
|
};
|
|
|
|
let running = true;
|
|
process.on("SIGTERM", () => {
|
|
running = false;
|
|
});
|
|
process.on("SIGINT", () => {
|
|
running = false;
|
|
});
|
|
|
|
function sleep(ms: number) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
|
|
async function claim(): Promise<Claimed | null> {
|
|
const { rows } = await query<Claimed>(
|
|
`update messages
|
|
set status = 'sending', attempts = attempts + 1
|
|
where id = (
|
|
select id from messages
|
|
where status = 'queued' and next_attempt_at <= now()
|
|
order by next_attempt_at
|
|
limit 1
|
|
for update skip locked
|
|
)
|
|
returning id, attempts, payload`,
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
async function run() {
|
|
console.log(`[courier-worker] gestartet, Transport ${process.env.MAIL_TRANSPORT || "dry-run"}`);
|
|
while (running) {
|
|
const job = await claim();
|
|
if (!job) {
|
|
await sleep(POLL_MS);
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
const result = await sendStored(job.payload);
|
|
await query(
|
|
`update messages
|
|
set status = 'sent', provider_message_id = $2, sent_at = now(), error = null
|
|
where id = $1`,
|
|
[job.id, result.providerMessageId],
|
|
);
|
|
console.log(`[courier-worker] ${job.id} gesendet (${result.providerMessageId})`);
|
|
} catch (error) {
|
|
const failure = error as SendFailure;
|
|
const retry = failure.retryable !== false && job.attempts < MAX_ATTEMPTS;
|
|
const delay = Math.min(3600, 30 * 2 ** Math.max(0, job.attempts - 1));
|
|
await query(
|
|
`update messages
|
|
set status = $2,
|
|
error = $3,
|
|
next_attempt_at = case when $2 = 'queued' then now() + ($4 || ' seconds')::interval else next_attempt_at end
|
|
where id = $1`,
|
|
[job.id, retry ? "queued" : "failed", String(failure.message || failure).slice(0, 2000), String(delay)],
|
|
);
|
|
console.error(`[courier-worker] ${job.id} ${retry ? `erneut in ${delay}s` : "endgültig fehlgeschlagen"}:`, failure.message);
|
|
}
|
|
}
|
|
console.log("[courier-worker] beendet");
|
|
}
|
|
|
|
run().catch((error) => {
|
|
console.error("[courier-worker] Absturz:", error);
|
|
process.exit(1);
|
|
});
|