1use crate::compare::compare;
12use crate::model::{RuleSpec, ThenAction};
13use crate::schedule::schedule_text;
14use crate::syntax::{condition_text, matches_kind};
15use serde::Serialize;
16use serde_json::{Value, json};
17use std::cell::{Cell, RefCell};
18
19pub const MAX_DEPTH: usize = 3;
21pub const MAX_RUNS: u32 = 50;
23pub const SCHEDULE: &str = "schedule";
26
27pub trait Rule {
29 type Then: ThenAction;
30 fn id(&self) -> &str;
31 fn name(&self) -> &str;
32 fn enabled(&self) -> bool;
33 fn spec(&self) -> &RuleSpec<Self::Then>;
34 fn created_at(&self) -> i64;
35 fn last_run_at(&self) -> Option<i64>;
36}
37
38pub trait Event {
40 fn id(&self) -> i64;
41 fn kind(&self) -> &str;
42 fn param(&self, key: &str) -> Option<&Value>;
44}
45
46#[derive(Debug, Default)]
49pub struct Runtime {
50 chain: RefCell<Vec<String>>,
51 budget: Cell<u32>,
52}
53
54impl Runtime {
55 pub fn new() -> Self {
56 Self::default()
57 }
58 pub fn chain(&self) -> Vec<String> {
61 self.chain.borrow().clone()
62 }
63 pub fn running(&self) -> bool {
64 !self.chain.borrow().is_empty()
65 }
66 pub fn budget(&self) -> u32 {
68 self.budget.get()
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Serialize)]
74pub struct Run {
75 pub action: Option<i64>,
77 pub status: &'static str,
79 pub results: Vec<Value>,
81 pub messages: Vec<String>,
83}
84
85#[derive(Debug, Clone, Serialize)]
87pub struct RunResult {
88 pub action: Option<i64>,
89 pub status: String,
90 pub messages: Vec<String>,
91}
92
93pub trait Host {
95 type Rule: Rule;
96 type Event: Event;
97 type Error: std::fmt::Display;
98
99 fn runtime(&self) -> &Runtime;
100 fn enabled_rules(&self) -> Result<Vec<Self::Rule>, Self::Error>;
102 fn field(&self, rule: &Self::Rule, event: &Self::Event, field: &str) -> Option<Value>;
104 fn deferred(&self, _field: &str) -> bool {
107 false
108 }
109 fn is_related(&self, rule: &Self::Rule, event: &Self::Event) -> bool;
111 fn begin_run(&self, rule: &Self::Rule, event: &Self::Event) -> Option<i64>;
113 fn exec(&self, rule: &Self::Rule, event: &Self::Event, then: &<Self::Rule as Rule>::Then) -> Result<String, Self::Error>;
115 fn finish_run(&self, rule: &Self::Rule, event: &Self::Event, run: &Run);
117 fn blocked(&self, rule: &Self::Rule, event: &Self::Event, why: &str);
119 fn rules_unavailable(&self, _error: &Self::Error) {}
121}
122
123#[derive(Debug, Clone, Serialize)]
125pub struct Check {
126 pub rule: String,
127 pub name: String,
128 pub action: i64,
129 pub kind: String,
130 pub enabled: bool,
131 pub on: Option<String>,
133 pub related: Option<bool>,
135 pub conditions: Vec<CondCheck>,
136 pub matched: bool,
137}
138
139#[derive(Debug, Clone, Serialize)]
140pub struct CondCheck {
141 pub condition: String,
142 pub actual: Option<Value>,
143 pub ok: bool,
144}
145
146pub fn check<H: Host>(host: &H, r: &H::Rule, e: &H::Event) -> Check {
148 let spec = r.spec();
149 let kind = e.kind();
150 let on = if kind.starts_with("rule.") {
151 None
152 } else if kind == SCHEDULE {
153 match e.param("rule").and_then(Value::as_str) {
155 Some(id) if id == r.id() => {
156 if spec.schedule.is_some() || spec.on.iter().any(|p| matches_kind(p, SCHEDULE)) {
157 Some(SCHEDULE.to_string())
158 } else {
159 None
160 }
161 }
162 Some(_) => None,
163 None => spec.on.iter().find(|p| matches_kind(p, SCHEDULE)).cloned(),
164 }
165 } else {
166 spec.on.iter().find(|p| matches_kind(p, kind)).cloned()
167 };
168 let related = spec.related.then(|| host.is_related(r, e));
169 let conditions: Vec<CondCheck> = spec
170 .when
171 .iter()
172 .map(|c| {
173 if host.deferred(&c.field) && (on.is_none() || related == Some(false)) {
174 return CondCheck { condition: condition_text(c), ok: false, actual: None };
175 }
176 let actual = host.field(r, e, &c.field);
177 CondCheck { condition: condition_text(c), ok: compare(actual.as_ref(), c.op, &c.value), actual }
178 })
179 .collect();
180 let matched = on.is_some() && related != Some(false) && conditions.iter().all(|c| c.ok);
181 Check {
182 rule: r.id().to_string(),
183 name: r.name().to_string(),
184 action: e.id(),
185 kind: kind.to_string(),
186 enabled: r.enabled(),
187 on,
188 related,
189 conditions,
190 matched,
191 }
192}
193
194pub fn dispatch<H: Host>(host: &H, e: &H::Event) -> usize {
197 if e.kind().starts_with("rule.") {
198 return 0;
199 }
200 let rt = host.runtime();
201 let chain = rt.chain();
202 if chain.is_empty() {
203 rt.budget.set(MAX_RUNS);
204 }
205 let rules = match host.enabled_rules() {
206 Ok(r) => r,
207 Err(err) => {
208 host.rules_unavailable(&err);
209 return 0;
210 }
211 };
212 let mut started = 0;
213 for r in rules {
214 if !check(host, &r, e).matched {
215 continue;
216 }
217 let blocked = if chain.iter().any(|id| id == r.id()) {
218 Some(format!("loop: {} is already running for this action", r.name()))
219 } else if chain.len() >= MAX_DEPTH {
220 Some(format!("too deep: {MAX_DEPTH} rules already ran in a chain"))
221 } else if rt.budget.get() == 0 {
222 Some(format!("limit: {MAX_RUNS} rule runs for one action"))
223 } else {
224 None
225 };
226 match blocked {
227 Some(why) => host.blocked(&r, e, &why),
228 None => {
229 rt.budget.set(rt.budget.get() - 1);
230 run(host, &r, e);
231 started += 1;
232 }
233 }
234 }
235 started
236}
237
238pub fn run<H: Host>(host: &H, r: &H::Rule, e: &H::Event) -> RunResult {
241 let rt = host.runtime();
242 let action = host.begin_run(r, e);
243 rt.chain.borrow_mut().push(r.id().to_string());
244 let mut results = vec![];
245 let mut messages = vec![];
246 let mut failed = false;
247 for t in &r.spec().then {
248 match host.exec(r, e, t) {
249 Ok(m) => {
250 results.push(json!({ "do": t.verb(), "ok": true, "message": m }));
251 messages.push(m);
252 }
253 Err(err) => {
254 failed = true;
255 let m = format!("{} failed: {err}", t.verb());
256 results.push(json!({ "do": t.verb(), "ok": false, "error": err.to_string() }));
257 messages.push(m);
258 }
259 }
260 }
261 rt.chain.borrow_mut().pop();
262 let status = if failed { "failed" } else { "ok" };
263 let done = Run { action, status, results, messages };
264 host.finish_run(r, e, &done);
265 RunResult { action, status: status.into(), messages: done.messages }
266}
267
268pub fn next_run<R: Rule>(r: &R) -> Option<i64> {
270 crate::schedule::next_run(r.spec().schedule.as_ref()?, r.created_at(), r.last_run_at())
271}
272
273pub fn due<R: Rule>(r: &R, now: i64) -> bool {
275 r.spec().schedule.is_some() && next_run(r).is_some_and(|t| t <= now)
276}
277
278pub fn brief<R: Rule>(r: &R) -> String {
280 let spec = r.spec();
281 let n = spec.then.len();
282 let when = match (&spec.schedule, spec.on.is_empty()) {
283 (Some(s), true) => schedule_text(s),
284 (Some(s), false) => format!("{}, on {}", schedule_text(s), spec.on.join(", ")),
285 (None, _) => format!("on {}", spec.on.join(", ")),
286 };
287 format!("{when} → {n} action{}{}", if n == 1 { "" } else { "s" }, if r.enabled() { "" } else { " (off)" })
288}
289
290#[cfg(test)]
291mod tests;