Cotton code
244 lines · 9.7 KB · RustRaw
//! The feeds' index: what Today and "Asked of you" last answered in each held//! database, so reading them across every database opens no idle file.//!//! Both reads are pure — the answer is the file's rows and the call's//! arguments, and the core has no clock — so an answer kept against a STAMP of//! the file is exact for as long as the stamp holds. The stamp is read off the//! file system, never off the database: the main file's identity, size and//! modification time, and the write-ahead log's size, time and 32-byte header,//! whose salts move whenever the log starts again. Any writer//! — the exchange applying a section, a write the person makes, a fill//! replacing the file — moves the stamp, so no writer has to remember to//! invalidate anything, and a changed file is read again.//!//! Closing a file checkpoints its log and so moves the stamp with no row//! changed; the close path carries the kept answers across that one move,//! and only when the stamp before it is the one they were kept against.//!//! Kept in memory on the controller and never synced: a launch reads each//! database once, and an app update cannot answer from an older build's read.use std::collections::BTreeMap;use std::io::Read;use std::path::{Path, PathBuf};use serde_json::{Map, Value};/// How many answers one database keeps — a few days the person flips between.const KEPT: usize = 8;/// A held file's state as the file system shows it, without opening it.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Stamp {    main: Part,    wal: Option<Part>,    wal_header: Option<Vec<u8>>,}#[derive(Debug, Clone, PartialEq, Eq)]struct Part {    inode: u64,    len: u64,    modified: u128,}fn part(path: &Path) -> Option<Part> {    let metadata = std::fs::metadata(path).ok()?;    #[cfg(unix)]    let inode = std::os::unix::fs::MetadataExt::ino(&metadata);    #[cfg(not(unix))]    let inode = 0;    Some(Part {        inode,        len: metadata.len(),        modified: metadata            .modified()            .ok()?            .duration_since(std::time::UNIX_EPOCH)            .ok()?            .as_nanos(),    })}fn beside(path: &Path, suffix: &str) -> PathBuf {    let mut name = path.as_os_str().to_os_string();    name.push(suffix);    PathBuf::from(name)}/// The stamp of the database file at `path`; `None` when there is no file.////// NO DESCRIPTOR ON THE MAIN FILE OR ITS `-shm`, EVER. A process that closes/// any descriptor on a file drops every POSIX lock it holds on it — SQLite's/// included, which SQLite goes on believing it holds. The stamp read the/// `-shm` header through `File::open`, so every Today read dropped the app's/// locks on its databases; the next process to open one (a `sqlite3` reading/// the copy) took itself for the first, truncated the wal-index under the/// app's live reader, and the app died of SIGBUS in `walFindFrame` — two Macs,/// three times on 11 Oct 2026. SQLite's unix VFS locks the main file and/// the `-shm`, never the `-wal`, so the log's own header is read instead: each/// commit moves the log's size and time, and a restart moves its salts.pub fn stamp(path: &Path) -> Option<Stamp> {    let main = part(path)?;    let wal = beside(path, "-wal");    let wal_header = std::fs::File::open(&wal).ok().and_then(|mut file| {        let mut header = vec![0; 32];        file.read_exact(&mut header).ok().map(|()| header)    });    Some(Stamp {        main,        wal: part(&wal),        wal_header,    })}/// The answer a call is kept under: the read's name and its arguments.pub fn key(method: &str, args: &Map<String, Value>) -> String {    format!("{method} {}", Value::Object(args.clone()))}struct Kept {    stamp: Stamp,    answers: Vec<(String, Value)>,}/// Every held database's kept answers, by database id.#[derive(Default)]pub struct FeedIndex {    files: BTreeMap<String, Kept>,}impl FeedIndex {    /// The answer kept for `key` in `database`, if the file still has `stamp`.    pub fn answer(&self, database: &str, stamp: &Stamp, key: &str) -> Option<Value> {        let kept = self.files.get(database).filter(|kept| &kept.stamp == stamp)?;        kept.answers            .iter()            .find(|(at, _)| at == key)            .map(|(_, answer)| answer.clone())    }    /// Keep an answer read while the file had `stamp`. A new stamp drops what    /// was kept against the old one.    pub fn keep(&mut self, database: &str, stamp: Stamp, key: String, answer: Value) {        let kept = self.files.entry(database.to_string()).or_insert_with(|| Kept {            stamp: stamp.clone(),            answers: Vec::new(),        });        if kept.stamp != stamp {            kept.stamp = stamp;            kept.answers.clear();        }        kept.answers.retain(|(at, _)| *at != key);        kept.answers.push((key, answer));        if kept.answers.len() > KEPT {            kept.answers.remove(0);        }    }    /// The file was closed: its stamp moved from `before` to `after` with no    /// row changed. What was kept against `before` holds against `after`;    /// anything else goes.    pub fn carry(&mut self, database: &str, before: Option<&Stamp>, after: Option<Stamp>) {        let holds = self            .files            .get(database)            .is_some_and(|kept| before == Some(&kept.stamp));        match (holds, after) {            (true, Some(after)) => {                if let Some(kept) = self.files.get_mut(database) {                    kept.stamp = after;                }            }            _ => {                self.files.remove(database);            }        }    }    /// The database's file is going.    pub fn forget(&mut self, database: &str) {        self.files.remove(database);    }}#[cfg(test)]mod tests {    use super::*;    fn stamp_of(len: u64) -> Stamp {        Stamp {            main: Part { inode: 1, len, modified: 1 },            wal: None,            wal_header: None,        }    }    /// RULE: Taking a file's stamp leaves every SQLite lock this process holds on it standing for other processes — closing any descriptor on the main file or its `-shm` drops them all, and the next opener elsewhere truncates the wal-index under this process's live connections (SIGBUS in walFindFrame, two Macs, 11 Oct 2026).    #[test]    fn a_stamp_leaves_the_open_files_locks_standing_for_other_processes() {        const PROBE: &str = "COTTON_FEED_INDEX_LOCK_PROBE";        if let Ok(path) = std::env::var(PROBE) {            // THE OTHER PROCESS: may it take the write lock now, without waiting?            let other = rusqlite::Connection::open(&path).expect("the probe opens the file");            other.pragma_update(None, "busy_timeout", 0).expect("no wait");            let took = other.execute_batch("BEGIN IMMEDIATE").is_ok();            std::fs::write(beside(Path::new(&path), ".probe"), if took { "took" } else { "refused" })                .expect("the probe's answer");            std::process::exit(0);        }        let dir = tempfile::tempdir().expect("a folder");        let path = dir.path().join("replica.db");        let live = cotton_store::Driver::open(&path).expect("a file");        live.connection()            .execute_batch("PRAGMA journal_mode = WAL; CREATE TABLE t(v); INSERT INTO t VALUES (1); BEGIN IMMEDIATE; INSERT INTO t VALUES (2);")            .expect("a write held open");        assert!(stamp(&path).is_some(), "the file has a stamp");        std::process::Command::new(std::env::current_exe().expect("this test binary"))            .args([                "--exact",                "shell::feed_index::tests::a_stamp_leaves_the_open_files_locks_standing_for_other_processes",                "--nocapture",                "--test-threads=1",            ])            .env(PROBE, &path)            .output()            .expect("the probe runs");        let said = std::fs::read_to_string(beside(&path, ".probe")).expect("the probe answered");        live.connection().execute_batch("ROLLBACK").expect("the write let go");        assert_eq!(            said, "refused",            "another process took the write lock this process still holds — the stamp dropped SQLite's locks"        );    }    /// RULE: A commit moves the stamp, so a feed is read again after every write — the stamp reads the log, not the wal-index, and still sees each commit.    #[test]    fn a_commit_moves_the_stamp() {        let dir = tempfile::tempdir().expect("a folder");        let path = dir.path().join("replica.db");        let live = cotton_store::Driver::open(&path).expect("a file");        live.connection()            .execute_batch("PRAGMA journal_mode = WAL; CREATE TABLE t(v); INSERT INTO t VALUES (1);")            .expect("a first commit");        let before = stamp(&path).expect("a stamp");        live.connection().execute_batch("INSERT INTO t VALUES (2);").expect("a second commit");        assert_ne!(stamp(&path), Some(before), "the commit moved it");    }    #[test]    fn an_answer_holds_only_while_its_stamp_does_and_carries_across_a_close() {        let mut index = FeedIndex::default();        index.keep("a", stamp_of(1), "read.day {}".into(), Value::from(1));        assert_eq!(index.answer("a", &stamp_of(1), "read.day {}"), Some(Value::from(1)));        assert_eq!(index.answer("a", &stamp_of(2), "read.day {}"), None, "a moved file is read again");        index.carry("a", Some(&stamp_of(1)), Some(stamp_of(3)));        assert_eq!(index.answer("a", &stamp_of(3), "read.day {}"), Some(Value::from(1)));        index.carry("a", Some(&stamp_of(9)), Some(stamp_of(4)));        assert_eq!(index.answer("a", &stamp_of(4), "read.day {}"), None, "a file changed before its close is forgotten");    }}