Cotton code
130 lines · 4.9 KB · RustRaw
//! Slice 4's guard on `_parked`: a park ends only when it applies, is folded//! as stale, is taken by the peer, or the owner discards it — every one of//! those through `cotton_store::rejected`'s one `end_park`, which is the only//! `DELETE FROM _parked` in any crate's production source. A second delete//! (a ceiling, a tidy-up, a reset) is a write a person lost without being//! told, so the scan refuses it rather than trusting a review to see it.//!//! Tests are not scanned: a test empties the table to set up a case. The//! phone snapshot's strip of a COPY (`snapshot::NOT_ON_A_PHONE`) deletes by//! a table name it reads from a list, not by this literal, and removes the//! serving Mac's parks from a file the phone has not yet taken — never a//! park of the file that holds it.use std::path::{Path, PathBuf};fn crates_root() -> PathBuf {    cotton_store::manifest_dir()        .parent()        .expect("cotton-store sits in the crates directory")        .to_path_buf()}/// Every production source file under `crates/*/src` (no `*_tests.rs`, no/// `tests.rs`), as (path from `crates/`, text).fn sources() -> Vec<(String, String)> {    let root = crates_root();    let mut found = Vec::new();    let mut crates: Vec<PathBuf> = std::fs::read_dir(&root)        .expect("the crates directory")        .filter_map(Result::ok)        .map(|entry| entry.path().join("src"))        .filter(|src| src.is_dir())        .collect();    crates.sort();    for src in crates {        walk(&src, &root, &mut found);    }    assert!(found.len() > 200, "the scan found only {} files", found.len());    found}fn walk(dir: &Path, root: &Path, found: &mut Vec<(String, String)>) {    let Ok(entries) = std::fs::read_dir(dir) else {        return;    };    let mut paths: Vec<PathBuf> = entries.filter_map(Result::ok).map(|e| e.path()).collect();    paths.sort();    for path in paths {        if path.is_dir() {            walk(&path, root, found);            continue;        }        let name = path.file_name().and_then(|n| n.to_str()).unwrap_or_default();        if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name == "tests.rs" {            continue;        }        let Ok(text) = std::fs::read_to_string(&path) else {            continue;        };        let relative = path            .strip_prefix(root)            .unwrap_or(&path)            .to_string_lossy()            .replace('\\', "/");        found.push((relative, text));    }}/// Each line of `text` that deletes from, drops or truncates `_parked`.fn deletes_of_parked(text: &str) -> Vec<(usize, String)> {    let mut hits = Vec::new();    for (number, line) in text.lines().enumerate() {        let lower = line.to_ascii_lowercase();        let code = lower.split("//").next().unwrap_or_default();        let compact: String = code.split_whitespace().collect::<Vec<_>>().join(" ");        if compact.contains("delete from _parked")            || compact.contains("drop table _parked")            || compact.contains("drop table if exists _parked")        {            hits.push((number + 1, line.trim().to_string()));        }    }    hits}/// RULE: A park is deleted only by resolution (applied, stale, delivered) or by the owner: `rejected::end_park` holds the one DELETE FROM _parked in production source, and nothing else calls it.#[test]fn no_park_is_deleted_except_by_resolution_or_owner() {    let mut deletes = Vec::new();    let mut callers = Vec::new();    for (path, text) in sources() {        for (line, sql) in deletes_of_parked(&text) {            deletes.push(format!("{path}:{line}: {sql}"));        }        if path != "cotton-store/src/rejected.rs" && text.contains("end_park(") {            callers.push(path);        }    }    assert_eq!(        deletes.len(),        1,        "a park ends only through `rejected::end_park` — a park is never dropped for any other reason:\n{}",        deletes.join("\n")    );    assert!(        deletes[0].starts_with("cotton-store/src/rejected.rs:"),        "the one delete of `_parked` is `rejected::end_park`'s: {}",        deletes[0]    );    assert!(callers.is_empty(), "`end_park` is rejected.rs's own: {callers:?}");    // And `end_park` takes only a named way to end: resolution or the owner.    let rejected = std::fs::read_to_string(crates_root().join("cotton-store/src/rejected.rs"))        .expect("rejected.rs");    let body = rejected        .split("enum Ended {")        .nth(1)        .and_then(|rest| rest.split('}').next())        .expect("the Ended enum");    let variants: Vec<&str> = body        .lines()        .map(str::trim)        .filter(|line| !line.is_empty() && !line.starts_with("//"))        .collect();    assert_eq!(        variants,        ["Resolved,", "Superseded,", "Delivered,", "Discarded,"],        "a new way for a park to end is a decision about losing writes — name it here deliberately"    );}