//! Groundwork slice 5b-i: a replicated table is written only through `mint`. //! A raw `INSERT`, `UPDATE` or `DELETE` on a table that travels changes the //! row with no receipt, no stamp and no actor, so no other device ever hears //! of it, and the next write that does travel can undo it on one file and not //! another. This scan finds every such statement in `crates/*/src` and refuses //! any not on [`NOT_YET_THROUGH_MINT`], where each entry says why it is there. //! Later slices move the writes and shrink the list; an entry that names no //! raw write fails, so it only shrinks. //! //! It reads SQL as written in this repository: upper-case keywords and a //! literal table name. A statement built with `format!("UPDATE {table} …")` is //! the store's own fold, mint and receipt machinery, which is the one place a //! replicated row is meant to be written. use std::collections::BTreeSet; use std::path::{Path, PathBuf}; use cotton_store::schema::table_specs::{is_handed_over, TABLE_NAMES}; /// Raw writes to a replicated table that stand for now: (file from `crates/`, /// the functions in it that write, why). const NOT_YET_THROUGH_MINT: &[(&str, &[&str], &str)] = &[ // Fixtures under `src`, compiled only for tests: they seed a file the way // a provisioned or carried one looks, before any mint has an author. ( "cotton-client/src/test_support.rs", &["seed_workspace_row_for", "replica_with_rows"], "cfg(test) fixture: a replica file as a snapshot leaves it, rows present with no receipts", ), ( "cotton-ffi/src/fixture.rs", &["seeded", "device_row", "seed", "a_mac_behind"], "cfg(test) fixture: a phone file with synthetic rows for the screen-read tests", ), ( "cotton-conformance/src/lib.rs", &["baseline"], "the conformance lanes' baseline file: the workspace row every replayed vector's foreign key names", ), ( "cotton-store/src/fixtures.rs", &["seed_workspace_row"], "feature fixtures: the workspace row a test file needs before its first mint", ), // Not a fixture: a Cotton Dev method (3b9f79f45a) that makes this one copy // look served by an older server, for a walk and a UI test. Through mint // the stripped definition would travel and break the dev server's own. ( "cotton-ffi/src/phone/dev_look.rs", &["served_before"], "COTTON DEV ONLY, refused by name in the real Cotton: face_settings' definition without type_face on this copy alone, as a server before Look serves it; it must not travel, and the next pull takes the object's definition again", ), ]; 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`, as (path from `crates/`, /// text with any trailing `#[cfg(test)] mod …` cut off and comments blanked). fn sources() -> Vec<(String, String)> { let root = crates_root(); let mut found = Vec::new(); let mut crates: Vec = 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.is_empty(), "the raw-write scan found no source files"); 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 = 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(); // Test code by name: `_tests.rs`, `tests.rs`, and a `_bench.rs` measure a `_tests.rs` // pulls in by path (cotton-ffi shell_list_bench.rs seeds 65k synthetic rows with SQL). if !name.ends_with(".rs") || name.ends_with("_tests.rs") || name.ends_with("_bench.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, production_text(&text))); } } fn production_text(text: &str) -> String { use syn::spanned::Spanned; use syn::visit::Visit; fn requires_test(meta: &syn::Meta) -> bool { match meta { syn::Meta::Path(path) => path.is_ident("test"), syn::Meta::List(list) if list.path.is_ident("all") => list .parse_args_with(syn::punctuated::Punctuated::::parse_terminated) .is_ok_and(|terms| terms.iter().any(requires_test)), _ => false, } } struct TestModules { spans: Vec<(proc_macro2::LineColumn, proc_macro2::LineColumn)> } impl<'ast> Visit<'ast> for TestModules { fn visit_item_mod(&mut self, module: &'ast syn::ItemMod) { let test_only = module.attrs.iter().any(|attr| attr.path().is_ident("cfg") && attr.parse_args::().is_ok_and(|meta| requires_test(&meta))); if test_only { let span = module.span(); self.spans.push((span.start(), span.end())); } else { syn::visit::visit_item_mod(self, module); } } } let parsed = syn::parse_file(text).expect("source must parse before its raw writes are scanned"); let mut tests = TestModules { spans: Vec::new() }; tests.visit_file(&parsed); text.lines().enumerate().map(|(index, line)| { let code: String = line.chars().enumerate().map(|(column, c)| { let position = (index + 1, column); if tests.spans.iter().any(|(start, end)| (start.line, start.column) <= position && position < (end.line, end.column)) { ' ' } else { c } }).collect(); code.split_once("//").map_or(code.clone(), |(code, _)| code.to_string()) }).collect::>().join("\n") } // RULE: Only test-required modules leave the shipping-write scan; visibility // and other attributes do not change that, and later production stays scanned. #[test] fn test_only_host_fixtures_are_not_shipping_writes() { let fixture = "fn shipping() {}\n#[cfg(all(test, feature = \"host\"))]\n#[allow(dead_code)]\npub(crate) mod fixtures {\nfn seed() {}\n}\nfn later_shipping() {}"; let shipping = production_text(fixture); assert!(!shipping.contains("fn seed")); assert!(shipping.contains("fn later_shipping")); assert!(production_text(&fixture.replace("}\nfn later_shipping", "} fn later_shipping")).contains("fn later_shipping")); assert!(production_text(&fixture.replace("all(test,", "any(test,")).contains("fn seed")); } /// The words of `text`, each with its line and the function it is in. fn words(text: &str) -> Vec<(usize, String, String)> { let mut out = Vec::new(); let mut function = String::from("(top)"); let mut after_fn = false; for (index, line) in text.lines().enumerate() { for word in line.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) { if word.is_empty() { continue; } if after_fn { function = word.to_string(); } after_fn = word == "fn"; out.push((index + 1, function.clone(), word.to_string())); } } out } /// Every raw `INSERT … INTO`, `REPLACE INTO`, `UPDATE … SET` and /// `DELETE FROM` naming a replicated table: (file, function, line, table). fn raw_writes() -> Vec<(String, String, usize, String)> { let replicated: BTreeSet<&str> = TABLE_NAMES.iter().copied().filter(|t| is_handed_over(t)).collect(); let mut found = Vec::new(); for (path, text) in sources() { // The schema's own DDL and triggers are the store's machinery. if path.starts_with("cotton-store/src/schema/") { continue; } let words = words(&text); for (at, (line, function, word)) in words.iter().enumerate() { let (table_at, needs_set) = match word.as_str() { "INTO" => (at + 1, false), "UPDATE" => (at + 1, true), "DELETE" if words.get(at + 1).is_some_and(|(_, _, w)| w == "FROM") => (at + 2, false), _ => continue, }; let Some((_, _, table)) = words.get(table_at) else { continue }; if !replicated.contains(table.as_str()) { continue; } if needs_set && !words.get(table_at + 1).is_some_and(|(_, _, w)| w == "SET") { continue; } found.push((path.clone(), function.clone(), *line, table.clone())); } } found } /// RULE: No production code writes a replicated table with raw INSERT, UPDATE or DELETE: such a write has no receipt, stamp or actor and never reaches another device; every standing exception is on NOT_YET_THROUGH_MINT with its reason. #[test] fn no_raw_write_to_a_replicated_table() { let writes = raw_writes(); let offenders: Vec = writes .iter() .filter(|(path, function, _, _)| { !NOT_YET_THROUGH_MINT .iter() .any(|(file, functions, _)| file == path && functions.contains(&function.as_str())) }) .map(|(path, function, line, table)| format!("{path}:{line} (`{function}`) writes {table} with raw SQL")) .collect(); assert!( offenders.is_empty(), "a replicated table written outside `cotton_store::mint::mint` — write it through a Writer or `mint`:\n{}", offenders.join("\n") ); let sites: BTreeSet<(&str, &str)> = writes.iter().map(|(p, f, _, _)| (p.as_str(), f.as_str())).collect(); let mut stale = Vec::new(); for (file, functions, reason) in NOT_YET_THROUGH_MINT { assert!(!reason.trim().is_empty(), "{file} gives no reason"); for function in *functions { if !sites.contains(&(*file, *function)) { stale.push(format!("{file} `{function}`")); } } } assert!(stale.is_empty(), "NOT_YET_THROUGH_MINT names a function that no longer writes raw SQL — delete it:\n{}", stale.join("\n")); }