Cotton code
841 lines · 46.9 KB · RustRaw
//! Mail end to end: a scripted IMAP server on a local socket (plain, so the//! loopback rule lets the password through), the importer, and the object as//! a server inside the test that keeps the rows it is sent.mod support;use std::collections::HashMap;use std::io::{BufRead, BufReader, Write};use std::net::TcpListener;use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};use cotton_mac::importer::{Importer, Progress, RunContext, SourceKey};use cotton_mac::mail::MailImporter;use cotton_mac::object::ObjectClient;use cotton_mac::sink::ObjectSink;use cotton_mac::store::Store;use cotton_store::protocol::derived_id::derived_id;use cotton_store::protocol::fingerprint::email::message_id_external_id;use serde_json::{json, Value};use support::{Answer, TestServer};const DB: &str = "00000000-0000-4000-8000-000000000001";type Rows = Arc<Mutex<HashMap<(String, String), Value>>>;/// The object's `/v1/act` as the contract has it: a create of a held id is/// `409 duplicate_id`, an update merges, an update or delete of a missing/// row is `404 no_such_record`.fn object() -> (TestServer, Rows) {    object_with_arrived(Vec::new())}/// The same object, holding `arrived` from the person's own domain (`POST /v1/mail/arrived`).fn object_with_arrived(arrived: Vec<String>) -> (TestServer, Rows) {    let rows: Rows = Arc::new(Mutex::new(HashMap::new()));    let held = Arc::clone(&rows);    let server = TestServer::start(move |request| {        if request.path == "/v1/mail/arrived" && !arrived.is_empty() {            let asked = request.json()["ids"].as_array().cloned().unwrap_or_default();            let found: Vec<Value> = asked.into_iter().filter(|id| arrived.iter().any(|a| id == a)).collect();            return Answer::json(200, json!({ "arrived": found }));        }        if request.path != "/v1/act" {            return Answer::json(404, json!({ "code": "not_found", "message": "no route" }));        }        let body = request.json();        let table = body["args"]["table"].as_str().unwrap().to_string();        let id = body["args"]["id"].as_str().unwrap().to_string();        let data = body["args"]["data"].clone();        let mut rows = held.lock().unwrap();        let key = (table, id);        match body["act"].as_str().unwrap() {            "create" if rows.contains_key(&key) => Answer::json(409, json!({ "code": "duplicate_id", "message": "held" })),            "create" => {                rows.insert(key, data);                Answer::json(200, json!({ "version": 1, "changed": [] }))            }            "update" => match rows.get_mut(&key) {                Some(row) => {                    for (k, v) in data.as_object().unwrap() {                        row[k] = v.clone();                    }                    Answer::json(200, json!({ "version": 2, "changed": [] }))                }                None => Answer::json(404, json!({ "code": "no_such_record", "message": "none" })),            },            "delete" => match rows.remove(&key) {                Some(_) => Answer::json(200, json!({ "version": 3, "changed": [] })),                None => Answer::json(404, json!({ "code": "no_such_record", "message": "none" })),            },            _ => Answer::json(400, json!({ "code": "bad_act", "message": "?" })),        }    });    (server, rows)}fn acts(server: &TestServer) -> Vec<Value> {    server.requests().iter().filter(|r| r.path == "/v1/act").map(|r| r.json()).collect()}fn message(id: &str, date: &str, subject: &str, refs: Option<&str>, from: &str, text: &str) -> String {    let refs = refs.map(|r| format!("References: {r}\r\nIn-Reply-To: {r}\r\n")).unwrap_or_default();    format!(        "From: {from}\r\nTo: Owner <owner@example.com>\r\nSubject: {subject}\r\nDate: {date}\r\nMessage-ID: {id}\r\n{refs}Content-Type: text/plain\r\n\r\n{text}\r\n"    )}/// The mailbox the fake server serves: (uid, flags, raw).type Mailbox = Arc<Mutex<Vec<(u32, &'static str, String)>>>;fn uids_of(set: &str, mailbox: &[(u32, &'static str, String)]) -> Vec<u32> {    let mut out = Vec::new();    for part in set.split(',') {        match part.split_once(':') {            Some((lo, hi)) => {                let lo: u32 = lo.parse().unwrap();                let hi: u32 = if hi == "*" { u32::MAX } else { hi.parse().unwrap() };                out.extend(mailbox.iter().map(|m| m.0).filter(|uid| *uid >= lo && *uid <= hi));            }            None => out.push(part.parse().unwrap()),        }    }    out}/// A plain IMAP server over `mailbox`: LOGIN, CAPABILITY, EXAMINE, UID/// SEARCH, UID FETCH, IDLE (which says `* n EXISTS` once `idle_news` is set)/// and LOGOUT, one thread per connection. Records every command line but the/// LOGIN's.fn imap(mailbox: Mailbox, idle_news: Arc<AtomicBool>) -> (u16, Arc<Mutex<Vec<String>>>) {    imap_dropping(mailbox, idle_news, Arc::new(AtomicUsize::new(0)))}/// As [`imap`], but the first `byes` body FETCHes are answered as Gmail did on 22 Nov 2026: `* BYE System/// Error`, and the connection closed.fn imap_dropping(mailbox: Mailbox, idle_news: Arc<AtomicBool>, byes: Arc<AtomicUsize>) -> (u16, Arc<Mutex<Vec<String>>>) {    serve(mailbox, idle_news, byes, false)}/// As [`imap`], speaking as Gmail: `X-GM-EXT-1`, All Mail by its `\All` flag, each message's Gmail id/// (1000 + its UID) and thread id with its metadata, `UID SEARCH X-GM-MSGID`, and no mail in any category.fn imap_gmail(mailbox: Mailbox) -> (u16, Arc<Mutex<Vec<String>>>) {    serve(mailbox, Arc::new(AtomicBool::new(false)), Arc::new(AtomicUsize::new(0)), true)}fn serve(mailbox: Mailbox, idle_news: Arc<AtomicBool>, byes: Arc<AtomicUsize>, gmail: bool) -> (u16, Arc<Mutex<Vec<String>>>) {    let listener = TcpListener::bind("127.0.0.1:0").unwrap();    let port = listener.local_addr().unwrap().port();    let lines = Arc::new(Mutex::new(Vec::new()));    let recorded = Arc::clone(&lines);    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { continue };            let mailbox = Arc::clone(&mailbox);            let recorded = Arc::clone(&recorded);            let idle_news = Arc::clone(&idle_news);            let byes = Arc::clone(&byes);            std::thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                let mut reader = BufReader::new(stream);                writer.write_all(b"* OK fake ready\r\n").unwrap();                let mut idle_tag: Option<String> = None;                loop {                    let mut line = String::new();                    if reader.read_line(&mut line).unwrap_or(0) == 0 {                        return;                    }                    let line = line.trim_end().to_string();                    if line == "DONE" {                        let tag = idle_tag.take().unwrap();                        writer.write_all(format!("{tag} OK idle done\r\n").as_bytes()).unwrap();                        continue;                    }                    let (tag, rest) = line.split_once(' ').unwrap();                    let words: Vec<&str> = rest.split(' ').collect();                    if words[0] != "LOGIN" {                        recorded.lock().unwrap().push(rest.to_string());                    }                    let held = mailbox.lock().unwrap().clone();                    let mut out = String::new();                    match words[0] {                        "LOGIN" => {                            assert_eq!(words[1], "\"owner@example.com\"");                            out.push_str(&format!("{tag} OK signed in\r\n"));                        }                        "CAPABILITY" => {                            let gm = if gmail { " X-GM-EXT-1" } else { "" };                            out.push_str(&format!("* CAPABILITY IMAP4rev1 IDLE{gm}\r\n{tag} OK\r\n"))                        }                        "LIST" if gmail => out.push_str(&format!("* LIST (\\HasNoChildren \\All) \"/\" \"[Gmail]/All Mail\"\r\n{tag} OK\r\n")),                        "EXAMINE" => {                            let next = held.iter().map(|m| m.0).max().unwrap_or(0) + 1;                            out.push_str(&format!(                                "* {} EXISTS\r\n* OK [UIDVALIDITY 9] v\r\n* OK [UIDNEXT {next}] n\r\n{tag} OK [READ-ONLY] done\r\n",                                held.len()                            ));                        }                        "UID" if words[1] == "SEARCH" => {                            // `UID 1:<n> SINCE <date>` with or without BEFORE:                            // every message is this year's.                            let found: Vec<String> = if rest.contains("X-GM-RAW") {                                Vec::new()                            } else if let Some(gm) = rest.split("X-GM-MSGID ").nth(1) {                                let gm: u32 = gm.trim().parse().unwrap();                                held.iter().filter(|m| m.0 + 1000 == gm).map(|m| m.0.to_string()).collect()                            } else if rest.contains("BEFORE") {                                Vec::new()                            } else if words.len() < 4 {                                // `UID SEARCH ALL`: every UID.                                held.iter().map(|m| m.0.to_string()).collect()                            } else {                                uids_of(words[3], &held).iter().map(u32::to_string).collect()                            };                            out.push_str(&format!("* SEARCH {}\r\n{tag} OK\r\n", found.join(" ")));                        }                        "UID" if words[1] == "FETCH" => {                            let bodies = rest.contains("BODY.PEEK[]");                            if bodies && byes.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok() {                                let _ = writer.write_all(b"* BYE System Error\r\n");                                return;                            }                            for (n, uid) in uids_of(words[2], &held).into_iter().enumerate() {                                let Some((_, flags, raw)) = held.iter().find(|m| m.0 == uid) else { continue };                                if bodies {                                    out.push_str(&format!(                                        "* {} FETCH (UID {uid} INTERNALDATE \"05-Oct-2026 09:30:00 +0000\" BODY[] {{{}}}\r\n{raw})\r\n",                                        n + 1,                                        raw.len()                                    ));                                } else if rest.contains("INTERNALDATE") {                                    out.push_str(&format!("* {} FETCH (UID {uid} INTERNALDATE \"04-Mar-2011 09:30:00 +0000\")\r\n", n + 1));                                } else if rest.contains("HEADER.FIELDS") {                                    // The page's metadata: flags, and the asked headers as Gmail answers them.                                    let head = raw.split("\r\n\r\n").next().unwrap_or("");                                    let wanted = ["message-id", "list-unsubscribe", "list-unsubscribe-post", "list-id", "precedence", "auto-submitted"];                                    // A folded line goes with the field it continues, as a server answers it.                                    let mut taking = false;                                    let fields: String = head                                        .split("\r\n")                                        .filter(|line| {                                            if !line.starts_with([' ', '\t']) {                                                taking = line.split_once(':').is_some_and(|(name, _)| wanted.contains(&name.trim().to_ascii_lowercase().as_str()));                                            }                                            taking                                        })                                        .map(|line| format!("{line}\r\n"))                                        .collect::<String>()                                        + "\r\n";                                    let gm = if gmail { format!("X-GM-MSGID {0} X-GM-THRID {0} X-GM-LABELS () ", uid + 1000) } else { String::new() };                                    out.push_str(&format!(                                        "* {} FETCH (UID {uid} {gm}FLAGS ({flags}) BODY[HEADER.FIELDS (MESSAGE-ID LIST-UNSUBSCRIBE LIST-UNSUBSCRIBE-POST LIST-ID PRECEDENCE AUTO-SUBMITTED)] {{{}}}\r\n{fields})\r\n",                                        n + 1,                                        fields.len()                                    ));                                } else {                                    out.push_str(&format!("* {} FETCH (UID {uid} FLAGS ({flags}))\r\n", n + 1));                                }                            }                            out.push_str(&format!("{tag} OK\r\n"));                        }                        "IDLE" => {                            idle_tag = Some(tag.to_string());                            writer.write_all(b"+ idling\r\n").unwrap();                            let idle_news = Arc::clone(&idle_news);                            let mut news_writer = writer.try_clone().unwrap();                            std::thread::spawn(move || {                                let started = Instant::now();                                while started.elapsed() < Duration::from_secs(10) {                                    if idle_news.swap(false, Ordering::SeqCst) {                                        let _ = news_writer.write_all(b"* 4 EXISTS\r\n");                                        return;                                    }                                    std::thread::sleep(Duration::from_millis(20));                                }                            });                        }                        "LOGOUT" => {                            out.push_str(&format!("* BYE bye\r\n{tag} OK\r\n"));                            writer.write_all(out.as_bytes()).unwrap();                            return;                        }                        _ => out.push_str(&format!("{tag} BAD unknown\r\n")),                    }                    writer.write_all(out.as_bytes()).unwrap();                }            });        }    });    (port, lines)}fn importer(dir: &std::path::Path, port: u16) -> MailImporter {    let importer = MailImporter::new(dir);    importer        .command(            "credentials",            &json!({ "address": "owner@example.com", "password": "app-pw", "imapHost": format!("127.0.0.1:{port}"), "imapTls": false }),        )        .unwrap();    importer}fn run(importer: &MailImporter, object: &TestServer, store: &Store) -> String {    let client = ObjectClient::new(object.url.clone(), Some("device-token".to_string())).unwrap();    let sink = ObjectSink::new(&client, DB);    let cancel = AtomicBool::new(false);    let on_progress = |_: Progress| {};    let cursor = store.cursor("mail").unwrap();    let mut ctx = RunContext::new(&sink, store, SourceKey::Mail, &cancel, &on_progress);    importer.run(cursor.as_deref(), &mut ctx).expect("the run")}fn mailbox() -> Mailbox {    Arc::new(Mutex::new(vec![        (            1,            "\\Seen",            message("<root@example.org>", "Sun, 4 Oct 2026 10:00:00 +0000", "Lunch?", None, "Owner <owner@example.com>", "Lunch tomorrow?"),        ),        (            2,            "",            message(                "<r1@example.org>",                "Mon, 5 Oct 2026 09:30:00 +0000",                "Re: Lunch?",                Some("<root@example.org>"),                "Ada Example <ada@example.org>",                "Noon works.\r\n\r\nOn Sun, 4 Oct 2026 at 10:00, Owner <owner@example.com> wrote:\r\n> Lunch tomorrow?",            ),        ),        (            3,            "\\Seen \\Flagged",            message("<bill@shop.example>", "Tue, 6 Oct 2026 08:00:00 +0000", "Your receipt", None, "Shop <bills@shop.example>", "Total 12.00"),        ),    ]))}#[test]fn a_mailbox_lands_as_rows_the_cursor_follows_and_a_rerun_sends_nothing() {    let dir = tempfile::tempdir().unwrap();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    let (object, rows) = object();    let messages = mailbox();    let (port, lines) = imap(Arc::clone(&messages), Arc::new(AtomicBool::new(false)));    let mail = importer(dir.path(), port);    assert!(mail.probe().ready);    let cursor = run(&mail, &object, &store);    let parsed: Value = serde_json::from_str(&cursor).unwrap();    assert_eq!(        parsed,        json!({ "v": 1, "mailboxes": { "INBOX": {            "uidValidity": 9, "topUid": 3, "backfillBelow": 1,            "backfillYear": chrono::Datelike::year(&chrono::Utc::now()), "backfillCeiling": 4,            "history": 2, "historyDone": 3, "historyTotal": 3, "historyReached": parsed["mailboxes"]["INBOX"]["historyReached"].clone(),            "historyBytes": parsed["mailboxes"]["INBOX"]["historyBytes"].clone()        } } })    );    assert_eq!(store.cursor("mail").unwrap().as_deref(), Some(cursor.as_str()), "the cursor moved with the pages");    assert!(lines.lock().unwrap().iter().all(|line| !line.contains("app-pw")));    let sent = acts(&object);    // Threads before the people in them, people and threads before emails.    let tables: Vec<&str> = sent.iter().map(|a| a["args"]["table"].as_str().unwrap()).collect();    let first_email = tables.iter().position(|t| *t == "email").unwrap();    assert!(tables[..first_email].contains(&"email_thread"));    assert_eq!(tables.iter().filter(|t| **t == "email").count(), 3);    assert!(sent.iter().all(|a| a["act"] == "create"), "a first read only creates");    let thread_key = "imap:root@example.org";    let thread_id = derived_id("cotton_email_threads", &[DB, thread_key]);    let rows = rows.lock().unwrap().clone();    let thread = &rows[&("email_thread".to_string(), thread_id.clone())];    assert_eq!(        thread,        &json!({            "external_key": thread_key,            "subject": "Lunch?",            "first_at": "2026-10-04T10:00:00.000Z",            "last_at": "2026-10-05T09:30:00.000Z",            "email_count": 2        })    );    let reply_external = message_id_external_id(Some("<r1@example.org>")).unwrap();    let reply = &rows[&("email".to_string(), derived_id("cotton_emails", &[DB, &reply_external]))];    assert_eq!(reply["thread_id"], Value::from(thread_id.clone()));    assert_eq!(reply["body"], "Noon works.");    assert_eq!(reply["unread"], true);    assert_eq!(reply["starred"], false);    assert_eq!(reply["from_email"], "ada@example.org");    assert_eq!(reply["account"], "owner@example.com");    let receipt_external = message_id_external_id(Some("<bill@shop.example>")).unwrap();    let receipt = &rows[&("email".to_string(), derived_id("cotton_emails", &[DB, &receipt_external]))];    assert_eq!(receipt["starred"], true);    assert_eq!(receipt["unread"], false);    let ada = &rows[&(        "email_participant".to_string(),        derived_id("cotton_email_participants", &[&thread_id, "ada@example.org"]),    )];    assert_eq!(ada, &json!({ "thread_id": thread_id, "email": "ada@example.org", "display_name": "Ada Example", "role": "from" }));    // Nothing new: the second run reads and sends nothing.    let before = acts(&object).len();    let again = run(&mail, &object, &store);    assert_eq!(again, cursor);    assert_eq!(acts(&object).len(), before, "a re-run sends nothing");    // New mail in the same conversation: one email, the thread's fold moves.    messages.lock().unwrap().push((        4,        "",        message("<r2@example.org>", "Wed, 7 Oct 2026 12:00:00 +0000", "Re: Lunch?", Some("<root@example.org>"), "Owner <owner@example.com>", "See you."),    ));    let third = run(&mail, &object, &store);    let parsed: Value = serde_json::from_str(&third).unwrap();    assert_eq!(parsed["mailboxes"]["INBOX"]["topUid"], 4);    let new_acts = &acts(&object)[before..];    assert_eq!(new_acts.iter().filter(|a| a["args"]["table"] == "email").count(), 1);    let thread_update = new_acts        .iter()        .find(|a| a["args"]["table"] == "email_thread")        .expect("the thread is sent again");    assert_eq!(thread_update["act"], "update");    assert_eq!(thread_update["args"]["data"]["email_count"], 3);    assert_eq!(thread_update["args"]["data"]["last_at"], "2026-10-07T12:00:00.000Z");}#[test]fn a_thread_the_object_already_held_only_has_its_latest_date_moved() {    let dir = tempfile::tempdir().unwrap();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    let (object, rows) = object();    // The old store's row for the conversation, brought over at cutover.    let thread_id = derived_id("cotton_email_threads", &[DB, "imap:root@example.org"]);    rows.lock().unwrap().insert(        ("email_thread".to_string(), thread_id.clone()),        json!({ "external_key": "imap:root@example.org", "subject": "Lunch?", "first_at": "2020-01-01T00:00:00.000Z", "last_at": "2026-10-04T10:00:00.000Z", "email_count": 37 }),    );    let messages = mailbox();    let (port, _) = imap(Arc::clone(&messages), Arc::new(AtomicBool::new(false)));    let mail = importer(dir.path(), port);    run(&mail, &object, &store);    {        let rows = rows.lock().unwrap();        let thread = &rows[&("email_thread".to_string(), thread_id.clone())];        assert_eq!(thread["email_count"], 37, "the backfill never rewrites an old thread's count");    }    messages.lock().unwrap().push((        4,        "",        message("<r2@example.org>", "Wed, 7 Oct 2026 12:00:00 +0000", "Re: Lunch?", Some("<root@example.org>"), "Owner <owner@example.com>", "See you."),    ));    run(&mail, &object, &store);    let rows = rows.lock().unwrap();    let thread = &rows[&("email_thread".to_string(), thread_id)];    assert_eq!(thread["email_count"], 37);    assert_eq!(thread["first_at"], "2020-01-01T00:00:00.000Z");    assert_eq!(thread["last_at"], "2026-10-07T12:00:00.000Z", "new mail moves its latest date");}// RULE (coordinator, 22 Nov 2026: Gmail answered the owner's Mac "BYE System Error" mid-FETCH and the run// failed): a dropped connection is not the end of a run. It goes on from the last page the object took over a// fresh connection with smaller batches; only when the server keeps dropping it does the run fail, in words a// person reads, and nothing is sent twice or lost.#[test]fn a_connection_the_server_drops_goes_on_over_a_fresh_one() {    let dir = tempfile::tempdir().unwrap();    let (object, _rows) = object();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    let byes = Arc::new(AtomicUsize::new(1));    let (port, _lines) = imap_dropping(mailbox(), Arc::new(AtomicBool::new(false)), Arc::clone(&byes));    let mail = importer(dir.path(), port);    run(&mail, &object, &store);    assert_eq!(byes.load(Ordering::SeqCst), 0, "the server dropped one connection");    let mut landed: Vec<String> = acts(&object)        .iter()        .filter(|act| act["args"]["table"] == "email" && act["act"] == "create")        .map(|act| act["args"]["id"].as_str().unwrap_or_default().to_string())        .collect();    let all = landed.len();    landed.sort();    landed.dedup();    assert_eq!(landed.len(), 3, "every message landed once over the fresh connection: {landed:?}");    assert_eq!(all, 3, "nothing was sent twice");    // A server that drops every connection: the run fails after its fresh tries, in plain words.    let dir = tempfile::tempdir().unwrap();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    let (port, _lines) = imap_dropping(mailbox(), Arc::new(AtomicBool::new(false)), Arc::new(AtomicUsize::new(usize::MAX)));    let mail = importer(dir.path(), port);    let client = ObjectClient::new(object.url.clone(), Some("device-token".to_string())).unwrap();    let sink = ObjectSink::new(&client, DB);    let cancel = AtomicBool::new(false);    let on_progress = |_: Progress| {};    let mut ctx = RunContext::new(&sink, &store, SourceKey::Mail, &cancel, &on_progress);    let error = mail.run(None, &mut ctx).unwrap_err().to_string();    assert!(error.starts_with("The mail server kept closing the connection"), "{error}");}// RULE (owner, 22 Nov 2026, MAC-PANEL.md: add mail is a guided step with a test and what was found): the test// signs in, looks read only at the mailbox a run would read, says how many and the oldest, and keeps nothing; a// refused password or an unknown server is said in the panel's words.#[test]fn the_mail_test_says_what_it_found_and_keeps_nothing() {    let dir = tempfile::tempdir().unwrap();    let (port, lines) = imap(mailbox(), Arc::new(AtomicBool::new(false)));    let mail = MailImporter::new(dir.path());    let found = mail        .command("test", &json!({ "address": "owner@example.com", "password": "app-pw", "imapHost": format!("127.0.0.1:{port}"), "imapTls": false }))        .unwrap();    assert_eq!(found["tested"], true, "{found}");    assert_eq!(found["mailbox"], "INBOX");    assert_eq!(found["count"], 3);    assert_eq!(found["oldest"], 1_299_231_000_000_i64, "4 March 2011, 09:30 UTC");    assert!(lines.lock().unwrap().iter().all(|l| !l.starts_with("SELECT") && !l.contains("STORE")), "read only");    // Nothing kept: the source still asks for an account.    assert_eq!(serde_json::to_value(mail.probe()).unwrap()["need"]["kind"], "credentials");    let unknown = mail.command("test", &json!({ "address": "me@unknown-provider.example", "password": "pw" })).unwrap();    assert_eq!(unknown["tested"], false);    assert_eq!(unknown["askServer"], true);    assert!(unknown["said"].as_str().unwrap().contains("mail server"));    let empty = mail.command("test", &json!({ "address": "", "password": "" })).unwrap();    assert_eq!(empty["tested"], false);}#[test]fn without_credentials_mail_asks_for_them() {    let dir = tempfile::tempdir().unwrap();    let mail = MailImporter::new(dir.path());    let probe = mail.probe();    assert!(!probe.ready);    assert_eq!(serde_json::to_value(&probe).unwrap()["need"]["kind"], "credentials");}#[test]fn idle_wakes_the_source_when_mail_lands_and_stops_with_the_app() {    let dir = tempfile::tempdir().unwrap();    let news = Arc::new(AtomicBool::new(false));    let (port, lines) = imap(mailbox(), Arc::clone(&news));    let mail = importer(dir.path(), port);    let woken = Arc::new(AtomicUsize::new(0));    let stop = Arc::new(AtomicBool::new(false));    let counter = Arc::clone(&woken);    let stopping = Arc::clone(&stop);    mail.watch(        Arc::new(move || {            counter.fetch_add(1, Ordering::SeqCst);        }),        Arc::new(move || stopping.load(Ordering::SeqCst)),    );    let deadline = Instant::now() + Duration::from_secs(10);    while !lines.lock().unwrap().iter().any(|line| line == "IDLE") {        assert!(Instant::now() < deadline, "the watcher entered IDLE");        std::thread::sleep(Duration::from_millis(20));    }    news.store(true, Ordering::SeqCst);    while woken.load(Ordering::SeqCst) == 0 {        assert!(Instant::now() < deadline, "new mail woke the source");        std::thread::sleep(Duration::from_millis(20));    }    stop.store(true, Ordering::SeqCst);    while !lines.lock().unwrap().iter().any(|line| line == "LOGOUT") {        assert!(Instant::now() < deadline, "the watcher signed out when the app stopped");        std::thread::sleep(Duration::from_millis(20));    }}/// RULE (OWN-MAIL.md "Beside the Gmail mail"): a message that came to the person's own domain first is the same row/// when Gmail's copy is read; the Mac sends only its state, and the conversation it arrived in keeps it.#[test]fn mail_that_came_to_the_own_domain_first_keeps_its_conversation() {    let dir = tempfile::tempdir().unwrap();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    let reply_id = derived_id("cotton_emails", &[DB, &message_id_external_id(Some("<r1@example.org>")).unwrap()]);    let (object, rows) = object_with_arrived(vec![reply_id.clone()]);    rows.lock().unwrap().insert(        ("email".to_string(), reply_id.clone()),        json!({ "thread_id": "the-domain-thread", "body": "Noon works.", "account": "me@own.example", "unread": true, "direction": "in" }),    );    let messages = mailbox();    messages.lock().unwrap()[1].1 = "\\Seen";    let (port, _) = imap(Arc::clone(&messages), Arc::new(AtomicBool::new(false)));    let mail = importer(dir.path(), port);    run(&mail, &object, &store);    let sent = acts(&object);    let for_reply: Vec<&Value> = sent.iter().filter(|a| a["args"]["id"] == reply_id.as_str()).collect();    assert_eq!(for_reply.len(), 1, "one act for the arrived mail: {for_reply:?}");    assert_eq!(for_reply[0]["act"], "update");    assert!(for_reply[0]["args"]["data"].get("thread_id").is_none(), "its conversation is not moved");    let rows = rows.lock().unwrap();    let reply = &rows[&("email".to_string(), reply_id)];    assert_eq!((reply["thread_id"].as_str(), reply["account"].as_str(), reply["unread"].as_bool()), (Some("the-domain-thread"), Some("me@own.example"), Some(false)));    assert_eq!(sent.iter().filter(|a| a["args"]["table"] == "email" && a["act"] == "create").count(), 2, "the other two are the Mac's own");}/// RULE (owner, 24 Nov 2026: all mail history, newest first, keeping List-Unsubscribe, List-Unsubscribe-Post,/// List-Id, Precedence, Auto-Submitted and the Seen flag, re-read for mail already held; a nonsense Date falls back to/// the mailbox's own date): a mailbox walked before is walked once more from the top. Mail the database holds gets/// only what changed (read now, its List-Id, a true date for one "sent" in 2611, its conversation's date with it);/// mail it lacks lands whole with its headers; the walk's progress is in the cursor and the person's mail_history/// row; and a second run sends nothing.#[test]fn the_whole_mailbox_is_walked_again_with_its_headers_and_held_mail_takes_only_what_changed() {    use cotton_client::seal::HeldDataKeys;    use cotton_core::seal::DataKey;    use cotton_mac::copy::Copy;    use cotton_mac::copy::SealDoor;    use support::object::{kit_sealed_table, kit_table, FakeObject};    let dir = tempfile::tempdir().unwrap();    let store = Store::open(&dir.path().join("importer.db")).unwrap();    // Sealed, as his mail is: the Mac's copy keeps every sealed table, so it knows what the database holds.    let tables = vec![kit_sealed_table("email"), kit_sealed_table("email_thread"), kit_sealed_table("email_participant"), kit_table("mail_history")];    let object = FakeObject::start(DB, "+919800000099", tables);    let keys = HeldDataKeys::new();    keys.hold(DB, &DataKey::from_bytes([7; 32]));    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, keys).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device-token".to_string())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    let seed = |table: &str, id: &str, data: Value| client.act(cotton_mac::object::Act::Create, table, id, &data).unwrap();    let held_external = message_id_external_id(Some("<old@lists.example>")).unwrap();    let held_id = derived_id("cotton_emails", &[DB, &held_external]);    let thread_id = derived_id("cotton_email_threads", &[DB, "imap:old@lists.example"]);    // Brought by an earlier import: unread, no headers, and the date its sender claimed.    seed("email_thread", &thread_id, json!({ "external_key": "imap:old@lists.example", "subject": "Weekly", "first_at": "2611-09-16T10:00:00.000Z", "last_at": "2611-09-16T10:00:00.000Z", "email_count": 1 }));    seed("email", &held_id, json!({ "thread_id": thread_id, "external_id": held_external, "subject": "Weekly", "from_email": "news@lists.example", "sent_at": "2611-09-16T10:00:00.000Z", "body": "This week", "unread": true, "starred": false }));    let weekly = "From: News <news@lists.example>\r\nTo: Owner <owner@example.com>\r\nSubject: Weekly\r\nDate: Mon, 16 Sep 2611 10:00:00 +0000\r\nMessage-ID: <old@lists.example>\r\nList-Id: Weekly <weekly.lists.example>\r\nPrecedence: list\r\nContent-Type: text/plain\r\n\r\nThis week\r\n".to_string();    let offer = "From: Shop <offers@shop.example>\r\nTo: Owner <owner@example.com>\r\nSubject: Sale\r\nDate: Tue, 6 Oct 2026 08:00:00 +0000\r\nMessage-ID: <sale@shop.example>\r\nList-Unsubscribe: <https://shop.example/u>,\r\n <mailto:u@shop.example>\r\nList-Unsubscribe-Post: List-Unsubscribe=One-Click\r\nContent-Type: text/plain\r\n\r\nHalf off\r\n".to_string();    // Held already, exactly as the mailbox has it: nothing goes for it.    let quiet_external = message_id_external_id(Some("<quiet@example.org>")).unwrap();    let quiet_id = derived_id("cotton_emails", &[DB, &quiet_external]);    seed("email", &quiet_id, json!({ "thread_id": thread_id, "external_id": quiet_external, "subject": "Hello", "from_email": "ada@example.org", "sent_at": "2026-10-04T10:00:00.000Z", "body": "Hi", "unread": false, "starred": false }));    let quiet = message("<quiet@example.org>", "Sun, 4 Oct 2026 10:00:00 +0000", "Hello", None, "Ada <ada@example.org>", "Hi");    let messages: Mailbox = Arc::new(Mutex::new(vec![(1, "\\Seen", weekly), (2, "", offer), (3, "\\Seen", quiet)]));    let (port, _) = imap(Arc::clone(&messages), Arc::new(AtomicBool::new(false)));    let mail = importer(dir.path(), port);    // A cursor that walked the mailbox before the headers were kept: its backfill says it is finished.    store        .advance("mail", Some(&json!({ "v": 1, "mailboxes": { "INBOX": { "uidValidity": 9, "topUid": 3, "backfillBelow": 1, "backfillYear": 2011, "backfillCeiling": 2 } } }).to_string()), 0, "2026-11-24T00:00:00Z")        .unwrap();    let seeded = object.server.requests().len();    let walk = |label: &str| {        let sink = ObjectSink::new(&client, DB).with_copy(&copy);        let cancel = AtomicBool::new(false);        let on_progress = |_: Progress| {};        let cursor = store.cursor("mail").unwrap();        let mut ctx = RunContext::new(&sink, &store, SourceKey::Mail, &cancel, &on_progress);        let text = mail.run(cursor.as_deref(), &mut ctx).unwrap_or_else(|e| panic!("{label}: {e}"));        store.advance("mail", Some(&text), 0, "2026-11-24T00:00:01Z").unwrap();        text    };    let cursor: Value = serde_json::from_str(&walk("first")).unwrap();    let at = &cursor["mailboxes"]["INBOX"];    assert_eq!((at["history"].as_u64(), at["historyDone"].as_u64(), at["historyTotal"].as_u64(), at["backfillBelow"].as_u64()), (Some(2), Some(3), Some(3), Some(1)), "{at}");    // Read as a device reads them: opened from the sealed rows the object holds.    copy.refresh(&client).unwrap();    let row = |table: &str, id: &str| Value::Object(copy.row(table, id).unwrap().unwrap_or_else(|| panic!("{table} {id}")));    let held = row("email", &held_id);    assert_eq!(held["unread"], false, "read now, as the mailbox says");    assert_eq!(held["list_id"], "Weekly <weekly.lists.example>");    assert_eq!(held["precedence"], "list");    assert_eq!(held["sent_at"], "2011-03-04T09:30:00.000Z", "a date no mail carries gives way to the mailbox's");    assert_eq!(held["body"], "This week", "what it held stays");    assert_eq!(row("email_thread", &thread_id)["last_at"], "2011-03-04T09:30:00.000Z");    let names = |r: &support::Request, id: &str| String::from_utf8_lossy(&r.body).contains(id);    assert!(        !object.server.requests()[seeded..].iter().any(|r| (r.path == "/v1/act" || r.path.starts_with("/v1/import")) && names(r, &quiet_id)),        "held mail that did not move is not written"    );    let sale_id = derived_id("cotton_emails", &[DB, &message_id_external_id(Some("<sale@shop.example>")).unwrap()]);    let sale = row("email", &sale_id);    assert_eq!(sale["list_unsubscribe"], "<https://shop.example/u>, <mailto:u@shop.example>");    assert_eq!(sale["list_unsubscribe_post"], "List-Unsubscribe=One-Click");    assert!(sale["list_id"].is_null() && sale["auto_submitted"].is_null());    let history = object.state.lock().unwrap().live("mail_history").into_iter().map(|(_, held)| Value::Object(held.data)).next().unwrap();    assert_eq!((history["state"].clone(), history["done"].clone(), history["total"].clone()), (json!("done"), json!(3), json!(3)));    assert_eq!(at["historyReached"], "2011-03-04", "the oldest day walked: the held mail's true date");    // Nothing moved: a second run sends no mail at all.    let writes = || object.server.requests().iter().filter(|r| r.path == "/v1/act" && String::from_utf8_lossy(&r.body).contains("\"email")).count();    let before = writes();    walk("second");    let after = writes();    assert_eq!(after, before, "a walk over mail that did not move sends nothing");}/// RULE (MAIL.md "All mail on the phone": the designed page and attachments are fetched when he opens a mail; Mac 9)./// A mail's whole message lands as sealed files on its sealed row: the page in `media` (named page.html, its inline/// picture inside it), the attachment's file beside its name in `attachments`, each with the key that opens it. The/// object never sees the page's words. Landing it again sends nothing more.#[test]fn a_mails_page_and_attachment_land_sealed_on_its_row() {    use cotton_client::seal::HeldDataKeys;    use cotton_core::seal::DataKey;    use cotton_mac::copy::{Copy, SealDoor};    use support::object::{kit_sealed_table, FakeObject};    let dir = tempfile::tempdir().unwrap();    let object = FakeObject::start(DB, "+919800000099", vec![kit_sealed_table("email"), kit_sealed_table("email_thread")]);    let keys = HeldDataKeys::new();    keys.hold(DB, &DataKey::from_bytes([7; 32]));    let copy = Arc::new(Copy::open(&dir.path().join("copy.db"), DB, keys).unwrap());    let client = ObjectClient::new(object.server.url.clone(), Some("device-token".to_string())).unwrap().sealing_with(SealDoor::over(Arc::clone(&copy)));    let external = message_id_external_id(Some("<s1@shop.invented>")).unwrap();    let id = derived_id("cotton_emails", &[DB, &external]);    let thread = derived_id("cotton_email_threads", &[DB, "imap:s1@shop.invented"]);    client.act(cotton_mac::object::Act::Create, "email_thread", &thread, &json!({ "external_key": "imap:s1@shop.invented", "subject": "Sale", "email_count": 1 })).unwrap();    client        .act(cotton_mac::object::Act::Create, "email", &id, &json!({ "thread_id": thread, "external_id": external, "subject": "Sale", "from_email": "deals@shop.invented",             "sent_at": "2026-10-06T08:00:00.000Z", "body": "Sale today", "attachments": [{ "name": "menu.pdf", "mime": "application/pdf", "size": 9 }] }))        .unwrap();    copy.refresh(&client).unwrap();    let raw = "From: Shop <deals@shop.invented>\r\nTo: owner@mail.invented\r\nSubject: Sale\r\nMessage-ID: <s1@shop.invented>\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"M\"\r\n\r\n--M\r\nContent-Type: multipart/alternative; boundary=\"A\"\r\n\r\n--A\r\nContent-Type: text/plain\r\n\r\nSale today\r\n--A\r\nContent-Type: text/html\r\n\r\n<html><body><h1>Quokka Sale</h1></body></html>\r\n--A--\r\n--M\r\nContent-Type: application/pdf; name=\"menu.pdf\"\r\nContent-Disposition: attachment; filename=\"menu.pdf\"\r\nContent-Transfer-Encoding: base64\r\n\r\nJVBERi0xLjQK\r\n--M--\r\n";    let sink = ObjectSink::new(&client, DB).with_copy(&copy);    let kept = cotton_mac::mail::land_page(&sink, &copy, &external, raw.as_bytes()).unwrap();    assert_eq!(kept, json!({ "page": true, "files": 1 }));    copy.refresh(&client).unwrap();    let row = copy.row("email", &id).unwrap().unwrap();    let list = |key: &str| -> Vec<Value> {        match &row[key] {            Value::String(text) => serde_json::from_str(text).unwrap(),            other => other.as_array().cloned().unwrap_or_default(),        }    };    let media = list("media");    assert_eq!(media.len(), 1);    assert_eq!((media[0]["name"].as_str(), media[0]["contentType"].as_str()), (Some("page.html"), Some("text/html")));    assert!(media[0]["key"].as_str().unwrap().starts_with(&format!("{DB}/sealed/")) && media[0]["fileKey"].as_str().is_some_and(|k| !k.is_empty()));    let attachments = list("attachments");    assert_eq!(attachments[0]["name"], "menu.pdf");    assert!(attachments[0]["key"].as_str().unwrap().starts_with(&format!("{DB}/sealed/")) && attachments[0]["fileKey"].as_str().is_some());    let stored = object.state.lock().unwrap().media.len();    assert_eq!(stored, 2, "the page and the file");    assert!(!object.everything().contains("Quokka"), "the page lands sealed");    // Asked again: nothing more goes up.    assert_eq!(cotton_mac::mail::land_page(&sink, &copy, &external, raw.as_bytes()).unwrap(), json!({ "page": true, "files": 0 }));    assert_eq!(object.state.lock().unwrap().media.len(), 2);}/// SYNC GAP (25 Nov 2026), a sealed object and the Mac's copy, Gmail's way: what one run of the reader over `mail`/// gives, with the cursor it leaves kept.struct Sealed {    dir: tempfile::TempDir,    store: Store,    object: support::object::FakeObject,    keys: std::sync::Arc<cotton_client::seal::HeldDataKeys>,}impl Sealed {    fn new() -> Sealed {        use support::object::{kit_sealed_table, kit_table, FakeObject};        let dir = tempfile::tempdir().unwrap();        let store = Store::open(&dir.path().join("importer.db")).unwrap();        let tables = vec![kit_sealed_table("email"), kit_sealed_table("email_thread"), kit_sealed_table("email_participant"), kit_table("mail_history")];        let object = FakeObject::start(DB, "+919800000099", tables);        let keys = cotton_client::seal::HeldDataKeys::new();        keys.hold(DB, &cotton_core::seal::DataKey::from_bytes([7; 32]));        // New mail from UID 1: the walk of the whole mailbox is done.        let cursor = json!({ "v": 1, "mailboxes": { "[Gmail]/All Mail": { "uidValidity": 9, "topUid": 0, "backfillBelow": 1, "history": 2, "historyDone": 0 } } });        store.advance("mail", Some(&cursor.to_string()), 0, "2026-11-25T00:00:00Z").unwrap();        Sealed { dir, store, object, keys }    }    /// A copy of the database as a launch opens it (`name`: its file), with the client sealing through it.    fn copy(&self, name: &str) -> (Arc<cotton_mac::copy::Copy>, ObjectClient) {        let copy = Arc::new(cotton_mac::copy::Copy::open(&self.dir.path().join(name), DB, self.keys.clone()).unwrap());        let client = ObjectClient::new(self.object.server.url.clone(), Some("device-token".to_string())).unwrap().sealing_with(cotton_mac::copy::SealDoor::over(Arc::clone(&copy)));        (copy, client)    }    fn run(&self, mail: &MailImporter, copy: &Arc<cotton_mac::copy::Copy>, client: &ObjectClient) -> Result<String, String> {        let sink = ObjectSink::new(client, DB).with_copy(copy);        let cancel = AtomicBool::new(false);        let on_progress = |_: Progress| {};        let cursor = self.store.cursor("mail").unwrap();        let mut ctx = RunContext::new(&sink, &self.store, SourceKey::Mail, &cancel, &on_progress);        let text = mail.run(cursor.as_deref(), &mut ctx).map_err(|e| e.to_string())?;        self.store.advance("mail", Some(&text), 0, "2026-11-25T00:00:01Z").unwrap();        Ok(text)    }    fn emails(&self) -> usize {        self.object.state.lock().unwrap().live("email").len()    }    fn tally(&self) -> cotton_mac::mail::tally::Tally {        cotton_mac::mail::tally::Tally::open(&self.dir.path().join("mail.db")).unwrap()    }}fn email_id(message_id: &str) -> String {    derived_id("cotton_emails", &[DB, &message_id_external_id(Some(message_id)).unwrap()])}/// RULE (SYNC GAP, 25 Nov 2026): a mail whose push the object did not take is not counted as sent. The email of/// 19:30 was counted, its push met the object's 500 ("the business did not answer"), and every later read took it/// for sent: the database never got it. Now the count is undone with the push, and the next read sends it whole.#[test]fn a_mail_whose_push_the_busy_object_did_not_take_goes_again_on_the_next_read() {    let at = Sealed::new();    let lunch = message("<lunch@example.org>", "Wed, 25 Nov 2026 14:00:00 +0000", "Lunch?", None, "Ada <ada@example.org>", "Noon?");    let (port, _) = imap_gmail(Arc::new(Mutex::new(vec![(1, "", lunch)])));    let mail = importer(at.dir.path(), port);    let (copy, client) = at.copy("copy.db");    at.object.state.lock().unwrap().busy_writes = Some(("email".into(), 1));    let failed = at.run(&mail, &copy, &client).expect_err("the object did not answer");    assert!(failed.contains("500"), "{failed}");    assert_eq!(at.emails(), 0);    assert!(!at.tally().knows(&email_id("<lunch@example.org>")).unwrap(), "a push that did not land is not counted");    at.run(&mail, &copy, &client).expect("the object answers again");    assert_eq!(at.emails(), 1, "the mail lands on the next read");    copy.refresh(&client).unwrap();    assert_eq!(copy.row("email", &email_id("<lunch@example.org>")).unwrap().unwrap()["body"].as_str().map(str::trim), Some("Noon?"));    assert!(at.tally().knows(&email_id("<lunch@example.org>")).unwrap());}/// RULE (SYNC GAP, 25 Nov 2026): a mail this Mac counted that the database holds no row of is read again and/// created: at launch the Mac finds it in the mailbox by its Gmail id, the object answers its refresh 404, and it/// is fetched whole and sent. A mail the database holds is not written; a second run writes nothing.#[test]fn a_launch_brings_back_the_mail_this_mac_counted_that_the_database_never_got() {    let at = Sealed::new();    let lunch = message("<lunch@example.org>", "Wed, 25 Nov 2026 14:00:00 +0000", "Lunch?", None, "Ada <ada@example.org>", "Noon?");    let bill = message("<bill@shop.example>", "Wed, 25 Nov 2026 14:30:00 +0000", "Receipt", None, "Shop <bills@shop.example>", "Total 12.00");    let (port, _) = imap_gmail(Arc::new(Mutex::new(vec![(1, "\\Seen", lunch), (2, "", bill)])));    let (copy, client) = at.copy("copy.db");    at.run(&importer(at.dir.path(), port), &copy, &client).unwrap();    assert_eq!(at.emails(), 2);    // As the email of 19:30 stood: counted by this Mac, never at the object (so in no copy of the database).    let lost = email_id("<bill@shop.example>");    at.object.state.lock().unwrap().rows.remove(&("email".to_string(), lost.clone()));    assert!(at.tally().knows(&lost).unwrap());    // The next launch: a fresh reader and a copy read from the object.    let mail = importer(at.dir.path(), port);    let (copy, client) = at.copy("relaunch.db");    let before = at.object.server.requests().len();    at.run(&mail, &copy, &client).unwrap();    assert_eq!(at.emails(), 2, "the lost mail is back");    copy.refresh(&client).unwrap();    assert_eq!(copy.row("email", &lost).unwrap().unwrap()["body"].as_str().map(str::trim), Some("Total 12.00"));    let wrote = |id: &str, from: usize| at.object.server.requests()[from..].iter().filter(|r| r.path == "/v1/act" && String::from_utf8_lossy(&r.body).contains(id)).count();    assert_eq!(wrote(&email_id("<lunch@example.org>"), before), 0, "the mail the database holds is not written");    let quiet = at.object.server.requests().len();    at.run(&mail, &copy, &client).unwrap();    assert_eq!(wrote("\"email", quiet), 0, "the next run of the same launch writes no mail");}