forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

rules.rs375 lines, 12.1 KiBHistoryRawDownload
1//! Mail rules, pure part: the closed set of triggers and audiences, the verdict of one rule on one
2//! event, and the rendering of a rule's subject. No I/O. The store (`store/rules_engine.rs`) loads the
3//! facts (task, members, eligible recipients) and writes the decisions and outbox rows this module decides.
4//!
5//! Invariants kept here: the actor of an event is never a recipient of it; a recipient is always one of
6//! the eligible members handed in (enabled, role admin or member), so a viewer, a role `none` member and a
7//! disabled member can never be owed mail; a subject is plain text with no control characters, at most
8//! `MAIL_SUBJECT_MAX` characters, whatever the template or the values were.
9
10use crate::limits::MAIL_SUBJECT_MAX;
11
12/// Every trigger a rule can name. The schema CHECK lists the same twelve words.
13pub const TRIGGERS: [&str; 12] = [
14 "status",
15 "unblocked",
16 "created",
17 "assigned",
18 "unassigned",
19 "commented",
20 "deadline_set",
21 "deadline_cleared",
22 "retitled",
23 "linked",
24 "unlinked",
25 "deleted",
26];
27
28/// Who a rule mails. The schema CHECK lists the same four words.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum Audience {
31 /// The task's assignees. For `assigned` and `unassigned`, only the person named by the event.
32 Assignees,
33 /// Every eligible member of the board.
34 Board,
35 /// The member who created the task.
36 Creator,
37 /// The members who opted in to watch this task.
38 Watchers,
39}
40
41impl Audience {
42 /// The stored spelling.
43 pub fn as_str(self) -> &'static str {
44 match self {
45 Audience::Assignees => "assignees",
46 Audience::Board => "board",
47 Audience::Creator => "creator",
48 Audience::Watchers => "watchers",
49 }
50 }
51
52 /// Parses the stored spelling. Unknown text is `None`.
53 pub fn parse(text: &str) -> Option<Audience> {
54 match text {
55 "assignees" => Some(Audience::Assignees),
56 "board" => Some(Audience::Board),
57 "creator" => Some(Audience::Creator),
58 "watchers" => Some(Audience::Watchers),
59 _ => None,
60 }
61 }
62}
63
64/// Whether `text` is one of the triggers.
65pub fn is_trigger(text: &str) -> bool {
66 TRIGGERS.contains(&text)
67}
68
69/// The rule fields a verdict depends on.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct RuleFacts {
72 /// Whether the rule is switched on.
73 pub enabled: bool,
74 /// Only for `status`: the column that must be entered. `None` means any column.
75 pub column_id: Option<String>,
76 /// The project the task must wear. `None` means any project.
77 pub tag_id: Option<String>,
78 /// Who is mailed.
79 pub audience: Audience,
80}
81
82/// The event fields a verdict depends on.
83#[derive(Debug, Clone, PartialEq, Eq)]
84pub struct EventFacts {
85 /// The trigger word of the event.
86 pub kind: String,
87 /// The member the event names (the person assigned or removed), if any.
88 pub subject: Option<String>,
89 /// The column the task entered, for `status` events.
90 pub column_id: Option<String>,
91 /// Who did it. Never mailed about their own action.
92 pub actor: Option<String>,
93}
94
95/// The task fields a verdict depends on, as they are now.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct TaskFacts {
98 /// The project the task wears.
99 pub tag_id: String,
100 /// Whether the task is soft-deleted.
101 pub deleted: bool,
102 /// Who created it.
103 pub creator: String,
104 /// Current assignees, sorted.
105 pub assignees: Vec<String>,
106 /// Members who watch the task, sorted.
107 pub watchers: Vec<String>,
108}
109
110/// Why a rule does not apply to an event whose task is in the wrong state or place.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum Mismatch {
113 /// A status rule names another column.
114 Column,
115 /// The rule is limited to another project.
116 Project,
117}
118
119impl Mismatch {
120 /// The text stored in the decision ledger.
121 pub fn as_str(self) -> &'static str {
122 match self {
123 Mismatch::Column => "column",
124 Mismatch::Project => "project",
125 }
126 }
127}
128
129/// The outcome of one rule on one event, before any row is written.
130#[derive(Debug, Clone, PartialEq, Eq)]
131pub enum Verdict {
132 /// The rule is off.
133 Disabled,
134 /// The task is gone (deleted before the event was handled), so the mail would be about nothing.
135 TaskGone,
136 /// The event does not match the rule's column or project.
137 NotMatched(Mismatch),
138 /// The rule applies, but nobody eligible is in the audience (after removing the actor).
139 NoRecipients,
140 /// These members are owed the mail, sorted.
141 Owed(Vec<String>),
142}
143
144/// Decides one rule on one event. `task` is `None` when the task row does not exist. `eligible` is every
145/// member who may receive mail (enabled, role admin or member), sorted.
146pub fn evaluate(
147 rule: &RuleFacts,
148 event: &EventFacts,
149 task: Option<&TaskFacts>,
150 eligible: &[String],
151) -> Verdict {
152 if !rule.enabled {
153 return Verdict::Disabled;
154 }
155 let Some(task) = task else {
156 return Verdict::TaskGone;
157 };
158 // A deleted task still announces its own deletion; any other event about it is gone.
159 if task.deleted && event.kind != "deleted" {
160 return Verdict::TaskGone;
161 }
162 if let Some(column) = &rule.column_id
163 && event.column_id.as_deref() != Some(column.as_str())
164 {
165 return Verdict::NotMatched(Mismatch::Column);
166 }
167 if let Some(tag) = &rule.tag_id
168 && *tag != task.tag_id
169 {
170 return Verdict::NotMatched(Mismatch::Project);
171 }
172 let owed = audience(rule.audience, event, task, eligible);
173 if owed.is_empty() {
174 Verdict::NoRecipients
175 } else {
176 Verdict::Owed(owed)
177 }
178}
179
180/// The recipients of an audience: the candidates, restricted to the eligible members and without the actor.
181/// Sorted and without duplicates. `eligible` may be in any order.
182pub fn audience(
183 audience: Audience,
184 event: &EventFacts,
185 task: &TaskFacts,
186 eligible: &[String],
187) -> Vec<String> {
188 let candidates: Vec<&String> = match audience {
189 Audience::Assignees if matches!(event.kind.as_str(), "assigned" | "unassigned") => {
190 event.subject.iter().collect()
191 }
192 Audience::Assignees => task.assignees.iter().collect(),
193 Audience::Board => eligible.iter().collect(),
194 Audience::Creator => vec![&task.creator],
195 Audience::Watchers => task.watchers.iter().collect(),
196 };
197 let mut out: Vec<String> = candidates
198 .into_iter()
199 .filter(|sub| eligible.contains(sub))
200 .filter(|sub| event.actor.as_deref() != Some(sub.as_str()))
201 .cloned()
202 .collect();
203 out.sort();
204 out.dedup();
205 out
206}
207
208/// Removes every control character (CR, LF, tab, NUL and the rest of the C0 and C1 sets) and the Unicode
209/// direction and zero-width format marks that let text pass for something else. Values that go into a
210/// mail header or a subject are cleaned with this first.
211pub fn clean_text(text: &str) -> String {
212 text.chars().filter(|c| !is_unsafe_char(*c)).collect()
213}
214
215/// Whether a character must never reach a mail header or a subject.
216fn is_unsafe_char(c: char) -> bool {
217 c.is_control()
218 || matches!(c, '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}')
219}
220
221/// Renders a subject from its template: `{name}` is replaced by the value of `name` in `vars`. A name
222/// that is not in `vars` stays as written, so a typo shows in the mail instead of vanishing. The values
223/// are inserted as they are and are never scanned again. The result is cleaned with [`clean_text`] and
224/// cut to [`MAIL_SUBJECT_MAX`] characters.
225pub fn render_subject(template: &str, vars: &[(&str, &str)]) -> String {
226 let mut out = String::with_capacity(template.len());
227 let mut rest = template;
228 while let Some(open) = rest.find('{') {
229 out.push_str(&rest[..open]);
230 let after = &rest[open + 1..];
231 let Some(close) = after.find('}') else {
232 out.push_str(&rest[open..]);
233 rest = "";
234 break;
235 };
236 let name = &after[..close];
237 match vars.iter().find(|(key, _)| *key == name) {
238 Some((_, value)) => out.push_str(value),
239 None => {
240 out.push('{');
241 out.push_str(name);
242 out.push('}');
243 }
244 }
245 rest = &after[close + 1..];
246 }
247 out.push_str(rest);
248 clean_text(&out)
249 .trim()
250 .chars()
251 .take(MAIL_SUBJECT_MAX)
252 .collect()
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 fn facts(assignees: &[&str], watchers: &[&str]) -> TaskFacts {
260 TaskFacts {
261 tag_id: "t1".into(),
262 deleted: false,
263 creator: "ada".into(),
264 assignees: assignees.iter().map(|s| s.to_string()).collect(),
265 watchers: watchers.iter().map(|s| s.to_string()).collect(),
266 }
267 }
268
269 fn event(kind: &str, subject: Option<&str>) -> EventFacts {
270 EventFacts {
271 kind: kind.into(),
272 subject: subject.map(str::to_owned),
273 column_id: None,
274 actor: Some("ada".into()),
275 }
276 }
277
278 fn rule(audience: Audience) -> RuleFacts {
279 RuleFacts {
280 enabled: true,
281 column_id: None,
282 tag_id: None,
283 audience,
284 }
285 }
286
287 #[test]
288 fn the_actor_is_never_owed_and_ineligible_members_never_are() {
289 let eligible = vec!["bo".to_owned(), "ada".to_owned()];
290 // "cy" is assigned but not eligible (a viewer, a disabled or a role-none member).
291 let task = facts(&["ada", "bo", "cy"], &[]);
292 let verdict = evaluate(
293 &rule(Audience::Assignees),
294 &event("commented", None),
295 Some(&task),
296 &eligible,
297 );
298 assert_eq!(verdict, Verdict::Owed(vec!["bo".to_owned()]));
299 }
300
301 #[test]
302 fn assignment_events_name_only_the_person_just_assigned() {
303 let eligible = vec!["bo".to_owned(), "cy".to_owned()];
304 let task = facts(&["bo", "cy"], &[]);
305 let verdict = evaluate(
306 &rule(Audience::Assignees),
307 &event("assigned", Some("cy")),
308 Some(&task),
309 &eligible,
310 );
311 assert_eq!(verdict, Verdict::Owed(vec!["cy".to_owned()]));
312 }
313
314 #[test]
315 fn disabled_gone_and_mismatched_rules_owe_nothing() {
316 let eligible = vec!["bo".to_owned()];
317 let task = facts(&["bo"], &[]);
318 let mut off = rule(Audience::Board);
319 off.enabled = false;
320 assert_eq!(
321 evaluate(&off, &event("created", None), Some(&task), &eligible),
322 Verdict::Disabled
323 );
324 assert_eq!(
325 evaluate(
326 &rule(Audience::Board),
327 &event("created", None),
328 None,
329 &eligible
330 ),
331 Verdict::TaskGone
332 );
333 let mut deleted = facts(&["bo"], &[]);
334 deleted.deleted = true;
335 assert_eq!(
336 evaluate(
337 &rule(Audience::Board),
338 &event("commented", None),
339 Some(&deleted),
340 &eligible
341 ),
342 Verdict::TaskGone
343 );
344 let mut status = rule(Audience::Board);
345 status.column_id = Some("done".into());
346 let mut moved = event("status", None);
347 moved.column_id = Some("todo".into());
348 assert_eq!(
349 evaluate(&status, &moved, Some(&task), &eligible),
350 Verdict::NotMatched(Mismatch::Column)
351 );
352 }
353
354 #[test]
355 fn subject_is_plain_text_without_line_breaks_and_capped() {
356 let title = "x\r\nBcc: evil@example.com";
357 let subject = render_subject(
358 "New: {title}\r\nBcc: {key}",
359 &[("title", title), ("key", "IZ-7")],
360 );
361 assert!(!subject.contains('\r') && !subject.contains('\n'));
362 assert!(subject.starts_with("New: xBcc: evil@example.com"));
363 let long = "a".repeat(500);
364 assert_eq!(
365 render_subject("{title}", &[("title", &long)])
366 .chars()
367 .count(),
368 MAIL_SUBJECT_MAX
369 );
370 assert_eq!(
371 render_subject("{nope} {key}", &[("key", "IZ-1")]),
372 "{nope} IZ-1"
373 );
374 }
375}