Cotton code
140 lines · 4.9 KB · RustRaw
//! The Mac's copy of the bytes — the client half of offline-first media.//!//! The rule is the phone's, unchanged: **bytes are part of the life, so the//! DEVICE holds them permanently and R2 is the backup.** Nothing here evicts,//! and the only thing that removes a file is the owner removing the record it//! belongs to.//!//! The layout is the phone's too — `<root>/<workspaceId>/<sha[0:2]>/<sha>.<ext>`//! — for the phone's reason: content-addressed, so the same photo forwarded into//! two threads, or a second import of the same backup, converges on ONE file//! instead of accumulating copies nobody can tell apart; and split by two//! characters of the digest, so no directory ends up holding 57,000 entries.//!//! UNDER `client/`, NOT beside the embedded server's `files/`. This Mac may hold//! its own server AND be a client of somebody else's, and the replica already//! refused to mix those two roles in one directory. The server's own object//! store is keyed by R2 object key and is a different thing entirely — that one//! is the bucket, this one is the device.use std::io::Read;use std::path::{Path, PathBuf};use sha2::{Digest, Sha256};use crate::layout::Layout;/// How much of a file is read at a time while hashing.////// NEVER the whole file into memory: a chat video out of a backup is routinely/// tens of megabytes and an import walks 57,000 of them, so one whole-file read/// per attachment is how a 16 GB Mac stops responding halfway through somebody's/// history.const HIGH_WATER_MARK: usize = 1024 * 1024;/// Where bytes with this digest live, whatever wrote them.pub fn media_file_path(layout: &Layout, workspace_id: &str, sha256: &str, ext: &str) -> PathBuf {    let name = if ext.is_empty() {        sha256.to_string()    } else {        format!("{sha256}.{ext}")    };    layout        .client_media_dir()        .join(workspace_id)        .join(&sha256[..2.min(sha256.len())])        .join(name)}#[derive(Debug, Clone, PartialEq, Eq)]pub struct StoredMediaFile {    pub sha256: String,    pub size_bytes: u64,    /// Absolute path inside the store.    pub path: PathBuf,}/// The digest of a file, taken through a stream.pub fn sha256_file(path: &Path) -> std::io::Result<(String, u64)> {    let mut file = std::fs::File::open(path)?;    let mut hasher = Sha256::new();    let mut buffer = vec![0u8; HIGH_WATER_MARK];    let mut size_bytes = 0u64;    loop {        let read = file.read(&mut buffer)?;        if read == 0 {            break;        }        hasher.update(&buffer[..read]);        size_bytes += read as u64;    }    Ok((hex::encode(hasher.finalize()), size_bytes))}/// Copy a file into the store and answer where it landed.////// Idempotent, because the destination IS the content: a file already there is/// the SAME bytes, so the copy is skipped rather than repeated. That is what/// makes re-running an interrupted import cheap — it re-hashes, and moves/// nothing.////// The copy goes to a scratch name first and is renamed into place, so a run/// killed mid-copy can never leave half a file under a name that says its/// digest. `rename` within one filesystem is atomic; the scratch sits in the/// same directory precisely so it is one.pub fn put_media_file(    layout: &Layout,    workspace_id: &str,    source: &Path,    ext: &str,) -> std::io::Result<StoredMediaFile> {    let _backup = cotton_store::media_backup_lock::mutating(&layout.client_media_dir())?;    let (sha256, size_bytes) = sha256_file(source)?;    let path = media_file_path(layout, workspace_id, &sha256, ext);    if path.exists() {        return Ok(StoredMediaFile {            sha256,            size_bytes,            path,        });    }    if let Some(parent) = path.parent() {        std::fs::create_dir_all(parent)?;    }    let scratch = path.with_file_name(format!(        "{}.part-{}",        path.file_name()            .and_then(std::ffi::OsStr::to_str)            .unwrap_or("media"),        std::process::id()    ));    match std::fs::copy(source, &scratch).and_then(|_| std::fs::rename(&scratch, &path)) {        Ok(()) => Ok(StoredMediaFile {            sha256,            size_bytes,            path,        }),        Err(error) => {            // A half copy under a name that promises a digest is worse than no            // copy at all: the next pass would find it, believe it, and hand a            // truncated file to the uploader.            let _ = std::fs::remove_file(&scratch);            Err(error)        }    }}/// How big a file is, or `None` when it is not there. Never fails outward: a/// missing attachment is a counted skip, not an error that takes a batch of/// five hundred messages down with it.pub fn file_size_of(path: &Path) -> Option<u64> {    std::fs::metadata(path)        .ok()        .filter(|info| info.is_file())        .map(|info| info.len())}#[cfg(test)]#[path = "store_tests.rs"]mod tests;