274 lines · 9.4 KB · RustRaw
//! The owner-facing readings and one writable setting for AI usage.use cotton_core::definitions::TableDefinition;use cotton_core::records::{Data, WhereClause};use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::{sql_err, Stored};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{now_iso, update_row, Valid};use crate::mcp::protocol::ToolFailure;/// RULE: usage is one row per purpose, owner-local day and currency; legacy calls without a local day retain their historical UTC date because their old owner zone is unknowable.const DAILY_SQL: &str = "SELECT COALESCE(local_day, substr(created_at, 1, 10)) AS day, function_name, currency, \ COALESCE(SUM(cost_amount), 0.0) AS cost_amount, COUNT(*) AS calls \ FROM cotton_ai_calls WHERE workspace_id = ? \ GROUP BY COALESCE(local_day, substr(created_at, 1, 10)), function_name, currency \ ORDER BY day DESC, cost_amount DESC, function_name ASC, currency ASC";const BUDGET_SQL: &str = "SELECT id, name, hourly_cap, daily_cap, currency, usd_rate, paused_until, pause_reason, created_at, updated_at \ FROM cotton_ai_budgets WHERE workspace_id = ?";/// Read usage in units that can safely be added: one purpose, day and currency.pub(super) fn daily( ctx: &Ctx<'_>, id: Option<&str>, _clauses: &[WhereClause],) -> Valid<Vec<Stored>> { let rows = ctx .read .driver() .all(DAILY_SQL, &[SqlValue::Text(ctx.workspace_id.to_string())]) .map_err(sql_err)?; let mut records = Vec::with_capacity(rows.len()); for row in rows { let day = row.text("day").unwrap_or_default().to_string(); let purpose = row.text("function_name").unwrap_or_default().to_string(); let currency = row.text("currency").unwrap_or_default().to_string(); let record_id = daily_id(&day, &purpose, ¤cy); if id.is_some_and(|wanted| wanted != record_id) { continue; } let mut data = Data::new(); data.insert("purpose".into(), Value::from(purpose)); data.insert("day".into(), Value::from(day.clone())); data.insert("currency".into(), Value::from(currency)); data.insert( "cost_amount".into(), Value::from(row.real("cost_amount").unwrap_or(0.0)), ); data.insert("calls".into(), Value::from(row.int("calls").unwrap_or(0))); records.push(Stored { id: record_id, data, created_at: Some(day), updated_at: None, deleted_at: None, byline: None, }); } Ok(records)}fn daily_id(day: &str, purpose: &str, currency: &str) -> String { format!("{day}:{currency}:{}:{purpose}", purpose.len())}/// Read the stored singleton, or the defaults a new database has before any/// AI call needs to persist them.pub(super) fn budget(ctx: &Ctx<'_>, id: Option<&str>) -> Valid<Vec<Stored>> { let rows = ctx .read .driver() .all(BUDGET_SQL, &[SqlValue::Text(ctx.workspace_id.to_string())]) .map_err(sql_err)?; let mut records: Vec<Stored> = rows.iter().filter_map(budget_record).collect(); if records.is_empty() { records.push(default_budget(ctx)); } Ok(records .into_iter() .filter(|record| id.is_none_or(|wanted| wanted == record.id)) .collect())}/// Update the one budget through the receipts writer, after applying the/// constraints SQLite cannot express for JSON's non-finite numbers.pub(super) fn budget_update( ctx: &mut Ctx<'_>, _definition: &TableDefinition, id: &str, patch: &Data,) -> Valid<()> { let patch = checked_budget_patch(patch)?; let workspace_id = ctx.workspace_id.to_string(); if ctx .read .driver() .all( "SELECT id FROM cotton_ai_budgets WHERE workspace_id = ? AND id = ?", &[ SqlValue::Text(workspace_id.clone()), SqlValue::Text(id.to_string()), ], ) .map_err(sql_err)? .is_empty() { let stamp = now_iso(ctx); ctx.writer()?.upsert( "cotton_ai_budgets", id, Map::from_iter([ ("workspace_id".into(), Value::from(workspace_id)), ("name".into(), Value::from("AI budget")), ("hourly_cap".into(), Value::from(1.0)), ("daily_cap".into(), Value::from(5.0)), ("currency".into(), Value::from("USD")), ("usd_rate".into(), Value::from(1.0)), ("created_at".into(), Value::from(stamp.clone())), ("updated_at".into(), Value::from(stamp)), ]), ); } let mut patch = patch; patch.insert("paused_until".into(), Value::Null); patch.insert("pause_reason".into(), Value::Null); update_row(ctx, "cotton_ai_budgets", id, patch)?; ctx.commit()}fn checked_budget_patch(patch: &Data) -> Valid<Map<String, Value>> { let mut checked = Map::new(); for (key, value) in patch { match key.as_str() { "hourly_cap" | "daily_cap" => { if !value .as_f64() .is_some_and(|number| number.is_finite() && number >= 0.0) { return Err(ToolFailure::new(format!( "{key} must be a finite number at least 0" ))); } } "usd_rate" => { if !value .as_f64() .is_some_and(|number| number.is_finite() && number > 0.0) { return Err(ToolFailure::new("usd_rate must be a finite number above 0")); } } "currency" => { if !value.as_str().is_some_and(is_currency) { return Err(ToolFailure::new( "currency must be three uppercase ASCII letters", )); } if !patch.contains_key("usd_rate") { return Err(ToolFailure::new( "currency changes need usd_rate in the same update", )); } } _ => {} } checked.insert(key.clone(), value.clone()); } Ok(checked)}fn default_budget(ctx: &Ctx<'_>) -> Stored { Stored { id: ctx.workspace_id.to_string(), data: budget_data("AI budget", 1.0, 5.0, "USD", 1.0, None, None), created_at: None, updated_at: None, deleted_at: None, byline: None, }}fn budget_record(row: &cotton_store::Row) -> Option<Stored> { let id = row.text("id")?.to_string(); Some(Stored { id, data: budget_data( row.text("name").unwrap_or("AI budget"), row.real("hourly_cap").unwrap_or(1.0), row.real("daily_cap").unwrap_or(5.0), row.text("currency").unwrap_or("USD"), row.real("usd_rate").unwrap_or(1.0), row.text("paused_until"), row.text("pause_reason"), ), created_at: row.text("created_at").map(str::to_owned), updated_at: row.text("updated_at").map(str::to_owned), deleted_at: None, byline: None, })}fn budget_data( name: &str, hourly_cap: f64, daily_cap: f64, currency: &str, usd_rate: f64, paused_until: Option<&str>, pause_reason: Option<&str>,) -> Data { let mut data = Data::from_iter([ ("name".into(), Value::from(name)), ("hourly_cap".into(), Value::from(hourly_cap)), ("daily_cap".into(), Value::from(daily_cap)), ("currency".into(), Value::from(currency)), ("usd_rate".into(), Value::from(usd_rate)), ]); if let Some(value) = paused_until { data.insert("paused_until".into(), Value::from(value)); } if let Some(value) = pause_reason { data.insert("pause_reason".into(), Value::from(value)); } data}fn is_currency(value: &str) -> bool { value.len() == 3 && value.bytes().all(|byte| byte.is_ascii_uppercase())}#[cfg(test)]mod tests { use serde_json::json; use super::{checked_budget_patch, daily_id, Data}; /// RULE: budget limits are finite non-negative amounts, exchange rates are finite and positive, and totals never combine different currencies. #[test] fn budget_refuses_invalid_caps_rates_and_currency() { for (key, value) in [ ("hourly_cap", json!(-0.01)), ("daily_cap", json!(-1)), ("usd_rate", json!(0)), ("currency", json!("usd")), ] { let mut patch = Data::new(); patch.insert(key.into(), value); assert!( checked_budget_patch(&patch).is_err(), "{key} should be refused" ); } } /// RULE: changing display currency also changes its USD conversion rate. #[test] fn budget_refuses_an_unpaired_currency_change() { let mut patch = Data::new(); patch.insert("currency".into(), json!("EUR")); assert!(checked_budget_patch(&patch).is_err()); } /// RULE: daily usage has one row per day, purpose and currency; different currencies never collide in its record identity. #[test] fn daily_ids_keep_same_day_purpose_and_currency_together() { assert_ne!( daily_id("2026-10-13", "mail.extract", "USD"), daily_id("2026-10-13", "mail.extract", "EUR") ); }}