Cotton code
511 lines · 21.0 KB · RustRaw
//! The write's data actions, and the run that is their idempotence and undo//! marker: one `cotton_automation_runs` row per firing (137), under the//! triggering change's id.use super::*;use crate::mcp::handlers::common::{now_ms, today_in, workspace_timezone};use cotton_store::actor::Actor;use cotton_core::definitions::automations::{    self, Action, Automation, MAX_DEPTH, MAX_WRITE_ACTIONS, NOTIFICATIONS,};/// Where each firing of an automation is kept: what fired, the changes it/// made (what an undo takes back), when and how it went.const RUNS: &str = "cotton_automation_runs";/// One loaded automation and the tool it came with.struct Loaded {    tool: String,    automation: Automation,}impl Loaded {    /// What a run names as having fired: `<tool>/<automation id>`.    fn label(&self) -> String {        format!("{}/{}", self.tool, self.automation.id)    }}/// The run row of one firing.struct Run {    automation: String,    changes: Vec<Value>,    root_first: Option<bool>,    started_at: String,    outcome: &'static str,}fn write_run(ctx: &mut Ctx<'_>, id: &str, run: Run) -> Valid<()> {    let ended_at = now_iso(ctx);    let patch = json!({        "automation": run.automation,        "changes": run.changes,        "root_first": run.root_first,        "started_at": run.started_at,        "ended_at": ended_at,        "outcome": run.outcome,        "summary": null,        "record_byline": byline(ctx),    });    insert_row(ctx, RUNS, id, patch.as_object().unwrap().clone())}pub(super) fn notification_definition() -> TableDefinition {    // A made table every file holds: its shape is the store's to step to.    serde_json::from_str(cotton_store::schema::package_shape::CODE_MADE[0]).expect("internal notification definition")}struct Limits {    remaining: usize,    depth_limited: bool,}pub(super) fn run(ctx: &mut Ctx<'_>, mut root: Value) -> ToolResult {    let table = root["change"]["table"]        .as_str()        .ok_or_else(|| ToolFailure::new("write returned no table"))?;    // Automations only watch user tables. A built-in write can remove its    // record (Cancel does), so its successful null-record answer goes through    // unchanged rather than requiring a live record for the cascade.    if !is_user_table(&definition(ctx, table)?) {        return Ok(root);    }    // An import carries records that were already written where they were    // made, and whatever their automations did there is carried with them:    // firing again here would make each effect twice.    if matches!(ctx.writer_actor(), Some(Actor::Import(_))) {        return Ok(root);    }    let started_at = now_iso(ctx);    let mut changes = Vec::new();    let mut notifications = Vec::new();    let mut fired: Vec<String> = Vec::new();    // Resolve once per user write. A stale or newer-device tool is data we cannot run, not a failed user write.    let mut loaded = Vec::new();    for tool in super::super::tool_packages::live_tool_definitions(ctx)? {        if tool.automations.is_empty() {            continue;        }        // A newer device's automation this build cannot run refuses the write        // whole: running it without the automation would skip what it does.        if !tool.unavailable.is_empty() {            return Err(ToolFailure::new(format!(                "The tool {:?} keeps automations this build cannot run ({}); update CottonDB on this device before writing here.",                tool.id,                tool.unavailable.join(", ")            )));        }        let resolve = || -> Result<Vec<Automation>, ToolFailure> {            let tables = tool                .tables                .iter()                .map(|id| definition(ctx, id))                .collect::<Result<Vec<_>, _>>()?;            automations::validate_tables(&tool, &tables).map_err(ToolFailure::new)?;            automations::parse(&tool).map_err(ToolFailure::new)        };        match resolve() {            Ok(actions) => loaded.extend(                actions.into_iter().map(|automation| Loaded { tool: tool.id.clone(), automation }),            ),            Err(error) => tracing::warn!(                tool = tool.id,                reason = error.message(),                "skipping automation tool"            ),        }    }    let mut limits = Limits {        remaining: MAX_WRITE_ACTIONS,        depth_limited: false,    };    cascade(        ctx,        &root,        0,        &loaded,        &mut limits,        &mut changes,        &mut notifications,        &mut fired,    )?;    root["automation_depth_limited"] = Value::Bool(limits.depth_limited);    if !changes.is_empty() {        let id = root["change"]["id"]            .as_str()            .ok_or_else(|| ToolFailure::new("write returned no change id"))?;        let run = Run {            automation: fired.join(","),            changes: changes.iter().map(|c| c["id"].clone()).collect(),            root_first: None,            started_at,            outcome: if limits.depth_limited { "depth_limited" } else { "done" },        };        write_run(ctx, id, run)?;        ctx.commit()?;    }    root["automation_changes"] = Value::Array(changes);    root["notifications"] = Value::Array(notifications);    // A set action can change the triggering record again; answer its final state.    if let (Some(table), Some(id)) = (        root["change"]["table"]            .as_str()            .or_else(|| root["record"]["table"].as_str()),        root["record"]["id"].as_str(),    ) {        let definition = definition(ctx, table)?;        root["record"] = read_json(&definition, &load_live(ctx, &definition, id)?);    }    Ok(root)}fn cascade(    ctx: &mut Ctx<'_>,    written: &Value,    depth: usize,    loaded: &[Loaded],    limits: &mut Limits,    changes: &mut Vec<Value>,    notifications: &mut Vec<Value>,    fired: &mut Vec<String>,) -> Valid<()> {    if depth >= MAX_DEPTH {        limits.depth_limited = true;        return Ok(());    }    let table = written["record"]["table"]        .as_str()        .ok_or_else(|| ToolFailure::new("write returned no table"))?;    let id = written["record"]["id"]        .as_str()        .ok_or_else(|| ToolFailure::new("write returned no record id"))?;    let record = written["record"]["data"]        .as_object()        .ok_or_else(|| ToolFailure::new("write returned no data"))?;    // The generic value model treats an absent declared column as null.    let mut record = record.clone();    let source_definition = definition(ctx, table)?;    for column in &source_definition.columns {        record.entry(column.key.clone()).or_insert(Value::Null);    }    if source_definition.has_computed() {        let resolved = expression_row(ctx, &source_definition, id)?;        for column in source_definition.columns.iter().filter(|c| c.computed.is_some()) {            record.insert(column.key.clone(), resolved.get(&column.key).cloned().unwrap_or(Value::Null));        }    }    record.insert("id".into(), Value::String(id.into()));    let clock_now = now_iso(ctx);    let clock_today = today_in(&workspace_timezone(ctx)?, now_ms(ctx))?;    let changed = written["change"]["after"]        .as_object()        .ok_or_else(|| ToolFailure::new("write returned no changed values"))?;    {        for loaded_automation in loaded {            let a = &loaded_automation.automation;            if a.when.table != table                || !changed.contains_key(&a.when.column)                || (a.when.to != "any" && record.get(&a.when.column) != Some(&a.when.to))            {                continue;            }            if let Some(guard) = &a.when.guard {                if automations::expressions::evaluate_at(guard, &record, &clock_now, &clock_today).map_err(ToolFailure::new)? != Value::Bool(true) { continue; }            }            let label = format!("automation {}", a.name);            for action in a.then.clone() {                if limits.remaining == 0 {                    return Err(ToolFailure::new(                        "automation action budget exceeded (64); write rolled back",                    ));                }                limits.remaining -= 1;                let action_record = expression_row(ctx, &source_definition, id)?;                // THE BYLINE IS WRITTEN BEFORE THE ROW (slice 6): a change row                // is a fact, so the action's writes are made under the label.                let bylined = Bylined::as_label(&label);                let mut next = match action {                    Action::Set(s) => {                        let value = automations::expressions::evaluate_at(&s.value, &action_record, &clock_now, &clock_today).map_err(ToolFailure::new)?;                        let args = json!({"table":table,"id":id,"patch":{s.column:value}});                        // Setting a value already present is an idempotent action, not a failed write.                        let patch = args["patch"].as_object().unwrap();                        if patch                            .iter()                            .all(|(key, value)| action_record.get(key) == Some(value))                        {                            continue;                        }                        update_record_now(ctx, args.as_object().unwrap())?                    }                    Action::Create(c) => {                        let values = c                            .values                            .iter()                            .map(|(k, v)| {                                automations::resolve(v, &action_record).map(|v| (k.clone(), v))                            })                            .collect::<Result<Map<_, _>, _>>()                            .map_err(ToolFailure::new)?;                        create_record_now(                            ctx,                            json!({"table":c.table,"data":values}).as_object().unwrap(),                        )?                    }                    Action::Ledger(l) => {                        let Some(purchase) = ledger_purchase(ctx, &l, &action_record)? else { continue; };                        update_record_now(ctx, json!({"table":table,"id":id,"patch":{l.purchase:purchase}}).as_object().unwrap())?                    }                    Action::Notify(n) => {                        let text =                            automations::text(&n.text, &action_record).map_err(ToolFailure::new)?;                        let next = create_record_now(                            ctx,                            json!({"table":NOTIFICATIONS,"data":{"text":text}})                                .as_object()                                .unwrap(),                        )?;                        notifications.push(json!({"id":next["record"]["id"],"text":text}));                        next                    }                };                drop(bylined);                let what = loaded_automation.label();                if !fired.contains(&what) {                    fired.push(what);                }                let record_id = next["record"]["id"].as_str().unwrap();                // The byline is a made table's record's own column, in its own                // table; a built-in's record keeps no byline of its own.                let table = next["record"]["table"]                    .as_str()                    .or_else(|| next["change"]["table"].as_str())                    .unwrap_or_default();                if is_user_table(&definition(ctx, table)?) {                    update_row(                        ctx,                        &made_table(table),                        record_id,                        json!({MADE_BYLINE: label}).as_object().unwrap().clone(),                    )?;                }                ctx.commit()?;                next["change"]["byline"] = Value::from(label.clone());                next["record"]["byline"] = Value::from(label.clone());                changes.push(next["change"].clone());                cascade(                    ctx,                    &next,                    depth + 1,                    loaded,                    limits,                    changes,                    notifications,                    fired,                )?;            }        }    }    Ok(())}/// Select the earliest expiring eligible purchase, with a stable id tie./// Refusal rolls back the root write and every cascade in the caller's transaction.fn ledger_purchase(ctx: &Ctx<'_>, rule: &automations::Ledger, row: &Data) -> Valid<Option<String>> {    let historical = rule.history.as_ref().is_some_and(|column| row.get(column).and_then(Value::as_str).is_some_and(|s| !s.is_empty()));    let override_ = row.get(&rule.override_column) == Some(&Value::Bool(true));    let account = row.get(&rule.account).and_then(Value::as_str)        .ok_or_else(|| ToolFailure::new(&rule.refusal))?;    let on = row.get(&rule.on).and_then(Value::as_str)        .ok_or_else(|| ToolFailure::new(&rule.refusal))?;    let held = row.get(&rule.purchase).and_then(Value::as_str);    let definition = definition(ctx, &rule.table)?;    let sql = format!("SELECT id FROM {} WHERE workspace_id = ? AND deleted_at IS NULL", made_table(definition.rows_table()));    let purchases = ctx.db().all(&sql, &[SqlValue::Text(ctx.workspace_id.into())]).map_err(sql_err)?;    let mut eligible = Vec::new();    for purchase in purchases {        let id = purchase.text("id").unwrap_or_default();        if held.is_some_and(|held| held != id) { continue; }        let data = expression_row(ctx, &definition, id)?;        if historical && !rule.history.as_ref().is_some_and(|column| data.get(column).and_then(Value::as_str).is_some_and(|s| !s.is_empty())) { continue; }        let starts = data.get(&rule.starts).and_then(Value::as_str);        let expires = data.get(&rule.expires).and_then(Value::as_str);        // An assigned live row already contributes its debit to the rollup.        // Historical credit is never a condition, even if its balance is absent.        // A purchase whose limit holds no count is unlimited between its dates.        let unlimited = rule.limit.as_ref().is_some_and(|limit| data.get(limit).is_none_or(Value::is_null));        let has_credit = historical || unlimited || data.get(&rule.remaining).and_then(Value::as_f64)            .is_some_and(|left| if held == Some(id) { left >= 0.0 } else { left >= 1.0 });        if data.get(&rule.purchase_account).and_then(Value::as_str) == Some(account)            && starts.is_none_or(|d| d <= on)            && expires.is_none_or(|d| on <= d)            && has_credit        {            eligible.push((expires.unwrap_or("9999-12-31").to_string(), id.to_string()));        }    }    eligible.sort();    if let Some((_, id)) = eligible.into_iter().next() {        if held == Some(id.as_str()) { return Ok(None); }        return Ok(Some(id));    }    // Historical books can be incomplete or overdrawn. Never allocate them to live credit.    if (historical || override_) && held.is_none() { return Ok(None); }    Err(ToolFailure::new(&rule.refusal))}/// Expressions read current derived columns without storing a balance in a synced field.fn expression_row(ctx: &Ctx<'_>, definition: &TableDefinition, id: &str) -> Valid<Data> {    let mut stored = load_live(ctx, definition, id)?;    if definition.has_computed() {        computed_in_step(ctx)?;        with_computed(ctx, definition, std::slice::from_mut(&mut stored))?;    }    for column in &definition.columns {        stored.data.entry(column.key.clone()).or_insert(Value::Null);    }    stored.data.insert("id".into(), Value::String(id.into()));    Ok(stored.data)}/// Whether the change `change_id` set an automation off: its run is kept/// under the change's own id.pub(super) fn ran_for(ctx: &Ctx<'_>, change_id: &str) -> Valid<bool> {    Ok(ctx        .read        .driver()        .get(            &format!("SELECT 1 AS ran FROM {RUNS} WHERE workspace_id = ? AND id = ? AND deleted_at IS NULL"),            &[                SqlValue::Text(ctx.workspace_id.into()),                SqlValue::Text(change_id.to_string()),            ],        )        .map_err(sql_err)?        .is_some())}pub(super) fn undo_group(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = id_arg(args, "change_id")?;    let started_at = now_iso(ctx);    let row = ctx        .read        .driver()        .get(            &format!(                "SELECT automation, changes, root_first FROM {RUNS} WHERE workspace_id = ? AND id = ? AND deleted_at IS NULL"            ),            &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(id)],        )        .map_err(sql_err)?;    let fired = row        .as_ref()        .and_then(|row| row.text("automation"))        .unwrap_or_default()        .to_string();    let ran = row        .as_ref()        .map(|row| serde_json::from_str::<Value>(row.text("changes").unwrap_or("[]")).map_err(sql_err))        .transpose()?;    let root_first = row.as_ref().and_then(|row| row.int("root_first")) == Some(1);    // A group's inverse has the opposite order: undo of undo restores the trigger first.    let mut result = if root_first {        Some(undo_now(ctx, args)?)    } else {        None    };    let mut undone = Vec::new();    let mut skipped = Vec::new();    if let Some(ran) = ran {        let ids = ran            .as_array()            .ok_or_else(|| ToolFailure::new("invalid automation undo group"))?;        for id in ids.iter().rev() {            let member = id                .as_str()                .ok_or_else(|| ToolFailure::new("invalid automation change id"))?;            let Some((mut change, _)) = find_change(ctx, member)? else {                // Emptying the Bin removes an erased record's changes. It has                // nothing left to reverse; keep the trigger undoable and tell                // the caller which effect's history has gone.                skipped.push(json!({"change_id":member,"reason":"The automation effect and its undo history were permanently erased; there is nothing left to reverse."}));                continue;            };            let mut live = true;            let mut seen = std::collections::BTreeSet::from([change.id.clone()]);            while let Some(next) = change.undone_by.clone() {                if !seen.insert(next.clone()) {                    return Err(ToolFailure::new("automation undo history contains a cycle"));                }                change = find_change(ctx, &next)?.ok_or_else(|| ToolFailure::new(format!(                    "automation undo history is missing change {next:?}; sync this device before undoing the trigger"                )))?.0;                live = !live;            }            if live {                // Reverse the last live inverse rather than the original,                // whose undone_by remains set even after its undo is undone.                undone.push(undo_now(                    ctx,                    json!({"change_id":change.id}).as_object().unwrap(),                )?);            }        }    }    let mut result = match result.take() {        Some(result) => result,        None => undo_now(ctx, args)?,    };    if !undone.is_empty() {        let id = result["change"]["id"].as_str().unwrap();        // The undo is a firing of its own, kept under the undo's change id:        // undoing IT puts the effects back, the trigger first.        let run = Run {            automation: fired,            changes: undone.iter().map(|c| c["change"]["id"].clone()).collect(),            root_first: Some(!root_first),            started_at,            outcome: if root_first { "redone" } else { "undone" },        };        write_run(ctx, id, run)?;        ctx.commit()?;        if let (Some(table), Some(id)) = (            result["change"]["table"].as_str(),            result["change"]["record_id"].as_str(),        ) {            let definition = definition(ctx, table)?;            result["record"] =                load(ctx, &definition, id)?.map_or(Value::Null, |stored| stored.to_json(&definition));        }    }    result["automation_undos"] = Value::Array(undone);    if !skipped.is_empty() {        result["automation_undo_skipped"] = Value::Array(skipped);    }    Ok(result)}thread_local! {    /// The byline an automation's writes carry while its action runs.    static BYLINE_AS: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };}/// The automation label [`byline`] answers with while an action runs.pub(super) fn byline_as() -> Option<String> {    BYLINE_AS.with(|cell| cell.borrow().clone())}/// Holds an automation's label as the byline until dropped, then puts back/// the one before it (an action can set off another automation).pub(super) struct Bylined(Option<String>);impl Bylined {    pub(super) fn as_label(label: &str) -> Bylined {        Bylined(BYLINE_AS.with(|cell| cell.replace(Some(label.to_string()))))    }}impl Drop for Bylined {    fn drop(&mut self) {        let before = self.0.take();        BYLINE_AS.with(|cell| *cell.borrow_mut() = before);    }}