//! The mail worker (architecture section 8): sends the outbox, with retries. //! //! A row is tried when it is due. A failed try is retried after 1, 5, 15 and 60 minutes; the fifth //! failure abandons the row. A sent or abandoned row loses its sealed body in the same write. With no //! sender configured the rows wait untouched, and a sender that cannot be built (for example an unreadable //! password file) also spends no attempt. use std::sync::Arc; use std::time::Duration; use im_core::config::SmtpConfig; use im_core::secret; use im_core::store::Store; use im_core::store::mail::{MailAttempt, MailJob}; use im_core::time::{now_stamp, stamp_after}; use serde::Deserialize; use tokio::sync::watch; use super::message::{Recipient, Sender, build}; use super::transport; /// Attempts before a row is abandoned. pub const MAX_ATTEMPTS: i64 = 5; /// How often the worker looks for due rows. const TICK: Duration = Duration::from_secs(5); /// The most rows one pass tries. const BATCH: i64 = 10; /// How long to wait before the next try, after `attempts` failed tries (1 to 4). pub fn retry_delay(attempts: i64) -> Duration { match attempts { 1 => Duration::from_secs(60), 2 => Duration::from_secs(5 * 60), 3 => Duration::from_secs(15 * 60), _ => Duration::from_secs(60 * 60), } } /// The body as stored (after opening): the name, when known, and the two alternatives. #[derive(Deserialize)] struct Body { to_name: Option, text: String, html: String, } /// Starts the worker. It runs until `stop` is set. pub fn spawn( store: Store, key: Arc<[u8; 32]>, smtp: SmtpConfig, mut stop: watch::Receiver, ) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { if !smtp.enabled() { tracing::info!("mail worker: no sender configured; mail waits in the outbox"); let _ = stop.wait_for(|stopped| *stopped).await; return; } let sender = match Sender::from_config(&smtp) { Ok(sender) => sender, Err(error) => { tracing::error!(error, "mail worker: the sender is not valid; mail waits"); let _ = stop.wait_for(|stopped| *stopped).await; return; } }; loop { run_once(&store, &key, &smtp, &sender).await; tokio::select! { () = tokio::time::sleep(TICK) => {} _ = stop.wait_for(|stopped| *stopped) => break, } } }) } /// One pass: builds the transport (spending no attempt if that fails) and sends what is due. async fn run_once(store: &Store, key: &[u8; 32], smtp: &SmtpConfig, sender: &Sender) { let password = if smtp.username.is_empty() { None } else { match transport::read_password(&smtp.password_file) { Ok(password) => Some(password), Err(error) => { tracing::error!(error, "mail worker: waiting, the sender is not ready"); return; } } }; let transport = match transport::build(smtp, password) { Ok(transport) => transport, Err(error) => { tracing::error!(error, "mail worker: waiting, the sender is not ready"); return; } }; if let Err(error) = deliver_due(store, key, sender, &transport, &now_stamp()).await { tracing::error!(error = %error, "mail worker: outbox could not be read"); } } /// Sends the due rows through `transport` and records each outcome. Generic over the transport so the /// tests can use lettre's stub. pub async fn deliver_due( store: &Store, key: &[u8; 32], sender: &Sender, transport: &T, now: &str, ) -> im_core::Result where T: lettre::AsyncTransport + Sync, T::Error: std::fmt::Debug, { let due = store.due_mail(now, BATCH).await?; let count = due.len(); for job in &due { let attempt = attempt_once(sender, transport, key, job).await; if let Err(error) = store.record_mail_attempt(&job.id, &attempt).await { tracing::error!(error = %error, mail = %job.id, "mail outcome not recorded"); } } Ok(count) } /// Tries one row and says what happened to it. async fn attempt_once( sender: &Sender, transport: &T, key: &[u8; 32], job: &MailJob, ) -> MailAttempt where T: lettre::AsyncTransport + Sync, T::Error: std::fmt::Debug, { // A body that cannot be opened or no longer checks out is not going to get better: give up now. let message = match open_message(sender, key, job) { Ok(message) => message, Err(error) => { tracing::error!(mail = %job.id, kind = %job.kind, error, "mail abandoned"); return MailAttempt::Abandon { error: error.to_owned(), }; } }; match transport.send(message).await { Ok(_) => { tracing::info!(mail = %job.id, kind = %job.kind, "mail sent"); MailAttempt::Sent } Err(error) => { let attempts = job.attempts + 1; // The transport error describes the SMTP reply. The body is never part of it. let reason = truncate(&format!("{error:?}"), 200); if attempts >= MAX_ATTEMPTS { tracing::error!(mail = %job.id, kind = %job.kind, attempts, "mail abandoned"); MailAttempt::Abandon { error: reason } } else { let delay = retry_delay(attempts); tracing::warn!(mail = %job.id, kind = %job.kind, attempts, "mail attempt failed; retry scheduled"); MailAttempt::Retry { next_at: stamp_after(delay), error: reason, } } } } } /// Opens the sealed body and builds the message. Every failure is a fixed text. fn open_message( sender: &Sender, key: &[u8; 32], job: &MailJob, ) -> Result { if job.sealed_body.is_empty() { return Err("mail body is missing"); } let plain = secret::open(key, secret::purpose::MAIL_BODY, &job.sealed_body) .map_err(|_| "mail body cannot be opened")?; let body: Body = serde_json::from_slice(&plain).map_err(|_| "mail body is not valid")?; let to = Recipient::new(body.to_name.as_deref(), &job.to_addr)?; build(sender, &to, &job.subject, body.text, body.html) } /// Cuts `text` to at most `max` characters, on a character boundary. fn truncate(text: &str, max: usize) -> String { text.chars().take(max).collect() }