Cotton code
219 lines · 7.8 KB · RustRaw
//! Where each queued file is (MEDIA DRAIN 1, item 3): the answer a screen//! draws "412 of 640 kept · 3 could not be kept" from, truthfully.//!//! Two sources, read together. **The ledger** (`_media`) says what the object//! answered: `synced` only after the object's own answer to the upload (stored,//! or held already at that size), `failed` with the word of a refusal it will//! repeat, `pending` with the word of a wait. **The watch** says what is in the//! air right now, and how far: it lives in memory, because a file half sent//! when the app is killed is simply queued again on the next launch, and a//! byte count that outlived its upload would be a lie.use std::collections::HashMap;use std::sync::Mutex;use cotton_store::media_ledger::{codes, MediaRow, AFTER_NEXT_EXCHANGE};use serde::Serialize;/// The uploads in the air on this device, by key, and how far each has gone.#[derive(Debug, Default)]pub struct UploadWatch {    flights: Mutex<HashMap<String, Flight>>,}/// One upload in the air: the bytes sent of the bytes that go (sealed, as/// they travel).#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]pub struct Flight {    pub sent: u64,    pub total: u64,}impl UploadWatch {    pub fn new() -> UploadWatch {        UploadWatch::default()    }    fn flights(&self) -> std::sync::MutexGuard<'_, HashMap<String, Flight>> {        self.flights.lock().unwrap_or_else(|poisoned| poisoned.into_inner())    }    /// An upload of `key` began; `total` is what the ledger says the file    /// weighs until the transport says what goes on the wire.    pub fn begin(&self, key: &str, total: u64) {        self.flights().insert(key.to_string(), Flight { sent: 0, total });    }    /// `sent` of `total` bytes of `key` have gone. A key not in the air (its    /// upload ended) is not put back.    pub fn progress(&self, key: &str, sent: u64, total: u64) {        if let Some(flight) = self.flights().get_mut(key) {            *flight = Flight { sent: sent.min(total), total };        }    }    /// The upload of `key` ended, whichever way: the ledger says how.    pub fn end(&self, key: &str) {        self.flights().remove(key);    }    pub fn flight(&self, key: &str) -> Option<Flight> {        self.flights().get(key).copied()    }    /// How many uploads are in the air.    pub fn in_the_air(&self) -> usize {        self.flights().len()    }}/// Where one file is.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]#[serde(rename_all = "lowercase")]pub enum Phase {    /// Waiting its turn.    Queued,    /// Held for a reason that goes by itself (`code`: `space_full`, `dead_key`).    Waiting,    /// Going up now (`sent` of `total`).    Uploading,    /// A try did not land (no network, the object busy); tried again at `nextTryAt`.    Retrying,    /// The object answered that it holds these bytes.    Uploaded,    /// Refused for good, with the word the person acts on (`code`).    Failed,    /// Taken out of Cotton: the bytes are leaving the object.    Removing,    /// This device holds no upload of this key.    Unknown,}/// One file's answer.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct FileUpload {    pub key: String,    pub phase: Phase,    /// Bytes sent, while `uploading`.    #[serde(skip_serializing_if = "Option::is_none")]    pub sent: Option<u64>,    /// The file's bytes (on the wire, while `uploading`).    pub total: u64,    /// The word a refusal or a wait is filed under ([`codes`]).    #[serde(skip_serializing_if = "Option::is_none")]    pub code: Option<String>,    /// The object's own sentence, for a refusal or the last failed try.    #[serde(skip_serializing_if = "Option::is_none")]    pub line: Option<String>,    pub attempts: i64,    #[serde(skip_serializing_if = "Option::is_none")]    pub next_try_at: Option<String>,    /// Under what rule it goes: `any` or `wifi`.    pub network: String,    #[serde(skip_serializing_if = "Option::is_none")]    pub asked_by: Option<String>,}impl FileUpload {    fn unknown(key: &str) -> FileUpload {        FileUpload {            key: key.to_string(),            phase: Phase::Unknown,            sent: None,            total: 0,            code: None,            line: None,            attempts: 0,            next_try_at: None,            network: "any".to_string(),            asked_by: None,        }    }}/// One ledger row and the watch, as one answer.pub fn file_upload(row: &MediaRow, watch: &UploadWatch) -> FileUpload {    let flight = (row.state == "pending").then(|| watch.flight(&row.key)).flatten();    let parked = row.next_attempt_at.as_deref() == Some(AFTER_NEXT_EXCHANGE);    let phase = match row.state.as_str() {        "synced" => Phase::Uploaded,        "failed" => Phase::Failed,        "delete_pending" => Phase::Removing,        "pending" if flight.is_some() => Phase::Uploading,        "pending" if parked || row.last_code.as_deref() == Some(codes::SPACE_FULL) => Phase::Waiting,        "pending" if row.attempts > 0 => Phase::Retrying,        "pending" => Phase::Queued,        _ => Phase::Unknown,    };    let code = match phase {        // A failed row an earlier build filed has no word: it was refused.        Phase::Failed => Some(row.last_code.clone().unwrap_or_else(|| codes::REFUSED.to_string())),        Phase::Waiting if parked => Some(codes::DEAD_KEY.to_string()),        Phase::Waiting | Phase::Retrying => row.last_code.clone(),        _ => None,    };    let line = matches!(phase, Phase::Failed | Phase::Waiting | Phase::Retrying).then(|| row.last_error.clone()).flatten();    FileUpload {        key: row.key.clone(),        phase,        sent: flight.map(|flight| flight.sent),        total: flight.map_or(u64::try_from(row.size_bytes).unwrap_or(0), |flight| flight.total),        code,        line,        attempts: row.attempts,        next_try_at: (phase == Phase::Retrying || (phase == Phase::Waiting && !parked)).then(|| row.next_attempt_at.clone()).flatten(),        network: row.network.clone(),        asked_by: row.asked_by.clone(),    }}/// How many of the asked files are in each phase.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct UploadCounts {    pub queued: usize,    pub waiting: usize,    pub uploading: usize,    pub retrying: usize,    pub uploaded: usize,    pub failed: usize,    pub removing: usize,    pub unknown: usize,}/// The answer to "where are these files": each key in the order asked, and the counts.#[derive(Debug, Clone, PartialEq, Eq, Serialize)]#[serde(rename_all = "camelCase")]pub struct Uploads {    pub files: Vec<FileUpload>,    pub counts: UploadCounts,}/// Where each of `keys` is, off the ledger rows a caller read for them/// (`media_by_keys`) and the watch.pub fn uploads_of(keys: &[String], rows: &[MediaRow], watch: &UploadWatch) -> Uploads {    let by_key: HashMap<&str, &MediaRow> = rows.iter().map(|row| (row.key.as_str(), row)).collect();    let files: Vec<FileUpload> = keys        .iter()        .map(|key| by_key.get(key.as_str()).map_or_else(|| FileUpload::unknown(key), |row| file_upload(row, watch)))        .collect();    let mut counts = UploadCounts::default();    for file in &files {        match file.phase {            Phase::Queued => counts.queued += 1,            Phase::Waiting => counts.waiting += 1,            Phase::Uploading => counts.uploading += 1,            Phase::Retrying => counts.retrying += 1,            Phase::Uploaded => counts.uploaded += 1,            Phase::Failed => counts.failed += 1,            Phase::Removing => counts.removing += 1,            Phase::Unknown => counts.unknown += 1,        }    }    Uploads { files, counts }}#[cfg(test)]#[path = "uploads_tests.rs"]mod tests;