//! A blocking client for the control channel, and the open logic the //! `lutra` CLI and a second app start share. //! //! [`connect_live`] reads the rendezvous file, connects to the listener it //! names and authenticates; [`Client::request`] sends one request and reads //! lines until its response arrives, keeping event lines that arrive in //! between for [`Client::next_event`]. Every line read is untrusted: lines //! are capped at [`MAX_RESPONSE_BYTES`] and malformed lines are errors, //! never panics. //! //! [`Client::open_folder`] and [`Client::open_file`] implement `lutra PATH`: //! a folder becomes the project; a file is opened with `file.open`, and if //! no project is open its parent folder is opened first. A file outside an //! open project is refused instead of replacing the project. use std::collections::VecDeque; use std::io::{self, BufRead, BufReader, Read, Write}; use std::net::{Ipv4Addr, SocketAddr, TcpStream}; use std::path::Path; use std::thread; use std::time::{Duration, Instant}; use serde_json::{Value, json}; use crate::methods::{APP_AUTH, APP_FOCUS, APP_PING, ENGINE_EXECUTE, EVENTS_SUBSCRIBE}; use crate::rendezvous::{self, Instance, ReadError}; /// Largest line the client reads, newline excluded. Responses carry whole /// buffer texts (`file.open`), so this is larger than the request cap. pub const MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; /// Default time to connect and to wait for one response. pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); /// Most event lines kept while waiting for a response; older ones are /// dropped. const MAX_QUEUED_EVENTS: usize = 4096; /// Engine error code of a command the engine does not know, which is what /// a UI command answers before the window has registered it. const UNKNOWN_COMMAND: &str = "unknown_command"; /// Engine error code of a command that needs a project. const DISABLED: &str = "disabled"; /// What went wrong talking to Lutra. #[derive(Debug)] pub enum ClientError { /// Connecting, reading or writing failed, or the peer closed the /// connection. Io(io::Error), /// The peer answered with an error. Remote { /// The stable error code, e.g. `unauthorized` or `disabled`. code: String, /// The message. message: String, }, /// The peer sent something that is not a protocol line. Protocol(String), } impl ClientError { /// The remote error code, if this is a remote error. pub fn code(&self) -> Option<&str> { match self { Self::Remote { code, .. } => Some(code), _ => None, } } } impl std::fmt::Display for ClientError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Io(e) => write!(f, "{e}"), Self::Remote { code, message } => write!(f, "{message} ({code})"), Self::Protocol(why) => write!(f, "unexpected answer from Lutra: {why}"), } } } impl std::error::Error for ClientError {} impl From for ClientError { fn from(e: io::Error) -> Self { Self::Io(e) } } /// Why no running instance could be reached through the rendezvous file. #[derive(Debug)] pub enum Unavailable { /// There is no rendezvous file. Missing, /// The file is unreadable or invalid, or its listener does not answer /// or does not accept its token: the instance is gone. Stale(String), } impl std::fmt::Display for Unavailable { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Missing => write!(f, "Lutra is not running"), Self::Stale(why) => write!(f, "stale rendezvous file: {why}"), } } } /// Connects to the instance named by the rendezvous file in `dir`, /// authenticates and pings it. /// /// # Errors /// [`Unavailable::Missing`] without a file, [`Unavailable::Stale`] if the /// file is invalid or nobody answers it properly within `timeout`. pub fn connect_live(dir: &Path, timeout: Duration) -> Result<(Instance, Client), Unavailable> { let instance = match rendezvous::read(dir) { Ok(instance) => instance, Err(ReadError::Missing) => return Err(Unavailable::Missing), Err(e) => return Err(Unavailable::Stale(e.to_string())), }; match Client::connect_instance(&instance, timeout) { Ok(client) => Ok((instance, client)), Err(e) => Err(Unavailable::Stale(e.to_string())), } } /// A file opened in Lutra. #[derive(Debug, Clone, PartialEq, Eq)] pub struct OpenedFile { /// The buffer id, for `bufferClosed`. pub id: u64, /// The project-relative path the engine reported. pub path: String, } /// A connection to the control channel. #[derive(Debug)] pub struct Client { /// Read side. reader: BufReader, /// Write side. writer: TcpStream, /// Bytes of a line whose end has not arrived yet (after a timeout). partial: Vec, /// Event lines read while waiting for a response. events: VecDeque, /// The id of the next request. next_id: u64, /// How long one response may take. timeout: Duration, } impl Client { /// Connects to `127.0.0.1:port` without authenticating, for the /// `--control` channel. /// /// # Errors /// The connect error. pub fn connect(port: u16, timeout: Duration) -> Result { let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); let stream = TcpStream::connect_timeout(&addr, timeout)?; stream.set_nodelay(true)?; Ok(Self { writer: stream.try_clone()?, reader: BufReader::new(stream), partial: Vec::new(), events: VecDeque::new(), next_id: 1, timeout, }) } /// Connects to `instance`, authenticates with its token and pings it. /// /// # Errors /// The connect error, `unauthorized`, or a ping failure. pub fn connect_instance(instance: &Instance, timeout: Duration) -> Result { let mut client = Self::connect(instance.port, timeout)?; client.request(APP_AUTH, json!({ "token": instance.token }))?; client.request(APP_PING, Value::Null)?; Ok(client) } /// Sends one request and waits for its response; event lines read /// meanwhile are kept for [`Client::next_event`]. /// /// # Errors /// I/O errors and timeouts, the remote error, or a malformed line. pub fn request(&mut self, method: &str, params: Value) -> Result { let id = self.next_id; self.next_id = self.next_id.saturating_add(1); let line = json!({ "id": id, "method": method, "params": params }).to_string(); let mut bytes = line.into_bytes(); bytes.push(b'\n'); self.writer.write_all(&bytes)?; self.writer.flush()?; let deadline = Instant::now() + self.timeout; loop { let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return Err(ClientError::Io(io::Error::new( io::ErrorKind::TimedOut, format!("no answer to {method} within {:?}", self.timeout), ))); } let Some(value) = self.read_value(Some(left))? else { continue; }; if let Some(event) = value.get("event") { if self.events.len() >= MAX_QUEUED_EVENTS { self.events.pop_front(); } self.events.push_back(event.clone()); continue; } if value.get("id").and_then(Value::as_u64) != Some(id) { continue; } if let Some(error) = value.get("error") { let text = |key: &str| { error .get(key) .and_then(Value::as_str) .unwrap_or_default() .to_string() }; return Err(ClientError::Remote { code: text("code"), message: text("message"), }); } return Ok(value.get("result").cloned().unwrap_or(Value::Null)); } } /// Runs an engine command (`engine.execute`). /// /// # Errors /// As [`Client::request`]. pub fn execute(&mut self, command: &str, params: Value) -> Result { self.request( ENGINE_EXECUTE, json!({ "command": command, "params": params }), ) } /// Subscribes this connection to engine events. /// /// # Errors /// As [`Client::request`]. pub fn subscribe(&mut self) -> Result<(), ClientError> { self.request(EVENTS_SUBSCRIBE, Value::Null).map(|_| ()) } /// The next event (the object inside `{"event": ...}`), waiting at most /// `timeout` (`None`: as long as it takes). /// /// # Returns /// `Ok(None)` on timeout. /// /// # Errors /// [`ClientError::Io`] with `UnexpectedEof` when the connection closed, /// other I/O errors, or a malformed line. pub fn next_event(&mut self, timeout: Option) -> Result, ClientError> { let deadline = timeout.map(|t| Instant::now() + t); loop { if let Some(event) = self.events.pop_front() { return Ok(Some(event)); } let left = match deadline { Some(deadline) => { let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { return Ok(None); } Some(left) } None => None, }; if let Some(value) = self.read_value(left)? && let Some(event) = value.get("event") { return Ok(Some(event.clone())); } } } /// Reads one line as JSON, waiting at most `timeout`. /// /// # Returns /// `Ok(None)` if the time ran out before a whole line arrived; the part /// read so far is kept for the next call. /// /// # Errors /// End of stream, other I/O errors, an oversized or malformed line. fn read_value(&mut self, timeout: Option) -> Result, ClientError> { self.reader.get_ref().set_read_timeout(timeout)?; let room = MAX_RESPONSE_BYTES.saturating_sub(self.partial.len()); let limit = u64::try_from(room).unwrap_or(u64::MAX).saturating_add(1); let read = (&mut self.reader) .take(limit) .read_until(b'\n', &mut self.partial); match read { Ok(0) if self.partial.is_empty() => { return Err(ClientError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "Lutra closed the connection", ))); } Ok(_) => {} Err(e) if matches!( e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut ) => { return Ok(None); } Err(e) if e.kind() == io::ErrorKind::Interrupted => return Ok(None), Err(e) => return Err(ClientError::Io(e)), } if self.partial.last() != Some(&b'\n') { if self.partial.len() > MAX_RESPONSE_BYTES { return Err(ClientError::Protocol(format!( "a line is longer than {MAX_RESPONSE_BYTES} bytes" ))); } return Err(ClientError::Io(io::Error::new( io::ErrorKind::UnexpectedEof, "Lutra closed the connection in the middle of a line", ))); } let line = std::mem::take(&mut self.partial); serde_json::from_slice(&line) .map(Some) .map_err(|e| ClientError::Protocol(e.to_string())) } /// Brings the window to the front. Failures are ignored by callers that /// only want to be helpful (there may be no window yet). /// /// # Errors /// As [`Client::request`]. pub fn focus(&mut self) -> Result<(), ClientError> { self.request(APP_FOCUS, Value::Null).map(|_| ()) } /// Opens `folder` as the project (`project.open`). /// /// # Errors /// The engine's error, e.g. `unsaved_changes` when the open project has /// dirty buffers. pub fn open_folder(&mut self, folder: &Path) -> Result { self.execute("project.open", json!({ "path": path_text(folder)? })) } /// Opens `file` in a tab. If no project is open, the file's parent /// folder is opened as the project first. A file outside the open /// project fails with the engine's error; the project is never replaced /// behind the user's back. /// /// # Errors /// The engine's error, or [`ClientError::Protocol`] for a result /// without a buffer id. pub fn open_file(&mut self, file: &Path) -> Result { let text = path_text(file)?; let result = match self.execute("file.open", json!({ "path": text })) { Err(e) if e.code() == Some(DISABLED) => { let parent = file.parent().ok_or_else(|| { ClientError::Protocol(format!("{} has no parent folder", file.display())) })?; self.open_folder(parent)?; self.execute("file.open", json!({ "path": text }))? } other => other?, }; let id = result .get("id") .and_then(Value::as_u64) .ok_or_else(|| ClientError::Protocol("file.open returned no buffer id".into()))?; let path = result .get("path") .and_then(Value::as_str) .map_or_else(|| text.clone(), str::to_string); Ok(OpenedFile { id, path }) } /// Moves the cursor of the open tab `path` to 0-based `line` and /// UTF-16 `column` with the UI command `editor.reveal`. Until the /// window has registered its UI commands (it is still starting) the /// engine answers `unknown_command`; the call is retried until `wait` /// has passed. /// /// # Errors /// The last error once `wait` has passed, or any other error at once. pub fn reveal( &mut self, path: &str, line: u32, column: u32, wait: Duration, ) -> Result<(), ClientError> { let deadline = Instant::now() + wait; let params = json!({ "path": path, "line": line, "column": column }); loop { match self.execute("editor.reveal", params.clone()) { Err(e) if e.code() == Some(UNKNOWN_COMMAND) && Instant::now() < deadline => { thread::sleep(Duration::from_millis(200)); } other => return other.map(|_| ()), } } } } /// The path as UTF-8 text for a JSON param. /// /// # Errors /// [`ClientError::Protocol`] if the path is not valid Unicode. fn path_text(path: &Path) -> Result { path.to_str() .map(str::to_string) .ok_or_else(|| ClientError::Protocol(format!("{} is not valid Unicode", path.display()))) }