Cotton code
96 lines · 4.2 KB · RustRaw
//! ONE FETCH OF AN ORIGINAL, RESUMED — never the whole file twice.//!//! On 13 Oct 2026 the serving Mac streamed the same 354.2 MB original to the//! owner's phone twice, three minutes apart: the kept-files sweep and a//! person's open (`media.ensure`) each fetched the key into a scratch file of//! their own, nothing told either that the other was already fetching it, and//! a fetch that stopped part way deleted what had arrived. Now that a sync//! read cuts every media stream at its start (records before bytes), a cut//! that threw the bytes away would refetch the whole file after every read.//!//! So://! - ONE partial file per key ([`partial_path`]), shared by every caller, and//!   a cut keeps it ([`keeps_partial`]): the next fetch asks only for what is//!   not on disk yet (`Range: bytes=N-`, `SocketObjectBytes::download`).//! - ONE fetch per key at a time ([`turn`]): a second caller waits for the//!   first, then looks again at what it holds before it asks for a byte.use std::collections::BTreeSet;use std::path::{Path, PathBuf};use std::sync::{Condvar, Mutex};use crate::transport::ServerRefusal;/// Where the bytes of `key` gather while they arrive, in `folder` — the same/// path for every caller and every attempt. Named by the key's hash, never by/// the key, which may hold a path's worth of characters.pub fn partial_path(folder: &Path, key: &str) -> PathBuf {    // Hashed here, never through `vault`: that module is built only for a    // machine that hosts, and a phone fetches originals too.    use sha2::{Digest, Sha256};    let hash = hex::encode(Sha256::digest(key.as_bytes()));    folder.join(format!("partial-{}.part", &hash[..32]))}/// Does a fetch that ended with `refusal` keep what arrived? A cut, a dropped/// line or a wait for the records (status 0) keeps it, to resume; an answer/// from the store (a refusal with a status) means those bytes are not to be/// had, and they go.pub fn keeps_partial(refusal: &ServerRefusal) -> bool {    refusal.status == 0}static FETCHING: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new());static DONE: Condvar = Condvar::new();/// This process's one fetch of `key`, until the guard drops.pub struct Turn(String);impl Drop for Turn {    fn drop(&mut self) {        FETCHING.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.0);        DONE.notify_all();    }}/// Take the turn to fetch `key`, waiting while another caller holds it. The/// caller then looks again at whether it holds `key` before it asks.pub fn turn(key: &str) -> Turn {    let mut fetching = FETCHING.lock().unwrap_or_else(|poisoned| poisoned.into_inner());    while fetching.contains(key) {        fetching = DONE.wait(fetching).unwrap_or_else(|poisoned| poisoned.into_inner());    }    fetching.insert(key.to_string());    Turn(key.to_string())}#[cfg(test)]mod tests {    use super::*;    /// RULE: One fetch of an original at a time per key in this process — a second caller (the sweep beside a person's open) waits for the first and looks again before it asks; on 13 Oct 2026 the same 354.2 MB original was streamed to the phone twice, three minutes apart.    #[test]    fn a_second_fetch_of_a_key_waits_for_the_first() {        let first = turn("synthetic/key-one");        let order = std::sync::Arc::new(Mutex::new(Vec::new()));        let seen = std::sync::Arc::clone(&order);        let second = std::thread::spawn(move || {            let _turn = turn("synthetic/key-one");            seen.lock().expect("order").push("second");        });        let _other = turn("synthetic/key-two");        std::thread::sleep(std::time::Duration::from_millis(100));        order.lock().expect("order").push("first done");        drop(first);        second.join().expect("the second");        assert_eq!(*order.lock().expect("order"), vec!["first done", "second"]);    }    #[test]    fn a_cut_keeps_what_arrived_and_a_refusal_does_not() {        assert!(keeps_partial(&ServerRefusal::offline("the bytes stopped arriving")));        assert!(!keeps_partial(&ServerRefusal::new("not yours", 403)));        assert_ne!(partial_path(Path::new("/m"), "a"), partial_path(Path::new("/m"), "b"));        assert_eq!(partial_path(Path::new("/m"), "a"), partial_path(Path::new("/m"), "a"));    }}