forge
Explore
Log in

Don't you dare go Hollow

iz

Clone
★ 0

0 watching0 forksRustAGPL-3.0567.3 KiB3950aceTahinli27 days ago34 commits

rules.rs295 lines, 9.9 KiBHistoryRawDownload
1//! Mail rules as stored: the list, the create/edit/delete writes and the enable switch. The rules
2//! themselves are evaluated in `rules_engine.rs`. Every write is checked here: the trigger and audience
3//! words, the column only for `status`, and the column and project belonging to the board.
4
5use turso::Connection;
6
7use super::{col_bool, col_opt_text, col_text, db_err, fetch_all, fetch_opt, new_id};
8use crate::error::{Error, Result};
9use crate::limits::RULE_SUBJECT_MAX;
10use crate::rules::{Audience, is_trigger};
11use crate::store::Store;
12use crate::time::now_stamp;
13
14/// The longest rule name, in characters.
15pub const RULE_NAME_MAX: usize = 120;
16
17/// One rule as stored.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct MailRule {
20 /// Rule id (ULID).
21 pub id: String,
22 /// The board it belongs to.
23 pub board_id: String,
24 /// The admin's name for it.
25 pub name: String,
26 /// The trigger word.
27 pub trigger: String,
28 /// Only for `status`: the column that must be entered; `None` is any column.
29 pub column_id: Option<String>,
30 /// The project it is limited to; `None` is any project.
31 pub tag_id: Option<String>,
32 /// Who is mailed.
33 pub audience: Audience,
34 /// Whether the mail carries the details block.
35 pub include_details: bool,
36 /// Whether the rule is on.
37 pub enabled: bool,
38 /// The subject template, with `{key}`, `{title}`, `{column}`, `{actor}`, `{tag}`, `{deadline}`.
39 pub subject_template: String,
40 /// UTC stamp of creation.
41 pub created_at: String,
42}
43
44/// The fields of a rule as the admin enters them. The store checks them all.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct RuleInput {
47 /// Name, 1 to 120 characters.
48 pub name: String,
49 /// The trigger word.
50 pub trigger: String,
51 /// Column, only with the `status` trigger.
52 pub column_id: Option<String>,
53 /// Project, or `None` for any.
54 pub tag_id: Option<String>,
55 /// Audience word.
56 pub audience: String,
57 /// Whether to include the details block.
58 pub include_details: bool,
59 /// Whether the rule is on.
60 pub enabled: bool,
61 /// Subject template, 1 to 120 characters.
62 pub subject_template: String,
63}
64
65const RULE_COLS: &str = "id, board_id, name, trigger, column_id, tag_id, audience, include_details, enabled, \
66 subject_template, created_at";
67
68fn map_rule(row: &turso::Row) -> Result<MailRule> {
69 let audience_text = col_text(row, 6)?;
70 let audience = Audience::parse(&audience_text)
71 .ok_or_else(|| Error::Database(format!("unknown stored audience: {audience_text}")))?;
72 Ok(MailRule {
73 id: col_text(row, 0)?,
74 board_id: col_text(row, 1)?,
75 name: col_text(row, 2)?,
76 trigger: col_text(row, 3)?,
77 column_id: col_opt_text(row, 4)?,
78 tag_id: col_opt_text(row, 5)?,
79 audience,
80 include_details: col_bool(row, 7)?,
81 enabled: col_bool(row, 8)?,
82 subject_template: col_text(row, 9)?,
83 created_at: col_text(row, 10)?,
84 })
85}
86
87/// Checks the input and returns the cleaned copy. Every refusal is a message for the admin.
88async fn checked(conn: &Connection, board_id: &str, input: &RuleInput) -> Result<RuleInput> {
89 let name = crate::text::single_line(&input.name);
90 if name.is_empty() || name.chars().count() > RULE_NAME_MAX {
91 return Err(Error::Invalid(format!(
92 "the name must be 1 to {RULE_NAME_MAX} characters"
93 )));
94 }
95 let trigger = input.trigger.trim().to_owned();
96 if !is_trigger(&trigger) {
97 return Err(Error::Invalid("that trigger does not exist".into()));
98 }
99 let column_id = match input
100 .column_id
101 .as_deref()
102 .map(str::trim)
103 .filter(|c| !c.is_empty())
104 {
105 None => None,
106 Some(column) if trigger == "status" => {
107 let live = fetch_opt(
108 conn,
109 "SELECT id FROM columns WHERE id = ?1 AND board_id = ?2 AND deleted_at IS NULL",
110 (column.to_owned(), board_id.to_owned()),
111 |row| col_text(row, 0),
112 )
113 .await?;
114 if live.is_none() {
115 return Err(Error::Invalid("that column does not exist".into()));
116 }
117 Some(column.to_owned())
118 }
119 Some(_) => {
120 return Err(Error::Invalid(
121 "only a status rule can name a column".into(),
122 ));
123 }
124 };
125 let tag_id = match input
126 .tag_id
127 .as_deref()
128 .map(str::trim)
129 .filter(|t| !t.is_empty())
130 {
131 None => None,
132 Some(tag) => {
133 let known = fetch_opt(
134 conn,
135 "SELECT id FROM tags WHERE id = ?1 AND board_id = ?2",
136 (tag.to_owned(), board_id.to_owned()),
137 |row| col_text(row, 0),
138 )
139 .await?;
140 if known.is_none() {
141 return Err(Error::Invalid("that project does not exist".into()));
142 }
143 Some(tag.to_owned())
144 }
145 };
146 let audience = input.audience.trim().to_owned();
147 if Audience::parse(&audience).is_none() {
148 return Err(Error::Invalid("that audience does not exist".into()));
149 }
150 let subject_template = input.subject_template.trim().to_owned();
151 if subject_template.is_empty() || subject_template.chars().count() > RULE_SUBJECT_MAX {
152 return Err(Error::Invalid(format!(
153 "the subject must be 1 to {RULE_SUBJECT_MAX} characters"
154 )));
155 }
156 Ok(RuleInput {
157 name,
158 trigger,
159 column_id,
160 tag_id,
161 audience,
162 include_details: input.include_details,
163 enabled: input.enabled,
164 subject_template,
165 })
166}
167
168impl Store {
169 /// Every rule of the board, oldest first.
170 pub async fn list_rules(&self, board_id: &str) -> Result<Vec<MailRule>> {
171 let conn = self.read_conn().await;
172 fetch_all(
173 &conn,
174 &format!(
175 "SELECT {RULE_COLS} FROM mail_rules WHERE board_id = ?1 ORDER BY created_at, id"
176 ),
177 (board_id.to_owned(),),
178 map_rule,
179 )
180 .await
181 }
182
183 /// One rule of the board, or `NotFound`.
184 pub async fn rule(&self, board_id: &str, rule_id: &str) -> Result<MailRule> {
185 let conn = self.read_conn().await;
186 fetch_opt(
187 &conn,
188 &format!("SELECT {RULE_COLS} FROM mail_rules WHERE id = ?1 AND board_id = ?2"),
189 (rule_id.to_owned(), board_id.to_owned()),
190 map_rule,
191 )
192 .await?
193 .ok_or(Error::NotFound)
194 }
195
196 /// Creates a rule after checking it. Returns the stored rule.
197 pub async fn create_rule(&self, board_id: &str, input: &RuleInput) -> Result<MailRule> {
198 let conn = self.inner.conn.lock().await;
199 let input = checked(&conn, board_id, input).await?;
200 let id = new_id();
201 conn.execute(
202 "INSERT INTO mail_rules (id, board_id, name, trigger, column_id, tag_id, audience, include_details, \
203 enabled, subject_template, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
204 (
205 id.clone(),
206 board_id.to_owned(),
207 input.name,
208 input.trigger,
209 input.column_id,
210 input.tag_id,
211 input.audience,
212 i64::from(input.include_details),
213 i64::from(input.enabled),
214 input.subject_template,
215 now_stamp(),
216 ),
217 )
218 .await
219 .map_err(db_err)?;
220 drop(conn);
221 self.rule(board_id, &id).await
222 }
223
224 /// Replaces the fields of a rule after checking them. The rule keeps its id and creation time.
225 pub async fn update_rule(
226 &self,
227 board_id: &str,
228 rule_id: &str,
229 input: &RuleInput,
230 ) -> Result<MailRule> {
231 let conn = self.inner.conn.lock().await;
232 let input = checked(&conn, board_id, input).await?;
233 let changed = conn
234 .execute(
235 "UPDATE mail_rules SET name = ?3, trigger = ?4, column_id = ?5, tag_id = ?6, audience = ?7, \
236 include_details = ?8, enabled = ?9, subject_template = ?10 WHERE id = ?1 AND board_id = ?2",
237 (
238 rule_id.to_owned(),
239 board_id.to_owned(),
240 input.name,
241 input.trigger,
242 input.column_id,
243 input.tag_id,
244 input.audience,
245 i64::from(input.include_details),
246 i64::from(input.enabled),
247 input.subject_template,
248 ),
249 )
250 .await
251 .map_err(db_err)?;
252 drop(conn);
253 if changed == 0 {
254 return Err(Error::NotFound);
255 }
256 self.rule(board_id, rule_id).await
257 }
258
259 /// Switches a rule on or off.
260 pub async fn set_rule_enabled(
261 &self,
262 board_id: &str,
263 rule_id: &str,
264 enabled: bool,
265 ) -> Result<()> {
266 let conn = self.inner.conn.lock().await;
267 let changed = conn
268 .execute(
269 "UPDATE mail_rules SET enabled = ?3 WHERE id = ?1 AND board_id = ?2",
270 (rule_id.to_owned(), board_id.to_owned(), i64::from(enabled)),
271 )
272 .await
273 .map_err(db_err)?;
274 if changed == 0 {
275 return Err(Error::NotFound);
276 }
277 Ok(())
278 }
279
280 /// Deletes a rule. Its outbox rows stay (the link to the rule is cleared), and its decisions go with it.
281 pub async fn delete_rule(&self, board_id: &str, rule_id: &str) -> Result<()> {
282 let conn = self.inner.conn.lock().await;
283 let changed = conn
284 .execute(
285 "DELETE FROM mail_rules WHERE id = ?1 AND board_id = ?2",
286 (rule_id.to_owned(), board_id.to_owned()),
287 )
288 .await
289 .map_err(db_err)?;
290 if changed == 0 {
291 return Err(Error::NotFound);
292 }
293 Ok(())
294 }
295}