//! Mail rules, pure part: the closed set of triggers and audiences, the verdict of one rule on one //! event, and the rendering of a rule's subject. No I/O. The store (`store/rules_engine.rs`) loads the //! facts (task, members, eligible recipients) and writes the decisions and outbox rows this module decides. //! //! Invariants kept here: the actor of an event is never a recipient of it; a recipient is always one of //! the eligible members handed in (enabled, role admin or member), so a viewer, a role `none` member and a //! disabled member can never be owed mail; a subject is plain text with no control characters, at most //! `MAIL_SUBJECT_MAX` characters, whatever the template or the values were. use crate::limits::MAIL_SUBJECT_MAX; /// Every trigger a rule can name. The schema CHECK lists the same twelve words. pub const TRIGGERS: [&str; 12] = [ "status", "unblocked", "created", "assigned", "unassigned", "commented", "deadline_set", "deadline_cleared", "retitled", "linked", "unlinked", "deleted", ]; /// Who a rule mails. The schema CHECK lists the same four words. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Audience { /// The task's assignees. For `assigned` and `unassigned`, only the person named by the event. Assignees, /// Every eligible member of the board. Board, /// The member who created the task. Creator, /// The members who opted in to watch this task. Watchers, } impl Audience { /// The stored spelling. pub fn as_str(self) -> &'static str { match self { Audience::Assignees => "assignees", Audience::Board => "board", Audience::Creator => "creator", Audience::Watchers => "watchers", } } /// Parses the stored spelling. Unknown text is `None`. pub fn parse(text: &str) -> Option { match text { "assignees" => Some(Audience::Assignees), "board" => Some(Audience::Board), "creator" => Some(Audience::Creator), "watchers" => Some(Audience::Watchers), _ => None, } } } /// Whether `text` is one of the triggers. pub fn is_trigger(text: &str) -> bool { TRIGGERS.contains(&text) } /// The rule fields a verdict depends on. #[derive(Debug, Clone, PartialEq, Eq)] pub struct RuleFacts { /// Whether the rule is switched on. pub enabled: bool, /// Only for `status`: the column that must be entered. `None` means any column. pub column_id: Option, /// The project the task must wear. `None` means any project. pub tag_id: Option, /// Who is mailed. pub audience: Audience, } /// The event fields a verdict depends on. #[derive(Debug, Clone, PartialEq, Eq)] pub struct EventFacts { /// The trigger word of the event. pub kind: String, /// The member the event names (the person assigned or removed), if any. pub subject: Option, /// The column the task entered, for `status` events. pub column_id: Option, /// Who did it. Never mailed about their own action. pub actor: Option, } /// The task fields a verdict depends on, as they are now. #[derive(Debug, Clone, PartialEq, Eq)] pub struct TaskFacts { /// The project the task wears. pub tag_id: String, /// Whether the task is soft-deleted. pub deleted: bool, /// Who created it. pub creator: String, /// Current assignees, sorted. pub assignees: Vec, /// Members who watch the task, sorted. pub watchers: Vec, } /// Why a rule does not apply to an event whose task is in the wrong state or place. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mismatch { /// A status rule names another column. Column, /// The rule is limited to another project. Project, } impl Mismatch { /// The text stored in the decision ledger. pub fn as_str(self) -> &'static str { match self { Mismatch::Column => "column", Mismatch::Project => "project", } } } /// The outcome of one rule on one event, before any row is written. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Verdict { /// The rule is off. Disabled, /// The task is gone (deleted before the event was handled), so the mail would be about nothing. TaskGone, /// The event does not match the rule's column or project. NotMatched(Mismatch), /// The rule applies, but nobody eligible is in the audience (after removing the actor). NoRecipients, /// These members are owed the mail, sorted. Owed(Vec), } /// Decides one rule on one event. `task` is `None` when the task row does not exist. `eligible` is every /// member who may receive mail (enabled, role admin or member), sorted. pub fn evaluate( rule: &RuleFacts, event: &EventFacts, task: Option<&TaskFacts>, eligible: &[String], ) -> Verdict { if !rule.enabled { return Verdict::Disabled; } let Some(task) = task else { return Verdict::TaskGone; }; // A deleted task still announces its own deletion; any other event about it is gone. if task.deleted && event.kind != "deleted" { return Verdict::TaskGone; } if let Some(column) = &rule.column_id && event.column_id.as_deref() != Some(column.as_str()) { return Verdict::NotMatched(Mismatch::Column); } if let Some(tag) = &rule.tag_id && *tag != task.tag_id { return Verdict::NotMatched(Mismatch::Project); } let owed = audience(rule.audience, event, task, eligible); if owed.is_empty() { Verdict::NoRecipients } else { Verdict::Owed(owed) } } /// The recipients of an audience: the candidates, restricted to the eligible members and without the actor. /// Sorted and without duplicates. `eligible` may be in any order. pub fn audience( audience: Audience, event: &EventFacts, task: &TaskFacts, eligible: &[String], ) -> Vec { let candidates: Vec<&String> = match audience { Audience::Assignees if matches!(event.kind.as_str(), "assigned" | "unassigned") => { event.subject.iter().collect() } Audience::Assignees => task.assignees.iter().collect(), Audience::Board => eligible.iter().collect(), Audience::Creator => vec![&task.creator], Audience::Watchers => task.watchers.iter().collect(), }; let mut out: Vec = candidates .into_iter() .filter(|sub| eligible.contains(sub)) .filter(|sub| event.actor.as_deref() != Some(sub.as_str())) .cloned() .collect(); out.sort(); out.dedup(); out } /// Removes every control character (CR, LF, tab, NUL and the rest of the C0 and C1 sets) and the Unicode /// direction and zero-width format marks that let text pass for something else. Values that go into a /// mail header or a subject are cleaned with this first. pub fn clean_text(text: &str) -> String { text.chars().filter(|c| !is_unsafe_char(*c)).collect() } /// Whether a character must never reach a mail header or a subject. fn is_unsafe_char(c: char) -> bool { c.is_control() || matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}') } /// Renders a subject from its template: `{name}` is replaced by the value of `name` in `vars`. A name /// that is not in `vars` stays as written, so a typo shows in the mail instead of vanishing. The values /// are inserted as they are and are never scanned again. The result is cleaned with [`clean_text`] and /// cut to [`MAIL_SUBJECT_MAX`] characters. pub fn render_subject(template: &str, vars: &[(&str, &str)]) -> String { let mut out = String::with_capacity(template.len()); let mut rest = template; while let Some(open) = rest.find('{') { out.push_str(&rest[..open]); let after = &rest[open + 1..]; let Some(close) = after.find('}') else { out.push_str(&rest[open..]); rest = ""; break; }; let name = &after[..close]; match vars.iter().find(|(key, _)| *key == name) { Some((_, value)) => out.push_str(value), None => { out.push('{'); out.push_str(name); out.push('}'); } } rest = &after[close + 1..]; } out.push_str(rest); clean_text(&out) .trim() .chars() .take(MAIL_SUBJECT_MAX) .collect() } #[cfg(test)] mod tests { use super::*; fn facts(assignees: &[&str], watchers: &[&str]) -> TaskFacts { TaskFacts { tag_id: "t1".into(), deleted: false, creator: "ada".into(), assignees: assignees.iter().map(|s| s.to_string()).collect(), watchers: watchers.iter().map(|s| s.to_string()).collect(), } } fn event(kind: &str, subject: Option<&str>) -> EventFacts { EventFacts { kind: kind.into(), subject: subject.map(str::to_owned), column_id: None, actor: Some("ada".into()), } } fn rule(audience: Audience) -> RuleFacts { RuleFacts { enabled: true, column_id: None, tag_id: None, audience, } } #[test] fn the_actor_is_never_owed_and_ineligible_members_never_are() { let eligible = vec!["bo".to_owned(), "ada".to_owned()]; // "cy" is assigned but not eligible (a viewer, a disabled or a role-none member). let task = facts(&["ada", "bo", "cy"], &[]); let verdict = evaluate( &rule(Audience::Assignees), &event("commented", None), Some(&task), &eligible, ); assert_eq!(verdict, Verdict::Owed(vec!["bo".to_owned()])); } #[test] fn assignment_events_name_only_the_person_just_assigned() { let eligible = vec!["bo".to_owned(), "cy".to_owned()]; let task = facts(&["bo", "cy"], &[]); let verdict = evaluate( &rule(Audience::Assignees), &event("assigned", Some("cy")), Some(&task), &eligible, ); assert_eq!(verdict, Verdict::Owed(vec!["cy".to_owned()])); } #[test] fn disabled_gone_and_mismatched_rules_owe_nothing() { let eligible = vec!["bo".to_owned()]; let task = facts(&["bo"], &[]); let mut off = rule(Audience::Board); off.enabled = false; assert_eq!( evaluate(&off, &event("created", None), Some(&task), &eligible), Verdict::Disabled ); assert_eq!( evaluate( &rule(Audience::Board), &event("created", None), None, &eligible ), Verdict::TaskGone ); let mut deleted = facts(&["bo"], &[]); deleted.deleted = true; assert_eq!( evaluate( &rule(Audience::Board), &event("commented", None), Some(&deleted), &eligible ), Verdict::TaskGone ); let mut status = rule(Audience::Board); status.column_id = Some("done".into()); let mut moved = event("status", None); moved.column_id = Some("todo".into()); assert_eq!( evaluate(&status, &moved, Some(&task), &eligible), Verdict::NotMatched(Mismatch::Column) ); } #[test] fn subject_is_plain_text_without_line_breaks_and_capped() { let title = "x\r\nBcc: evil@example.com"; let subject = render_subject( "New: {title}\r\nBcc: {key}", &[("title", title), ("key", "IZ-7")], ); assert!(!subject.contains('\r') && !subject.contains('\n')); assert!(subject.starts_with("New: xBcc: evil@example.com")); let long = "a".repeat(500); assert_eq!( render_subject("{title}", &[("title", &long)]) .chars() .count(), MAIL_SUBJECT_MAX ); assert_eq!( render_subject("{nope} {key}", &[("key", "IZ-1")]), "{nope} IZ-1" ); } }