Cotton code
1736 lines · 87.1 KB · RustRaw
//! `sites.*` — COMMS' SITES (assets/design/chat/SITES.md; the shape in chat//! CONTRACT.md "Sites: the core's `sites.*`"): the rows' book, sealed in one//! file on this phone (`client/sites.c1`) under a key the phone keeps in its//! own keychain or keystore, on this device only, and sends with every call as//! `key` (32 bytes, base64url). Never synced, never sent anywhere.//!//! ```json//! sites.list {key, unlocked?} → {title, place: "tab"|"you", private: {label, line},//!     rows: [{id, label, home, site, line, stay, store, store_uuid}],//!     hidden: {label, count, locked, line, rows?}, add: {label}, paste: {label}, words: {…}}//! sites.add {key, label, home, stay?, hidden?} → {row, said}//! sites.edit {key, id, label?, home?, stay?, hidden?} → {row, said}//! sites.delete {key, id} → {deleted, store, said}//! sites.open {key, id?, url?} → {store, store_uuid?, url, stay, private, title}//! sites.link {key, url} → sites.open's Private answer + open_in: {label, rows}//! ```//!//! - Hidden rows are answered only with `unlocked: true`, which the phone asks//!   once the device lock has said yes (`hidden.rows`); `sites.link`'s//!   `open_in` never holds them.//! - `place` is "tab" once a row exists (hidden ones count), and from the//!   start on CottonDB's own build (the owner's household); else Sites is a//!   row under You (`chat.you`).//! - A home or a link that is not a web address is refused as `not_web`.//! - A file the key cannot open is set aside (`sites.c1.unreadable`), never//!   read as empty and never written over.use std::sync::Mutex;use serde_json::{json, Value};use zeroize::Zeroizing;use cotton_core::messages::app::list::{self, say};use cotton_core::rules::shell_lines::LineSet;use cotton_core::sites::{self, Book, Refused, Row};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;pub const METHODS: [&str; 7] = ["sites.add", "sites.delete", "sites.edit", "sites.left", "sites.link", "sites.list", "sites.open"];/// Cotton Sites' own calls (assets/design/sites/CONTRACT.md), beside the seven Comms uses.#[path = "sites_app.rs"]pub mod app;/// Whether a method is one of Sites' (Comms' seven or the app's own).pub fn handles(method: &str) -> bool {    METHODS.contains(&method) || app::METHODS.contains(&method) || ROWS_METHODS.contains(&method)}/// The calls the rows model adds (`rows_call`).pub const ROWS_METHODS: [&str; 6] = ["sites.book.leave", "sites.orphans.remove", "sites.stores.gone", "sites.stores.keep", "sites.stores.removed", "sites.undo"];const FILE: &str = "sites.c1";static LOCK: Mutex<()> = Mutex::new(());pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    let lines = list::lines();    let text = |k: &str| request.get(k).and_then(Value::as_str);    let flag = |k: &str| request.get(k).and_then(Value::as_bool);    if let Some(answer) = rows_call(handle, method, request) {        return answer;    }    if app::METHODS.contains(&method) {        return app::call(handle, method, request);    }    match method {        "sites.list" => {            let key = key(request)?;            let book = read(&handle.client(), &key)?;            Ok(listed(handle, &lines, &book, flag("unlocked").unwrap_or(false)))        }        "sites.add" => change(handle, request, |book| {            let id = new_id();            book.add(id.clone(), text("label").unwrap_or_default(), text("home").unwrap_or_default(), flag("stay").unwrap_or(true), flag("hidden").unwrap_or(false))?;            // Cotton Sites: pinned at once, if asked.            if flag("pinned") == Some(true) {                let pinned: Vec<String> = book.rows.iter().filter(|r| r.pinned || r.id == id).map(|r| r.id.clone()).collect();                book.arrange(&[], &pinned);            }            let row = book.rows.iter().find(|r| r.id == id).expect("added");            Ok(json!({ "row": drawn(&lines, row), "said": say(&lines, "app.sites.said.added", &[("label", &row.label)]) }))        }),        "sites.edit" => change(handle, request, |book| {            let id = text("id").unwrap_or_default();            book.edit(id, text("label"), text("home"), flag("stay"), flag("hidden"))?;            // Cotton Sites' own fields: pinned and trackers for this one site.            let row = book.rows.iter_mut().find(|r| r.id == id).ok_or(Refused::NoRow)?;            if let Some(pinned) = flag("pinned") {                row.pinned = pinned;            }            if let Some(trackers) = flag("trackers") {                row.trackers = trackers;            }            let row = book.rows.iter().find(|r| r.id == id).expect("edited");            Ok(json!({ "row": drawn(&lines, row), "said": say(&lines, "app.sites.said.saved", &[]) }))        }),        // SITES 4: where a row's page is now, so it reopens there after the phone let it go; `url` null on Sign out.        "sites.left" => change(handle, request, |book| {            book.leave_titled(text("id").unwrap_or_default(), text("url"), text("title"))?;            Ok(json!({}))        }),        "sites.delete" => change(handle, request, |book| {            let id = text("id").unwrap_or_default();            let label = book.rows.iter().find(|r| r.id == id).map(|r| r.label.clone()).unwrap_or_default();            book.delete(id)?;            // On Sites' own list the row waits five seconds for its Undo before it is erased (`tidy`).            Ok(json!({ "deleted": id, "store": store(id), "said": say(&lines, "app.sites.said.deleted", &[("label", &label)]), "undo": { "label": app::s("said.undo"), "seconds": UNDO_MS / 1000 } }))        }),        "sites.open" => {            let key = key(request)?;            // A link that waits in this site (the share sheet's) is where it opens now, once.            if let Some(id) = text("id").filter(|_| text("url").is_none_or(|u| u.trim().is_empty())) {                let waited = change(handle, request, |book| Ok(json!(book.rows.iter_mut().find(|r| r.id == id).and_then(|r| r.waiting.take()))))?;                if let Some(link) = waited.as_str() {                    let book = read(&handle.client(), &key)?;                    let mut answer = opened(&lines, &book, Some(id), Some(link))?;                    answer["from_share"] = json!(true);                    return Ok(answer);                }            }            let book = read(&handle.client(), &key)?;            let mut answer = opened(&lines, &book, text("id"), text("url"))?;            // Cotton Sites: a quick visit or a search's throwaway place, and where a link came from.            if text("id").is_none() && (flag("quick") == Some(true) || flag("search") == Some(true)) {                answer["store"] = json!(format!("quick-{}", new_id()));                answer["title"] = json!(app::s("quick.label"));                answer["quick"] = app::quick(flag("search") == Some(true));            }            if let Some(row) = text("id").and_then(|id| book.rows.iter().find(|r| r.id == id)) {                if let Some(arrived) = app::arrived(text("from"), &row.label) {                    answer["arrived"] = arrived;                }                answer["state"] = json!(row.state);                answer["trackers"] = json!(row.trackers);            }            Ok(answer)        }        "sites.link" => {            let key = key(request)?;            let book = read(&handle.client(), &key)?;            let url = text("url").unwrap_or_default();            let mut answer = opened(&lines, &book, None, Some(url.clone()))?;            let rows = book.for_link(&url).into_iter().map(|r| drawn(&lines, r)).collect::<Vec<_>>();            answer["open_in"] = json!({ "label": say(&lines, "app.sites.open_in", &[]), "rows": rows });            Ok(answer)        }        _ => Err(MethodError::new("unknown_method", format!("unknown sites method {method}"))),    }}/// Where Sites stands: a place on the pill once a row exists, and from the start on CottonDB's own build.pub fn is_place(handle: &CottonHandle, rows: usize) -> bool {    rows > 0 || handle.flavor() == cotton_core::flavor::Flavor::Real}/// Whether this phone holds any row, for `chat.you` (which has no key): the sealed file stands only while one does.pub fn has_rows(handle: &CottonHandle) -> bool {    path(&handle.client()).exists()}fn listed(handle: &CottonHandle, lines: &LineSet, book: &Book, unlocked: bool) -> Value {    let w = |k: &str| say(lines, &format!("app.sites.{k}"), &[]);    let rows: Vec<Value> = book.shown(false).map(|row| drawn(lines, row)).collect();    let count = book.rows.iter().filter(|r| r.hidden).count();    let mut hidden = json!({ "label": w("hidden.label"), "count": count, "locked": !unlocked, "line": w(if unlocked { "hidden.again" } else { "hidden.line" }) });    if unlocked {        hidden["rows"] = json!(book.rows.iter().filter(|r| r.hidden).map(|r| drawn(lines, r)).collect::<Vec<_>>());    }    json!({        "title": w("title"),        "place": if is_place(handle, book.rows.len()) { "tab" } else { "you" },        "private": { "label": w("private.label"), "line": w("private.line") },        "rows": rows,        "hidden": hidden,        "add": { "label": w("add") },        "paste": { "label": w("paste") },        "words": {            "label": w("label"), "home": w("address"), "stay": w("stay"), "stay_line": w("stay_line"), "hidden": w("hide"),            "save": w("save"), "delete": w("remove"), "delete_ask": w("remove_ask"), "cancel": w("cancel"),        },    })}fn drawn(lines: &LineSet, row: &Row) -> Value {    let site = sites::host_of(&row.home);    let line = if row.stay { site.clone() } else { say(lines, "app.sites.closed_line", &[("host", &site)]) };    json!({        "id": row.id, "label": row.label, "home": row.home, "open": row.reopen(), "site": site, "line": line,        "stay": row.stay, "hidden": row.hidden, "store": store(row.store.as_deref().unwrap_or(&row.id)), "store_uuid": sites::store_uuid(row.store.as_deref().unwrap_or(&row.id)),    })}/// What a session screen opens: a row where it was left, else at its home (or at `url`), or Private (no `id`) in a store made for this once.fn opened(lines: &LineSet, book: &Book, id: Option<&str>, url: Option<&str>) -> Result<Value, MethodError> {    let url = url.filter(|u| !u.trim().is_empty()).map(sites::home_of).transpose().map_err(|why| refused(lines, why))?;    match id {        Some(id) => {            let row = book.rows.iter().find(|r| r.id == id).ok_or_else(|| refused(lines, Refused::NoRow))?;            Ok(json!({ "store": store(row.store.as_deref().unwrap_or(&row.id)), "store_uuid": sites::store_uuid(row.store.as_deref().unwrap_or(&row.id)), "url": url.unwrap_or_else(|| row.reopen().to_string()), "stay": row.stay, "private": false, "title": row.label }))        }        None => Ok(json!({ "store": format!("private-{}", new_id()), "url": url.unwrap_or_default(), "stay": false, "private": true, "title": say(lines, "app.sites.private.label", &[]) })),    }}fn store(id: &str) -> String {    format!("site-{id}")}fn refused(lines: &LineSet, why: Refused) -> MethodError {    let code = match why {        Refused::NotAnAddress => "not_web",        Refused::NoRow => "no_row",        Refused::NotASetting => "bad_request",    };    MethodError::new(code, say(lines, why.line(), &[]))}fn key(request: &Value) -> Result<Zeroizing<[u8; 32]>, MethodError> {    key_named(request, "key")}/// A 32-byte key sent under `name` (this phone's Sites key, or a hand-over key for the move).fn key_named(request: &Value, name: &str) -> Result<Zeroizing<[u8; 32]>, MethodError> {    let text = request.get(name).and_then(Value::as_str).ok_or_else(|| MethodError::new("bad_request", "key: this phone's Sites key, from its keychain"))?;    // base64url (iPhone) or standard base64 (Android), with or without padding.    let url = text.trim_end_matches('=').replace('+', "-").replace('/', "_");    cotton_core::chat::seal::key_from_text(&url).map(Zeroizing::new).ok_or_else(|| MethodError::new("bad_request", "key: 32 bytes as base64"))}/// Comms' book, and an old book Sites takes in once: `client/sites.c1`.fn path(client: &ClientController) -> std::path::PathBuf {    client.layout().client_dir().join(FILE)}/// Old books an earlier Sites build kept beside `sites.c1`: the list while signed out after an account, and one per/// further account (SYNC 3, dev only), named by the first eight bytes of that account's SHA-256.const SIGNED_OUT: &str = "sites-signed-out.c1";/// The account this copy stands for: none while it is the phone's own, signed out or never signed in./// A connection file that cannot be read is an error, never "signed out" (review of SITES ROWS 2, item 6).fn account(client: &ClientController) -> Result<Option<String>, MethodError> {    let record = cotton_client::connection::read_record(&client.layout().connection_json()).map_err(|e| MethodError::new("unreadable", format!("the connection file: {e}")))?;    let Some(record) = record else { return Ok(None) };    if !record.mine.mode.has_server() {        return Ok(None);    }    Ok(record.mine.workspace_id.clone().or(record.mine.owner_id.clone()))}/// The list as Sites draws it: Comms' book, or on Sites' own kit the rows with what this phone keeps beside them.pub(crate) fn read(client: &ClientController, key: &[u8; 32]) -> Result<Book, MethodError> {    if !served(client)? {        return read_book(client, key);    }    Ok(view(client, key)?.book)}fn read_book(client: &ClientController, key: &[u8; 32]) -> Result<Book, MethodError> {    let file = path(client);    match std::fs::read(&file) {        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Book::default()),        Err(e) => Err(MethodError::new("unreadable", format!("{FILE}: {e}"))),        Ok(bytes) => match Book::open(key, &bytes) {            Some(book) => Ok(book),            None => {                // Not this key's: set aside, never read as empty and never written over (numbered, ROWS 8 low).                // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.                let _ = std::fs::rename(&file, unreadable_name(&file));                Ok(Book::default())            }        },    }}fn write_book(client: &ClientController, key: &[u8; 32], book: &Book) -> Result<(), MethodError> {    let file = path(client);    if book.rows.is_empty() && book.settings == cotton_core::sites::Settings::default() {        // No row left and nothing set: no file, so `chat.you` sees Sites back under You.        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        return match std::fs::remove_file(&file) {            Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(MethodError::new("unwritable", format!("{FILE}: {e}"))),            _ => Ok(()),        };    }    let nonce: [u8; 12] = rand::random();    let bytes = book.seal(key, &nonce).ok_or_else(|| MethodError::new("unwritable", "the Sites book could not be sealed"))?;    if let Some(parent) = file.parent() {        std::fs::create_dir_all(parent).map_err(|e| MethodError::new("unwritable", format!("{}: {e}", parent.display())))?;    }    let next = file.with_extension("c1.next");    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    std::fs::write(&next, bytes).map_err(|e| MethodError::new("unwritable", format!("{FILE}: {e}")))?;    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    std::fs::rename(&next, &file).map_err(|e| MethodError::new("unwritable", format!("{FILE}: {e}")))}/// Comms lets its book go once Sites has it (`sites.move.done`): the sealed file deleted, never read again.fn let_go(handle: &CottonHandle) -> Result<(), MethodError> {    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    match std::fs::remove_file(path(&handle.client())) {        Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(MethodError::new("unwritable", format!("{FILE}: {e}"))),        _ => Ok(()),    }}/// Read, change, write, under one lock: a refused change writes nothing.fn change(handle: &CottonHandle, request: &Value, work: impl FnOnce(&mut Book) -> Result<Value, Refused>) -> Result<Value, MethodError> {    change_with(handle, request, work, |why| refused(&list::lines(), why))}/// `change`, with the refusal said in the caller's words (Comms' or Sites'). On Sites' own kit the change is made on/// the list as the rows hold it now and written as the rows it changed (`commit`).fn change_with(handle: &CottonHandle, request: &Value, work: impl FnOnce(&mut Book) -> Result<Value, Refused>, said: impl Fn(Refused) -> MethodError) -> Result<Value, MethodError> {    let key = key(request)?;    let client = handle.client();    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    if !served(&client)? {        let mut book = read_book(&client, &key)?;        let answer = work(&mut book).map_err(said)?;        write_book(&client, &key, &book)?;        return Ok(answer);    }    claim_old_book(&client);    tidy(&client, &key)?;    let seen = view(&client, &key)?;    let mut book = seen.book.clone();    let answer = work(&mut book).map_err(said)?;    commit(&client, &key, &seen, &book)?;    Ok(answer)}/// The synced list (SYNC-DESIGN.md): Sites' kit carries the sealed `site` table and its rows are the list; Comms'/// does not, and its book stays on the phone as it always has.const SYNCED: &str = "site";/// What this phone keeps beside the rows, sealed, in the database's own folder (`Local`), and the plain list of the/// website stores it names (random keys only), read when the copy is forgotten without the Sites key.const LOCAL: &str = "sites.local.c1";const STORES: &str = "sites.stores.json";/// Entries carried from another copy of this phone (an adopt, a copy made again), taken in at the next read.const CARRIED: &str = "sites.carried.";/// Sites an earlier build kept only on this phone at sign-in, carried into the account's folder (`carry`,/// `read_local`) and written into the list from there (`retire_only`). Nothing writes one now.const LEFT_HERE: &str = "sites.left-here.";/// The same, as an earlier build left it in a signed-out copy's folder: carried with the copy at its sign-in.const LEFT_HERE_FILE: &str = "sites.left-here.c1";/// Website stores whose site is gone, for the shell to remove (`sites.stores.gone`): random keys only.const STORES_GONE: &str = "sites-stores-gone.json";/// How long a removal waits for its Undo before the row is erased.const UNDO_MS: i64 = 5_000;/// Whether this app keeps its list as the `site` rows: decided by the app's kit (Cotton Sites' carries the table,/// Comms' does not), never by whether a read of the table worked a moment ago. A copy that cannot be read fails the/// act with words; it never falls back to the phone's old book (review of SITES ROWS, item 7).pub(crate) fn served(client: &ClientController) -> Result<bool, MethodError> {    match crate::phone::tool_acts::app_kit(client)? {        Some(kit) => Ok(kit.keeps_table(SYNCED)),        None => match client.with_file(|file| Ok(file.driver.get("SELECT id FROM cotton_table_definitions WHERE id = ?1", &[rusqlite::types::Value::Text(SYNCED.into())]).map_err(|e| e.to_string())?.is_some())) {            Ok(held) => Ok(held),            Err(_) if client.current_database().is_err() => Ok(false),            Err(_) => Err(MethodError::new("unreadable", app::s("refused.unreadable"))),        },    }}/// The list as the rows hold it now, read once for a call.struct View {    book: Book,    /// Each site's place, as its row (or this phone, for a site only here) holds it.    places: std::collections::BTreeMap<String, f64>,    local: cotton_core::sites::Local,    carried: Vec<std::path::PathBuf>,    folder: std::path::PathBuf,    database: String,}/// The database folder Sites keeps its file in: the attached copy's own.fn local_folder(client: &ClientController) -> Result<(String, std::path::PathBuf), MethodError> {    let database = client.current_database().map_err(|e| MethodError::new("not_connected", e.to_string()))?;    let folder = client.layout().replica(&database).parent().map(std::path::Path::to_path_buf).ok_or_else(|| MethodError::new("unreadable", "no folder for this copy"))?;    Ok((database, folder))}fn read_local(folder: &std::path::Path, key: &[u8; 32]) -> Result<(cotton_core::sites::Local, Vec<std::path::PathBuf>), MethodError> {    let file = folder.join(LOCAL);    let mut local = match std::fs::read(&file) {        Err(e) if e.kind() == std::io::ErrorKind::NotFound => cotton_core::sites::Local::default(),        Err(e) => return Err(MethodError::new("unreadable", format!("{LOCAL}: {e}"))),        Ok(bytes) => match cotton_core::sites::Local::open(key, &bytes) {            Some(local) => local,            None => {                // Kept beside under a name of its own, numbered so a second never writes over the first (ROWS 8, low).                // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.                let _ = std::fs::rename(&file, unreadable_name(&file));                cotton_core::sites::Local::default()            }        },    };    // What an adopt or a copy made again carried here, in a fixed order (review of SITES ROWS 4, item 1): the files    // carried first, then the sites kept only on this phone at sign-in; each merged field by field, what this copy    // holds winning and the carried values filling what it lacks.    let carried = carried_files(folder);    let mut read = Vec::new();    let mut opened = Vec::new();    for path in &carried {        let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();        // A file that could not be read now is asked again next time, untouched (review of SITES ROWS 6, item 4).        let Ok(bytes) = std::fs::read(path) else { continue };        let Some(from) = cotton_core::sites::Local::open(key, &bytes) else {            // Not opened with this key: kept beside under a name of its own, never deleted (review of SITES ROWS 5,            // item 3), and said once (`sites.home` `unread`).            // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.            let _ = std::fs::rename(path, unread_name(path));            continue;        };        read.push(path.clone());        opened.push((name, from));    }    // What he removed in ANY carried copy stays removed, whatever file brings it: every removed list first, then the    // entries (review of NO SWITCH 3).    for (_, from) in &opened {        local.gone.extend(from.gone.iter().cloned());    }    for (name, mut from) in opened {        // What he removed here never comes back from a file taken in again.        from.entries.retain(|k, _| !local.gone.contains(k));        from.only.retain(|k, _| !local.gone.contains(k));        if name.starts_with(LEFT_HERE) {            // Each stays here whole, with its sign-in, until it is written into the account's list (`retire_only`).            for (k, e) in from.entries {                let row = match local.entries.get(&k) {                    Some(held) => Row { label: e.label.clone(), home: e.home.clone(), stay: e.stay, hidden: e.hidden, pinned: e.pinned, trackers: e.trackers, login: e.login.clone(), ..merged_kept(held, &e) },                    None => e,                };                local.entries.insert(k, row);            }            for (k, p) in from.only {                local.only.entry(k).or_insert(p);            }            continue;        }        for (k, e) in from.entries {            let row = match local.entries.get(&k) {                Some(held) => merged_kept(held, &e),                None => e,            };            local.entries.insert(k, row);        }        for (k, p) in from.only {            local.only.entry(k).or_insert(p);        }        for (k, at) in from.erasing {            local.erasing.entry(k).or_insert(at);        }        // Hidden wins: a site either copy held as hidden stays hidden. A copy whose flags are not filled leaves the        // merged flags not filled.        if !from.known.is_empty() && !from.known_hidden_filled {            local.known_hidden_filled = false;        }        local.known_hidden.extend(from.known_hidden.iter().cloned());        for (k, v) in from.known {            local.known.entry(k).or_insert(v);        }        local.book_stuck |= from.book_stuck;        local.book_tries = local.book_tries.max(from.book_tries);        if local.settings == cotton_core::sites::Settings::default() {            local.settings = from.settings;        }    }    Ok((local, read))}/// A name beside `path` for a carried file that did not open: `.unread`, then `.unread-2`, `-3`… so a second never/// writes over the first.fn unread_name(path: &std::path::Path) -> std::path::PathBuf {    let first = path.with_extension("c1.unread");    if !first.exists() {        return first;    }    (2..).map(|n| path.with_extension(format!("c1.unread-{n}"))).find(|p| !p.exists()).unwrap_or(first)}/// A name beside `file` for Sites' own file that did not open: `.unreadable`, then `.unreadable-2`, `-3`…fn unreadable_name(file: &std::path::Path) -> std::path::PathBuf {    let first = file.with_extension("c1.unreadable");    if !first.exists() {        return first;    }    (2..).map(|n| file.with_extension(format!("c1.unreadable-{n}"))).find(|p| !p.exists()).unwrap_or(first)}/// The carried files kept beside because they did not open, by name.fn unread_files(folder: &std::path::Path) -> Vec<String> {    let mut names: Vec<String> = std::fs::read_dir(folder).into_iter().flatten().flatten().map(|e| e.file_name().to_string_lossy().to_string()).filter(|n| (n.starts_with(CARRIED) || n.starts_with(LEFT_HERE)) && n.contains(".c1.unread")).collect();    names.sort();    names}/// The unread files the list has already said, beside them.const UNREAD_SAID: &str = "sites.unread-said.json";/// The files carried into this folder, in the order they are taken in: each copy's own file first (by name), then the/// sites kept only on this phone at sign-in (by name).fn carried_files(folder: &std::path::Path) -> Vec<std::path::PathBuf> {    let mut carried = Vec::new();    let mut left = Vec::new();    for entry in std::fs::read_dir(folder).into_iter().flatten().flatten() {        let name = entry.file_name().to_string_lossy().to_string();        if name == LEFT_HERE_FILE {            // This copy's own, waiting for its sign-in: carried on when one completes, never taken in here.            continue;        }        if !name.ends_with(".c1") {            continue;        }        if name.starts_with(LEFT_HERE) {            left.push(entry.path());        } else if name.starts_with(CARRIED) {            carried.push(entry.path());        }    }    carried.sort();    left.sort();    carried.extend(left);    carried}/// The file written into the copy's own folder, which must still stand: a folder moved aside or removed meanwhile/// (a sign-out, a switch, a deletion on another thread) takes nothing, and no folder is made for it.fn write_local(folder: &std::path::Path, key: &[u8; 32], local: &cotton_core::sites::Local, read: &[std::path::PathBuf]) -> Result<(), MethodError> {    if !folder.is_dir() {        return Err(MethodError::new("moved", "this copy moved while Sites wrote; nothing was written"));    }    let nonce: [u8; 12] = rand::random();    let bytes = local.seal(key, &nonce).ok_or_else(|| MethodError::new("unwritable", "Sites' own file could not be sealed"))?;    let file = folder.join(LOCAL);    let next = file.with_extension("c1.next");    {        use std::io::Write as _;        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let mut out = std::fs::File::create(&next).map_err(|e| MethodError::new("unwritable", format!("{LOCAL}: {e}")))?;        out.write_all(&bytes).and_then(|()| out.sync_all()).map_err(|e| MethodError::new("unwritable", format!("{LOCAL}: {e}")))?;    }    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    std::fs::rename(&next, &file).map_err(|e| MethodError::new("unwritable", format!("{LOCAL}: {e}")))?;    if let Ok(dir) = std::fs::File::open(folder) {        let _ = dir.sync_all();    }    // The carried files this call's read took in have done their work once the merged file stands, and none may bring    // back what this write let go (an orphan removed, an entry dropped). Only those: a file carried here after the    // read is taken in by the next one (review of SITES ROWS 5, item 1).    for path in read {        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let _ = std::fs::remove_file(path);    }    let stores: Vec<String> = local.entries.iter().map(|(k, e)| e.store.clone().unwrap_or_else(|| k.clone())).collect();    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    std::fs::write(folder.join(STORES), serde_json::to_vec(&stores).unwrap_or_default()).map_err(|e| MethodError::new("unwritable", format!("{STORES}: {e}")))}/// The table's live rows, every page, by key; and the keys of rows an earlier dev build kept as removed (`gone`).fn table_rows(client: &ClientController) -> Result<(std::collections::BTreeMap<String, Value>, Vec<String>), MethodError> {    let mut rows = std::collections::BTreeMap::new();    let mut dead = Vec::new();    let mut page = 0_i64;    loop {        let listed = table(client, false, "list_records", json!({ "table": SYNCED, "limit": 500, "page": page }))?;        for r in listed["records"].as_array().into_iter().flatten() {            if !r.get("deleted_at").is_none_or(Value::is_null) {                continue;            }            let Some(k) = r["data"]["key"].as_str().or_else(|| r["id"].as_str()).map(str::to_string) else { continue };            if r["data"]["gone"] == true {                dead.push(k);            } else {                rows.insert(k, r["data"].clone());            }        }        match listed["next_page"].as_i64() {            Some(next) if next > page => page = next,            _ => break,        }    }    Ok((rows, dead))}/// A row of the table as Sites draws it, with what this phone keeps of it (`entry`): a site with nothing kept here/// came from another phone, and says "Sign in once" until it is used.fn drawn_row(key: &str, data: &Value, entry: Option<&Row>) -> Row {    let text = |k: &str| data[k].as_str().unwrap_or_default().to_string();    let on = |k: &str, default: bool| data[k].as_bool().unwrap_or(default);    Row {        id: key.to_string(),        label: text("label"),        home: text("home"),        stay: on("stay", true),        hidden: on("hidden", false),        pinned: on("pinned", false),        trackers: on("trackers", true),        login: data["login"].as_str().filter(|l| !l.is_empty()).map(str::to_string),        last: entry.and_then(|e| e.last.clone()),        title: entry.and_then(|e| e.title.clone()),        state: entry.and_then(|e| e.state.clone()),        sign_in_once: entry.is_none_or(|e| e.sign_in_once),        waiting: entry.and_then(|e| e.waiting.clone()),        changed_at: 0,        store: entry.and_then(|e| e.store.clone()),    }}/// What this phone keeps of a synced site: its own fields only, never what the row says.fn kept_of(row: &Row) -> Row {    Row { id: row.id.clone(), label: String::new(), home: String::new(), stay: true, hidden: false, pinned: false, trackers: true, login: None, changed_at: 0, ..row.clone() }}fn place_of(data: &Value) -> f64 {    data["position"].as_f64().filter(|p| p.is_finite()).unwrap_or(f64::MAX / 4.0)}fn view(client: &ClientController, key: &[u8; 32]) -> Result<View, MethodError> {    let (database, folder) = local_folder(client)?;    let (local, carried) = read_local(&folder, key)?;    let (rows, _) = table_rows(client)?;    let mut all: Vec<(f64, String, Row)> = Vec::new();    // A site that went in under the key derived from its own is the site this phone holds a sign-in for: drawn with    // it, never asking "Sign in once" (review of NO SWITCH 2, item 4).    let by_derived: std::collections::BTreeMap<String, &Row> = local.entries.iter().map(|(k, e)| (derived_key(k), e)).collect();    for (k, data) in &rows {        if local.erasing.contains_key(k) || local.only.contains_key(k) {            continue;        }        let entry = local.entries.get(k).cloned().or_else(|| by_derived.get(k).map(|e| Row { id: k.clone(), store: Some(e.store.clone().unwrap_or_else(|| e.id.clone())), ..(*e).clone() }));        all.push((place_of(data), k.clone(), drawn_row(k, data, entry.as_ref())));    }    for (k, p) in &local.only {        // A run killed after it made the row at the derived key: the row is the site, never both.        if rows.contains_key(&derived_key(k)) {            continue;        }        if let (false, Some(e)) = (local.erasing.contains_key(k), local.entries.get(k)) {            all.push((*p, k.clone(), e.clone()));        }    }    all.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1)));    let places = all.iter().map(|(p, k, _)| (k.clone(), *p)).collect();    let book = Book { rows: all.into_iter().map(|(_, _, r)| r).collect(), settings: local.settings.clone() };    Ok(View { book, places, local, carried, folder, database })}/// The nine columns the live Worker serves, for a site's row.fn columns(row: &Row) -> serde_json::Map<String, Value> {    let mut data = serde_json::Map::new();    data.insert("key".into(), json!(row.id));    data.insert("label".into(), json!(row.label));    data.insert("home".into(), json!(row.home));    data.insert("stay".into(), json!(row.stay));    data.insert("hidden".into(), json!(row.hidden));    data.insert("pinned".into(), json!(row.pinned));    data.insert("trackers".into(), json!(row.trackers));    data.insert("login".into(), json!(row.login.clone().unwrap_or_default()));    data}/// The change written as the rows it changed: a new site is a row at its fresh key, an edit the columns it changed,/// a move the one place, a removal waits five seconds for its Undo (`tidy` erases it). What this phone keeps of each/// site is written to its own file. Every table write goes to the database the list was read from, or nowhere.fn commit(client: &ClientController, key: &[u8; 32], seen: &View, after: &Book) -> Result<(), MethodError> {    let mut local = seen.local.clone();    let now = now_ms();    for gone in seen.book.rows.iter().filter(|b| !after.rows.iter().any(|r| r.id == b.id)) {        local.erasing.insert(gone.id.clone(), now + UNDO_MS);    }    let order: Vec<String> = after.rows.iter().map(|r| r.id.clone()).collect();    let moved = cotton_core::sites::places(&order, &seen.places);    let mut writes: Vec<(&str, Value)> = Vec::new();    for row in &after.rows {        let place = moved.get(&row.id).or_else(|| seen.places.get(&row.id)).copied();        if local.only.contains_key(&row.id) {            if let Some(p) = place {                local.only.insert(row.id.clone(), p);            }            local.entries.insert(row.id.clone(), row.clone());            continue;        }        let now_cols = columns(row);        match seen.book.rows.iter().find(|b| b.id == row.id) {            None => {                let mut data = now_cols;                data.insert("position".into(), json!(place.unwrap_or(cotton_core::sites::PLACE_GAP)));                writes.push(("create_record", json!({ "table": SYNCED, "data": data })));            }            Some(before) => {                let was = columns(before);                let mut data: serde_json::Map<String, Value> = now_cols.into_iter().filter(|(k, v)| was.get(k) != Some(v)).collect();                if let Some(p) = moved.get(&row.id) {                    data.insert("position".into(), json!(p));                }                if !data.is_empty() {                    writes.push(("update_record", json!({ "table": SYNCED, "id": row.id, "patch": data })));                }            }        }        local.entries.insert(row.id.clone(), kept_of(row));    }    local.settings = after.settings.clone();    if !writes.is_empty() {        if client.current_database().ok().as_deref() != Some(seen.database.as_str()) {            return Err(MethodError::new("moved", "this copy moved while Sites wrote; nothing was written"));        }        for (tool, args) in writes {            match table(client, true, tool, args) {                // A place written as the number the row already holds (1024 and 1024.0).                Err(e) if e.message.contains("the patch changes nothing") => {}                other => {                    other?;                }            }        }    }    if local != seen.local || !seen.carried.is_empty() {        write_local(&seen.folder, key, &local, &seen.carried)?;    }    Ok(())}/// What waits, done before the list is drawn or changed: removals whose Undo ended are erased (kept waiting while/// an erase does not go); and once this copy has truly caught up (`caught_up`: no backlog, nothing of Sites parked,/// the device rows in, the data key held), sites this copy saw removed elsewhere let go of what this phone kept of/// them and owe their website stores, rows an earlier dev build kept as removed are erased, and this database's old/// book is taken in, once: its sites' own fields written here first, and the book deleted only after.fn tidy(client: &ClientController, key: &[u8; 32]) -> Result<(), MethodError> {    let (database, folder) = local_folder(client)?;    let (mut local, carried) = read_local(&folder, key)?;    let before = local.clone();    let now = now_ms();    let due: Vec<String> = local.erasing.iter().filter(|(_, at)| **at <= now).map(|(k, _)| k.clone()).collect();    let mut stores_gone = Vec::new();    for k in due {        // A site still in `only` has nothing to erase only when no row stands at its key; a row there (a run killed        // after its create, a left-here file whose rows also went up) is erased like any (review of NO SWITCH 2, 1).        let nothing_held = local.only.contains_key(&k) && matches!(held_at_all(client, &k), Ok(false));        let gone = nothing_held || match erase(client, &database, &k) {            Ok(()) => true,            Err(e) => {                tracing::warn!("sites: {k} waits to be erased ({}: {})", e.code, e.message);                !matches!(held_at_all(client, &k), Ok(true) | Err(_))            }        };        if gone {            local.erasing.remove(&k);            local.only.remove(&k);            local.gone.insert(k.clone());            // A site here whose row went in under the key derived from its own is that same site: it goes too.            let shadows: Vec<String> = local.only.keys().filter(|o| derived_key(o) == k).cloned().collect();            for o in shadows {                local.only.remove(&o);                local.gone.insert(o.clone());                if let Some(e) = local.entries.remove(&o) {                    stores_gone.push(e.store.unwrap_or(o));                }            }            if let Some(e) = local.entries.remove(&k) {                stores_gone.push(e.store.unwrap_or(k));            }        }    }    // Build 1's book, taken in but not yet set aside (the app ended between the two): set aside now.    let mut books_done = if local.migrated { old_books(client, &database) } else { Vec::new() };    // Each site's name as the rows hold it, on every read (a partial view only adds names); one whose row left keeps    // its name while this phone keeps the site.    if let Ok((rows, _)) = table_rows(client) {        // A site still here at a key whose row came from another phone: the row is the site. Nothing is queued; the        // stale entry goes from `only`, and what this phone kept of it (its sign-in, page, state) stays for the row.        let stale: Vec<String> = local.only.keys().filter(|k| rows.contains_key(*k) && !local.erasing.contains_key(*k)).cloned().collect();        for k in stale {            local.only.remove(&k);            if let Some(e) = local.entries.get(&k).map(kept_of) {                local.entries.insert(k, e);            }        }        let mut known = local.known.clone();        let mut known_hidden = local.known_hidden.clone();        // The flags are whole once nothing was known before them, or once a caught-up copy read every row; a name kept        // with no row (an older build's, its flag never written) is then taken as hidden, never shown before the unlock.        let mut filled = local.known_hidden_filled || known.is_empty();        if !filled && caught_up(client) {            known_hidden.extend(known.keys().filter(|k| !rows.contains_key(*k)).cloned());            filled = true;        }        for (k, data) in &rows {            known.insert(k.clone(), (data["label"].as_str().unwrap_or_default().to_string(), data["home"].as_str().unwrap_or_default().to_string()));            if data["hidden"].as_bool().unwrap_or(false) {                known_hidden.insert(k.clone());            } else {                known_hidden.remove(k);            }        }        // Names go only for sites a caught-up copy no longer holds and this phone keeps nothing of (only names).        if caught_up(client) {            known.retain(|k, _| rows.contains_key(k) || local.entries.contains_key(k));        }        known_hidden.retain(|k| known.contains_key(k));        local.known = known;        local.known_hidden = known_hidden;        local.known_hidden_filled = filled;    }    retire_set_aside(client);    // A site's sign-in store goes only when he removes that site here (above): never because its row is not in    // this copy (review of SITES ROWS 2, blocking 1). A store whose site left the list is offered, never taken.    if caught_up(client) {        let (rows, dead) = table_rows(client)?;        for k in dead {            if let Err(e) = erase(client, &database, &k) {                tracing::warn!("sites: a row kept as removed ({k}) was not erased ({}: {})", e.code, e.message);            }        }        retire_only(client, &database, &mut local, &rows)?;        if !local.migrated {            match migrate(client, key, &database, &mut local, &rows)? {                Migrated::Done(done) => {                    books_done = done;                    local.migrated = true;                    local.book_stuck = false;                }                Migrated::Later => {}                Migrated::Stuck => local.book_stuck = true,            }        }    }    if local != before || !carried.is_empty() {        write_local(&folder, key, &local, &carried)?;    }    // The old book is set aside only once what it held is written here.    for file in books_done {        set_aside(&file);    }    owe_stores(client, &stores_gone);    Ok(())}/// THE SWITCH IS GONE (owner, 27 Nov 2026: "We do not need that switch at all in sites"). The sites an earlier build/// kept only on this phone (`only`, from the switch, from "Keep only on this phone" at a sign-in, or from build 1's/// book) are made rows, once this copy has truly caught up (so a row it would learn of is here). A site is in `only`/// or it is a row, never both: each is made a row with the ordinary create (the outbox is the durable record, as for/// a site he adds offline) and leaves `only` in the same turn; from then on it is an ordinary row./// - Its key is decided, never drawn: its own key when a live row stands there or none was ever held or erased there;///   else a key derived from its own (`derived_key`), so a second run after a kill finds that row standing and only///   lets the site go from `only`./// - Its sign-in (its store), page and state stay in this phone's file under the row's key, as every site's do./// - A create refused leaves that one site in `only`, said once in the log; the rest go on.fn retire_only(client: &ClientController, database: &str, local: &mut cotton_core::sites::Local, rows: &std::collections::BTreeMap<String, Value>) -> Result<(), MethodError> {    if local.only.is_empty() || client.current_database().ok().as_deref() != Some(database) {        return Ok(());    }    let only: Vec<(String, f64)> = local.only.iter().map(|(k, p)| (k.clone(), *p)).collect();    for (k, place) in only {        // The copy moved on meanwhile (a sign-out, a switch): nothing more is made, in either copy.        if !same_database(client, database) {            return Ok(());        }        if local.erasing.contains_key(&k) {            // Removed here meanwhile: its erase lets it go.            continue;        }        let Some(entry) = local.entries.get(&k).cloned() else {            // Nothing of it kept here (no name, no address): nothing to make.            local.only.remove(&k);            continue;        };        let n = if rows.contains_key(&k) || free_key(client, &k)? { k.clone() } else { derived_key(&k) };        let row = Row { id: n.clone(), store: if n == k { entry.store.clone() } else { Some(entry.store.clone().unwrap_or_else(|| k.clone())) }, ..entry };        // Made unless it stands already: live, or held in the store (a run killed after its create; the outbox holds        // its write), or erased here (removed after a run made it: never made again).        let made = rows.contains_key(&n) || held_at_all(client, &n)? || (n != k && !free_key(client, &n)?);        if !made {            let mut data = columns(&row);            data.insert("position".into(), json!(place));            #[cfg(test)]            let refused_here = TEST_REFUSE.with(|r| r.borrow().as_deref() == Some(k.as_str()));            #[cfg(not(test))]            let refused_here = false;            let made_now = if refused_here { Err(MethodError::new("refused", "test: the create is refused")) } else { table(client, true, "create_record", json!({ "table": SYNCED, "data": data })) };            if let Err(e) = made_now {                if REFUSED_SAID.lock().unwrap_or_else(|p| p.into_inner()).insert(k.clone()) {                    tracing::warn!("sites: an earlier site stays on this phone for now; its row was refused ({}: {})", e.code, e.message);                }                continue;            }            #[cfg(test)]            if let Some(stop) = after_create_for_tests() {                return Err(MethodError::new("killed", stop));            }        }        local.only.remove(&k);        if n != k {            local.entries.remove(&k);            local.gone.insert(k.clone());        }        local.entries.insert(n.clone(), kept_of(&row));    }    Ok(())}/// Whether the attached copy is still `database`.fn same_database(client: &ClientController, database: &str) -> bool {    #[cfg(test)]    if TEST_RETIRE.with(|t| t.get()).is_some_and(|(left, kill)| left == 0 && !kill) {        return false;    }    client.current_database().ok().as_deref() == Some(database)}// Tests only: after `left` more creates, the run is killed (`kill`) or the copy is switched; and the one key whose// create is refused.#[cfg(test)]thread_local! {    static TEST_RETIRE: std::cell::Cell<Option<(usize, bool)>> = const { std::cell::Cell::new(None) };    static TEST_REFUSE: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };}#[cfg(test)]pub(crate) fn refuse_create_for_tests(key: Option<&str>) {    TEST_REFUSE.with(|r| *r.borrow_mut() = key.map(str::to_string));}#[cfg(test)]fn after_create_for_tests() -> Option<&'static str> {    TEST_RETIRE.with(|t| match t.get() {        Some((0, true)) => {            t.set(None);            Some("test: killed between the create and the file write")        }        Some((left, kill)) if left > 0 => {            t.set(Some((left - 1, kill)));            if left - 1 == 0 && kill {                t.set(None);                return Some("test: killed between the create and the file write");            }            None        }        _ => None,    })}/// Tests only: kill the migration after `creates` creates (`kill`), or switch the copy after them.#[cfg(test)]pub(crate) fn stop_retire_for_tests(creates: usize, kill: bool) {    TEST_RETIRE.with(|t| t.set(Some((creates, kill))));}#[cfg(test)]pub(crate) fn go_on_retire_for_tests() {    TEST_RETIRE.with(|t| t.set(None));}/// Whether a refused row of the old book was said in the log: once a launch.static BOOK_REFUSED_SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// The sites whose row was refused, said once each in the log.static REFUSED_SAID: Mutex<std::collections::BTreeSet<String>> = Mutex::new(std::collections::BTreeSet::new());/// The fresh key a site kept only here goes in under when its own is taken: decided by its own key (a UUID, version 4/// shape, from SHA-256 of it), so every run makes the same one.pub(crate) fn derived_key(key: &str) -> String {    use sha2::Digest as _;    let digest = sha2::Sha256::digest(format!("cotton-sites-only:{key}").as_bytes());    let mut b = [0u8; 16];    b.copy_from_slice(&digest[..16]);    b[6] = (b[6] & 0x0f) | 0x40;    b[8] = (b[8] & 0x3f) | 0x80;    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();    format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])}/// Whether a row may be made at `key`: this copy holds none there in any state and never erased one.fn free_key(client: &ClientController, key: &str) -> Result<bool, MethodError> {    if held_at_all(client, key)? {        return Ok(false);    }    client        .with_file(|file| Ok(file.driver.get("SELECT 1 AS v FROM _gone WHERE tbl = ?1 AND row_id = ?2 LIMIT 1", &[rusqlite::types::Value::Text(SITE_STORE.into()), rusqlite::types::Value::Text(key.to_string())]).map_err(|e| e.to_string())?.is_none()))        .map_err(|e| MethodError::new("unreadable", e))}/// Erase one row for good (decision 1, 26 Nov 2026): binned and then erased through the bin's own eraser, so it never/// waits in his Bin; on the database the list was read from, or not at all.fn erase(client: &ClientController, database: &str, k: &str) -> Result<(), MethodError> {    if client.current_database().ok().as_deref() != Some(database) {        return Err(MethodError::new("moved", "this copy moved; nothing was erased"));    }    let _ = table(client, true, "delete_record", json!({ "table": SYNCED, "id": k }));    table(client, true, "erase", json!({ "id": k })).map(|_| ())}/// The old book an earlier build kept on this phone (`client/sites.c1`, build 1's one book) and the database it/// belongs to, marked at the first launch of the rows build before anything else: the copy that stood then, the/// account's or the phone's own signed-out one (review of SITES ROWS, item 8). Never another account's.fn owner_of(file: &std::path::Path) -> std::path::PathBuf {    file.with_extension("c1.owner")}fn claim_old_book(client: &ClientController) {    let file = client.layout().client_dir().join(FILE);    let owner = owner_of(&file);    if !file.exists() || owner.exists() {        return;    }    if let Ok(database) = client.current_database() {        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let _ = std::fs::write(&owner, database);    }}fn old_books(client: &ClientController, database: &str) -> Vec<std::path::PathBuf> {    let file = client.layout().client_dir().join(FILE);    let ours = std::fs::read_to_string(owner_of(&file)).is_ok_and(|owner| owner.trim() == database);    if file.exists() && ours { vec![file] } else { Vec::new() }}/// What taking in the old book came to.enum Migrated {    /// Taken in: these books are set aside once Sites' file holds what they held.    Done(Vec<std::path::PathBuf>),    /// Not this time (a read that failed decides nothing).    Later,    /// The book does not open with this phone's key: said in the list, tried again each time.    Stuck,}/// This database's old book taken in, once, after a caught-up pull (SYNC-DESIGN.md "The migration"). No site of the/// book is ever dropped (review of SITES ROWS 2, decision 2), and none is kept only on this phone (the switch is gone,/// 27 Nov 2026):/// - a site the copy holds keeps its own fields here by key, what was saved while it waited winning, and the row's;/// - a site the copy does not hold is written into the list: at its key when this copy never held a row there, else///   at a fresh key keeping its sign-in (a site removed elsewhere comes back, never lost; he can remove it again).fn migrate(client: &ClientController, key: &[u8; 32], database: &str, local: &mut cotton_core::sites::Local, rows: &std::collections::BTreeMap<String, Value>) -> Result<Migrated, MethodError> {    let mut done = Vec::new();    for file in old_books(client, database) {        let Ok(bytes) = std::fs::read(&file) else {            local.book_tries += 1;            return Ok(if local.book_tries >= 3 { Migrated::Stuck } else { Migrated::Later });        };        let Some(book) = Book::open(key, &bytes) else { return Ok(Migrated::Stuck) };        let mut last = rows.values().map(place_of).filter(|p| *p < f64::MAX / 8.0).chain(local.only.values().copied()).fold(0.0_f64, f64::max);        let mut kept = Vec::new();        let mut creates = Vec::new();        for r in &book.rows {            if rows.contains_key(&r.id) {                kept.push(kept_of(r));                continue;            }            let Ok(free) = free_key(client, &r.id) else { return Ok(Migrated::Later) };            last += cotton_core::sites::PLACE_GAP;            // A taken key goes in under the one derived from it, so a run killed after its creates makes nothing twice.            let at = if !free { Row { id: derived_key(&r.id), store: Some(r.store.clone().unwrap_or_else(|| r.id.clone())), ..r.clone() } } else { r.clone() };            let Ok(held) = held_at_all(client, &at.id) else { return Ok(Migrated::Later) };            let erased = !free && !matches!(free_key(client, &at.id), Ok(true));            if !held && !erased {                let mut data = columns(&at);                data.insert("position".into(), json!(last));                creates.push(json!({ "table": SYNCED, "data": data }));            }            kept.push(kept_of(&at));        }        if client.current_database().ok().as_deref() != Some(database) {            return Ok(Migrated::Later);        }        for args in creates {            // Refused: the book stays and is tried again; no other Sites act fails for it (review of NO SWITCH, item 5).            if let Err(e) = table(client, true, "create_record", args) {                if !BOOK_REFUSED_SAID.swap(true, std::sync::atomic::Ordering::SeqCst) {                    tracing::warn!("sites: the earlier list waits; a row was refused ({}: {})", e.code, e.message);                }                return Ok(Migrated::Later);            }        }        for e in kept {            let merged = match local.entries.get(&e.id) {                Some(waited) => merged_kept(waited, &e),                None => e,            };            local.entries.insert(merged.id.clone(), merged);        }        if local.settings == cotton_core::sites::Settings::default() {            local.settings = cotton_core::sites::Settings { synced: false, ..book.settings.clone() };        }        done.push(file);    }    Ok(Migrated::Done(done))}/// What this phone kept of a site, from the old book (`from`) under what was saved while the migration waited/// (`waited`): field by field, the wait's values win (they are newer than any book), the book fills what is empty.fn merged_kept(waited: &Row, from: &Row) -> Row {    let (last, title) = if waited.last.is_some() { (waited.last.clone(), waited.title.clone()) } else { (from.last.clone(), from.title.clone()) };    Row {        last,        title,        state: waited.state.clone().or_else(|| from.state.clone()),        waiting: waited.waiting.clone().or_else(|| from.waiting.clone()),        store: waited.store.clone().or_else(|| from.store.clone()),        sign_in_once: waited.sign_in_once && from.sign_in_once,        ..waited.clone()    }}/// Build 1's book set aside as `sites.c1.migrated` once taken in, kept 30 days in case, then removed (`retire_set_aside`).fn set_aside(file: &std::path::Path) {    let aside = file.with_extension("c1.migrated");    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    if std::fs::rename(file, &aside).is_ok() {        if let Ok(f) = std::fs::File::options().write(true).open(&aside) {            let _ = f.set_modified(std::time::SystemTime::now());        }        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let _ = std::fs::remove_file(owner_of(file));    }}fn retire_set_aside(client: &ClientController) {    let aside = client.layout().client_dir().join(FILE).with_extension("c1.migrated");    let old = std::fs::metadata(&aside).and_then(|m| m.modified()).ok().and_then(|at| at.elapsed().ok()).is_some_and(|age| age > std::time::Duration::from_secs(30 * 24 * 3600));    if old {        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let _ = std::fs::remove_file(&aside);    }}/// `sites.book.leave`: he leaves the old book that does not open on this phone; it is set aside (kept 30 days).fn book_leave(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let key = key(request)?;    let client = handle.client();    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    let (database, folder) = local_folder(&client)?;    let (mut local, read) = read_local(&folder, &key)?;    local.migrated = true;    local.book_stuck = false;    write_local(&folder, &key, &local, &read)?;    for file in old_books(&client, &database) {        set_aside(&file);    }    Ok(json!({ "left": true }))}/// What `sites.home` says beside the list, from what this phone keeps: sites kept here from the old book that are/// not on his other devices, the old book that does not open, sign-ins of sites no longer in the list, and while a/// signed-in copy is still loading, the sites it held before, greyed.pub(crate) fn home_extras(client: &ClientController, key: &[u8; 32], answer: &mut Value) {    let Ok((_, folder)) = local_folder(client) else { return };    let Ok((local, _)) = read_local(&folder, key) else { return };    let drawn: std::collections::BTreeSet<String> = answer.get("rows").and_then(Value::as_array).into_iter().flatten().chain(answer.get("hidden").and_then(|h| h.get("rows")).and_then(Value::as_array).into_iter().flatten()).filter_map(|r| r["id"].as_str().map(str::to_string)).collect();    if local.book_stuck && !local.migrated {        answer["book_stuck"] = json!({ "line": app::s("book_stuck.line"), "leave": app::s("book_stuck.leave") });    }    // Sites carried from another copy that would not open here: said once, the files kept.    let unread = unread_files(&folder);    let said: Vec<String> = std::fs::read(folder.join(UNREAD_SAID)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    if unread.iter().any(|n| !said.contains(n)) {        answer["unread"] = json!({ "line": app::s("unread.line") });        // Under the lock every write of Sites' files takes (ROWS 8, low).        let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());        // not a copy: Sites' own note of which unread files were said.        let _ = std::fs::write(folder.join(UNREAD_SAID), serde_json::to_vec(&unread).unwrap_or_default());    }    // A hidden site is named only while the hidden sites show, as the loaded list draws it (its flag not yet filled: as hidden).    let shown = answer.get("hidden").and_then(|h| h["locked"].as_bool()) == Some(false);    let hidden = |k: &str| !local.known_hidden_filled || local.known_hidden.contains(k);    let found: Vec<(String, String)> = orphans(client, key).into_iter().filter(|(k, _)| shown || !hidden(k)).collect();    if !found.is_empty() {        let sites: Vec<Value> = found.iter().map(|(id, label)| json!({ "id": id, "label": label })).collect();        answer["orphans"] = json!({ "line": app::s("orphans.line"), "remove": app::s("orphans.remove"), "sites": sites });    }    // Loading until this copy has been caught up once since it opened (a pass running never brings it back).    if !caught_up_once(client) {        // A hidden site only while the hidden sites show, as the loaded list draws it (never its name before Face ID).        // Flags an older build never wrote: nothing waiting is drawn until they are filled.        let waiting: Vec<Value> = local            .known            .iter()            .filter(|_| local.known_hidden_filled)            .filter(|(k, _)| !drawn.contains(*k) && !local.erasing.contains_key(*k))            .filter(|(k, _)| shown || !local.known_hidden.contains(*k))            .map(|(k, (label, home))| json!({ "id": k, "label": label, "site": cotton_core::sites::host_of(home), "letter": app::letter(label), "waiting": true, "hidden": local.known_hidden.contains(k) }))            .collect();        answer["loading"] = json!({ "line": app::s("loading.line") });        if !waiting.is_empty() {            answer["waiting_rows"] = json!(waiting);        } else if drawn.is_empty() {            // Not an Add alone while the list may still be on its way (it would make the same sites again).            if let Some(o) = answer.as_object_mut() {                o.remove("add");            }        }    }}/// Sign-in stores whose site is no longer in the list (removed on another phone, or never back after a copy was made/// again): offered in You one by one ("Sign-ins for sites no longer in your list"), never removed on their own, and/// never offered unless the old book is taken in, the copy is caught up and holds rows, and they are at most half of/// what this phone keeps (more says something is off: then nothing is said).pub(crate) fn orphans(client: &ClientController, key: &[u8; 32]) -> Vec<(String, String)> {    if !caught_up(client) {        return Vec::new();    }    let Ok((_, folder)) = local_folder(client) else { return Vec::new() };    let Ok((local, _)) = read_local(&folder, key) else { return Vec::new() };    let Ok((rows, _)) = table_rows(client) else { return Vec::new() };    if !local.migrated || rows.is_empty() {        return Vec::new();    }    let found: Vec<(String, String)> = local        .entries        .keys()        .filter(|k| !rows.contains_key(*k) && !local.only.contains_key(*k) && !local.erasing.contains_key(*k))        .map(|k| (k.clone(), local.known.get(k).map(|(label, _)| label.clone()).unwrap_or_default()))        .collect();    if found.len() * 2 > local.entries.len() {        return Vec::new();    }    found}/// `sites.orphans.remove {id}`: he removes the sign-in of one site no longer in his list, checked again at the tap.fn orphans_remove(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let key = key(request)?;    let id = request.get("id").and_then(Value::as_str).unwrap_or_default().to_string();    let client = handle.client();    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    if !orphans(&client, &key).iter().any(|(k, _)| *k == id) {        return Ok(json!({ "removed": 0 }));    }    let (_, folder) = local_folder(&client)?;    let (mut local, read) = read_local(&folder, &key)?;    let Some(e) = local.entries.remove(&id) else { return Ok(json!({ "removed": 0 })) };    local.gone.insert(id.clone());    local.known.remove(&id);    write_local(&folder, &key, &local, &read)?;    owe_stores(&client, &[e.store.unwrap_or(id)]);    Ok(json!({ "removed": 1 }))}/// Whether this copy holds a row at `key` in any state (live, binned): a key it holds is never created again.fn held_at_all(client: &ClientController, key: &str) -> Result<bool, MethodError> {    client        .with_file(|file| Ok(file.driver.get("SELECT id FROM cotton_site WHERE id = ?1", &[rusqlite::types::Value::Text(key.to_string())]).map_err(|e| e.to_string())?.is_some()))        .map_err(|e| MethodError::new("unreadable", e))}/// Website stores whose site is gone, kept for the shell to remove.fn owe_stores(client: &ClientController, stores: &[String]) {    if stores.is_empty() {        return;    }    owe_stores_in(&client.layout().client_dir(), stores);}fn owe_stores_in(dir: &std::path::Path, stores: &[String]) {    let file = dir.join(STORES_GONE);    let mut owed: Vec<String> = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    for s in stores {        if !owed.contains(s) {            owed.push(s.clone());        }    }    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    let _ = std::fs::write(&file, serde_json::to_vec(&owed).unwrap_or_default());}/// `sites.stores.gone`: the website stores to remove, named as `sites.open` names them. Never on a partial view: the/// cleanup that finds them runs only after a caught-up pull. Stores he said Keep for now to (`sites.stores.keep`) are/// left out for good; `kept` is true when every owed store is one of them.fn stores_gone(client: &ClientController) -> Value {    let dir = client.layout().client_dir();    let owed: Vec<String> = std::fs::read(dir.join(STORES_GONE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    let kept: Vec<String> = std::fs::read(dir.join(STORES_KEPT)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    let all_kept = !owed.is_empty() && owed.iter().all(|s| kept.contains(&store(s)));    // Only what is newly owed: the stores he kept stay kept, never named again.    json!({ "stores": owed.iter().filter(|s| !kept.contains(&store(s))).map(|s| json!({ "store": store(s), "store_uuid": sites::store_uuid(s) })).collect::<Vec<_>>(), "kept": all_kept })}/// Website stores he said Keep for now to (`sites.stores.keep`), as `sites.stores.gone` names them.const STORES_KEPT: &str = "sites-stores-kept.json";/// `sites.stores.keep {stores}`: he said Keep for now to these, added to those he kept before; never named again.fn stores_keep(client: &ClientController, request: &Value) -> Value {    let file = client.layout().client_dir().join(STORES_KEPT);    let mut kept: Vec<String> = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    for s in request.get("stores").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {        if !kept.iter().any(|k| k == s) {            kept.push(s.to_string());        }    }    // not a copy: Sites' own note of the stores he said Keep for now to.    let _ = std::fs::write(&file, serde_json::to_vec(&kept).unwrap_or_default());    json!({ "kept": kept.len() })}/// `sites.stores.removed {stores}`: the shell removed these.fn stores_removed(client: &ClientController, request: &Value) -> Value {    let done: Vec<String> = request.get("stores").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();    let file = client.layout().client_dir().join(STORES_GONE);    let owed: Vec<String> = std::fs::read(&file).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default();    let left: Vec<String> = owed.into_iter().filter(|s| !done.contains(&store(s))).collect();    // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.    let _ = std::fs::write(&file, serde_json::to_vec(&left).unwrap_or_default());    let kept_file = client.layout().client_dir().join(STORES_KEPT);    if let Some(kept) = std::fs::read(&kept_file).ok().and_then(|b| serde_json::from_slice::<Vec<String>>(&b).ok()) {        // not a copy: Sites' own note of the stores he said Keep for now to.        let _ = std::fs::write(&kept_file, serde_json::to_vec(&kept.into_iter().filter(|s| !done.contains(s)).collect::<Vec<_>>()).unwrap_or_default());    }    json!({ "left": left.len() })}/// A database folder about to go for good (the account deleted, `copy_aside::forget`): the website stores its sites/// named are owed for removal. Read from the plain list beside Sites' file, so no Sites key is needed.pub(crate) fn folder_forgotten(layout: &cotton_client::layout::Layout, folder: &std::path::Path) {    fn find(dir: &std::path::Path, depth: usize, out: &mut Vec<String>) {        if let Some(stores) = std::fs::read(dir.join(STORES)).ok().and_then(|b| serde_json::from_slice::<Vec<String>>(&b).ok()) {            out.extend(stores);        }        if depth == 0 {            return;        }        for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {            if entry.file_type().is_ok_and(|t| t.is_dir()) {                find(&entry.path(), depth - 1, out);            }        }    }    let mut stores = Vec::new();    find(folder, 3, &mut stores);    owe_stores_in(&layout.client_dir(), &stores);}/// An adopt or a copy made again is about to remove the old copy's folder: what Sites kept there goes with the sites/// to the new copy (taken in at its next read).pub(crate) fn carry(layout: &cotton_client::layout::Layout, from: &str, to: &str) -> Result<(), String> {    let carried = carry_once(layout, from, to);    // Owed, for the next launch and the next list open (review of SITES ROWS 6, item 1): one entry per pair of copies,    // each cleared only by its own carry going (ROWS 8, item 3).    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    let mut owed = carries_owed(layout);    owed.retain(|(f, t)| !(f == from && t == to));    if carried.is_err() {        owed.push((from.to_string(), to.to_string()));    }    write_carries_owed(layout, &owed);    carried}/// Carries that failed, waiting to be tried again: `[{from, to}]`.const CARRY_OWED: &str = "sites-carry-owed.json";fn carries_owed(layout: &cotton_client::layout::Layout) -> Vec<(String, String)> {    let Some(record) = std::fs::read(layout.client_dir().join(CARRY_OWED)).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) else { return Vec::new() };    record.as_array().into_iter().flatten().filter_map(|e| Some((e["from"].as_str()?.to_string(), e["to"].as_str()?.to_string()))).collect()}fn write_carries_owed(layout: &cotton_client::layout::Layout, owed: &[(String, String)]) {    let file = layout.client_dir().join(CARRY_OWED);    if owed.is_empty() {        // not a copy: Sites' own note of a carry owed.        let _ = std::fs::remove_file(&file);        return;    }    let list: Vec<Value> = owed.iter().map(|(from, to)| json!({ "from": from, "to": to })).collect();    // not a copy: Sites' own note of a carry owed.    let _ = std::fs::write(&file, serde_json::to_vec(&list).unwrap_or_default());}/// Try each failed carry again (next launch, next list open): once one goes, its earlier copy's folder goes as the adopt/// would have removed it. A carry from the copy now in use, or from a folder no longer here, is owed no more; one to a/// copy since moved on (a to b, then b to c) goes to the copy now in use instead (NO SWITCH 2, item 4). Answers whether/// any went.pub(crate) fn retry_carry(layout: &cotton_client::layout::Layout, current: Option<&str>) -> bool {    let mut went = false;    let forget = |from: &str, to: &str| {        let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());        let mut owed = carries_owed(layout);        owed.retain(|(f, t)| !(f == from && t == to));        write_carries_owed(layout, &owed);    };    for (from, owed_to) in carries_owed(layout) {        if Some(from.as_str()) == current || layout.replica(&from).parent().is_none_or(|old| !old.is_dir()) {            forget(&from, &owed_to);            continue;        }        let to = if layout.replica(&owed_to).parent().is_some_and(std::path::Path::is_dir) {            owed_to.clone()        } else {            match current {                Some(now) => now.to_string(),                None => continue,            }        };        if carry(layout, &from, &to).is_err() {            continue;        }        #[cfg(test)]        if TEST_CARRY_KILLED.with(|k| k.replace(false)) {            return went;        }        // Forgotten only once carried: a kill before this carries it again next time (review of NO SWITCH 2, item 3).        forget(&from, &owed_to);        // The earlier copy and its media leave through the one function, filed under the database it was adopted        // into (QUEUE BAD OP 6): what it holds beyond what went keeps it aside.        crate::phone::personal_object::remove_database_folder(layout, &from, cotton_client::copy_keep::Ending::keep_into("a local database was adopted into the signed-in copy", &to, &[]));        went = true;    }    went}fn carry_once(layout: &cotton_client::layout::Layout, from: &str, to: &str) -> Result<(), String> {    let (Some(old), Some(new)) = (layout.replica(from).parent().map(std::path::Path::to_path_buf), layout.replica(to).parent().map(std::path::Path::to_path_buf)) else { return Ok(()) };    if old == new {        return Ok(());    }    // Under the lock every write of the list takes, so no write in between can miss a file carried here.    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    // A copy that fails stops the old folder's removal: for sites kept only on this phone it is their only route    // (review of SITES ROWS 5, item 2).    if old.join(LOCAL).exists() {        copy_whole(&old.join(LOCAL), &new, &format!("{CARRIED}{from}.c1")).map_err(|e| format!("what this phone kept of its sites did not move to the new copy ({e})"))?;    }    // Build 1's book belongs to the copy that stood at the rows build's first launch: it follows that copy here.    let book = layout.client_dir().join(FILE);    if std::fs::read_to_string(owner_of(&book)).is_ok_and(|owner| owner.trim() == from) {        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        std::fs::write(owner_of(&book), to).map_err(|e| format!("Sites' earlier list did not follow the new copy ({e})"))?;    }    // Sites an earlier build kept only on this phone at sign-in come along whole, to be written into the list there.    if old.join(LEFT_HERE_FILE).exists() {        copy_whole(&old.join(LEFT_HERE_FILE), &new, &format!("{LEFT_HERE}{from}.c1")).map_err(|e| format!("the sites kept only on this phone did not move to the new copy ({e})"))?;        // Read once, at this sign-in: never carried again by a later one (review of NO SWITCH 2, item 6).        // not a copy: the sites kept only on this phone, copied whole to the new copy first (copy_whole above).        let _ = std::fs::remove_file(old.join(LEFT_HERE_FILE));    }    Ok(())}/// Copy `from` into `folder` as `name`, whole or not at all: written beside under a name no read takes, synced, then/// renamed into place.fn copy_whole(from: &std::path::Path, folder: &std::path::Path, name: &str) -> std::io::Result<()> {    if !folder.is_dir() {        return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "the new copy has no folder"));    }    let part = folder.join(format!("{name}.part"));    let result = (|| {        let bytes = std::fs::read(from)?;        #[cfg(test)]        if CARRY_FAILS.lock().unwrap_or_else(|p| p.into_inner()).iter().any(|f| Some(f.as_path()) == from.parent()) {            return Err(std::io::Error::other("no space left on device (test)"));        }        use std::io::Write as _;        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let mut out = std::fs::File::create(&part)?;        out.write_all(&bytes)?;        out.sync_all()?;        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        std::fs::rename(&part, folder.join(name))?;        if let Ok(dir) = std::fs::File::open(folder) {            let _ = dir.sync_all();        }        Ok(())    })();    if result.is_err() {        // not a copy: a Sites file of its own (its book, its sealed local file, its lists and marks), never a copy.        let _ = std::fs::remove_file(&part);    }    result}// Tests only: the run killed right after an owed carry went, before it is forgotten.#[cfg(test)]thread_local! {    static TEST_CARRY_KILLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };}#[cfg(test)]pub(crate) fn kill_after_carry_for_tests() {    TEST_CARRY_KILLED.with(|k| k.set(true));}/// Tests only: folders a carry out of fails, as a full disk would.#[cfg(test)]static CARRY_FAILS: Mutex<Vec<std::path::PathBuf>> = Mutex::new(Vec::new());#[cfg(test)]pub(crate) fn carry_fails_from_for_tests(folder: &std::path::Path) {    CARRY_FAILS.lock().unwrap_or_else(|p| p.into_inner()).push(folder.to_path_buf());}#[cfg(test)]pub(crate) fn carry_goes_from_for_tests(folder: &std::path::Path) {    CARRY_FAILS.lock().unwrap_or_else(|p| p.into_inner()).retain(|f| f != folder);}/// The store table Sites' rows live in, as the adopt names a row.pub(crate) const SITE_STORE: &str = "cotton_site";/// Whether this copy has been caught up at least once since it opened, with the key held: what "Loading your list…"/// waits for (review of SITES ROWS 3, item 2).fn caught_up_once(client: &ClientController) -> bool {    #[cfg(test)]    if let Some(on) = TEST_CAUGHT_UP.with(std::cell::Cell::get) {        return on;    }    match account(client) {        Ok(None) => return true,        Ok(Some(_)) => {}        Err(_) => return false,    }    let Ok(database) = client.current_database() else { return false };    use cotton_client::seal::DataKeyStore as _;    client.caught_up_once(&database) && client.data_keys().data_key(&database).is_ok_and(|k| k.is_some())}/// Whether this copy has truly caught up, for Sites' purposes (review of SITES ROWS, item 5): always, for the phone's/// own copy (nothing to pull); for an account's, only when its last pass ended with nothing still to come/// (`ClientController::caught_up`), the data key is held, and no row of the `site` table waits parked for it.fn caught_up(client: &ClientController) -> bool {    #[cfg(test)]    if let Some(on) = TEST_CAUGHT_UP.with(std::cell::Cell::get) {        return on;    }    match account(client) {        Ok(None) => return true,        Ok(Some(_)) => {}        Err(_) => return false,    }    let Ok(database) = client.current_database() else { return false };    if !client.caught_up(&database) {        return false;    }    use cotton_client::seal::DataKeyStore as _;    if !client.data_keys().data_key(&database).is_ok_and(|k| k.is_some()) {        return false;    }    client        .with_file(|file| {            let parked = file.driver.get("SELECT 1 AS v FROM sqlite_master WHERE type = 'table' AND name = '_seal_parked'", &[]).map_err(|e| e.to_string())?.is_some()                && file.driver.get("SELECT 1 AS v FROM _seal_parked WHERE tbl = ?1 LIMIT 1", &[rusqlite::types::Value::Text(SYNCED.into())]).map_err(|e| e.to_string())?.is_some();            Ok(!parked)        })        .unwrap_or(false)}#[cfg(test)]thread_local! {    static TEST_CAUGHT_UP: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };    static TEST_LATER: std::cell::Cell<i64> = const { std::cell::Cell::new(0) };    static TEST_FROZEN: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };}/// A change made straight to the list, through the same commit as every method (tests only).#[cfg(test)]pub(crate) fn with_book_for_tests(handle: &CottonHandle, work: impl FnOnce(&mut Book)) -> Result<Value, MethodError> {    let request = json!({ "key": "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" });    change(handle, &request, |book| {        work(book);        Ok(json!({}))    })}#[cfg(test)]pub(crate) fn table_for_tests(client: &ClientController, write: bool, tool: &str, args: Value) -> Result<Value, MethodError> {    table(client, write, tool, args)}/// One call on the `site` table, through the table tools themselves: no tool draws Sites' list, so the generic/// `records.*` refuses it (as it does Post's accounts).fn table(client: &ClientController, write: bool, tool: &str, args: Value) -> Result<Value, MethodError> {    use cotton_tools::mcp::handlers::tables;    let args = args.as_object().cloned().unwrap_or_default();    let mut body = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>| -> Result<Value, String> {        match tool {            "list_records" => tables::list_records(ctx, &args),            "create_record" => tables::create_record(ctx, &args),            "update_record" => tables::update_record(ctx, &args),            "delete_record" => tables::delete_record(ctx, &args),            "erase" => tables::erase_one_binned(ctx, args.get("id").and_then(Value::as_str).unwrap_or_default()).map(|()| json!({ "erased": true })),            other => unreachable!("sites calls no {other}"),        }        .map_err(|failure| failure.to_string())    };    let answer = if write { client.write_rows("sites.sync", &mut body) } else { client.read_rows("sites.sync", &mut body) };    answer.map_err(|why| MethodError::new(if write { "write_refused" } else { "unreadable" }, why))}fn now_ms() -> i64 {    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);    #[cfg(test)]    let now = TEST_FROZEN.with(std::cell::Cell::get).unwrap_or(now) + TEST_LATER.with(std::cell::Cell::get);    now}/// The list taken in before Sites draws it: what waits done first (`tidy`).pub(crate) fn take_in(client: &ClientController, key: &[u8; 32]) -> Result<Book, MethodError> {    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    if !served(client)? {        return read_book(client, key);    }    claim_old_book(client);    if let Err(why) = tidy(client, key) {        tracing::warn!("sites: what waits was not done before drawing the list ({}: {})", why.code, why.message);    }    Ok(view(client, key)?.book)}/// `sites.undo {id}`: a removal brought back within its five seconds; nothing after.fn undo(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {    let key = key(request)?;    let client = handle.client();    let _held = LOCK.lock().unwrap_or_else(|p| p.into_inner());    let id = request.get("id").and_then(Value::as_str).unwrap_or_default();    let (_, folder) = local_folder(&client)?;    let (mut local, read) = read_local(&folder, &key)?;    // Within its five seconds, or for as long as the erase has not gone (held back by the guard): nothing after.    match local.erasing.get(id) {        Some(_) => {            local.erasing.remove(id);            write_local(&folder, &key, &local, &read)?;            Ok(json!({ "undone": id }))        }        _ => Err(refused(&list::lines(), Refused::NoRow)),    }}/// The calls the rows model adds (SYNC-DESIGN.md, design 2).pub(crate) fn rows_call(handle: &CottonHandle, method: &str, request: &Value) -> Option<Result<Value, MethodError>> {    let client = handle.client();    Some(match method {        "sites.undo" => undo(handle, request),        "sites.book.leave" => book_leave(handle, request),        "sites.orphans.remove" => orphans_remove(handle, request),        "sites.stores.gone" => Ok(stores_gone(&client)),        "sites.stores.removed" => Ok(stores_removed(&client, request)),        "sites.stores.keep" => Ok(stores_keep(&client, request)),        _ => return None,    })}/// A fresh UUID (version 4): the row's id, which names its website store.pub(crate) fn new_id() -> String {    let mut b: [u8; 16] = rand::random();    b[6] = (b[6] & 0x0f) | 0x40;    b[8] = (b[8] & 0x3f) | 0x80;    let h: String = b.iter().map(|x| format!("{x:02x}")).collect();    format!("{}-{}-{}-{}-{}", &h[0..8], &h[8..12], &h[12..16], &h[16..20], &h[20..32])}#[cfg(test)]#[path = "sites_tests.rs"]mod tests;#[cfg(test)]#[path = "sites_rows_tests.rs"]mod rows_tests;// Test hooks: what the rows tests ask of the core.#[cfg(test)]pub(crate) fn caught_up_for_tests(_client: &ClientController, on: bool) {    TEST_CAUGHT_UP.with(|c| c.set(Some(on)));}/// Each test starts with Sites' own clock and caught-up as a phone has them (a test thread may be reused).#[cfg(test)]pub(crate) fn reset_for_tests() {    TEST_CAUGHT_UP.with(|c| c.set(None));    TEST_LATER.with(|c| c.set(0));    TEST_FROZEN.with(|c| c.set(None));    TEST_RETIRE.with(|c| c.set(None));    TEST_REFUSE.with(|c| *c.borrow_mut() = None);    TEST_CARRY_KILLED.with(|c| c.set(false));}/// Sites' clock held still for a test (a loaded box takes seconds between two calls).#[cfg(test)]pub(crate) fn freeze_for_tests() {    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis() as i64);    TEST_FROZEN.with(|c| c.set(Some(now)));}/// Each part of `caught_up` for a signed-in copy, said (tests only).#[cfg(test)]pub(crate) fn caught_up_parts_for_tests(client: &ClientController) -> String {    use cotton_client::seal::DataKeyStore as _;    let database = client.current_database().unwrap_or_default();    let cursors = client.with_file(|file| cotton_store::cursors::read_cursors(file.driver).map_err(|e| e.to_string())).unwrap_or_default();    format!(        "account {:?} client {} key {} passed {:?} parked {:?} sites {}",        account(client).ok(),        client.caught_up(&database),        client.data_keys().data_key(&database).is_ok_and(|k| k.is_some()),        cursors.get(cotton_client::transport::object::PASSED_KEY),        client.with_file(|file| cotton_client::seal::parked_count(file.driver.connection())),        caught_up(client)    )}#[cfg(test)]pub(crate) fn later_for_tests(ms: i64) {    TEST_LATER.with(|c| c.set(c.get() + ms));}#[cfg(test)]pub(crate) fn local_folder_for_tests(client: &ClientController) -> Result<std::path::PathBuf, MethodError> {    local_folder(client).map(|(_, folder)| folder)}/// Tests only: this copy's own file written as given (an earlier build's, with sites kept only on this phone).#[cfg(test)]pub(crate) fn write_local_as_for_tests(client: &ClientController, local: &cotton_core::sites::Local) {    let key = cotton_core::chat::seal::key_from_text("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8").expect("the test key");    let (_, folder) = local_folder(client).expect("a folder");    write_local(&folder, &key, local, &[]).expect("written");}/// Tests only: this copy's own file as it stands.#[cfg(test)]pub(crate) fn local_for_tests(client: &ClientController) -> cotton_core::sites::Local {    let key = cotton_core::chat::seal::key_from_text("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8").expect("the test key");    let (_, folder) = local_folder(client).expect("a folder");    read_local(&folder, &key).expect("read").0}#[cfg(test)]pub(crate) fn write_local_for_tests(_client: &ClientController, folder: &std::path::Path) -> Result<(), MethodError> {    let key = cotton_core::chat::seal::key_from_text("AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8").expect("the test key");    write_local(folder, &key, &cotton_core::sites::Local::default(), &[])}