Cotton code
413 lines · 23.6 KB · RustRaw
//! Books on this phone: what this device keeps of each book's file, the pin//! that keeps the budget off it, Remove download, and how a book's record and//! its lists say so.use serde_json::json;use super::*;use crate::shell::client::phone_tests::attached;fn key_of_book(name: char) -> String {    format!("{}/books/{}.epub", crate::fixture::WORKSPACE, name.to_string().repeat(64))}/// A book's bytes on this phone: the file in the media store and its ledger/// row, `synced` or still waiting to go up.fn on_this_phone(client: &ClientController, key: &str, state: &str) -> std::path::PathBuf {    let path = client.layout().client_media_dir().join(crate::fixture::WORKSPACE).join(key.rsplit('/').next().expect("a name"));    std::fs::create_dir_all(path.parent().expect("a folder")).expect("the media folder");    std::fs::write(&path, b"invented").expect("the book's bytes");    client        .with_writer(|replica| {            cotton_store::media_ledger::enqueue_media(                replica.driver,                &cotton_store::media_ledger::MediaEnqueueInput {                    key: key.to_string(),                    workspace_id: replica.workspace_id.to_string(),                    sha256: "b".repeat(64),                    content_type: "application/epub+zip".to_string(),                    size_bytes: 8,                    local_path: Some(path.to_string_lossy().to_string()),                    state: Some(state.to_string()),                    after: None,                    after_row_id: None,                    tier: None,                    captured_here: false,                    now: "2026-11-01T10:00:00.000Z".to_string(),                },            )            .map(|_| ())            .map_err(|error| error.to_string())        })        .expect("the ledger row");    path}fn ledger(client: &ClientController, key: &str) -> cotton_store::media_ledger::MediaRow {    client        .with_file(|file| cotton_store::media_ledger::media_by_key(file.driver, key).map_err(|error| error.to_string()))        .expect("a read")        .expect("the ledger row")}/// A book as the import writes one, with its file named when given.fn book(client: &ClientController, title: &str, file: Option<&str>) -> String {    let made = crate::phone::records::call(client, "records.create", &json!({"table": "book", "data": {"title": title}})).expect("a book");    let id = ["/record/id", "/id", "/after/id", "/change/after/id"]        .iter()        .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str))        .unwrap_or_else(|| panic!("the book's id: {made}"))        .to_string();    if let Some(file) = file {        client            .with_writer(|replica| {                replica.driver.exec(&format!("UPDATE cotton_book SET file = '{file}' WHERE id = '{id}'")).map_err(|error| error.to_string())            })            .expect("the file");    }    id}fn on_phone(client: &ClientController, id: &str) -> Value {    let record = crate::phone::records::call(client, "records.get", &json!({"table": "book", "id": id})).expect("the book");    record["data"][ON_PHONE].clone()}fn listed(client: &ClientController, filter: Value) -> Vec<String> {    let answer = crate::phone::records::call(client, "records.list", &json!({"table": "book", "where": filter})).expect("the books");    let mut titles: Vec<String> = answer["records"].as_array().expect("records").iter().filter_map(|row| row["data"]["title"].as_str().map(str::to_string)).collect();    titles.sort();    titles}// RULE: what this device keeps of a book reads back as written and a null clears it; `kept` needs the bytes on this phone and pins their ledger row, and any other state unpins it.#[test]fn a_books_keep_round_trips_and_pins_its_file() {    let (_dir, client) = attached();    let key = key_of_book('a');    let kept = |key: &str| read(&client, &json!({"key": key})).expect("read");    assert_eq!(kept(&key), json!({"key": key, "state": null}));    write(&client, &json!({"key": key, "state": "keeping"})).expect("keeping");    assert_eq!(kept(&key), json!({"key": key, "state": "keeping"}));    assert_eq!(write(&client, &json!({"key": key, "state": "kept"})).expect_err("no bytes yet").code, "not_here");    assert_eq!(kept(&key), json!({"key": key, "state": "keeping"}), "a refused write leaves the keep as it was");    on_this_phone(&client, &key, "synced");    assert!(!ledger(&client, &key).pinned);    write(&client, &json!({"key": key, "state": "kept"})).expect("kept");    assert_eq!(kept(&key), json!({"key": key, "state": "kept"}));    assert!(ledger(&client, &key).pinned, "the budget never takes a kept book");    write(&client, &json!({"key": key, "state": null})).expect("cleared");    assert_eq!(kept(&key), json!({"key": key, "state": null}));    assert!(!ledger(&client, &key).pinned);    assert_eq!(write(&client, &json!({"key": key, "state": "lost"})).expect_err("no such state").code, "bad_request");    assert_eq!(write(&client, &json!({"key": key})).expect_err("names its state").code, "bad_request");    assert_eq!(write(&client, &json!({"key": key, "state": null, "file": "x"})).expect_err("unknown field").code, "bad_request");    assert_eq!(read(&client, &json!({"key": " "})).expect_err("no key").code, "bad_request");}// RULE: a book downloaded in the background from its signed address is kept by naming the download: its bytes move into the store, must be the ones its key names, and land synced and pinned; anything else is refused and nothing is kept.#[test]fn a_background_download_is_adopted_as_the_kept_book() {    let (dir, client) = attached();    let bytes = b"synthetic epub bytes";    let download = |name: &str, body: &[u8]| {        let path = dir.path().join(name);        std::fs::write(&path, body).expect("the download");        path    };    let probe = download("probe", bytes);    let (sha, _) = cotton_client::media::store::sha256_file(&probe).expect("a digest");    let key = format!("{}/books/{sha}.epub", crate::fixture::WORKSPACE);    let kept = |key: &str| read(&client, &json!({"key": key})).expect("read");    let stored = |key: &str| {        client.with_file(|file| Ok::<_, String>(super::super::media::local_path_of(file.driver, key))).expect("a read")    };    let wrong = download("wrong", b"another book");    let refused = write(&client, &json!({"key": key, "state": "kept", "from": wrong.to_string_lossy()})).expect_err("not this book");    assert_eq!(refused.code, "not_this_book");    assert_eq!(kept(&key), json!({"key": key, "state": null}));    assert!(stored(&key).is_none(), "the wrong bytes never reach the store");    let came = download("came", bytes);    assert_eq!(write(&client, &json!({"key": key, "state": "keeping", "from": came.to_string_lossy()})).expect_err("kept only").code, "bad_request");    write(&client, &json!({"key": key, "state": "kept", "from": came.to_string_lossy()})).expect("kept");    assert_eq!(kept(&key), json!({"key": key, "state": "kept"}));    assert!(!came.exists(), "the download moved into the store");    let row = ledger(&client, &key);    assert!(row.pinned && row.state == "synced", "kept, and already up: {row:?}");    assert_eq!(std::fs::read(stored(&key).expect("in the store")).expect("the bytes"), bytes);}// RULE: Remove download takes a kept book's file off this phone only once the bucket holds its bytes: the file goes, the keep and the pin go with it, and the ledger row stays to fetch it again.#[test]fn books_remove_takes_a_backed_up_file_off_this_phone() {    let (_dir, client) = attached();    let key = key_of_book('a');    let path = on_this_phone(&client, &key, "synced");    write(&client, &json!({"key": key, "state": "kept"})).expect("kept");    let answer = remove(&client, &json!({"key": key})).expect("removed");    assert_eq!(answer, json!({"key": key, "freed_bytes": 8}));    assert!(!path.exists());    assert_eq!(read(&client, &json!({"key": key})).expect("read")["state"], Value::Null);    let row = ledger(&client, &key);    assert_eq!((row.local_path, row.pinned), (None, false));    let waiting = key_of_book('c');    let path = on_this_phone(&client, &waiting, "pending");    write(&client, &json!({"key": waiting, "state": "kept"})).expect("kept");    assert_eq!(remove(&client, &json!({"key": waiting})).expect_err("not up yet").code, "not_backed_up");    assert!(path.exists(), "this phone may hold the last copy");    assert_eq!(read(&client, &json!({"key": waiting})).expect("read")["state"], json!("kept"));    assert!(ledger(&client, &waiting).pinned);}// RULE: only a book whose file is named answers on_phone: absent until this device keeps it, then keeping or kept; a list's on_phone reads as the files this device keeps.#[test]fn on_phone_is_answered_and_narrowed_from_what_this_device_keeps() {    let (_dir, client) = attached();    let mut answer = json!({"records": [        {"id": "1", "data": {"title": "Kept", "file": key_of_book('a')}},        {"id": "2", "data": {"title": "Not kept", "file": key_of_book('b')}},        {"id": "3", "data": {"title": "No file", "file": "", "on_phone": "kept"}},    ]});    write(&client, &json!({"key": key_of_book('a'), "state": "keeping"})).expect("keeping");    answer_on_phone(&client, &mut answer).expect("answered");    let said: Vec<Value> = answer["records"].as_array().unwrap().iter().map(|row| row["data"][ON_PHONE].clone()).collect();    assert_eq!(said, vec![json!("keeping"), json!("absent"), Value::Null]);    let narrowed = |on_phone: Value| -> Result<Value, MethodError> {        let mut args = json!({"table": "book", "where": {"on_phone": on_phone}}).as_object().unwrap().clone();        narrow_where(&client, &mut args)?;        Ok(args["where"].clone())    };    assert_eq!(narrowed(json!("keeping")).unwrap(), json!({"file": [key_of_book('a')]}));    assert_eq!(narrowed(json!("kept")).unwrap(), json!({"file": [NOTHING_KEPT]}), "nothing kept matches nothing");    assert_eq!(narrowed(json!("absent")).unwrap(), json!({"file": {"not": [key_of_book('a')]}}));    assert_eq!(narrowed(json!("lost")).unwrap_err().code, "bad_request");    write(&client, &json!({"key": key_of_book('a'), "state": null})).expect("cleared");    assert_eq!(narrowed(json!("absent")).unwrap(), json!({"file": {"present": true}}), "every book with a file");    let mut episodes = json!({"table": "episode", "where": {"on_phone": "kept"}}).as_object().unwrap().clone();    narrow_where(&client, &mut episodes).expect("another table passes");    assert_eq!(episodes["where"], json!({"on_phone": "kept"}));}// RULE: a book's record says what this device keeps of its file, and Keep on phone and Remove download come only from a book in the state they are for. (Reads `book.json`'s `file` column.)#[test]fn a_books_record_and_flows_follow_what_this_device_keeps() {    let (_dir, client) = attached();    let key = key_of_book('a');    let id = book(&client, "Dune", Some(&key));    let bare = book(&client, "No file yet", None);    assert_eq!(on_phone(&client, &id), json!(ABSENT));    assert_eq!(on_phone(&client, &bare), Value::Null);    assert!(flow_origin(&client, "keepBook", "book", &id).is_ok());    assert!(flow_origin(&client, "removeBookDownload", "book", &id).is_err(), "nothing kept to remove");    assert!(flow_origin(&client, "keepBook", "book", &bare).is_err(), "no file to keep");    assert!(flow_origin(&client, "keepBook", "film", &id).is_err(), "only a book's record");    on_this_phone(&client, &key, "synced");    write(&client, &json!({"key": key, "state": "kept"})).expect("kept");    assert_eq!(on_phone(&client, &id), json!(KEPT));    assert!(flow_origin(&client, "keepBook", "book", &id).is_err(), "kept already");    assert!(flow_origin(&client, "removeBookDownload", "book", &id).is_ok());    book(&client, "Other", Some(&key_of_book('b')));    assert_eq!(listed(&client, json!({"on_phone": "kept"})), vec!["Dune"]);    assert_eq!(listed(&client, json!({"on_phone": "absent"})), vec!["Other"]);}// RULE (Books app definition, 4 Nov 2026): On this phone's top line says how many books this device keeps, the size of their files here, and, on a phone never signed in, that it is not synced yet.#[test]fn on_this_phone_says_its_books_their_size_and_not_backed_up() {    let (_dir, client) = attached();    let tool: Value = serde_json::from_str(include_str!("../../../cotton-core/kits/personal/tools/books/manifest.json")).expect("the books tool");    client        .with_writer(|file| {            let sql = "INSERT OR REPLACE INTO cotton_tool_definitions (id, workspace_id, definition, created_at, updated_at) \                       VALUES ('books', ?, ?, '2026-11-04T09:00:00.000Z', '2026-11-04T09:00:00.000Z')";            file.driver                .run(sql, &[rusqlite::types::Value::Text(file.workspace_id.to_string()), rusqlite::types::Value::Text(tool.to_string())])                .map_err(|error| error.to_string())?;            crate::fixture::receipted(file.driver, sql);            Ok(())        })        .expect("the tool");    let head = |client: &ClientController| {        let answer = crate::phone::tool_views::read(client, &json!({"tool": "books", "today": "2026-11-04", "timezone": "UTC"})).expect("the views");        answer["views"].as_array().expect("views").iter().find(|view| view["id"] == "on_phone").expect("On this phone")["head"].clone()    };    assert_eq!(head(&client), json!("0\u{a0}books · 0\u{a0}B · not synced\u{a0}yet"));    let (one, two) = (key_of_book('a'), key_of_book('b'));    book(&client, "Synthetic Kept", Some(&one));    book(&client, "Synthetic Also Kept", Some(&two));    book(&client, "Synthetic Elsewhere", Some(&key_of_book('c')));    on_this_phone(&client, &one, "synced");    write(&client, &json!({"key": one, "state": "kept"})).expect("kept");    assert_eq!(head(&client), json!("1\u{a0}book · 8\u{a0}B · not synced\u{a0}yet"), "a book kept here, its file's size");    on_this_phone(&client, &two, "synced");    write(&client, &json!({"key": two, "state": "kept"})).expect("kept");    assert_eq!(head(&client), json!("2\u{a0}books · 16\u{a0}B · not synced\u{a0}yet"), "a book not kept here is not counted");}// ── Add a folder ───────────────────────────────────────────────────────────/// An invented EPUB whose package says `title` and carries its own cover.fn folder_epub(title: &str) -> Vec<u8> {    use std::io::Write;    let mut bytes = std::io::Cursor::new(Vec::new());    let mut zip = zip::ZipWriter::new(&mut bytes);    let deflated = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);    let opf = format!(r#"<package xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:title>{title}</dc:title><dc:language>en</dc:language></metadata><manifest><item id="c" href="inside.jpg" media-type="image/jpeg" properties="cover-image"/></manifest></package>"#);    let files: [(&str, &[u8]); 4] = [        ("mimetype", b"application/epub+zip"),        ("META-INF/container.xml", br#"<container><rootfiles><rootfile full-path="OPS/package.opf"/></rootfiles></container>"#),        ("OPS/package.opf", opf.as_bytes()),        ("OPS/inside.jpg", b"\xff\xd8\xff the cover inside"),    ];    for (name, body) in files {        zip.start_file(name, deflated).expect("an entry");        zip.write_all(body).expect("its bytes");    }    zip.finish().expect("the archive closed");    bytes.into_inner()}/// An invented Calibre `metadata.opf`.fn calibre_opf(title: &str, author: &str, isbn: &str) -> Vec<u8> {    format!(        r#"<?xml version='1.0' encoding='utf-8'?><package xmlns="http://www.idpf.org/2007/opf" unique-identifier="uuid_id" version="2.0">  <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">    <dc:identifier opf:scheme="uuid" id="uuid_id">invented-{isbn}</dc:identifier>    <dc:title>{title}</dc:title>    <dc:creator opf:file-as="{author}" opf:role="aut">{author}</dc:creator>    <dc:identifier opf:scheme="ISBN">{isbn}</dc:identifier>    <meta name="calibre:rating" content="8"/>  </metadata></package>"#    )    .into_bytes()}/// A picked tree staged as the shell stages one: each file under a name of/// its own, handed in with its path in the folder.fn staged(dir: &std::path::Path, tree: &[(&str, Vec<u8>)]) -> Value {    let stage = dir.join("staged");    std::fs::create_dir_all(&stage).expect("the staging folder");    let files: Vec<Value> = tree        .iter()        .enumerate()        .map(|(n, (name, bytes))| {            let ext = name.rsplit_once('.').map(|(_, ext)| ext).unwrap_or("bin");            let path = stage.join(format!("{n:04}-staged.{ext}"));            std::fs::write(&path, bytes).expect("a staged file");            json!({ "path": path.to_string_lossy(), "name": name })        })        .collect();    json!({ "files": files })}// RULE (7 Nov 2026): books.folder walks a picked tree — a Calibre book from its metadata.opf (title, author, rating) and cover.jpg first, its EPUB second; a bare PDF a book by its name; a file that is no book named in skipped — and lands each through capture.media's own writer (kept here, queued up), on a phone signed in to nothing; the same folder again is `already` for every book, and a folder with no book is refused in words.#[test]fn a_folder_of_books_comes_in_once_by_calibre_first() {    let (dir, client, _) = crate::shell::client::phone_tests::attached_on_a_clock_in("local");    let jpeg = |what: &str| [b"\xff\xd8\xff ".as_slice(), what.as_bytes()].concat();    let tree: Vec<(&str, Vec<u8>)> = vec![        ("Hollis Brand/A Lamp for Winter (7)/A Lamp for Winter - Hollis Brand.epub", folder_epub("lamp_winter_final")),        ("Hollis Brand/A Lamp for Winter (7)/metadata.opf", calibre_opf("A Lamp for Winter", "Hollis Brand", "9780000000019")),        ("Hollis Brand/A Lamp for Winter (7)/cover.jpg", jpeg("winter's cover")),        ("Hollis Brand/The Salt Ledger (8)/The Salt Ledger - Hollis Brand.epub", folder_epub("salt_ledger_v2")),        ("Hollis Brand/The Salt Ledger (8)/metadata.opf", calibre_opf("The Salt Ledger", "Hollis Brand", "9780000000026")),        ("Hollis Brand/The Salt Ledger (8)/cover.jpg", jpeg("ledger's cover")),        ("Odile Marsh/Paper Rivers (9)/Paper Rivers - Odile Marsh.epub", folder_epub("rivers")),        ("Odile Marsh/Paper Rivers (9)/metadata.opf", calibre_opf("Paper Rivers", "Odile Marsh", "9780000000033")),        ("Odile Marsh/Paper Rivers (9)/cover.jpg", jpeg("rivers' cover")),        ("Field Notes on Moss.pdf", b"%PDF-1.4 an invented pdf".to_vec()),        ("broken.epub", b"no zip at all".to_vec()),        ("metadata.db", b"calibre's own database".to_vec()),    ];    let request = staged(dir.path(), &tree);    let answer = call_on(&client, "books.folder", &request).expect("the folder");    let mut titles: Vec<(String, String)> = answer["books"].as_array().expect("books").iter()        .map(|book| (book["title"].as_str().unwrap_or_default().to_string(), book["outcome"].as_str().unwrap_or_default().to_string()))        .collect();    titles.sort();    assert_eq!(titles, [        ("A Lamp for Winter".to_string(), "added".to_string()),        ("Field Notes on Moss".to_string(), "added".to_string()),        ("Paper Rivers".to_string(), "added".to_string()),        ("The Salt Ledger".to_string(), "added".to_string()),    ], "{answer}");    assert_eq!(answer["skipped"], json!(["broken.epub"]), "{answer}");    let row = |title: &str| -> Value {        let book = answer["books"].as_array().unwrap().iter().find(|book| book["title"] == title).expect("the book");        crate::phone::records::call(&client, "records.get", &json!({"table": "book", "id": book["id"]})).expect("its row")["data"].clone()    };    let lamp = row("A Lamp for Winter");    assert_eq!((lamp["author"].as_str(), lamp["isbn"].as_str(), lamp["language"].as_str(), lamp["format"].as_str()),        (Some("Hollis Brand"), Some("9780000000019"), Some("en"), Some("epub")), "the OPF first, the file second: {lamp}");    assert_eq!(lamp["rating"].as_f64(), Some(4.0), "Calibre's rating is the owner's: {lamp}");    let cover = lamp["cover"].as_str().expect("the cover attached");    assert!(cover.contains("/photos/") && cover.ends_with(".jpg"), "{lamp}");    let file = lamp["file"].as_str().expect("its file");    assert_eq!(on_phone(&client, answer["books"].as_array().unwrap().iter().find(|b| b["title"] == "A Lamp for Winter").unwrap()["id"].as_str().unwrap()), json!(KEPT), "kept here as Add files keeps one");    assert!(ledger(&client, file).local_path.is_some(), "queued up for the object");    let moss = row("Field Notes on Moss");    assert_eq!((moss["format"].as_str(), moss["cover"].as_str()), (Some("pdf"), None), "a bare PDF is a book by its name: {moss}");    let again = call_on(&client, "books.folder", &request).expect("the folder again");    assert!(again["books"].as_array().unwrap().iter().all(|book| book["outcome"] == "already"), "{again}");    assert_eq!(again["books"].as_array().unwrap().len(), 4);    let ids = |answer: &Value| { let mut ids: Vec<String> = answer["books"].as_array().unwrap().iter().map(|b| b["id"].as_str().unwrap().to_string()).collect(); ids.sort(); ids };    assert_eq!(ids(&again), ids(&answer), "the same books, never second ones");    let nothing = staged(&dir.path().join("empty"), &[("notes.txt", b"words".to_vec()), ("half.epub", b"not a zip".to_vec())]);    let refused = call_on(&client, "books.folder", &nothing).expect_err("no book");    assert_eq!(refused.code, "refused");    assert!(refused.message.contains("no EPUB or PDF"), "{}", refused.message);}// RULE: books.folder takes only `files`, each { path, name }, a name once.#[test]fn a_folder_request_names_its_files() {    let (_dir, client) = attached();    for request in [json!([]), json!({"files": [], "more": 1}), json!({"files": [{"path": "/x"}]}), json!({"files": [{"path": "/x", "name": "a.pdf"}, {"path": "/y", "name": "a.pdf"}]})] {        assert_eq!(call_on(&client, "books.folder", &request).expect_err("refused").code, "bad_request", "{request}");    }}fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {    match method {        "books.folder" => folder(client, request),        other => panic!("{other}"),    }}// RULE (android parity, 17 Nov 2026): every book being read whose file this phone does not keep is due to be kept here, whichever phone set it reading; one kept, one not being read, or one with no file is not.#[test]fn a_book_being_read_is_due_to_be_kept_here() {    let (_dir, client) = attached();    let reading = key_of_book('r');    let kept = key_of_book('k');    // The status first (records.update writes the row whole), then the file as `book` writes it.    let shelved = |title: &str, status: &str, file: Option<&str>| {        let id = book(&client, title, None);        for at in ["finished", status] {            crate::phone::records::call(&client, "records.update", &json!({"table": "book", "id": id, "patch": {"status": at}})).expect("status");        }        if let Some(file) = file {            client.with_writer(|replica| replica.driver.exec(&format!("UPDATE cotton_book SET file = '{file}' WHERE id = '{id}'")).map_err(|error| error.to_string())).expect("the file");        }    };    shelved("Being read", "reading", Some(&reading));    shelved("Read and kept", "reading", Some(&kept));    on_this_phone(&client, &kept, "synced");    write(&client, &json!({"key": kept, "state": "kept"})).expect("kept");    shelved("Wanted", "want_to_read", Some(&key_of_book('w')));    shelved("No file", "reading", None);    assert_eq!(due(&client).expect("due"), json!({"keys": [reading]}));}