//! 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.pubtypeCloser = Box<dynFn() + Send + Sync>;/// The gate. Cheap to share; every clone of the `Arc` is the same gate.pubstructRecordsFirst { 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,}implDefaultforRecordsFirst {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::DebugforRecordsFirst {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.pubstructStreaming(Arc<RecordsFirst>, u64);implDropforStreaming {fn drop(&mutself) {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)]pubstructSyncRead(Arc<RecordsFirst>, u64);implSyncRead {/// The read is dialled over the socket `close` shuts: a/// [`RecordsFirst::cut_reads`] from here on closes it.pubfn over(&self, close: Option<Closer>) {ifletSome(close) = close {self.0.read_sockets.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).insert(self.1, close); } }}implDropforSyncRead {fn drop(&mutself) {self.0.read_sockets.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).remove(&self.1);self.0.reads.fetch_sub(1, Ordering::SeqCst); }}implRecordsFirst {/// A sync read begins; it holds the gate until the guard drops, and every/// media fetch streaming now is closed at once.pubfn reading(self: &Arc<Self>) -> SyncRead {self.reads.fetch_add(1, Ordering::SeqCst);for close inself.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.pubfn cut_reads(&self) {for close inself.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.pubfn 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?pubfn due(&self) -> bool {self.reads.load(Ordering::SeqCst) > 0 }/// The media fetch on the wire now, or `None` when it is over.pubfn 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.pubfn 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?pubfn 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 {usesuper::*;/// 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); }}