//! The interface the control channel needs from its host, and the //! subscriber list hosts use to publish engine events. use std::path::Path; use std::sync::mpsc::{SyncSender, TrySendError}; use std::sync::{Mutex, PoisonError}; use lutra_engine::{CommandInfo, EngineError, Event}; use serde_json::Value; /// Queue of events for one subscriber. Bounded so that a client that stops /// reading cannot make the host buffer without limit. pub type EventSink = SyncSender; /// Capacity of each subscriber's queue. pub const EVENT_QUEUE: usize = 4096; /// What the control channel can ask the host to do. /// /// The desktop app implements it on top of its engine and window; tests /// implement it with a bare engine. Methods are called from connection /// threads, so implementations synchronise internally. pub trait Backend: Send + Sync + 'static { /// Runs an engine command, applies its effects and publishes its events. /// /// # Errors /// The engine's error for the command. fn execute(&self, command: &str, params: Value) -> Result; /// Lists every command with its current enabled state. fn list_commands(&self) -> Vec; /// Writes a PNG screenshot of the main window to `path`. /// /// # Errors /// A message if there is no window to capture or the file cannot be /// written. fn screenshot(&self, path: &Path) -> Result<(), String>; /// Adds a subscriber that receives every engine event from now on. fn subscribe(&self, sink: EventSink); /// Brings the main window to the front, for the CLI and a second app /// start. The default has no window and fails. /// /// # Errors /// A message if there is no window or it cannot be focused. fn focus(&self) -> Result<(), String> { Err("there is no window".into()) } } /// The event subscribers of a host. #[derive(Debug, Default)] pub struct Subscribers { /// Live subscribers. sinks: Mutex>, } impl Subscribers { /// Adds a subscriber. pub fn add(&self, sink: EventSink) { self.sinks .lock() .unwrap_or_else(PoisonError::into_inner) .push(sink); } /// Sends `events` to every subscriber, in order. A subscriber whose /// queue is full or whose receiver is gone is dropped: a full queue /// means the client stopped reading, and dropping it keeps the host from /// blocking or buffering without limit. pub fn publish(&self, events: &[Event]) { if events.is_empty() { return; } let mut sinks = self.sinks.lock().unwrap_or_else(PoisonError::into_inner); sinks.retain(|sink| { events .iter() .all(|event| match sink.try_send(event.clone()) { Ok(()) => true, Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => false, }) }); } /// Number of live subscribers. pub fn len(&self) -> usize { self.sinks .lock() .unwrap_or_else(PoisonError::into_inner) .len() } /// Whether there is no subscriber. pub fn is_empty(&self) -> bool { self.len() == 0 } } #[cfg(test)] mod tests { use std::sync::mpsc::sync_channel; use super::*; #[test] fn publishes_in_order_and_drops_dead_or_slow_subscribers() { let subs = Subscribers::default(); let (fast_tx, fast_rx) = sync_channel(10); let (slow_tx, _slow_rx) = sync_channel(1); let (dead_tx, dead_rx) = sync_channel(10); subs.add(fast_tx); subs.add(slow_tx); subs.add(dead_tx); drop(dead_rx); subs.publish(&[Event::ProjectClosed, Event::BufferClosed { id: 1 }]); assert_eq!(subs.len(), 1); assert_eq!(fast_rx.try_recv().unwrap(), Event::ProjectClosed); assert_eq!(fast_rx.try_recv().unwrap(), Event::BufferClosed { id: 1 }); } }