forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

rules_engine.rs608 lines, 21.6 KiBHistoryRawDownload
1//! The rules engine: turns queued events into decisions and outbox rows.
2//!
3//! One pass reads up to `batch` unprocessed events in order and handles all of them in one transaction:
4//! for each event, every rule with its trigger gets one decision row (outcome and reason) and, when it
5//! owes mail, one outbox row per recipient. The unique keys (decision per rule, event and task; outbox per
6//! rule, event, task and recipient) make a repeated pass a no-op. The pass either commits everything or
7//! nothing, so a crash between the two leaves the events unprocessed and they are handled again.
8//!
9//! Recipients come from the eligible members only (enabled, role admin or member), and the actor is
10//! removed by `rules::audience`. Mail text is built per recipient in the recipient's language and zone.
11
12use jiff::Timestamp;
13use turso::Connection;
14use turso::transaction::Transaction;
15
16use super::outbox::{OutboxDraft, insert_outbox};
17use super::{col_int, col_opt_text, col_text, db_err, fetch_all, fetch_opt, finish, new_id};
18use crate::clock::stamp_of;
19use crate::error::Result;
20use crate::mail_text::{MailLang, RuleMail, rule_body, when_text};
21use crate::rules::{Audience, EventFacts, RuleFacts, TaskFacts, Verdict, evaluate, render_subject};
22use crate::sender::DEFAULT_RULE_CAP;
23use crate::store::Store;
24use crate::store::sender::KEY_RULE_CAP;
25use crate::time::now_stamp;
26
27/// What one event's handling needs from the pass: the hourly cap and where its window starts.
28#[derive(Clone, Copy)]
29struct Limits<'a> {
30 cap: i64,
31 window_start: &'a str,
32}
33
34/// One unprocessed event as read back.
35struct QueuedEvent {
36 id: String,
37 board_id: String,
38 task_id: Option<String>,
39 kind: String,
40 column_id: Option<String>,
41 actor: Option<String>,
42 subject: Option<String>,
43}
44
45/// An eligible member: enabled, role admin or member. The language and zone are the ones mail uses.
46#[derive(Clone)]
47struct Eligible {
48 sub: String,
49 lang: MailLang,
50 zone: String,
51}
52
53/// The task row fields a mail body needs.
54struct TaskRow {
55 key: String,
56 title: String,
57 column_id: String,
58 tag_id: String,
59 deadline: Option<String>,
60 meeting_at: Option<String>,
61 deleted: bool,
62 creator: String,
63}
64
65/// What one pass did. Returned for logs and tests.
66#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
67pub struct PassReport {
68 /// Events handled in this pass.
69 pub events: usize,
70 /// Outbox rows queued in this pass.
71 pub mails: usize,
72}
73
74/// The eligible members of the instance, sorted by id.
75async fn eligible_members(tx: &Transaction<'_>) -> Result<Vec<Eligible>> {
76 fetch_all(
77 tx,
78 "SELECT sub, locale, locale_override, zoneinfo FROM members \
79 WHERE disabled = 0 AND (im_admin = 1 OR role IN ('admin', 'member')) ORDER BY sub",
80 (),
81 |row| {
82 let locale = col_opt_text(row, 1)?;
83 let locale_override = col_opt_text(row, 2)?;
84 Ok(Eligible {
85 sub: col_text(row, 0)?,
86 lang: MailLang::of(locale_override.as_deref(), locale.as_deref()),
87 zone: col_text(row, 3)?,
88 })
89 },
90 )
91 .await
92}
93
94/// The task row of `task_id` on `board_id`, deleted or not.
95async fn task_row(conn: &Connection, board_id: &str, task_id: &str) -> Result<Option<TaskRow>> {
96 fetch_opt(
97 conn,
98 "SELECT key, title, column_id, tag_id, deadline, meeting_at, deleted_at, created_by FROM tasks \
99 WHERE id = ?1 AND board_id = ?2",
100 (task_id.to_owned(), board_id.to_owned()),
101 |row| {
102 Ok(TaskRow {
103 key: col_text(row, 0)?,
104 title: col_text(row, 1)?,
105 column_id: col_text(row, 2)?,
106 tag_id: col_text(row, 3)?,
107 deadline: col_opt_text(row, 4)?,
108 meeting_at: col_opt_text(row, 5)?,
109 deleted: col_opt_text(row, 6)?.is_some(),
110 creator: col_text(row, 7)?,
111 })
112 },
113 )
114 .await
115}
116
117/// Sorted ids of the people assigned to `task_id`, and the names in the same order.
118async fn assignees_of(conn: &Connection, task_id: &str) -> Result<Vec<(String, String)>> {
119 fetch_all(
120 conn,
121 "SELECT a.sub, m.name FROM task_assignees a JOIN members m ON m.sub = a.sub \
122 WHERE a.task_id = ?1 ORDER BY a.sub",
123 (task_id.to_owned(),),
124 |row| Ok((col_text(row, 0)?, col_text(row, 1)?)),
125 )
126 .await
127}
128
129/// Sorted ids of the members who watch `task_id`.
130async fn watchers_of(conn: &Connection, task_id: &str) -> Result<Vec<String>> {
131 fetch_all(
132 conn,
133 "SELECT sub FROM task_watchers WHERE task_id = ?1 ORDER BY sub",
134 (task_id.to_owned(),),
135 |row| col_text(row, 0),
136 )
137 .await
138}
139
140/// A name by id, or empty when the member is unknown.
141async fn name_of(conn: &Connection, sub: &str) -> Result<String> {
142 Ok(fetch_opt(
143 conn,
144 "SELECT name FROM members WHERE sub = ?1",
145 (sub.to_owned(),),
146 |row| col_text(row, 0),
147 )
148 .await?
149 .unwrap_or_default())
150}
151
152/// A column or project name by id, or empty when it is gone.
153async fn label_of(conn: &Connection, table: &'static str, id: &str) -> Result<String> {
154 let sql = match table {
155 "columns" => "SELECT name FROM columns WHERE id = ?1",
156 _ => "SELECT name FROM tags WHERE id = ?1",
157 };
158 Ok(
159 fetch_opt(conn, sql, (id.to_owned(),), |row| col_text(row, 0))
160 .await?
161 .unwrap_or_default(),
162 )
163}
164
165/// The link back to a task. The base has no trailing slash (see `config.base_url`).
166pub fn task_link(base_url: &str, key: &str) -> String {
167 format!("{}/?task={key}", base_url.trim_end_matches('/'))
168}
169
170/// Handles one event: every rule of its trigger gets a decision, and mail rows for the owed recipients.
171/// A recipient already queued `limits.cap` rule mails since `limits.window_start` gets none; the decision
172/// then records `skipped` with the detail `rate_limited`.
173async fn handle(
174 tx: &Transaction<'_>,
175 event: &QueuedEvent,
176 base_url: &str,
177 limits: Limits<'_>,
178) -> Result<usize> {
179 let rules = fetch_all(
180 tx,
181 "SELECT id, column_id, tag_id, audience, enabled, subject_template, include_details FROM mail_rules \
182 WHERE board_id = ?1 AND trigger = ?2 ORDER BY created_at, id",
183 (event.board_id.clone(), event.kind.clone()),
184 |row| {
185 let audience_text = col_text(row, 3)?;
186 let audience = Audience::parse(&audience_text).unwrap_or(Audience::Assignees);
187 Ok((
188 col_text(row, 0)?,
189 RuleFacts {
190 enabled: col_int(row, 4)? == 1,
191 column_id: col_opt_text(row, 1)?,
192 tag_id: col_opt_text(row, 2)?,
193 audience,
194 },
195 col_text(row, 5)?,
196 col_int(row, 6)? == 1,
197 ))
198 },
199 )
200 .await?;
201 if rules.is_empty() {
202 return Ok(0);
203 }
204 let eligible = eligible_members(tx).await?;
205 let subs: Vec<String> = eligible.iter().map(|m| m.sub.clone()).collect();
206 let task = match &event.task_id {
207 Some(task_id) => task_row(tx, &event.board_id, task_id).await?,
208 None => None,
209 };
210 let facts = match (&event.task_id, &task) {
211 (Some(task_id), Some(row)) => Some(TaskFacts {
212 tag_id: row.tag_id.clone(),
213 deleted: row.deleted,
214 creator: row.creator.clone(),
215 assignees: assignees_of(tx, task_id)
216 .await?
217 .into_iter()
218 .map(|(sub, _)| sub)
219 .collect(),
220 watchers: watchers_of(tx, task_id).await?,
221 }),
222 _ => None,
223 };
224 let event_facts = EventFacts {
225 kind: event.kind.clone(),
226 subject: event.subject.clone(),
227 column_id: event.column_id.clone(),
228 actor: event.actor.clone(),
229 };
230 let actor_name = match &event.actor {
231 Some(actor) => name_of(tx, actor).await?,
232 None => String::new(),
233 };
234 let subject_name = match &event.subject {
235 Some(sub) => name_of(tx, sub).await?,
236 None => String::new(),
237 };
238 let queued_at = now_stamp();
239 let mut mails = 0;
240 for (rule_id, rule, template, details) in &rules {
241 let verdict = evaluate(rule, &event_facts, facts.as_ref(), &subs);
242 let (outcome, detail, recipients) = match &verdict {
243 Verdict::Disabled => ("disabled", String::new(), Vec::new()),
244 Verdict::TaskGone => ("task_gone", String::new(), Vec::new()),
245 Verdict::NotMatched(reason) => ("not_matched", reason.as_str().to_owned(), Vec::new()),
246 Verdict::NoRecipients => ("no_recipients", "empty".to_owned(), Vec::new()),
247 Verdict::Owed(recipients) => ("owed", String::new(), recipients.clone()),
248 };
249 let mut queued = 0;
250 let mut capped = 0;
251 if let (Some(row), Some(task_id)) = (&task, &event.task_id) {
252 let column_id = event
253 .column_id
254 .clone()
255 .unwrap_or_else(|| row.column_id.clone());
256 let column = label_of(tx, "columns", &column_id).await?;
257 let tag = label_of(tx, "tags", &row.tag_id).await?;
258 let assignees: Vec<String> = assignees_of(tx, task_id)
259 .await?
260 .into_iter()
261 .map(|(_, n)| n)
262 .collect();
263 let link = task_link(base_url, &row.key);
264 for sub in &recipients {
265 let Some(member) = eligible.iter().find(|m| &m.sub == sub) else {
266 continue;
267 };
268 let sent_before = fetch_opt(
269 tx,
270 "SELECT COUNT(*) FROM mail_outbox WHERE recipient = ?1 AND kind = 'rule' AND created_at >= ?2",
271 (sub.clone(), limits.window_start.to_owned()),
272 |row| col_int(row, 0),
273 )
274 .await?
275 .unwrap_or(0);
276 if sent_before >= limits.cap {
277 capped += 1;
278 tracing::warn!(recipient = %sub, cap = limits.cap, "rule mail held back by the hourly cap");
279 continue;
280 }
281 let when = row
282 .meeting_at
283 .as_deref()
284 .and_then(|at| when_text(at, &member.zone));
285 let subject = render_subject(
286 template,
287 &[
288 ("key", &row.key),
289 ("title", &row.title),
290 ("column", &column),
291 ("actor", &actor_name),
292 ("tag", &tag),
293 ("deadline", row.deadline.as_deref().unwrap_or("")),
294 ],
295 );
296 let body = rule_body(&RuleMail {
297 lang: member.lang,
298 kind: &event.kind,
299 actor: &actor_name,
300 subject_name: &subject_name,
301 key: &row.key,
302 title: &row.title,
303 column: &column,
304 deadline: row.deadline.as_deref(),
305 assignees: &assignees,
306 when: when.as_deref(),
307 link: &link,
308 details: *details,
309 subject: &subject,
310 });
311 let draft = OutboxDraft {
312 rule_id: Some(rule_id),
313 event_id: &event.id,
314 task_id: Some(task_id),
315 recipient: sub,
316 kind: "rule",
317 subject: &subject,
318 body: &body,
319 next_attempt_at: &queued_at,
320 };
321 if insert_outbox(tx, &draft).await? {
322 queued += 1;
323 }
324 }
325 }
326 mails += queued;
327 let (outcome, detail) = if capped > 0 {
328 let outcome = if queued == 0 { "skipped" } else { outcome };
329 (outcome, "rate_limited".to_owned())
330 } else if outcome == "owed" && queued == 0 {
331 ("already_owed", detail)
332 } else {
333 (outcome, detail)
334 };
335 tx.execute(
336 "INSERT INTO mail_decisions (id, rule_id, event_id, task_id, outcome, detail, created_at) \
337 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7) ON CONFLICT(rule_id, event_id, task_id) DO NOTHING",
338 (
339 new_id(),
340 rule_id.clone(),
341 event.id.clone(),
342 event.task_id.clone(),
343 outcome,
344 detail,
345 now_stamp(),
346 ),
347 )
348 .await
349 .map_err(db_err)?;
350 }
351 Ok(mails)
352}
353
354impl Store {
355 /// One pass of the rules engine over up to `batch` queued events, in one transaction. `now` stamps the
356 /// outbox rows; `base_url` is the link base of the mails.
357 pub async fn run_rules(
358 &self,
359 now: Timestamp,
360 base_url: &str,
361 batch: usize,
362 ) -> Result<PassReport> {
363 let conn = self.inner.conn.lock().await;
364 let tx = conn.unchecked_transaction().await.map_err(db_err)?;
365 let outcome: Result<PassReport> = async {
366 let events = fetch_all(
367 &tx,
368 "SELECT id, board_id, task_id, kind, column_id, actor, subject FROM mail_events \
369 WHERE processed_at IS NULL ORDER BY at, id LIMIT ?1",
370 (i64::try_from(batch).unwrap_or(i64::MAX),),
371 |row| {
372 Ok(QueuedEvent {
373 id: col_text(row, 0)?,
374 board_id: col_text(row, 1)?,
375 task_id: col_opt_text(row, 2)?,
376 kind: col_text(row, 3)?,
377 column_id: col_opt_text(row, 4)?,
378 actor: col_opt_text(row, 5)?,
379 subject: col_opt_text(row, 6)?,
380 })
381 },
382 )
383 .await?;
384 let mut report = PassReport::default();
385 let stamp = stamp_of(now)?;
386 let cap = fetch_opt(
387 &tx,
388 "SELECT value FROM settings WHERE key = ?1",
389 (KEY_RULE_CAP.to_owned(),),
390 |row| col_text(row, 0),
391 )
392 .await?
393 .and_then(|v| v.parse::<u32>().ok())
394 .unwrap_or(DEFAULT_RULE_CAP)
395 .min(crate::limits::REMINDER_CAP_MAX);
396 let window_start = stamp_of(now - jiff::SignedDuration::from_hours(1))?;
397 let limits = Limits {
398 cap: i64::from(cap),
399 window_start: &window_start,
400 };
401 for event in &events {
402 report.mails += handle(&tx, event, base_url, limits).await?;
403 tx.execute(
404 "UPDATE mail_events SET processed_at = ?2 WHERE id = ?1",
405 (event.id.clone(), stamp.clone()),
406 )
407 .await
408 .map_err(db_err)?;
409 report.events += 1;
410 }
411 Ok(report)
412 }
413 .await;
414 finish(tx, outcome).await
415 }
416}
417
418#[cfg(test)]
419mod tests {
420 use jiff::{SignedDuration, Timestamp};
421
422 use super::*;
423 use crate::clock::stamp_of;
424 use crate::store::rules::RuleInput;
425 use crate::store::tasks::{NewTask, TaskEdit};
426 use crate::store::test_support::seeded;
427 use crate::time::stamp_after;
428 use std::time::Duration;
429
430 const BASE: &str = "http://127.0.0.1:7654";
431
432 fn rule(trigger: &str, audience: &str) -> RuleInput {
433 RuleInput {
434 name: "Test rule".into(),
435 trigger: trigger.into(),
436 column_id: None,
437 tag_id: None,
438 audience: audience.into(),
439 include_details: true,
440 enabled: true,
441 subject_template: "{key} {title}".into(),
442 }
443 }
444
445 fn new_task(column: &str, tag: &str, assignees: &[&str], meeting: Option<String>) -> NewTask {
446 NewTask {
447 title: "Dentist".into(),
448 description: String::new(),
449 column_id: column.into(),
450 tag_id: tag.into(),
451 deadline: None,
452 meeting_at: meeting,
453 assignees: assignees.iter().map(|s| s.to_string()).collect(),
454 parent_id: None,
455 link: None,
456 }
457 }
458
459 /// The first column and the default project of the board.
460 async fn column_and_tag(store: &Store, board_id: &str) -> (String, String) {
461 let column = store.columns(board_id).await.unwrap()[0].id.clone();
462 let tag = store.tags(board_id).await.unwrap()[0].id.clone();
463 (column, tag)
464 }
465
466 #[tokio::test]
467 async fn a_mail_event_cannot_trigger_a_rule() {
468 let (_dir, store, board_id) = seeded().await;
469 store
470 .create_rule(&board_id, &rule("commented", "board"))
471 .await
472 .unwrap();
473 // A notice is mail, not a board event: queuing and sending it writes no event.
474 let queued = store
475 .queue_message("ada", "Hello", "Bye", Timestamp::now())
476 .await
477 .unwrap();
478 assert_eq!(queued, 1);
479 let now = Timestamp::now();
480 for row in store.claim_due(now, 10).await.unwrap() {
481 store.mark_sent(&row.id, now).await.unwrap();
482 }
483 let report = store.run_rules(now, BASE, 100).await.unwrap();
484 assert_eq!(
485 report,
486 PassReport {
487 events: 0,
488 mails: 0
489 }
490 );
491 let rule_mail = store
492 .outbox_page(None, 100)
493 .await
494 .unwrap()
495 .items
496 .iter()
497 .filter(|row| row.kind == "rule")
498 .count();
499 assert_eq!(rule_mail, 0);
500 }
501
502 #[tokio::test]
503 async fn a_ghost_member_and_the_actor_receive_nothing() {
504 let (_dir, store, board_id) = seeded().await;
505 let (column, tag) = column_and_tag(&store, &board_id).await;
506 let ghost = crate::store::members::DirectoryMember {
507 sub: "ghost".into(),
508 email: "ghost@example.com".into(),
509 name: "Ghost".into(),
510 im_admin: false,
511 disabled: false,
512 locale: None,
513 zoneinfo: "UTC".into(),
514 picture_version: 0,
515 updated_at: "2026-10-28T09:00:00.000000000Z".into(),
516 };
517 store
518 .apply_directory_member(&ghost, crate::authz::Role::Member)
519 .await
520 .unwrap();
521 store
522 .create_rule(&board_id, &rule("created", "board"))
523 .await
524 .unwrap();
525 store
526 .create_task(
527 &board_id,
528 new_task(&column, &tag, &["bo", "ghost"], None),
529 "ada",
530 )
531 .await
532 .unwrap();
533 // The member leaves the family after being assigned: the queued mail must not reach them.
534 let mut gone = ghost.clone();
535 gone.disabled = true;
536 store
537 .apply_directory_member(&gone, crate::authz::Role::Member)
538 .await
539 .unwrap();
540 store.run_rules(Timestamp::now(), BASE, 100).await.unwrap();
541 let rows = store.outbox_page(None, 100).await.unwrap().items;
542 let recipients: Vec<&str> = rows.iter().map(|r| r.recipient.as_str()).collect();
543 assert_eq!(
544 recipients,
545 vec!["bo"],
546 "only the eligible, non-acting member is mailed"
547 );
548 // Anybody claiming the queued mail after the change is refused as well.
549 let claimed = store.claim_due(Timestamp::now(), 10).await.unwrap();
550 assert!(claimed.iter().all(|r| r.recipient != "ghost"));
551 }
552
553 #[tokio::test]
554 async fn a_reminder_fires_once_per_meeting_and_re_arms_after_a_change() {
555 let (_dir, store, board_id) = seeded().await;
556 let (column, tag) = column_and_tag(&store, &board_id).await;
557 let now = Timestamp::now();
558 let meeting = stamp_after(Duration::from_secs(2 * 3600));
559 let task = store
560 .create_task(
561 &board_id,
562 new_task(&column, &tag, &["bo"], Some(meeting)),
563 "ada",
564 )
565 .await
566 .unwrap();
567 let reminders_for_bo = |store: &Store| {
568 let store = store.clone();
569 async move {
570 store
571 .outbox_page(None, 200)
572 .await
573 .unwrap()
574 .items
575 .iter()
576 .filter(|r| r.kind == "reminder" && r.recipient == "bo")
577 .count()
578 }
579 };
580 // Past the due time (meeting minus 15 minutes) once: one reminder.
581 let after_due = now + SignedDuration::from_mins(110);
582 store.run_reminders(after_due, BASE, 20, 100).await.unwrap();
583 store.run_reminders(after_due, BASE, 20, 100).await.unwrap();
584 assert_eq!(reminders_for_bo(&store).await, 1);
585 // Moving the meeting re-arms the reminder for the new due value.
586 let moved = stamp_of(now + SignedDuration::from_hours(4)).unwrap();
587 let edit = TaskEdit {
588 title: task.title.clone(),
589 description: task.description.clone(),
590 tag_id: task.tag_id.clone(),
591 deadline: None,
592 meeting_at: Some(moved),
593 };
594 store
595 .edit_task(&board_id, &task.id, edit, "ada")
596 .await
597 .unwrap();
598 store
599 .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100)
600 .await
601 .unwrap();
602 store
603 .run_reminders(now + SignedDuration::from_hours(5), BASE, 20, 100)
604 .await
605 .unwrap();
606 assert_eq!(reminders_for_bo(&store).await, 2);
607 }
608}