Cotton code
175 lines · 5.6 KB · RustRaw
//! Durable owner requests, separate from synced approvals: only the serving//! Mac can confirm removal. A pending intent never changes an approval row.use super::{ClientAnswer, ClientRequest, ServerRefusal};use serde::{Deserialize, Serialize};use std::path::{Path, PathBuf};use std::sync::Mutex;#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]pub(super) struct Removal {    pub origin: String,    pub database: String,    pub device: String,    pub erase: bool,}impl Removal {    pub fn request(&self) -> ClientRequest {        let mut request =            ClientRequest::delete(format!("/v1/devices/approved/{}", segment(&self.device)));        if !self.database.is_empty() {            request = request.for_database(&self.database);        }        request.body = Some(            serde_json::to_vec(&serde_json::json!({"erase":self.erase})).expect("boolean body"),        );        request.content_type = Some("application/json");        request    }}fn segment(text: &str) -> String {    text.bytes()        .map(|b| {            if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {                (b as char).to_string()            } else {                format!("%{b:02X}")            }        })        .collect()}#[derive(Debug)]pub(super) struct Removals {    path: PathBuf,    rows: Mutex<Vec<Removal>>,    load_error: Option<String>,    pub(super) flight: Mutex<()>,}impl Removals {    pub fn at(path: PathBuf) -> Self {        let (rows, load_error) = match read(&path) {            Ok(rows) => (rows, None),            Err(error) => (Vec::new(), Some(error)),        };        Self {            path,            rows: Mutex::new(rows),            load_error,            flight: Mutex::new(()),        }    }    fn readable(&self) -> Result<(), ServerRefusal> {        match &self.load_error {            Some(error) => Err(ServerRefusal::new(error, 0).with_code("removal_unreadable")),            None => Ok(()),        }    }    fn save(&self, rows: &[Removal]) -> Result<(), ServerRefusal> {        let path = &self.path;        let write = || -> Result<(), String> {            let parent = path.parent().ok_or("removal journal has no parent")?;            std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;            let bytes = serde_json::to_vec(rows).map_err(|e| e.to_string())?;            let temporary = path.with_extension("json.new");            // not a copy: the device removals list.            let mut file = std::fs::File::create(&temporary).map_err(|e| e.to_string())?;            use std::io::Write;            file.write_all(&bytes)                .and_then(|_| file.sync_all())                .map_err(|e| e.to_string())?;            // not a copy: the device removals list.            std::fs::rename(&temporary, path).map_err(|e| e.to_string())?;            std::fs::File::open(parent)                .and_then(|f| f.sync_all())                .map_err(|e| e.to_string())        };        write().map_err(|e| {            ServerRefusal::new(format!("Device removal could not be saved: {e}"), 0)                .with_code("removal_unwritable")        })    }    pub(super) fn queue(&self, row: Removal) -> Result<Removal, ServerRefusal> {        self.readable()?;        let mut rows = self.rows.lock().unwrap_or_else(|e| e.into_inner());        let mut next = rows.clone();        let result = if let Some(old) = next.iter_mut().find(|r| {            r.origin == row.origin && r.database == row.database && r.device == row.device        }) {            old.erase |= row.erase;            old.clone()        } else {            next.push(row.clone());            row        };        self.save(&next)?;        *rows = next;        Ok(result)    }    pub(super) fn complete(&self, row: &Removal) -> Result<(), ServerRefusal> {        self.readable()?;        let mut rows = self.rows.lock().unwrap_or_else(|e| e.into_inner());        let next: Vec<_> = rows.iter().filter(|old| *old != row).cloned().collect();        self.save(&next)?;        *rows = next;        Ok(())    }    pub(super) fn for_origin(&self, origin: &str) -> Result<Vec<Removal>, ServerRefusal> {        self.readable()?;        Ok(self            .rows            .lock()            .unwrap_or_else(|e| e.into_inner())            .iter()            .filter(|r| r.origin == origin)            .cloned()            .collect())    }}fn read(path: &Path) -> Result<Vec<Removal>, String> {    match std::fs::read(path) {        Ok(bytes) => serde_json::from_slice(&bytes)            .map_err(|e| format!("Device removals could not be read: {e}")),        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),        Err(e) => Err(format!("Device removals could not be read: {e}")),    }}/// Device-local typed state for the generic row, including after a restart.pub fn pending(path: &Path, database: &str, device: &str) -> Result<bool, String> {    Ok(read(path)?        .iter()        .any(|r| r.database == database && r.device == device))}pub(super) fn transient(error: &ServerRefusal) -> bool {    error.status == 0 || error.status >= 500 || matches!(error.status, 408 | 429)}pub(super) fn waiting() -> ClientAnswer {    ClientAnswer {        status: 202,        body: br#"{"pending":true}"#.to_vec(),    }}/// Read the pending device keys once for a list or page answer.pub fn pending_devices(    path: &Path,    database: &str,) -> Result<std::collections::BTreeSet<String>, String> {    Ok(read(path)?        .into_iter()        .filter(|r| r.database == database)        .map(|r| r.device)        .collect())}