//! The `forum` task: the forum's daily e-mail digest. In the evening //! (18–22 h, Hungarian time) every member who asked for it gets one e-mail //! listing the threads with posts they have not read yet: replies to them //! (`email_replies = 'daily'`) and new posts in followed threads //! (`email_followed = 'daily'`). Nothing new, no e-mail. The instant e-mails //! are queued by the forum service itself. use std::time::Duration; use serde_json::json; use sqlx::PgPool; use tokio::sync::watch; use uuid::Uuid; /// Members handled in one round. const BATCH: i64 = 200; /// Threads listed in one digest. const MAX_THREADS: i64 = 10; #[derive(sqlx::FromRow)] struct Due { user_id: Uuid, email: String, locale: String, nickname: String, email_token: String, replies: bool, followed: bool, since: time::OffsetDateTime, } /// The evening window, by Hungarian time. async fn evening(db: &PgPool) -> Result { let hour: i32 = sqlx::query_scalar("SELECT extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int").fetch_one(db).await?; Ok((18..22).contains(&hour)) } /// Makes the digests that are due; returns how many e-mails were queued. /// `any_time`: also outside the evening window (tests). pub async fn run_once(db: &PgPool, base_url: &str, any_time: bool) -> Result { if !any_time && !evening(db).await? { return Ok(0); } let base = base_url.trim_end_matches('/'); let mut tx = db.begin().await?; let due: Vec = sqlx::query_as( "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token, \ m.email_replies = 'daily' AS replies, m.email_followed = 'daily' AS followed, \ greatest(COALESCE(m.digest_sent_at, m.created_at), now() - interval '2 days') AS since \ FROM forum.members m JOIN users u ON u.id = m.user_id \ WHERE (m.email_replies = 'daily' OR m.email_followed = 'daily') \ AND (m.digest_sent_at IS NULL OR m.digest_sent_at < now() - interval '20 hours') \ ORDER BY m.user_id LIMIT $1 FOR UPDATE OF m SKIP LOCKED", ) .bind(BATCH) .fetch_all(&mut *tx) .await?; let mut queued = 0; for m in due { let threads: Vec<(String, i64)> = sqlx::query_as( "SELECT th.title, count(*) FROM forum.posts p JOIN forum.threads th ON th.id = p.thread_id \ WHERE p.deleted_at IS NULL AND th.deleted_at IS NULL AND p.author_id IS DISTINCT FROM $1 \ AND p.created_at > $2 \ AND p.id > COALESCE((SELECT r.last_post_id FROM forum.reads r \ WHERE r.user_id = $1 AND r.thread_id = th.id), 0) \ AND (($3 AND (th.author_id = $1 \ OR p.parent_id IN (SELECT id FROM forum.posts WHERE author_id = $1))) \ OR ($4 AND th.id IN (SELECT thread_id FROM forum.follows WHERE user_id = $1))) \ GROUP BY th.id, th.title ORDER BY max(p.id) DESC LIMIT $5", ) .bind(m.user_id) .bind(m.since) .bind(m.replies) .bind(m.followed) .bind(MAX_THREADS) .fetch_all(&mut *tx) .await?; if !threads.is_empty() { let total: i64 = threads.iter().map(|(_, n)| n).sum(); let lines: Vec = threads.iter().map(|(title, n)| format!("„{title}” – {n} új hozzászólás")).collect(); let payload = json!({ "url": format!("{base}/forum/kovetett"), "nickname": m.nickname, "lines": lines, "total": total, "unsubscribe_url": format!("{base}/forum/leiratkozas?token={}", m.email_token), "unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={}", m.email_token), }); sqlx::query( "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) \ VALUES ($1, $2, $3, 'forum_digest', $4, $5)", ) .bind(Uuid::now_v7()) .bind(m.user_id) .bind(&m.email) .bind(&m.locale) .bind(payload) .execute(&mut *tx) .await?; queued += 1; } sqlx::query("UPDATE forum.members SET digest_sent_at = now() WHERE user_id = $1") .bind(m.user_id) .execute(&mut *tx) .await?; } tx.commit().await?; if queued > 0 { tracing::info!(queued, "forum digests queued"); } Ok(queued) } pub async fn run(db: PgPool, base_url: String, stop: watch::Receiver) { loop { if let Err(e) = run_once(&db, &base_url, false).await { tracing::error!(error = %e, "forum digests"); } tokio::select! { () = tokio::time::sleep(Duration::from_secs(10 * 60)) => {} () = crate::stopped(stop.clone()) => break, } } } #[cfg(test)] mod tests { use super::*; async fn member(db: &PgPool, email: &str, nickname: &str, replies: &str, followed: &str) -> Uuid { let id = Uuid::now_v7(); sqlx::query("INSERT INTO users (id, email) VALUES ($1, $2)").bind(id).bind(email).execute(db).await.unwrap(); sqlx::query( "INSERT INTO forum.members (user_id, nickname, nickname_key, avatar, email_replies, email_followed, created_at) \ VALUES ($1, $2, lower($2), 'hold-ejkek', $3, $4, now() - interval '3 days')", ) .bind(id) .bind(nickname) .bind(replies) .bind(followed) .execute(db) .await .unwrap(); id } async fn post(db: &PgPool, thread: i64, author: Uuid, parent: Option) -> i64 { sqlx::query_scalar( "INSERT INTO forum.posts (thread_id, author_id, parent_id, body) VALUES ($1, $2, $3, 'x') RETURNING id", ) .bind(thread) .bind(author) .bind(parent) .fetch_one(db) .await .unwrap() } #[sqlx::test(migrator = "db::MIGRATOR")] async fn one_digest_a_day_with_what_is_unread(pool: PgPool) { let anna = member(&pool, "anna@example.com", "Anna", "daily", "off").await; let bea = member(&pool, "bea@example.com", "Bea", "off", "daily").await; let cili = member(&pool, "cili@example.com", "Cili", "instant", "off").await; let thread: i64 = sqlx::query_scalar( "INSERT INTO forum.threads (topic_id, author_id, title) VALUES (2, $1, 'Reggeli csend') RETURNING id", ) .bind(anna) .fetch_one(&pool) .await .unwrap(); post(&pool, thread, anna, None).await; sqlx::query("INSERT INTO forum.follows (user_id, thread_id) VALUES ($1, $2), ($3, $2)") .bind(anna) .bind(thread) .bind(bea) .execute(&pool) .await .unwrap(); post(&pool, thread, cili, None).await; post(&pool, thread, cili, None).await; assert_eq!(run_once(&pool, "https://sorsfonalak.hu/", true).await.unwrap(), 2); let mails: Vec<(String, serde_json::Value)> = sqlx::query_as( "SELECT to_email, payload FROM email_outbox WHERE template = 'forum_digest' ORDER BY to_email", ) .fetch_all(&pool) .await .unwrap(); assert_eq!(mails.len(), 2, "Cili asked for instant e-mails, not the digest"); assert_eq!(mails[0].0, "anna@example.com"); assert_eq!(mails[0].1["lines"][0], "„Reggeli csend” – 2 új hozzászólás"); assert_eq!(mails[0].1["url"], "https://sorsfonalak.hu/forum/kovetett"); assert!(email_templates::render("forum_digest", "hu", &mails[0].1).is_ok()); // Once a day only; and nothing unread, nothing sent. post(&pool, thread, cili, None).await; assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0); sqlx::query("UPDATE forum.members SET digest_sent_at = now() - interval '1 day'").execute(&pool).await.unwrap(); let last: i64 = sqlx::query_scalar("SELECT max(id) FROM forum.posts").fetch_one(&pool).await.unwrap(); sqlx::query("INSERT INTO forum.reads (user_id, thread_id, last_post_id) VALUES ($1, $2, $3), ($4, $2, $3)") .bind(anna) .bind(thread) .bind(last) .bind(bea) .execute(&pool) .await .unwrap(); assert_eq!(run_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0); } }