Cotton code
224 lines · 8.2 KB · RustRaw
//! Device-local delivery facts shared by feedback record readers.use crate::mcp::dispatch::Ctx;use serde_json::{Map, Value};use std::collections::HashMap;/// What this device knows about a row it wrote and has not heard back about.////// Three states and no fourth: the row is at the server, the row is on its way,/// or the server refused it. "Failed to upload the picture" is not a fourth/// state — it is a refusal that happens to be about the picture, and it says so/// in its reason.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Delivery {    /// Nothing of this row is queued and nothing was refused.    Sent,    /// The row, or its picture, is still waiting for a network.    Waiting,    /// The server refused the row or its picture, and the store kept why.    Refused,}impl Delivery {    pub const fn as_str(self) -> &'static str {        match self {            Delivery::Sent => "sent",            Delivery::Waiting => "waiting",            Delivery::Refused => "refused",        }    }}/// Where a report's picture has got to. `None` on a report with no picture.#[derive(Debug, Clone, PartialEq, Eq)]pub enum ImageState {    /// In `_media` as `pending` or `delete_pending` — still to go up.    Queued,    /// `synced`. The bytes are at the server.    Arrived,    /// `failed`. Terminal, with the ledger's `last_error`.    Refused(String),}/// The three facts the decision is taken from, so the decision can be tested/// without a database.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct DeliveryFacts {    /// The row's own patch is still in `_outbox`.    pub row_queued: bool,    /// What the LAST attempt to hand this row over failed with, if one has.    ///    /// Not part of the state machine — a queued row is waiting whether or not    /// an attempt has been made yet. It rides along because it is the most    /// direct answer there is to "why is THIS one still here": the store writes    /// the transport's own sentence onto the row it could not send, and    /// `_outbox` keeps both (`cotton-store/src/exchange.rs`, the transport-    /// failure arm) rather than dropping the op — which is why a stranded    /// report is never a lost one.    pub row_last_error: Option<String>,    /// The server refused the row's patch and `_parked` kept it, with the    /// reason it gave.    pub row_refused: Option<String>,    /// The picture, if there is one.    pub image: Option<ImageState>,}/// The whole rule, in one place.////// PRECEDENCE, and why. A refusal outranks a wait because a wait resolves/// itself and a refusal never will — telling somebody to be patient about a row/// the server has already thrown out is the silent-fallback failure in words./// Between the two refusals the ROW's outranks the PICTURE's: a refused row is/// a report that does not exist at the other end, where a refused picture is a/// report that arrived without its evidence. And a queued ROW outranks a queued/// picture for the mirror of that reason — the sentence a person needs is about/// the biggest thing still missing.#[must_use]pub fn decide(facts: &DeliveryFacts) -> (Delivery, Option<String>) {    if let Some(reason) = &facts.row_refused {        return (Delivery::Refused, Some(reason.clone()));    }    if let Some(ImageState::Refused(reason)) = &facts.image {        return (Delivery::Refused, Some(reason.clone()));    }    if facts.row_queued {        return (Delivery::Waiting, None);    }    if facts.image == Some(ImageState::Queued) {        return (Delivery::Waiting, None);    }    (Delivery::Sent, None)}/// The wire shape of a decision: `{ state, reason }`.fn delivery_out(facts: &DeliveryFacts) -> Value {    let (state, reason) = decide(facts);    let mut out = Map::new();    out.insert("state".to_string(), Value::from(state.as_str()));    out.insert(        "reason".to_string(),        reason.map_or(Value::Null, Value::from),    );    // Which half is still moving, so a detail view can say "the picture" rather    // than "it" without re-deriving the rule.    out.insert(        "imageWaiting".to_string(),        Value::from(facts.image == Some(ImageState::Queued)),    );    // The last transport failure on this row, for a reader that wants to say    // more than "waiting". A screen is free to ignore it: it is a transport's    // sentence, not one written for a person.    out.insert(        "lastAttemptError".to_string(),        facts            .row_last_error            .clone()            .map_or(Value::Null, Value::from),    );    Value::Object(out)}/// Read delivery ledgers once, then project every row from the same facts.pub struct Readings {    queued: HashMap<String, Option<String>>,    refused: HashMap<String, String>,    media: HashMap<String, ImageState>,}impl Readings {    pub fn load(ctx: &Ctx<'_>) -> Result<Self, String> {        Ok(Self {            queued: queued_feedback_rows(ctx)?,            refused: refused_feedback_rows(ctx)?,            media: media_states(ctx)?,        })    }    pub fn delivery(&self, id: &str, image_key: Option<&str>) -> Value {        delivery_out(&DeliveryFacts {            row_queued: self.queued.contains_key(id),            row_last_error: self.queued.get(id).cloned().flatten(),            row_refused: self.refused.get(id).cloned(),            image: image_key.and_then(|key| self.media.get(key).cloned()),        })    }}/// Feedback rows whose own patch is still in `_outbox`, each with what the last/// attempt to hand it over failed with.////// Ordered oldest op first so the LATEST attempt on a row is the one that lands/// in the map — a row can have several queued ops and only the newest verdict/// describes where it stands now.fn queued_feedback_rows(ctx: &Ctx<'_>) -> Result<HashMap<String, Option<String>>, String> {    let found = ctx        .db()        .all(            "SELECT row_id, last_error FROM _outbox \             WHERE tbl = 'cotton_feedback' ORDER BY op_id ASC",            &[],        )        .map_err(|error| error.to_string())?;    let mut out: HashMap<String, Option<String>> = HashMap::new();    for row in &found {        let Some(id) = row.text("row_id") else {            continue;        };        out.insert(id.to_string(), row.text("last_error").map(str::to_string));    }    Ok(out)}/// Feedback row ids the server refused, with the reason it gave.////// `direction = 'push'` only: a PULL rejection is news this device could not/// fold, which is a different sentence and belongs to `/rejected`, not here./// Ordered oldest first so the LATEST verdict on a row is the one that lands in/// the map.fn refused_feedback_rows(ctx: &Ctx<'_>) -> Result<HashMap<String, String>, String> {    let found = ctx        .db()        .all(            "SELECT row_id, reason FROM _parked \             WHERE tbl = 'cotton_feedback' AND direction = 'push' ORDER BY first_at ASC",            &[],        )        .map_err(|error| error.to_string())?;    let mut out: HashMap<String, String> = HashMap::new();    for row in &found {        let (Some(id), Some(reason)) = (row.text("row_id"), row.text("reason")) else {            continue;        };        out.insert(id.to_string(), reason.to_string());    }    Ok(out)}/// Every media key this device holds, and where its bytes have got to.fn media_states(ctx: &Ctx<'_>) -> Result<HashMap<String, ImageState>, String> {    let found = ctx        .db()        .all("SELECT key, state, last_error FROM _media", &[])        .map_err(|error| error.to_string())?;    let mut out: HashMap<String, ImageState> = HashMap::new();    for row in &found {        let Some(key) = row.text("key") else { continue };        let state = match row.text("state") {            Some("synced") => ImageState::Arrived,            Some("failed") => ImageState::Refused(                row.text("last_error")                    .unwrap_or("the upload was refused")                    .to_string(),            ),            // `pending` and `delete_pending` are both "not there yet".            _ => ImageState::Queued,        };        out.insert(key.to_string(), state);    }    Ok(out)}#[cfg(test)]#[path = "feedback_delivery_tests.rs"]mod tests;