//! The connection to a running Lutra, as the MCP server sees it. //! //! The server does not know how Lutra is reached: the `lutra` CLI (layer //! L6) implements [`Connector`] on top of the control channel client and //! the single-instance rendezvous file, and tests implement it with a //! test backend. That keeps this crate free of sockets and process //! launching. use std::time::Duration; use serde_json::Value; /// Error code of a failure to reach Lutra or of a lost connection. pub const UNAVAILABLE: &str = "unavailable"; /// Why a call to Lutra failed. #[derive(Debug, Clone, PartialEq, Eq)] pub enum CallError { /// Lutra answered with an error: the engine's or the control /// channel's code and message. Remote { /// Stable code, e.g. `disabled` or `invalid_params`. code: String, /// Human-readable message. message: String, }, /// The connection failed or was lost, or Lutra sent something that is /// not a protocol line. The next call connects again. Lost(String), } impl CallError { /// The stable code: the remote code, or [`UNAVAILABLE`]. pub fn code(&self) -> &str { match self { Self::Remote { code, .. } => code, Self::Lost(_) => UNAVAILABLE, } } /// The message. pub fn message(&self) -> &str { match self { Self::Remote { message, .. } | Self::Lost(message) => message, } } } impl std::fmt::Display for CallError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}: {}", self.code(), self.message()) } } /// One authenticated connection to the control channel. pub trait Connection: Send { /// Sends one control request (`engine.execute`, `ui.screenshot`, …) /// and waits for its result. /// /// # Errors /// [`CallError::Remote`] for an error answer, [`CallError::Lost`] if /// the connection failed. fn request(&mut self, method: &str, params: Value) -> Result; /// The next event (the object inside `{"event": ...}`) after /// `events.subscribe`, waiting at most `timeout`. /// /// # Returns /// `Ok(None)` if none arrived in time. /// /// # Errors /// [`CallError::Lost`] if the connection failed. fn next_event(&mut self, timeout: Duration) -> Result, CallError>; } /// Opens connections to Lutra. pub trait Connector: Send + Sync { /// Connects to the running Lutra. With `start`, a Lutra that is not /// running is started first. /// /// # Errors /// A message saying why Lutra cannot be reached. fn connect(&self, start: bool) -> Result, String>; }