troupekit_graph/
condition.rs1use crate::error::GraphError;
2use serde_json::{Map, Value};
3use std::collections::HashMap;
4use std::sync::Arc;
5use troupekit_agent::dsl::is_ident;
6
7pub type ConditionFn =
11 Arc<dyn Fn(&Map<String, Value>, &[Value]) -> Result<String, String> + Send + Sync>;
12
13#[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 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 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 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}