Cotton code
427 lines · 16.8 KB · RustRaw
//! One server transaction reads capacity, counts live claims, and writes one movement row.use super::*;use cotton_core::definitions::{reserve::Reservation, ToolDefinition};use cotton_store::mint::Held;thread_local! {static WRITING:std::cell::Cell<bool>=const{std::cell::Cell::new(false)};}pub(super) struct Writing(bool);impl Writing {    pub(super) fn enter() -> Self {        Self(WRITING.with(|v| v.replace(true)))    }}impl Drop for Writing {    fn drop(&mut self) {        WRITING.with(|v| v.set(self.0));    }}pub(super) fn require_action(ctx: &Ctx<'_>, table: &str) -> Valid<()> {    if !WRITING.with(|v| v.get())        && cotton_store::server_actions::reservation_table(ctx.db(), &made_table(table))            .map_err(sql_err)?    {        return Err(ToolFailure::new(            "Use reserve_record or cancel_reservation for this server-owned claim table",        ));    }    Ok(())}fn config(ctx: &Ctx<'_>, args: &Map<String, Value>) -> Valid<(ToolDefinition, Reservation)> {    if ctx.writer_held() != Some(Held::Served) {        return Err(ToolFailure::new(            "Reservations run only on the serving machine, never on a phone copy",        ));    }    let id = id_arg(args, "tool")?;    let tool = super::super::tool_packages::live_tool_definitions(ctx)?        .into_iter()        .find(|t| t.id == id)        .ok_or_else(|| ToolFailure::new("reservation tool is not installed"))?;    tool.validate().map_err(sql_err)?;    let tables = tool        .tables        .iter()        .map(|t| definition(ctx, t))        .collect::<Valid<Vec<_>>>()?;    cotton_core::definitions::reserve::validate_tables(&tool, &tables).map_err(ToolFailure::new)?;    let binding = tool        .reserve        .clone()        .ok_or_else(|| ToolFailure::new("tool has no reserve binding"))?;    Ok((tool, binding))}fn remaining(ctx: &mut Ctx<'_>, r: &Reservation, slot: &str) -> Valid<i64> {    let table = definition(ctx, &r.slot_table)?;    let mut stored = load_live(ctx, &table, slot)?;    if table        .column(&r.capacity_column)        .is_some_and(|c| c.computed.is_some())    {        computed_in_step(ctx)?;        with_computed(ctx, &table, std::slice::from_mut(&mut stored))?;    }    let capacity = stored        .data        .get(&r.capacity_column)        .and_then(Value::as_f64)        .filter(|n| n.is_finite() && *n >= 0.0 && n.fract() == 0.0 && *n < (i64::MAX as f64))        .ok_or_else(|| ToolFailure::new("capacity must be a nonnegative whole number"))?        as i64;    let claims = definition(ctx, &r.claim_table)?;    // Read typed quantities rather than SQL SUM: checked integer addition refuses overflow.    let quantity = r        .quantity_column        .as_ref()        .map(|key| ident(key))        .unwrap_or_else(|| "1".into());    let rows = ctx.db().all(&format!("SELECT {quantity} AS quantity FROM {} WHERE workspace_id = ? AND {} = ? AND deleted_at IS NULL", ident(&made_table(&claims.id)), ident(&r.slot_column)),        &[SqlValue::Text(ctx.workspace_id.into()),SqlValue::Text(slot.into())]).map_err(sql_err)?;    let mut used = 0_i64;    for row in rows {        let value = row.get("quantity");        let count = match value {            None | Some(SqlValue::Null) => 1,            Some(SqlValue::Integer(n)) if *n > 0 => *n,            Some(SqlValue::Real(n))                if n.is_finite() && *n > 0.0 && n.fract() == 0.0 && *n < i64::MAX as f64 =>            {                *n as i64            }            _ => {                return Err(ToolFailure::new(                    "stored quantity must be a positive whole number",                ))            }        };        used = used            .checked_add(count)            .ok_or_else(|| ToolFailure::new("reservation quantity overflow"))?;    }    Ok(capacity.saturating_sub(used).max(0))}pub fn reserve_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    reserve(ctx, args, false)}/// Trusted import producers retain source identity while claiming capacity./// This is deliberately absent from public MCP dispatch.pub fn reserve_imported_record(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    reserve(ctx, args, true)}fn reserve(ctx: &mut Ctx<'_>, args: &Map<String, Value>, imported: bool) -> ToolResult {    atomically_noted(ctx, |ctx| {        let (tool, r) = config(ctx, args)?;        let slot = id_arg(args, "slot")?;        let left = remaining(ctx, &r, &slot)?;        let mut data = data_arg(args, "data")?            .as_object()            .cloned()            .ok_or_else(|| ToolFailure::new("data must be an object"))?;        let order = if imported { None } else { order_binding(&tool)? };        if imported {            let claims = definition(ctx, &r.claim_table)?;            if !claims                .column("import_id")                .is_some_and(|c| c.column_type == cotton_core::definitions::ColumnType::Text)            {                return Err(ToolFailure::new(                    "This table needs an import id text column",                ));            }            if let Some(source) = data.get("import_id").and_then(Value::as_str) {                let found = ctx                    .db()                    .get(                        &format!(                            "SELECT id FROM {} WHERE workspace_id=? AND import_id=?",                            ident(&made_table(claims.rows_table()))                        ),                        &[ctx.workspace_id.to_owned().into(), source.to_owned().into()],                    )                    .map_err(sql_err)?;                if found.is_some() {                    let written = super::create_imported_record(                        ctx,                        json!({"table":r.claim_table,"data":data})                            .as_object()                            .unwrap(),                    )?;                    return Ok(                        json!({"ok":true,"reason":null,"remaining":left,"record":written["record"]}),                    );                }            }        }        let quantity = if let Some(key) = &r.quantity_column {            let value = data.entry(key.clone()).or_insert(json!(1));            value                .as_i64()                .filter(|n| *n > 0)                .or_else(|| {                    value                        .as_f64()                        .filter(|n| {                            n.is_finite() && *n > 0.0 && n.fract() == 0.0 && *n < i64::MAX as f64                        })                        .map(|n| n as i64)                })                .ok_or_else(|| ToolFailure::new("quantity must be a positive whole number"))?        } else {            1        };        if quantity > left {            return Ok(json!({"ok":false,"reason":"full","remaining":left}));        }        let quote = order            .map(|spec| quote(ctx, spec, &r, &slot, quantity, &mut data))            .transpose()?;        if data            .get(&r.slot_column)            .is_some_and(|v| v != &Value::String(slot.clone()))        {            return Err(ToolFailure::new("data names a different slot"));        }        data.insert(r.slot_column.clone(), Value::String(slot));        let _writing = Writing::enter();        let create = if imported {            super::create_imported_record_now        } else {            create_record_now        };        let written = create(            ctx,            json!({"table":r.claim_table,"data":data})                .as_object()                .unwrap(),        )?;        if written.get("ask").is_some() {            return Err(ToolFailure::new(                "reservation data needs all required values",            ));        }        drop(_writing);        let written = automations::run(ctx, written)?;        // A cancellation is its own action; generic undo must not bypass the capacity check.        let mut answer = json!({"ok":true,"reason":null,"remaining":left-quantity,"record":written["record"]});        if let Some(quote) = quote {            write_line(ctx, &r, quote, &mut answer)?;        }        Ok(answer)    })}pub fn cancel_reservation(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    atomically_noted(ctx, |ctx| {        let (tool, r) = config(ctx, args)?;        let id = id_arg(args, "id")?;        let table = definition(ctx, &r.claim_table)?;        let record = load(ctx, &table, &id)?.ok_or_else(|| not_found(&table, &id))?;        let slot = record            .data            .get(&r.slot_column)            .and_then(Value::as_str)            .ok_or_else(|| ToolFailure::new("claim has no slot"))?            .to_string();        if record.deleted_at.is_none() {            let _writing = Writing::enter();            delete_record_now(                ctx,                json!({"table":r.claim_table,"id":id}).as_object().unwrap(),            )?;        }        // An order's lines go with it.        if let Some(spec) = order_binding(&tool)? {            let lines = definition(ctx, &spec.line_table)?;            let held = ctx.db().all(                &format!("SELECT id FROM {} WHERE workspace_id=? AND {}=? AND deleted_at IS NULL", ident(&made_table(lines.rows_table())), ident(&spec.order_link)),                &[SqlValue::Text(ctx.workspace_id.into()), SqlValue::Text(id.clone())],            ).map_err(sql_err)?;            for line in held {                delete_record_now(ctx, json!({"table":spec.line_table,"id":line.text("id")}).as_object().unwrap())?;            }        }        Ok(json!({"ok":true,"reason":null,"remaining":remaining(ctx,&r,&slot)?}))    })}fn ident(name: &str) -> String {    format!("\"{}\"", name.replace('"', "\"\""))}/// A package's order binding, its tool's `order` block: a reservation that is/// an order is priced from its slot's item and writes one line for it, the/// same on every road an order comes by — a customer's order, a menu day's/// Take an order, a dish's Order.#[derive(Clone, serde::Deserialize)]#[serde(deny_unknown_fields)]pub struct OrderBinding {    pub line_table: String,    pub order_link: String,    pub item_table: String,    pub item_link: String,    pub slot_item_link: String,    pub quantity: String,    pub price: String,    pub currency: String,    pub line_total: String,    pub order_total: String,    pub order_date: String,    pub slot_date: String,    /// The order's link to a plan the customer bought (a kitchen's meal    /// subscription): an order naming one is a meal the plan already paid    /// for, so its line is priced at nothing. Whether the plan has a meal    /// left is the package's own rule (its ledger), run in the same write.    #[serde(default)]    pub plan: Option<String>,}pub fn order_binding(tool: &ToolDefinition) -> Valid<Option<OrderBinding>> {    tool.unknown        .get("order")        .map(|v| serde_json::from_value(v.clone()).map_err(|e| ToolFailure::new(format!("order binding: {e}"))))        .transpose()}/// The line an order is about to write, priced before the order is.struct Quote {    spec: OrderBinding,    line: Map<String, Value>,    price: i64,    quantity: i64,    total: i64,    currency: String,}fn whole(value: Option<&Value>) -> Option<i64> {    let value = value?;    value.as_i64().or_else(|| {        value            .as_f64()            .filter(|n| n.is_finite() && n.fract() == 0.0 && n.abs() < i64::MAX as f64)            .map(|n| n as i64)    })}/// Price the order on `slot` from the slot's item, and put its quantity,/// currency and day into the order: a value already there must agree.fn quote(ctx: &mut Ctx<'_>, spec: OrderBinding, r: &Reservation, slot: &str, quantity: i64, data: &mut Map<String, Value>) -> Valid<Quote> {    let slots = definition(ctx, &r.slot_table)?;    if !slots        .column(&spec.slot_item_link)        .is_some_and(|c| c.link_to.as_deref() == Some(spec.item_table.as_str()))    {        return Err(ToolFailure::new("order binding must link the slot to its item"));    }    if r.quantity_column.as_deref() != Some(spec.quantity.as_str()) {        return Err(ToolFailure::new("reserve must bind the order quantity column"));    }    let slot_row = load_live(ctx, &slots, slot)?;    let item = slot_row        .data        .get(&spec.slot_item_link)        .and_then(Value::as_str)        .ok_or_else(|| ToolFailure::new("menu slot has no item"))?        .to_string();    let items = definition(ctx, &spec.item_table)?;    let item_row = load_live(ctx, &items, &item)?;    let price = whole(item_row.data.get(&spec.price))        .filter(|p| *p >= 0)        .ok_or_else(|| ToolFailure::new("menu item needs a price in whole minor units"))?;    let on_plan = spec        .plan        .as_ref()        .is_some_and(|plan| data.get(plan).is_some_and(|held| !held.is_null()));    let price = if on_plan { 0 } else { price };    let currency = item_row        .data        .get(&spec.currency)        .and_then(Value::as_str)        .filter(|v| !v.is_empty())        .ok_or_else(|| ToolFailure::new("menu item needs a currency"))?        .to_string();    let date = slot_row        .data        .get(&spec.slot_date)        .filter(|day| !day.is_null())        .cloned()        .ok_or_else(|| ToolFailure::new("menu slot needs its date"))?;    let total = price        .checked_mul(quantity)        .ok_or_else(|| ToolFailure::new("order total overflow"))?;    for (key, value) in [        (&spec.quantity, json!(quantity)),        (&spec.currency, json!(currency)),        (&spec.order_date, date),    ] {        if data.get(key).is_some_and(|old| !old.is_null() && whole(Some(old)).map(Value::from).as_ref().unwrap_or(old) != &value) {            return Err(ToolFailure::new("order currency and date come from the selected menu slot"));        }        data.insert(key.clone(), value);    }    let line = definition(ctx, &spec.line_table)?;    if !line        .column(&spec.order_link)        .is_some_and(|c| c.link_to.as_deref() == Some(r.claim_table.as_str()))        || !line            .column(&spec.item_link)            .is_some_and(|c| c.link_to.as_deref() == Some(spec.item_table.as_str()))    {        return Err(ToolFailure::new("order line must link its order and item"));    }    let computed_total = definition(ctx, &r.claim_table)?        .column(&spec.order_total)        .and_then(|c| c.computed.as_ref())        .map(serde_json::to_value)        .transpose()        .map_err(|e| ToolFailure::new(e.to_string()))?;    if computed_total.as_ref().and_then(|v| v.get("rollup"))        != Some(&json!({"table":spec.line_table,"link":spec.order_link,"op":"sum","column":spec.line_total}))    {        return Err(ToolFailure::new("order total must sum its line rows"));    }    let mut values = Map::from_iter([        (spec.item_link.clone(), json!(item)),        (spec.quantity.clone(), json!(quantity)),        (spec.price.clone(), json!(price)),        (spec.currency.clone(), json!(currency)),        (spec.line_total.clone(), json!(total)),    ]);    if let Some(name) = item_row.data.get(&items.title).filter(|name| !name.is_null()) {        values.insert(line.title.clone(), name.clone());    }    Ok(Quote { spec, line: values, price, quantity, total, currency })}/// Write the order's line beside the order just taken. The line is whose the/// order is: each link the line shares with the order (its customer) holds/// the order's own value.fn write_line(ctx: &mut Ctx<'_>, r: &Reservation, mut quote: Quote, answer: &mut Value) -> Valid<()> {    let id = answer["record"]["id"]        .as_str()        .ok_or_else(|| ToolFailure::new("order was not created"))?        .to_string();    let claims = definition(ctx, &r.claim_table)?;    let lines = definition(ctx, &quote.spec.line_table)?;    for column in &lines.columns {        let shared = column.link_to.is_some()            && column.key != quote.spec.order_link            && column.key != quote.spec.item_link            && claims.column(&column.key).is_some_and(|c| c.link_to == column.link_to);        if let Some(value) = answer["record"]["data"].get(&column.key).filter(|v| shared && !v.is_null()) {            quote.line.insert(column.key.clone(), value.clone());        }    }    quote.line.insert(quote.spec.order_link.clone(), json!(id));    let made = create_record_now(        ctx,        json!({"table":quote.spec.line_table,"data":quote.line}).as_object().unwrap(),    )?;    if made.get("ask").is_some() {        return Err(ToolFailure::new("order line needs additional details"));    }    let made = automations::run(ctx, made)?;    answer["record"]["data"][&quote.spec.order_total] = json!(quote.total);    answer["lines"] = json!([made["record"]]);    answer["quote"] = json!({"quantity":quote.quantity,"price":quote.price,"currency":quote.currency,"total":quote.total});    Ok(())}