//! `sync.*` — what this Mac's own copy is doing, and pushing it now.//!//! Two methods and no third: STARTING the loop is not a question the window//! asks, because the loop runs whenever there is a connection to run it over//! (design M6). What the window can ask is where it got to, and "go now".use serde_json::Value;usesuper::MethodError;usecrate::handle::CottonHandle;/// Where the sync loop and the outbox got to.////// Never a refusal: a Mac nobody has connected yet answers/// `connected: false` with the sentence that says what to do about it, because/// that is the ordinary state of a fresh install and a menu bar has to draw/// something.////// `{ detail: true }` adds each table's rows and newest receipt to `status`,/// for the detail page.pubfn status(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let detail = request.get("detail").and_then(Value::as_bool).unwrap_or(false);Ok(handle.client().sync_status_of(detail))}/// `sync.row { table }` → `{ coming, line, arriving?, arrived? }` (SYNC SEEN, owner 25 Nov 2026: a row being edited/// while a newer copy is on its way says so before he types). `coming` while the pass under way still brings rows of/// `table` (this phone's name for it or the object's); `line` is then what the edit screen shows above the row, in/// the shell's words (`sync.json` `row.coming`), else null. Never a refusal past a missing `table`: a phone with no/// pass running, or no server, has nothing on its way.pubfn row(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let table = request .get("table") .and_then(Value::as_str) .map(str::trim) .filter(|table| !table.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`table` is the row's table"))?;let client = handle.client();let arriving = client.sync_progress().and_then(|progress| progress.state().arriving(table));letSome(pass) = arriving else {returnOk(serde_json::json!({ "coming": false, "line": Value::Null })); };let words = client .with_file(|file| Ok(cotton_core::rules::sync_status::SyncWords::of_rows(&cotton_tools::presentation::line_rows(file.driver, file.workspace_id)))) .unwrap_or_else(|_| cotton_core::rules::sync_status::SyncWords::shipped().clone());let line = words.row.get("coming").cloned().or_else(|| cotton_core::rules::sync_status::SyncWords::shipped().row.get("coming").cloned());Ok(serde_json::json!({ "coming": true, "line": line, "arriving": pass.rows, "arrived": pass.done }))}/// The least and the most a slice may ask for. Under the floor there is no/// room for a page; the cap is past anything iOS grants and keeps a mistyped/// budget from boxing the loop for a day.const SLICE_BUDGET_MS: std::ops::RangeInclusive<u64> = 1_000..=600_000;/// Push whatever is queued, now.////// A refusal HERE is right where a status answer would be wrong: the person/// asked for something to happen, so "it did not" is the answer, with the/// reason in it.////// **`{ budgetMs }` IS A BACKGROUND SLICE.** A foreground "sync now" carries/// no budget and runs as it always did. A phone woken in the background has/// the time iOS gave it and no more, and says so: the passes then run one/// after another until the device is level or the time is gone, each stops/// BETWEEN pages, and the answer's `behind` says whether another slice is/// owed. Nothing a slice fetched is lost when it stops — every page is in the/// file with its cursor before the next is asked — so thirty short slices/// through a day add up to a backfill.pubfn now(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let budget = match request.get("budgetMs") {None | Some(Value::Null) => None,Some(budget) => Some( budget .as_u64() .filter(|ms| SLICE_BUDGET_MS.contains(ms)) .map(std::time::Duration::from_millis) .ok_or_else(|| {MethodError::new("bad_request", format!("budgetMs is the milliseconds a background slice has, {} to {}", SLICE_BUDGET_MS.start(), SLICE_BUDGET_MS.end() ), ) })?, ), };let client = handle.client(); handle .block_on(asyncmove { tokio::task::spawn_blocking(move || {// In a slice, the slice's box covers the pass, and is lifted// as this closure ends.let slice = budget.map(|budget| client.begin_slice(budget));let personal = match slice {Some(_) => client.sync_now_until_level(),None => client.sync_now(), }; drop(slice);let answer = personal?;Ok::<Value, String>(answer) }) .await }) .map_err(|error| MethodError::new("sync_failed", error.to_string()))? .map_err(|reason| MethodError::new("sync_failed", reason))}/// The Sync page's words for what cannot be sent (`sync.json` `unsent`), the database's own rows first.fn unsent_words(client: &crate::shell::client::ClientController) -> std::collections::BTreeMap<String, String> {let shipped = cotton_core::rules::sync_status::SyncWords::shipped().unsent.clone();letmut words = client .with_file(|file| Ok(cotton_core::rules::sync_status::SyncWords::of_rows(&cotton_tools::presentation::line_rows(file.driver, file.workspace_id)).unsent)) .unwrap_or_default();for (key, line) in shipped { words.entry(key).or_insert(line); } words}/// The writes of this phone that wait and will not go by themselves (UNSENT HEAL, `cotton_client::unsent_heal`).fn stuck_now(client: &crate::shell::client::ClientController) -> Vec<cotton_client::unsent_heal::Stuck> {let now_ms = client.now().timestamp_millis();let layout = client.layout().clone(); client .with_file(|file| {letmut stuck = cotton_client::unsent_heal::stuck(file.driver, now_ms)?; stuck.extend(kept_stuck(&layout, file.workspace_id));Ok(stuck) }) .unwrap_or_default()}/// The code of a change kept in a copy set aside whole (QUEUE BAD OP 4): it does not read in this build; recovery/// tries it again on every pass, and Let go is the person's way to end it.const KEPT: &str = "kept";/// The changes the kept copies of `database` still hold, as the stuck list says them.fn kept_stuck(layout: &cotton_client::layout::Layout, database: &str) -> Vec<cotton_client::unsent_heal::Stuck> {let kept = cotton_client::copy_keep::kept(layout, Some(database)); cotton_client::copy_keep::kept_changes(layout, database) .into_iter() .map(|change| {let since = kept.iter().find(|copy| copy.dir == change.kept).map(|copy| copy.state.at.clone()).unwrap_or_default();let reason = kept.iter().find(|copy| copy.dir == change.kept).map(|copy| copy.state.why.clone()).unwrap_or_default(); cotton_client::unsent_heal::Stuck { op_id: change.op_id, table: change.table, row_id: change.row_id, code: KEPT.to_string(), reason, since, parked: true } }) .collect()}/// The kept changes no Send again can send (KEPT FOUR 2, review M4): those of a copy kept from an adopt, which/// recovery never sends (what the adopt left is the local database's, or waits for the re-seal at the next unlock).fn kept_unsendable(layout: &cotton_client::layout::Layout, database: &str) -> std::collections::BTreeSet<String> {let adopted: Vec<std::path::PathBuf> = cotton_client::copy_keep::kept(layout, Some(database)).into_iter().filter(|kept| kept.state.adopted_from.is_some()).map(|kept| kept.dir).collect(); cotton_client::copy_keep::kept_changes(layout, database).into_iter().filter(|change| adopted.contains(&change.kept)).map(|change| change.op_id).collect()}/// `ids` split into the changes kept aside whole and the ones in this copy.fn split_kept(client: &crate::shell::client::ClientController, ids: Vec<String>) -> (Vec<String>, Vec<String>) {let kept: std::collections::BTreeSet<String> = client .with_file(|file| Ok(kept_stuck(client.layout(), file.workspace_id).into_iter().map(|s| s.op_id).collect())) .unwrap_or_default(); ids.into_iter().partition(|id| kept.contains(id))}/// What the Sync page says of changes that cannot be sent (UNSENT HEAL, coordinator 26 Nov 2026), or null when/// there are none: `{ title, detail, things, acts }`. `things` counts each record once. The two acts are Send again/// (`sync.stuck.again`) and Let go (`sync.stuck.letGo`, behind its confirm), each for all of them.pubfn stuck_part(client: &crate::shell::client::ClientController) -> Value {let stuck = stuck_now(client);let kept = kept_here(client);if stuck.is_empty() && kept == 0 {returnValue::Null; }let words = unsent_words(client);let word = |key: &str| words.get(key).cloned().unwrap_or_default();// Changes a table this app never carries holds here only, written down (UNSENT HEAL 2, review item 7).let kept_line = (kept > 0).then(|| if kept == 1 { word("kept_one") } else { word("kept_many").replace("{n}", &kept.to_string()) });if stuck.is_empty() {return serde_json::json!({ "title": kept_line, "detail": Value::Null, "things": 0, "kept": kept, "acts": [], "seen": seen_act(kept) }); }let things = stuck.iter().map(|s| (s.table.as_str(), s.row_id.as_str())).collect::<std::collections::BTreeSet<_>>().len();let title = if things == 1 { word("one") } else { word("many").replace("{n}", &things.to_string()) };// The acts name the changes this answer showed: the core refuses them if what is stuck has changed since (review item 2).let ids: Vec<&str> = stuck.iter().map(|s| s.op_id.as_str()).collect();// Send again only where it can send something (KEPT FOUR 2, review M4): never for changes kept from an adopt alone.let unsendable = client.with_file(|file| Ok(kept_unsendable(client.layout(), file.workspace_id))).unwrap_or_default();let again = stuck.iter().any(|s| !unsendable.contains(&s.op_id));// The detail offers only what the acts offer: no "Send again" where Let go is the one act (Android, 28 Nov 2026).let detail_key = match (things == 1, again) { (true, true) => "detail", (false, true) => "detail_many", (true, false) => "detail_let_go", (false, false) => "detail_let_go_many", };let detail = [Some(word(detail_key)), kept_line].into_iter().flatten().collect::<Vec<_>>().join(" ");letmut acts = Vec::new();if again { acts.push(serde_json::json!({ "id": "again", "label": word("again"), "method": "sync.stuck.again", "request": { "ids": ids } })); } acts.push(serde_json::json!({ "id": "let_go", "label": word("let_go"), "method": "sync.stuck.letGo", "request": { "ids": ids }, "tone": "danger","confirm": { "title": word("let_go_title"), "body": word("let_go_body"), "yes": word("let_go"), "no": word("keep") } })); serde_json::json!({"title": title,"detail": detail,"things": things,"kept": kept,"seen": seen_act(kept),"acts": acts, })}/// What a Sync page calls once it has shown the kept count, so that count is said until seen, then no more.fn seen_act(kept: usize) -> Value {if kept == 0 {returnValue::Null; } serde_json::json!({ "method": "sync.kept.seen", "request": { "count": kept } })}/// `sync.kept.seen { count }`: the Sync page showed that many changes kept only on this phone. → `{ seen }`.pubfn kept_seen(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let shown = request.get("count").and_then(Value::as_u64).ok_or_else(|| MethodError::new("bad_request", "`count`: how many the page showed"))? as usize; client .with_file(|file| cotton_client::unsent_heal::kept_here_seen(client.layout(), file.workspace_id, shown)) .map_err(|why| MethodError::new("unwritten", why))?;Ok(serde_json::json!({ "seen": shown }))}fn kept_here(client: &crate::shell::client::ClientController) -> usize {// An unreadable count is said in the log and shows nothing: the Sync page never fails for it. client.with_file(|file| cotton_client::unsent_heal::kept_here_only(client.layout(), file.workspace_id)).unwrap_or_else(|why| { eprintln!("[cotton-sync] the count of changes kept on this phone: {why}");0 })}/// `sync.stuck` → `{ stuck: <stuck_part or null>, writes: [{ table, code, parked, since }] }`: what cannot be sent, by/// table and code only (never a value or a row id), for the Sync page and a report.pubfn stuck(handle: &CottonHandle, _request: &Value) -> Result<Value, MethodError> {let client = handle.client();let writes: Vec<Value> = stuck_now(&client).iter().map(|s| serde_json::json!({ "table": s.table, "code": s.code, "parked": s.parked, "since": s.since })).collect();Ok(serde_json::json!({ "stuck": stuck_part(&client), "writes": writes }))}/// The op ids a request names (`ids`, what the screen showed), refused unless they are exactly what is stuck now:/// the act then does what the person saw, never more (UNSENT HEAL 2, review item 2). The screen draws again.fn named(client: &crate::shell::client::ClientController, request: &Value) -> Result<Vec<String>, MethodError> {let ids: std::collections::BTreeSet<String> = request .get("ids") .and_then(Value::as_array) .ok_or_else(|| MethodError::new("bad_request", "`ids`: the changes the screen showed"))? .iter() .filter_map(Value::as_str) .map(str::to_string) .collect();let now: std::collections::BTreeSet<String> = stuck_now(client).into_iter().map(|s| s.op_id).collect();if ids.is_empty() || ids != now {returnErr(MethodError::new("stuck_changed", unsent_words(client).get("changed").cloned().unwrap_or_default())); }Ok(ids.into_iter().collect())}/// `sync.stuck.again { ids }`: send again the changes the screen showed, and start a pass. One that would go nowhere/// (its row gone from this phone) is written down and let go instead. → `{ sent, writtenDown, line }`.pubfn stuck_again(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let ids = named(&client, request)?;let now = client.now_iso();let layout = client.layout().clone();// A kept change is tried by recovery on the pass this starts; one still kept after it does not read in this build.let (kept, ids) = split_kept(&client, ids);let (sent, written, cannot) = if ids.is_empty() { (0, 0, 0) } else { client .with_writer(|file| cotton_client::unsent_heal::send_again(file.driver, &layout, file.workspace_id, &ids, &now)) .map_err(|why| MethodError::new("unwritten", why))? };let cannot = cannot + kept.len(); client.nudge_sync();// One this build cannot read is never sent nor ended by Send again: said plainly (QUEUE BAD OP 2).let words = unsent_words(&client);// A mixed answer says how many could not go (QUEUE BAD OP 3, review item 5).let line = match (sent, cannot) { (_, 0) => words.get("sent_again").cloned(), (0, _) => words.get("cannot_send").cloned(), (_, n) => words.get("sent_some").map(|line| line.replace("{n}", &n.to_string())), };Ok(serde_json::json!({ "sent": sent, "writtenDown": written, "cannot": cannot, "line": line }))}/// `sync.stuck.letGo { ids }`: the changes the screen showed, written down for Feedback, then stop sending them; the rows stay on this phone./// → `{ let_go, line }`.pubfn stuck_let_go(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let client = handle.client();let ids = named(&client, request)?;let now = client.now_iso();let layout = client.layout().clone();// A change kept aside whole ends only here, by the person (QUEUE BAD OP 4); its kept copy goes once nothing is left.let (kept, ids) = split_kept(&client, ids);let database = client.with_file(|file| Ok(file.workspace_id.to_string())).map_err(|why| MethodError::new("unwritten", why))?;letmut gone = 0;// The person let go: one of the three acts that end a kept change (QUEUE BAD OP 5, item 5).let act = cotton_client::copy_keep::PersonsAct::of_the_person();for id in &kept {if cotton_client::copy_keep::let_go(&layout, &database, id, &act).map_err(|why| MethodError::new("unwritten", why))? { gone += 1; } }if !ids.is_empty() { gone += client .with_writer(|file| cotton_client::unsent_heal::let_go(file.driver, &layout, file.workspace_id, &ids, &now)) .map_err(|why| MethodError::new("unwritten", why))?; }Ok(serde_json::json!({ "letGo": gone, "line": unsent_words(&client).get("let_gone") }))}