Cotton code
170 lines · 6.6 KB · RustRaw
//! Sync reads take priority over media streams on a shared transport.//!//! A read closes media sockets registered with [`RecordsFirst::streaming`].//! Its own socket can be closed by [`RecordsFirst::cut_reads`] when the sync//! task has stopped waiting for a pass. One gate belongs to each signed//! transport, shared by all its requests.use std::collections::BTreeMap;use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};/// Closes one media fetch's socket from another thread.pub type Closer = Box<dyn Fn() + Send + Sync>;/// The gate. Cheap to share; every clone of the `Arc` is the same gate.pub struct RecordsFirst {    reads: AtomicUsize,    /// A description of the media fetch on the wire, for timeout diagnostics.    media: Mutex<Option<String>>,    /// The media fetches streaming now, each with the closer of its socket.    streams: Mutex<BTreeMap<u64, Closer>>,    /// The sync reads on the wire now, each with the closer of its socket    /// once it is dialled — what [`RecordsFirst::cut_reads`] shuts.    read_sockets: Mutex<BTreeMap<u64, Closer>>,    next: AtomicU64,}impl Default for RecordsFirst {    fn default() -> RecordsFirst {        RecordsFirst {            reads: AtomicUsize::new(0),            media: Mutex::new(None),            streams: Mutex::new(BTreeMap::new()),            read_sockets: Mutex::new(BTreeMap::new()),            next: AtomicU64::new(0),        }    }}impl std::fmt::Debug for RecordsFirst {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("RecordsFirst")            .field("reads", &self.reads)            .field("media", &self.media)            .finish_non_exhaustive()    }}/// A media fetch on the wire, registered so a sync read can close it.pub struct Streaming(Arc<RecordsFirst>, u64);impl Drop for Streaming {    fn drop(&mut self) {        self.0.streams.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.1);    }}/// A sync read on the wire. The gate is lowered when the last one drops.#[derive(Debug)]pub struct SyncRead(Arc<RecordsFirst>, u64);impl SyncRead {    /// The read is dialled over the socket `close` shuts: a    /// [`RecordsFirst::cut_reads`] from here on closes it.    pub fn over(&self, close: Option<Closer>) {        if let Some(close) = close {            self.0.read_sockets.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(self.1, close);        }    }}impl Drop for SyncRead {    fn drop(&mut self) {        self.0.read_sockets.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.1);        self.0.reads.fetch_sub(1, Ordering::SeqCst);    }}impl RecordsFirst {    /// A sync read begins; it holds the gate until the guard drops, and every    /// media fetch streaming now is closed at once.    pub fn reading(self: &Arc<Self>) -> SyncRead {        self.reads.fetch_add(1, Ordering::SeqCst);        for close in self.streams.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).values() {            close();        }        SyncRead(Arc::clone(self), self.next.fetch_add(1, Ordering::SeqCst))    }    /// CUT EVERY SYNC READ ON THE WIRE: its socket is shut, so a read that a    /// frozen process left waiting on a dead line ends now, not at its    /// sixty-second ceiling. Only a pass the loop already stopped waiting for    /// is cut this way; what it folded before stays folded.    pub fn cut_reads(&self) {        for close in self.read_sockets.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).values() {            close();        }    }    /// A media fetch is streaming over the socket `close` shuts; a sync read    /// that starts before the guard drops closes it.    pub fn streaming(self: &Arc<Self>, close: Closer) -> Streaming {        let id = self.next.fetch_add(1, Ordering::SeqCst);        self.streams.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(id, close);        Streaming(Arc::clone(self), id)    }    /// Is a sync read on the wire — must a media fetch yield?    pub fn due(&self) -> bool {        self.reads.load(Ordering::SeqCst) > 0    }    /// The media fetch on the wire now, or `None` when it is over.    pub fn media(&self, what: Option<String>) {        *self.media.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = what;    }    /// What media fetch was on the wire, for a sync read's failure.    pub fn media_in_flight(&self) -> Option<String> {        self.media.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).clone()    }}/// Is this request a SYNC READ — one of the exchange routes?pub fn is_sync_read(path: &str) -> bool {    let route = path.split('?').next().unwrap_or(path);    route == "/v1/sync/exchange" || route == cotton_store::protocol::types::EXCHANGE_SECTIONS_PATH}#[cfg(test)]mod tests {    use super::*;    /// RULE: The exchange outranks every media fetch: while any sync read is on the wire the gate is raised and a media fetch must yield, and it lowers only when the last read is over — records before bytes (architect, 13 Oct 2026).    #[test]    fn the_gate_is_raised_for_as_long_as_a_sync_read_is_on_the_wire() {        let gate = Arc::new(RecordsFirst::default());        assert!(!gate.due());        let one = gate.reading();        let two = gate.reading();        assert!(gate.due());        drop(one);        assert!(gate.due(), "a second read still holds it");        drop(two);        assert!(!gate.due());        assert!(is_sync_read("/v1/sync/exchange?db=x"));        assert!(is_sync_read(cotton_store::protocol::types::EXCHANGE_SECTIONS_PATH));        assert!(!is_sync_read("/v1/media/synthetic-key"));    }    /// RULE: A sync read's start closes every media fetch streaming at that moment — cancelled, not left to stop at its next chunk — and a fetch that has ended is never closed again.    #[test]    fn a_sync_read_closes_every_media_fetch_streaming_at_its_start() {        use std::sync::atomic::AtomicUsize;        let gate = Arc::new(RecordsFirst::default());        let closed = Arc::new(AtomicUsize::new(0));        let counter = |closed: &Arc<AtomicUsize>| -> Closer {            let closed = Arc::clone(closed);            Box::new(move || {                closed.fetch_add(1, Ordering::SeqCst);            })        };        let active = gate.streaming(counter(&closed));        let ended = gate.streaming(counter(&closed));        drop(ended);        let _read = gate.reading();        assert_eq!(closed.load(Ordering::SeqCst), 1, "the active stream was closed, the ended one not");        drop(active);    }}