//! Albums on a phone, through the screens' methods, on synthetic libraries //! (no photos, no owner data): the pass, Tidy, a set, the Bin and Delete on //! both phones, the coordinator's rules A to G, and the shape of ALBUMS CORE //! 1d (27 Nov 2026): one library state per item, one function that makes a //! platform list, handed as a state settled only by the library, request ids, //! sliced planning, compared sweep tokens, and the generated matrix. use std::sync::atomic::{AtomicU64, Ordering}; use base64::Engine; use serde_json::{json, Value}; use cotton_core::albums::bin::{LibraryState, Mark}; use cotton_core::albums::synthetic::{library, Options, Synth}; use cotton_core::albums::{look, sets, words, Item, Kind, Platform}; use super::{answer, counted, put_mark, rebuild_tally, Chosen, Index, ACTS, METHODS}; static REQUEST: AtomicU64 = AtomicU64::new(1); fn index() -> (tempfile::TempDir, Index) { let dir = tempfile::tempdir().unwrap(); let ix = Index::open(&Index::path_in(dir.path())).unwrap(); (dir, ix) } /// An index on a disk whose flush costs nothing (tmpfs when the machine has /// one): the timing tests measure the core's own work in a tap, not this /// machine's disk under other builds (a phone's flash flushes in a few ms). fn index_on_fast_disk() -> (tempfile::TempDir, Index) { let dir = if std::path::Path::new("/dev/shm").is_dir() { tempfile::tempdir_in("/dev/shm").unwrap() } else { tempfile::tempdir().unwrap() }; let ix = Index::open(&Index::path_in(dir.path())).unwrap(); (dir, ix) } /// An act carries a request id the way a shell makes one per tap. fn with_request(method: &str, mut request: Value) -> Value { if ACTS.contains(&method) && request.get("request_id").is_none() { request["request_id"] = json!(format!("tap-{}", REQUEST.fetch_add(1, Ordering::Relaxed))); } request } fn call(ix: &mut Index, method: &str, request: Value, now: i64) -> Value { let request = with_request(method, request); answer(ix, method, &request, now).unwrap_or_else(|e| panic!("{method}: {} {}", e.code, e.message)) } fn refused(ix: &mut Index, method: &str, request: Value, now: i64) -> String { let request = with_request(method, request); answer(ix, method, &request, now).err().unwrap_or_else(|| panic!("{method} answered")).code } fn grey_json(s: &Synth) -> Value { match &s.grey { Some(g) => json!({ "width": g.width, "height": g.height, "pixels": base64::engine::general_purpose::STANDARD.encode(&g.pixels) }), None => Value::Null, } } fn strs(v: &Value) -> Vec { v.as_array().unwrap().iter().map(|x| x.as_str().unwrap().to_string()).collect() } /// The running counts equal the counts made from scratch. fn counts_hold(ix: &Index) { let fresh = counted(ix).unwrap(); let kept: std::collections::BTreeMap = ix .conn .prepare("SELECT k, n, bytes, inexact FROM tally") .unwrap() .query_map([], |r| Ok((r.get::<_, String>(0)?, (r.get(1)?, r.get(2)?, r.get(3)?)))) .unwrap() .map(Result::unwrap) .filter(|(_, v): &(String, (i64, i64, i64))| *v != (0, 0, 0)) .collect(); let fresh: std::collections::BTreeMap = fresh.into_iter().filter(|(_, v)| *v != (0, 0, 0)).collect(); assert_eq!(kept, fresh, "the running counts drifted"); } /// Start, hand over the library, and run the pass to the end the way a shell would. fn load(ix: &mut Index, lib: &[Synth], platform: &str) -> i64 { let first = call(ix, "albums.start", json!({ "platform": platform, "permission": "none", "offset_s": 19_800 }), 0); assert_eq!(first["screen"], "first_run"); assert_eq!(call(ix, "albums.start", json!({ "platform": platform, "permission": "full" }), 0)["screen"], "home"); for chunk in lib.chunks(1_000) { let items: Vec<&Item> = chunk.iter().map(|s| &s.item).collect(); call(ix, "albums.library.take", json!({ "items": items }), 0); } look_all(ix, lib, 1_000_000) } fn look_all(ix: &mut Index, lib: &[Synth], mut now: i64) -> i64 { let by_id: std::collections::HashMap<&str, &Synth> = lib.iter().map(|s| (s.item.id.as_str(), s)).collect(); loop { let next = call(ix, "albums.pass.next", json!({ "limit": 200, "on_wifi": false }), now); let asks = next["asks"].as_array().unwrap().clone(); if asks.is_empty() { break; } let looks: Vec = asks .iter() .map(|a| { assert_eq!(a["px"], 360); assert_eq!(a["network"], false, "the first ask never uses the network"); let s = by_id[a["id"].as_str().unwrap()]; json!({ "id": a["id"], "grey": grey_json(s), "platform": s.platform, "network": false }) }) .collect(); now += 8_000; call(ix, "albums.look.take", json!({ "looks": looks }), now); } now } /// Keep the picks of the first set as the screen showed it. fn keep_first_set(ix: &mut Index, now: i64) -> (String, Vec, Vec, Value) { let row = call(ix, "albums.sets", json!({}), now)["sets"][0].clone(); let sid = row["set"].as_str().unwrap().to_string(); let members = strs(&row["members"]); let keepers = strs(&row["keepers"]); let done = call(ix, "albums.set.keep", json!({ "set": sid, "members": members, "count": members.len(), "keep": keepers }), now); (sid, members, keepers, done) } fn bin_count(ix: &mut Index, now: i64) -> usize { call(ix, "albums.bin", json!({}), now)["count"].as_u64().unwrap_or(0) as usize } /// Carry on the waiting acts the way the shell does: `albums.work` until an /// act finishes (its answer) or nothing is left (`idle`). fn work(ix: &mut Index, now: i64) -> Value { loop { let w = call(ix, "albums.work", json!({}), now); if w["idle"] == true || w["finished"] == true { return w; } } } /// Bin everything a list's screen offers, as its Bin all button does; answers /// how the act ended. fn bin_all(ix: &mut Index, list: &str, now: i64) -> Value { let l = call(ix, "albums.list", json!({ "list": list }), now); call(ix, "albums.bin.move", json!({ "list": list, "all": true, "token": l["token"], "count": l["bin_all"]["count"] }), now); work(ix, now) } /// Delete everything in the Bin as the screen showed it; answers how the act /// ended (its `platform` list and `held_back`, or `changed`). fn delete_all(ix: &mut Index, now: i64) -> Value { let bin = call(ix, "albums.bin", json!({}), now); let tap = call(ix, "albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] }), now); assert!(tap["job"]["act_id"].is_string(), "the tap writes one act row and answers its job"); work(ix, now) } fn asked_of(plan: &Value) -> Vec { plan["platform"]["parts"].as_array().map(|p| p.iter().flat_map(strs).collect()).unwrap_or_default() } /// After the phone asked the system: `platform.done` says which ids to read; /// the shell reads them and sends what the library says. Answers `settled`. fn settle(ix: &mut Index, plan: &Value, state: impl Fn(&str) -> &'static str, now: i64) -> Value { let act = plan["platform"]["act_id"].clone(); let read = call(ix, "albums.platform.done", json!({ "act_id": act }), now); let states: Vec = strs(&read["read"]).iter().map(|id| json!({ "id": id, "state": state(id) })).collect(); call(ix, "albums.library.take", json!({ "act_id": act, "states": states, "complete": true }), now)["settled"].clone() } fn screenshot(id: &str, at: i64, path: Option<&str>, bytes: u64) -> Item { Item { id: id.into(), kind: Kind::Photo, taken_at_ms: at, width: 1170, height: 2532, duration_ms: 0, bytes: Some(bytes), flags: vec!["screenshot".into()], path: path.map(String::from), camera: None, cloud_id: None, offset_s: None, added_ms: Some(at), generation_added: None, modified: None } } fn trashed(mut it: Item) -> Item { it.flags.push("trashed".into()); it } #[test] fn a_whole_library_passes_and_tidy_offers_its_lists_biggest_first() { let lib = library(&Options { items: 4_000, others: true, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let lines = call(&mut ix, "albums.pass.lines", json!({}), now); assert_eq!(lines["head"], format!("Looked through {} photos and videos.", words::count(lib.iter().filter(|s| s.item.kind == Kind::Photo).count()))); let tidy = call(&mut ix, "albums.tidy", json!({}), now); let names: Vec<&str> = tidy["lists"].as_array().unwrap().iter().map(|l| l["list"].as_str().unwrap()).collect(); for want in ["sets", "screenshots", "large_videos", "whatsapp_copies", "documents"] { assert!(names.contains(&want), "{want} missing from {names:?}"); } assert!(tidy["could_free"].as_str().unwrap().starts_with("You could free about ")); // the sets the index made, batch by batch, are the core's sets over the whole library let looks: Vec = lib.iter().map(|s| look::analyse(s.grey.as_ref(), s.platform.clone())).collect(); let mut shots: Vec> = lib.iter().enumerate().filter(|(i, s)| sets::groupable(&s.item, Some(&looks[*i]))).map(|(i, s)| sets::Shot { index: i, taken_at_ms: s.item.taken_at_ms, look: &looks[i] }).collect(); let whole = sets::group(&mut shots); let (mut seen, mut from) = (0, Value::Null); loop { let page = call(&mut ix, "albums.sets", json!({ "from": from }), now); seen += page["sets"].as_array().unwrap().len(); match &page["next_from"] { Value::Null => break, f => from = f.clone(), } } assert_eq!(seen, whole.len(), "incremental sets equal the whole-library sets"); let list = call(&mut ix, "albums.list", json!({ "list": "whatsapp_copies" }), now); assert_eq!(list["groups"][0]["heading"], "Copies of photos you already have"); assert!(list["groups"][0]["items"][0]["original"].is_string()); assert!(list["bin_all"]["count"].as_u64().unwrap() < list["count"].as_u64().unwrap(), "Bin all takes only the copies of his own photos"); counts_hold(&ix); } #[test] fn keeping_a_set_bins_the_rest_and_undo_puts_it_back_as_one_act() { let lib = library(&Options { items: 1_500, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let before = call(&mut ix, "albums.tidy", json!({}), now); let (sid, members, keepers, done) = keep_first_set(&mut ix, now + 1); assert_eq!(done["after"], words::kept_after(keepers.len(), members.len() - keepers.len())); assert!(done["job"].is_null()); assert_eq!(refused(&mut ix, "albums.set", json!({ "set": sid }), now), "gone"); assert_eq!(call(&mut ix, "albums.tidy", json!({}), now + 2)["bin"]["act"], format!("Delete {}", members.len() - keepers.len())); let bin = call(&mut ix, "albums.bin", json!({}), now + 2); assert!(bin["groups"][0]["heading"].as_str().unwrap().ends_with("· from a set")); assert_eq!(ix.count("SELECT count(*) FROM act"), 1, "one act row for the whole set"); counts_hold(&ix); call(&mut ix, "albums.undo", json!({ "token": done["undo"]["token"] }), now + 3); assert_eq!(call(&mut ix, "albums.tidy", json!({}), now + 3)["lists"], before["lists"]); assert_eq!(refused(&mut ix, "albums.undo", json!({ "token": done["undo"]["token"] }), now), "gone"); let row = call(&mut ix, "albums.sets", json!({}), now + 4)["sets"][0].clone(); let m = strs(&row["members"]); assert_eq!(refused(&mut ix, "albums.set.keep", json!({ "set": row["set"], "members": m, "count": m.len(), "keep": ["not-here"] }), now + 4), "bad_request"); counts_hold(&ix); } #[test] fn a_pass_landing_between_seeing_a_set_and_tapping_keep_refuses_the_keep() { let lib = library(&Options { items: 1_200, ..Options::default() }); let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec<&Item> = lib.iter().map(|s| &s.item).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); let looks_all: Vec = lib.iter().map(|s| look::analyse(s.grey.as_ref(), s.platform.clone())).collect(); let mut shots: Vec> = lib.iter().enumerate().filter(|(i, s)| sets::groupable(&s.item, Some(&looks_all[*i]))).map(|(i, s)| sets::Shot { index: i, taken_at_ms: s.item.taken_at_ms, look: &looks_all[i] }).collect(); let big = sets::group(&mut shots).into_iter().find(|s| s.len() >= 4).unwrap(); let held = &lib[*big.last().unwrap()]; let rest: Vec = lib.iter().filter(|s| s.item.id != held.item.id && s.item.kind == Kind::Photo).map(|s| json!({ "id": s.item.id, "grey": grey_json(s) })).collect(); for chunk in rest.chunks(300) { call(&mut ix, "albums.look.take", json!({ "looks": chunk }), 10); } let sid = sets::set_id(&lib[big[0]].item.id); let seen = call(&mut ix, "albums.set", json!({ "set": sid }), 10); let members: Vec = seen["members"].as_array().unwrap().iter().map(|m| m["id"].as_str().unwrap().to_string()).collect(); let keepers: Vec = seen["members"].as_array().unwrap().iter().filter(|m| m["keep"] == true).map(|m| m["id"].as_str().unwrap().to_string()).collect(); assert!(!members.contains(&held.item.id)); call(&mut ix, "albums.look.take", json!({ "looks": [{ "id": held.item.id, "grey": grey_json(held) }] }), 20); let r = json!({ "set": sid, "members": members, "count": members.len(), "keep": keepers }); assert_eq!(refused(&mut ix, "albums.set.keep", r, 30), "changed", "what he saw is not the set now"); assert!(call(&mut ix, "albums.bin", json!({}), 30)["empty"].is_object(), "nothing was binned"); } #[test] fn on_android_the_bin_is_marks_only_and_the_phones_trash_is_never_the_bin() { // decision G: one Bin on both phones; binning touches nothing in MediaStore let lib = library(&Options { items: 1_500, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "android"); let (_sid, members, keepers, done) = keep_first_set(&mut ix, now); assert!(done.get("platform").map_or(true, Value::is_null), "no system act at bin time"); let binned = members.len() - keepers.len(); // forty days on, two sweeps of the whole library: nothing has been erased by a clock let later = now + 40 * 86_400_000; let ids: Vec<&str> = lib.iter().map(|s| s.item.id.as_str()).collect(); for token in ["gen-9", "gen-10"] { call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": ids, "complete": true, "token": token }), later); } let bin = call(&mut ix, "albums.bin", json!({}), later); assert_eq!(bin["count"].as_u64().unwrap() as usize, binned); assert_eq!(bin["note"], words::BIN_NOTE); let some: Vec = strs(&bin["groups"][0]["ids"]).into_iter().take(1).collect(); call(&mut ix, "albums.bin.bring_back", json!({ "ids": some, "count": 1 }), later); assert_eq!(bin_count(&mut ix, later), binned - 1, "brought back at day 40"); // Delete ships on the iPhone first: Android is never offered it, and never handed anything let bin = call(&mut ix, "albums.bin", json!({}), later); assert!(bin["act"].is_null()); assert_eq!(bin["delete_later"], words::DELETE_ANDROID_LATER); assert_eq!(refused(&mut ix, "albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] }), later), "not_on_this_phone"); assert_eq!(ix.count("SELECT count(*) FROM mark WHERE state = 'handed'"), 0); counts_hold(&ix); } /// Bring back of a deleted photo is refused or skipped, never applied. fn refused_or_skip(ix: &mut Index, id: &str, now: i64) -> String { match answer(ix, "albums.bin.bring_back", &with_request("albums.bin.bring_back", json!({ "ids": [id], "count": 1 })), now) { Ok(v) => { assert!(v["undo"].is_null(), "a deleted photo is never brought back"); "changed".to_string() } Err(e) => e.code, } } #[test] fn a_sweep_needs_full_access_a_finished_read_and_a_new_token_and_two_must_agree() { let lib = library(&Options { items: 800, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let (_s, members, keepers, _) = keep_first_set(&mut ix, now); let before = call(&mut ix, "albums.tidy", json!({}), now); let all: Vec<&str> = lib.iter().map(|s| s.item.id.as_str()).collect(); assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": [], "complete": true }), now)["sweep"]["why"], "no_token"); assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": &all[..600], "complete": false, "token": "t1" }), now)["sweep"]["why"], "not_complete"); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "limited", "chosen": 12 }), now); assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": &all[..12], "complete": true, "token": "t1" }), now)["sweep"]["why"], "not_full_access"); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), now); assert_eq!(call(&mut ix, "albums.tidy", json!({}), now), before, "nothing was swept"); // he deletes a quarter of the library in another app, his set among them: a large, real deletion let set_ids: Vec<&str> = members.iter().map(String::as_str).collect(); let left: Vec<&str> = all.iter().copied().filter(|id| !set_ids.contains(id)).skip(200).collect(); let gone_n = all.len() - left.len(); let first = call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": left, "complete": true, "token": "t2" }), now); assert_eq!(first["sweep"], json!({ "swept": true, "gone": 0, "waiting": gone_n }), "one sweep alone drops nothing"); // M3: the same token again is the same reading, never a second witness let same = call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": left, "complete": true, "token": "t2" }), now); assert_eq!(same["sweep"], json!({ "swept": false, "why": "same_token" })); // a sweep whose ids differ from the last one starts again: nothing is believed from the pair let other: Vec<&str> = left.iter().copied().skip(1).collect(); let differ = call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": other, "complete": true, "token": "t3" }), now); assert_eq!(differ["sweep"]["gone"], 0, "the two disagree in their ids"); let second = call(&mut ix, "albums.library.take", json!({ "items": [], "all_ids": other, "complete": true, "token": "t4" }), now); assert_eq!(second["sweep"], json!({ "swept": true, "gone": gone_n + 1, "waiting": 0 }), "two agreeing sweeps with different tokens: a big deletion is accepted"); // `removed` is held to the same rule: one report, or one token twice, removes nothing let one = left[5]; call(&mut ix, "albums.library.take", json!({ "removed": [one], "token": "c1" }), now); call(&mut ix, "albums.library.take", json!({ "removed": [one], "token": "c1" }), now); assert!(ix.present(one)); assert_eq!(refused(&mut ix, "albums.library.take", json!({ "removed": [one] }), now), "bad_request", "removed needs a token"); call(&mut ix, "albums.library.take", json!({ "removed": [one], "token": "c2" }), now); assert!(!ix.present(one)); // his choices stay, listed with what he chose (rule A) assert!(keepers.iter().all(|k| matches!(ix.mark(k), Mark::Keep { .. }))); let bin = call(&mut ix, "albums.bin", json!({}), now); let gone = bin["groups"].as_array().unwrap().iter().find(|g| g["heading"] == words::GONE_HEADING).unwrap(); assert_eq!(gone["count"].as_u64().unwrap() as usize, members.len()); assert!(strs(&gone["chosen"]).iter().any(|c| c == "keep") && strs(&gone["chosen"]).iter().any(|c| c == "bin")); assert_eq!(bin["count"], 0, "never counted, never deleted"); counts_hold(&ix); } /// A WhatsApp copy whose camera original is itself offered somewhere. fn a_pair(ix: &mut Index, now: i64) -> (String, String) { let mut from = Value::Null; loop { let list = call(ix, "albums.list", json!({ "list": "whatsapp_copies", "from": from }), now); for c in list["groups"][0]["items"].as_array().unwrap() { let o = c["original"].as_str().unwrap().to_string(); let offered: i64 = ix.conn.query_row("SELECT count(*) FROM offer WHERE id = ?1", [&o], |r| r.get(0)).unwrap(); if offered > 0 { return (c["id"].as_str().unwrap().to_string(), o); } } from = list["next_from"].clone(); assert!(!from.is_null(), "a copy whose original is offered"); } } #[test] fn a_photo_and_its_copy_never_both_go_at_bin_or_at_delete() { let lib = library(&Options { items: 12_000, others: true, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let (copy, orig) = a_pair(&mut ix, now); call(&mut ix, "albums.bin.move", json!({ "ids": [copy], "count": 1 }), now + 1); // the original is now not offered as an original, and cannot follow its copy let r = call(&mut ix, "albums.bin.move", json!({ "ids": [orig], "count": 1 }), now + 2); assert_eq!(r["pairs"], json!([{ "id": orig, "other": copy, "line": words::PAIR_LINE }])); assert!(r["undo"].is_null() && !ix.mark(&orig).in_bin()); // both in one act: neither goes, both shown call(&mut ix, "albums.bin.bring_back", json!({ "ids": [copy], "count": 1 }), now + 3); let r = call(&mut ix, "albums.bin.move", json!({ "ids": [copy, orig], "count": 2 }), now + 4); assert_eq!(r["pairs"].as_array().unwrap().len(), 2); assert!(!ix.mark(©).in_bin() && !ix.mark(&orig).in_bin()); // both in the Bin anyway (a relation found after both were binned): the copy is // kept back, whichever was planned first, and the original may go put_mark(&ix, &orig, Chosen::Bin { at_ms: now }, "", "chosen").unwrap(); put_mark(&ix, ©, Chosen::Bin { at_ms: now }, "", "chosen").unwrap(); let plan = delete_all(&mut ix, now + 5); assert_eq!(plan["held_back"]["items"], json!([{ "id": copy, "reason": "original_binned", "line": words::held_reason("original_binned") }])); assert_eq!(asked_of(&plan), vec![orig.clone()]); assert!(matches!(ix.mark(©), Mark::Keep { .. }), "kept back: kept, and no longer a copy in the Bin"); assert!(ix.mark(&orig).handed()); counts_hold(&ix); } #[test] fn a_copy_whose_original_is_gone_is_kept_back_with_its_reason() { // H2: the mark says copy:; the original went in another app let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); call(&mut ix, "albums.library.take", json!({ "items": [screenshot("orig", 1_000_000, None, 2_000_000), screenshot("copy", 2_000_000, None, 300_000)] }), 0); call(&mut ix, "albums.bin.move", json!({ "ids": ["copy"], "count": 1 }), 1); put_mark(&ix, "copy", Chosen::Bin { at_ms: 1 }, "", "copy:orig").unwrap(); for t in ["g1", "g2"] { call(&mut ix, "albums.library.take", json!({ "removed": ["orig"], "token": t }), 2); } assert!(!ix.present("orig")); assert!(ix.mark("copy").in_bin(), "absence alone changes no mark (rule A)"); let plan = delete_all(&mut ix, 3); assert!(plan["platform"].is_null(), "his only copy is never handed to the phone"); assert_eq!(plan["held_back"]["items"][0]["line"], "Kept: its original is gone."); let (m, why, _) = ix.mark_row("copy"); assert!(matches!(m, Mark::Keep { .. }) && why.is_empty(), "kept, and its why cleared so it stops being a copy"); // and its original trashed (Android) holds it back the same way call(&mut ix, "albums.library.take", json!({ "items": [screenshot("o2", 3_000_000, None, 2_000_000), screenshot("c2", 4_000_000, None, 300_000)] }), 4); call(&mut ix, "albums.bin.move", json!({ "ids": ["c2"], "count": 1 }), 5); put_mark(&ix, "c2", Chosen::Bin { at_ms: 5 }, "", "copy:o2").unwrap(); call(&mut ix, "albums.library.take", json!({ "items": [trashed(screenshot("o2", 3_000_000, None, 2_000_000))] }), 6); let plan = delete_all(&mut ix, 7); assert_eq!(plan["held_back"]["items"][0]["reason"], "original_trashed"); counts_hold(&ix); } #[test] fn a_part_keeps_its_own_choice_and_loses_its_link_when_its_main_goes() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let at = 1_700_000_000_000; call(&mut ix, "albums.library.take", json!({ "items": [screenshot("img", at, Some("DCIM/Camera/IMG_1.jpg"), 3_000_000)] }), 0); call(&mut ix, "albums.keep", json!({ "ids": ["img"], "count": 1 }), 1); // he saves an edit: the original becomes its part call(&mut ix, "albums.library.take", json!({ "items": [screenshot("edit", at + 300, Some("DCIM/Camera/IMG_1-edited.jpg"), 3_100_000)] }), 2); assert!(ix.is_part("img")); let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 3); assert_eq!(l["groups"][0]["items"][0]["size"], words::size(3_100_000, true), "a kept part is not counted with its main"); call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": 1 }), 3); work(&mut ix, 3); assert!(matches!(ix.mark("img"), Mark::Keep { .. }), "binning the edit never turns his Keep into Bin"); let bin = call(&mut ix, "albums.bin", json!({}), 4); assert_eq!(bin["kept_parts"], words::kept_parts(1)); let plan = delete_all(&mut ix, 5); assert_eq!(asked_of(&plan), vec!["edit".to_string()]); settle(&mut ix, &plan, |_| "trashed", 6); assert!(!ix.is_part("img"), "the link goes with its main"); assert!(matches!(ix.mark("img"), Mark::Keep { .. })); counts_hold(&ix); } #[test] fn keep_on_something_in_the_bin_brings_it_back_in_one_act_and_undo_returns_it() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); call(&mut ix, "albums.library.take", json!({ "items": [screenshot("a", 1_000_000, None, 2_000_000), screenshot("b", 9_000_000, None, 2_000_000)] }), 0); let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 0); let bin = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": 2 }), 1); work(&mut ix, 1); let k = call(&mut ix, "albums.keep", json!({ "ids": ["a"], "count": 1 }), 2); assert_eq!(k["after"], words::from_bin(1)); assert_eq!(bin_count(&mut ix, 2), 1); // the older act cannot be undone under the newer one assert_eq!(refused(&mut ix, "albums.undo", json!({ "token": bin["undo"]["token"] }), 3), "later"); call(&mut ix, "albums.undo", json!({ "token": k["undo"]["token"] }), 3); assert_eq!(bin_count(&mut ix, 3), 2, "undo puts it back in the Bin"); call(&mut ix, "albums.undo", json!({ "token": bin["undo"]["token"] }), 4); assert!(call(&mut ix, "albums.bin", json!({}), 4)["empty"].is_object()); // after Delete, undo says so let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 5); let again = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": 2 }), 5); work(&mut ix, 5); let plan = delete_all(&mut ix, 6); settle(&mut ix, &plan, |_| "absent", 7); let e = answer(&mut ix, "albums.undo", &with_request("albums.undo", json!({ "token": again["undo"]["token"] })), 8).err().unwrap(); assert_eq!((e.code.as_str(), e.message.as_str()), ("deleted", words::UNDO_DELETED)); counts_hold(&ix); } #[test] fn a_handed_photo_is_touched_by_nothing_until_the_library_is_read() { // M1: handed is a state; only a read of the library settles it let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..5).map(|i| screenshot(&format!("s{i}"), 1_000_000 * (i + 1), None, 1_000_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); let binned = bin_all(&mut ix, "screenshots", 1); let plan = delete_all(&mut ix, 2); let asked = asked_of(&plan); assert_eq!(asked.len(), 5); assert!(asked.iter().all(|id| ix.mark(id).handed())); assert_eq!(call(&mut ix, "albums.waiting", json!({}), 2)["count"], 5); // while the dialog is up: every act refuses them assert_eq!(refused(&mut ix, "albums.bin.bring_back", json!({ "ids": ["s0"], "count": 1 }), 3), "handed"); assert_eq!(refused(&mut ix, "albums.keep", json!({ "ids": ["s0"], "count": 1 }), 3), "handed"); assert_eq!(refused(&mut ix, "albums.bin.move", json!({ "ids": ["s0"], "count": 1 }), 3), "handed"); assert_eq!(refused(&mut ix, "albums.bin.delete", json!({ "ids": ["s0"], "count": 1, "token": 0 }), 3), "handed"); assert_eq!(refused(&mut ix, "albums.undo", json!({ "token": binned["act_id"] }), 3), "handed"); let bin = call(&mut ix, "albums.bin", json!({}), 3); assert_eq!(bin["count"], 0, "handed photos are not in the Bin"); assert_eq!(bin["waiting"], words::waiting_line(5)); // platform.done only asks for the read; it never says what happened assert_eq!(refused(&mut ix, "albums.platform.done", json!({}), 3), "bad_request", "no act id"); let read = call(&mut ix, "albums.platform.done", json!({ "act_id": plan["platform"]["act_id"] }), 3); assert_eq!(strs(&read["read"]).len(), 5); assert!(asked.iter().all(|id| ix.mark(id).handed()), "nothing settled by platform.done"); // the read: two still in the library (the dialog was refused for them), three gone let settled = settle(&mut ix, &plan, |id| if id == "s0" || id == "s1" { "present" } else { "absent" }, 4); assert_eq!((settled["freed"].as_u64(), settled["back"].as_u64()), (Some(3), Some(2))); assert_eq!(settled["not_done"], words::not_freed(2)); assert!(ix.mark("s0").in_bin() && matches!(ix.mark("s4"), Mark::Freed { .. })); assert_eq!(bin_count(&mut ix, 4), 2); assert_eq!(call(&mut ix, "albums.waiting", json!({}), 4)["count"], 0); assert_eq!(refused(&mut ix, "albums.platform.done", json!({ "act_id": plan["platform"]["act_id"] }), 5), "gone"); counts_hold(&ix); } #[test] fn a_kill_anywhere_in_a_delete_is_healed_by_the_next_read() { let dir = tempfile::tempdir().unwrap(); let path = Index::path_in(dir.path()); let mut ix = Index::open(&path).unwrap(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..4).map(|i| screenshot(&format!("s{i}"), 1_000_000 * (i + 1), None, 1_000_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); bin_all(&mut ix, "screenshots", 1); // killed after the tap, before any planning: the act waits and the next work carries it on let bin = call(&mut ix, "albums.bin", json!({}), 2); call(&mut ix, "albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] }), 2); drop(ix); let mut ix = Index::open(&path).unwrap(); let plan = work(&mut ix, 3); assert_eq!(asked_of(&plan).len(), 4); // killed after the phone deleted, before platform.done: albums.waiting says what to read drop(ix); let mut ix = Index::open(&path).unwrap(); let w = call(&mut ix, "albums.waiting", json!({}), 4); assert_eq!(w["count"], 4); let act = w["acts"][0]["act_id"].clone(); let states: Vec = strs(&w["acts"][0]["read"]).iter().map(|id| json!({ "id": id, "state": "absent" })).collect(); call(&mut ix, "albums.library.take", json!({ "act_id": act, "states": states, "complete": true }), 5); assert_eq!(call(&mut ix, "albums.waiting", json!({}), 5)["count"], 0); assert_eq!(ix.count("SELECT count(*) FROM mark WHERE state = 'freed'"), 4); refused_or_skip(&mut ix, "s0", 6); counts_hold(&ix); } #[test] fn the_same_request_again_answers_the_first_answer_and_writes_nothing() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); call(&mut ix, "albums.library.take", json!({ "items": [screenshot("a", 1_000_000, None, 2_000_000), screenshot("b", 2_000_000, None, 2_000_000)] }), 0); let r = json!({ "ids": ["a"], "count": 1, "request_id": "4f1c-tap" }); let first = call(&mut ix, "albums.bin.move", r.clone(), 1); let acts = ix.count("SELECT count(*) FROM act"); let again = call(&mut ix, "albums.bin.move", r.clone(), 2); let mut again = again; assert_eq!(again.as_object_mut().unwrap().remove("replayed"), Some(json!(true)), "a replay says it is one"); assert_eq!(first, again); assert_eq!(ix.count("SELECT count(*) FROM act"), acts, "a replayed act writes no second act"); call(&mut ix, "albums.undo", json!({ "token": first["undo"]["token"] }), 3); assert_eq!(ix.mark("a"), Mark::None, "and Undo is not blocked by a twin"); // a replayed Delete never makes a second waiting act call(&mut ix, "albums.bin.move", json!({ "ids": ["b"], "count": 1 }), 4); let bin = call(&mut ix, "albums.bin", json!({}), 4); let d = json!({ "all": true, "token": bin["token"], "count": bin["count"], "request_id": "9e2a-delete" }); let t1 = call(&mut ix, "albums.bin.delete", d.clone(), 4); let t2 = call(&mut ix, "albums.bin.delete", d.clone(), 5); assert_eq!(t2["replayed"], true); assert_eq!(t1["job"], t2["job"]); assert_eq!(ix.count("SELECT count(*) FROM act WHERE kind = 'free'"), 1); // an act without one is refused; one id for two methods is refused assert_eq!(answer(&mut ix, "albums.keep", &json!({ "ids": ["a"], "count": 1 }), 6).err().unwrap().code, "bad_request"); assert_eq!(refused(&mut ix, "albums.keep", json!({ "ids": ["a"], "count": 1, "request_id": "4f1c-tap" }), 6), "bad_request"); } #[test] fn bin_all_and_delete_refuse_a_set_that_grew_and_delete_one_that_shrank() { // M2: a binned photo back in the library joins with a new number, so it is never taken unseen let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..4).map(|i| screenshot(&format!("s{i}"), 1_000_000 * (i + 1), None, 1_000_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": items.clone() }), 0); bin_all(&mut ix, "screenshots", 1); for t in ["a", "b"] { call(&mut ix, "albums.library.take", json!({ "removed": ["s3"], "token": t }), 2); } let bin = call(&mut ix, "albums.bin", json!({}), 3); assert_eq!(bin["count"], 3); call(&mut ix, "albums.library.take", json!({ "items": [items[3].clone()] }), 4); // grew: refused at the tap let r = json!({ "all": true, "token": bin["token"], "count": bin["count"] }); assert_eq!(refused(&mut ix, "albums.bin.delete", r, 5), "changed"); // shrank: refused too (a Delete takes exactly what he saw) let bin = call(&mut ix, "albums.bin", json!({}), 6); call(&mut ix, "albums.bin.bring_back", json!({ "ids": ["s0"], "count": 1 }), 7); let tap = answer(&mut ix, "albums.bin.delete", &with_request("albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] })), 8); match tap { Err(e) => assert_eq!(e.code, "changed"), Ok(_) => assert_eq!(work(&mut ix, 8)["changed"], words::CHANGED), } assert_eq!(ix.count("SELECT count(*) FROM mark WHERE state = 'handed'"), 0, "nothing handed"); // Bin all on a list that grew since he looked: refused call(&mut ix, "albums.library.take", json!({ "items": [screenshot("n0", 5_000_000, None, 1_000_000)] }), 9); let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 9); call(&mut ix, "albums.library.take", json!({ "items": [screenshot("n1", 6_000_000, None, 1_000_000)] }), 10); assert_eq!(refused(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": l["bin_all"]["count"] }), 10), "changed"); counts_hold(&ix); } #[test] fn a_mark_follows_a_new_id_only_by_its_exact_cloud_id() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let mut a = screenshot("old-a", 1_000_000, None, 1_000_000); a.cloud_id = Some("cloud-1".into()); let b = screenshot("old-b", 2_000_000, None, 1_000_000); call(&mut ix, "albums.library.take", json!({ "items": [a.clone(), b.clone()] }), 0); call(&mut ix, "albums.keep", json!({ "ids": ["old-a", "old-b"], "count": 2 }), 1); for t in ["x", "y"] { call(&mut ix, "albums.library.take", json!({ "removed": ["old-a", "old-b"], "token": t }), 2); } let mut a2 = a.clone(); a2.id = "new-a".into(); let mut b2 = b.clone(); b2.id = "new-b".into(); call(&mut ix, "albums.library.take", json!({ "items": [a2, b2] }), 3); assert!(matches!(ix.mark("new-a"), Mark::Keep { .. }), "the same cloud id: his Keep follows"); assert_eq!(ix.mark("new-b"), Mark::None, "no cloud id: never applied to a new id"); assert!(matches!(ix.mark("old-b"), Mark::Keep { .. }), "it stays on the old id"); counts_hold(&ix); } #[test] fn only_the_cores_free_plan_can_hand_a_photo_or_make_a_platform_list() { // decision M-b by type: Mark::Handed carries a Seal and PlatformList has // private fields, both in cotton-core, made only by its free_plan (the // core's compile_fail doctests prove neither can be built outside it). // Here: this app never tries, and writes marks only inside `handing`. let src = include_str!("albums_app.rs"); assert!(!src.contains("Seal("), "no seal is made here"); assert!(!src.contains("free_batches("), "no platform list is made here"); let outside = &src[..src.find("mod handing {").expect("the handing module")]; assert!(!outside.contains("INSERT INTO mark"), "marks are written only inside handing"); let module = &src[src.find("mod handing {").unwrap()..]; assert!(!module.contains("pub(super) fn write("), "writing any Mark stays private to handing"); } #[test] fn an_id_that_now_names_another_photo_is_a_new_unmarked_photo() { // tier one: a restored backup or a rebuilt MediaStore gives id 4812 to a photo added on another day let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "android", "permission": "full", "library": "ms-1" }), 0); call(&mut ix, "albums.library.take", json!({ "items": [screenshot("4812", 1_000_000, None, 2_000_000), screenshot("o", 2_000_000, None, 2_000_000)] }), 0); call(&mut ix, "albums.bin.move", json!({ "ids": ["4812"], "count": 1 }), 1); assert_eq!(bin_count(&mut ix, 1), 1); let other = screenshot("4812", 9_000_000, None, 640_000); let r = call(&mut ix, "albums.library.take", json!({ "items": [other] }), 2); assert_eq!(r["renamed"], 1); assert_eq!(ix.mark("4812"), Mark::None, "the new photo carries no choice"); assert_eq!(ix.count("SELECT count(*) FROM mark WHERE id LIKE '4812#retired-%' AND state = 'bin'"), 1, "the choice stays with the old photo"); let bin = call(&mut ix, "albums.bin", json!({}), 2); assert!(bin["empty"].is_object(), "nothing of either photo in the Bin, not even under No longer on this phone: {bin}"); // You counts it, and he clears it when he says let you = call(&mut ix, "albums.you", json!({}), 3); assert_eq!(you["gone"]["line"], words::retired(1)); assert_eq!(refused(&mut ix, "albums.you.clear_gone", json!({ "count": 2 }), 3), "changed"); call(&mut ix, "albums.you.clear_gone", json!({ "count": 1 }), 3); assert!(call(&mut ix, "albums.you", json!({}), 3)["gone"].is_null()); counts_hold(&ix); } #[test] fn an_edit_is_the_same_photo_a_keep_stays_and_a_binned_one_waits_for_his_look() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full", "library": "ms-1" }), 0); let (k, b) = (screenshot("k", 1_000_000, None, 2_000_000), screenshot("b", 2_000_000, None, 2_100_000)); call(&mut ix, "albums.library.take", json!({ "items": [k.clone(), b.clone()] }), 0); call(&mut ix, "albums.keep", json!({ "ids": ["k"], "count": 1 }), 1); call(&mut ix, "albums.bin.move", json!({ "ids": ["b"], "count": 1 }), 1); // he crops k (pixel size and size change) and changes b's date (Adjust Date; Android rewrites SIZE) let mut k2 = k.clone(); (k2.width, k2.height, k2.bytes, k2.modified) = (1000, 1800, Some(900_000), Some(2)); let mut b2 = b.clone(); (b2.taken_at_ms, b2.bytes, b2.modified) = (1_500_000, Some(2_200_000), Some(2)); let r = call(&mut ix, "albums.library.take", json!({ "items": [k2, b2] }), 2); assert_eq!((r["renamed"].as_u64(), r["edited"].as_u64()), (Some(0), Some(2))); assert!(matches!(ix.mark("k"), Mark::Keep { .. }), "keeping is always safe"); assert!(ix.mark("b").in_bin(), "still in the Bin"); assert_eq!(ix.count("SELECT count(*) FROM mark WHERE id LIKE '%#retired-%'"), 0); let bin = call(&mut ix, "albums.bin", json!({}), 2); let g = &bin["groups"][0]; assert_eq!((g["heading"].as_str(), g["bin_again"].as_str()), (Some(words::EDITED_HEADING), Some(words::BIN_AGAIN))); assert_eq!(strs(&g["ids"]), ["b"]); // Delete holds it back, in the Bin, with the reason let plan = delete_all(&mut ix, 3); assert!(plan["platform"].is_null()); assert_eq!(plan["held_back"]["items"][0]["line"], words::held_reason("edited_since_binned")); assert!(ix.mark("b").in_bin()); // he looks again and bins it again: now Delete may take it call(&mut ix, "albums.bin.move", json!({ "ids": ["b"], "count": 1 }), 4); assert!(!super::edited(&ix, "b")); assert_eq!(asked_of(&delete_all(&mut ix, 5)), ["b"]); counts_hold(&ix); } #[test] fn facts_that_arrive_later_fill_in_and_an_unknown_never_hides_a_change() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); // Android first sends 0 for the size and no SIZE, and fills them in later let mut f = screenshot("f", 1_000_000, None, 2_000_000); (f.width, f.height, f.bytes) = (0, 0, None); call(&mut ix, "albums.library.take", json!({ "items": [f] }), 0); call(&mut ix, "albums.bin.move", json!({ "ids": ["f"], "count": 1 }), 1); let r = call(&mut ix, "albums.library.take", json!({ "items": [screenshot("f", 1_000_000, None, 2_000_000)] }), 2); assert_eq!(r["edited"], 0, "a fill-in is not a change"); assert!(!super::edited(&ix, "f")); // A -> unknown -> B: the stored A is kept through the unknown, so B is seen let mut unknown = screenshot("f", 1_000_000, None, 0); unknown.bytes = None; assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [unknown] }), 3)["edited"], 0); assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [screenshot("f", 1_000_000, None, 2_400_000)] }), 4)["edited"], 1); assert!(super::edited(&ix, "f"), "held for his look"); assert!(delete_all(&mut ix, 5)["platform"].is_null(), "held for his look"); counts_hold(&ix); } #[test] fn on_android_a_read_with_no_identity_facts_proves_nothing_and_nothing_is_handed() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "android", "permission": "full", "library": "ms-1" }), 0); let mut n = screenshot("n", 5_000_000, None, 1_000_000); call(&mut ix, "albums.library.take", json!({ "items": [n.clone()] }), 0); call(&mut ix, "albums.bin.move", json!({ "ids": ["n"], "count": 1 }), 1); (n.added_ms, n.generation_added) = (None, None); call(&mut ix, "albums.library.take", json!({ "items": [n] }), 2); assert!(!ix.verified("n"), "unverified"); assert_eq!(call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 2)["count"].as_u64().unwrap_or(0), 0, "offered nowhere"); let bin = call(&mut ix, "albums.bin", json!({}), 2); assert!(bin["act"].is_null(), "and Android is never offered Delete"); counts_hold(&ix); } #[test] fn a_new_library_rechecks_every_id_by_identity_and_suspends_only_what_it_cannot_find() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "android", "permission": "full", "library": "ms-1" }), 0); let mut a = screenshot("a", 1_000_000, None, 2_000_000); a.cloud_id = Some("cloud-a".into()); let mut b = screenshot("b", 2_000_000, None, 2_100_000); b.generation_added = Some(5); let c = screenshot("c", 3_000_000, None, 2_200_000); let (u, z) = (screenshot("u", 4_000_000, None, 900_000), screenshot("z", 5_000_000, None, 800_000)); call(&mut ix, "albums.library.take", json!({ "items": [a.clone(), b.clone(), c.clone(), u.clone(), z.clone()] }), 0); call(&mut ix, "albums.bin.move", json!({ "ids": ["a", "b"], "count": 2 }), 1); call(&mut ix, "albums.keep", json!({ "ids": ["c"], "count": 1 }), 1); // an Android update: the MediaStore version changed let s = call(&mut ix, "albums.start", json!({ "platform": "android", "permission": "full", "library": "ms-2" }), 2); assert_eq!(s["rechecking"], true); let bin = call(&mut ix, "albums.bin", json!({}), 2); assert_eq!(bin["count"], 0, "nothing in the Bin, nothing freeable"); assert_eq!(bin["rechecking"], words::RECHECKING); assert!(bin["other_library"].is_null(), "not yet: the full read decides"); assert_eq!(call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 2)["count"].as_u64().unwrap_or(0), 0, "nothing unverified is offered"); // the full read: b the same photo (its generation is not comparable across // versions), c's id now another photo, a under a new id with its cloud id, u the same let mut b2 = b.clone(); b2.generation_added = Some(900); let mut c2 = screenshot("c", 7_000_000, None, 500_000); c2.added_ms = Some(7_000_000); let mut a2 = a.clone(); a2.id = "91".into(); a2.added_ms = Some(91); call(&mut ix, "albums.library.take", json!({ "items": [a2, b2, c2, u.clone()], "library": "ms-2" }), 3); assert!(ix.mark("b").in_bin() && ix.mark("91").in_bin(), "re-matched by identity and by cloud id"); assert_eq!(ix.mark("c"), Mark::None, "another photo starts clean"); assert!(ix.verified("u") && !ix.verified("z"), "z not read again yet"); // z, unmarked and not read again, can be neither binned nor handed call(&mut ix, "albums.bin.move", json!({ "ids": ["z"], "count": 1 }), 4); assert_eq!(ix.mark("z"), Mark::None); assert_eq!(bin_count(&mut ix, 4), 2); // the sweep that ends the full read: what it did not re-match is from another library for (t, now) in [("t1", 5), ("t2", 6)] { call(&mut ix, "albums.library.take", json!({ "all_ids": ["91", "b", "c", "u"], "complete": true, "token": t }), now); } let bin = call(&mut ix, "albums.bin", json!({}), 7); assert!(bin["rechecking"].is_null()); assert_eq!(bin["other_library"]["count"], 1, "c's Keep, its photo never found"); call(&mut ix, "albums.bin.clear_other", json!({ "count": 1 }), 8); counts_hold(&ix); } #[test] fn a_copy_whose_original_id_now_names_another_photo_is_kept_back() { let (_d, mut ix) = index(); let lib = library(&Options { items: 12_000, others: true, ..Options::default() }); let now = load(&mut ix, &lib, "ios"); let (copy, original) = a_pair(&mut ix, now); call(&mut ix, "albums.bin.move", json!({ "ids": [copy.clone()], "count": 1 }), now + 1); assert_eq!(ix.mark_row(©).1, format!("copy:{original}")); // the original's id now names a photo added another day let mut other = ix.item(&original).unwrap(); other.added_ms = Some(other.added_ms.unwrap_or(0) + 86_400_000); other.taken_at_ms += 86_400_000; assert_eq!(call(&mut ix, "albums.library.take", json!({ "items": [other] }), now + 2)["renamed"], 1); assert!(ix.mark_row(©).1.starts_with(&format!("copy:{original}#retired-")), "the copy's original is the retired photo"); let bin = call(&mut ix, "albums.bin", json!({}), now + 3); let ids: Vec = strs(&bin["groups"][0]["ids"]); let plan = delete_all(&mut ix, now + 3); assert!(!asked_of(&plan).contains(©), "never handed as a copy of a photo that is not its original"); assert!(ids.contains(©)); assert!(matches!(ix.mark(©), Mark::Keep { .. }), "kept: its original is gone"); counts_hold(&ix); } #[test] fn under_limited_access_delete_is_not_offered_and_a_waiting_delete_says_why() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..3).map(|i| screenshot(&format!("s{i}"), 1_000_000 * (i + 1), None, 1_000_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); bin_all(&mut ix, "screenshots", 1); let plan = delete_all(&mut ix, 2); // he narrows access to chosen photos while the dialog is up call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "limited", "chosen": 3 }), 3); let settled = settle(&mut ix, &plan, |_| "absent", 3); assert_eq!(settled["freed"], 0); assert_eq!(settled["unsure"]["why"], "needs_full_access", "the screen can offer full access"); assert_eq!(call(&mut ix, "albums.waiting", json!({}), 3)["count"], 3, "still handed, still listed"); // nothing more is offered to delete under limited access call(&mut ix, "albums.library.take", json!({ "items": [screenshot("t", 9_000_000, None, 1_000_000)] }), 4); call(&mut ix, "albums.bin.move", json!({ "ids": ["t"], "count": 1 }), 4); let bin = call(&mut ix, "albums.bin", json!({}), 4); assert!(bin["act"].is_null()); assert_eq!(bin["needs_full_access"]["line"], words::DELETE_NEEDS_FULL); assert_eq!(refused(&mut ix, "albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] }), 4), "needs_full_access"); // with full access and a complete read it settles call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 5); let w = call(&mut ix, "albums.waiting", json!({}), 5); let act = w["acts"][0]["act_id"].clone(); let states: Vec = strs(&w["acts"][0]["read"]).iter().map(|id| json!({ "id": id, "state": "absent" })).collect(); let partial = call(&mut ix, "albums.library.take", json!({ "act_id": act, "states": states }), 6)["settled"].clone(); assert_eq!(partial["unsure"]["why"], "not_complete"); call(&mut ix, "albums.library.take", json!({ "act_id": act, "states": states, "complete": true }), 7); assert_eq!(call(&mut ix, "albums.waiting", json!({}), 7)["count"], 0); counts_hold(&ix); } #[test] fn a_request_is_answered_once_a_passing_refusal_is_not_kept_and_old_ones_are_pruned() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..3).map(|i| screenshot(&format!("s{i}"), 1_000_000 * (i + 1), None, 1_000_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); // a refusal is stored: the same id again is refused the same way, even once it would pass let r = json!({ "ids": ["s0"], "count": 2, "request_id": "r-refused" }); assert_eq!(refused(&mut ix, "albums.bin.move", r.clone(), 1), "changed"); assert_eq!(refused(&mut ix, "albums.bin.move", r, 2), "changed"); // a passing refusal is not: Undo while the act is still being worked on, then again let list = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 3); let all = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": list["token"], "count": list["count"] }), 3); let undo = json!({ "token": all["undo"]["token"], "request_id": "r-undo" }); assert_eq!(refused(&mut ix, "albums.undo", undo.clone(), 4), "busy"); work(&mut ix, 5); call(&mut ix, "albums.undo", undo, 6); assert_eq!(bin_count(&mut ix, 6), 0, "the retried Undo ran"); // a replay after Undo is marked as one, never said as if current let m = call(&mut ix, "albums.bin.move", json!({ "ids": ["s0"], "count": 1, "request_id": "r-move" }), 7); call(&mut ix, "albums.undo", json!({ "token": m["undo"]["token"] }), 8); let again = call(&mut ix, "albums.bin.move", json!({ "ids": ["s0"], "count": 1, "request_id": "r-move" }), 9); assert_eq!(again["replayed"], true); assert_eq!(ix.mark("s0"), Mark::None, "the replay changed nothing"); // answered ids older than 30 days go, a few at a time let old = 10 + 31 * 86_400_000; for i in 0..120 { ix.conn.execute("INSERT INTO request (id, method, answer, at) VALUES (?1, 'albums.keep', '{}', 0)", [format!("old-{i}")]).unwrap(); } call(&mut ix, "albums.keep", json!({ "ids": ["s1"], "count": 1 }), old); assert_eq!(ix.count("SELECT count(*) FROM request WHERE id LIKE 'old-%'"), 70, "50 pruned per act, bounded"); } #[test] fn deleting_15000_picked_ids_is_one_act_row_in_the_tap_and_slices_after() { let (_d, mut ix) = index_on_fast_disk(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let n = 15_000usize; ix.conn.execute_batch("BEGIN").unwrap(); for i in 0..n { let it = screenshot(&format!("s{i}"), 1_000_000_000 + i as i64 * 1_000, None, 1_500_000); ix.conn.execute("INSERT INTO item (id, taken, kind, w, h, bytes, meta, state, fp, ident) VALUES (?1, ?2, 'photo', 1170, 2532, 1500000, ?3, 'present', ?4, ?5)", rusqlite::params![it.id, it.taken_at_ms, serde_json::to_string(&it).unwrap(), super::content(&it), super::identity(&it)]).unwrap(); ix.conn.execute("INSERT INTO mark (id, mark, state, at, act, why, seq, fp) VALUES (?1, ?2, 'bin', 5, '', 'screenshots', ?3, ?4)", rusqlite::params![it.id, serde_json::to_string(&Mark::Bin { at_ms: 5 }).unwrap(), i as i64 + 1, super::content(&it)]).unwrap(); } ix.conn.execute("INSERT OR REPLACE INTO kv (k, v) VALUES ('seq', ?1)", [n.to_string()]).unwrap(); rebuild_tally(&ix).unwrap(); ix.conn.execute_batch("COMMIT").unwrap(); let bin = call(&mut ix, "albums.bin", json!({}), 1); let ids: Vec = (0..n).map(|i| format!("s{i}")).collect(); // the request as the shell sends it, made before the clock starts let request = with_request("albums.bin.delete", json!({ "ids": ids, "count": n, "token": bin["token"] })); let t = std::time::Instant::now(); answer(&mut ix, "albums.bin.delete", &request, 2).unwrap(); let tap = t.elapsed(); assert!(tap.as_millis() < 50, "Delete of {n} picked ids: the tap in {tap:?} (debug build)"); let (mut slices, mut worst) = (0, std::time::Duration::ZERO); let plan = loop { let t = std::time::Instant::now(); let w = call(&mut ix, "albums.work", json!({}), 3); worst = worst.max(t.elapsed()); slices += 1; if w["finished"] == true { break w; } }; println!("Delete of {n} picked ids: tap {tap:?}; {slices} albums.work slices of {}, the slowest {worst:?} (debug build, tmpfs)", super::WORK_BUDGET); assert_eq!(asked_of(&plan).len(), n); assert!(worst.as_millis() < 3_000, "a slice in {worst:?}"); } #[test] fn the_taps_write_one_act_row_in_under_50_ms_at_15000_and_64000() { for n in [15_000usize, 64_000] { let (_d, mut ix) = index_on_fast_disk(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); // n screenshots offered and n more already binned, written straight to the index ix.conn.execute_batch("BEGIN").unwrap(); for i in 0..2 * n { let it = screenshot(&format!("s{i}"), 1_000_000_000 + i as i64 * 1_000, None, 1_500_000); ix.conn.execute("INSERT INTO item (id, taken, kind, w, h, bytes, meta, state, fp, ident) VALUES (?1, ?2, 'photo', 1170, 2532, 1500000, ?3, 'present', ?4, ?5)", rusqlite::params![it.id, it.taken_at_ms, serde_json::to_string(&it).unwrap(), super::content(&it), super::identity(&it)]).unwrap(); if i < n { ix.conn.execute("INSERT INTO offer (id, list, bytes, exact, taken, sub, seq) VALUES (?1, 'screenshots', 1500000, 1, ?2, '', ?3)", rusqlite::params![it.id, it.taken_at_ms, i as i64 + 1]).unwrap(); } else { ix.conn.execute("INSERT INTO mark (id, mark, state, at, act, why, seq, fp) VALUES (?1, ?2, 'bin', 5, '', 'screenshots', ?3, ?4)", rusqlite::params![it.id, serde_json::to_string(&Mark::Bin { at_ms: 5 }).unwrap(), i as i64 + 1, super::content(&it)]).unwrap(); } } ix.conn.execute("INSERT OR REPLACE INTO kv (k, v) VALUES ('seq', ?1)", [(2 * n).to_string()]).unwrap(); rebuild_tally(&ix).unwrap(); ix.conn.execute_batch("COMMIT").unwrap(); let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 1); assert_eq!(l["count"], n); let t = std::time::Instant::now(); let r = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": l["bin_all"]["count"] }), 2); assert!(t.elapsed().as_millis() < 50, "Bin all of {n}: the tap in {:?} (debug build)", t.elapsed()); assert!(r["job"]["act_id"].is_string()); let w = work(&mut ix, 3); assert_eq!(w["finished"], true); let bin = call(&mut ix, "albums.bin", json!({}), 4); assert_eq!(bin["count"], 2 * n); let t = std::time::Instant::now(); call(&mut ix, "albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] }), 5); assert!(t.elapsed().as_millis() < 50, "Delete of {}: the tap in {:?} (debug build)", 2 * n, t.elapsed()); let plan = work(&mut ix, 6); assert_eq!(asked_of(&plan).len(), 2 * n); assert_eq!(ix.count("SELECT count(*) FROM act"), 2, "Bin all, Delete: one act row each"); counts_hold(&ix); } } #[test] fn bin_all_of_15000_runs_off_the_tap_and_a_snapshot_skips_what_changed() { let (_d, mut ix) = index_on_fast_disk(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec = (0..15_000).map(|i| screenshot(&format!("s{i}"), 1_000_000_000 + i * 600_000, None, 1_500_000)).collect(); for chunk in items.chunks(5_000) { call(&mut ix, "albums.library.take", json!({ "items": chunk }), 0); } let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 1); assert_eq!(l["count"], 15_000); assert_eq!(l["groups"][0]["items"].as_array().unwrap().len(), 60, "a page, never the whole list"); // while he looks: one is kept elsewhere (the list shrank; new arrivals come after his snapshot) call(&mut ix, "albums.keep", json!({ "ids": ["s7"], "count": 1 }), 2); let t = std::time::Instant::now(); call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": l["bin_all"]["count"] }), 3); assert!(t.elapsed().as_millis() < 50, "the tap writes one act row ({:?}, debug build)", t.elapsed()); let fresh: Vec = (0..3).map(|i| screenshot(&format!("new{i}"), 2_000_000_000_000 + i, None, 1_500_000)).collect(); call(&mut ix, "albums.library.take", json!({ "items": fresh }), 3); let w = work(&mut ix, 4); assert_eq!(w["after"]["skipped"], words::skipped(1)); assert_eq!(call(&mut ix, "albums.work", json!({}), 5)["idle"], true); assert_eq!(bin_count(&mut ix, 5), 14_999); assert!((0..3).all(|i| ix.mark(&format!("new{i}")) == Mark::None), "what arrived after he looked is not binned"); assert_eq!(ix.count("SELECT count(*) FROM act"), 2, "keep one, bin all: two act rows"); // the screens read kept counts let t = std::time::Instant::now(); call(&mut ix, "albums.tidy", json!({}), 6); call(&mut ix, "albums.bin", json!({}), 6); call(&mut ix, "albums.home", json!({}), 6); let screens = t.elapsed(); assert!(screens.as_millis() < 300, "three screens in {screens:?} (debug build)"); // opening the index is paid once a process (`call` keeps it open), never in a tap let t = std::time::Instant::now(); drop(Index::open(&ix.path).unwrap()); println!("15,000 items: three screens {screens:?}; opening the index {:?} (debug build)", t.elapsed()); counts_hold(&ix); } #[test] fn acts_carry_what_was_on_screen() { let lib = library(&Options { items: 2_000, others: true, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let list = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), now); let ids = strs(&list["groups"][0]["items"].as_array().unwrap().iter().map(|i| i["id"].clone()).collect::()); assert_eq!(refused(&mut ix, "albums.bin.move", json!({ "ids": ids, "count": 1 }), now), "changed"); assert_eq!(refused(&mut ix, "albums.bin.move", json!({ "ids": ids }), now), "bad_request"); assert_eq!(refused(&mut ix, "albums.bin.move", json!({ "all": true, "count": 3 }), now), "bad_request"); let m = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "ids": &ids[..3], "count": 3, "token": list["token"] }), now); assert_eq!(m["after"], words::moved_after(3)); let again = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "ids": &ids[..3], "count": 3, "token": list["token"] }), now); assert_eq!(again["skipped"], words::skipped(3), "already binned: skipped, never binned twice"); assert_eq!(ix.count("SELECT count(*) FROM act"), 1, "an act that moved nothing leaves no row"); } #[test] fn deleting_from_the_iphone_bin_believes_only_the_library() { let lib = library(&Options { items: 3_000, others: true, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); bin_all(&mut ix, "screenshots", now); let bin = call(&mut ix, "albums.bin", json!({}), now); assert_eq!(bin["act"]["note"], words::DELETE_NOTE_IOS); let plan = delete_all(&mut ix, now); assert_eq!(plan["platform"]["act"], "delete"); assert_eq!(plan["platform"]["parts"].as_array().unwrap().len(), 1, "the iPhone asks once"); let asked = asked_of(&plan); let still = [asked[0].clone(), asked[1].clone()]; let settled = settle(&mut ix, &plan, |id| if still.iter().any(|s| s == id) { "present" } else { "absent" }, now); assert_eq!(settled["freed"], asked.len() - 2); assert_eq!(settled["not_done"], "2 weren't deleted and are still in the Bin."); assert!(call(&mut ix, "albums.bin", json!({}), now)["head"].as_str().unwrap().starts_with("2 · ")); assert_eq!(ix.count("SELECT count(*) FROM mark WHERE state = 'freed'"), asked.len() - 2); counts_hold(&ix); } #[test] fn a_raw_beside_its_jpeg_moves_with_it_and_is_never_offered_alone() { let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let at = 1_700_000_000_000; call(&mut ix, "albums.library.take", json!({ "items": [screenshot("jpg", at, Some("DCIM/Camera/IMG_1.jpg"), 3_000_000), screenshot("raw", at, Some("DCIM/Camera/IMG_1.dng"), 25_000_000)] }), 0); let l = call(&mut ix, "albums.list", json!({ "list": "screenshots" }), 0); assert_eq!(l["count"], 1, "the RAW is a part, never a rival"); assert_eq!(l["groups"][0]["items"][0]["size"], words::size(28_000_000, true)); let m = call(&mut ix, "albums.bin.move", json!({ "list": "screenshots", "all": true, "token": l["token"], "count": 1 }), 0); assert!(m.get("platform").is_none(), "marks only at bin time"); work(&mut ix, 0); let plan = delete_all(&mut ix, 1); assert_eq!(asked_of(&plan), vec!["jpg".to_string(), "raw".to_string()]); counts_hold(&ix); } #[test] fn one_old_and_one_new_change_on_64000_refresh_only_their_own_ranges() { let lib = library(&Options { items: 64_000, ..Options::default() }); let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); for chunk in lib.chunks(8_000) { let items: Vec<&Item> = chunk.iter().map(|s| &s.item).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); } assert_eq!(ix.count("SELECT count(*) FROM item"), 64_000); let mut o = lib[10].item.clone(); o.flags.push("favourite".into()); let mut n = lib[63_990].item.clone(); n.flags.push("favourite".into()); let t = std::time::Instant::now(); call(&mut ix, "albums.library.take", json!({ "items": [o, n] }), 1); let took = t.elapsed(); assert!(ix.refreshed_rows.get() < 200, "read {} rows, not the 64,000 between", ix.refreshed_rows.get()); assert!(took.as_millis() < 1_000, "{took:?} (debug build)"); let t = std::time::Instant::now(); call(&mut ix, "albums.tidy", json!({}), 2); call(&mut ix, "albums.home", json!({}), 2); assert!(t.elapsed().as_millis() < 100, "screens on 64,000 in {:?} (debug build)", t.elapsed()); } #[test] fn photos_only_in_icloud_are_counted_said_and_asked_once_more_on_wifi() { let lib = library(&Options { items: 1_000, cloud_only: 0.25, ..Options::default() }); let (_d, mut ix) = index(); let now = load(&mut ix, &lib, "ios"); let lines = call(&mut ix, "albums.pass.lines", json!({ "state": "running", "charging": true }), now); assert!(lines["cloud"].as_str().unwrap().ends_with("only in iCloud. Albums will look at them on Wi-Fi.")); assert!(call(&mut ix, "albums.pass.next", json!({ "on_wifi": false }), now)["asks"].as_array().unwrap().is_empty()); let asks = call(&mut ix, "albums.pass.next", json!({ "on_wifi": true, "limit": 1000 }), now)["asks"].as_array().unwrap().clone(); assert!(!asks.is_empty() && asks.iter().all(|a| a["network"] == true && a["px"] == 360)); let looks: Vec = asks.iter().map(|a| json!({ "id": a["id"], "grey": null, "network": true })).collect(); call(&mut ix, "albums.look.take", json!({ "looks": looks }), now + 1); assert!(call(&mut ix, "albums.pass.next", json!({ "on_wifi": true, "limit": 1000 }), now)["asks"].as_array().unwrap().is_empty()); counts_hold(&ix); } #[test] fn the_progress_line_runs_pauses_and_measures() { let lib = library(&Options { items: 2_000, ..Options::default() }); let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec<&Item> = lib.iter().map(|s| &s.item).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); let by_id: std::collections::HashMap<&str, &Synth> = lib.iter().map(|s| (s.item.id.as_str(), s)).collect(); for k in 0..4 { let asks = call(&mut ix, "albums.pass.next", json!({ "limit": 200 }), 0)["asks"].as_array().unwrap().clone(); let looks: Vec = asks.iter().map(|a| json!({ "id": a["id"], "grey": grey_json(by_id[a["id"].as_str().unwrap()]) })).collect(); call(&mut ix, "albums.look.take", json!({ "looks": looks }), 10_000 * (k + 1)); } let l = call(&mut ix, "albums.pass.lines", json!({ "state": "running", "charging": true }), 0); assert_eq!(l["head"], "Looking through 2,000 photos and videos"); assert_eq!(l["detail"], "800 done · about a minute left while charging"); let p = call(&mut ix, "albums.pass.lines", json!({ "state": "paused_battery", "charging": false }), 0); assert_eq!(p["note"], "Paused to save battery. Carries on when charging."); } #[test] fn permission_states_open_the_right_screen() { let (_d, mut ix) = index(); assert_eq!(call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "denied" }), 0)["line"], "Albums can't see your photos. Allow access in Settings to tidy your library."); let limited = call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "limited", "chosen": 212 }), 0); assert_eq!(limited["line"], "Albums can see the 212 photos you chose. To tidy the whole library, allow all photos in Settings."); assert_eq!(refused(&mut ix, "albums.start", json!({ "platform": "windows" }), 0), "bad_request"); assert_eq!(call(&mut ix, "albums.tidy", json!({}), 0)["empty"]["title"], "Nothing to tidy right now."); assert_eq!(call(&mut ix, "albums.bin", json!({}), 0)["empty"]["title"], "The Bin is empty."); } #[test] fn a_platform_print_is_never_kept_in_the_index() { let lib = library(&Options { items: 300, ..Options::default() }); let (_d, mut ix) = index(); call(&mut ix, "albums.start", json!({ "platform": "ios", "permission": "full" }), 0); let items: Vec<&Item> = lib.iter().map(|s| &s.item).collect(); call(&mut ix, "albums.library.take", json!({ "items": items }), 0); let s = lib.iter().find(|s| s.grey.is_some()).unwrap(); let print = json!({ "print": { "revision": "2", "values": [0.25, -0.5, 1.0] } }); call(&mut ix, "albums.look.take", json!({ "looks": [{ "id": s.item.id, "grey": grey_json(s), "platform": print }] }), 1); assert!(ix.look_of(&s.item.id).unwrap().platform.print.is_none(), "the print stays in the shell's own store"); assert_eq!(ix.count("SELECT count(*) FROM look WHERE print IS NOT NULL"), 0); } #[test] fn the_face_crop_is_the_cores_on_both_phones() { let (_d, mut ix) = index(); let (w, h) = (64u32, 48u32); let rgba: Vec = (0..w * h).flat_map(|i| [(i % 251) as u8, (i % 13) as u8, 7, 255]).collect(); let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b); let points: Vec = cotton_core::albums::face::TEMPLATE.iter().flat_map(|(x, y)| [(x / 2.0 + 4.0) / w as f32, (y / 2.0 + 2.0) / h as f32]).collect(); let a = call(&mut ix, "albums.face.align", json!({ "rgba": { "width": w, "height": h, "pixels": b64(&rgba) }, "points": points }), 0); let rgb: Vec = rgba.chunks(4).flat_map(|p| [p[0], p[1], p[2]]).collect(); let b = call(&mut ix, "albums.face.align", json!({ "rgb": { "width": w, "height": h, "pixels": b64(&rgb) }, "points": points }), 0); assert_eq!(a, b); assert_eq!(a["side"], 112); assert_eq!(base64::engine::general_purpose::STANDARD.decode(a["rgb"].as_str().unwrap()).unwrap().len(), 112 * 112 * 3); assert!(call(&mut ix, "albums.face.align", json!({ "rgb": { "width": w, "height": h, "pixels": b64(&rgb) }, "points": vec![0.5f32; 10] }), 0).is_null()); assert_eq!(refused(&mut ix, "albums.face.align", json!({ "rgb": { "width": w, "height": h, "pixels": b64(&rgb[..9]) }, "points": points }), 0), "bad_request"); } // ── the matrix (rule 9, decisions M-a and 1f.6): generated from the code's own // enums and method table; every cell held to the invariants, every column // shown to apply ── /// Every method has a column, or this does not compile (decision M-a): a new /// method is a build error until the matrix acts it out. const COLUMNS: [&str; 27] = [ "albums.start", "albums.library.take", "albums.pass.next", "albums.look.take", "albums.pass.lines", "albums.home", "albums.tidy", "albums.list", "albums.sets", "albums.set", "albums.set.keep", "albums.keep", "albums.bin.move", "albums.undo", "albums.bin", "albums.bin.bring_back", "albums.bin.delete", "albums.bin.clear_other", "albums.you.clear_gone", "albums.platform.done", "albums.work", "albums.waiting", "albums.you", "albums.face.align", // and what happens between and around the calls "late work", "replay", "kill and reopen", ]; const fn same_str(a: &str, b: &str) -> bool { let (a, b) = (a.as_bytes(), b.as_bytes()); if a.len() != b.len() { return false; } let mut i = 0; while i < a.len() { if a[i] != b[i] { return false; } i += 1; } true } const fn has_column(m: &str) -> bool { let mut i = 0; while i < COLUMNS.len() { if same_str(COLUMNS[i], m) { return true; } i += 1; } false } const _: () = { let mut i = 0; while i < METHODS.len() { assert!(has_column(METHODS[i]), "an albums method has no column in the matrix"); i += 1; } }; /// Cells where each column applied: an act that changed a mark, a screen that answered. static APPLIED: std::sync::Mutex> = std::sync::Mutex::new(std::collections::BTreeMap::new()); /// The item states (decision H.d and 1f.6): the library's own three; the id /// now naming another photo; the same photo edited; facts filled in later; /// the library's identity changed. #[derive(Debug, Clone, Copy, PartialEq)] enum ItemState { Lib(LibraryState), Renamed, Edited, FilledIn, NewLibrary, } fn item_states() -> Vec { LibraryState::ALL.iter().map(|s| ItemState::Lib(*s)).chain([ItemState::Renamed, ItemState::Edited, ItemState::FilledIn, ItemState::NewLibrary]).collect() } /// p's mark: one column per kind of `Mark` (an exhaustive match, so a new kind /// is a build error here), with "binned" split into binned and binned as a copy. #[derive(Debug, Clone, Copy, PartialEq)] enum MarkCol { None, Keep, Binned, BinnedCopy, Handed, Freed, } fn mark_cols() -> Vec { // a Handed mark cannot be made here (decision M-b): a stored one is decoded let handed: Mark = serde_json::from_str(r#"{"mark":"handed","at_ms":0}"#).unwrap(); let mut out = Vec::new(); for m in [Mark::None, Mark::Keep { at_ms: 0 }, Mark::Bin { at_ms: 0 }, handed, Mark::Freed { at_ms: 0 }] { match m { Mark::None => out.push(MarkCol::None), Mark::Keep { .. } => out.push(MarkCol::Keep), Mark::Bin { .. } => out.extend([MarkCol::Binned, MarkCol::BinnedCopy]), Mark::Handed { .. } => out.push(MarkCol::Handed), Mark::Freed { .. } => out.push(MarkCol::Freed), } } out } /// X: present, binned through an act, in the phone's trash, gone, its id now /// naming another photo, or binned and in the same Delete as p. const XS: [&str; 6] = ["present", "binned", "trashed", "absent", "renamed", "same_act"]; const M_T: i64 = 1_700_000_000_000; /// A small grey picture: `seed` makes it another photo; `nudge` a near one. fn grey_of(seed: u8, nudge: bool) -> Value { let mut px: Vec = (0..48 * 48).map(|i: u32| ((i % 48) as u8).wrapping_mul(3).wrapping_add(seed.wrapping_mul(37)) ^ ((i / 48) as u8).wrapping_mul(seed | 1)).collect(); if nudge { px[0] = px[0].wrapping_add(9); } json!({ "width": 48, "height": 48, "pixels": base64::engine::general_purpose::STANDARD.encode(px) }) } fn photo(id: &str, at: i64, bytes: u64) -> Item { Item { id: id.into(), kind: Kind::Photo, taken_at_ms: at, width: 4032, height: 3024, duration_ms: 0, bytes: Some(bytes), flags: vec![], path: None, camera: Some("phone".into()), cloud_id: None, offset_s: None, added_ms: Some(at), generation_added: Some(at / 1000), modified: None } } #[derive(Clone, Copy)] struct Variant { platform: Platform, parts: bool, limited: bool, } struct Cell { ctx: String, path: std::path::PathBuf, ix: Option, state: ItemState, x: &'static str, v: Variant, now: i64, lists: usize, /// The items of this cell as the library holds them. items: Vec, library: &'static str, limited_now: bool, } impl Cell { fn ix(&mut self) -> &mut Index { self.ix.as_mut().unwrap() } fn tick(&mut self) -> i64 { self.now += 1; self.now } fn try_call(&mut self, method: &str, request: Value) -> Result { let now = self.tick(); let request = with_request(method, request); match answer(self.ix(), method, &request, now) { Ok(v) => { if v["platform"].is_object() { self.check_list(&asked_of(&v)); } Ok(v) } Err(e) => { assert_ne!(e.code, "unwritable", "{}: {method}: {}", self.ctx, e.message); Err(e.code) } } } fn call(&mut self, method: &str, request: Value) -> Value { let ctx = self.ctx.clone(); self.try_call(method, request).unwrap_or_else(|e| panic!("{ctx}: {method} refused {e}")) } fn platform_key(&self) -> &'static str { match self.v.platform { Platform::Ios => "ios", Platform::Android => "android", } } fn permission(&self) -> &'static str { if self.limited_now { "limited" } else { "full" } } fn ios(&self) -> bool { self.v.platform == Platform::Ios } /// What the library says of an id, as the shell reports it on this /// platform (an iPhone cannot read Recently Deleted: it says absent). fn truth(&self, id: &str) -> &'static str { let raw = match id { "p" => match self.state { ItemState::Lib(s) => s.key(), _ => "present", }, "x" if self.x == "trashed" => "trashed", "x" if self.x == "absent" => "absent", _ => "present", }; if raw == "trashed" && self.ios() { "absent" } else { raw } } /// What this phone reports of a photo it deleted. fn phone_gone(&self) -> &'static str { if self.ios() { "absent" } else { "trashed" } } fn reopen(&mut self) { self.ix = None; let ix = Index::open(&self.path).unwrap(); ix.work_budget.set(1); self.ix = Some(ix); } fn marks(&mut self) -> String { self.ix().conn.query_row("SELECT coalesce(group_concat(id || ':' || state || ':' || suspended || ':' || seq, ','), '') FROM (SELECT * FROM mark ORDER BY id)", [], |r| r.get(0)).unwrap() } /// `albums.work` to the end, one item a slice; each platform list checked as it is made. fn work(&mut self) { loop { let w = self.call("albums.work", json!({})); if w["idle"] == true { return; } } } fn check_list(&mut self, ids: &[String]) { self.lists += 1; let ctx = self.ctx.clone(); assert!(self.ios(), "{ctx}: a platform list on Android"); let ix = self.ix(); for id in ids { // (a) rule 2 held for each id at that moment, on both tiers assert_eq!(ix.lib(id), "present", "{ctx}: {id} handed while not present"); assert!(ix.mark(id).handed(), "{ctx}: {id} in a platform list without being handed"); assert!(ix.verified(id), "{ctx}: {id} handed though not read again since the library changed"); assert!(!super::content_changed(&ix.mark_fp(id), &ix.fp(id)), "{ctx}: {id} handed though edited since he binned it"); assert!(!id.contains("#retired-"), "{ctx}: a retired key reached the phone"); // (d) on the real copy link: a copy goes only with its original here, kept, staying if let Some(o) = ix.copy_of(id) { assert!(!ids.contains(&o), "{ctx}: {id} and its original {o} in one list"); assert!(ix.present(&o) && matches!(ix.mark(&o), Mark::None | Mark::Keep { .. }), "{ctx}: copy {id} handed while its original {o} is {} / {:?}", ix.lib(&o), ix.mark(&o)); } for c in ix.copies_of(id) { assert!(matches!(ix.mark(&c), Mark::None | Mark::Keep { .. }), "{ctx}: original {id} handed while its copy {c} is {:?}", ix.mark(&c)); } } } fn item(&self, id: &str) -> Item { self.items.iter().find(|i| i.id == id).unwrap().clone() } fn set_item(&mut self, it: Item) { self.items.retain(|i| i.id != it.id); self.items.push(it); } fn read(&mut self, items: Vec) -> Value { let library = self.library; self.call("albums.library.take", json!({ "items": items, "library": library })) } /// The id now names another photo: another identity (decision 1f tier one). fn rename(&mut self, id: &str) -> Value { let mut other = self.item(id); other.added_ms = other.added_ms.map(|a| a + 86_400_000); other.generation_added = other.generation_added.map(|g| g + 77); other.taken_at_ms += 86_400_000; other.bytes = Some(777_000); self.set_item(other.clone()); let r = self.read(vec![other]); assert_eq!(r["renamed"], 1, "{}: {id} renamed", self.ctx); r } /// The same photo edited: a crop and a save (tier two). fn edit(&mut self, id: &str) -> Value { let mut e = self.item(id); e.width = 1000; e.height = 1500; e.bytes = Some(e.bytes.unwrap_or(1) + 12_345); e.modified = Some(e.modified.unwrap_or(0) + 1); self.set_item(e.clone()); let r = self.read(vec![e]); assert_eq!(r["renamed"], 0, "{}: an edit is the same photo", self.ctx); r } /// Make an item leave as the library says, and prove absence alone changed /// no mark (e); a handed item may only become freed. fn leave(&mut self, id: &str, how: &str) { let before = self.ix().mark(id); match how { "trashed" => { let mut it = self.item(id); it.flags.push("trashed".into()); self.read(vec![it]); } "absent" => { for t in ["gone-1", "gone-2"] { self.call("albums.library.take", json!({ "removed": [id], "token": format!("{t}-{id}") })); } } _ => return, } let after = self.ix().mark(id); let lib = self.ix().lib(id); if how == "absent" && self.limited_now { assert_eq!(lib, "present", "{}: under limited access absence is never believed", self.ctx); } else { assert_eq!(lib, how, "{}: {id}", self.ctx); } if before.handed() && lib != "present" { assert!(matches!(after, Mark::Freed { .. }), "{}: a handed {id} the library no longer shows is freed", self.ctx); } else { assert_eq!(before, after, "{}: absence changed {id}'s mark (e)", self.ctx); } } /// Bin an offered item through the act, from the list that offers it. fn bin_from_list(&mut self, id: &str) { let list: String = self.ix().conn.query_row("SELECT list FROM offer WHERE id = ?1", [id], |r| r.get(0)).unwrap_or_else(|_| panic!("{} is offered", id)); let l = self.call("albums.list", json!({ "list": list })); self.call("albums.bin.move", json!({ "list": list, "token": l["token"], "ids": [id], "count": 1 })); let ctx = self.ctx.clone(); assert!(self.ix().mark(id).in_bin(), "{ctx}: {id} binned through the act"); } fn delete_ids(&mut self, ids: &[&str]) { let bin = self.call("albums.bin", json!({})); let token = bin["token"].clone(); self.call("albums.bin.delete", json!({ "ids": ids, "count": ids.len(), "token": token })); self.work(); } fn delete_all_tap(&mut self) -> bool { let bin = self.call("albums.bin", json!({})); if bin["count"].as_u64().unwrap_or(0) == 0 { return false; } if !self.ios() { // Delete ships on the iPhone first: never offered on Android assert!(bin["act"].is_null() && bin["delete_later"].is_string(), "{}: no Delete on Android", self.ctx); let r = self.try_call("albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] })); assert_eq!(r.err().as_deref(), Some("not_on_this_phone"), "{}", self.ctx); return false; } if self.limited_now { assert!(bin["act"].is_null() && bin["needs_full_access"].is_object(), "{}: no Delete under limited access, and why", self.ctx); } self.try_call("albums.bin.delete", json!({ "all": true, "token": bin["token"], "count": bin["count"] })).is_ok() } /// The shell after `platform.done`, or after a kill from `albums.waiting`. fn settle_waiting(&mut self, read_as: Option<&'static str>) { let w = self.call("albums.waiting", json!({})); assert_eq!(w["count"].as_u64().unwrap() as usize, w["acts"].as_array().unwrap().iter().map(|a| a["read"].as_array().unwrap().len()).sum::(), "{}: waiting count and acts agree", self.ctx); for a in w["acts"].as_array().unwrap().clone() { let act = a["act_id"].clone(); let read = self.call("albums.platform.done", json!({ "act_id": act })); let states: Vec = strs(&read["read"]).iter().map(|id| json!({ "id": id, "state": read_as.unwrap_or_else(|| self.truth(id)) })).collect(); let s = self.call("albums.library.take", json!({ "act_id": act, "states": states, "complete": true })); if !s["settled"]["unsure"].is_null() { // only an absent read without full access waits, and it says why assert!(self.limited_now, "{}: unsure with full access and a complete read", self.ctx); assert_eq!(s["settled"]["unsure"]["why"], "needs_full_access", "{}", self.ctx); } } } fn applied(&self, column: &'static str) { *APPLIED.lock().unwrap().entry(column).or_insert(0) += 1; } } fn matrix_cell(state: ItemState, mark: MarkCol, x: &'static str, column: &'static str, v: Variant) -> usize { let ctx = format!("{:?}{}{} · p {state:?} · mark {mark:?} · X {x} · {column}", v.platform, if v.parts { " parts" } else { "" }, if v.limited { " limited" } else { "" }); let base = if std::path::Path::new("/dev/shm").is_dir() { tempfile::tempdir_in("/dev/shm").unwrap() } else { tempfile::tempdir().unwrap() }; let path = Index::path_in(base.path()); let ix = Index::open(&path).unwrap(); ix.work_budget.set(1); // a copy is a real copy: the same photo, found by the core (item.copy_of), never a typed reason let copy = mark == MarkCol::BinnedCopy; let x_item = screenshot("x", M_T, None, 3_000_000); let p_item = if copy { screenshot("p", M_T + 600_000, None, 3_000_000) } else { screenshot("p", M_T + 600_000, if v.parts { Some("DCIM/Camera/IMG_7.jpg") } else { None }, 2_000_000) }; let mut items = vec![x_item, p_item, screenshot("o", M_T + 1_200_000, None, 1_000_000)]; if v.parts { items.push(screenshot("p-raw", M_T + 600_000, Some("DCIM/Camera/IMG_7.dng"), 20_000_000)); } let set_cols = matches!(column, "albums.sets" | "albums.set" | "albums.set.keep"); if set_cols { // two shots of one moment: a real set items.push(photo("m1", M_T + 1_800_000, 2_500_000)); items.push(photo("m2", M_T + 1_801_000, 2_600_000)); } let mut first_read = items.clone(); if state == ItemState::FilledIn { // Android can send 0 and no size first, and the facts later let p = first_read.iter_mut().find(|i| i.id == "p").unwrap(); p.width = 0; p.height = 0; p.bytes = None; } let mut c = Cell { ctx: ctx.clone(), ix: Some(ix), path, state, x, v, now: 0, lists: 0, items, library: "lib-1", limited_now: false }; let platform = c.platform_key(); // set up with full access; limited access, when this cell has it, comes after c.call("albums.start", json!({ "platform": platform, "permission": "full", "library": "lib-1" })); c.read(first_read); let both_before = copy && matches!(x, "binned" | "same_act"); if both_before { // both binned through the act before the core knew one is a copy of the other c.bin_from_list("x"); c.bin_from_list("p"); } let mut looks: Vec = [("x", 9u8), ("p", if copy { 9 } else { 4 }), ("o", 5)].iter().map(|(id, seed)| json!({ "id": id, "grey": grey_of(*seed, false) })).collect(); if set_cols { looks.push(json!({ "id": "m1", "grey": grey_of(7, false) })); looks.push(json!({ "id": "m2", "grey": grey_of(7, true) })); } c.call("albums.look.take", json!({ "looks": looks })); if copy { assert_eq!(c.ix().copy_of("p").as_deref(), Some("x"), "{ctx}: the core found the copy"); } if matches!(x, "binned" | "same_act") && !both_before { c.bin_from_list("x"); } // p's mark, through the acts while p is in the library match mark { MarkCol::None => {} MarkCol::Keep => { c.call("albums.keep", json!({ "ids": ["p"], "count": 1 })); } MarkCol::BinnedCopy if both_before => {} _ => c.bin_from_list("p"), } if matches!(mark, MarkCol::Handed | MarkCol::Freed) { c.delete_ids(&["p"]); assert!(c.ix().mark("p").handed(), "{ctx}: set up handed"); } if mark == MarkCol::Freed { let gone = c.phone_gone(); c.settle_waiting(Some(gone)); assert!(matches!(c.ix().mark("p"), Mark::Freed { .. }), "{ctx}: set up freed"); } if v.limited { c.limited_now = true; c.call("albums.start", json!({ "platform": platform, "permission": "limited", "library": "lib-1" })); } // the library's state of X, then of p match x { "renamed" => { c.rename("x"); } _ => { let xs = c.truth("x"); c.leave("x", xs); } } let freed = mark == MarkCol::Freed; match state { ItemState::Lib(LibraryState::Present) if freed => { // restored from the phone's trash: an ordinary photo again (rule 4) let p = c.item("p"); c.read(vec![p]); assert_eq!(c.ix().mark("p"), Mark::None, "{ctx}: came back"); } ItemState::Lib(LibraryState::Present) => {} ItemState::Lib(_) if freed => {} ItemState::Lib(_) => { let how = c.truth("p"); c.leave("p", how); } ItemState::Edited | ItemState::FilledIn if freed => {} ItemState::Edited => { // the same photo edited: a Keep stays, a binned one stays binned (and waits for his look) let before = c.ix().mark("p"); let r = c.edit("p"); assert_eq!(r["edited"], 1, "{ctx}"); assert_eq!(c.ix().mark("p"), before, "{ctx}: an edit changed no choice"); if before.in_bin() { assert!(super::edited(c.ix(), "p"), "{ctx}: held for his look"); } } ItemState::FilledIn => { let before = c.ix().mark("p"); let full = c.item("p"); let r = c.read(vec![full]); assert_eq!((r["edited"].as_u64(), r["renamed"].as_u64()), (Some(0), Some(0)), "{ctx}: facts that arrive later fill in"); assert_eq!(c.ix().mark("p"), before, "{ctx}"); assert!(!super::edited(c.ix(), "p"), "{ctx}: a fill-in is not an edit"); } ItemState::Renamed => { let before = c.ix().mark("p"); c.rename("p"); assert_eq!(c.ix().mark("p"), Mark::None, "{ctx}: the new photo is unmarked"); if before != Mark::None { assert_eq!(c.ix().count("SELECT count(*) FROM mark WHERE id LIKE 'p#retired-%'"), 1, "{ctx}: the old mark stays with the old photo"); } } ItemState::NewLibrary => { let marked = c.ix().count("SELECT count(*) FROM mark WHERE state IN ('bin', 'keep')"); c.library = "lib-2"; let permission = c.permission(); let s = c.call("albums.start", json!({ "platform": platform, "permission": permission, "library": "lib-2" })); assert_eq!(s["rechecking"], true, "{ctx}"); assert_eq!(c.ix().count("SELECT count(*) FROM mark WHERE suspended = 1"), marked, "{ctx}: every choice waits"); assert_eq!(c.ix().count("SELECT count(*) FROM item WHERE verified = 1"), 0, "{ctx}: no id trusted until read again"); assert_eq!(c.ix().count("SELECT count(*) FROM offer"), 0, "{ctx}: nothing offered from the old library"); assert_eq!(c.call("albums.bin", json!({}))["count"].as_u64().unwrap_or(0), 0, "{ctx}: nothing in the Bin from another library"); } } let before = c.ix().mark_row("p"); let handed_before = before.0.handed(); let marks_before = c.marks(); let platform = c.platform_key(); let permission = c.permission(); // a set to act on, when the column needs one let set = if set_cols { c.call("albums.sets", json!({}))["sets"][0].clone() } else { Value::Null }; // the act let refusal = match column { "albums.start" => c.try_call("albums.start", json!({ "platform": platform, "permission": permission })).err(), "albums.library.take" => { let present: Vec = c .items .clone() .into_iter() .filter(|it| c.truth(&it.id) != "absent") .map(|mut it| { if c.truth(&it.id) == "trashed" { it.flags.push("trashed".into()); } it }) .collect(); let gone: Vec = c.items.iter().map(|i| i.id.clone()).filter(|id| c.truth(id) == "absent").collect(); let ids: Vec = c.items.iter().map(|i| i.id.clone()).collect(); let marks_before: Vec = ids.iter().map(|id| c.ix().mark(id)).collect(); let library = c.library; c.call("albums.library.take", json!({ "items": present, "removed": gone, "token": "read-1", "library": library })); c.call("albums.library.take", json!({ "removed": gone, "token": "read-2" })); if state == ItemState::NewLibrary { // the same photos read again: each waiting choice is matched back let still = c.ix().count("SELECT count(*) FROM mark JOIN item ON item.id = mark.id WHERE mark.suspended = 1 AND item.fp IN (SELECT fp FROM item WHERE state = 'present' AND id NOT LIKE '%#retired-%')"); assert_eq!(still, 0, "{ctx}: a waiting choice whose photo was read again is matched back"); } else { // (e) a read that only repeats the library changes no mark (a handed one may settle) for (k, id) in ids.iter().enumerate() { let now_m = c.ix().mark(id); if !marks_before[k].handed() && !matches!(marks_before[k], Mark::Freed { .. }) { assert_eq!(marks_before[k], now_m, "{ctx}: a library read changed {id}'s mark (e)"); } } } None } "albums.pass.next" => c.try_call("albums.pass.next", json!({ "limit": 10 })).err(), "albums.look.take" => c.try_call("albums.look.take", json!({ "looks": [{ "id": "p", "grey": grey_of(4, false) }] })).err(), "albums.pass.lines" => c.try_call("albums.pass.lines", json!({})).err(), "albums.home" => c.try_call("albums.home", json!({})).err(), "albums.tidy" => c.try_call("albums.tidy", json!({})).err(), "albums.list" => c.try_call("albums.list", json!({ "list": "screenshots" })).err(), "albums.sets" => c.try_call("albums.sets", json!({})).err(), "albums.set" if set.is_null() => Some("no set".to_string()), "albums.set" => c.try_call("albums.set", json!({ "set": set["set"] })).err(), "albums.set.keep" if set.is_null() => Some("no set".to_string()), "albums.set.keep" => { let members = strs(&set["members"]); let r = c.try_call("albums.set.keep", json!({ "set": set["set"], "members": members, "count": members.len(), "keep": set["keepers"] })); if r.is_ok() { assert_ne!(c.marks(), marks_before, "{ctx}: keeping a set's pick bins the rest"); } r.err() } "albums.keep" => c.try_call("albums.keep", json!({ "ids": ["p"], "count": 1 })).err(), "albums.bin.move" => c.try_call("albums.bin.move", json!({ "ids": ["p"], "count": 1 })).err(), "albums.bin.bring_back" => c.try_call("albums.bin.bring_back", json!({ "ids": ["p"], "count": 1 })).err(), "albums.undo" => { let a = before.2.clone(); if a.is_empty() { Some("nothing".to_string()) } else { c.try_call("albums.undo", json!({ "token": a })).err() } } "albums.bin" => c.try_call("albums.bin", json!({})).err(), "albums.bin.delete" => { c.delete_all_tap(); c.work(); None } "albums.bin.clear_other" => { let n = c.ix().count("SELECT count(*) FROM mark WHERE suspended = 1"); c.call("albums.bin.clear_other", json!({ "count": n })); assert_eq!(c.ix().count("SELECT count(*) FROM mark WHERE suspended = 1"), 0, "{ctx}: cleared"); None } "albums.you.clear_gone" => { let you = c.call("albums.you", json!({})); let n = you["gone"]["count"].as_u64().unwrap_or(0); c.call("albums.you.clear_gone", json!({ "count": n })); assert!(c.call("albums.you", json!({}))["gone"].is_null(), "{ctx}: cleared"); None } "albums.platform.done" => { c.work(); c.settle_waiting(None); None } "albums.work" => { // work queued by a tap, done a slice at a time c.delete_all_tap(); c.work(); None } "albums.waiting" => { let w = c.call("albums.waiting", json!({})); assert_eq!(w["count"].as_u64().unwrap() as usize, c.ix().count("SELECT count(*) FROM mark WHERE state = 'handed'"), "{ctx}"); None } "albums.you" => c.try_call("albums.you", json!({})).err(), "albums.face.align" => c.try_call("albums.face.align", json!({ "rgb": { "width": 2, "height": 2, "pixels": base64::engine::general_purpose::STANDARD.encode([0u8; 12]) }, "points": vec![0.5f32; 10] })).err(), "late work" => { // the tap, then a slice at a time with the library and his choices changing between if c.delete_all_tap() { for k in 0..12 { let w = c.call("albums.work", json!({})); if w["idle"] == true { break; } match k % 3 { 0 => { // he bins x from its list between slices (a copy rule may skip it) let list: Option = c.ix().conn.query_row("SELECT list FROM offer WHERE id = 'x'", [], |r| r.get(0)).ok(); if let Some(list) = list { let l = c.call("albums.list", json!({ "list": list })); c.try_call("albums.bin.move", json!({ "list": list, "token": l["token"], "ids": ["x"], "count": 1 })).ok(); } } 1 => { c.try_call("albums.keep", json!({ "ids": ["o"], "count": 1 })).ok(); } _ => { // he edits p between slices (once handed, nothing touches it) if c.ix().present("p") && !c.ix().mark("p").handed() && c.truth("p") == "present" { c.edit("p"); } } } } c.work(); } None } "replay" => { let r = json!({ "ids": ["p"], "count": 1, "request_id": "the-same-tap" }); let first = c.try_call("albums.bin.move", r.clone()); let acts = c.ix().count("SELECT count(*) FROM act"); let again = c.try_call("albums.bin.move", r); match (&first, &again) { (Ok(a), Ok(b)) => { let mut b = b.clone(); assert_eq!(b.as_object_mut().unwrap().remove("replayed"), Some(json!(true)), "{ctx}: a replay says so"); assert_eq!(a, &b, "{ctx}: a replay answers the first answer"); } (a, b) => assert_eq!(a, b, "{ctx}: a refusal is answered again as it was"), } assert_eq!(c.ix().count("SELECT count(*) FROM act"), acts, "{ctx}: a replay writes nothing"); first.err() } "kill and reopen" => { let tapped = c.delete_all_tap(); c.reopen(); if tapped { c.work(); } c.reopen(); // the phone deleted what it was handed, and reports it as this phone can let gone = c.phone_gone(); c.settle_waiting(Some(gone)); if c.call("albums.waiting", json!({}))["count"] != 0 { // only an iPhone's absent under limited access waits; full access heals it assert!(c.limited_now && c.ios(), "{ctx}: still waiting after a complete read"); c.limited_now = false; c.call("albums.start", json!({ "platform": platform, "permission": "full" })); c.settle_waiting(Some(gone)); } assert_eq!(c.call("albums.waiting", json!({}))["count"], 0, "{ctx}: healed by the next read"); None } other => unreachable!("{other}"), }; let is_act = ACTS.contains(&column) || matches!(column, "late work" | "replay" | "kill and reopen" | "albums.work"); if (is_act && c.marks() != marks_before && refusal.is_none()) || (!is_act && refusal.is_none()) { c.applied(column); } // (b) nothing acts on a handed photo let after = c.ix().mark_row("p"); if handed_before && !matches!(column, "albums.library.take" | "albums.platform.done" | "kill and reopen") { assert_eq!(before, after, "{ctx}: a handed photo was changed"); if matches!(column, "albums.bin.move" | "albums.keep" | "albums.bin.bring_back") { assert_eq!(refusal.as_deref(), Some("handed"), "{ctx}: refused as handed"); } } // (c) never in the Bin, offered, or handed while the library says otherwise; // a retired or waiting choice is never in the Bin let bin = c.call("albums.bin", json!({})); for g in bin["groups"].as_array().cloned().unwrap_or_default() { for id in strs(&g["ids"]) { assert!(!id.contains("#retired-"), "{ctx}: a retired key in the Bin"); if !g["bring_back"].is_null() { assert!(c.ix().present(&id), "{ctx}: {id} shown in the Bin while {}", c.ix().lib(&id)); } } } if c.ix().lib("p") != "present" { assert_eq!(c.ix().count("SELECT count(*) FROM offer WHERE id = 'p'"), 0, "{ctx}: p offered while {}", c.ix().lib("p")); assert!(!c.ix().mark("p").handed(), "{ctx}: p handed while {}", c.ix().lib("p")); } assert_eq!(c.ix().count("SELECT count(*) FROM offer JOIN item ON item.id = offer.id WHERE item.verified = 0"), 0, "{ctx}: an unverified id offered"); assert_eq!(c.ix().count("SELECT count(*) FROM mark WHERE suspended = 1 AND state = 'handed'"), 0, "{ctx}: a waiting choice is never handed"); counts_hold(c.ix()); c.lists } #[test] fn the_matrix_every_state_mark_original_and_method_keeps_the_rules() { let (mut cells, mut lists) = (0usize, 0usize); let (states, marks) = (item_states(), mark_cols()); // a fill-in before the core found a copy is not a copy cell // nothing is handed on Android (Delete ships on the iPhone first): no handed or freed cells there let applies = |s: ItemState, m: MarkCol, p: Platform| !(s == ItemState::FilledIn && m == MarkCol::BinnedCopy) && !(p == Platform::Android && matches!(m, MarkCol::Handed | MarkCol::Freed)); for platform in Platform::ALL { let v = Variant { platform, parts: false, limited: false }; for &state in &states { for &mark in marks.iter().filter(|m| applies(state, **m, platform)) { for x in XS { for column in COLUMNS { lists += matrix_cell(state, mark, x, column, v); cells += 1; } } } } } // parts, and limited access on both phones, over every state, mark and column let mut variants = 0usize; for v in [Variant { platform: Platform::Ios, parts: true, limited: false }, Variant { platform: Platform::Ios, parts: false, limited: true }, Variant { platform: Platform::Android, parts: false, limited: true }] { for &state in &states { for &mark in marks.iter().filter(|m| **m != MarkCol::BinnedCopy && applies(state, **m, v.platform)) { for column in COLUMNS { lists += matrix_cell(state, mark, "present", column, v); variants += 1; } } } } let applied = APPLIED.lock().unwrap().clone(); let never: Vec<&str> = COLUMNS.iter().copied().filter(|c| applied.get(c).copied().unwrap_or(0) == 0).collect(); println!( "ALBUMS CORE 1f matrix: {cells} cells ({} platforms x {} item states x {} marks x {} originals x {} columns, less fill-in copies and Android's handed and freed) + {variants} cells with parts or limited access on both phones; {lists} platform lists checked; one item a slice; columns applied in {:?}", Platform::ALL.len(), states.len(), marks.len(), XS.len(), COLUMNS.len(), applied ); assert!(never.is_empty(), "columns that never applied: {never:?}"); assert!(lists > 0); }