//! The scripted [`Exchange`] every transport suite drives, and what it saw. //! //! An HTTP-level double rather than a `ServerFetch` one, deliberately: the //! ladder this crate has to prove — the moved follow, the clock correction, //! the terminal notes, the nonce rule — all happens BELOW `ServerFetch`, and a //! double above it would test the shape of a struct. This one sees the real //! signed headers and the real body bytes, so a suite asserts what actually //! went on the wire. use std::collections::VecDeque; use std::io::Read; use std::sync::{Arc, Mutex}; use std::time::Duration; use super::wire::Origin; use super::{Answer, Exchange}; /// One answer the script hands back. #[derive(Debug, Clone)] pub struct Reply { pub status: u16, pub headers: Vec<(String, String)>, pub body: Vec, /// How long the server took to answer, for a suite that cares. /// /// Zero for every reply that does not say otherwise, which is what a /// scripted server is: instant. It matters to exactly one caller so far — /// the join's LONG POLL, where "the server held the request for its full /// wait" and "the server answered at once" are different behaviours and the /// client does different things. See [`Reply::after_ms`]. pub took_ms: u64, /// The connection drops after this many bytes of the body: a read past /// them is an error, never a quiet end. `None` — every reply that does not /// say otherwise — delivers the whole body. pub cut_after: Option, } impl Reply { pub fn new(status: u16, body: impl Into>) -> Reply { Reply { status, headers: Vec::new(), body: body.into(), took_ms: 0, cut_after: None, } } pub fn json(status: u16, body: &str) -> Reply { Reply::new(status, body.as_bytes().to_vec()).with_header("content-type", "application/json") } pub fn ok(body: &str) -> Reply { Reply::json(200, body) } /// The server took this long to answer it. /// /// Only honoured by an exchange built with [`ScriptedExchange::on_clock`]: /// the time has to move SOMEWHERE, and a scripted server has no clock of /// its own. #[must_use] pub fn after_ms(mut self, took_ms: u64) -> Reply { self.took_ms = took_ms; self } /// The snapshot route's `200` for a ready copy: `plain` gzipped, with the /// headers the server sends — the gzip's length, the database's size and /// the copy's id. pub fn snapshot(plain: &[u8], copy: &str) -> Reply { let body = gzip(plain); let length = body.len().to_string(); let sha = sha256_hex(&body); Reply::new(200, body) .with_header("content-length", &length) .with_header("content-encoding", "gzip") .with_header("x-cotton-snapshot-bytes", &plain.len().to_string()) .with_header("x-cotton-snapshot-sha256", &sha) .with_header("x-cotton-snapshot-copy", copy) .with_header("accept-ranges", "bytes") } /// The snapshot route's `206`: the gzip of `plain` from byte `from`. pub fn snapshot_from(plain: &[u8], copy: &str, from: usize) -> Reply { let whole = gzip(plain); let total = whole.len(); let sha = sha256_hex(&whole); let body = whole[from..].to_vec(); let length = body.len().to_string(); Reply::new(206, body) .with_header("content-length", &length) .with_header("content-encoding", "gzip") .with_header("content-range", &format!("bytes {from}-{}/{total}", total - 1)) .with_header("x-cotton-snapshot-bytes", &plain.len().to_string()) .with_header("x-cotton-snapshot-sha256", &sha) .with_header("x-cotton-snapshot-copy", copy) } /// The snapshot route's `202`: the copy is still being prepared. pub fn preparing(copy: &str, stage: &str, done: u32) -> Reply { Reply::json( 202, &format!( r#"{{"copy":"{copy}","stage":"{stage}","done":{done},"of":3,"bytes":null,"retryAfterMs":2000}}"# ), ) } /// The connection drops after `bytes` of the body ([`Reply::cut_after`]). #[must_use] pub fn dropped_after(mut self, bytes: usize) -> Reply { self.cut_after = Some(bytes); self } #[must_use] pub fn with_header(mut self, name: &str, value: &str) -> Reply { self.headers.push((name.to_string(), value.to_string())); self } } /// What one request looked like on the wire. #[derive(Debug, Clone)] pub struct Seen { pub origin: String, pub method: String, pub path: String, pub headers: Vec<(String, String)>, pub body: Vec, /// What the transport gave this request to finish in. pub ceiling: Duration, } impl Seen { pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|(key, _)| key.eq_ignore_ascii_case(name)) .map(|(_, value)| value.as_str()) } } /// A scripted server, and the record of what it was asked. #[derive(Debug, Default)] pub struct ScriptedExchange { replies: Mutex>, seen: Mutex>, /// The clock a [`Reply::after_ms`] moves. `None` — the ordinary case — /// means every answer is instant, which is what a script is. clock: Option, } impl ScriptedExchange { pub fn new(replies: impl IntoIterator) -> Arc { Arc::new(ScriptedExchange { replies: Mutex::new(replies.into_iter().collect()), seen: Mutex::new(Vec::new()), clock: None, }) } /// The same, over a clock a [`Reply::after_ms`] may move forward. /// /// The clock is the SUITE's — the same one the transport signs with and the /// pause advances — so a reply that took twenty-five seconds is twenty-five /// seconds to everything that asks the time, which is how a long poll is /// told apart from an instant one. pub fn on_clock( replies: impl IntoIterator, clock: &crate::seams::FixedClock, ) -> Arc { Arc::new(ScriptedExchange { replies: Mutex::new(replies.into_iter().collect()), seen: Mutex::new(Vec::new()), clock: Some(clock.clone()), }) } pub fn seen(&self) -> Vec { self.seen .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } pub fn calls(&self) -> usize { self.seen().len() } /// The one request this suite asked about — loud when there was not /// exactly the number expected, so a test never reads index 0 of an empty /// record and passes. pub fn only(&self) -> Seen { let seen = self.seen(); assert_eq!(seen.len(), 1, "expected one request, saw {}", seen.len()); seen.into_iter().next().expect("one request") } pub fn nth(&self, index: usize) -> Seen { let seen = self.seen(); assert!( seen.len() > index, "asked for request {index} and only {} were made", seen.len() ); seen[index].clone() } } impl Exchange for ScriptedExchange { fn send( &self, origin: &Origin, request: &super::http1::Http1Request<'_>, ceiling: Duration, ) -> Result, String> { self.seen .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .push(Seen { origin: origin.text.clone(), method: request.method.to_string(), path: request.path.to_string(), headers: request.headers.clone(), body: request.body.map(<[u8]>::to_vec).unwrap_or_default(), ceiling, }); let reply = self .replies .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .pop_front() // Loud rather than an implicit 200: a script that ran out is a // test asserting against an answer nobody wrote. .ok_or_else(|| "the script ran out of answers".to_string())?; if reply.took_ms > 0 { if let Some(clock) = &self.clock { clock.advance(chrono::Duration::milliseconds(reply.took_ms as i64)); } } Ok(Box::new(Canned { status: reply.status, headers: reply.headers, body: std::io::Cursor::new(reply.body), cut_after: reply.cut_after, })) } /// A script reads the whole body, so the record holds what was sent. fn send_stream( &self, origin: &Origin, request: &super::http1::Http1Request<'_>, body: &mut dyn Read, length: u64, ceiling: Duration, ) -> Result, String> { let mut bytes = Vec::new(); body.take(length).read_to_end(&mut bytes).map_err(|error| error.to_string())?; let whole = super::http1::Http1Request { body: Some(&bytes), headers: request.headers.clone(), ..*request }; self.send(origin, &whole, ceiling) } } struct Canned { status: u16, headers: Vec<(String, String)>, body: std::io::Cursor>, cut_after: Option, } impl Read for Canned { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let Some(cut) = self.cut_after else { return self.body.read(buf); }; let at = usize::try_from(self.body.position()).unwrap_or(usize::MAX); if at >= cut { return Err(std::io::Error::new( std::io::ErrorKind::ConnectionReset, "the scripted connection dropped", )); } let room = (cut - at).min(buf.len()); self.body.read(&mut buf[..room]) } } impl Answer for Canned { fn status(&self) -> u16 { self.status } fn header(&self, name: &str) -> Option { self.headers .iter() .find(|(key, _)| key.eq_ignore_ascii_case(name)) .map(|(_, value)| value.clone()) } fn content_length(&self) -> Option { self.header("content-length") .and_then(|value| value.trim().parse().ok()) } fn set_read_timeout(&mut self, _timeout: Duration) -> std::io::Result<()> { Ok(()) } } /// An address a test moves under the transport's feet. #[derive(Debug)] pub struct RememberedAddress { base: Mutex>, /// Mine's id, for a suite about which database a request is filed under. mine: Option, /// The database this device acts on — `None` unless a test named one, /// and then requests go out naming none. database: Mutex>, } impl RememberedAddress { pub fn at(base: &str) -> Arc { Arc::new(RememberedAddress { base: Mutex::new(Some(base.to_string())), mine: None, database: Mutex::new(None), }) } /// An address that also knows Mine's id. pub fn at_with_mine(base: &str, mine: &str) -> Arc { Arc::new(RememberedAddress { base: Mutex::new(Some(base.to_string())), mine: Some(mine.to_string()), database: Mutex::new(None), }) } /// An address AND the database a device there acts on — Mine, named on /// every request it signs. What a test against a real server needs, since /// every signed request names one. pub fn at_in(base: &str, database: &str) -> Arc { Arc::new(RememberedAddress { base: Mutex::new(Some(base.to_string())), mine: Some(database.to_string()), database: Mutex::new(Some(database.to_string())), }) } pub fn none() -> Arc { Arc::new(RememberedAddress { base: Mutex::new(None), mine: None, database: Mutex::new(None), }) } pub fn get(&self) -> Option { self.base .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } } impl super::ServerAddress for RememberedAddress { fn base_url(&self) -> Option { self.get() } fn mine_id(&self) -> Option { self.mine.clone() } fn database(&self) -> Option { self.database .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) .clone() } } // ─── a real socket that never finishes ───────────────────────────────────── /// A listener that reads what the client says first, answers `at_once` in /// one write, and then `trickled` and a minute more of filler ONE BYTE every /// 200 ms — the shape a per-syscall timeout never catches, because every read /// returns something. The port is the OS's. pub fn trickling(at_once: &'static [u8], trickled: &'static [u8]) -> u16 { let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("the OS hands out a port"); let port = listener.local_addr().expect("an address").port(); std::thread::spawn(move || { use std::io::Write as _; let Ok((mut socket, _)) = listener.accept() else { return; }; let mut scratch = [0u8; 4096]; let _ = socket.read(&mut scratch); if socket.write_all(at_once).is_err() { return; } for byte in trickled.iter().chain(std::iter::repeat_n(&b'x', 300)) { if socket.write_all(&[*byte]).is_err() { return; } std::thread::sleep(Duration::from_millis(200)); } }); port } /// `run` on its own thread, waited for no longer than `within` — so a /// test of a deadline that does not hold FAILS rather than hanging. pub fn finishes( within: Duration, run: impl FnOnce() -> T + Send + 'static, ) -> T { let (done, finished) = std::sync::mpsc::channel(); std::thread::spawn(move || { let _ = done.send(run()); }); finished .recv_timeout(within) .unwrap_or_else(|_| panic!("still waiting after {within:?} — the deadline did not hold")) } /// A listener that answers `at_once` and then says NOTHING, holding the /// socket open for a minute — a read on it blocks for whatever window the /// socket allows. pub fn silent_after(at_once: &'static [u8]) -> u16 { let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("the OS hands out a port"); let port = listener.local_addr().expect("an address").port(); std::thread::spawn(move || { use std::io::Write as _; let Ok((mut socket, _)) = listener.accept() else { return; }; let mut scratch = [0u8; 4096]; let _ = socket.read(&mut scratch); let _ = socket.write_all(at_once); std::thread::sleep(Duration::from_secs(60)); }); port } /// `plain`, gzipped the way the server keeps a copy. /// The sha256 of `bytes`, lowercase hex — what the snapshot route names the /// whole gzip by. pub fn sha256_hex(bytes: &[u8]) -> String { use sha2::Digest; hex::encode(sha2::Sha256::digest(bytes)) } pub fn gzip(plain: &[u8]) -> Vec { use std::io::Write as _; let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); let _ = encoder.write_all(plain); encoder.finish().unwrap_or_default() }