Cotton code
122 lines · 5.1 KB · RustRaw
//! A search index filled in the background — the mailsearch lane's guards on//! `cotton_store::fts_fill`. Synthetic mail only: animals at example.invalid.use cotton_store::fts_fill::{begin, filling, step};use cotton_store::migrate::migrate_store;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;const WS: &str = "00000000-0000-4000-8000-000000000001";fn file_with_mail(n: i64) -> Driver {    let db = Driver::open_in_memory().expect("opens");    migrate_store(&db).expect("migrates");    db.exec("PRAGMA foreign_keys = OFF").unwrap();    for i in 0..n {        add(&db, i, &format!("Letter {i}"), "the river is high");    }    db}fn add(db: &Driver, i: i64, subject: &str, body: &str) {    db.run(        "INSERT INTO cotton_emails (id, workspace_id, thread_id, external_id, subject, from_email, from_name, \         sent_at, body, created_at) VALUES (?, ?, 'thread', ?, ?, 'otter@example.invalid', 'Otter', \         '2026-01-01T00:00:00.000Z', ?, '2026-01-01T00:00:00.000Z')",        &[            SqlValue::Text(format!("mail-{i}")),            SqlValue::Text(WS.into()),            SqlValue::Text(format!("mail-{i}")),            SqlValue::Text(subject.into()),            SqlValue::Text(body.into()),        ],    )    .unwrap();}/// Start the fill as a v122 move does: empty the new index, set the floor.fn as_moved(db: &Driver) {    db.exec("INSERT INTO fts_mail (fts_mail) VALUES ('delete-all')").unwrap();    begin(db, "fts_mail").unwrap();}fn held(db: &Driver) -> i64 {    db.get("SELECT count(*) AS n FROM fts_mail_docsize", &[]).unwrap().unwrap().int("n").unwrap()}fn found(db: &Driver, word: &str) -> Vec<String> {    db.all(        "SELECT e.id FROM fts_mail JOIN cotton_emails e ON e.rowid = fts_mail.rowid WHERE fts_mail MATCH ? ORDER BY e.id",        &[SqlValue::Text(word.into())],    )    .unwrap()    .iter()    .map(|row| row.text("id").unwrap().to_string())    .collect()}fn whole(db: &Driver) {    db.exec("INSERT INTO fts_mail (fts_mail, rank) VALUES ('integrity-check', 1)")        .expect("the index agrees with every row of its source");}/// RULE: filling an index is a BUDGETED job — each step writes at most its/// slice, in its own transaction, newest rows first — so indexing seventy/// thousand threads on a phone is many short holds of the file, never one/// long one on the thread that draws the screen.#[test]fn a_fill_step_never_writes_more_than_its_slice_and_goes_newest_first() {    let db = file_with_mail(25);    as_moved(&db);    assert_eq!(filling(&db, "fts_mail").unwrap().map(|p| (p.filled, p.total)), Some((0, 25)));    let first = step(&db, "fts_mail", 10).unwrap().unwrap();    assert_eq!((first.filled, first.done), (10, false));    assert_eq!(held(&db), 10);    // The newest ten: the last rows written are the first found.    assert!(found(&db, "river").contains(&"mail-24".to_string()));    assert!(!found(&db, "river").contains(&"mail-0".to_string()));    let mut steps = 1;    while !step(&db, "fts_mail", 10).unwrap().unwrap().done {        steps += 1;        assert!(held(&db) <= 25);    }    assert_eq!(steps, 3, "25 rows in slices of 10");    assert!(filling(&db, "fts_mail").unwrap().is_none(), "a whole index has no fill row");    assert_eq!(held(&db), 25);    whole(&db);}/// RULE: mail that arrives, changes or is erased WHILE an index fills is kept/// right — new mail is searchable at once (it lands above the floor), and a/// change to a row the fill has not reached never retracts an entry the index/// does not hold, which for an external-content index is corruption.#[test]fn writes_during_the_fill_are_searchable_at_once_and_never_corrupt_the_index() {    let db = file_with_mail(6);    as_moved(&db);    add(&db, 100, "Kingfisher", "a new letter about the kingfisher");    assert_eq!(found(&db, "kingfisher"), vec!["mail-100"], "new mail is found before the fill reaches anything");    step(&db, "fts_mail", 2).unwrap();    // Below the floor, not yet filled: changed and erased.    db.exec("UPDATE cotton_emails SET body = 'the heron came back' WHERE id = 'mail-0'").unwrap();    db.exec("DELETE FROM cotton_emails WHERE id = 'mail-1'").unwrap();    // Above the floor, already filled: changed.    db.exec("UPDATE cotton_emails SET body = 'the weir is low' WHERE id = 'mail-5'").unwrap();    while !step(&db, "fts_mail", 2).unwrap().unwrap().done {}    whole(&db);    assert_eq!(found(&db, "heron"), vec!["mail-0"]);    assert_eq!(found(&db, "weir"), vec!["mail-5"]);    assert!(!found(&db, "river").contains(&"mail-1".to_string()));    assert_eq!(held(&db), 6, "five letters left and the kingfisher");}/// RULE: a sender's NAME and ADDRESS are in the same index as the words, so a/// search for who wrote finds the mail without a scan of every thread.#[test]fn the_wide_index_finds_mail_by_the_sender_s_name_and_address() {    let db = file_with_mail(2);    assert!(filling(&db, "fts_mail").unwrap().is_none(), "a fresh file's index is whole from its first row");    assert_eq!(found(&db, "otter").len(), 2);    assert_eq!(found(&db, "\"otter@example.invalid\"").len(), 2);    whole(&db);}