Cotton code
220 lines · 13.1 KB · RustRaw
//! The place column writer. Dataset facts are resolved before any record write;//! only personal text and stable references enter the person's signed records.use cotton_core::definitions::{ColumnType, TableDefinition};use cotton_core::records::{place::PickedPlace, Data};use cotton_store::published::{self, Ask, Unread};use serde_json::{json, Value};use super::sql_err;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, now_iso, update_row, Valid};use crate::mcp::protocol::ToolFailure;pub fn is_column(definition: &TableDefinition, key: &str) -> bool {    (definition.id == "location" && key == "near" && definition.column("near").is_some())        || definition.columns.iter().any(|column| column.column_type == ColumnType::Place        && (column.key == key || column.place.as_ref().is_some_and(|p| p.id == key || p.country == key || p.zone == key            || [&p.lat, &p.lng, &p.version].into_iter().flatten().any(|sibling| sibling == key))))}pub fn split(definition: &TableDefinition, values: &Data, native_columns: &[&str]) -> (Data, Data) {    values.iter().map(|(k,v)| (k.clone(),v.clone())).partition(|(key,_)| {        let native_place_text = definition.column(key).is_some_and(|column|            column.column_type == ColumnType::Place && native_columns.contains(&key.as_str()));        native_place_text || !is_column(definition,key)    })}pub fn resolve(ctx: &mut Ctx<'_>, definition: &TableDefinition, values: &Data, record_id: Option<&str>) -> Valid<Data> {    // The generic verb owns an outer store transaction. Queue the personal    // location through the signed writer inside it; any later refusal rolls    // back the location, the parent, its companions and their receipts.    let mut picked_values = values.clone();    for column in definition.columns.iter().filter(|c| c.column_type == ColumnType::Place) {        if let Some((words, near)) = values.get(&column.key).and_then(cotton_core::records::place::kept) {            let id = keep(ctx, words, near)?;            picked_values.insert(column.key.clone(), json!({"place":id}));        }    }    let mut resolved = cotton_core::records::place::resolve(definition, &picked_values, |id| {        if let Some(location) = id.strip_prefix("location:") {            let row = ctx.read.driver().get(                "SELECT name,near FROM cotton_locations WHERE id=? AND workspace_id=? AND archived_at IS NULL AND trashed_at IS NULL",                &[location.to_string().into(), ctx.workspace_id.to_string().into()]).map_err(|e| e.to_string())?                .ok_or_else(|| "That saved location is not in this database".to_string())?;            let near = row.text("near").ok_or_else(|| "Choose the nearest dataset place for this location".to_string())?;            let (place, version) = place_at(near)?;            let place = place.ok_or_else(|| "The saved location's nearest place is missing from the dataset".to_string())?;            return Ok(PickedPlace {id:id.into(),name:row.text("name").unwrap_or_default().into(),country:text(&place,"country"),zone:text(&place,"zone"),                lat:place["lat"].as_f64(),lng:place["lng"].as_f64(),version:Some(version.clone())});        }        let (place, version) = place_at(id)?;        let place = place.ok_or_else(|| "Choose a place from the dataset".to_string())?;        Ok(PickedPlace {id:text(&place,"id"),name:text(&place,"name"),country:text(&place,"country"),zone:text(&place,"zone"),            lat:place["lat"].as_f64(),lng:place["lng"].as_f64(),version:Some(version)})    }).map_err(|refusal| ToolFailure::new(refusal.say(&crate::presentation::line_rows(ctx.read.driver(), ctx.workspace_id))))?;    if definition.id == "location" && definition.column("near").is_some() {        if values.contains_key("near") {            return Err(ToolFailure::new("The nearest dataset place is filled from the location's coordinates or its place pick"));        }        if values.contains_key("lat") || values.contains_key("lng") {            let existing = match record_id {                Some(id) => ctx.read.driver().get("SELECT lat,lng FROM cotton_locations WHERE id=? AND workspace_id=?",                    &[id.to_string().into(),ctx.workspace_id.to_string().into()]).map_err(sql_err)?,                None => None,            };            let coordinate = |key: &str| -> Option<f64> {                if let Some(value) = values.get(key) { return value.as_f64(); }                match existing.as_ref()?.get(key)? {                    rusqlite::types::Value::Real(value) => Some(*value),                    rusqlite::types::Value::Integer(value) => Some(*value as f64),                    _ => None,                }            };            let nearest = match (coordinate("lat"),coordinate("lng")) {                (Some(lat),Some(lng)) if lat.is_finite() && lng.is_finite() && lat.abs() <= 90.0 && lng.abs() <= 180.0 => {                    published::read("places", "places", &Ask::Near { lat, lng, limit: 1 }).map_err(|u| ToolFailure::new(said(&u)))?                        .rows.into_iter().next().and_then(|place| place.get("id").cloned()).unwrap_or(Value::Null)                }                (Some(_),Some(_)) => return Err(ToolFailure::new("finite latitude/longitude within Earth")),                _ => Value::Null,            };            resolved.insert("near".into(), nearest);        } else if let Some(id) = resolved.get("place_id").and_then(Value::as_str).filter(|id| id.starts_with("geonames:")) {            resolved.insert("near".into(), Value::String(id.into()));        }    }    Ok(resolved)}/// Reuse only a live personal location in this database with the same exact/// words and neighbour. A dataset name alone never creates a personal record.fn keep(ctx: &mut Ctx<'_>, words: &str, near: &str) -> Valid<String> {    let place = place(near).map_err(ToolFailure::new)?        .ok_or_else(|| ToolFailure::new("Choose the nearest place from the dataset"))?;    let held = ctx.read.driver().all("PRAGMA table_info(cotton_locations)", &[]).map_err(sql_err)?;    for key in ["near", "place", "place_id", "country", "timezone"] {        if !held.iter().any(|column| column.text("name") == Some(key)) {            return Err(ToolFailure::new("Update the app to keep this place"));        }    }    if let Some(row) = ctx.read.driver().get(        "SELECT id FROM cotton_locations WHERE workspace_id=? AND name=? AND near=? AND archived_at IS NULL AND trashed_at IS NULL ORDER BY id LIMIT 1",        &[ctx.workspace_id.to_string().into(), words.to_string().into(), near.to_string().into()]).map_err(sql_err)? {        if let Some(id) = row.text("id") { return Ok(format!("location:{id}")); }    }    let id = ctx.new_uuid();    let patch = json!({"workspace_id":ctx.workspace_id,"name":words,"near":near,        "place":place["name"],"place_id":place["id"],"country":place["country"],"timezone":place["zone"]});    insert_row(ctx, "cotton_locations", &id, patch.as_object().unwrap().clone())?;    ctx.commit()?;    Ok(format!("location:{id}"))}/// One published place by its id (`geonames:<n>`), through the one read;/// `None` when the published set has no such place.fn place(id: &str) -> Result<Option<Value>, String> {    place_at(id).map(|(place, _)| place)}/// [`place`] with the published version it was read at.fn place_at(id: &str) -> Result<(Option<Value>, String), String> {    let answer = published::read("places", "places", &Ask::Ids { ids: vec![id.to_string()], version: None }).map_err(|u| said(&u))?;    Ok((answer.rows.into_iter().next(), answer.version))}fn text(row: &Value, key: &str) -> String {    row.get(key).and_then(Value::as_str).unwrap_or_default().to_string()}/// Why no place was read, in the kit's words (`refusal.published.*`).fn said(unread: &Unread) -> String {    cotton_core::rules::shell_lines::LineSet::shipped("refusal")        .and_then(|set| set.say(unread.line(), &[("said", unread.said())]))        .unwrap_or_else(|| format!("refusal.{}", unread.line()))}/// Only the resolver (or an exact Undo before-image) hands these values here.pub fn write(ctx: &mut Ctx<'_>, definition: &TableDefinition, id: &str, values: &Data) -> Valid<()> {    if values.is_empty() { return Ok(()); }    let table = cotton_core::definitions::builtin_store_table(&definition.id)        .ok_or_else(|| ToolFailure::new("This place column has no record store"))?;    // What the store takes is the file's spec: the build's columns and those the object's definitions added.    let spec = cotton_store::schema::package_shape::spec_on(ctx.read.driver(), table).map_err(sql_err)?;    let holds = |key: &str| spec.is_some_and(|spec| spec.columns.iter().any(|(name, _)| *name == key));    // A place's coordinates and version are kept where this file stores them:    // a copy gains those columns from the object's definitions.    let extra: Vec<&String> = definition.columns.iter().filter_map(|c| c.place.as_ref())        .flat_map(cotton_core::records::place::extra_siblings).collect();    let mut patch = Data::new();    for (key, value) in values {        if extra.contains(&key) && !holds(key) { continue; }        if !is_column(definition,key) || !holds(key) {            return Err(ToolFailure::new("Update the app to store this place"));        }        patch.insert(key.clone(), value.clone());    }    if patch.is_empty() { return Ok(()); }    patch.insert("updated_at".into(), Value::String(now_iso(ctx)));    update_row(ctx, table, id, patch)?;    ctx.commit()}pub fn merge(ctx: &Ctx<'_>, definition: &TableDefinition, records: &mut [super::Stored]) -> Valid<()> {    if !definition.columns.iter().any(|c| c.column_type == ColumnType::Place) { return Ok(()); }    let Some(table) = cotton_core::definitions::builtin_store_table(&definition.id) else { return Ok(()) };    if records.is_empty() { return Ok(()); }    for chunk in records.chunks_mut(super::IN_CHUNK) {        let params = chunk.iter().map(|record| record.id.clone().into()).collect::<Vec<_>>();        let sql = format!("SELECT * FROM {table} WHERE id IN ({})", vec!["?";params.len()].join(","));        for row in ctx.read.driver().all(&sql, &params).map_err(sql_err)? {            let Some(record) = chunk.iter_mut().find(|record| row.text("id") == Some(record.id.as_str())) else { continue; };            for column in &definition.columns {                if is_column(definition, &column.key) {                    record.data.remove(&column.key);                    match row.get(&column.key) {                        Some(rusqlite::types::Value::Text(text)) => { record.data.insert(column.key.clone(), Value::String(text.clone())); }                        Some(rusqlite::types::Value::Real(n)) => { record.data.insert(column.key.clone(), serde_json::Number::from_f64(*n).map_or(Value::Null, Value::Number)); }                        Some(rusqlite::types::Value::Integer(n)) => { record.data.insert(column.key.clone(), Value::from(*n)); }                        _ => {}                    }                }            }        }    }    Ok(())}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// RULE: Picking an existing engine-owned place field still runs that engine's edit semantics, including calendar sync; only companion facts bypass its old argument format.    #[test]    fn native_place_text_keeps_its_engine_writer() {        let mut raw = serde_json::to_value(cotton_core::definitions::builtin_table_definition("event").unwrap()).unwrap();        let columns = raw["columns"].as_array_mut().unwrap();        let location = columns.iter_mut().find(|c| c["key"] == "location").unwrap();        location["type"] = json!("place");        location["place"] = json!({"id":"event_place","country":"country","zone":"timezone"});        for key in ["event_place","country","timezone"] {            if !columns.iter().any(|column| column["key"] == key) {                columns.push(json!({"key":key,"type":"text","readonly":true}));            }        }        let definition = TableDefinition::from_json(&raw.to_string()).unwrap();        definition.validate().unwrap();        let values = json!({"location":"Hyderabad","event_place":"geonames:1269843","country":"IN","timezone":"Asia/Kolkata"}).as_object().unwrap().clone();        let (engine,side) = split(&definition,&values,super::super::builtin::native_place_columns(&definition));        assert_eq!(engine,json!({"location":"Hyderabad"}).as_object().unwrap().clone());        assert_eq!(side,json!({"event_place":"geonames:1269843","country":"IN","timezone":"Asia/Kolkata"}).as_object().unwrap().clone());    }    /// RULE: Offline and signed out are told apart and each said in a kit line that promises what was picked still shows; the server's own refusal keeps its words.    #[test]    fn offline_signed_out_and_refused_are_each_said() {        assert_eq!(said(&Unread::Offline("no route".into())), "Cotton cannot be reached to look this up; what you already picked still shows");        assert_eq!(said(&Unread::SignedOut), "Sign in to Cotton to look this up; what you already picked still shows");        assert_eq!(said(&Unread::Refused { code: "slow_down".into(), message: "too many reads".into() }), "Cotton did not look this up: too many reads");    }}