//! Data-only automation format shared by package validation and the write interpreter. use super::{is_valid_id, refusal_words, TableDefinition, ToolDefinition}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use std::collections::BTreeSet; pub mod expressions; pub const MAX_DEPTH: usize = 3; pub const MAX_AUTOMATIONS: usize = 16; pub const MAX_ACTIONS: usize = 16; pub const MAX_WRITE_ACTIONS: usize = 64; pub const MAX_NOTIFICATION_CHARS: usize = 2048; /// A `refusal.definition` line with each `{name}` filled by `fills`; the /// piece as written when the kit has no such line. pub(crate) fn said(piece: &str, fills: &[(&str, &dyn std::fmt::Display)]) -> String { let fills: Vec<(&str, String)> = fills.iter().map(|(name, value)| (*name, value.to_string())).collect(); let fills: Vec<(&str, &str)> = fills.iter().map(|(name, value)| (*name, value.as_str())).collect(); crate::rules::shell_lines::resolve("refusal", &format!("definition.{piece}"), &[], &fills).unwrap_or_else(|| piece.to_string()) } pub const NOTIFICATIONS: &str = "automation_notification"; pub const RUNS: &str = "automation_run"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Automation { pub id: String, pub name: String, pub when: When, pub then: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct When { pub table: String, pub column: String, pub to: Value, #[serde(default, skip_serializing_if = "Option::is_none")] pub guard: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Action { Set(Set), Create(Create), Notify(Notify), Ledger(Ledger), } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Set { pub column: String, pub value: Value, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Create { pub table: String, pub values: Map, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Notify { pub text: String, } /// Allocate one movement row against an eligible purchase. All names are /// definition data; the interpreter knows neither classes nor businesses. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct Ledger { pub table: String, pub account: String, pub on: String, pub purchase: String, pub override_column: String, pub purchase_account: String, pub remaining: String, pub expires: String, pub starts: String, pub refusal: String, /// Provenance text on movements and purchases: history never spends live credit. #[serde(default, skip_serializing_if = "Option::is_none")] pub history: Option, /// The purchase's stored count (a number column). A purchase that holds /// none is unlimited: it covers every movement between its dates, and /// its `remaining` is never read (a time-based membership beside a pack /// of classes). Absent, every purchase is counted. #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option, } /// Every automation, for the write interpreter: one naming an action this /// build does not name refuses — a write to its table is refused whole rather /// than run without the automation a newer device keeps on it. pub fn parse(tool: &ToolDefinition) -> Result, String> { tool.automations .iter() .map(|v| serde_json::from_value(v.clone()).map_err(|e| e.to_string())) .collect() } /// The automations this build can read, for drawing the tool: one naming an /// action this build does not name is a newer device's, left out and named /// by [`unrunnable`] (the tool's `unavailable`); anything else malformed refuses. pub fn parse_known(tool: &ToolDefinition) -> Result, String> { tool.automations .iter() .filter(|v| !newer(v)) .map(|v| serde_json::from_value(v.clone()).map_err(|e| e.to_string())) .collect() } fn newer(automation: &Value) -> bool { serde_json::from_value::(automation.clone()) .is_err_and(|error| error.to_string().starts_with("unknown variant")) } /// The ids of the automations [`parse_known`] leaves out. pub fn unrunnable(tool: &ToolDefinition) -> Vec { tool.automations .iter() .filter(|v| newer(v)) .map(|v| { v.get("id") .and_then(Value::as_str) .unwrap_or_default() .to_string() }) .collect() } pub fn validate(tool: &ToolDefinition) -> Result<(), String> { if tool.automations.len() > MAX_AUTOMATIONS { return Err(said("too_many_automations_maximum", &[("most", &MAX_AUTOMATIONS)])); } let mut ids = BTreeSet::new(); for a in parse_known(tool)? { if !is_valid_id(&a.id) || !ids.insert(a.id.clone()) || a.name.trim().is_empty() || a.name.chars().any(char::is_control) || a.name.chars().count() > 128 || a.then.is_empty() || a.then.len() > MAX_ACTIONS { return Err(said("automation_needs_a_unique_id_a_name", &[("id", &a.id)])); } if !tool.tables.contains(&a.when.table) || !is_valid_id(&a.when.column) { return Err(said("automation_has_an_unknown_trigger", &[("id", &a.id)])); } for action in a.then { match action { Action::Set(s) if !is_valid_id(&s.column) => { return Err(said("invalid_set_column", &[("column", &s.column)])) } Action::Create(c) if !tool.tables.contains(&c.table) || c.values.keys().any(|k| !is_valid_id(k)) => { return Err(said("invalid_create_table_or_column", &[("table", &c.table)])) } Action::Notify(n) if n.text.trim().is_empty() || n.text.chars().count() > MAX_NOTIFICATION_CHARS => { return Err(refusal_words("notify_text_is_empty")) } _ => {} } } } Ok(()) } /// Packages must reference their own user tables and declared columns, never an engine. pub fn validate_tables(tool: &ToolDefinition, tables: &[TableDefinition]) -> Result<(), String> { super::reserve::validate_tables(tool, tables)?; super::acts::validate_tables(tool, tables)?; if tables .iter() .any(|t| matches!(t.id.as_str(), NOTIFICATIONS | RUNS)) { return Err(refusal_words("reserved_automation_table_id")); } let table = |id: &str| { tables .iter() .find(|t| t.id == id && t.engine.is_none()) .ok_or_else(|| said("automation_cannot_touch_engine_or_unknown", &[("id", &id)])) }; let column = |t: &TableDefinition, key: &str| { if t.columns.iter().any(|c| c.key == key) { Ok(()) } else { Err(said("automation_table_has_no_column", &[("table", &t.id), ("key", &key)])) } }; for a in parse(tool)? { let source = table(&a.when.table)?; column(source, &a.when.column)?; if a.when.to != "any" { crate::records::check_value( source .columns .iter() .find(|c| c.key == a.when.column) .unwrap(), &a.when.to, ) .map_err(|e| e.to_string())?; } if let Some(guard) = &a.when.guard { if expressions::validate(guard, source)? != expressions::Type::Bool { return Err(refusal_words("automation_guard_must_be_boolean")); } } for action in a.then { match action { Action::Set(s) => { validate_set(source, &s)?; } Action::Ledger(l) => { if !tool.engines.iter().any(|e| e == "rules@1") { return Err(refusal_words("ledger_action_requires_rules_1")); } let purchase = table(&l.table)?; fn typed<'a>(t: &'a TableDefinition, column_name: &str, ty: super::ColumnType) -> Result<&'a super::Column, String> { t.column(column_name).filter(|c| c.column_type == ty) .ok_or_else(|| said("ledger_column_has_the_wrong_type", &[("table", &t.id), ("column", &column_name)])) } use super::ColumnType as T; let account = typed(source, &l.account, T::Link)?; let other = typed(purchase, &l.purchase_account, T::Link)?; if account.link_to != other.link_to || account.multiple == Some(true) || other.multiple == Some(true) { return Err(refusal_words("ledger_accounts_must_link_to_the_same")); } let link = typed(source, &l.purchase, T::Link)?; if link.link_to.as_deref() != Some(l.table.as_str()) || link.multiple == Some(true) || link.computed.is_some() { return Err(refusal_words("ledger_purchase_must_be_a_writable_link")); } if let Some(history) = &l.history { typed(source, history, T::Text)?; typed(purchase, history, T::Text)?; } typed(source, &l.on, T::Date)?; typed(source, &l.override_column, T::Bool)?; typed(purchase, &l.expires, T::Date)?; typed(purchase, &l.starts, T::Date)?; if typed(purchase, &l.remaining, T::Number)?.computed.is_none() { return Err("ledger remaining must be computed from rows".into()); } if let Some(limit) = &l.limit { if typed(purchase, limit, T::Number)?.computed.is_some() { return Err(refusal_words("ledger_limit_stored")); } } if l.refusal.trim().is_empty() { return Err(refusal_words("ledger_needs_refusal_words")); } } Action::Create(c) => { let target = table(&c.table)?; if target .columns .iter() .any(|col| col.counter == Some(true) && c.values.contains_key(&col.key)) { return Err(refusal_words("an_automation_cannot_write_a_counter")); } for (k, v) in &c.values { column(target, k)?; if let Some(reference) = v.as_str().and_then(|s| s.strip_prefix("$record.")) { let to = target.column(k).unwrap(); if reference == "id" { if to.column_type != super::ColumnType::Link || to.link_to.as_deref() != Some(source.id.as_str()) || to.multiple == Some(true) { return Err(refusal_words("record_id_needs_a_link_to_the")); } } else { column(source, reference)?; let from = source.column(reference).unwrap(); if from.column_type != to.column_type || (from.multiple == Some(true)) != (to.multiple == Some(true)) || (from.column_type == super::ColumnType::Link && from.link_to != to.link_to) { return Err(format!("automation reference {reference} has a different type from {k}")); } } } else { let col = target.columns.iter().find(|col| col.key == *k).unwrap(); crate::records::check_value(col, v).map_err(|e| e.to_string())?; } } for col in target .columns .iter() .filter(|col| col.required == Some(true)) { if !c.values.contains_key(&col.key) { return Err(said("automation_create_needs", &[("key", &col.key)])); } } } Action::Notify(n) => { let mut source_values: Map = source .columns .iter() .map(|col| (col.key.clone(), Value::Null)) .collect(); source_values.insert("id".into(), Value::Null); text(&n.text, &source_values)?; } } } } Ok(()) } /// Shared validation for an automation Set and a package Set act. pub fn validate_set(table: &TableDefinition, s: &Set) -> Result<(), String> { if table.column(&s.column).is_none() { return Err(said("unknown_set_column", &[("column", &s.column)])); } if table .columns .iter() .any(|c| c.key == s.column && c.counter == Some(true)) { return Err(refusal_words("a_counter_cannot_be_mutated_by_an")); } if s.value.is_object() || s.value.as_str().is_some_and(|v| v.starts_with("$record.")) { let kind = expressions::validate(&s.value, table)?; let target = table.columns.iter().find(|c| c.key == s.column).unwrap(); if (kind != expressions::column_type(target.column_type) && kind != expressions::Type::Null) || target.multiple == Some(true) || target.readonly == Some(true) || target.computed.is_some() { return Err(refusal_words("set_expression_needs_a_writable_column_of")); } return Ok(()); } let mut patch = Map::new(); patch.insert(s.column.clone(), s.value.clone()); crate::records::validate_patch(table, &Value::Object(patch)).map_err(|e| e.to_string())?; Ok(()) } /// Exact references in create values preserve JSON types. pub fn resolve(value: &Value, record: &Map) -> Result { if let Some(key) = value.as_str().and_then(|s| s.strip_prefix("$record.")) { record .get(key) .cloned() .ok_or_else(|| said("record_has_no_column", &[("key", &key)])) } else { Ok(value.clone()) } } /// Interpolate column references into text without interpreting any code. pub fn text(template: &str, record: &Map) -> Result { let mut rest = template; let mut out = String::new(); while let Some(at) = rest.find("$record.") { out.push_str(&rest[..at]); rest = &rest[at + 8..]; let end = rest .find(|c: char| !c.is_ascii_alphanumeric() && c != '_') .unwrap_or(rest.len()); let key = &rest[..end]; let value = record .get(key) .ok_or_else(|| said("record_has_no_column", &[("key", &key)]))?; if let Some(s) = value.as_str() { out.push_str(s); } else { out.push_str(&value.to_string()); } rest = &rest[end..]; } out.push_str(rest); if out.chars().count() > MAX_NOTIFICATION_CHARS { return Err(said("notification_text_exceeds_characters", &[("most", &MAX_NOTIFICATION_CHARS)])); } Ok(out) } #[cfg(test)] mod tests { use super::*; // RULE: A create reference preserves the column's JSON type, and notification text interpolates columns as text only. #[test] fn templates_preserve_values_and_render_text() { let record = serde_json::json!({"title":"Ada","done":true,"score":7}) .as_object() .unwrap() .clone(); assert_eq!( resolve(&Value::from("$record.done"), &record).unwrap(), Value::Bool(true) ); assert_eq!( resolve(&Value::from("$record.score"), &record).unwrap(), Value::from(7) ); assert_eq!( text( "Welcome $record.title: $record.score/$record.done.", &record ) .unwrap(), "Welcome Ada: 7/true." ); assert!(text("$record.missing", &record) .unwrap_err() .contains("missing")); } // RULE: A rule works out days as data: `add_days` moves a day on or back, `later_of` keeps the later of two days, `first_of` keeps a value while it holds one — so a membership renewed from its plan runs its plan's days, and one extended early runs on from its end, late from today; an empty day says nothing. #[test] fn a_rule_works_out_days() { let row = serde_json::json!({"expires":"2026-10-20","bought_on":null,"days":30,"plan":null}) .as_object() .unwrap() .clone(); let at = |expression: Value| expressions::evaluate_at(&expression, &row, "2026-10-23T09:00:00.000Z", "2026-10-23").unwrap(); let json = |text: &str| serde_json::from_str::(text).unwrap(); assert_eq!(at(json(r#"{"add_days":[{"column":"expires"},{"column":"days"}]}"#)), "2026-11-19"); assert_eq!(at(json(r#"{"add_days":[{"today":true},-1]}"#)), "2026-10-22"); assert_eq!(at(json(r#"{"add_days":[{"later_of":[{"column":"expires"},{"add_days":[{"today":true},-1]}]},{"column":"days"}]}"#)), "2026-11-21"); assert_eq!(at(json(r#"{"first_of":[{"column":"bought_on"},{"today":true}]}"#)), "2026-10-23"); assert_eq!(at(json(r#"{"first_of":[{"column":"expires"},{"today":true}]}"#)), "2026-10-20"); assert_eq!(at(json(r#"{"add_days":[{"column":"bought_on"},{"column":"days"}]}"#)), Value::Null); assert_eq!(at(json(r#"{"later_of":[{"column":"bought_on"},{"column":"expires"}]}"#)), "2026-10-20"); assert!(expressions::evaluate_at(&json(r#"{"add_days":[{"column":"days"},1]}"#), &row, "", "2026-10-23").is_err()); } }