Cotton code
157 lines · 6.7 KB · RustRaw
//! `sync.rejected` and `sync.retryRejected` — the writes this device could not//! fold, and one more go at them.//!//! **Why these are methods and not reads.** A `read.*` answers over the//! REPLICA, and `_parked` is device-local: it never syncs, so what these//! answer is this device's own diagnosis rather than anything in the person's//! database. The screen is `/rejected` (`CottonUI/Screens/Settings///! Rejected/`), which is on `READ_LESS` naming these two names — reached from//! the join sheet's merge count and from Settings › Devices, so a person//! diagnosing "my laptop has this note and my phone does not" is given an//! answer instead of a shrug.//!//! **A retry is not a write.** Nothing here mints an op or queues one: the op//! already exists, kept whole in `_parked` since version 8, and the retry//! offers that same op — same id, same stamp — to//! `cotton_store::fold::fold_ops`. So it goes through `with_file` like the//! media ledger's own device-local write rather than through `write_rows`,//! which is for writes this device is the AUTHOR of.//!//! **Only the pull half moves.** A parked `push` row is the PEER's verdict on//! our own write; no fold here can change it, and `cotton_store::rejected` says//! so in one place rather than in two. The list shows both, because a person//! asking what went missing wants both directions.use serde_json::{json, Value};use crate::handle::CottonHandle;use crate::methods::MethodError;use crate::shell::client::ClientController;/// The method names this module answers.pub const METHODS: [&str; 2] = ["sync.rejected", "sync.retryRejected"];/// How many parked writes one answer carries.////// A ceiling rather than "all of them": this is a diagnostic list, and a file/// that has somehow parked ten thousand writes has a problem the first two/// hundred already describe.const LIMIT: i64 = 200;pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> {    over(&handle.client(), method, request)}/// The same, over a NAMED controller.////// The split is `phone::vault`'s and it is here for the same reason: a suite/// drives a paired phone assembled by `shell::client::phone_tests::attached`/// and asserts what the file holds afterwards, without dragging a runtime and/// a data directory into a test about two methods' shape.pub fn over(    client: &ClientController,    method: &str,    request: &Value,) -> Result<Value, MethodError> {    match method {        "sync.rejected" => list(client),        "sync.retryRejected" => retry(client, request),        other => Err(MethodError::new(            "unknown_method",            format!("`{other}` is not a method this build answers"),        )),    }}/// Every write this file knows it lost, newest FIRST VERDICT first.fn list(client: &ClientController) -> Result<Value, MethodError> {    let rows = client        .with_file(|file| {            cotton_store::rejected::list_parked(file.driver, LIMIT)                .map_err(|error| error.to_string())        })        .map_err(|reason| MethodError::new("unreadable", reason))?;    Ok(json!({        "rejected": rows.iter().map(row).collect::<Vec<Value>>(),        "count": rows.len(),    }))}/// A PROJECTION of named fields, never the row.////// The patch is deliberately absent. It is a row of somebody's database in/// whatever shape the table has, and a screen that drew it would be drawing/// columns nothing designed — the table, the row id and the reason are what a/// person acts on, and the op id is what `sync.retryRejected` takes.fn row(parked: &cotton_store::rejected::RejectedOp) -> Value {    json!({        "opId": parked.op_id,        "direction": parked.direction,        // `waiting` or `conflict` (`cotton_store::rejected::Class`).        "class": parked.class,        "table": parked.table,        "rowId": parked.row_id,        "kind": parked.kind,        "reason": parked.reason,        // WHEN IT WAS FIRST REFUSED, and it never moves — how long a write has        // been stuck is the fact worth reading.        "at": parked.at,        "retriedAt": parked.retried_at,        "hlc": parked.hlc,        "author": parked.device_id,        // `push` rows and rows parked with no receipt cannot be retried — a        // retry folds the parked receipt byte for byte        // (`cotton_store::stored::rejected_row`); the caller is told which is        // which rather than being handed a button that does nothing.        "retryable": parked.direction == "pull" && parked.bytes.is_some(),    })}/// Offer parked writes to the fold again — the ones named, or all of them.fn retry(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let ids: Option<Vec<String>> = request.get("ids").and_then(Value::as_array).map(|ids| {        ids.iter()            .filter_map(Value::as_str)            .map(str::to_string)            .collect()    });    let now = client.now_iso();    // The WRITER: a retry folds the parked ops into the rows.    let (workspace_id, report, tables) = client        .with_writer(|file| {            // Which table each parked op writes, read before the fold takes            // them off the list, so the folded ones can be named after it.            let parked = cotton_store::rejected::list_parked(file.driver, i64::MAX)                .map_err(|error| error.to_string())?;            let report = cotton_store::rejected::retry_rejected(file.driver, ids.as_deref(), &now)                .map_err(|error| error.to_string())?;            let tables: std::collections::BTreeSet<String> = parked                .into_iter()                .filter(|op| report.folded.contains(&op.op_id))                .map(|op| op.table)                .collect();            Ok((file.workspace_id.to_string(), report, tables))        })        // A refusal HERE is right where a list's would be wrong: the person        // asked for something to happen, so "it did not" is the answer.        .map_err(|reason| MethodError::new("retry_failed", reason))?;    // A folded op changed rows, so every list showing them reads again — the    // `data` event a pull's fold sends, emitted after the writer let go    // (`write`'s rule: a subscriber re-reading on this thread would deadlock).    // None when nothing folded, as a pull that brought nothing sends none.    if !tables.is_empty() {        client.emit_data(&workspace_id, tables.into_iter().collect(), "pull");    }    Ok(json!({        "folded": report.folded,        "stillRejected": report            .still_rejected            .iter()            .map(|(op_id, reason)| json!({ "opId": op_id, "reason": reason }))            .collect::<Vec<Value>>(),    }))}#[cfg(test)]#[path = "rejected_tests.rs"]mod tests;