250 lines · 15.2 KB · RustRaw
//! Storage by chat (the owner's iPhone, Comms build 23, 23 Nov 2026, item 4)://! what each chat keeps on this phone, measured from its files, largest//! first, and Free this chat, which takes only that chat's files already//! safe in the person's account. Every name, number and byte is invented.use serde_json::{json, Value};use super::{answer, contact, item, message, refused, sql, t, thread, ASHA, WEEKEND};use crate::handle::CottonHandle;const RAVI: &str = "11111111-1111-4111-8111-0000000000d1";const MEERA: &str = "11111111-1111-4111-8111-0000000000e1";/// An invented file of `bytes` kept in `thread`'s folder of the person's own media, as a chat file is/// (`chat_files::keep`): its ledger entry `pending` until the drain puts it in the account. Answers its key.pub(crate) fn kept_file(handle: &CottonHandle, thread: &str, n: u32, name: &str, mime: &str, bytes: usize) -> String { let client = handle.client(); let dir = client.layout().root().join("invented-chat-files"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join(format!("{n}-{name}")); // Distinct bytes for each, as the store keeps files by what they hold. let mut plain = format!("invented file {n} of {thread} ").into_bytes(); plain.resize(bytes, (n % 251) as u8); std::fs::write(&path, &plain).unwrap(); let layout = client.layout().clone(); let clock = client.clock(); let outcome = client .with_writer(|replica| { let file_id = replica.identity.id().clone(); let leg = cotton_client::messages_import::media::MediaLeg { layout: &layout, file: &file_id, thread_id: thread, clock: clock.as_ref() }; let media = cotton_client::messages_import::MediaFile { external_id: format!("m-{n}"), path: path.clone(), name: Some(name.to_string()), content_type: Some(mime.to_string()) }; let outcome = cotton_client::messages_import::media::store_one_file(&leg, replica.driver, &media); if let cotton_client::messages_import::media::MediaOutcome::Stored { key, .. } = &outcome { replica.driver.run("UPDATE _media SET tier = 'original' WHERE key = ? AND tier IS NULL", &[t(key)]).map_err(|e| e.to_string())?; } Ok(outcome) }) .unwrap(); let _ = std::fs::remove_file(&path); match outcome { cotton_client::messages_import::media::MediaOutcome::Stored { key, .. } => key, other => panic!("{name} was not kept: {other:?}"), }}/// The file reached the person's account (the drain's upload done).pub(crate) fn synced(handle: &CottonHandle, key: &str) { sql(handle, "UPDATE _media SET state = 'synced' WHERE key = ?", &[t(key)]);}fn chats(handle: &CottonHandle) -> Vec<Value> { answer(handle, "chat.storage", json!({}))["chats"].as_array().cloned().unwrap_or_default()}fn chat(handle: &CottonHandle, thread: &str) -> Option<Value> { chats(handle).into_iter().find(|c| c["thread"] == thread)}fn ids(parts: &Value) -> Vec<String> { parts.as_array().unwrap().iter().map(|p| p["id"].as_str().unwrap().to_string()).collect()}fn three_people(handle: &CottonHandle) { contact(handle, "c-asha", "Asha Verma", "15550100001"); thread(handle, ASHA, "dm", Some("cotton:+15550100001"), None, Some("c-asha"), "2026-11-20T09:41:00.000Z"); contact(handle, "c-ravi", "Ravi Menon", "15550100002"); thread(handle, RAVI, "dm", Some("cotton:+15550100002"), None, Some("c-ravi"), "2026-11-19T12:00:00.000Z"); contact(handle, "c-meera", "Meera Iyer", "15550100003"); thread(handle, MEERA, "dm", Some("cotton:+15550100003"), None, Some("c-meera"), "2026-11-18T08:00:00.000Z"); thread(handle, WEEKEND, "group", Some("group:weekend"), Some("Hill trip"), None, "2026-11-20T04:02:00.000Z");}// RULE (owner, 23 Nov 2026, item 4): each chat says what it keeps on this phone, measured from its files: the sum of// its kinds, each kind its own files only, a kind with nothing left out, and the chats largest first. A chat that// keeps nothing is not listed; a file the ledger names but the disk no longer has counts nothing; a thumbnail stays in// Other, as Storage counts it; and the chats together are what Storage's Photos and files holds.#[test]fn each_chat_says_what_it_keeps_largest_first() { let (_dir, handle) = crate::phone::passwords::tests::phone(); three_people(&handle); assert_eq!(answer(&handle, "chat.storage", json!({}))["none"], "No chat keeps photos or files on this phone yet."); assert!(chats(&handle).is_empty()); kept_file(&handle, ASHA, 1, "lake.jpg", "image/jpeg", 300_000); kept_file(&handle, ASHA, 2, "jetty.png", "image/png", 200_000); kept_file(&handle, ASHA, 3, "voice.m4a", "audio/mp4", 50_000); kept_file(&handle, RAVI, 4, "plants.mp4", "video/mp4", 900_000); kept_file(&handle, WEEKEND, 5, "tent-list.pdf", "application/pdf", 40_000); kept_file(&handle, WEEKEND, 6, "view.jpg", "image/jpeg", 10_000); // Gone from the disk (the ledger still names it): measured, it is nothing. let gone = kept_file(&handle, MEERA, 7, "gone.jpg", "image/jpeg", 70_000); let path = handle.client().with_file(|file| Ok(crate::phone::media::local_path_of(file.driver, &gone))).unwrap().expect("here"); std::fs::remove_file(path).unwrap(); // A thumbnail of Asha's picture: Other, not hers. let thumb = kept_file(&handle, ASHA, 8, "lake.t256.jpg", "image/jpeg", 9_000); sql(&handle, "UPDATE _media SET tier = 'thumb' WHERE key = ?", &[t(&thumb)]); let all = answer(&handle, "chat.storage", json!({})); assert_eq!(all["title"], "By chat", "{all}"); assert!(all.get("none").is_none(), "{all}"); let listed = chats(&handle); let order: Vec<&str> = listed.iter().map(|c| c["thread"].as_str().unwrap()).collect(); assert_eq!(order, [RAVI, ASHA, WEEKEND], "largest first; Meera's keeps nothing on the disk: {all}"); assert_eq!(listed.iter().map(|c| c["name"].as_str().unwrap()).collect::<Vec<_>>(), ["Ravi Menon", "Asha Verma", "Hill trip"], "the list's own names"); let asha = &listed[1]; assert_eq!(asha["bytes"], 550_000, "{asha}"); assert_eq!(asha["said"], "0.6 MB"); assert_eq!(ids(&asha["parts"]), ["photos", "voice"], "only the kinds it holds: {asha}"); assert_eq!(asha["parts"][0], json!({ "id": "photos", "label": "Photos", "bytes": 500_000, "said": "0.5 MB" })); assert_eq!(asha["parts"][1]["label"], "Voice messages"); assert_eq!(asha["parts"][1]["bytes"], 50_000); assert_eq!(ids(&listed[0]["parts"]), ["videos"]); assert_eq!(listed[0]["parts"][0]["label"], "Videos"); assert_eq!(ids(&listed[2]["parts"]), ["photos", "files"]); assert_eq!(listed[2]["parts"][1]["label"], "Files"); for c in &listed { let sum: u64 = c["parts"].as_array().unwrap().iter().map(|p| p["bytes"].as_u64().unwrap()).sum(); assert_eq!(c["bytes"].as_u64(), Some(sum), "a chat's size is the sum of its kinds: {c}"); assert!(c["picture"].is_object(), "drawn as the list draws it: {c}"); } // The chats together are Storage's Photos and files (the thumbnail and the file gone aside). let files = crate::methods::shell_settings::kept(&handle.client()).files; let together: u64 = listed.iter().map(|c| c["bytes"].as_u64().unwrap()).sum(); assert_eq!(together + 70_000, files, "Photos and files (the ledger's; the thumbnail is Other), less the file no longer on the disk"); // Equal sizes stand by name. kept_file(&handle, MEERA, 9, "same.jpg", "image/jpeg", 550_000); let order: Vec<String> = chats(&handle).iter().map(|c| c["name"].as_str().unwrap().to_string()).collect(); assert_eq!(order, ["Ravi Menon", "Asha Verma", "Meera Iyer", "Hill trip"]);}// RULE (owner, 23 Nov 2026, item 4): Free this chat takes only that chat's files already safe in the person's account,// exactly as Free up space does: never a file not synced yet, never another chat's, never a preview (it lives in the// message). It says how much before it is asked, answers what it freed in the kit's words, and refuses when more// would go than the person agreed to.#[test]fn free_this_chat_takes_only_its_files_safe_in_the_account() { let (_dir, handle) = crate::phone::passwords::tests::phone(); three_people(&handle); let photo = kept_file(&handle, MEERA, 1, "lake.jpg", "image/jpeg", 2_100_000); let file = kept_file(&handle, MEERA, 2, "plan.pdf", "application/pdf", 240_000); let _voice = kept_file(&handle, MEERA, 3, "voice.m4a", "audio/mp4", 300_000); let ravis = kept_file(&handle, RAVI, 4, "plants.jpg", "image/jpeg", 400_000); for key in [&photo, &file, &ravis] { synced(&handle, key); } // Meera's photo is in a message that carries its preview (Pictures at once). message(&handle, "m-e-photo", MEERA, false, "cotton", "live", "", "2026-11-18T08:01:00.000Z", 2, None); let preview = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2Q=="; let meta = json!({ "cotton": { "pictures": [{ "file": "f-lake", "key": "A".repeat(43), "sha256": "00", "mime": "image/jpeg", "bytes": 2_100_000, "width": 1200, "height": 900, "preview": preview, "kept": photo }] } }); sql(&handle, "UPDATE cotton_msg_messages SET meta = ? WHERE id = 'm-e-photo'", &[t(&meta.to_string())]); let before = answer(&handle, "chat.thread", json!({ "thread": MEERA })); let shown = item(&before, "m-e-photo")["media"][0]["preview"].clone(); assert!(shown.is_string(), "the message carries its preview: {before}"); let meera = chat(&handle, MEERA).expect("Meera's chat keeps files"); assert_eq!(meera["bytes"], 2_640_000, "{meera}"); let free = &meera["free"]; assert_eq!(free["label"], "Free this chat"); assert_eq!(free["bytes"], 2_340_000, "the photo and the PDF are safe in the account; the voice message is not synced yet: {free}"); assert_eq!(free["line"], "Frees 2.3 MB. Previews stay, and so does anything not synced yet. What goes comes back when you open it."); assert_eq!(free["ask"], "Free 2.3 MB from this chat?"); assert!(free["ask_body"].as_str().is_some_and(|b| b.contains("Previews stay")), "{free}"); assert_eq!(free["confirm"], "Free up"); assert_eq!(refused(&handle, "chat.storage.free", json!({ "thread": MEERA, "expected": 1_000 })), "storage_changed", "more would go than was said"); assert_eq!(refused(&handle, "chat.storage.free", json!({ "thread": MEERA })), "bad_request"); assert_eq!(refused(&handle, "chat.storage.free", json!({ "thread": "../x", "expected": 1 })), "bad_request", "a chat, never a path"); let freed = answer(&handle, "chat.storage.free", json!({ "thread": MEERA, "expected": 2_340_000 })); assert_eq!(freed, json!({ "freed_bytes": 2_340_000, "said": "Freed 2.3 MB." })); let meera = chat(&handle, MEERA).expect("the voice message not synced yet stays"); assert_eq!(meera["bytes"], 300_000, "{meera}"); assert_eq!(ids(&meera["parts"]), ["voice"], "{meera}"); assert_eq!(meera["free"]["bytes"], 0); assert_eq!(meera["free"]["line"], "Nothing to free here. Previews stay, and so does anything not synced yet."); assert!(meera["free"].get("ask").is_none(), "nothing to ask: {meera}"); assert_eq!(chat(&handle, RAVI).expect("Ravi's stays")["bytes"], 400_000, "another chat's files are not touched"); let after = answer(&handle, "chat.thread", json!({ "thread": MEERA })); assert_eq!(item(&after, "m-e-photo")["media"][0]["preview"], shown, "the preview stays: {after}"); // Nothing left to free in it: said so. assert_eq!(answer(&handle, "chat.storage.free", json!({ "thread": MEERA, "expected": 0 })), json!({ "freed_bytes": 0, "said": "Nothing was freed." })); // Free up space, after: only Ravi's goes. let all = crate::methods::shell_settings::kept(&handle.client()).freeable; assert_eq!(all, 400_000);}// RULE: every word the breakdown says is a kit line, none of them empty.#[test]fn the_breakdowns_words_are_lines() { let lines = cotton_core::messages::app::list::lines(); for kind in crate::phone::chat_storage::KINDS.iter().chain(["free", "free_line", "free_none", "free_ask", "free_ask_body", "free_confirm"].iter()) { let said = cotton_core::messages::app::list::say(&lines, &format!("app.you.storage_chat.{kind}"), &[("size", "1 MB")]); assert!(!said.is_empty() && !said.contains("app.you"), "{kind}: {said}"); } assert_eq!(crate::phone::chat_storage::kind_of("IMAGE/HEIC"), "photos"); assert_eq!(crate::phone::chat_storage::kind_of("video/quicktime"), "videos"); assert_eq!(crate::phone::chat_storage::kind_of("audio/ogg"), "voice"); assert_eq!(crate::phone::chat_storage::kind_of("application/pdf"), "files");}/// Chat Dev's Storage by chat (`chat-warm.json` `storage`, written by `write_chat_warm_fixture`): the core's own answers/// over invented files of known sizes in Asha's chat, the Hill trip and Meera's chat (Meera's voice message not/// synced yet), before anything is freed and after each chat is freed by itself: `chats` (`chat.storage`), `settings`/// (`shell.settings`' `storage`, the totals above the list) and `row` (You's Storage line, `chat.you`).pub(crate) fn warm_fixture() -> Value { fn stocked() -> (tempfile::TempDir, CottonHandle) { let (dir, handle) = crate::phone::passwords::tests::phone(); three_people(&handle); let files: [(&str, u32, &str, &str, usize, bool); 10] = [ (ASHA, 1, "lake-morning.jpg", "image/jpeg", 1_800_000, true), (ASHA, 2, "balcony.jpg", "image/jpeg", 2_400_000, true), (ASHA, 3, "bookshop.jpg", "image/jpeg", 1_100_000, true), (ASHA, 4, "lake.mp4", "video/mp4", 14_000_000, true), (WEEKEND, 5, "tent.jpg", "image/jpeg", 2_200_000, true), (WEEKEND, 6, "the-top.jpg", "image/jpeg", 2_200_000, true), (WEEKEND, 7, "packing-list.pdf", "application/pdf", 600_000, true), (MEERA, 8, "namaste.jpg", "image/jpeg", 2_100_000, true), (MEERA, 9, "plan.pdf", "application/pdf", 240_000, true), (MEERA, 10, "voice.m4a", "audio/mp4", 300_000, false), ]; for (thread, n, name, mime, bytes, up) in files { let key = kept_file(&handle, thread, n, name, mime, bytes); if up { synced(&handle, &key); } } (dir, handle) } fn state(handle: &CottonHandle) -> Value { let settings = crate::methods::dispatch(handle, "shell.settings", &json!({ "commit": "fixture" })).expect("shell.settings"); let you = crate::methods::dispatch(handle, "chat.you", &json!({})).expect("chat.you"); let row = you["rows"].as_array().unwrap().iter().find(|r| r["id"] == "storage").map(|r| r["line"].clone()).unwrap_or(Value::Null); json!({ "chats": answer(handle, "chat.storage", json!({})), "settings": settings["storage"], "row": row }) } let (_dir, handle) = stocked(); let before = state(&handle); let mut freed = serde_json::Map::new(); for c in before["chats"]["chats"].as_array().unwrap() { let (_dir, handle) = stocked(); let thread = c["thread"].as_str().unwrap(); let said = answer(&handle, "chat.storage.free", json!({ "thread": thread, "expected": c["free"]["bytes"] })); let mut after = state(&handle); after["said"] = said; freed.insert(thread.to_string(), after); } json!({ "before": before, "freed": freed })}