Cotton code
115 lines · 4.6 KB · RustRaw
//! THE RULE (e2e rulings R1, 15 Nov 2026): every table of a personal database//! is sealed unless `default.json` (beside this file) names it, open by design//! (R1) or pending the move of the object's own work on its values (R2/R3).//!//! A table's own `seal` block wins. A table with none takes the default: its//! clear columns are only what the object's SQL needs: the columns the//! definition names as its date, order, archive, project, row key, sort and//! group (a sort of words excepted: each device sorts its own copy), its links, the archive and trash marks, and the columns its computed//! columns read. Everything else is sealed.//!//! The Worker reads the same file (apps/business/src/seal.ts `defaultSeal`),//! and both answer the vectors in//! `crates/cotton-conformance/vectors/seal/default.json`.use std::collections::{BTreeMap, BTreeSet};use std::sync::OnceLock;use serde::Deserialize;use serde_json::{json, Value};use crate::definitions::seal::SealSpec;/// The rule's file, as the Worker imports it too.pub const RULE_JSON: &str = include_str!("default.json");#[derive(Deserialize)]struct SortedOnDevice {    types: Vec<String>,}#[derive(Deserialize)]struct Rule {    marks: Vec<String>,    sorted_on_device: SortedOnDevice,    open: BTreeMap<String, String>,    pending: BTreeMap<String, String>,}fn rule() -> &'static Rule {    static RULE: OnceLock<Rule> = OnceLock::new();    RULE.get_or_init(|| serde_json::from_str(RULE_JSON).expect("seal/default.json reads"))}/// Why `table` stays open by design (R1), when the rule says it does.pub fn open_by_design(table: &str) -> Option<&'static str> {    rule().open.get(table).map(String::as_str)}/// Why `table` is still open until the object's own work on its values moves/// (R2/R3), when the rule says so.pub fn pending(table: &str) -> Option<&'static str> {    rule().pending.get(table).map(String::as_str)}/// The seal a personal table with no `seal` block of its own takes, or none:/// for a table the rule leaves open, an `internal` one (the object's own),/// and one with a block (it says itself).pub fn default_seal(definition: &Value) -> Option<SealSpec> {    let id = definition["id"].as_str()?;    if definition.get("seal").is_some() || definition["internal"] == json!(true) || open_by_design(id).is_some() || pending(id).is_some() {        return None;    }    let mut named: BTreeSet<&str> = BTreeSet::new();    for key in [&definition["date"], &definition["order"], &definition["archived"], &definition["project"], &definition["row_key"], &definition["group"]["column"]] {        if let Some(key) = key.as_str() {            named.insert(key);        }    }    let columns: Vec<&Value> = definition["columns"].as_array().into_iter().flatten().filter(|column| column["key"].is_string()).collect();    // A sort of words is the device's (R3): only a sort the object can order without reading a word stays clear.    let words = &rule().sorted_on_device.types;    for key in [&definition["sort"]["column"], &definition["sort"]["tie"]].into_iter().filter_map(Value::as_str) {        let kind = columns.iter().find(|column| column["key"] == json!(key)).and_then(|column| column["type"].as_str());        if !kind.is_some_and(|kind| words.iter().any(|word| word == kind)) {            named.insert(key);        }    }    for column in &columns {        let computed = &column["computed"];        for key in computed["formula"]["of"].as_array().into_iter().flatten().filter_map(Value::as_str) {            named.insert(key);        }        for key in [&computed["formula"]["flip_when"]["column"], &computed["lookup"]["through"]] {            if let Some(key) = key.as_str() {                named.insert(key);            }        }    }    let marks = &rule().marks;    let clear = columns        .iter()        .filter(|column| column["computed"].is_null())        .filter_map(|column| column["key"].as_str().map(|key| (key, column)))        .filter(|(key, column)| *key != "id" && (named.contains(key) || column["type"] == json!("link") || marks.iter().any(|mark| mark == key)))        .map(|(key, _)| key.to_string())        .collect();    Some(SealSpec { clear, ..SealSpec::default() })}/// A personal database's table definition as the rule makes it: its own/// block, the default's written out, or itself when the rule leaves it open.pub fn ruled(definition: &Value) -> Value {    match default_seal(definition) {        Some(seal) => {            let mut out = definition.clone();            out["seal"] = json!({ "clear": seal.clear });            out        }        None => definition.clone(),    }}#[cfg(test)]#[path = "rule_tests.rs"]mod tests;