//! The `forum` task: the forum's scheduled work. //! //! * The 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. //! * The daily "Mai égbolt" thread (`forum_sky`). //! * Volunteer listeners: a thread asking to be heard that waited two hours //! without a reply is sent to those who asked for such e-mails. //! * The weekly summary, on Sunday evening, for those who asked for it. 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) } /// A waiting thread is sent to the listeners after this long without a reply. const LISTENER_AFTER: &str = "2 hours"; /// Sends the listeners the threads that wait for a first reply; returns how /// many e-mails were queued. Each thread once; a listener at most one such /// e-mail in six hours. pub async fn listeners_once(db: &PgPool, base_url: &str) -> Result { let base = base_url.trim_end_matches('/'); let mut tx = db.begin().await?; let threads: Vec<(i64, String, Option)> = sqlx::query_as(&format!( "SELECT th.id, th.title, th.author_id FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE th.reply_count = 0 AND NOT th.locked AND th.deleted_at IS NULL AND NOT th.system \ AND th.listeners_notified_at IS NULL AND tp.visibility <> 'restricted' \ AND (th.intent = 'listen' OR tp.listening) \ AND th.created_at < now() - interval '{LISTENER_AFTER}' AND th.created_at > now() - interval '3 days' \ ORDER BY th.created_at LIMIT 20 FOR UPDATE OF th SKIP LOCKED" )) .fetch_all(&mut *tx) .await?; let mut queued = 0; for (id, title, author) in threads { let listeners: Vec<(Uuid, String, String, String, String)> = sqlx::query_as( "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \ FROM forum.members m JOIN users u ON u.id = m.user_id \ WHERE m.listener AND m.email_listener = 'instant' AND m.user_id IS DISTINCT FROM $1 \ AND (m.banned_until IS NULL OR m.banned_until < now()) \ AND (m.last_seen_at IS NULL OR m.last_seen_at < now() - interval '5 minutes') \ AND NOT EXISTS (SELECT 1 FROM email_outbox e WHERE e.user_id = m.user_id \ AND e.template = 'forum_listener' AND e.created_at > now() - interval '6 hours')", ) .bind(author) .fetch_all(&mut *tx) .await?; let slug = thread_slug(&title); for (user, email, locale, nickname, token) in listeners { let payload = json!({ "url": format!("{base}/forum/szal/{id}-{slug}#valasz"), "nickname": nickname, "thread_title": title, "unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"), "unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"), }); queue(&mut tx, user, &email, &locale, "forum_listener", payload).await?; queued += 1; } sqlx::query("UPDATE forum.threads SET listeners_notified_at = now() WHERE id = $1") .bind(id) .execute(&mut *tx) .await?; } tx.commit().await?; Ok(queued) } /// Sunday evening: the week's busiest threads and those still waiting, to the /// members who asked for it; returns how many e-mails were queued. pub async fn weekly_once(db: &PgPool, base_url: &str, any_time: bool) -> Result { if !any_time { let (dow, hour): (i32, i32) = sqlx::query_as( "SELECT extract(dow FROM now() AT TIME ZONE 'Europe/Budapest')::int, \ extract(hour FROM now() AT TIME ZONE 'Europe/Budapest')::int", ) .fetch_one(db) .await?; if dow != 0 || !(18..22).contains(&hour) { return Ok(0); } } let base = base_url.trim_end_matches('/'); let busy: Vec<(i64, String, i64)> = sqlx::query_as( "SELECT th.id, th.title, count(p.id) FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ JOIN forum.posts p ON p.thread_id = th.id AND p.deleted_at IS NULL AND p.created_at > now() - interval '7 days' \ WHERE th.deleted_at IS NULL AND tp.visibility <> 'restricted' \ GROUP BY th.id, th.title ORDER BY count(p.id) DESC, max(p.id) DESC LIMIT 5", ) .fetch_all(db) .await?; let waiting: Vec = sqlx::query_scalar( "SELECT th.title FROM forum.threads th JOIN forum.topics tp ON tp.id = th.topic_id \ WHERE th.reply_count = 0 AND th.deleted_at IS NULL AND NOT th.locked AND NOT th.system \ AND tp.visibility <> 'restricted' AND th.created_at > now() - interval '7 days' \ ORDER BY th.created_at LIMIT 3", ) .fetch_all(db) .await?; let busy: Vec = busy.iter().map(|(_, title, n)| format!("„{title}” – {n} hozzászólás")).collect(); let waiting: Vec = waiting.iter().map(|t| format!("„{t}”")).collect(); let mut tx = db.begin().await?; let due: Vec<(Uuid, String, String, String, String)> = sqlx::query_as( "SELECT m.user_id, u.email, u.locale, m.nickname, m.email_token \ FROM forum.members m JOIN users u ON u.id = m.user_id \ WHERE m.email_weekly AND (m.weekly_sent_at IS NULL OR m.weekly_sent_at < now() - interval '6 days') \ 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 (user, email, locale, nickname, token) in due { if !busy.is_empty() || !waiting.is_empty() { let payload = json!({ "url": format!("{base}/forum"), "nickname": nickname, "busy": busy, "waiting": waiting, "unsubscribe_url": format!("{base}/forum/leiratkozas?token={token}"), "unsubscribe_post_url": format!("{base}/api/v1/forum/unsubscribe?token={token}"), }); queue(&mut tx, user, &email, &locale, "forum_weekly", payload).await?; queued += 1; } sqlx::query("UPDATE forum.members SET weekly_sent_at = now() WHERE user_id = $1") .bind(user) .execute(&mut *tx) .await?; } tx.commit().await?; Ok(queued) } async fn queue( tx: &mut sqlx::PgConnection, user: Uuid, email: &str, locale: &str, template: &str, payload: serde_json::Value, ) -> Result<(), sqlx::Error> { sqlx::query( "INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)", ) .bind(Uuid::now_v7()) .bind(user) .bind(email) .bind(template) .bind(locale) .bind(payload) .execute(&mut *tx) .await?; Ok(()) } /// The readable part of a thread's address (the forum service's `text::slug`). fn thread_slug(title: &str) -> String { let ascii = deunicode::deunicode(title).to_lowercase(); let mut slug = String::new(); for word in ascii.split(|c: char| !c.is_ascii_alphanumeric()).filter(|w| !w.is_empty()) { if !slug.is_empty() && slug.len() + 1 + word.len() > 60 { break; } if !slug.is_empty() { slug.push('-'); } slug.push_str(word); } slug } pub async fn run(db: PgPool, base_url: String, backend_url: String, stop: watch::Receiver) { let http = reqwest::Client::builder().timeout(Duration::from_secs(20)).build().expect("static configuration"); loop { if let Err(e) = run_once(&db, &base_url, false).await { tracing::error!(error = %e, "forum digests"); } if let Err(e) = crate::forum_sky::run_once(&db, &http, &backend_url, false).await { tracing::error!(error = %e, "daily sky thread"); } if let Err(e) = listeners_once(&db, &base_url).await { tracing::error!(error = %e, "forum listener e-mails"); } if let Err(e) = weekly_once(&db, &base_url, false).await { tracing::error!(error = %e, "forum weekly summary"); } 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); } } #[cfg(test)] mod more_tests { use axum::Json; use axum::routing::get; use super::*; async fn user(db: &PgPool, email: &str, nickname: &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) VALUES ($1, $2, lower($2), 'hold-ejkek')") .bind(id) .bind(nickname) .execute(db) .await .unwrap(); id } #[sqlx::test(migrator = "db::MIGRATOR")] async fn listeners_hear_of_a_waiting_thread_once(pool: PgPool) { let anna = user(&pool, "anna@example.com", "Anna").await; let bea = user(&pool, "bea@example.com", "Bea").await; let cili = user(&pool, "cili@example.com", "Cili").await; sqlx::query("UPDATE forum.members SET listener = true, email_listener = 'instant' WHERE user_id IN ($1, $2)") .bind(bea) .bind(cili) .execute(&pool) .await .unwrap(); // Anna asks to be heard; three hours, no reply. Another thread is fresh. sqlx::query( "INSERT INTO forum.threads (topic_id, author_id, title, intent, created_at) VALUES \ (2, $1, 'Nehéz napok', 'listen', now() - interval '3 hours'), (2, $1, 'Friss', 'listen', now())", ) .bind(anna) .execute(&pool) .await .unwrap(); assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 2); assert_eq!(listeners_once(&pool, "https://sorsfonalak.hu").await.unwrap(), 0, "once per thread"); let to: Vec = sqlx::query_scalar("SELECT to_email FROM email_outbox WHERE template = 'forum_listener' ORDER BY to_email") .fetch_all(&pool) .await .unwrap(); assert_eq!(to, vec!["bea@example.com", "cili@example.com"]); } #[sqlx::test(migrator = "db::MIGRATOR")] async fn the_weekly_summary_only_for_those_who_asked(pool: PgPool) { let anna = user(&pool, "anna@example.com", "Anna").await; user(&pool, "bea@example.com", "Bea").await; sqlx::query("UPDATE forum.members SET email_weekly = true WHERE user_id = $1") .bind(anna) .execute(&pool) .await .unwrap(); let thread: i64 = sqlx::query_scalar( "INSERT INTO forum.threads (topic_id, author_id, title) VALUES (4, $1, 'Téli levesek') RETURNING id", ) .bind(anna) .fetch_one(&pool) .await .unwrap(); sqlx::query("INSERT INTO forum.posts (thread_id, author_id, is_opening, body) VALUES ($1, $2, true, 'x')") .bind(thread) .bind(anna) .execute(&pool) .await .unwrap(); assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 1); assert_eq!(weekly_once(&pool, "https://sorsfonalak.hu", true).await.unwrap(), 0, "once a week"); let payload: serde_json::Value = sqlx::query_scalar("SELECT payload FROM email_outbox WHERE template = 'forum_weekly'") .fetch_one(&pool) .await .unwrap(); assert_eq!(payload["busy"][0], "„Téli levesek” – 1 hozzászólás"); assert!(email_templates::render("forum_weekly", "hu", &payload).is_ok()); } #[sqlx::test(migrator = "db::MIGRATOR")] async fn the_daily_sky_thread_is_opened_once(pool: PgPool) { async fn sky() -> Json { Json(serde_json::json!({ "local_time": "2026-11-27T06:10", "moon": {"position": {"sign": "cancer"}, "phase": "waning_gibbous", "illumination": 0.9, "sign_change": null, "next_phases": []}, "planets": [] })) } let app = axum::Router::new().route("/v1/public/sky", get(sky)); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); let http = reqwest::Client::new(); let url = format!("http://{addr}"); assert!(crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap()); assert!(!crate::forum_sky::run_once(&pool, &http, &url, true).await.unwrap(), "one a day"); let (title, system, pinned, body): (String, bool, bool, String) = sqlx::query_as( "SELECT th.title, th.system, th.pinned, p.body FROM forum.threads th \ JOIN forum.posts p ON p.thread_id = th.id AND p.is_opening", ) .fetch_one(&pool) .await .unwrap(); assert!(title.starts_with("Mai égbolt · ") && system && pinned); assert!(body.starts_with("A Hold ma a Rákban jár.")); } }