use crate::compare::compare;
use crate::model::{RuleSpec, ThenAction};
use crate::schedule::schedule_text;
use crate::syntax::{condition_text, matches_kind};
use serde::Serialize;
use serde_json::{Value, json};
use std::cell::{Cell, RefCell};
pub const MAX_DEPTH: usize = 3;
pub const MAX_RUNS: u32 = 50;
pub const SCHEDULE: &str = "schedule";
pub trait Rule {
type Then: ThenAction;
fn id(&self) -> &str;
fn name(&self) -> &str;
fn enabled(&self) -> bool;
fn spec(&self) -> &RuleSpec<Self::Then>;
fn created_at(&self) -> i64;
fn last_run_at(&self) -> Option<i64>;
}
pub trait Event {
fn id(&self) -> i64;
fn kind(&self) -> &str;
fn param(&self, key: &str) -> Option<&Value>;
}
#[derive(Debug, Default)]
pub struct Runtime {
chain: RefCell<Vec<String>>,
budget: Cell<u32>,
}
impl Runtime {
pub fn new() -> Self {
Self::default()
}
pub fn chain(&self) -> Vec<String> {
self.chain.borrow().clone()
}
pub fn running(&self) -> bool {
!self.chain.borrow().is_empty()
}
pub fn budget(&self) -> u32 {
self.budget.get()
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Run {
pub action: Option<i64>,
pub status: &'static str,
pub results: Vec<Value>,
pub messages: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RunResult {
pub action: Option<i64>,
pub status: String,
pub messages: Vec<String>,
}
pub trait Host {
type Rule: Rule;
type Event: Event;
type Error: std::fmt::Display;
fn runtime(&self) -> &Runtime;
fn enabled_rules(&self) -> Result<Vec<Self::Rule>, Self::Error>;
fn field(&self, rule: &Self::Rule, event: &Self::Event, field: &str) -> Option<Value>;
fn deferred(&self, _field: &str) -> bool {
false
}
fn is_related(&self, rule: &Self::Rule, event: &Self::Event) -> bool;
fn begin_run(&self, rule: &Self::Rule, event: &Self::Event) -> Option<i64>;
fn exec(&self, rule: &Self::Rule, event: &Self::Event, then: &<Self::Rule as Rule>::Then) -> Result<String, Self::Error>;
fn finish_run(&self, rule: &Self::Rule, event: &Self::Event, run: &Run);
fn blocked(&self, rule: &Self::Rule, event: &Self::Event, why: &str);
fn rules_unavailable(&self, _error: &Self::Error) {}
}
#[derive(Debug, Clone, Serialize)]
pub struct Check {
pub rule: String,
pub name: String,
pub action: i64,
pub kind: String,
pub enabled: bool,
pub on: Option<String>,
pub related: Option<bool>,
pub conditions: Vec<CondCheck>,
pub matched: bool,
}
#[derive(Debug, Clone, Serialize)]
pub struct CondCheck {
pub condition: String,
pub actual: Option<Value>,
pub ok: bool,
}
pub fn check<H: Host>(host: &H, r: &H::Rule, e: &H::Event) -> Check {
let spec = r.spec();
let kind = e.kind();
let on = if kind.starts_with("rule.") {
None
} else if kind == SCHEDULE {
match e.param("rule").and_then(Value::as_str) {
Some(id) if id == r.id() => {
if spec.schedule.is_some() || spec.on.iter().any(|p| matches_kind(p, SCHEDULE)) {
Some(SCHEDULE.to_string())
} else {
None
}
}
Some(_) => None,
None => spec.on.iter().find(|p| matches_kind(p, SCHEDULE)).cloned(),
}
} else {
spec.on.iter().find(|p| matches_kind(p, kind)).cloned()
};
let related = spec.related.then(|| host.is_related(r, e));
let conditions: Vec<CondCheck> = spec
.when
.iter()
.map(|c| {
if host.deferred(&c.field) && (on.is_none() || related == Some(false)) {
return CondCheck { condition: condition_text(c), ok: false, actual: None };
}
let actual = host.field(r, e, &c.field);
CondCheck { condition: condition_text(c), ok: compare(actual.as_ref(), c.op, &c.value), actual }
})
.collect();
let matched = on.is_some() && related != Some(false) && conditions.iter().all(|c| c.ok);
Check {
rule: r.id().to_string(),
name: r.name().to_string(),
action: e.id(),
kind: kind.to_string(),
enabled: r.enabled(),
on,
related,
conditions,
matched,
}
}
pub fn dispatch<H: Host>(host: &H, e: &H::Event) -> usize {
if e.kind().starts_with("rule.") {
return 0;
}
let rt = host.runtime();
let chain = rt.chain();
if chain.is_empty() {
rt.budget.set(MAX_RUNS);
}
let rules = match host.enabled_rules() {
Ok(r) => r,
Err(err) => {
host.rules_unavailable(&err);
return 0;
}
};
let mut started = 0;
for r in rules {
if !check(host, &r, e).matched {
continue;
}
let blocked = if chain.iter().any(|id| id == r.id()) {
Some(format!("loop: {} is already running for this action", r.name()))
} else if chain.len() >= MAX_DEPTH {
Some(format!("too deep: {MAX_DEPTH} rules already ran in a chain"))
} else if rt.budget.get() == 0 {
Some(format!("limit: {MAX_RUNS} rule runs for one action"))
} else {
None
};
match blocked {
Some(why) => host.blocked(&r, e, &why),
None => {
rt.budget.set(rt.budget.get() - 1);
run(host, &r, e);
started += 1;
}
}
}
started
}
pub fn run<H: Host>(host: &H, r: &H::Rule, e: &H::Event) -> RunResult {
let rt = host.runtime();
let action = host.begin_run(r, e);
rt.chain.borrow_mut().push(r.id().to_string());
let mut results = vec![];
let mut messages = vec![];
let mut failed = false;
for t in &r.spec().then {
match host.exec(r, e, t) {
Ok(m) => {
results.push(json!({ "do": t.verb(), "ok": true, "message": m }));
messages.push(m);
}
Err(err) => {
failed = true;
let m = format!("{} failed: {err}", t.verb());
results.push(json!({ "do": t.verb(), "ok": false, "error": err.to_string() }));
messages.push(m);
}
}
}
rt.chain.borrow_mut().pop();
let status = if failed { "failed" } else { "ok" };
let done = Run { action, status, results, messages };
host.finish_run(r, e, &done);
RunResult { action, status: status.into(), messages: done.messages }
}
pub fn next_run<R: Rule>(r: &R) -> Option<i64> {
crate::schedule::next_run(r.spec().schedule.as_ref()?, r.created_at(), r.last_run_at())
}
pub fn due<R: Rule>(r: &R, now: i64) -> bool {
r.spec().schedule.is_some() && next_run(r).is_some_and(|t| t <= now)
}
pub fn brief<R: Rule>(r: &R) -> String {
let spec = r.spec();
let n = spec.then.len();
let when = match (&spec.schedule, spec.on.is_empty()) {
(Some(s), true) => schedule_text(s),
(Some(s), false) => format!("{}, on {}", schedule_text(s), spec.on.join(", ")),
(None, _) => format!("on {}", spec.on.join(", ")),
};
format!("{when} → {n} action{}{}", if n == 1 { "" } else { "s" }, if r.enabled() { "" } else { " (off)" })
}
#[cfg(test)]
mod tests;