Skip to main content

troupekit_graph/
condition.rs

1use crate::error::GraphError;
2use serde_json::{Map, Value};
3use std::collections::HashMap;
4use std::sync::Arc;
5use troupekit_agent::dsl::is_ident;
6
7/// A router condition: reads the run state and the call's arguments and
8/// returns the label of the edge to take, or why it cannot decide.
9/// Must be deterministic, so a replayed step routes the same way.
10pub type ConditionFn =
11    Arc<dyn Fn(&Map<String, Value>, &[Value]) -> Result<String, String> + Send + Sync>;
12
13/// Router conditions by name, as written in `condition = "name(args)"`.
14/// `new` starts with the built-in `flag(key)`, which returns `"true"` or
15/// `"false"` for a bool state key.
16#[derive(Clone)]
17pub struct Conditions {
18    map: HashMap<String, ConditionFn>,
19}
20
21impl Default for Conditions {
22    fn default() -> Self {
23        Self::new()
24    }
25}
26
27impl Conditions {
28    /// Builds the set holding only the built-in `flag`.
29    /// Register more with `register`.
30    /// Returns the set.
31    pub fn new() -> Self {
32        let mut map: HashMap<String, ConditionFn> = HashMap::new();
33        map.insert("flag".into(), Arc::new(flag));
34        Self { map }
35    }
36
37    /// Adds condition `f` under `name`, which must match
38    /// `[a-z_][a-z0-9_]*` and not be taken yet.
39    /// Returns `Setup` otherwise.
40    pub fn register(&mut self, name: &str, f: ConditionFn) -> Result<(), GraphError> {
41        if !is_ident(name) {
42            return Err(GraphError::Setup(format!(
43                "condition name `{name}` must match [a-z_][a-z0-9_]*"
44            )));
45        }
46        if self.map.contains_key(name) {
47            return Err(GraphError::Setup(format!(
48                "condition `{name}` is already registered"
49            )));
50        }
51        self.map.insert(name.to_string(), f);
52        Ok(())
53    }
54
55    /// Returns the condition registered under `name`.
56    /// `None` when there is none.
57    /// Graph runs check every router's condition at setup.
58    pub fn get(&self, name: &str) -> Option<&ConditionFn> {
59        self.map.get(name)
60    }
61}
62
63fn flag(state: &Map<String, Value>, args: &[Value]) -> Result<String, String> {
64    let [Value::String(key)] = args else {
65        return Err("flag takes one state key".into());
66    };
67    match state.get(key) {
68        Some(Value::Bool(b)) => Ok(b.to_string()),
69        Some(_) => Err(format!("flag: `{key}` is not a bool")),
70        None => Err(format!("flag: `{key}` is not set")),
71    }
72}