Files
sorsfonalak/services/worker/src/email.rs
T
fecoandClaude Opus 5.5 382bd31271 Christmas gifts and timed gift e-mails
- Gifts bought 15 Nov - 6 Jan get a Christmas card ("Boldog karácsonyt és
  csillagos 2027-et!", snowflakes) and a Christmas e-mail subject.
- The buyer can time the gift e-mail (e.g. Christmas morning); "Küldés most"
  replaces a waiting one, a refund takes it back.
- Admin: timed e-mails by hour (waiting / sent / failed), e-mail state per gift.
- /karacsony landing page; seasonal hints on /csomagok and /ajandek.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-24 13:46:35 +00:00

302 lines
11 KiB
Rust

//! Delivers queued e-mails (`email_outbox`) over SMTP.
//!
//! New rows wake the job at once (`NOTIFY email_outbox`, see migration 0002);
//! a slow poll picks up retries. Rows are claimed with `FOR UPDATE SKIP LOCKED`,
//! so several workers can run side by side. Delivery is at-least-once.
//!
//! An e-mail whose payload has a `gift_card` gets the gift card as a PDF
//! attachment, drawn here (it is not stored anywhere).
use std::time::Duration;
use lettre::message::header::{ContentType, Header, HeaderName, HeaderValue};
use lettre::message::{Attachment, Mailbox, MultiPart};
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde_json::Value;
use sqlx::PgPool;
use tokio::sync::watch;
use uuid::Uuid;
use crate::config::Config;
use crate::templates::{self, Rendered};
const BATCH: i64 = 10;
const CHANNEL: &str = "email_outbox";
pub enum Mailer {
Smtp(AsyncSmtpTransport<Tokio1Executor>),
/// Collects messages instead of sending; fails for addresses listed in `fail`.
#[cfg(test)]
Memory {
/// Recipient, rendered mail and the whole message as sent.
sent: std::sync::Mutex<Vec<(String, Rendered, String)>>,
fail: Vec<(String, bool)>,
},
}
/// Why sending failed; permanent errors (bad address, SMTP 5xx) are not retried.
#[derive(Debug)]
pub struct SendError {
pub permanent: bool,
pub message: String,
}
impl SendError {
fn permanent(message: impl ToString) -> Self {
Self { permanent: true, message: message.to_string() }
}
}
/// The host part of an SMTP URL, for logs (no credentials).
pub fn smtp_host(url: &str) -> String {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
let rest = rest.rsplit_once('@').map_or(rest, |(_, r)| r);
rest.split(['/', '?']).next().unwrap_or_default().to_owned()
}
impl Mailer {
pub fn smtp(url: &str) -> anyhow::Result<Self> {
let transport = AsyncSmtpTransport::<Tokio1Executor>::from_url(url)
.map_err(|e| anyhow::anyhow!("invalid SMTP_URL for {}: {e}", smtp_host(url)))?
.timeout(Some(Duration::from_secs(30)))
.build();
Ok(Mailer::Smtp(transport))
}
async fn send(
&self,
id: Uuid,
from: &Mailbox,
to: &str,
mail: &Rendered,
attachment: Option<&Pdf>,
) -> Result<(), SendError> {
let to_mailbox: Mailbox = to.parse().map_err(SendError::permanent)?;
// A Message-ID on our own domain (lettre would use the container's
// host name, which spam filters dislike); the same on every retry.
let mut builder = Message::builder()
.message_id(Some(format!("<{id}@{}>", from.email.domain())))
.from(from.clone())
.to(to_mailbox)
.subject(&mail.subject);
if let Some(url) = &mail.unsubscribe_post_url {
builder = builder.header(ListUnsubscribe(url.clone())).header(ListUnsubscribePost);
}
let body = MultiPart::alternative_plain_html(mail.text.clone(), mail.html.clone());
let body = match attachment {
Some(pdf) => MultiPart::mixed().multipart(body).singlepart(
Attachment::new(pdf.filename.clone())
.body(pdf.bytes.clone(), ContentType::parse("application/pdf").expect("a content type")),
),
None => body,
};
let message = builder.multipart(body).map_err(SendError::permanent)?;
match self {
Mailer::Smtp(transport) => transport
.send(message)
.await
.map(drop)
.map_err(|e| SendError { permanent: e.is_permanent(), message: e.to_string() }),
#[cfg(test)]
Mailer::Memory { sent, fail } => {
if let Some((_, permanent)) = fail.iter().find(|(addr, _)| addr == to) {
return Err(SendError { permanent: *permanent, message: "test failure".into() });
}
let raw = String::from_utf8_lossy(&message.formatted()).into_owned();
sent.lock().unwrap().push((to.to_owned(), mail.clone(), raw));
Ok(())
}
}
}
}
/// A PDF to attach.
pub struct Pdf {
pub filename: String,
pub bytes: Vec<u8>,
}
/// The gift card of a payload's `gift_card`, if it has one. A card that
/// cannot be drawn is logged, and the e-mail goes without it (the code is in
/// the text too).
async fn gift_card(id: Uuid, payload: &Value) -> Option<Pdf> {
let card = payload.get("gift_card").filter(|c| c.is_object())?.clone();
let drawn = tokio::task::spawn_blocking(move || {
let text = |k: &str| card[k].as_str().map(str::to_owned);
let contents: Vec<String> =
card["contents"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect();
let (Some(package), Some(code), Some(url)) = (text("package"), text("code"), text("redeem_url")) else {
return Err("the gift card has no package, code or link".to_string());
};
let (to, from, message) = (text("recipient_name"), text("from_name"), text("message"));
let bytes = gift_card::pdf(&gift_card::Card {
package: &package,
contents: &contents,
code: &code,
redeem_url: &url,
recipient_name: to.as_deref(),
from_name: from.as_deref(),
message: message.as_deref(),
christmas: card["christmas_year"].as_i64().and_then(|y| i32::try_from(y).ok()),
})
.map_err(|e| e.to_string())?;
let code: String = code.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
Ok(Pdf { filename: format!("sorsfonalak-ajandek-{code}.pdf"), bytes })
})
.await;
match drawn {
Ok(Ok(pdf)) => Some(pdf),
Ok(Err(e)) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
Err(e) => {
tracing::error!(%id, error = %e, "gift card not drawn; the e-mail goes without it");
None
}
}
}
/// `List-Unsubscribe: <url>`: mail clients show an unsubscribe button.
#[derive(Clone)]
struct ListUnsubscribe(String);
impl Header for ListUnsubscribe {
fn name() -> HeaderName {
HeaderName::new_from_ascii_str("List-Unsubscribe")
}
fn parse(s: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
Ok(Self(s.trim().trim_start_matches('<').trim_end_matches('>').to_owned()))
}
fn display(&self) -> HeaderValue {
HeaderValue::new(Self::name(), format!("<{}>", self.0))
}
}
/// `List-Unsubscribe-Post`: the button unsubscribes with one POST (RFC 8058).
#[derive(Clone)]
struct ListUnsubscribePost;
impl Header for ListUnsubscribePost {
fn name() -> HeaderName {
HeaderName::new_from_ascii_str("List-Unsubscribe-Post")
}
fn parse(_: &str) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
Ok(Self)
}
fn display(&self) -> HeaderValue {
HeaderValue::new(Self::name(), "List-Unsubscribe=One-Click".into())
}
}
pub struct Delivery {
pub db: PgPool,
pub mailer: Mailer,
pub from: Mailbox,
pub max_attempts: i32,
}
#[derive(sqlx::FromRow)]
struct OutboxRow {
id: Uuid,
to_email: String,
template: String,
locale: String,
payload: Value,
attempts: i32,
}
/// Wait before the next attempt: 1, 2, 4, ... minutes, at most 6 hours.
pub fn backoff(attempts: i32) -> Duration {
let minutes = 1u64 << attempts.clamp(1, 10).saturating_sub(1);
Duration::from_secs((minutes * 60).min(6 * 3600))
}
impl Delivery {
pub fn new(db: PgPool, mailer: Mailer, config: &Config) -> Self {
Self { db, mailer, from: config.mail_from.clone(), max_attempts: config.max_email_attempts }
}
/// Sends up to one batch of due e-mails; returns how many rows were handled.
pub async fn deliver_due(&self) -> anyhow::Result<usize> {
let mut tx = self.db.begin().await?;
let rows: Vec<OutboxRow> = sqlx::query_as(
"SELECT id, to_email, template, locale, payload, attempts FROM email_outbox \
WHERE sent_at IS NULL AND failed_at IS NULL AND next_attempt_at <= now() \
ORDER BY next_attempt_at LIMIT $1 FOR UPDATE SKIP LOCKED",
)
.bind(BATCH)
.fetch_all(&mut *tx)
.await?;
for row in &rows {
let attempts = row.attempts + 1;
let result = match templates::render(&row.template, &row.locale, &row.payload) {
Ok(mail) => {
let pdf = gift_card(row.id, &row.payload).await;
self.mailer.send(row.id, &self.from, &row.to_email, &mail, pdf.as_ref()).await
}
Err(e) => Err(SendError::permanent(e)),
};
match result {
Ok(()) => {
sqlx::query(
"UPDATE email_outbox SET sent_at = now(), attempts = $2, last_error = NULL WHERE id = $1",
)
.bind(row.id)
.bind(attempts)
.execute(&mut *tx)
.await?;
tracing::info!(id = %row.id, template = %row.template, "e-mail sent");
}
Err(e) if e.permanent || attempts >= self.max_attempts => {
sqlx::query(
"UPDATE email_outbox SET failed_at = now(), attempts = $2, last_error = $3 WHERE id = $1",
)
.bind(row.id)
.bind(attempts)
.bind(&e.message)
.execute(&mut *tx)
.await?;
tracing::error!(id = %row.id, template = %row.template, attempts, error = %e.message, "e-mail failed");
}
Err(e) => {
let wait = backoff(attempts);
sqlx::query(
"UPDATE email_outbox SET attempts = $2, last_error = $3, \
next_attempt_at = now() + make_interval(secs => $4) WHERE id = $1",
)
.bind(row.id)
.bind(attempts)
.bind(&e.message)
.bind(wait.as_secs_f64())
.execute(&mut *tx)
.await?;
tracing::warn!(id = %row.id, attempts, retry_in_secs = wait.as_secs(), error = %e.message, "e-mail will be retried");
}
}
}
tx.commit().await?;
Ok(rows.len())
}
}
pub async fn run(delivery: Delivery, poll: Duration, stop: watch::Receiver<bool>) {
let mut listener = crate::listen(&delivery.db, CHANNEL).await;
loop {
if *stop.borrow() {
break;
}
match delivery.deliver_due().await {
Ok(n) if n as i64 == BATCH => continue,
Ok(_) => {}
Err(e) => tracing::error!(error = %e, "e-mail delivery"),
}
tokio::select! {
() = crate::notified(listener.as_mut()) => {}
() = tokio::time::sleep(poll) => {}
() = crate::stopped(stop.clone()) => break,
}
}
}