//! The drain's port and the hydrator's, filled at the person's own object. //! //! One protocol, the Worker's media door (`apps/business/src/media.ts`), under //! the object's bearer — the same door the Mac's importer puts through //! (`cotton-mac`'s `ObjectClient`) and the same GET `personal.connect`'s //! `ObjectMedia` reads pictures through: //! //! * `PUT /v1/media/` with the row's content type and the file's length: //! the bytes, streamed off the file. A key the object already holds at that //! size answers `{stored: false}` and takes nothing, so a picture the Mac //! imported first is never stored twice; //! * above [`PART_BYTES`], the file in parts: `POST …?uploads {size, //! content_type}` (or `{stored: false}` for a key held already), one `PUT //! …?upload=&part=` per part, each streamed off its slice of the //! file, and `POST …?upload= {parts}` to put them together; //! * `GET /v1/media/`: the bytes coming down, written to a file; //! * `POST /v1/media/stream {key}`: a film's HLS master signed for a while, //! `{url, expires_at}` — the player reads it and every playlist and segment //! under it with no bearer, so the credential never leaves this crate. //! //! Bytes are a FILE on both legs, never a `Vec`: a 100 MB video is the //! ordinary case here, and build 106 already paid for the other shape once. use std::io::{Read, Seek, SeekFrom}; use std::path::Path; use std::sync::Arc; use cotton_store::media_ledger::MediaRow; use serde_json::{json, Value}; use crate::media::drain::{Landed, MediaDrainDeps}; use crate::transport::object::{bearer, media_path, routes, ObjectAddress, ObjectRefusal}; use crate::transport::{Exchange, ServerRefusal}; /// What one part of a file sent in parts weighs, and the most a file sent in /// one PUT may: under the Worker's one-request limit (`MEDIA_MAX_BYTES`, /// 100 MB, refused at the edge before the Worker sees it) and over R2's 5 MB /// floor for every part but the last. The Mac's number (`cotton-mac`'s /// `object::PART_BYTES`), so one file is cut the same way from either. pub const PART_BYTES: u64 = 64 * 1024 * 1024; /// A body the transport reads and seeks: a file, or a file sealed as it is read. pub trait ReadSeek: Read + Seek + Send {} impl ReadSeek for T {} /// The object's media door, for one credential. pub struct ObjectMediaTransport { address: ObjectAddress, exchange: Arc, credential: String, /// What one part weighs: [`PART_BYTES`], smaller only in a test. part_bytes: u64, /// The person's files this transport seals going up and opens coming down (R6); none, every file as it is. files: Option>, /// PLAYER START (26 Nov 2026): the sealed windows this transport read lately (key, window start, file length, /// bytes), so the player's next request through the phone's door, which opens the file again, asks the object /// nothing for a window it already read (the first, which says the length; a film's index at its end). windows: std::sync::Mutex)>>, /// RELAY 2: the read ahead's generation; a seek away or a release moves it on, and a fetch ahead not yet begun /// under an older one asks nothing. ahead_generation: std::sync::atomic::AtomicU64, /// How many fetches ahead are on their way now: at most [`super::remote::AHEAD`]. ahead_in_flight: std::sync::atomic::AtomicUsize, } /// One sealed window, fetched or being fetched: its file's length and bytes, or the object's refusal as it came. #[derive(Default)] pub(super) struct Slot { done: std::sync::Mutex>), ServerRefusal>>>, ready: std::sync::Condvar, } /// How many sealed windows (about 1 MiB each) a transport keeps, oldest dropped first (RELAY 2: 8, about 8 MiB). pub const WINDOWS_KEPT: usize = 8; impl std::fmt::Debug for ObjectMediaTransport { // The credential is never said, however the transport is printed. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ObjectMediaTransport").field("address", &self.address).finish_non_exhaustive() } } /// The object's refusal as the drain reads one: its status and word kept, so /// `object_full` fails a row with the object's own sentence and a dropped line /// (status 0) backs off. fn refusal(refused: ObjectRefusal) -> ServerRefusal { if refused.status == 0 { return ServerRefusal::offline(refused.message); } ServerRefusal::new(refused.message, refused.status).with_code(refused.code) } fn unreadable(path: &Path, error: &std::io::Error) -> ServerRefusal { ServerRefusal::offline(format!("{} could not be read ({error})", path.display())) } /// `{stored: false}` is a key the object held already; anything else stored. fn landed_of(answer: &Value) -> Landed { if answer.get("stored") == Some(&Value::Bool(false)) { Landed::Held } else { Landed::Stored } } /// A film's stream, as the object signed it: the master's address, which /// names its own token, and when the token stops being taken. #[derive(Debug, Clone, PartialEq, Eq)] pub struct StreamGrant { pub url: String, pub expires_at: String, } impl ObjectMediaTransport { pub fn new(address: ObjectAddress, exchange: Arc, credential: String) -> ObjectMediaTransport { ObjectMediaTransport { address, exchange, credential, part_bytes: PART_BYTES, files: None, windows: std::sync::Mutex::new(Vec::new()), ahead_generation: std::sync::atomic::AtomicU64::new(0), ahead_in_flight: std::sync::atomic::AtomicUsize::new(0) } } /// The same door, sealing `files`' own files before they go up and opening /// them as they come down (R6, `super::sealed`). pub fn sealing(mut self, files: Arc) -> ObjectMediaTransport { self.files = Some(files); self } /// `key` fetched into `dest` as plaintext: a person's file opened here with /// its own key (sealed, or clear and the bytes its name says); any other /// key as the object sends it. pub fn fetch_opened_to(&self, key: &str, dest: &Path) -> Result<(), ServerRefusal> { let Some(files) = self.files.as_ref().filter(|files| files.seals(key)) else { return self.fetch_to(key, None, dest); }; let raw = dest.with_extension("sealed"); self.fetch_to(key, None, &raw)?; // A clear file from before needs no key; a sealed one its own, or the one a file the object sealed at // arrival carries wrapped to this person. files.open_fetched(key, &raw, dest) } /// Stream an original or an object-drawn rendition through the same /// authenticated door as uploads and hydration. pub fn fetch_to(&self, key: &str, width: Option, dest: &Path) -> Result<(), ServerRefusal> { self.address.fetch_media_to(self.exchange.as_ref(), &self.credential, key, width, dest).map_err(refusal) } /// A film's HLS master `key`, signed for the player: the object answers /// an address under its own token (`routes::MEDIA_STREAM`). An answer /// with no `https` address or no expiry is the object's fault, said so. pub fn stream(&self, key: &str) -> Result { let answer = self .address .send(self.exchange.as_ref(), "POST", routes::MEDIA_STREAM, bearer(&self.credential), Some(&json!({"key": key}))) .map_err(refusal)?; let text = |name: &str| answer.get(name).and_then(Value::as_str).map(str::trim).filter(|text| !text.is_empty()); let url = text("url") .filter(|url| url.starts_with("https://") || url.starts_with("http://")) .ok_or_else(|| ServerRefusal::new("the object signed no address for this film", 502))?; let expires_at = text("expires_at").ok_or_else(|| ServerRefusal::new("the object said no expiry for this film's address", 502))?; Ok(StreamGrant { url: url.to_string(), expires_at: expires_at.to_string() }) } /// The sealed window of `key` from `start`, `len` bytes asked: the file's length and its bytes. One read lately is /// answered from the transport; one another thread is fetching now (Play's look ahead, or the window before's /// read ahead) is waited for, never fetched twice; else it is fetched and kept (PLAYER START, 26 Nov 2026). pub(super) fn window(&self, key: &str, start: u64, len: u64) -> Result<(u64, Arc>), ServerRefusal> { let (slot, mine) = { let mut kept = self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner); match kept.iter().position(|(k, s, _)| k == key && *s == start) { Some(at) => { // The newest last, so a window read again is the last dropped. let window = kept.remove(at); let slot = Arc::clone(&window.2); kept.push(window); (slot, false) } None => { let slot = Arc::new(Slot::default()); kept.push((key.to_string(), start, Arc::clone(&slot))); if kept.len() > WINDOWS_KEPT { kept.remove(0); } (slot, true) } } }; if mine { let fetched = self.fetch_range(key, start, len).map(|(bytes, total)| (total, Arc::new(bytes))); // A refusal is not kept, and nor is a window shorter than the file holds from its start (RELAY 2): the // next ask fetches again rather than reading past what came. let whole = fetched.as_ref().is_ok_and(|(total, bytes)| bytes.len() as u64 >= len.min(total.saturating_sub(start))); if !whole { self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).retain(|(_, _, s)| !Arc::ptr_eq(s, &slot)); } let mut done = slot.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); *done = Some(fetched.as_ref().map(|(total, bytes)| (*total, Arc::clone(bytes))).map_err(Clone::clone)); slot.ready.notify_all(); return fetched; } let mut done = slot.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner); while done.is_none() { done = slot.ready.wait(done).unwrap_or_else(std::sync::PoisonError::into_inner); } // The object's own refusal, its status and code as they came (RELAY 2: never a 502 of the waiter's own). match done.as_ref().expect("filled") { Ok((total, bytes)) => Ok((*total, Arc::clone(bytes))), Err(refusal) => Err(refusal.clone()), } } /// RELAY 2: the read ahead stops: a fetch ahead not yet begun asks nothing (one on its way finishes, at most /// [`super::remote::AHEAD`] of them). A seek away from where the film was read, and a release, ask it. pub fn cancel_ahead(&self) { self.ahead_generation.fetch_add(1, std::sync::atomic::Ordering::SeqCst); } /// RELAY 2: every window this transport holds let go, and its read ahead stopped: a play stopped, the app gone to /// the background, the phone signed out. pub fn release(&self) { self.cancel_ahead(); self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).clear(); } /// How many windows it holds or is fetching now. pub fn windows_held(&self) -> usize { self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).len() } /// The window of `key` from `start` fetched on a thread of its own, kept for whoever asks it next. pub(super) fn fetch_ahead(self: &Arc, key: &str, start: u64, len: u64) { use std::sync::atomic::Ordering; // Held, or on its way: nothing more to ask. if self.windows.lock().unwrap_or_else(std::sync::PoisonError::into_inner).iter().any(|(k, s, _)| k == key && *s == start) { return; } // Bounded (RELAY 2): at most AHEAD fetches ahead at once; past that, the read itself asks when it gets there. if self.ahead_in_flight.fetch_add(1, Ordering::SeqCst) >= super::remote::AHEAD { self.ahead_in_flight.fetch_sub(1, Ordering::SeqCst); return; } let generation = self.ahead_generation.load(Ordering::SeqCst); let (transport, key) = (Arc::clone(self), key.to_string()); std::thread::spawn(move || { // Cancelled before it began (a seek away, a stop): it asks nothing. if transport.ahead_generation.load(Ordering::SeqCst) == generation { let _ = transport.window(&key, start, len); } transport.ahead_in_flight.fetch_sub(1, Ordering::SeqCst); }); } /// How many fetches ahead are on their way now. pub fn ahead_in_flight(&self) -> usize { self.ahead_in_flight.load(std::sync::atomic::Ordering::SeqCst) } /// `len` bytes of `key` as the object keeps it, from `offset`, and the object's whole length. pub fn fetch_range(&self, key: &str, offset: u64, len: u64) -> Result<(Vec, u64), ServerRefusal> { self.address.fetch_media_range(self.exchange.as_ref(), &self.credential, key, offset, len).map_err(refusal) } /// A person's sealed file read where it lies, as plaintext any range of /// which opens from the parts it covers (R6): a film seeks with nothing /// downloaded whole. Refused for a file that is not one of the person's, /// or that the object holds not sealed. pub fn open_remote(self: &Arc, key: &str) -> Result, ServerRefusal> { let files = self.files.as_ref().filter(|files| files.seals(key)).ok_or_else(|| ServerRefusal::new(format!("{key} is not a file this device seals"), 400))?; let fk = files.file_key(key)?; let remote = super::remote::RemoteSealed::open(Arc::clone(self), key)?; if !remote.is_sealed() { return Err(ServerRefusal::new(format!("{key} is not sealed where the object keeps it"), 422).with_code("seal_does_not_open")); } let len = remote.len(); cotton_core::seal::file::OpeningReader::new(&fk, key, remote, len).map_err(|error| ServerRefusal::new(error.to_string(), 422).with_code(error.code())) } /// The same door, cutting files at `part_bytes`: a test proves the parts /// without writing 64 MB. #[cfg(test)] pub(crate) fn with_parts_of(mut self, part_bytes: u64) -> ObjectMediaTransport { self.part_bytes = part_bytes; self } /// `path`, `length` bytes, under `key` in one PUT. fn put_whole(&self, key: &str, file: &mut dyn ReadSeek, path: &Path, length: u64, content_type: &str) -> Result { file.seek(SeekFrom::Start(0)).map_err(|error| unreadable(path, &error))?; let mut headers = bearer(&self.credential); headers.push(("Content-Type".into(), content_type.to_string())); let answer = self .address .send_file(self.exchange.as_ref(), "PUT", &media_path(key), headers, file, length) .map_err(refusal)?; Ok(landed_of(&answer)) } /// `path`, `length` bytes, under `key` in parts of `part_bytes`, each /// streamed off its own slice of the file. A part refused fails the whole; /// the next attempt starts a new upload (R2 lets an unfinished one go). fn put_in_parts(&self, key: &str, file: &mut dyn ReadSeek, path: &Path, length: u64, content_type: &str) -> Result { let at = media_path(key); let started = self .address .send( self.exchange.as_ref(), "POST", &format!("{at}?uploads"), bearer(&self.credential), Some(&json!({"size": length, "content_type": content_type})), ) .map_err(refusal)?; if landed_of(&started) == Landed::Held { return Ok(Landed::Held); } let upload = started .get("upload") .and_then(Value::as_str) .filter(|upload| !upload.is_empty()) .ok_or_else(|| ServerRefusal::new("the object started no upload for this file", 502))?; let query = url::form_urlencoded::Serializer::new(String::new()).append_pair("upload", upload).finish(); let mut parts = Vec::new(); let mut sent = 0u64; let mut number = 1u32; while sent < length { let want = self.part_bytes.min(length - sent); file.seek(SeekFrom::Start(sent)).map_err(|error| unreadable(path, &error))?; let mut slice = (&mut *file).take(want); let mut headers = bearer(&self.credential); headers.push(("Content-Type".into(), "application/octet-stream".into())); let answer = self .address .send_file(self.exchange.as_ref(), "PUT", &format!("{at}?{query}&part={number}"), headers, &mut slice, want) .map_err(refusal)?; let etag = answer .get("etag") .and_then(Value::as_str) .ok_or_else(|| ServerRefusal::new("a part came back with no etag", 502))?; parts.push(json!({"part": number, "etag": etag})); sent += want; number += 1; } let finished = self .address .send(self.exchange.as_ref(), "POST", &format!("{at}?{query}"), bearer(&self.credential), Some(&json!({"parts": parts}))) .map_err(refusal)?; Ok(landed_of(&finished)) } } impl MediaDrainDeps for ObjectMediaTransport { fn upload(&self, row: &MediaRow, local_path: &Path) -> Result { self.upload_watched(row, local_path, Arc::new(|_, _| {})) } fn upload_watched(&self, row: &MediaRow, local_path: &Path, progress: crate::media::drain::Progress) -> Result { // The LENGTH is the file's own, read once: what `Content-Length` // promises and what the object checks a held key's size against. let length = std::fs::metadata(local_path).map_err(|error| unreadable(local_path, &error))?.len(); let file = std::fs::File::open(local_path).map_err(|error| unreadable(local_path, &error))?; // A person's own file goes up sealed, never open (R6): its parts are // made as they are read, and the object is told only that it is sealed. let (body, length, content_type): (Box, u64, &str) = match self.files.as_ref().filter(|files| files.seals(&row.key)) { Some(files) => { let fk = files.file_key(&row.key)?; let sealing = cotton_core::seal::file::SealingReader::new(&fk, &row.key, std::io::BufReader::new(file), length); let sealed = sealing.sealed_len(); (Box::new(sealing), sealed, super::sealed::SEALED_FILE_TYPE) } None => (Box::new(file), length, row.content_type.as_str()), }; // HOW FAR IT HAS GONE (MEDIA DRAIN 1): the body counts what the // request has read off it, which is what has gone onto the wire // give or take one buffer. let mut body = Counted::new(body, length, progress); if length > self.part_bytes { self.put_in_parts(&row.key, &mut body, local_path, length, content_type) } else { self.put_whole(&row.key, &mut body, local_path, length, content_type) } } } /// A body that says how far it has been read: the furthest byte read, so a /// part sent again after a seek back does not count twice. struct Counted { inner: Box, at: u64, furthest: u64, told: u64, total: u64, progress: crate::media::drain::Progress, } /// How often a count is told: every 64 KiB, and at the end (4,500 tellings /// for a 290 MB film, each a map write). const TELL_EVERY: u64 = 64 * 1024; impl Counted { fn new(inner: Box, total: u64, progress: crate::media::drain::Progress) -> Counted { progress(0, total); Counted { inner, at: 0, furthest: 0, told: 0, total, progress } } } impl Read for Counted { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let n = self.inner.read(buf)?; self.at += n as u64; if self.at > self.furthest { self.furthest = self.at; if self.furthest - self.told >= TELL_EVERY || self.furthest >= self.total { self.told = self.furthest; (self.progress)(self.furthest, self.total); } } Ok(n) } } impl Seek for Counted { fn seek(&mut self, to: SeekFrom) -> std::io::Result { self.at = self.inner.seek(to)?; Ok(self.at) } } impl super::hydrate::MediaHydrateDeps for ObjectMediaTransport { /// The hydrator's bytes, through the GET `ObjectMedia` reads pictures by. fn fetch_object_to(&self, _database: &str, key: &str, dest: &Path) -> Result<(), ServerRefusal> { self.fetch_opened_to(key, dest) } fn free_bytes(&self, path: &Path) -> Option { super::hydrate::free_bytes_at(path) } } #[cfg(test)] #[path = "transport_tests.rs"] mod tests;