//! The rules engine: turns queued events into decisions and outbox rows. //! //! One pass reads up to `batch` unprocessed events in order and handles all of them in one transaction: //! for each event, every rule with its trigger gets one decision row (outcome and reason) and, when it //! owes mail, one outbox row per recipient. The unique keys (decision per rule, event and task; outbox per //! rule, event, task and recipient) make a repeated pass a no-op. The pass either commits everything or //! nothing, so a crash between the two leaves the events unprocessed and they are handled again. //! //! Recipients come from the eligible members only (enabled, role admin or member), and the actor is //! removed by `rules::audience`. Mail text is built per recipient in the recipient's language and zone. use jiff::Timestamp; use turso::Connection; use turso::transaction::Transaction; use super::outbox::{OutboxDraft, insert_outbox}; use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id}; use crate::clock::stamp_of; use crate::error::Result; use crate::mail_text::{MailLang, RuleMail, rule_body, when_text}; use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject}; use crate::sender::DEFAULT_RULE_CAP; use crate::store::Store; use crate::store::sender::KEY_RULE_CAP; use crate::time::now_stamp; /// What one event's handling needs from the pass: the hourly cap and where its window starts. #[derive(Clone, Copy)] struct Limits<'a> { cap: i64, window_start: &'a str, } /// One unprocessed event as read back. struct QueuedEvent { id: String, board_id: String, task_id: Option, kind: String, column_id: Option, actor: Option, subject: Option, } /// An eligible member: enabled, role admin or member. The language and zone are the ones mail uses. #[derive(Clone)] struct Eligible { sub: String, lang: MailLang, zone: String, } /// The task row fields a mail body needs. struct TaskRow { key: String, title: String, column_id: String, tag_id: String, deadline: Option, meeting_at: Option, deleted: bool, creator: String, } /// What one pass did. Returned for logs and tests. #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct PassReport { /// Events handled in this pass. pub events: usize, /// Outbox rows queued in this pass. pub mails: usize, } /// The eligible members of the instance, sorted by id. async fn eligible_members(tx: &Transaction<'_>) -> Result> { fetch_all( tx, "SELECT sub, locale, locale_override, zoneinfo FROM members \ WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) ORDER BY sub", (), |row| { let locale = col_opt_text(row, 1)?; let locale_override = col_opt_text(row, 2)?; Ok(Eligible { sub: col_text(row, 0)?, lang: MailLang::of(locale_override.as_deref(), locale.as_deref()), zone: col_text(row, 3)?, }) }, ) .await } /// The task row of `task_id` on `board_id`, deleted or not. async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result> { fetch_opt( conn, "SELECT key, title, column_id, tag_id, deadline, meeting_at, deleted_at, created_by FROM tasks \ WHERE id = ?1 AND board_id = ?2", (task_id.to_owned(), board_id.to_owned()), |row| { Ok(TaskRow { key: col_text(row, 0)?, title: col_text(row, 1)?, column_id: col_text(row, 2)?, tag_id: col_text(row, 3)?, deadline: col_opt_text(row, 4)?, meeting_at: col_opt_text(row, 5)?, deleted: col_opt_text(row, 6)?.is_some(), creator: col_text(row, 7)?, }) }, ) .await } /// Sorted ids of the people assigned to `task_id`, and the names in the same order. async fn assignees_of(conn: &Connection, task_id: &str) -> Result> { fetch_all( conn, "SELECT a.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \ WHERE a.task_id = ?1 ORDER BY a.sub", (task_id.to_owned(),), |row| Ok((col_text(row, 0)?, col_text(row, 1)?)), ) .await } /// Sorted ids of the members who watch `task_id`. async fn watchers_of(conn: &Connection, task_id: &str) -> Result> { fetch_all( conn, "SELECT sub FROM task_watchers WHERE task_id = ?1 ORDER BY sub", (task_id.to_owned(),), |row| col_text(row, 0), ) .await } /// A name by id, or empty when the member is unknown. async fn name_of(conn: &Connection, sub: &str) -> Result { Ok(fetch_opt( conn, "SELECT name FROM members WHERE sub = ?1", (sub.to_owned(),), |row| col_text(row, 0), ) .await? .unwrap_or_default()) } /// A column or project name by id, or empty when it is gone. async fn label_of(conn: &Connection, table: &'static str, id: &str) -> Result { let sql = match table { "columns" => "SELECT name FROM columns WHERE id = ?1", _ => "SELECT name FROM tags WHERE id = ?1", }; Ok( fetch_opt(conn, sql, (id.to_owned(),), |row| col_text(row, 0)) .await? .unwrap_or_default(), ) } /// The link back to a task. The base has no trailing slash (see `config.base_url`). pub fn task_link(base_url: &str, key: &str) -> String { format!("{}/?task={key}", base_url.trim_end_matches('/')) } /// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients. /// A recipient already queued `limits.cap` rule mails since `limits.window_start` gets none; the decision /// then records `skipped` with the detail `rate_limited`. async fn handle( tx: &Transaction<'_>, event: &QueuedEvent, base_url: &str, limits: Limits<'_>, ) -> Result { let rules = fetch_all( tx, "SELECT id, column_id, tag_id, audience, enabled, subject_template, include_details FROM mail_rules \ WHERE board_id = ?1 AND trigger = ?2 ORDER BY created_at, id", (event.board_id.clone(), event.kind.clone()), |row| { let audience_text = col_text(row, 3)?; let audience = Audience::parse(&audience_text).unwrap_or(Audience::Assignees); Ok(( col_text(row, 0)?, RuleFacts { enabled: col_int(row, 4)? == 1, column_id: col_opt_text(row, 1)?, tag_id: col_opt_text(row, 2)?, audience, }, col_text(row, 5)?, col_int(row, 6)? == 1, )) }, ) .await?; if rules.is_empty() { return Ok(0); } let eligible = eligible_members(tx).await?; let subs: Vec = eligible.iter().map(|m| m.sub.clone()).collect(); let task = match &event.task_id { Some(task_id) => task_row(tx, &event.board_id, task_id).await?, None => None, }; let facts = match (&event.task_id, &task) { (Some(task_id), Some(row)) => Some(TaskFacts { tag_id: row.tag_id.clone(), deleted: row.deleted, creator: row.creator.clone(), assignees: assignees_of(tx, task_id) .await? .into_iter() .map(|(sub, _)| sub) .collect(), watchers: watchers_of(tx, task_id).await?, }), _ => None, }; let event_facts = EventFacts { kind: event.kind.clone(), subject: event.subject.clone(), column_id: event.column_id.clone(), actor: event.actor.clone(), }; let actor_name = match &event.actor { Some(actor) => name_of(tx, actor).await?, None => String::new(), }; let subject_name = match &event.subject { Some(sub) => name_of(tx, sub).await?, None => String::new(), }; let queued_at = now_stamp(); let mut mails = 0; for (rule_id, rule, template, details) in &rules { let verdict = evaluate(rule, &event_facts, facts.as_ref(), &subs); let (outcome, detail, recipients) = match &verdict { Verdict::Disabled => ("disabled", String::new(), Vec::new()), Verdict::TaskGone => ("task_gone", String::new(), Vec::new()), Verdict::NotMatched(reason) => ("not_matched", reason.as_str().to_owned(), Vec::new()), Verdict::NoRecipients => ("no_recipients", "empty".to_owned(), Vec::new()), Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()), }; let mut queued = 0; let mut capped = 0; if let (Some(row), Some(task_id)) = (&task, &event.task_id) { let column_id = event .column_id .clone() .unwrap_or_else(|| row.column_id.clone()); let column = label_of(tx, "columns", &column_id).await?; let tag = label_of(tx, "tags", &row.tag_id).await?; let assignees: Vec = assignees_of(tx, task_id) .await? .into_iter() .map(|(_, n)| n) .collect(); let link = task_link(base_url, &row.key); for sub in &recipients { let Some(member) = eligible.iter().find(|m| &m.sub == sub) else { continue; }; let sent_before = fetch_opt( tx, "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'rule' AND created_at >= ?2", (sub.clone(), limits.window_start.to_owned()), |row| col_int(row, 0), ) .await? .unwrap_or(0); if sent_before >= limits.cap { capped += 1; tracing::warn!(recipient = %sub, cap = limits.cap, "rule mail held back by the hourly cap"); continue; } let when = row .meeting_at .as_deref() .and_then(|at| when_text(at, &member.zone)); let subject = render_subject( template, &[ ("key", &row.key), ("title", &row.title), ("column", &column), ("actor", &actor_name), ("tag", &tag), ("deadline", row.deadline.as_deref().unwrap_or("")), ], ); let body = rule_body(&RuleMail { lang: member.lang, kind: &event.kind, actor: &actor_name, subject_name: &subject_name, key: &row.key, title: &row.title, column: &column, deadline: row.deadline.as_deref(), assignees: &assignees, when: when.as_deref(), link: &link, details: *details, subject: &subject, }); let draft = OutboxDraft { rule_id: Some(rule_id), event_id: &event.id, task_id: Some(task_id), recipient: sub, kind: "rule", subject: &subject, body: &body, next_attempt_at: &queued_at, }; if insert_outbox(tx, &draft).await? { queued += 1; } } } mails += queued; let (outcome, detail) = if capped > 0 { let outcome = if queued == 0 { "skipped" } else { outcome }; (outcome, "rate_limited".to_owned()) } else if outcome == "owed" && queued == 0 { ("already_owed", detail) } else { (outcome, detail) }; tx.execute( "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(rule_id, event_id, task_id) DO NOTHING", ( new_id(), rule_id.clone(), event.id.clone(), event.task_id.clone(), outcome, detail, now_stamp(), ), ) .await .map_err(db_err)?; } Ok(mails) } impl Store { /// One pass of the rules engine over up to `batch` queued events, in one transaction. `now` stamps the /// outbox rows; `base_url` is the link base of the mails. pub async fn run_rules( &self, now: Timestamp, base_url: &str, batch: usize, ) -> Result { let conn = self.inner.conn.lock().await; let tx = conn.unchecked_transaction().await.map_err(db_err)?; let outcome: Result = async { let events = fetch_all( &tx, "SELECT id, board_id, task_id, kind, column_id, actor, subject FROM mail_events \ WHERE processed_at IS NULL ORDER BY at, id LIMIT ?1", (i64::try_from(batch).unwrap_or(i64::MAX),), |row| { Ok(QueuedEvent { id: col_text(row, 0)?, board_id: col_text(row, 1)?, task_id: col_opt_text(row, 2)?, kind: col_text(row, 3)?, column_id: col_opt_text(row, 4)?, actor: col_opt_text(row, 5)?, subject: col_opt_text(row, 6)?, }) }, ) .await?; let mut report = PassReport::default(); let stamp = stamp_of(now)?; let cap = fetch_opt( &tx, "SELECT value FROM settings WHERE key = ?1", (KEY_RULE_CAP.to_owned(),), |row| col_text(row, 0), ) .await? .and_then(|v| v.parse::().ok()) .unwrap_or(DEFAULT_RULE_CAP) .min(crate::limits::REMINDER_CAP_MAX); let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?; let limits = Limits { cap: i64::from(cap), window_start: &window_start, }; for event in &events { report.mails += handle(&tx, event, base_url, limits).await?; tx.execute( "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1", (event.id.clone(), stamp.clone()), ) .await .map_err(db_err)?; report.events += 1; } Ok(report) } .await; finish(tx, outcome).await } } #[cfg(test)] mod tests { use jiff::{SignedDuration, Timestamp}; use super::*; use crate::clock::stamp_of; use crate::store::rules::RuleInput; use crate::store::tasks::{NewTask, TaskEdit}; use crate::store::test_support::seeded; use crate::time::stamp_after; use std::time::Duration; const BASE: &str = "http://127.0.0.1:7654"; fn rule(trigger: &str, audience: &str) -> RuleInput { RuleInput { name: "Test rule".into(), trigger: trigger.into(), column_id: None, tag_id: None, audience: audience.into(), include_details: true, enabled: true, subject_template: "{key} {title}".into(), } } fn new_task(column: &str, tag: &str, assignees: &[&str], meeting: Option) -> NewTask { NewTask { title: "Dentist".into(), description: String::new(), column_id: column.into(), tag_id: tag.into(), deadline: None, meeting_at: meeting, assignees: assignees.iter().map(|s| s.to_string()).collect(), parent_id: None, link: None, } } /// The first column and the default project of the board. async fn column_and_tag(store: &Store, board_id: &str) -> (String, String) { let column = store.columns(board_id).await.unwrap()[0].id.clone(); let tag = store.tags(board_id).await.unwrap()[0].id.clone(); (column, tag) } #[tokio::test] async fn a_mail_event_cannot_trigger_a_rule() { let (_dir, store, board_id) = seeded().await; store .create_rule(&board_id, &rule("commented", "board")) .await .unwrap(); // A notice is mail, not a board event: queuing and sending it writes no event. let queued = store .queue_message("ada", "Hello", "Bye", Timestamp::now()) .await .unwrap(); assert_eq!(queued, 1); let now = Timestamp::now(); for row in store.claim_due(now, 10).await.unwrap() { store.mark_sent(&row.id, now).await.unwrap(); } let report = store.run_rules(now, BASE, 100).await.unwrap(); assert_eq!( report, PassReport { events: 0, mails: 0 } ); let rule_mail = store .outbox_page(None, 100) .await .unwrap() .items .iter() .filter(|row| row.kind == "rule") .count(); assert_eq!(rule_mail, 0); } #[tokio::test] async fn a_ghost_member_and_the_actor_receive_nothing() { let (_dir, store, board_id) = seeded().await; let (column, tag) = column_and_tag(&store, &board_id).await; let ghost = crate::store::members::DirectoryMember { sub: "ghost".into(), email: "ghost@example.com".into(), name: "Ghost".into(), im_admin: false, disabled: false, locale: None, zoneinfo: "UTC".into(), picture_version: 0, updated_at: "2026-10-28T09:00:00.000000000Z".into(), }; store .apply_directory_member(&ghost, crate::authz::Role::Member) .await .unwrap(); store .create_rule(&board_id, &rule("created", "board")) .await .unwrap(); store .create_task( &board_id, new_task(&column, &tag, &["bo", "ghost"], None), "ada", ) .await .unwrap(); // The member leaves the family after being assigned: the queued mail must not reach them. let mut gone = ghost.clone(); gone.disabled = true; store .apply_directory_member(&gone, crate::authz::Role::Member) .await .unwrap(); store.run_rules(Timestamp::now(), BASE, 100).await.unwrap(); let rows = store.outbox_page(None, 100).await.unwrap().items; let recipients: Vec<&str> = rows.iter().map(|r| r.recipient.as_str()).collect(); assert_eq!( recipients, vec!["bo"], "only the eligible, non-acting member is mailed" ); // Anybody claiming the queued mail after the change is refused as well. let claimed = store.claim_due(Timestamp::now(), 10).await.unwrap(); assert!(claimed.iter().all(|r| r.recipient != "ghost")); } #[tokio::test] async fn a_reminder_fires_once_per_meeting_and_re_arms_after_a_change() { let (_dir, store, board_id) = seeded().await; let (column, tag) = column_and_tag(&store, &board_id).await; let now = Timestamp::now(); let meeting = stamp_after(Duration::from_secs(2 * 3600)); let task = store .create_task( &board_id, new_task(&column, &tag, &["bo"], Some(meeting)), "ada", ) .await .unwrap(); let reminders_for_bo = |store: &Store| { let store = store.clone(); async move { store .outbox_page(None, 200) .await .unwrap() .items .iter() .filter(|r| r.kind == "reminder" && r.recipient == "bo") .count() } }; // Past the due time (meeting minus 15 minutes) once: one reminder. let after_due = now + SignedDuration::from_mins(110); store.run_reminders(after_due, BASE, 20, 100).await.unwrap(); store.run_reminders(after_due, BASE, 20, 100).await.unwrap(); assert_eq!(reminders_for_bo(&store).await, 1); // Moving the meeting re-arms the reminder for the new due value. let moved = stamp_of(now + SignedDuration::from_hours(4)).unwrap(); let edit = TaskEdit { title: task.title.clone(), description: task.description.clone(), tag_id: task.tag_id.clone(), deadline: None, meeting_at: Some(moved), }; store .edit_task(&board_id, &task.id, edit, "ada") .await .unwrap(); store .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100) .await .unwrap(); store .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100) .await .unwrap(); assert_eq!(reminders_for_bo(&store).await, 2); } }