Cotton code
140 lines · 5.8 KB · RustRaw
//! A sealed file read where the object keeps it (R6): `Read + Seek` over its//! sealed bytes, each read a `Range` request of whole sealed parts, so an//! `OpeningReader` over it opens any plaintext range of a 2 GB film from the//! parts that range covers and nothing else.use std::io::{Read, Seek, SeekFrom};use std::sync::Arc;use cotton_core::seal::file::{HEAD, MAGIC, SEALED_PART};use super::transport::ObjectMediaTransport;use crate::transport::ServerRefusal;/// The sealed bytes one request reads: 16 parts, about 1 MiB, from a part's start.pub const WINDOW: u64 = 16 * SEALED_PART;/// How many windows a read fetches ahead of itself: three MiB in flight while one is read.pub const AHEAD: usize = 3;/// One sealed file at the object.pub struct RemoteSealed {    transport: Arc<ObjectMediaTransport>,    key: String,    len: u64,    pos: u64,    held: (u64, Arc<Vec<u8>>),    /// Whether this reader has begun reading ahead: on its first read, never on its open alone (a prepare, and Play's    /// check that it opens, read the first window and nothing after it; RELAY 2).    ahead: bool,}impl std::fmt::Debug for RemoteSealed {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("RemoteSealed").field("key", &self.key).field("len", &self.len).finish_non_exhaustive()    }}impl RemoteSealed {    /// `key` at the object: its first window read, which says its length. Kept on the transport (PLAYER START, 26 Nov    /// 2026): a player asks the phone's door for a film several times as it starts (each request opens the file    /// again), and each open fetched the same first window, a round trip and about 1 MiB, before the range asked.    pub fn open(transport: Arc<ObjectMediaTransport>, key: &str) -> Result<RemoteSealed, ServerRefusal> {        let (len, bytes) = transport.window(key, 0, HEAD + WINDOW)?;        Ok(RemoteSealed { transport, key: key.to_string(), len, pos: 0, held: (0, bytes), ahead: false })    }    /// The sealed file's length.    pub fn len(&self) -> u64 {        self.len    }    /// Whether it is empty (no f1 file is).    pub fn is_empty(&self) -> bool {        self.len == 0    }    /// Whether the object holds it sealed (its first bytes are f1's).    pub fn is_sealed(&self) -> bool {        self.held.0 == 0 && self.held.1.starts_with(MAGIC)    }    /// The windows after the one from `from` fetched while this one is read, [`AHEAD`] of them: a film plays on    /// without waiting a round trip each MiB (PLAYER START: 3.8 MB segments came at about 1 MB/s, a window and its    /// round trip at a time; the iPhone's relay ran at about 5 Mbit/s).    fn read_ahead(&self, from: u64) {        let mut at = from;        for _ in 0..AHEAD {            let (_, len) = self.window_of(at);            at += len;            if at >= self.len {                return;            }            let (start, len) = self.window_of(at);            self.transport.fetch_ahead(&self.key, start, len);            at = start;        }    }    fn window_of(&self, at: u64) -> (u64, u64) {        // On a fixed grid (the head and the first window, then window after window), so a seek and a read ahead ask        // the same windows, and a window kept is found again; each starts at a sealed part's start.        if at < HEAD + WINDOW {            return (0, (HEAD + WINDOW).min(self.len));        }        let start = HEAD + (at - HEAD) / WINDOW * WINDOW;        (start, (start + WINDOW).min(self.len) - start)    }}impl Read for RemoteSealed {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        if buf.is_empty() || self.pos >= self.len {            return Ok(0);        }        let (start, bytes) = &self.held;        if self.pos < *start || self.pos >= start + bytes.len() as u64 {            let (from, len) = self.window_of(self.pos);            let (_, fetched) = self.transport.window(&self.key, from, len).map_err(|refusal| std::io::Error::other(refusal.message))?;            // A window shorter than asked that does not reach where this reads (RELAY 2): said, never read past.            if fetched.is_empty() || self.pos >= from + fetched.len() as u64 {                return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "the object sent less of this range than asked"));            }            self.held = (from, fetched);            self.read_ahead(from);            self.ahead = true;        } else if !self.ahead {            self.read_ahead(*start);            self.ahead = true;        }        let (start, bytes) = &self.held;        let within = (self.pos - start) as usize;        if within >= bytes.len() {            return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "the object sent less of this range than asked"));        }        let n = (bytes.len() - within).min(buf.len());        buf[..n].copy_from_slice(&bytes[within..within + n]);        self.pos += n as u64;        Ok(n)    }}impl Seek for RemoteSealed {    fn seek(&mut self, to: SeekFrom) -> std::io::Result<u64> {        let at = match to {            SeekFrom::Start(n) => Some(n),            SeekFrom::End(d) => self.len.checked_add_signed(d),            SeekFrom::Current(d) => self.pos.checked_add_signed(d),        };        let at = at.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidInput, "a seek before the start"))?;        // A seek away from the window read and those just after it (RELAY 2): the read ahead there is no longer        // ahead of anything, so what has not begun asks nothing. A seek within reach keeps it.        let (start, bytes) = &self.held;        let reach = start + bytes.len() as u64 + AHEAD as u64 * WINDOW;        if self.ahead && (at < *start || at >= reach) {            self.transport.cancel_ahead();        }        self.pos = at;        Ok(self.pos)    }}