//! Client for the record-daemon's IPC protocol. //! //! Ported from `tauri-app/src-tauri/src/daemon_ipc.rs`. The wire format is the daemon's //! (`record-daemon/src/ipc/protocol.rs`): one JSON object per line over a named pipe, a //! `request` answered by one `response` with the same id. //! //! Requests are async (tokio). The UI runs on rune's thread and never blocks, so a worker thread //! owns a current-thread runtime, executes one request at a time and pushes results into a queue //! that `poll` drains. use serde::{Deserialize, Serialize}; use serde_json::Value; use std::path::PathBuf; use std::sync::mpsc::{Receiver, Sender, channel}; use std::sync::{Arc, Mutex}; use std::time::Duration; // --------------------------------------------------------------------------- // Protocol // --------------------------------------------------------------------------- /// Message type, as the daemon's `MessageType`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum MessageType { Request, Response, Notification, } /// Commands the daemon accepts (`IpcCommand`, camelCase). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum Command { GetSettings, UpdateSettings, ResetSettings, GetStatus, GetEncoders, GetAudioDevices, AddAudioSource, RemoveAudioSource { id: String }, UpdateAudioSource, StartRecording, StopRecording, Shutdown, } /// Request envelope. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IpcMessage { #[serde(rename = "type")] pub message_type: MessageType, pub id: String, #[serde(skip_serializing_if = "Option::is_none")] pub command: Option, #[serde(skip_serializing_if = "Option::is_none")] pub payload: Option, } /// Response envelope. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct IpcResponse { pub request_id: String, pub success: bool, #[serde(default)] pub data: Option, #[serde(default)] pub error: Option, } /// The pipe the daemon listens on. A scratch home, as scripts set, gets a pipe of its own. pub fn default_socket_path() -> PathBuf { let scratch = std::env::var_os(crate::daemon::HOME_ENV).is_some_and(|value| !value.is_empty()); #[cfg(windows)] { if scratch { return PathBuf::from(r"\\.\pipe\record-daemon-scratch"); } PathBuf::from(r"\\.\pipe\record-daemon") } #[cfg(not(windows))] { let name = if scratch { "record-daemon-scratch.sock" } else { "record-daemon.sock" }; let dir = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/tmp".into()); Path::new(&dir).join(name) } } // --------------------------------------------------------------------------- // Client // --------------------------------------------------------------------------- pub struct Client { path: PathBuf, timeout: Duration, } impl Client { pub fn new() -> Self { Self { path: default_socket_path(), timeout: Duration::from_secs(5), } } /// Send one command and wait for its answer. pub async fn call(&self, command: Command, payload: Option) -> Result { let message = IpcMessage { message_type: MessageType::Request, id: uuid::Uuid::new_v4().to_string(), command: Some(command), payload, }; let json = serde_json::to_string(&message).map_err(|e| format!("serialize: {e}"))?; let line = self.round_trip(&json).await?; let response: IpcResponse = serde_json::from_str(&line).map_err(|e| format!("parse response: {e}"))?; if response.success { Ok(response.data.unwrap_or(Value::Null)) } else { Err(response .error .unwrap_or_else(|| "daemon returned an error".into())) } } pub async fn is_running(&self) -> bool { self.call(Command::GetStatus, None).await.is_ok() } #[cfg(windows)] async fn round_trip(&self, message: &str) -> Result { use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::windows::named_pipe::ClientOptions; let pipe = self.path.to_string_lossy().to_string(); let client = tokio::time::timeout(self.timeout, async { let mut attempts = 0; loop { match ClientOptions::new().open(&pipe) { Ok(client) => return Ok(client), // ERROR_PIPE_BUSY: every instance is serving another client. Err(e) if e.raw_os_error() == Some(231) => { attempts += 1; if attempts > 5 { return Err(format!("daemon pipe busy: {e}")); } tokio::time::sleep(Duration::from_millis(100)).await; } Err(e) => return Err(format!("cannot connect to daemon: {e}")), } } }) .await .map_err(|_| "connecting to the daemon timed out".to_string())??; let (reader, mut writer) = tokio::io::split(client); writer .write_all(message.as_bytes()) .await .map_err(|e| format!("write: {e}"))?; writer .write_all(b"\n") .await .map_err(|e| format!("write: {e}"))?; writer.flush().await.map_err(|e| format!("flush: {e}"))?; let mut lines = BufReader::new(reader).lines(); let line = tokio::time::timeout(self.timeout, lines.next_line()) .await .map_err(|_| "the daemon did not answer in time".to_string())? .map_err(|e| format!("read: {e}"))?; line.ok_or_else(|| "the daemon closed the pipe without answering".to_string()) } #[cfg(not(windows))] async fn round_trip(&self, message: &str) -> Result { use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::UnixStream; let stream = tokio::time::timeout(self.timeout, UnixStream::connect(&self.path)) .await .map_err(|_| "connecting to the daemon timed out".to_string())? .map_err(|e| format!("cannot connect to daemon: {e}"))?; let (reader, mut writer) = stream.into_split(); writer .write_all(message.as_bytes()) .await .map_err(|e| format!("write: {e}"))?; writer .write_all(b"\n") .await .map_err(|e| format!("write: {e}"))?; writer.flush().await.map_err(|e| format!("flush: {e}"))?; let mut lines = BufReader::new(reader).lines(); let line = tokio::time::timeout(self.timeout, lines.next_line()) .await .map_err(|_| "the daemon did not answer in time".to_string())? .map_err(|e| format!("read: {e}"))?; line.ok_or_else(|| "the daemon closed the socket without answering".to_string()) } } // --------------------------------------------------------------------------- // Background worker // --------------------------------------------------------------------------- /// What a queued request is for, so `poll` can route its answer. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Request { EnsureRunning, Settings, SaveSettings, ResetSettings, Status, Encoders, AudioDevices, AddAudioSource, RemoveAudioSource, UpdateAudioSource, StartRecording, StopRecording, Shutdown, Logs, } struct Job { request: Request, command: Command, payload: Option, } /// An answer from the worker thread. #[derive(Debug, Clone)] pub struct Event { pub request: Request, pub result: Result, } /// A cloneable handle to the worker thread. #[derive(Clone)] pub struct Daemon { jobs: Sender, events: Arc>>, waker: Arc>>, /// Headless runs keep no worker and send nothing. off: bool, } impl Daemon { /// Start the worker. It also brings the daemon process up on first use. /// A headless run (`--snap` and friends) starts nothing and talks to nobody. pub fn start(headless: bool) -> Self { let (job_tx, job_rx) = channel::(); let (event_tx, event_rx) = channel::(); let waker: Arc>> = Arc::new(Mutex::new(None)); let worker_waker = waker.clone(); if headless { return Self { jobs: job_tx, events: Arc::new(Mutex::new(event_rx)), waker, off: true, }; } std::thread::Builder::new() .name("daemon-ipc".into()) .spawn(move || { let runtime = match tokio::runtime::Builder::new_current_thread() .enable_all() .build() { Ok(rt) => rt, Err(e) => { let _ = event_tx.send(Event { request: Request::EnsureRunning, result: Err(format!("no async runtime: {e}")), }); return; } }; let client = Client::new(); // Bring the daemon up before the first request. It takes a few seconds to // initialise OBS, so this must not run on the UI thread. let started = runtime .block_on(crate::daemon::ensure_running()) .map(|_| Value::Null); let _ = event_tx.send(Event { request: Request::EnsureRunning, result: started, }); wake(&worker_waker); while let Ok(job) = job_rx.recv() { let result = match job.request { Request::EnsureRunning => runtime .block_on(crate::daemon::ensure_running()) .map(|_| Value::Null), Request::Logs => crate::daemon::read_logs(200).map(Value::String), _ => runtime.block_on(client.call(job.command, job.payload)), }; let _ = event_tx.send(Event { request: job.request, result, }); wake(&worker_waker); } }) .expect("spawn daemon worker"); Self { jobs: job_tx, events: Arc::new(Mutex::new(event_rx)), waker, off: false, } } /// The waker rune hands to `AppSpec::setup`. pub fn set_waker(&self, waker: rune::Waker) { *self.waker.lock().unwrap() = Some(waker); } fn send(&self, request: Request, command: Command, payload: Option) { if self.off { return; } let _ = self.jobs.send(Job { request, command, payload, }); } pub fn get_settings(&self) { self.send(Request::Settings, Command::GetSettings, None); } pub fn save_settings(&self, settings: Value) { self.send( Request::SaveSettings, Command::UpdateSettings, Some(settings), ); } pub fn reset_settings(&self) { self.send(Request::ResetSettings, Command::ResetSettings, None); } pub fn get_status(&self) { self.send(Request::Status, Command::GetStatus, None); } pub fn get_encoders(&self) { self.send(Request::Encoders, Command::GetEncoders, None); } pub fn get_audio_devices(&self) { self.send(Request::AudioDevices, Command::GetAudioDevices, None); } pub fn add_audio_source(&self, source: Value) { self.send( Request::AddAudioSource, Command::AddAudioSource, Some(source), ); } pub fn remove_audio_source(&self, id: &str) { self.send( Request::RemoveAudioSource, Command::RemoveAudioSource { id: id.to_string() }, None, ); } pub fn update_audio_source(&self, source: Value) { self.send( Request::UpdateAudioSource, Command::UpdateAudioSource, Some(source), ); } pub fn start_recording(&self) { self.send(Request::StartRecording, Command::StartRecording, None); } pub fn stop_recording(&self) { self.send(Request::StopRecording, Command::StopRecording, None); } pub fn shutdown(&self) { self.send(Request::Shutdown, Command::Shutdown, None); } pub fn ensure_running(&self) { self.send(Request::EnsureRunning, Command::GetStatus, None); } pub fn logs(&self) { self.send(Request::Logs, Command::GetStatus, None); } /// Answers that arrived since the last frame, without blocking. pub fn drain(&self) -> Vec { let rx = self.events.lock().unwrap(); let mut out = Vec::new(); while let Ok(event) = rx.try_recv() { out.push(event); } out } } fn wake(waker: &Mutex>) { if let Some(w) = waker.lock().unwrap().as_ref() { w(); } } #[cfg(test)] mod tests { use super::*; use serde_json::json; fn request(command: Command, payload: Option) -> Value { let message = IpcMessage { message_type: MessageType::Request, id: "00000000-0000-4000-8000-000000000000".into(), command: Some(command), payload, }; serde_json::to_value(message).unwrap() } #[test] fn a_unit_command_is_a_plain_string() { assert_eq!( request(Command::GetSettings, None), json!({ "type": "request", "id": "00000000-0000-4000-8000-000000000000", "command": "getSettings" }) ); } #[test] fn a_command_with_a_field_is_an_object() { assert_eq!( request(Command::RemoveAudioSource { id: "abc".into() }, None), json!({ "type": "request", "id": "00000000-0000-4000-8000-000000000000", "command": {"removeAudioSource": {"id": "abc"}} }) ); } #[test] fn settings_go_in_the_payload_untouched() { let payload = json!({"video": {"frame_rate": 60}}); assert_eq!( request(Command::UpdateSettings, Some(payload.clone()))["payload"], payload ); } #[test] fn responses_parse_with_and_without_data() { let ok: IpcResponse = serde_json::from_str(r#"{"request_id":"x","success":true,"data":{"a":1}}"#).unwrap(); assert!(ok.success); assert_eq!(ok.data.unwrap()["a"], 1); let err: IpcResponse = serde_json::from_str(r#"{"request_id":"x","success":false,"error":"nope"}"#).unwrap(); assert!(!err.success); assert_eq!(err.error.as_deref(), Some("nope")); } #[test] fn the_pipe_name_matches_the_daemon() { assert_eq!( default_socket_path().to_string_lossy(), r"\\.\pipe\record-daemon" ); } }