//! The object's media door, spoken by the drain and the hydrator, against a //! fake of the Worker's door (`apps/business/src/media.ts`) behind the //! [`Exchange`] seam: what goes on the wire, and what each answer does to a //! ledger row. use std::collections::BTreeMap; use std::io::Read; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use cotton_core::media::keys::photo_key; use cotton_store::media_ledger::{enqueue_media, media_by_key, MediaEnqueueInput}; use super::*; use crate::media::drain::{upload_one, Uploaded}; use crate::media::hydrate::MediaHydrateDeps; use crate::media::media_file_path; use crate::seams::{Clock, FixedClock}; use crate::test_support::{file_id, open_test_replica, WORKSPACE}; use crate::transport::http1::Http1Request; use crate::transport::scripted::{Reply, ScriptedExchange}; use crate::transport::{Answer, Origin}; const CREDENTIAL: &str = "ctd_invented_credential"; const OBJECT_FULL: &str = "This database's media have reached their size limit: they still read, but take nothing new."; /// One request as the door saw it. #[derive(Debug, Clone)] struct Asked { method: String, path: String, content_type: Option, length: usize, } /// The Worker's media door, as `media.ts` answers, over a map: a PUT stores /// unless the key holds those bytes, parts are started, carried and put /// together, a GET answers the bytes, and past `left` bytes it refuses /// `object_full`. `down` is a phone with no network. #[derive(Debug)] struct MediaDoor { held: Mutex, String)>>, uploads: Mutex>)>>, left: Mutex, asked: Mutex>, down: AtomicBool, } impl Default for MediaDoor { fn default() -> Self { MediaDoor { held: Mutex::default(), uploads: Mutex::default(), left: Mutex::new(u64::MAX), asked: Mutex::default(), down: AtomicBool::new(false), } } } fn header(request: &Http1Request<'_>, name: &str) -> Option { request.headers.iter().find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.clone()) } fn decoded(path: &str) -> String { url::form_urlencoded::parse(format!("k={}", path.replace('+', "%2B")).as_bytes()) .next() .map(|(_, value)| value.into_owned()) .unwrap_or_default() } impl MediaDoor { fn asked(&self) -> Vec { self.asked.lock().expect("the log").clone() } fn holds(&self, key: &str) -> Option<(Vec, String)> { self.held.lock().expect("the bucket").get(key).cloned() } fn answer(&self, request: &Http1Request<'_>, body: &[u8]) -> Reply { assert_eq!( header(request, "authorization").as_deref(), Some(format!("Bearer {CREDENTIAL}").as_str()), "every media request carries the object's bearer" ); let (route, query) = request.path.split_once('?').unwrap_or((request.path, "")); if route == "/v1/media/stream" { return self.stream(request, body); } let key = decoded(route.strip_prefix("/v1/media/").expect("a media route")); let query: BTreeMap = url::form_urlencoded::parse(query.as_bytes()).into_owned().collect(); let refuse = |status: u16, code: &str, message: &str| { Reply::json(status, &serde_json::json!({"code": code, "message": message}).to_string()) }; let mut left = self.left.lock().expect("the budget"); let mut held = self.held.lock().expect("the bucket"); let mut uploads = self.uploads.lock().expect("the uploads"); match (request.method, query.contains_key("uploads"), query.get("upload")) { ("PUT", false, None) => { let content_type = header(request, "content-type").unwrap_or_default(); if held.get(&key).is_some_and(|(bytes, _)| bytes.len() == body.len()) { return Reply::json(200, &format!(r#"{{"stored":false,"bytes":{}}}"#, body.len())); } if body.len() as u64 > *left { return refuse(413, "object_full", OBJECT_FULL); } *left -= body.len() as u64; held.insert(key, (body.to_vec(), content_type)); Reply::json(201, &format!(r#"{{"stored":true,"bytes":{}}}"#, body.len())) } ("POST", true, None) => { let asked: serde_json::Value = serde_json::from_slice(body).expect("a JSON start"); let size = asked["size"].as_u64().expect("a size"); if held.get(&key).is_some_and(|(bytes, _)| bytes.len() as u64 == size) { return Reply::json(200, &format!(r#"{{"stored":false,"bytes":{size}}}"#)); } if size > *left { return refuse(413, "object_full", OBJECT_FULL); } let id = format!("upload-{}", uploads.len() + 1); uploads.insert(id.clone(), (key, asked["content_type"].as_str().unwrap_or_default().to_string(), BTreeMap::new())); Reply::json(201, &format!(r#"{{"upload":"{id}"}}"#)) } ("PUT", false, Some(id)) => { let part: u32 = query.get("part").and_then(|n| n.parse().ok()).expect("a part number"); let Some((_, _, parts)) = uploads.get_mut(id) else { return refuse(404, "no_upload", "no such upload") }; parts.insert(part, body.to_vec()); Reply::json(200, &format!(r#"{{"part":{part},"etag":"etag-{part}"}}"#)) } ("POST", false, Some(id)) => { let Some((under, content_type, parts)) = uploads.remove(id) else { return refuse(400, "bad_upload", "no such upload") }; let named: serde_json::Value = serde_json::from_slice(body).expect("a JSON finish"); let numbers: Vec = named["parts"].as_array().expect("parts").iter().map(|p| p["part"].as_u64().expect("a number")).collect(); assert_eq!(numbers, (1..=parts.len() as u64).collect::>(), "every part named, in order"); let whole: Vec = parts.into_values().flatten().collect(); *left -= whole.len() as u64; held.insert(under, (whole.clone(), content_type)); Reply::json(201, &format!(r#"{{"stored":true,"bytes":{}}}"#, whole.len())) } ("GET", false, None) => match held.get(&key) { Some((bytes, _)) if header(request, "range").is_some() => { let range = header(request, "range").unwrap(); let (first, last) = range.trim_start_matches("bytes=").split_once('-').unwrap(); let first: usize = first.parse().unwrap(); let last: usize = last.parse::().unwrap().min(bytes.len() - 1); Reply::new(206, bytes[first..=last].to_vec()).with_header("content-range", &format!("bytes {first}-{last}/{}", bytes.len())) } Some((bytes, _)) => Reply::new(200, bytes.clone()), None => refuse(404, "not_found", "no such media"), }, (method, _, _) => panic!("the door takes no {method} {}", request.path), } } /// The stream route as the Worker's contract says it: a master the /// bucket holds is signed under a token for its folder; any other key /// is the object's 404. fn stream(&self, request: &Http1Request<'_>, body: &[u8]) -> Reply { assert_eq!(request.method, "POST", "a stream is minted by a POST"); let asked: serde_json::Value = serde_json::from_slice(body).expect("a JSON ask"); let key = asked["key"].as_str().expect("the master's key").to_string(); if !self.held.lock().expect("the bucket").contains_key(&key) { return Reply::json(404, r#"{"code":"not_found","message":"no such film"}"#); } let answer = serde_json::json!({ "url": format!("https://cottondb.com/v1/stream/tok-1/{key}"), "expires_at": "2026-11-04T12:00:00.000Z", }); Reply::json(200, &answer.to_string()) } fn reply( &self, origin: &Origin, request: &Http1Request<'_>, body: &[u8], ceiling: Duration, ) -> Result, String> { if self.down.load(Ordering::SeqCst) { return Err("no network".to_string()); } self.asked.lock().expect("the log").push(Asked { method: request.method.to_string(), path: request.path.to_string(), content_type: header(request, "content-type"), length: body.len(), }); let reply = self.answer(request, body); ScriptedExchange::new([reply]).send(origin, request, ceiling) } } impl Exchange for MediaDoor { fn send(&self, origin: &Origin, request: &Http1Request<'_>, ceiling: Duration) -> Result, String> { self.reply(origin, request, request.body.unwrap_or_default(), ceiling) } fn send_stream( &self, origin: &Origin, request: &Http1Request<'_>, body: &mut dyn Read, length: u64, ceiling: Duration, ) -> Result, String> { assert!(request.body.is_none(), "a streamed request carries its body on the reader"); let mut bytes = Vec::new(); body.take(length).read_to_end(&mut bytes).map_err(|error| error.to_string())?; assert_eq!(bytes.len() as u64, length, "the reader gave what the length promised"); self.reply(origin, request, &bytes, ceiling) } } fn transport(door: &Arc) -> ObjectMediaTransport { let address = ObjectAddress::open("https://cottondb.com").expect("an address"); ObjectMediaTransport::new(address, Arc::clone(door) as Arc, CREDENTIAL.to_string()) } /// A pending photo of `bytes` in the ledger, its file on disk; answers its key. fn queue_photo(replica: &crate::Replica, layout: &crate::Layout, mark: char, bytes: &[u8]) -> String { let sha256 = mark.to_string().repeat(64); let path = media_file_path(layout, WORKSPACE, &sha256, "heic"); std::fs::create_dir_all(path.parent().expect("the folder")).expect("the folder"); std::fs::write(&path, bytes).expect("the file"); let key = photo_key(file_id(), &sha256, "heic"); enqueue_media( &replica.driver, &MediaEnqueueInput { key: key.clone(), workspace_id: WORKSPACE.to_string(), sha256, content_type: "image/heic".to_string(), size_bytes: bytes.len() as i64, local_path: Some(path.to_string_lossy().to_string()), state: None, after: None, after_row_id: None, now: "2026-11-01T10:00:00.000Z".to_string(), tier: None, captured_here: true, }, ) .expect("a ledger row"); key } fn row(replica: &crate::Replica, key: &str) -> cotton_store::media_ledger::MediaRow { media_by_key(&replica.driver, key).expect("a read").expect("a row") } /// RULE: A file within one request's limit goes up in ONE `PUT /v1/media/`, with the row's content type and the file's length, under the object's bearer; the row is synced and its bytes stay on the device. #[test] fn a_file_goes_up_in_one_put_with_its_content_type() { let (_dir, layout, replica) = open_test_replica(); let key = queue_photo(&replica, &layout, 'a', b"an invented picture"); let door = Arc::new(MediaDoor::default()); assert_eq!(upload_one(&replica, &transport(&door), &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); let asked = door.asked(); assert_eq!(asked.len(), 1, "{asked:?}"); assert_eq!((asked[0].method.as_str(), asked[0].path.as_str()), ("PUT", format!("/v1/media/{key}").as_str())); assert_eq!(asked[0].content_type.as_deref(), Some("image/heic")); assert_eq!(door.holds(&key), Some((b"an invented picture".to_vec(), "image/heic".to_string()))); let after = row(&replica, &key); assert_eq!(after.state, "synced"); assert!(std::path::Path::new(after.local_path.as_deref().expect("a path")).is_file(), "the device keeps its copy"); } /// RULE: A key the object already holds at that size (the Mac imported the same picture) is a no-op: the object answers `stored: false`, keeps its one copy, and the row is synced. #[test] fn a_key_the_object_holds_is_taken_as_it_stands() { let (_dir, layout, replica) = open_test_replica(); let key = queue_photo(&replica, &layout, 'b', b"the same picture"); let door = Arc::new(MediaDoor::default()); door.held.lock().expect("the bucket").insert(key.clone(), (b"the same picture".to_vec(), "image/heic".to_string())); *door.left.lock().expect("the budget") = 0; let carried = transport(&door).upload(&row(&replica, &key), std::path::Path::new(row(&replica, &key).local_path.as_deref().expect("a path"))); assert_eq!(carried, Ok(Landed::Held)); assert_eq!(upload_one(&replica, &transport(&door), &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); assert_eq!(row(&replica, &key).state, "synced"); assert_eq!(door.held.lock().expect("the bucket").len(), 1, "one copy"); } /// RULE: A file over one part's weight goes in parts: `POST ?uploads {size, content_type}`, one `PUT ?upload=&part=` per slice (every part but the last the same size), and `POST ?upload= {parts}` — the object holds the file whole. #[test] fn a_large_file_goes_up_in_parts() { let (_dir, layout, replica) = open_test_replica(); let bytes: Vec = (0u8..=11).collect(); let key = queue_photo(&replica, &layout, 'c', &bytes); let door = Arc::new(MediaDoor::default()); let parts = transport(&door).with_parts_of(5); assert_eq!(upload_one(&replica, &parts, &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); let asked: Vec<(String, String, usize)> = door.asked().into_iter().map(|a| (a.method, a.path, a.length)).collect(); let at = format!("/v1/media/{key}"); assert_eq!(asked.len(), 5, "{asked:?}"); assert_eq!((asked[0].0.as_str(), asked[0].1.as_str()), ("POST", format!("{at}?uploads").as_str())); for (n, length) in [(1usize, 5usize), (2, 5), (3, 2)] { assert_eq!(asked[n], ("PUT".to_string(), format!("{at}?upload=upload-1&part={n}"), length)); } assert_eq!((asked[4].0.as_str(), asked[4].1.as_str()), ("POST", format!("{at}?upload=upload-1").as_str())); assert_eq!(door.holds(&key), Some((bytes, "image/heic".to_string()))); assert_eq!(row(&replica, &key).state, "synced"); } /// RULE: A file in parts whose key the object holds stops at the start: `stored: false`, no part sent. #[test] fn a_large_file_the_object_holds_sends_no_part() { let (_dir, layout, replica) = open_test_replica(); let bytes = vec![7u8; 12]; let key = queue_photo(&replica, &layout, 'd', &bytes); let door = Arc::new(MediaDoor::default()); door.held.lock().expect("the bucket").insert(key.clone(), (bytes, "image/heic".to_string())); assert_eq!(upload_one(&replica, &transport(&door).with_parts_of(5), &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); assert_eq!(door.asked().len(), 1, "only the start was asked"); } /// RULE: `object_full` is a refusal the object repeats: the row is failed with the object's own line, in one PUT or in parts. #[test] fn an_object_at_its_cap_fails_the_row_with_its_line() { let (_dir, layout, replica) = open_test_replica(); let whole = queue_photo(&replica, &layout, 'e', b"one picture too many"); let large = queue_photo(&replica, &layout, 'f', &[9u8; 12]); let door = Arc::new(MediaDoor::default()); *door.left.lock().expect("the budget") = 3; assert_eq!(upload_one(&replica, &transport(&door), &row(&replica, &whole), &FixedClock::default_start()), Uploaded::Failed); assert_eq!(upload_one(&replica, &transport(&door).with_parts_of(5), &row(&replica, &large), &FixedClock::default_start()), Uploaded::Failed); for key in [whole, large] { let after = row(&replica, &key); assert_eq!(after.state, "failed"); assert_eq!(after.last_error.as_deref(), Some(OBJECT_FULL)); } } /// RULE: No network is a backoff, never a failure: the row stays pending with its attempt counted, and once its backoff is past the same row goes up. #[test] fn a_dropped_line_backs_off_and_the_row_goes_up_later() { let (_dir, layout, replica) = open_test_replica(); let key = queue_photo(&replica, &layout, 'g', b"taken on a train"); let door = Arc::new(MediaDoor::default()); door.down.store(true, Ordering::SeqCst); let clock = FixedClock::default_start(); assert_eq!(upload_one(&replica, &transport(&door), &row(&replica, &key), &clock), Uploaded::Retry); let waiting = row(&replica, &key); assert_eq!((waiting.state.as_str(), waiting.attempts), ("pending", 1)); let due_at = waiting.next_attempt_at.clone().expect("backed off"); assert!(cotton_store::media_ledger::claim_due_media(&replica.driver, 10, &clock.now_iso()).expect("claims").is_empty(), "not due while backed off"); door.down.store(false, Ordering::SeqCst); let due = cotton_store::media_ledger::claim_due_media(&replica.driver, 10, &due_at).expect("claims"); assert_eq!(due.iter().map(|row| row.key.clone()).collect::>(), vec![key.clone()]); assert_eq!(upload_one(&replica, &transport(&door), &due[0], &clock), Uploaded::Uploaded); assert_eq!(row(&replica, &key).state, "synced"); } /// RULE: The hydrator's bytes come down by the same `GET /v1/media/` the phone's pictures do, written to the file it names. #[test] fn the_hydrator_reads_through_the_objects_get() { let dir = tempfile::tempdir().expect("a folder"); let door = Arc::new(MediaDoor::default()); let key = format!("{WORKSPACE}/photos/{}.heic", "h".repeat(64)); door.held.lock().expect("the bucket").insert(key.clone(), (b"from the object".to_vec(), "image/heic".to_string())); let dest = dir.path().join("landed"); transport(&door).fetch_object_to(WORKSPACE, &key, &dest).expect("the bytes came"); assert_eq!(std::fs::read(&dest).expect("the file"), b"from the object"); let asked = door.asked(); assert_eq!((asked[0].method.as_str(), asked[0].path.as_str()), ("GET", format!("/v1/media/{key}").as_str())); let missing = transport(&door).fetch_object_to(WORKSPACE, &format!("{WORKSPACE}/photos/none.heic"), &dest); assert_eq!(missing.expect_err("refused").status, 404); } /// RULE: A thumbnail uses the object's authenticated rendition GET and lands /// at the caller's path, through the same door as hydration and uploads. #[test] fn a_thumbnail_reads_the_objects_rendition() { let dir = tempfile::tempdir().expect("a folder"); let door = Arc::new(MediaDoor::default()); let key = format!("{WORKSPACE}/photos/{}.heic", "t".repeat(64)); door.held.lock().expect("the bucket").insert(key.clone(), (b"object rendition".to_vec(), "image/jpeg".to_string())); let dest = dir.path().join("thumb.jpg"); transport(&door).fetch_to(&key, Some(256), &dest).expect("the thumbnail came"); assert_eq!(std::fs::read(dest).expect("the thumbnail"), b"object rendition"); let asked = door.asked(); assert_eq!((asked[0].method.as_str(), asked[0].path.as_str()), ("GET", format!("/v1/media/{key}?width=256").as_str())); } /// RULE: A key's segments are percent-encoded and its `/` kept, as the Mac sends them and the Worker's `decodeURIComponent` reads them. #[test] fn a_media_path_keeps_the_key_shape() { use crate::transport::object::media_path; assert_eq!(media_path("db/photos/ab.heic"), "/v1/media/db/photos/ab.heic"); assert_eq!(media_path("db/a b/c+d"), "/v1/media/db/a%20b/c%2Bd"); } /// RULE: A film's stream is minted at the object under the phone's bearer, /// and what comes back is an address the player reads with none — the /// credential is in no part of it. #[test] fn a_films_stream_is_minted_under_the_bearer_and_carries_none() { let door = Arc::new(MediaDoor::default()); let key = format!("{WORKSPACE}/films/film-1/master.m3u8"); door.held.lock().expect("the bucket").insert(key.clone(), (b"#EXTM3U".to_vec(), "application/vnd.apple.mpegurl".to_string())); let grant = transport(&door).stream(&key).expect("the stream was minted"); assert_eq!(grant.url, format!("https://cottondb.com/v1/stream/tok-1/{key}")); assert_eq!(grant.expires_at, "2026-11-04T12:00:00.000Z"); assert!(!grant.url.contains(CREDENTIAL), "the address carries no bearer"); let asked = door.asked(); assert_eq!((asked[0].method.as_str(), asked[0].path.as_str()), ("POST", "/v1/media/stream")); assert_eq!(asked[0].content_type.as_deref(), Some("application/json")); let missing = transport(&door).stream(&format!("{WORKSPACE}/films/none/master.m3u8")); assert_eq!(missing.expect_err("refused").status, 404); } /// RULE: An answer that signs no address, or says no expiry, is refused as /// the object's fault — never a player pointed at nothing. #[test] fn a_stream_answer_with_no_address_is_refused() { let address = ObjectAddress::open("https://cottondb.com").expect("an address"); for body in [r#"{"expires_at":"2026-11-04T12:00:00Z"}"#, r#"{"url":"https://cottondb.com/v1/stream/t/k"}"#, r#"{"url":"file:///etc","expires_at":"x"}"#] { let exchange = ScriptedExchange::new([Reply::json(200, body)]); let refused = ObjectMediaTransport::new(address.clone(), exchange as Arc, CREDENTIAL.to_string()) .stream("db/films/f/master.m3u8") .expect_err("refused"); assert_eq!(refused.status, 502, "{body}"); } } /// RULE: The transport never prints its credential. #[test] fn the_credential_is_never_printed() { let door = Arc::new(MediaDoor::default()); assert!(!format!("{:?}", transport(&door)).contains(CREDENTIAL)); } // ── a person's own files, sealed going up (R6) ──────────── fn sealing_transport(door: &Arc, key: &str, held: bool) -> (ObjectMediaTransport, Arc) { let database = key.split('/').next().expect("a database").to_string(); let keys = crate::seal::HeldDataKeys::new(); if held { keys.hold(&database, &cotton_core::seal::DataKey::from_bytes([5; 32])); } let files = Arc::new(crate::media::sealed::PersonFiles::new(database, Arc::clone(&keys) as Arc)); (transport(door).sealing(files), keys) } /// RULE (R6): a person's picture goes up sealed: the object is handed f1 bytes typed as a sealed file, never the /// picture, and the same file comes back down as the picture through the device's own key. #[test] fn a_persons_picture_goes_up_sealed_and_comes_down_opened() { let (dir, layout, replica) = open_test_replica(); let picture = b"an invented picture, its bytes never seen by the object".to_vec(); let key = queue_photo(&replica, &layout, 'e', &picture); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, true); assert_eq!(upload_one(&replica, &sealing, &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); let (stored, content_type) = door.holds(&key).expect("stored"); assert_eq!(content_type, crate::media::sealed::SEALED_FILE_TYPE); assert_eq!(&stored[..4], b"CTF1"); assert_eq!(stored.len() as u64, cotton_core::seal::file::sealed_len(picture.len() as u64)); assert!(!stored.windows(16).any(|w| picture.windows(16).any(|p| p == w)), "no run of the picture in what the object holds"); let dest = dir.path().join("down.heic"); sealing.fetch_opened_to(&key, &dest).expect("opened"); assert_eq!(std::fs::read(&dest).expect("the file"), picture); } /// RULE (R6): a large file goes up sealed in parts, each part a slice of the sealed stream, and the object puts /// together exactly the sealed file; sealed again from the store (a resumed upload) it is the same bytes. #[test] fn a_large_persons_file_goes_up_sealed_in_parts() { let (_dir, layout, replica) = open_test_replica(); let film: Vec = (0..(2 * cotton_core::seal::file::PART + 99)).map(|i| (i % 233) as u8).collect(); let key = queue_photo(&replica, &layout, 'f', &film); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, true); let sealing = sealing.with_parts_of(50_000); assert_eq!(upload_one(&replica, &sealing, &row(&replica, &key), &FixedClock::default_start()), Uploaded::Uploaded); let sealed_len = cotton_core::seal::file::sealed_len(film.len() as u64) as usize; let parts: Vec = door.asked().into_iter().filter(|a| a.method == "PUT").map(|a| a.length).collect(); assert_eq!(parts.iter().sum::(), sealed_len, "{parts:?}"); assert!(parts.len() >= 3, "{parts:?}"); let (stored, content_type) = door.holds(&key).expect("stored"); assert_eq!(content_type, crate::media::sealed::SEALED_FILE_TYPE); assert_eq!(stored.len(), sealed_len); let again = { let (door, _) = (Arc::new(MediaDoor::default()), ()); let (sealing, _keys) = sealing_transport(&door, &key, true); let path = row(&replica, &key).local_path.expect("a path"); sealing.upload(&row(&replica, &key), std::path::Path::new(&path)).expect("up"); door.holds(&key).expect("stored").0 }; assert_eq!(again, stored, "sealed again, the same bytes: an upload resumes at any part"); } /// RULE (R6): with no data key on this device a person's file waits (a backoff, never failed) and nothing goes up: /// never open, never under a key the device could not open again. #[test] fn with_no_data_key_a_persons_file_waits_and_nothing_goes_up() { let (_dir, layout, replica) = open_test_replica(); let key = queue_photo(&replica, &layout, 'g', b"a picture taken before the key arrived"); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, false); assert_eq!(upload_one(&replica, &sealing, &row(&replica, &key), &FixedClock::default_start()), Uploaded::Retry); assert!(door.asked().is_empty(), "{:?}", door.asked()); assert_eq!(row(&replica, &key).state, "pending"); } /// RULE (R6): clear bytes in place of a sealed file are refused unless they are the very bytes the key's digest /// names (a file stored before R6), and a sealed file opened with another person's key does not open. #[test] fn clear_bytes_open_only_when_they_are_the_ones_the_key_names() { let (dir, _layout, _replica) = open_test_replica(); let door = Arc::new(MediaDoor::default()); let true_bytes = b"a picture stored before R6".to_vec(); let sha = hex::encode(::digest(&true_bytes)); let named = photo_key(file_id(), &sha, "jpg"); let other = photo_key(file_id(), &"9".repeat(64), "jpg"); door.held.lock().unwrap().insert(named.clone(), (true_bytes.clone(), "image/jpeg".into())); door.held.lock().unwrap().insert(other.clone(), (b"bytes the object made up".to_vec(), "image/jpeg".into())); let (sealing, _keys) = sealing_transport(&door, &named, true); let dest = dir.path().join("old.jpg"); sealing.fetch_opened_to(&named, &dest).expect("the old file is the one its name says"); assert_eq!(std::fs::read(&dest).unwrap(), true_bytes); let refused = sealing.fetch_opened_to(&other, &dir.path().join("forged.jpg")).unwrap_err(); assert!(refused.message.contains("not the bytes its name says"), "{refused:?}"); assert!(!dir.path().join("forged.jpg").exists()); // Sealed under one person's key, fetched by another's: nothing opens. let mut sealed = Vec::new(); let fk = crate::media::sealed::PersonFiles::new(other.split('/').next().unwrap(), { let keys = crate::seal::HeldDataKeys::new(); keys.hold(other.split('/').next().unwrap(), &cotton_core::seal::DataKey::from_bytes([6; 32])); keys as Arc }) .file_key(&other) .unwrap(); cotton_core::seal::file::seal_file(&fk, &other, &mut &b"someone else's"[..], &mut sealed).unwrap(); door.held.lock().unwrap().insert(other.clone(), (sealed, crate::media::sealed::SEALED_FILE_TYPE.into())); assert!(sealing.fetch_opened_to(&other, &dir.path().join("theirs.jpg")).is_err()); assert!(!dir.path().join("theirs.jpg").exists()); } /// RULE (R6): a person's sealed file read where the object keeps it opens any plaintext range from `Range` reads of /// the parts it covers, never the whole file; one the object holds not sealed is refused. #[test] fn a_sealed_file_at_the_object_opens_any_range_by_ranged_reads() { let film: Vec = (0..(40 * cotton_core::seal::file::PART + 77)).map(|i| (i % 229) as u8).collect(); let db = photo_key(file_id(), &"0".repeat(64), "jpg").split('/').next().unwrap().to_string(); let key = format!("{db}/films/film-r/whole.mp4"); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, true); let fk = sealing.files.as_ref().unwrap().file_key(&key).unwrap(); let mut sealed = Vec::new(); cotton_core::seal::file::SealingReader::new(&fk, &key, std::io::Cursor::new(film.clone()), film.len() as u64).read_to_end(&mut sealed).unwrap(); door.held.lock().unwrap().insert(key.clone(), (sealed.clone(), crate::media::sealed::SEALED_FILE_TYPE.into())); let sealing = Arc::new(sealing); let mut reader = sealing.open_remote(&key).expect("opened where it lies"); use std::io::{Seek as _, SeekFrom}; let at = 33 * cotton_core::seal::file::PART + 5; reader.seek(SeekFrom::Start(at as u64)).unwrap(); let mut got = vec![0u8; 1000]; reader.read_exact(&mut got).unwrap(); assert_eq!(got, film[at..at + 1000]); let fetched: usize = door.asked().iter().filter(|a| a.method == "GET").count(); assert!(fetched <= 3, "a seek reads its own window (and the one after, ahead), not the film: {fetched} reads"); // PLAYER START: the player's next requests open it again, and each window read is fetched ahead of the next. // However often it is opened and read, each of its three windows is fetched once. for _ in 0..3 { let mut again = sealing.open_remote(&key).expect("opened again"); let mut first = vec![0u8; 4096]; again.read_exact(&mut first).unwrap(); assert_eq!(first, film[..4096]); again.seek(SeekFrom::Start(at as u64)).unwrap(); again.read_exact(&mut got).unwrap(); assert_eq!(got, film[at..at + 1000]); } let mut whole = Vec::new(); sealing.open_remote(&key).unwrap().read_to_end(&mut whole).unwrap(); assert!(whole == film, "read through, the film is whole"); std::thread::sleep(std::time::Duration::from_millis(200)); let windows = (sealed.len() as u64).div_ceil(crate::media::remote::WINDOW) as usize; let fetched: usize = door.asked().iter().filter(|a| a.method == "GET").count(); assert!(fetched <= windows, "each window fetched once, held or waited for after: {fetched} reads of {windows} windows"); let clear = format!("{db}/films/film-c/whole.mp4"); door.held.lock().unwrap().insert(clear.clone(), (film[..5000].to_vec(), "video/mp4".into())); assert!(sealing.open_remote(&clear).is_err(), "clear bytes are never played in place of a sealed film"); } /// A door that holds every request until it is opened, then answers each with `reply` (RELAY 2's tests: a fetch on /// its way while another thread asks the same window, and fetches ahead held in flight). struct Gate { open: Mutex, opened: std::sync::Condvar, reply: fn() -> Reply, asked: std::sync::atomic::AtomicUsize, } impl std::fmt::Debug for Gate { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("Gate") } } impl Gate { fn new(reply: fn() -> Reply) -> Arc { Arc::new(Gate { open: Mutex::new(false), opened: std::sync::Condvar::new(), reply, asked: std::sync::atomic::AtomicUsize::new(0) }) } fn let_through(&self) { *self.open.lock().unwrap() = true; self.opened.notify_all(); } } impl Exchange for Gate { fn send(&self, origin: &Origin, request: &Http1Request<'_>, ceiling: Duration) -> Result, String> { self.asked.fetch_add(1, Ordering::SeqCst); let mut open = self.open.lock().unwrap(); while !*open { open = self.opened.wait(open).unwrap(); } drop(open); ScriptedExchange::new([(self.reply)()]).send(origin, request, ceiling) } fn send_stream(&self, origin: &Origin, request: &Http1Request<'_>, _body: &mut dyn Read, _length: u64, ceiling: Duration) -> Result, String> { self.send(origin, request, ceiling) } } fn gated(gate: &Arc) -> Arc { let address = ObjectAddress::open("https://cottondb.com").expect("an address"); Arc::new(ObjectMediaTransport::new(address, Arc::clone(gate) as Arc, CREDENTIAL.to_string())) } fn wait_until(what: &str, done: impl Fn() -> bool) { let started = std::time::Instant::now(); while !done() { assert!(started.elapsed() < Duration::from_secs(10), "{what}: never"); std::thread::sleep(Duration::from_millis(5)); } } /// RULE (RELAY 2, review B of a8580dbc38): a thread that waits on a window another is fetching is told the object's /// own refusal, its status and code, never a 502 of its own; and a refusal is not kept: the next ask asks again. #[test] fn a_window_waited_for_is_refused_with_the_objects_own_refusal() { let gate = Gate::new(|| Reply::json(403, r#"{"code":"owner_only","message":"the media are the owner's"}"#)); let transport = gated(&gate); let first = { let transport = Arc::clone(&transport); std::thread::spawn(move || transport.window("db/films/f/whole.mp4", 0, 4096)) }; wait_until("the first fetch on its way", || gate.asked.load(Ordering::SeqCst) == 1); let second = { let transport = Arc::clone(&transport); std::thread::spawn(move || transport.window("db/films/f/whole.mp4", 0, 4096)) }; std::thread::sleep(Duration::from_millis(50)); gate.let_through(); let (first, second) = (first.join().unwrap().unwrap_err(), second.join().unwrap().unwrap_err()); assert_eq!(gate.asked.load(Ordering::SeqCst), 1, "the second waited, it did not ask"); assert_eq!((first.status, first.code.as_deref()), (403, Some("owner_only"))); assert_eq!((second.status, second.code.as_deref()), (403, Some("owner_only")), "the waiter is told what the object said"); assert_eq!(transport.windows_held(), 0, "a refusal is not kept"); } /// RULE (RELAY 2): a window shorter than the file holds from its start is not kept, and a read past what came is /// refused as short, never a panic. #[test] fn a_short_window_is_not_kept_and_never_read_past() { use std::io::{Seek as _, SeekFrom}; // The object says the file is 1 MB and sends ten bytes of it. let gate = Gate::new(|| Reply::new(206, b"cotton-f1!".to_vec()).with_header("content-range", "bytes 0-9/1000000")); gate.let_through(); let transport = gated(&gate); let (total, bytes) = transport.window("db/films/f/whole.mp4", 0, 4096).unwrap(); assert_eq!((total, bytes.len()), (1_000_000, 10)); assert_eq!(transport.windows_held(), 0, "a short window is not kept"); let mut remote = crate::media::remote::RemoteSealed::open(Arc::clone(&transport), "db/films/f/whole.mp4").unwrap(); let mut got = [0u8; 4]; remote.read_exact(&mut got).unwrap(); assert_eq!(&got, b"cott"); remote.seek(SeekFrom::Start(100)).unwrap(); let refused = remote.read(&mut got).unwrap_err(); assert_eq!(refused.kind(), std::io::ErrorKind::UnexpectedEof, "{refused}"); } /// RULE (RELAY 2): at most AHEAD fetches ahead are on their way at once; one not yet begun when the read ahead is /// cancelled asks nothing; a release lets every window go. #[test] fn fetches_ahead_are_bounded_cancelled_and_released() { let gate = Gate::new(|| Reply::new(206, vec![7u8; 64]).with_header("content-range", "bytes 0-63/64")); let transport = gated(&gate); for n in 0..10u64 { transport.fetch_ahead("db/films/f/whole.mp4", n * 1_000_000, 64); } wait_until("the fetches ahead on their way", || gate.asked.load(Ordering::SeqCst) == crate::media::remote::AHEAD); std::thread::sleep(Duration::from_millis(50)); assert_eq!(transport.ahead_in_flight(), crate::media::remote::AHEAD, "bounded"); assert_eq!(gate.asked.load(Ordering::SeqCst), crate::media::remote::AHEAD, "the rest were never begun"); transport.cancel_ahead(); gate.let_through(); wait_until("the fetches ahead done", || transport.ahead_in_flight() == 0); // Begun before the cancel: they finished; a fetch ahead asked after it asks again. transport.fetch_ahead("db/films/f/whole.mp4", 50_000_000, 64); wait_until("the new fetch ahead done", || transport.ahead_in_flight() == 0); assert_eq!(gate.asked.load(Ordering::SeqCst), crate::media::remote::AHEAD + 1); assert!(transport.windows_held() > 0); transport.release(); assert_eq!(transport.windows_held(), 0, "a release lets every window go"); } /// RULE (RELAY 2): a seek away from where the film is read cancels the read ahead there; one within reach keeps it. #[test] fn a_seek_away_cancels_the_read_ahead() { use std::io::{Seek as _, SeekFrom}; let film: Vec = (0..(80 * cotton_core::seal::file::PART + 3)).map(|i| (i % 233) as u8).collect(); let db = photo_key(file_id(), &"0".repeat(64), "jpg").split('/').next().unwrap().to_string(); let key = format!("{db}/films/film-s/whole.mp4"); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, true); let fk = sealing.files.as_ref().unwrap().file_key(&key).unwrap(); let mut sealed = Vec::new(); cotton_core::seal::file::SealingReader::new(&fk, &key, std::io::Cursor::new(film.clone()), film.len() as u64).read_to_end(&mut sealed).unwrap(); door.held.lock().unwrap().insert(key.clone(), (sealed, crate::media::sealed::SEALED_FILE_TYPE.into())); let sealing = Arc::new(sealing); let mut remote = crate::media::remote::RemoteSealed::open(Arc::clone(&sealing), &key).unwrap(); assert_eq!(sealing.ahead_in_flight(), 0, "an open alone reads nothing ahead"); let generation = sealing.ahead_generation.load(Ordering::SeqCst); let mut got = [0u8; 16]; remote.read_exact(&mut got).unwrap(); remote.seek(SeekFrom::Start(crate::media::remote::WINDOW + 10)).unwrap(); assert_eq!(sealing.ahead_generation.load(Ordering::SeqCst), generation, "within reach: kept"); remote.seek(SeekFrom::Start(sealed_len_far(&remote))).unwrap(); assert!(sealing.ahead_generation.load(Ordering::SeqCst) > generation, "far away: cancelled"); wait_until("the read ahead done", || sealing.ahead_in_flight() == 0); } fn sealed_len_far(remote: &crate::media::remote::RemoteSealed) -> u64 { remote.len() - 10 } /// RULE: A file going up says how far it has gone, in the bytes on the wire (sealed), never backwards, ending at the whole: what a screen shows as "uploading, x of y". #[test] fn a_file_going_up_in_parts_says_how_far_it_has_gone() { let (_dir, layout, replica) = open_test_replica(); let film: Vec = (0..(3 * cotton_core::seal::file::PART + 7)).map(|i| (i % 211) as u8).collect(); let key = queue_photo(&replica, &layout, 'g', &film); let door = Arc::new(MediaDoor::default()); let (sealing, _keys) = sealing_transport(&door, &key, true); let sealing = sealing.with_parts_of(60_000); let told: Arc>> = Arc::default(); let progress: crate::media::drain::Progress = { let told = Arc::clone(&told); Arc::new(move |sent, total| told.lock().expect("the log").push((sent, total))) }; let path = row(&replica, &key).local_path.expect("a path"); sealing.upload_watched(&row(&replica, &key), std::path::Path::new(&path), progress).expect("up"); let sealed_len = cotton_core::seal::file::sealed_len(film.len() as u64); let told = told.lock().expect("the log").clone(); assert_eq!(told.first(), Some(&(0, sealed_len)), "begins at nothing of the sealed whole"); assert_eq!(told.last(), Some(&(sealed_len, sealed_len)), "ends at the whole"); assert!(told.windows(2).all(|pair| pair[0].0 <= pair[1].0), "never backwards: {told:?}"); assert!(told.len() > 2, "told along the way, not only at the ends: {told:?}"); }