Cotton code
428 lines · 17.0 KB · RustRaw
//! Tolerant reading, strict authoring — the guard that replaced//! `deny_unknown_fields` on every definition kind (design note 26203e21 §8).//!//! Devices on different builds share one database: a newer Mac writes a//! definition, board or theme row carrying a key an older phone cannot name.//! Refusing it on read made the older device's whole catalogue unreadable and//! a relay drop the row; dropping it silently lost the key on the next write.//! So a READ decodes what it knows and keeps the rest (a top-level `unknown`//! map). Capabilities are recognised by field presence. AUTHORING — a package, a//! built-in file, a row a person writes here — is held to exactly the keys//! this build names, by [`unknown_keys`].//!//! The same holds for a VALUE (architect, 15 Oct 2026): a newer device's word//! for how something is drawn (a face "grid" this build cannot draw) never//! fails the read of the whole row. A drawing word this build does not name//! reads as its key's shipped default — absent for an optional key, the//! enum's declared default for a required one, dropped from a list or a map —//! and the row carries the paths it fell back on (`fallbacks`), so the app//! says one line and draws the rest. A word that decides what a write does or//! what a figure computes (a column's type, a command's kind) has no safe//! default and still refuses the row. An authored row is refused for either.use std::cell::RefCell;use serde::de::{DeserializeOwned, Deserializer, Error as _};use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use super::DefinitionError;/// The opaque remainder of a row: keys this build does not name.pub type Unknown = Map<String, Value>;/// The keys `raw` carries that `typed` (its tolerant decode) does not, as/// dotted paths (`page.0.width`), plus `typed`'s own top-level `unknown`/// keys, which the decode kept rather than understood.////// A key whose value is empty (null, false, [], {}) can be absent from the/// encoding because the field skips an empty value, not because the type/// does not name it; such a key is PROBED — set to a value no field holds and/// decoded again — and named only when the type still reads around it.pub fn unknown_keys<T: Serialize + DeserializeOwned>(raw: &Value, typed: &T, kept: &Unknown) -> Vec<String> {    let encoded = encode(typed, kept);    let (mut sure, mut probe) = (Vec::new(), Vec::new());    missing(raw, &encoded, &mut Vec::new(), &mut sure, &mut probe);    for path in probe {        let mut probed = raw.clone();        if let Some(slot) = probed.pointer_mut(&pointer(&path)) {            *slot = Value::String(PROBE.into());        }        let read_around = serde_json::from_value::<T>(probed).is_ok_and(|again| {            encode(&again, kept).pointer(&pointer(&path)).is_none()        });        if read_around {            sure.push(path);        }    }    let mut out: Vec<String> = sure.iter().map(|path| path.join(".")).collect();    out.sort();    out}const PROBE: &str = "\u{0}not a value any field holds";fn encode<T: Serialize>(typed: &T, kept: &Unknown) -> Value {    let mut encoded = serde_json::to_value(typed).unwrap_or(Value::Null);    if let Value::Object(map) = &mut encoded {        for key in kept.keys() {            map.remove(key);        }    }    encoded}fn pointer(path: &[String]) -> String {    path.iter().map(|segment| format!("/{}", segment.replace('~', "~0").replace('/', "~1"))).collect()}fn missing(raw: &Value, encoded: &Value, at: &mut Vec<String>, sure: &mut Vec<Vec<String>>, probe: &mut Vec<Vec<String>>) {    match (raw, encoded) {        (Value::Object(raw), Value::Object(encoded)) => {            for (key, value) in raw {                at.push(key.clone());                match encoded.get(key) {                    Some(inner) => missing(value, inner, at, sure, probe),                    None if empty(value) => probe.push(at.clone()),                    None => sure.push(at.clone()),                }                at.pop();            }        }        (Value::Array(raw), Value::Array(encoded)) => {            for (index, (value, inner)) in raw.iter().zip(encoded).enumerate() {                at.push(index.to_string());                missing(value, inner, at, sure, probe);                at.pop();            }        }        _ => {}    }}fn empty(value: &Value) -> bool {    match value {        Value::Null | Value::Bool(false) => true,        Value::Array(items) => items.is_empty(),        Value::Object(map) => map.is_empty(),        _ => false,    }}/// Refuse what [`unknown_keys`] finds, and every drawing word this build/// does not name ([`fallback_paths`]), as `path word`.pub fn refuse_unknown<T: Serialize + DeserializeOwned>(raw: &Value, typed: &T, kept: &Unknown) -> Result<(), DefinitionError> {    let mut unknown = unknown_keys(raw, typed, kept);    let (again, words, acts) = reading_acts(|| serde_json::from_value::<T>(raw.clone()));    unknown.extend(acts.iter().map(|act| super::automations::said("an_act_this_build_cannot_run", &[("act", act)])));    if let Ok(again) = again {        for path in fallback_paths(raw, &again, &words) {            let word = raw.pointer(&pointer(&path.split('.').map(str::to_string).collect::<Vec<_>>())).and_then(Value::as_str).unwrap_or_default();            unknown.push(format!("{path} {word}"));        }    }    if unknown.is_empty() {        Ok(())    } else {        Err(DefinitionError::UnknownKeys(unknown))    }}/// Decode an AUTHORED value of a type with no top-level `unknown` map, and/// refuse any key the type does not name.pub fn authored<T: Serialize + DeserializeOwned>(raw: &Value) -> Result<T, DefinitionError> {    let typed: T = serde_json::from_value(raw.clone()).map_err(|error| DefinitionError::Parse(error.to_string()))?;    refuse_unknown(raw, &typed, &Map::new())?;    Ok(typed)}thread_local! {    /// The words each read in progress fell back on, innermost read last.    static FELL_BACK: RefCell<Vec<Vec<String>>> = const { RefCell::new(Vec::new()) };    /// The acts each read in progress left out as unavailable, by id or label.    static UNAVAILABLE: RefCell<Vec<Vec<String>>> = const { RefCell::new(Vec::new()) };}type Frames = std::thread::LocalKey<RefCell<Vec<Vec<String>>>>;fn open(frames: &'static Frames) {    frames.with(|frames| frames.borrow_mut().push(Vec::new()));}fn close(frames: &'static Frames) -> Vec<String> {    frames.with(|frames| {        let mut frames = frames.borrow_mut();        let found = frames.pop().unwrap_or_default();        // A read inside another is part of it: the outer read fell back too.        if let Some(outer) = frames.last_mut() {            outer.extend(found.iter().cloned());        }        found    })}fn note(frames: &'static Frames, said: String) {    frames.with(|frames| {        if let Some(frame) = frames.borrow_mut().last_mut() {            frame.push(said);        }    });}/// Run `read`, answering what it read and the drawing words it fell back on.pub fn reading<T>(read: impl FnOnce() -> T) -> (T, Vec<String>) {    let (read, words, _) = reading_acts(read);    (read, words)}/// [`reading`], also answering the acts it left out as unavailable.pub fn reading_acts<T>(read: impl FnOnce() -> T) -> (T, Vec<String>, Vec<String>) {    open(&FELL_BACK);    open(&UNAVAILABLE);    let read = read();    let acts = close(&UNAVAILABLE);    let words = close(&FELL_BACK);    (read, words, acts)}/// Say that the read in progress left out the act `name` as unavailable.pub fn left_out(name: &str) {    note(&UNAVAILABLE, name.to_string());}/// A list of acts (`C`, of `T`s, optional or not): an act holding a word this/// build does not name — a kind, a class, a scheme: a word that decides what/// it does, so no default is safe — is left out whole as unavailable, named/// by its `id` (or its `label`), and every other act reads as it came.pub fn available<'de, D: Deserializer<'de>, T: DeserializeOwned, C: DeserializeOwned>(deserializer: D) -> Result<C, D::Error> {    let mut value = Value::deserialize(deserializer)?;    if let Value::Array(items) = &mut value {        items.retain(|item| {            let Err(error) = serde_json::from_value::<T>(item.clone()) else { return true };            let said = error.to_string();            if !said.starts_with("unknown variant") {                return true;            }            if let Some(word) = said.split('`').nth(1) {                fell_back(&Value::String(word.to_string()));            }            let name = item.get("id").or_else(|| item.get("label")).and_then(Value::as_str).unwrap_or_default();            left_out(name);            false        });    }    serde_json::from_value(value).map_err(D::Error::custom)}pub(crate) fn fell_back(word: &Value) {    note(&FELL_BACK, word.as_str().map_or_else(|| word.to_string(), str::to_string));}/// `value` is a word `T` does not name — not malformed, a newer build's.pub(crate) fn unnamed<T: DeserializeOwned>(value: &Value) -> bool {    value.is_string()        && serde_json::from_value::<T>(value.clone()).is_err_and(|error| error.to_string().starts_with("unknown variant"))}/// A required drawing word: one this build does not name reads as the enum's/// declared default (`#[serde(deserialize_with = "tolerant::word")]`).pub fn word<'de, D: Deserializer<'de>, T: DeserializeOwned + Default>(deserializer: D) -> Result<T, D::Error> {    let value = Value::deserialize(deserializer)?;    if unnamed::<T>(&value) {        fell_back(&value);        return Ok(T::default());    }    serde_json::from_value(value).map_err(D::Error::custom)}/// An optional drawing word: one this build does not name reads as absent,/// what the key draws when a row does not say it.pub fn word_or_absent<'de, D: Deserializer<'de>, T: DeserializeOwned>(deserializer: D) -> Result<Option<T>, D::Error> {    let value = Value::deserialize(deserializer)?;    if unnamed::<T>(&value) {        fell_back(&value);        return Ok(None);    }    serde_json::from_value(value).map_err(D::Error::custom)}/// A list or a map of drawing words (`C`, of `T`s, optional or not): each/// word this build does not name is left out, the rest read as they came.pub fn known_words<'de, D: Deserializer<'de>, T: DeserializeOwned, C: DeserializeOwned>(deserializer: D) -> Result<C, D::Error> {    let mut value = Value::deserialize(deserializer)?;    let keep = |item: &Value| {        let unknown = unnamed::<T>(item);        if unknown {            fell_back(item);        }        !unknown    };    match &mut value {        Value::Array(items) => items.retain(|item| keep(item)),        Value::Object(map) => map.retain(|_, item| keep(item)),        _ => {}    }    serde_json::from_value(value).map_err(D::Error::custom)}/// A list of objects each drawn with the word under its `face` (`F`) — a/// table's shipped views: an object whose face this build does not name is/// left out, the rest read as they came (`T`). A definition another build/// serves, naming a face this one does not draw, still reads, without it.pub fn known_faces<'de, D: Deserializer<'de>, T: DeserializeOwned, F: DeserializeOwned>(    deserializer: D,) -> Result<Option<Vec<T>>, D::Error> {    let mut value = Value::deserialize(deserializer)?;    if let Value::Array(items) = &mut value {        items.retain(|item| {            let unknown = item.get("face").is_some_and(unnamed::<F>);            if unknown {                fell_back(&item["face"]);            }            !unknown        });    }    serde_json::from_value(value).map_err(D::Error::custom)}/// Where in `raw` the words a read fell back on stood, as dotted paths/// (`tile.face`, `page_parts.2`): each place `raw` holds one of `words` that/// the typed read (`typed`) does not hold as it came.pub fn fallback_paths<T: Serialize>(raw: &Value, typed: &T, words: &[String]) -> Vec<String> {    if words.is_empty() {        return Vec::new();    }    let encoded = serde_json::to_value(typed).unwrap_or(Value::Null);    let mut out = Vec::new();    differs(raw, Some(&encoded), &mut Vec::new(), words, &mut out);    out.sort();    out.dedup();    out}fn differs(raw: &Value, encoded: Option<&Value>, at: &mut Vec<String>, words: &[String], out: &mut Vec<String>) {    match raw {        Value::Object(map) => {            for (key, value) in map {                at.push(key.clone());                differs(value, encoded.and_then(|encoded| encoded.get(key)), at, words, out);                at.pop();            }        }        Value::Array(items) => {            for (index, value) in items.iter().enumerate() {                at.push(index.to_string());                differs(value, encoded.and_then(|encoded| encoded.get(index)), at, words, out);                at.pop();            }        }        Value::String(word) if encoded != Some(raw) && words.contains(word) => out.push(at.join(".")),        _ => {}    }}/// A JSON tree read whole for a second pass, refusing an object that names a/// key twice: `serde_json::Value` keeps the last, and the direct read it/// stands in for refused it (a filter naming a column twice).pub struct Whole(pub Value);impl<'de> Deserialize<'de> for Whole {    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {        deserializer.deserialize_any(WholeVisitor).map(Whole)    }}struct WholeVisitor;impl<'de> serde::de::Visitor<'de> for WholeVisitor {    type Value = Value;    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {        formatter.write_str(&super::refusal_words("a_json_value"))    }    fn visit_bool<E>(self, value: bool) -> Result<Value, E> {        Ok(Value::Bool(value))    }    fn visit_i64<E>(self, value: i64) -> Result<Value, E> {        Ok(Value::from(value))    }    fn visit_u64<E>(self, value: u64) -> Result<Value, E> {        Ok(Value::from(value))    }    fn visit_f64<E>(self, value: f64) -> Result<Value, E> {        Ok(Value::from(value))    }    fn visit_str<E>(self, value: &str) -> Result<Value, E> {        Ok(Value::String(value.to_string()))    }    fn visit_string<E>(self, value: String) -> Result<Value, E> {        Ok(Value::String(value))    }    fn visit_none<E>(self) -> Result<Value, E> {        Ok(Value::Null)    }    fn visit_unit<E>(self) -> Result<Value, E> {        Ok(Value::Null)    }    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Value, D::Error> {        Whole::deserialize(deserializer).map(|whole| whole.0)    }    fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Value, A::Error> {        let mut items = Vec::new();        while let Some(Whole(item)) = seq.next_element()? {            items.push(item);        }        Ok(Value::Array(items))    }    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {        let mut map = Map::new();        while let Some(property) = access.next_key::<String>()? {            if map.contains_key(&property) {                return Err(A::Error::custom(super::automations::said("key_is_named_twice", &[("key", &format!("{property:?}"))])));            }            let Whole(value) = access.next_value()?;            map.insert(property, value);        }        Ok(Value::Object(map))    }}/// The read of a definition kind whose drawing words fall back: the derived/// decode (`#[serde(remote = "Self")]`) inside [`reading_acts`], with the/// paths it fell back on in the kind's `fallbacks` and the acts it left out/// (and those its `unrunnable` names) in `unavailable`. Serialising is the/// derived one.#[macro_export]macro_rules! tolerant_read {    ($kind:ty) => {        impl<'de> serde::Deserialize<'de> for $kind {            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {                let mut raw = $crate::definitions::tolerant::Whole::deserialize(deserializer)?.0;                if let Some(map) = raw.as_object_mut() {                    map.remove("fallbacks");                }                if let Some(map) = raw.as_object_mut() {                    map.remove("unavailable");                }                let (read, words, mut acts) = $crate::definitions::tolerant::reading_acts(|| <$kind>::deserialize(&raw));                let mut read = read.map_err(<D::Error as serde::de::Error>::custom)?;                for act in read.unrunnable() {                    $crate::definitions::tolerant::left_out(&act);                    acts.push(act);                }                read.fallbacks = $crate::definitions::tolerant::fallback_paths(&raw, &read, &words);                read.unavailable = acts;                Ok(read)            }        }        impl serde::Serialize for $kind {            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {                <$kind>::serialize(self, serializer)            }        }    };}#[cfg(test)]#[path = "tolerant_tests.rs"]mod tests;