Cotton code
311 lines · 18.2 KB · RustRaw
//! The books kit's acts on a phone that never signed in: each writes the//! phone's own copy and queues for the object; an act only the object can run//! is refused by name.use serde_json::{json, Value};use super::*;use crate::shell::client::phone_tests::attached_on_a_clock_in;/// A phone that started its own database and has met no object.fn local_phone() -> (tempfile::TempDir, std::sync::Arc<ClientController>) {    let (dir, client, _) = attached_on_a_clock_in("local");    (dir, client)}fn book(client: &ClientController, data: Value) -> String {    let made = crate::phone::records::call(client, "records.create", &json!({"table": "book", "data": data})).expect("a book");    made.pointer("/record/id").and_then(Value::as_str).expect("the book's id").to_string()}fn data(client: &ClientController, id: &str) -> Value {    crate::phone::records::call(client, "records.get", &json!({"table": "book", "id": id})).expect("the book")["data"].clone()}fn act(client: &ClientController, request: Value) -> Result<Value, MethodError> {    crate::phone::object_acts::call_on(client, &request)}/// The writes this phone holds for the object, by table.fn queued(client: &ClientController, table: &str) -> i64 {    client        .with_file(|file| {            file.driver                .get(&format!("SELECT COUNT(*) AS n FROM _outbox WHERE tbl = '{table}'"), &[])                .map_err(|error| error.to_string())                .map(|row| row.and_then(|row| row.int("n")).unwrap_or(0))        })        .expect("the outbox")}/// RULE: Before sign-in, Start reading and Finished run in the phone's own copy: Start stamps reading and today, a finished book started again clears its finished day, Finished stamps today, counts one more reading and writes the stars it asked for (Skip leaves the rating, a rating past five is refused), each write queues for the object, and starting a book being read or finishing a finished one is refused by name.#[test]fn start_and_finish_run_in_the_phones_copy_before_sign_in() {    let (_dir, client) = local_phone();    assert!(client.object_door().is_none());    let id = book(&client, json!({"title": "The Lantern Orchard", "status": "want_to_read"}));    let before = queued(&client, "cotton_book");    let answer = act(&client, json!({"act": "start_book", "book": id})).expect("started");    assert_eq!(answer["book"], json!(id));    let started = data(&client, &id);    assert_eq!(started["status"], json!("reading"));    let today = started["started_on"].as_str().expect("a day").to_string();    assert_eq!(today.len(), 10);    assert_eq!(act(&client, json!({"act": "start_book", "book": id})).expect_err("reading").code, "already_reading");    act(&client, json!({"act": "finish_book", "args": {"book": id}})).expect("finished");    let finished = data(&client, &id);    assert_eq!(finished["status"], json!("finished"));    assert_eq!(finished["finished_on"], json!(today));    assert_eq!(finished["read_count"], json!(1));    assert_eq!(act(&client, json!({"act": "finish_book", "book": id})).expect_err("finished").code, "already_finished");    act(&client, json!({"act": "start_book", "book": id})).expect("a re-read");    let again = data(&client, &id);    assert_eq!(again["status"], json!("reading"));    assert!(again.get("finished_on").is_none_or(Value::is_null), "{again}");    act(&client, json!({"act": "finish_book", "book": id, "rating": 4})).expect("finished again, four stars");    assert_eq!(data(&client, &id)["read_count"], json!(2));    assert_eq!(data(&client, &id)["rating"], json!(4));    act(&client, json!({"act": "start_book", "book": id})).expect("a third reading");    act(&client, json!({"act": "finish_book", "book": id, "rating": null})).expect("finished, Skip");    assert_eq!(data(&client, &id)["rating"], json!(4), "Skip leaves the stars");    act(&client, json!({"act": "start_book", "book": id})).expect("a fourth reading");    assert_eq!(act(&client, json!({"act": "finish_book", "book": id, "rating": 7})).expect_err("seven stars").code, "bad_args");    assert!(queued(&client, "cotton_book") > before, "the writes queue for the object");    assert_eq!(act(&client, json!({"act": "start_book", "book": "no-such-book"})).expect_err("no book").code, "no_such_book");}/// RULE: An act only the object can run (Find a book asks Open Library from the object) is refused `sign_in_first` on a phone not signed in, naming the act; nothing is written.#[test]fn an_act_at_the_object_before_sign_in_is_refused_sign_in_first() {    let (_dir, client) = local_phone();    let refused = act(&client, json!({"act": "find_book", "args": {"query": "the lantern orchard"}})).expect_err("no object");    assert_eq!(refused.code, crate::phone::object_acts::SIGN_IN_FIRST);    assert_eq!(refused.message, "Sign in first: this needs your account.");    assert_eq!(refused.details["act"], json!("find_book"));}const EXPORT: &str = "Book Id,Title,Author,ISBN,ISBN13,My Rating,Number of Pages,Year Published,Original Publication Year,Date Read,Date Added,Bookshelves,Exclusive Shelf,My Review,Read Count\n\1001,The Lantern Orchard,Ada Vale,\"=\"\"0141439513\"\"\",\"=\"\"\"\"\",4,320,2001,1999,2026/03/02,2025/12/01,\"favourites, to-read\",read,Loved it<br/>twice,1\n\1002,\"Salt, and Other Rivers\",Bo Lin,,,0,,,,,2026/01/05,favourites,to-read,,0\n\1003,A Quiet Engine,Cy Moor,,,0,210,,,,2026/02/10,dnf,currently-reading,,0\n";/// RULE: Before sign-in, a Goodreads export lands whole in the phone's copy: each row a book by its Goodreads id with its status from the exclusive shelf (a dnf shelf stops it), its rating, review, dates, pages and times read, every other shelf a list of books made once by name; a second import makes nothing new and never moves a book backwards or over what the owner set; the answer lands on the first book made.#[test]fn a_goodreads_export_lands_in_the_phones_copy_before_sign_in() {    let (_dir, client) = local_phone();    let answer = act(&client, json!({"act": "import_goodreads", "file": EXPORT})).expect("imported");    assert_eq!((answer["books"].clone(), answer["made"].clone(), answer["lists"].clone()), (json!(3), json!(3), json!(1)), "{answer}");    let first = answer["first"].as_str().expect("the first book").to_string();    let lantern = data(&client, &first);    assert_eq!(lantern["title"], json!("The Lantern Orchard"));    assert_eq!(lantern["status"], json!("finished"));    assert_eq!(lantern["rating"], json!(4));    assert_eq!(lantern["isbn"], json!("0141439513"));    assert_eq!(lantern["year"], json!("1999"));    assert_eq!(lantern["finished_on"], json!("2026-03-02"));    assert_eq!(lantern["review"], json!("Loved it\ntwice"));    assert_eq!(lantern["source"], json!("goodreads"));    assert_eq!(lantern["goodreads_id"], json!("1001"));    let listed = crate::phone::records::call(&client, "records.list", &json!({"table": "book"})).expect("the books");    let by_title = |title: &str| listed["records"].as_array().unwrap().iter().find(|r| r["data"]["title"] == json!(title)).cloned().expect(title);    assert_eq!(by_title("Salt, and Other Rivers")["data"]["status"], json!("want_to_read"));    let engine = by_title("A Quiet Engine");    assert_eq!(engine["data"]["status"], json!("stopped"));    let groups = crate::phone::records::call(&client, "groups.list", &json!({"table": "book"})).expect("the lists");    let lists = groups["groups"].as_array().expect("lists");    assert_eq!(lists.len(), 1, "{groups}");    assert_eq!(lists[0]["name"], json!("favourites"));    assert_eq!(lists[0]["count"], json!(2));    // The owner rates it again in Cotton and starts the stopped one over.    let engine_id = engine["id"].as_str().unwrap().to_string();    crate::phone::records::call(&client, "records.update", &json!({"table": "book", "id": first, "patch": {"rating": 5}})).expect("rated");    act(&client, json!({"act": "finish_book", "book": engine_id})).expect("finished");    let again = act(&client, json!({"act": "import_goodreads", "file": EXPORT})).expect("again");    assert_eq!((again["made"].clone(), again["lists"].clone()), (json!(0), json!(0)), "{again}");    assert_eq!(again["first"], json!(first));    assert_eq!(data(&client, &first)["rating"], json!(5));    assert_eq!(data(&client, &engine_id)["status"], json!("finished"));    let groups = crate::phone::records::call(&client, "groups.list", &json!({"table": "book"})).expect("the lists");    assert_eq!(groups["groups"][0]["count"], json!(2));}/// RULE: A file that is not a Goodreads library export is refused by name, and nothing is written.#[test]fn a_file_that_is_no_export_is_refused() {    let (_dir, client) = local_phone();    let refused = act(&client, json!({"act": "import_goodreads", "file": "Title,Author\nA,B\n"})).expect_err("no export");    assert_eq!(refused.code, "not_goodreads");    let listed = crate::phone::records::call(&client, "records.list", &json!({"table": "book"})).expect("the books");    assert_eq!(listed["records"].as_array().map(Vec::len), Some(0));}/// RULE: The export's CSV is read as RFC 4180: quoted commas, doubled quotes and line breaks inside a field, CRLF rows and a byte-order mark.#[test]fn the_export_is_read_as_rfc_4180() {    let rows = csv_rows("\u{feff}a,\"b, c\",\"say \"\"hi\"\"\"\r\n\"two\nlines\",x,\r\n\r\n");    assert_eq!(rows, vec![vec!["a", "b, c", "say \"hi\""], vec!["two\nlines", "x", ""]]);    assert_eq!(isbn_of("=\"0141439513\""), "0141439513");    assert_eq!(isbn_of("=\"\""), "");}/// This app's own core, opened over a phone that never signed in.fn handle() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    let layout = cotton_client::layout::Layout::new(dir.path());    std::fs::create_dir_all(layout.client_dir()).expect("the client folder");    std::fs::write(        layout.connection_json(),        serde_json::to_vec_pretty(&json!({            "mode": "local", "baseUrl": "https://server.invalid", "workspaceId": crate::fixture::WORKSPACE,            "ownerId": crate::fixture::OWNER, "connectedAt": "2026-11-05T10:00:00.000Z",        }))        .expect("json"),    )    .expect("the connection record");    let replica = layout.replica(crate::fixture::WORKSPACE);    std::fs::create_dir_all(replica.parent().expect("a parent")).expect("the replica folder");    let seeded = crate::fixture::seeded(&replica);    crate::fixture::this_devices_row(&seeded);    drop(seeded);    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: None,        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: None,    })    .expect("an open core");    handle.client().set_self_device_id(Some(crate::fixture::SELF_DEVICE_ID.to_string()));    (dir, handle)}/// RULE (Books app definition: Finish asks for stars): a book's Finished asks its stars on the fan and writes them as `rating` (Skip writes none); Rate sets the stars on any book, a value it does not offer refused; Review writes the review; Add file stands only on a book with no file.#[test]fn finish_asks_for_stars_and_rate_review_and_add_file_stand_on_a_book() {    let (_dir, handle) = handle();    let client = handle.client();    let command = |id: &str, name: &str, picked: Option<&str>| {        let mut request = json!({"table": "book", "id": id, "command": name});        if let Some(picked) = picked {            request["picked"] = json!(picked);        }        crate::methods::dispatch(&handle, "records.command", &request)    };    let id = book(&client, json!({"title": "The Lantern Orchard", "status": "reading"}));    let kit = cotton_core::definitions::TableDefinition::from_json(include_str!("../../../cotton-core/kits/personal/tables/book.json")).expect("the kit's book");    let finish = kit.command("finish").cloned();    let pick = finish.and_then(|finish| finish.pick).expect("Finished asks a pick");    assert_eq!(pick.labels.as_ref().map(|labels| labels.iter().count()), Some(5), "one to five stars");    assert_eq!(pick.optional, Some(true), "and Skip");    command(&id, "finish", Some("4.0")).expect("finished, four stars");    let finished = data(&client, &id);    assert_eq!((finished["status"].clone(), finished["rating"].clone()), (json!("finished"), json!(4)), "{finished}");    command(&id, "start", None).expect("read again");    command(&id, "finish", Some("")).expect("finished, Skip");    assert_eq!(data(&client, &id)["rating"], json!(4), "Skip leaves the stars");    command(&id, "rate", Some("2")).expect("rated");    assert_eq!(data(&client, &id)["rating"], json!(2));    assert_eq!(command(&id, "rate", Some("2.5")).expect_err("no half star offered").code, "bad_request");    command(&id, "review", Some("Slow, then all at once.")).expect("reviewed");    assert_eq!(data(&client, &id)["review"], json!("Slow, then all at once."));    let open = command(&id, "add_file", None).expect("a book with no file offers Add file");    assert_eq!(open["answer"]["flow"].as_str().or(open["flow"].as_str()), Some("addBookFile"), "{open}");    client        .with_writer(|replica| replica.driver.exec(&format!("UPDATE cotton_book SET file = 'x/books/{}.epub' WHERE id = '{id}'", "a".repeat(64))).map_err(|error| error.to_string()))        .expect("a file");    assert!(command(&id, "add_file", None).is_err(), "a book with a file offers no Add file");}/// RULE: A held highlight offers the reader's own four besides Group and/// Bin: Open in book, Recolour (the colour column's choices), Note (its/// words on note) and Remove (it is deleted, unmarked), each run here on the/// phone (claude-books-gaps, 5 Nov 2026).#[test]fn a_held_highlight_recolours_notes_and_removes() {    let (_dir, handle) = handle();    let client = handle.client();    let command = |id: &str, name: &str, picked: Option<&str>| {        let mut request = json!({"table": "highlight", "id": id, "command": name});        if let Some(picked) = picked {            request["picked"] = json!(picked);        }        crate::methods::dispatch(&handle, "records.command", &request)    };    let book = book(&client, json!({"title": "The Lantern Orchard"}));    let made = crate::phone::records::call(&client, "records.create", &json!({"table": "highlight", "data": {        "book": book, "text": "A synthetic passage", "colour": "yellow", "locator": "{\"href\":\"one.xhtml\"}",    }}))    .expect("a highlight");    let id = made.pointer("/record/id").and_then(Value::as_str).expect("its id").to_string();    let read = |id: &str| crate::phone::records::call(&client, "records.get", &json!({"table": "highlight", "id": id}));    command(&id, "recolour", Some("teal")).expect("recoloured");    assert_eq!(read(&id).expect("the highlight")["data"]["colour"], json!("teal"));    assert!(command(&id, "recolour", Some("mauve")).is_err(), "only the column's choices");    command(&id, "note", Some("Keep this one.")).expect("noted");    assert_eq!(read(&id).expect("the highlight")["data"]["note"], json!("Keep this one."));    command(&id, "remove", None).expect("removed");    assert!(read(&id).expect("held in Deleted")["deleted_at"].is_string(), "unmarked");}/// RULE: A book file this phone brought in is kept on this phone/// (`books.here` kept), so its reader opens the bytes here before any/// sign-in and never asks the object for them (claude-books-gaps walk,/// 5 Nov 2026: an added EPUB would not open signed out).#[test]fn a_book_this_phone_brought_in_is_kept_here() {    let (dir, handle) = handle();    let file = dir.path().join("the-lantern-orchard.epub");    std::fs::write(&file, b"PK\x03\x04 an invented book, not a real one").expect("the book");    let captured = crate::methods::dispatch(&handle, "capture.media", &json!({        "path": file.to_string_lossy(), "mime": "application/epub+zip", "kind": "book", "filename": "the-lantern-orchard.epub",        "book": {"format": "epub", "title": "The Lantern Orchard"},    }))    .expect("the book captured");    let key = captured["key"].as_str().or(captured["answer"]["key"].as_str()).expect("its key").to_string();    let here = crate::methods::dispatch(&handle, "books.here.read", &json!({"key": key})).expect("what this phone keeps");    assert_eq!(here["state"], json!("kept"), "{here}");}/// RULE: Find details before sign-in is refused in so many words (the/// object is asked, and there is none yet), never run silently.#[test]fn find_details_before_sign_in_says_sign_in_first() {    let (_dir, handle) = handle();    let client = handle.client();    let id = book(&client, json!({"title": "Letters to the Lighthouse", "author": "Iris Mendel"}));    let refused = crate::methods::dispatch(&handle, "records.command", &json!({"table": "book", "id": id, "command": "find_details"}))        .expect_err("no object to ask");    assert_eq!(refused.code, "sign_in_first", "{refused:?}");}/// RULE: Add file on a book the Goodreads import made, before sign-in, gives/// that book the PDF picked (claude-books-gaps walk, 5 Nov 2026: refused).#[test]fn add_file_gives_an_imported_book_its_pdf_before_sign_in() {    let (dir, handle) = handle();    let client = handle.client();    let answer = act(&client, json!({"act": "import_goodreads", "file": EXPORT})).expect("imported");    let first = answer["first"].as_str().expect("the first book").to_string();    crate::methods::dispatch(&handle, "records.command", &json!({"table": "book", "id": first, "command": "rate", "args": {"patch": {"rating": 3}}})).ok();    let file = dir.path().join("wallpaper-as-pdf.pdf");    std::fs::write(&file, b"%PDF-1.4\n% an invented PDF\n").expect("a synthetic PDF");    let added = crate::methods::dispatch(&handle, "capture.media", &json!({        "path": file.to_string_lossy(), "mime": "application/pdf", "kind": "book", "filename": "wallpaper-as-pdf.pdf",        "book": {"format": "pdf", "title": "wallpaper-as-pdf", "pages": 12}, "into": first,    }))    .unwrap_or_else(|refused| panic!("the file added: {refused:?}"));    assert_eq!(added["recordId"].as_str().or(added["answer"]["recordId"].as_str()), Some(first.as_str()), "{added}");    assert_eq!(data(&client, &first)["format"], json!("pdf"));}