Add worker service with e-mail delivery and dev Mailpit
- worker: sends email_outbox mail over SMTP (lettre), woken by LISTEN/NOTIFY, SKIP LOCKED claiming, retries with backoff, hu/en templates (text + HTML), hourly cleanup of expired data - migration 0002: next_attempt_at, failed_at, notify trigger - docker-compose.override.yml: Mailpit for development only - Dockerfiles: lock shared cargo cache mounts for parallel builds Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
//! Sorsfonalak worker: background jobs that read and write the shared
|
||||
//! PostgreSQL database.
|
||||
//!
|
||||
//! * e-mail delivery from `email_outbox` over SMTP (Mailpit in development)
|
||||
//! * hourly cleanup of expired sessions, tokens, invites and old e-mails
|
||||
//! * later: writing the text analyses (LLM)
|
||||
//!
|
||||
//! Configuration: see [`config::Config`]; plus `BIND_ADDR` (default
|
||||
//! `0.0.0.0:8082`, only `/healthz`), `LOG_FORMAT` and `RUST_LOG`.
|
||||
//! `worker healthcheck` performs a local health check (for Docker).
|
||||
|
||||
mod cleanup;
|
||||
mod config;
|
||||
mod email;
|
||||
mod templates;
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use axum::Router;
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::routing::get;
|
||||
use sqlx::PgPool;
|
||||
use tokio::sync::watch;
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8082";
|
||||
|
||||
/// Resolves once shutdown has been requested.
|
||||
pub async fn stopped(mut stop: watch::Receiver<bool>) {
|
||||
let _ = stop.wait_for(|s| *s).await;
|
||||
}
|
||||
|
||||
async fn healthz(State(db): State<PgPool>) -> StatusCode {
|
||||
match sqlx::query("SELECT 1").execute(&db).await {
|
||||
Ok(_) => StatusCode::OK,
|
||||
Err(_) => StatusCode::SERVICE_UNAVAILABLE,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
|
||||
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
|
||||
return service_kit::healthcheck(addr);
|
||||
}
|
||||
service_kit::init_logging();
|
||||
let config = Config::from_env()?;
|
||||
let pool = db::connect(&config.database_url).await.context("connecting to the database")?;
|
||||
db::MIGRATOR.run(&pool).await.context("running database migrations")?;
|
||||
|
||||
let (stop_tx, stop) = watch::channel(false);
|
||||
let mut jobs = tokio::task::JoinSet::new();
|
||||
match &config.smtp_url {
|
||||
Some(url) => {
|
||||
let delivery = email::Delivery::new(pool.clone(), email::Mailer::smtp(url)?, &config);
|
||||
tracing::info!(host = %email::smtp_host(url), "e-mail delivery enabled");
|
||||
jobs.spawn(email::run(delivery, config.poll_interval, stop.clone()));
|
||||
}
|
||||
None => tracing::warn!("SMTP_URL is not set: e-mails stay in the outbox"),
|
||||
}
|
||||
jobs.spawn(cleanup::run(pool.clone(), stop.clone()));
|
||||
|
||||
let app = Router::new().route("/healthz", get(healthz)).with_state(pool);
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
|
||||
tracing::info!(%addr, "worker running");
|
||||
let server = axum::serve(listener, app).with_graceful_shutdown(stopped(stop.clone()));
|
||||
tokio::select! {
|
||||
r = server => r?,
|
||||
() = service_kit::shutdown_signal() => {}
|
||||
}
|
||||
let _ = stop_tx.send(true);
|
||||
// Let jobs finish the batch they are working on.
|
||||
let finished = tokio::time::timeout(Duration::from_secs(30), async { while jobs.join_next().await.is_some() {} });
|
||||
if finished.await.is_err() {
|
||||
tracing::warn!("jobs did not stop in time");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
Reference in New Issue
Block a user