//! What this device keeps: opening a record it does not hold, and settling//! its own copy with its keep rules.//!//! A row outside a phone's keep rules is not on the phone at all — not a//! stub. When its record is opened the phone asks the serving Mac for it//! (`POST /v1/sync/open`), folds the receipts that come back as the pulled//! arrival they are, and writes down that it opened them//! (`cotton_store::keep::fold_opened`). The rules and the judge that reads//! them are `cotton_store::keep`, the same code the serving Mac runs.//!//! The serving Mac only decides what it sends. What this device already//! holds is settled HERE ([`reconcile`]), after a sync pass goes idle: what//! its rules no longer keep leaves its copy (`keep::leave` — a local drop,//! nothing travels), and what they keep that it can see it lacks is fetched//! the way an opened record is (`keep::wanted`). And what a WIDENED rule//! keeps — rows a narrower rule left out, which this device never heard of//! and cannot name — is asked for by table, a page at a time, from where the//! last pass stopped (`keep::widenings`, [`widen`]).use std::collections::BTreeSet;use serde_json::{json, Value};use cotton_client::transport::ServerFetch;use cotton_store::protocol::types::{OpenResponse, OPEN_PATH};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::owner::{post, send};usecrate::shell::client::ClientController;pubconst METHODS: [&str; 3] = ["keep.open", "keep.reconcile", "keep.audience"];/// How many rows one hold of the writer drops, and how many holds one pass/// takes: a phone that just took a rule sheds a table over a few passes, and/// no screen waits behind one of them for long.const LEAVE_ROWS: usize = 200;const LEAVE_HOLDS: usize = 25;/// How many records one pass fetches back.const WANT_ROWS: usize = 50;/// How many pages of a widened table one pass asks for, over every table of/// one database. A page is at most `keep::OPEN_PAGE_ROWS` rows and what the/// last record owns; twelve years of mail comes back over several passes, and/// the line in `_keep_fetch` is where the next one goes on.const WIDEN_PAGES: usize = 40;pubfn dispatch(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"keep.open" => open(handle, request.get("args").unwrap_or(request)),"keep.reconcile" => {let done = reconcile(&handle.client()).map_err(|reason| MethodError::new("reconcile_failed", reason))?;Ok(json!({ "dropped": done.dropped, "owed": done.owed, "fetched": done.fetched, "more": done.more })) }"keep.audience" => audience(handle, request.get("args").unwrap_or(request)), other => Err(MethodError::new("unknown_method", format!("{other} is no keep method"))), }}fn required<'a>(args: &'a Value, key: &str) -> Result<&'a str, MethodError> { args.get(key) .and_then(Value::as_str) .filter(|s| !s.is_empty()) .ok_or_else(|| MethodError::new("bad_request", format!("opening a record needs {key}")))}fn no_way_to_ask() -> MethodError {MethodError::new("device_key_unreadable", crate::phone::owner::NO_DEVICE_IDENTITY)}/// `keep.open { table, id }` — fetch a record this device does not keep.////// Answers `{ held, rows, tables }`: `held` is whether the record is on this/// device after the call. The serving Mac's own refusal (a row never kept on this device,/// `not_kept`) and an unreachable Mac are the caller's answers as they came.fn open(handle: &CottonHandle, args: &Value) -> Result<Value, MethodError> {let table = required(args, "table")?;let row_id = required(args, "id")?;let client = handle.client();let workspace = client .with_writer(|file| Ok(file.workspace_id.to_string())) .map_err(|reason| MethodError::new("open_failed", reason))?;let fetch = client.fetch().ok_or_else(no_way_to_ask)?;let (rows, tables) = fetch_record(&client, fetch.as_ref(), &workspace, table, row_id, true)?;// Rows landed, so every list showing them reads again — the `data` event// a pull's fold sends, emitted after the writer let go.if !tables.is_empty() { client.emit_data(&workspace, tables.iter().cloned().collect(), "pull"); }Ok(json!({ "held": rows > 0, "rows": rows, "tables": tables }))}/// `keep.audience { database, table, id? }` — who may hold one record, for/// the record tray and the new-record form: `{ audience, offered }`./// `audience` is `only_you`, `everyone` or null (never set: everyone's, and/// always null for a record not made yet — no `id`); `offered` is whether/// this device may set it at all — a SHARED database, at one of the owner's/// own devices. The tray's act is the owner-scope tool `set_audience`; the/// form's is the create's own `audience`, minted with the record.////// The database is the one the dispatch named for this call: it takes/// `database` off the request and opens that file before any method runs/// (`methods::dispatch`), so the method reads the named file and never looks/// for the argument itself. Looking for it refused every caller with/// "opening a record needs database" (Rigby build 2's walk, 22 Oct 2026).fn audience(handle: &CottonHandle, args: &Value) -> Result<Value, MethodError> {let table = required(args, "table")?;let row_id = args["id"].as_str().map(str::trim).filter(|id| !id.is_empty());let client = handle.client();let device = client.self_device_id();let record = match row_id {Some(row_id) => {let target = cotton_tools::mcp::handlers::keep_rules::record_target(&cotton_store::keep::record_target_of(table, row_id));Some( cotton_store::keep::record_target(&target) .map(|(table, id)| (table.to_string(), id.to_string())) .ok_or_else(|| MethodError::new("bad_request", "table and id name one record"))?, ) }None => None, }; client .with_file(|file| {let db = file.driver;let shared = cotton_store::link_rule::file_kind(db).map_err(|e| e.to_string())? == cotton_store::link_rule::FileKind::Shared;let owners = match &device {Some(key) => cotton_store::audience::owners_device(db, key).map_err(|e| e.to_string())?,None => false, };let audience = match &record {Some((table, row_id)) => cotton_store::audience::of_record(db, table, row_id).map_err(|e| e.to_string())?,None => None, };Ok(json!({ "audience": audience, "offered": shared && owners })) }) .map_err(|reason| MethodError::new("read_failed", reason))}/// Ask the serving Mac for one record whole and fold every answer: the rows/// that landed and their tables. `opened` writes the `_on_demand` line a/// record opened from outside the rules carries; a record the rules keep/// ([`reconcile`]) carries none.fn fetch_record( client: &ClientController, fetch: &dynServerFetch, workspace: &str, table: &str, row_id: &str, opened: bool,) -> Result<(usize, BTreeSet<String>), MethodError> {letmut after: Option<usize> = None;letmut rows = 0usize;letmut tables: BTreeSet<String> = BTreeSet::new();loop {let body = json!({ "workspaceId": workspace, "table": table, "rowId": row_id, "after": after });let answer = send(fetch, post(OPEN_PATH.to_string(), &body).for_database(workspace))?;let answer: OpenResponse = serde_json::from_value(answer).map_err(|error| {MethodError::new("unreadable_answer", format!("the serving Mac's answer could not be read: {error}")) })?;let landed: Vec<(String, String)> = answer.rows.iter().map(|row| (row.table.clone(), row.row_id.clone())).collect();let now = client.clock().now().timestamp_millis();// No lock is held across the call above: the writer is taken only to// fold what came back. client .with_writer_in(workspace, |file| {let folded = if opened { cotton_store::keep::fold_opened(file.driver, &answer.ops, &landed, now) } else { cotton_store::keep::fold_fetched(file.driver, &answer.ops, now) }; folded.map(|_| ()).map_err(|error| error.to_string()) }) .map_err(|reason| MethodError::new("open_failed", reason))?; rows += landed.len(); tables.extend(landed.into_iter().map(|(table, _)| table));match answer.next {Some(next) => after = Some(next),None => break, } }Ok((rows, tables))}/// What one [`reconcile`] did, over every database this device holds.#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pubstructReconciled {/// Rows that left this device's copies.pub dropped: usize,/// Rows kept back because this device still owes somebody a change to them.pub owed: usize,/// Rows fetched because a rule keeps them and they were not here.pub fetched: usize,/// There is more to drop or fetch: the next pass goes on.pub more: bool,}/// SETTLE THIS DEVICE'S COPIES WITH ITS KEEP RULES, each database it holds.////// A Mac is told it keeps everything by the judge (`Keep::of_device` reads/// no rule for it), so on a Mac this is two reads a database. An unreachable serving Mac costs only the fetches —/// what leaves needs nobody — and the next pass asks again.pubfn reconcile(client: &ClientController) -> Result<Reconciled, String> {letmut done = Reconciled::default();letSome(device) = client.self_device_id() else {returnOk(done); };for database in client.databases()? {if database.pending {continue; }let workspace = database.id;letmut tables: BTreeSet<String> = BTreeSet::new();letmut wanted: Vec<(String, String)> = Vec::new();for hold in0..LEAVE_HOLDS {let (left, wants) = client.with_writer_in(&workspace, |file| {// The judge's clock where the file has one: a phone whose own// clock runs ahead must not drop a year of mail early.let now = file .driver .judge() .and_then(|judge| judge.now()) .unwrap_or_else(|| client.clock().now().timestamp_millis());let keep = cotton_store::keep::Keep::of_device(file.driver, &device).map_err(|e| e.to_string())?;let left = cotton_store::keep::leave(file.driver, &keep, now, LEAVE_ROWS).map_err(|e| e.to_string())?;let wants = if left.more {Vec::new() } else {letmut wants = cotton_store::keep::wanted(file.driver, &keep, WANT_ROWS).map_err(|e| e.to_string())?;// A RELEASED RECORD this copy never held: the owner made it// everyone's after this device's cursors passed it, so no// page will carry it — it is opened by name like any other.let room = WANT_ROWS.saturating_sub(wants.len());for released in cotton_store::audience::released_missing(file.driver, room).map_err(|e| e.to_string())? {if !wants.contains(&released) { wants.push(released); } } wants };Ok((left, wants)) })?; done.dropped += left.dropped; done.owed += left.owed; tables.extend(left.tables);if !left.more { wanted = wants;break; }// Out of holds with more to drop: the next pass goes on. done.more |= hold + 1 == LEAVE_HOLDS; }if !wanted.is_empty() { done.more |= wanted.len() >= WANT_ROWS;match client.fetch() {Some(fetch) => {for (table, row_id) in &wanted {match fetch_record(client, fetch.as_ref(), &workspace, table, row_id, false) {Ok((rows, landed)) => { done.fetched += rows; tables.extend(landed); }Err(refusal) => {// Unreachable, or refused: the rows are still// wanted, and the next pass asks again. tracing::debug!("keep: {table} {row_id} is kept by a rule and could not be fetched — {}", refusal.message );break; } } } }None => tracing::debug!("keep: this device has no way to ask the serving Mac yet"), } }match widen(client, &workspace, &device) {Ok((rows, landed, more)) => { done.fetched += rows; done.more |= more; tables.extend(landed); }// Unreachable, refused, or a serving Mac that cannot answer a// table yet: the line stays, and the next pass asks again.Err(reason) => tracing::debug!("keep: a widened rule's rows were not fetched — {reason}"), }if !tables.is_empty() { client.emit_data(&workspace, tables.into_iter().collect(), "pull"); } }Ok(done)}/// A WIDENED RULE BRINGS ITS ROWS BACK. Every narrowable table whose rule now/// keeps more than this copy is complete for (`keep::widenings`) is asked of/// the serving Mac by table (`POST /v1/sync/open` with `tableAfter`), each/// answer folded as the pulled arrival it is and its end written down/// (`keep::widened`), [`WIDEN_PAGES`] pages a pass. Answers the rows that/// landed, their tables, and whether a fetch is still under way.////// The serving Mac must SAY it answered a table (`OpenResponse::table`): one/// built before the selector reads the request as an open of no row and/// answers nothing, and that silence is never taken for a finished fetch.fn widen(client: &ClientController, workspace: &str, device: &str) -> Result<(usize, BTreeSet<String>, bool), String> {let owed = client.with_writer_in(workspace, |file| {let keep = cotton_store::keep::Keep::of_device(file.driver, device).map_err(|e| e.to_string())?; cotton_store::keep::widenings(file.driver, &keep).map_err(|e| e.to_string()) })?;letmut rows = 0usize;letmut tables: BTreeSet<String> = BTreeSet::new();if owed.is_empty() {returnOk((rows, tables, false)); }letSome(fetch) = client.fetch() else {returnErr("this device has no way to ask the serving Mac yet".to_string()); };letmut pages = 0usize;for widening in owed {letmut after = widening.after.clone();loop {if pages == WIDEN_PAGES {returnOk((rows, tables, true)); } pages += 1;let body = json!({ "workspaceId": workspace, "table": widening.table, "rowId": "", "tableAfter": after });let answer = send(fetch.as_ref(), post(OPEN_PATH.to_string(), &body).for_database(workspace)) .map_err(|refusal| refusal.message)?;let answer: OpenResponse = serde_json::from_value(answer) .map_err(|error| format!("the serving Mac's answer could not be read: {error}"))?;letSome(table) = answer.table else {returnErr(format!("the serving Mac cannot answer a whole table yet (an older build), so the {} rows a wider rule keeps wait for it", widening.table )); };let now = client.clock().now().timestamp_millis(); client.with_writer_in(workspace, |file| { cotton_store::keep::fold_fetched(file.driver, &answer.ops, now).map_err(|e| e.to_string())?; cotton_store::keep::widened(file.driver, &widening.table, &widening.target, &table.reached, table.more) .map_err(|e| e.to_string()) })?; rows += answer.rows.len(); tables.extend(answer.rows.iter().map(|row| row.table.clone()));if !table.more {break; } after = table.reached; } }Ok((rows, tables, false))}