//! The bytes: the phone's one dial. //! //! Terminal output is never a row (Cotton note "The Code tool — why a Mac holds the sessions"). It is a //! live stream and a file on the Mac, and this module is how it reaches Swift: //! as `terminal.data` and `terminal.state` events on the FFI bus, with //! `terminal.write` / `terminal.resize` / `terminal.detach` going back. //! //! **THE PHONE OPENS NO SOCKET OF ITS OWN.** [`TerminalTransport::Server`] //! is `/v1/sessions/attach` over the same [`crate::transport::wire::Wire`] //! every other request takes, with blocking `tungstenite` on top. Binary //! frames are the bytes and //! are not re-encoded; the three text frames are the only JSON. //! //! **Coalesced to thirty events a second per session.** A compiling agent //! writes thousands of small chunks; one FFI event each would be thirty //! thousand JSON envelopes a second crossing a boundary to be appended to a //! terminal that redraws sixty times a second at best. So a pump gathers what //! arrived and emits at most every [`TERMINAL_COALESCE_MS`], which loses //! nothing — the bytes are concatenated, in order — and costs at most that //! much latency. //! //! **A viewer that falls behind is told, and never blocks the terminal.** The //! helper drops a slow subscriber by name and the server's attach route holds //! a bounded queue; either way the stream says `catchingUp` and the view draws //! that rather than freezing an agent because a phone is on a train. use std::io::Read; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use base64::Engine; use serde_json::{json, Value}; /// The route a phone attaches through. pub const TERMINAL_PATH: &str = "/v1/sessions/attach"; /// The most `terminal.data` events one session may emit in a second. pub const TERMINAL_MAX_EVENTS_PER_SECOND: u32 = 30; /// How long a pump gathers bytes before emitting. /// /// Derived from the ceiling above rather than written twice, so the two cannot /// disagree. pub const TERMINAL_COALESCE_MS: i64 = 1_000 / TERMINAL_MAX_EVENTS_PER_SECOND as i64; /// How long a dial may take before it is a failure. const DIAL_CEILING_MS: u64 = 15_000; /// How long one read waits before answering "nothing yet". const READ_WAIT_MS: i64 = 200; /// What a terminal view draws besides the bytes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TerminalState { /// Bytes are flowing. Attached, /// The viewer fell behind and output was dropped. Nothing is broken and /// nothing is blocked; what is on screen is behind what the agent wrote. CatchingUp, /// There is no stream any more. Closed, } impl TerminalState { pub fn as_str(self) -> &'static str { match self { TerminalState::Attached => "attached", TerminalState::CatchingUp => "catchingUp", TerminalState::Closed => "closed", } } } /// One attached terminal, whichever end it came from. pub trait TerminalStream: Send { /// The next chunk. `Ok(None)` is "nothing yet" and is never a dead stream. fn read(&mut self, wait_ms: i64) -> Result>, String>; fn write(&mut self, bytes: &[u8]) -> Result<(), String>; fn resize(&mut self, cols: u16, rows: u16) -> Result<(), String>; /// The viewer fell behind, as the far end reported it. fn behind(&self) -> bool { false } fn close(&mut self); } /// Where a `terminal.data` / `terminal.state` event goes. /// /// A seam because the event bus is `cotton-ffi`'s and this crate may not reach /// it — the same line `SyncLoopInput::on_tables` draws. pub trait TerminalSink: Send + Sync + std::fmt::Debug { fn data(&self, session_id: &str, bytes: &[u8]); fn state(&self, session_id: &str, state: TerminalState); } /// How a session's terminal is opened. #[derive(Clone)] pub enum TerminalTransport { /// A server over the relay — the phone's, and a Mac that is a client of /// another Mac. /// /// The closure mints `(url, headers)` for THIS attach rather than holding /// a pair, because a device signature carries a timestamp the server /// bounds and headers minted for the first attempt are stale by the /// fourth. #[allow(clippy::type_complexity)] Server( Arc Result<(String, Vec<(String, String)>), String> + Send + Sync>, ), } impl std::fmt::Debug for TerminalTransport { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TerminalTransport::Server(_) => f.write_str("TerminalTransport::Server"), } } } impl TerminalTransport { /// Open a stream on one session. pub fn attach( &self, session_id: &str, cols: u16, rows: u16, ) -> Result, String> { match self { TerminalTransport::Server(credential) => { let (url, headers) = credential(session_id)?; Ok(Box::new(ServerTerminal::dial(&url, &headers, cols, rows)?)) } } } } // ─── the phone's dial ─────────────────────────────────────────────────────── struct ServerTerminal { inner: tungstenite::WebSocket, behind: bool, } impl ServerTerminal { fn dial( url: &str, headers: &[(String, String)], cols: u16, rows: u16, ) -> Result { // Against the HTTP origin, not the `wss://` one: `wss` is a URL scheme // and what a TCP connection needs is a host, a port and whether to // wrap it. let origin = crate::transport::wire::Origin::parse( &crate::transport::address::http_origin_of(url)?, )?; let wire = crate::transport::wire::dial(&origin, Duration::from_millis(DIAL_CEILING_MS))?; let mut request = tungstenite::handshake::client::Request::builder() .uri(url) .method("GET"); for (name, value) in headers { request = request.header(name.as_str(), value.as_str()); } let request = request .header("Host", origin.authority()) .header("Connection", "Upgrade") .header("Upgrade", "websocket") .header("Sec-WebSocket-Version", "13") .header( "Sec-WebSocket-Key", tungstenite::handshake::client::generate_key(), ) .body(()) .map_err(|error| format!("the upgrade could not be built ({error})"))?; let (inner, _answer) = tungstenite::client::client(request, wire) .map_err(|error| format!("{url} did not upgrade ({error})"))?; let mut socket = ServerTerminal { inner, behind: false, }; // `hello` is the first thing on the wire and it carries the offset we // are resuming from — zero, because a fresh attach wants the tail the // server decides on rather than a point this viewer invented. socket.say(&json!({ "t": "hello", "offset": 0 }))?; socket.resize(cols, rows)?; Ok(socket) } fn say(&mut self, frame: &Value) -> Result<(), String> { self.inner .send(tungstenite::Message::Text(frame.to_string().into())) .map_err(|error| error.to_string()) } } impl TerminalStream for ServerTerminal { fn read(&mut self, wait_ms: i64) -> Result>, String> { let _ = self .inner .get_ref() .set_read_timeout(Duration::from_millis(wait_ms.max(1) as u64)); match self.inner.read() { // THE BYTES, not re-encoded once on this hop. Ok(tungstenite::Message::Binary(bytes)) => Ok(Some(bytes.to_vec())), Ok(tungstenite::Message::Text(text)) => { let frame: Value = serde_json::from_str(&text).unwrap_or(Value::Null); match frame.get("t").and_then(Value::as_str) { Some("state") => { self.behind = frame.get("state").and_then(Value::as_str) == Some("catchingUp"); Ok(None) } Some("error") => Err(frame .get("message") .and_then(Value::as_str) .unwrap_or("the server refused the attach and said nothing") .to_string()), // `attached`, and anything a later server grows. DROPPED, // never fatal — a server that adds a frame must not take // every phone's terminal down. _ => Ok(None), } } Ok(_) => Ok(None), Err(tungstenite::Error::Io(error)) if matches!( error.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut ) => { Ok(None) } Err(error) => Err(error.to_string()), } } fn write(&mut self, bytes: &[u8]) -> Result<(), String> { self.say(&json!({ "t": "input", "data": base64::engine::general_purpose::STANDARD.encode(bytes), })) } fn resize(&mut self, cols: u16, rows: u16) -> Result<(), String> { self.say(&json!({ "t": "resize", "cols": cols, "rows": rows })) } fn behind(&self) -> bool { self.behind } fn close(&mut self) { let _ = self.inner.close(None); let _ = self.inner.flush(); self.inner.get_ref().shutdown(); } } /// `std::io::Read` is imported for `Wire`'s sake; naming it keeps clippy from /// calling the import unused on a build with no TLS. #[allow(dead_code)] fn _wire_is_read() {} // ─── the hub ──────────────────────────────────────────────────────────────── /// Every terminal this device has open, and the pump behind each one. /// /// One thread per attached session, which is one per SCREEN: a person looks at /// one terminal at a time and the tab closes when they leave it. A shared /// reactor would be the right shape for a hundred; for the one or two a phone /// ever holds it would be machinery with no reader. #[derive(Default)] pub struct TerminalHub { open: Mutex>, } impl std::fmt::Debug for TerminalHub { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("TerminalHub") .field("attached", &self.attached()) .finish() } } struct Attached { session_id: String, stopped: Arc, stream: Arc>>, } impl TerminalHub { pub fn new() -> TerminalHub { TerminalHub::default() } /// Is this session attached right now? pub fn is_attached(&self, session_id: &str) -> bool { self.held() .iter() .any(|attached| attached.session_id == session_id) } pub fn attached(&self) -> Vec { self.held() .iter() .map(|attached| attached.session_id.clone()) .collect() } fn held(&self) -> std::sync::MutexGuard<'_, Vec> { self.open .lock() .unwrap_or_else(|poisoned| poisoned.into_inner()) } /// Open a terminal and start pumping it. /// /// Attaching a session that is already attached RESIZES it rather than /// opening a second stream: two pumps on one session would double every /// byte on screen, and a view that reopened its tab means "show me this /// one", not "show it to me twice". pub fn attach( &self, transport: &TerminalTransport, sink: Arc, session_id: &str, cols: u16, rows: u16, ) -> Result<(), String> { if self.is_attached(session_id) { return self.resize(session_id, cols, rows); } let stream = transport.attach(session_id, cols, rows)?; let stream = Arc::new(Mutex::new(stream)); let stopped = Arc::new(AtomicBool::new(false)); self.held().push(Attached { session_id: session_id.to_string(), stopped: Arc::clone(&stopped), stream: Arc::clone(&stream), }); sink.state(session_id, TerminalState::Attached); let pump_session = session_id.to_string(); let pump_stream = Arc::clone(&stream); let pump_stopped = Arc::clone(&stopped); std::thread::Builder::new() .name(format!("cotton-terminal-{session_id}")) .spawn(move || { pump(&pump_session, &pump_stream, &pump_stopped, sink.as_ref()); }) .map_err(|error| format!("the terminal's reader could not be started — {error}"))?; Ok(()) } pub fn write(&self, session_id: &str, bytes: &[u8]) -> Result<(), String> { self.with(session_id, |stream| stream.write(bytes)) } pub fn resize(&self, session_id: &str, cols: u16, rows: u16) -> Result<(), String> { self.with(session_id, |stream| stream.resize(cols, rows)) } /// Close one terminal. Idempotent: a view that detaches twice has still /// detached, and a refusal there would be noise on a screen going away. pub fn detach(&self, session_id: &str) { let taken = { let mut held = self.held(); held.iter() .position(|attached| attached.session_id == session_id) .map(|at| held.remove(at)) }; if let Some(attached) = taken { attached.stopped.store(true, Ordering::SeqCst); if let Ok(mut stream) = attached.stream.lock() { stream.close(); } } } /// Close every terminal — the app going away, or a device leaving a /// server. pub fn detach_all(&self) { for session_id in self.attached() { self.detach(&session_id); } } fn with( &self, session_id: &str, body: impl FnOnce(&mut dyn TerminalStream) -> Result<(), String>, ) -> Result<(), String> { let stream = { let held = self.held(); held.iter() .find(|attached| attached.session_id == session_id) .map(|attached| Arc::clone(&attached.stream)) }; let stream = stream.ok_or_else(|| { format!("nothing is attached to {session_id} on this device") })?; let mut stream = stream .lock() .map_err(|_| "the terminal is poisoned".to_string())?; body(stream.as_mut()) } } /// The reader loop: gather, and emit at most thirty times a second. fn pump( session_id: &str, stream: &Arc>>, stopped: &AtomicBool, sink: &dyn TerminalSink, ) { let mut pending: Vec = Vec::new(); let mut behind = false; loop { if stopped.load(Ordering::SeqCst) { break; } let read = { let Ok(mut held) = stream.lock() else { break }; let chunk = held.read(READ_WAIT_MS); let now_behind = held.behind(); (chunk, now_behind) }; match read.0 { Ok(Some(bytes)) => pending.extend_from_slice(&bytes), Ok(None) => {} Err(reason) => { if !pending.is_empty() { sink.data(session_id, &pending); } sink.state(session_id, TerminalState::Closed); let _ = reason; return; } } if read.1 != behind { behind = read.1; sink.state( session_id, if behind { TerminalState::CatchingUp } else { TerminalState::Attached }, ); } if !pending.is_empty() { sink.data(session_id, &pending); pending.clear(); // The floor under the emit rate. `read` already waited // `READ_WAIT_MS` for nothing, so this only bites while bytes are // actually pouring in — which is exactly when it should. std::thread::sleep(Duration::from_millis(TERMINAL_COALESCE_MS as u64)); } } sink.state(session_id, TerminalState::Closed); } #[cfg(test)] #[path = "terminal_tests.rs"] mod tests;