use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::time::Duration;
use fluxframe_core::protocol::{Command, DaemonInfo, Response};
use relm4::Worker;
use relm4::prelude::ComponentSender;
use crate::ipc::wire::{parse_inventory, parse_presets};
use crate::state::EffectInventory;
#[derive(Debug)]
pub enum WorkerInput {
Connect,
Send {
tag: u64,
command: Command,
},
}
#[derive(Debug)]
pub enum WorkerOutput {
Connected(Box<InitialState>),
Reply {
tag: u64,
response: Response,
},
Disconnected {
reason: String,
},
}
#[derive(Debug)]
pub struct InitialState {
pub inventory: EffectInventory,
pub presets: Vec<String>,
pub active_preset: String,
pub active_config: serde_json::Value,
pub config_path: Option<PathBuf>,
pub daemon_info: Option<DaemonInfo>,
}
const READ_TIMEOUT: Duration = Duration::from_secs(5);
pub struct IpcWorker {
socket_path: PathBuf,
stream: Option<BufferedStream>,
}
struct BufferedStream {
reader: BufReader<UnixStream>,
writer: UnixStream,
read_timeout: Duration,
}
#[derive(Debug)]
enum IpcError {
Io(std::io::Error),
Timeout(Duration),
Closed,
Serialize(serde_json::Error),
Parse(serde_json::Error),
}
impl std::fmt::Display for IpcError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "socket IO failed: {e}"),
Self::Timeout(d) if d.subsec_millis() == 0 => {
write!(f, "daemon did not reply within {} s", d.as_secs())
}
Self::Timeout(d) => write!(f, "daemon did not reply within {} ms", d.as_millis()),
Self::Closed => f.write_str("daemon closed the connection"),
Self::Serialize(e) => write!(f, "serialise command failed: {e}"),
Self::Parse(e) => write!(f, "parse response failed: {e}"),
}
}
}
impl BufferedStream {
fn connect(path: &std::path::Path) -> std::io::Result<Self> {
let stream = UnixStream::connect(path)?;
tracing::info!(path = %path.display(), "socket connected, starting handshake");
Self::from_stream(stream, READ_TIMEOUT)
}
fn from_stream(stream: UnixStream, read_timeout: Duration) -> std::io::Result<Self> {
stream.set_read_timeout(Some(read_timeout))?;
let writer = stream.try_clone()?;
Ok(Self {
reader: BufReader::new(stream),
writer,
read_timeout,
})
}
#[tracing::instrument(skip(self), level = "debug")]
fn round_trip(&mut self, cmd: &Command) -> Result<Response, IpcError> {
tracing::debug!(?cmd, "ipc round trip start");
let payload = serde_json::to_string(cmd).map_err(IpcError::Serialize)?;
self.writer
.write_all(payload.as_bytes())
.and_then(|()| self.writer.write_all(b"\n"))
.and_then(|()| self.writer.flush())
.map_err(IpcError::Io)?;
let mut line = String::new();
let n = self
.reader
.read_line(&mut line)
.map_err(|e| match e.kind() {
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut => {
IpcError::Timeout(self.read_timeout)
}
_ => IpcError::Io(e),
})?;
if n == 0 {
return Err(IpcError::Closed);
}
serde_json::from_str::<Response>(line.trim_end()).map_err(IpcError::Parse)
}
}
impl Worker for IpcWorker {
type Init = PathBuf;
type Input = WorkerInput;
type Output = WorkerOutput;
fn init(socket_path: Self::Init, sender: ComponentSender<Self>) -> Self {
sender.input(WorkerInput::Connect);
Self {
socket_path,
stream: None,
}
}
fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>) {
let (tag, command) = match msg {
WorkerInput::Connect => {
self.connect(&sender);
return;
}
WorkerInput::Send { tag, command } => (tag, command),
};
let Some(stream) = self.stream.as_mut() else {
let _ = sender.output(WorkerOutput::Reply {
tag,
response: Response::err("not connected", None),
});
return;
};
match stream.round_trip(&command) {
Ok(response) => {
let _ = sender.output(WorkerOutput::Reply { tag, response });
}
Err(err) => {
let reason = err.to_string();
self.stream = None;
let _ = sender.output(WorkerOutput::Reply {
tag,
response: Response::err(reason.clone(), None),
});
let _ = sender.output(WorkerOutput::Disconnected { reason });
}
}
}
}
impl IpcWorker {
fn connect(&mut self, sender: &ComponentSender<Self>) {
if self.stream.is_some() {
tracing::debug!("ipc worker already connected; ignoring Connect");
return;
}
match BufferedStream::connect(&self.socket_path) {
Ok(mut stream) => match handshake(&mut stream) {
Ok(initial) => {
let _ = sender.output(WorkerOutput::Connected(Box::new(initial)));
self.stream = Some(stream);
}
Err(reason) => {
let _ = sender.output(WorkerOutput::Disconnected { reason });
}
},
Err(e) => {
let hint = match e.kind() {
std::io::ErrorKind::ConnectionRefused => {
"the daemon is not running or not listening on this socket"
}
std::io::ErrorKind::NotFound => {
"the socket file does not exist — check the daemon's [control] config"
}
std::io::ErrorKind::PermissionDenied => {
"permission denied — check the socket file's owner/mode"
}
_ => "connection failed",
};
let _ = sender.output(WorkerOutput::Disconnected {
reason: format!("{hint} ({e})"),
});
}
}
}
}
#[tracing::instrument(skip(stream), level = "info")]
fn handshake(stream: &mut BufferedStream) -> Result<InitialState, String> {
let inventory = one(stream, &Command::ListEffects, "list_effects", |d| {
parse_inventory(&d)
})?;
let presets = one(stream, &Command::ListPresets, "list_presets", |d| {
parse_presets(&d)
})?;
let active_preset = one(stream, &Command::CurrentPreset, "current_preset", |d| {
d.as_str()
.map(str::to_string)
.ok_or_else(|| format!("current_preset payload is not a string: {d}"))
})?;
let active_config = one(stream, &Command::GetConfig { path: None }, "get_config", Ok)?;
let config_path = match stream.round_trip(&Command::ConfigPath) {
Ok(Response::Ok { data }) => parse_config_path(&data),
Ok(Response::Err { error, hint }) => {
tracing::warn!(
error,
?hint,
"config_path command refused; Save will be disabled"
);
None
}
Ok(_) => None,
Err(reason) => return Err(format!("config_path failed: {reason}")),
};
let daemon_info = match stream.round_trip(&Command::DaemonInfo) {
Ok(Response::Ok { data }) => parse_daemon_info(data),
Ok(Response::Err { error, .. }) => {
tracing::debug!(error, "daemon_info refused; assuming an older daemon");
None
}
Ok(_) => None,
Err(reason) => return Err(format!("daemon_info failed: {reason}")),
};
Ok(InitialState {
inventory,
presets,
active_preset,
active_config,
config_path,
daemon_info,
})
}
fn parse_daemon_info(data: serde_json::Value) -> Option<DaemonInfo> {
match serde_json::from_value::<DaemonInfo>(data) {
Ok(info) => Some(info),
Err(e) => {
tracing::debug!(error = %e, "daemon_info: unexpected payload; treating as unreported");
None
}
}
}
fn parse_config_path(data: &serde_json::Value) -> Option<PathBuf> {
if data.is_null() {
return None;
}
if let Some(p) = data.get("path").and_then(serde_json::Value::as_str) {
Some(PathBuf::from(p))
} else {
tracing::debug!(
?data,
"config_path: unexpected payload shape; treating as None"
);
None
}
}
#[tracing::instrument(skip(stream, parse))]
fn one<T>(
stream: &mut BufferedStream,
cmd: &Command,
label: &str,
parse: impl FnOnce(serde_json::Value) -> Result<T, String>,
) -> Result<T, String> {
match stream.round_trip(cmd).map_err(|e| e.to_string())? {
Response::Ok { data } => parse(data),
Response::Err { error, hint } => Err(format!("{label} failed: {error}{}", fmt_hint(hint))),
_ => Err(format!("{label} failed: unrecognised Response variant")),
}
}
fn fmt_hint(hint: Option<String>) -> String {
hint.map_or_else(String::new, |h| format!(" (hint: {h})"))
}
#[cfg(test)]
mod tests {
use super::*;
use fluxframe_core::protocol::OutputInfo;
#[test]
fn ipc_error_display_distinguishes_timeout_from_closed() {
assert_eq!(
IpcError::Timeout(READ_TIMEOUT).to_string(),
"daemon did not reply within 5 s"
);
assert_eq!(IpcError::Closed.to_string(), "daemon closed the connection");
}
#[test]
fn round_trip_reports_closed_peer() {
let (ours, peer) = UnixStream::pair().expect("socket pair");
let mut stream = BufferedStream::from_stream(ours, READ_TIMEOUT).expect("wrap");
let mut req = String::new();
let reader = std::thread::spawn(move || {
BufReader::new(peer)
.read_line(&mut req)
.expect("read request");
});
let err = stream
.round_trip(&Command::ListPresets)
.expect_err("closed peer must fail");
reader.join().expect("peer thread");
assert!(matches!(err, IpcError::Closed), "got {err:?}");
}
#[test]
fn round_trip_reports_silent_peer_as_timeout() {
let (ours, _peer) = UnixStream::pair().expect("socket pair");
let mut stream =
BufferedStream::from_stream(ours, Duration::from_millis(50)).expect("wrap");
let err = stream
.round_trip(&Command::ListPresets)
.expect_err("silent peer must time out");
assert!(matches!(err, IpcError::Timeout(_)), "got {err:?}");
assert_eq!(err.to_string(), "daemon did not reply within 50 ms");
}
fn spawn_mock_daemon(
peer: UnixStream,
script: Vec<(Command, Response)>,
) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let mut writer = peer.try_clone().expect("clone peer");
let mut reader = BufReader::new(peer);
for (expected, reply) in script {
let mut line = String::new();
reader.read_line(&mut line).expect("read request");
let got: Command = serde_json::from_str(line.trim_end()).expect("decode request");
assert_eq!(got, expected, "handshake request order");
let payload = serde_json::to_string(&reply).expect("encode reply");
writer
.write_all(format!("{payload}\n").as_bytes())
.expect("write reply");
}
})
}
fn inventory_payload() -> serde_json::Value {
serde_json::json!({
"mask": [],
"background": [],
"foreground": [],
"post": [],
"build_features": ["ml"]
})
}
fn handshake_script(
config_path_reply: Response,
daemon_info_reply: Response,
) -> Vec<(Command, Response)> {
vec![
(Command::ListEffects, Response::ok_with(inventory_payload())),
(
Command::ListPresets,
Response::ok_with(serde_json::json!(["default", "office"])),
),
(
Command::CurrentPreset,
Response::ok_with(serde_json::json!("office")),
),
(
Command::GetConfig { path: None },
Response::ok_with(serde_json::json!({"marker": 42})),
),
(Command::ConfigPath, config_path_reply),
(Command::DaemonInfo, daemon_info_reply),
]
}
fn v4l2_info(device: &str) -> Response {
Response::ok_with(serde_json::json!({"output": {"kind": "v4l2", "device": device}}))
}
fn run_handshake(script: Vec<(Command, Response)>) -> Result<InitialState, String> {
let (ours, peer) = UnixStream::pair().expect("socket pair");
let mut stream = BufferedStream::from_stream(ours, READ_TIMEOUT).expect("wrap");
let daemon = spawn_mock_daemon(peer, script);
let result = handshake(&mut stream);
daemon.join().expect("mock daemon thread");
result
}
#[test]
fn handshake_collects_all_replies() {
let initial = run_handshake(handshake_script(
Response::ok_with(serde_json::json!({"path": "/etc/fluxframe.toml"})),
v4l2_info("/dev/video11"),
))
.expect("handshake succeeds");
assert_eq!(
initial.daemon_info.map(|i| i.output),
Some(OutputInfo::V4l2 {
device: PathBuf::from("/dev/video11")
})
);
assert_eq!(initial.presets, vec!["default", "office"]);
assert_eq!(initial.active_preset, "office");
assert_eq!(initial.active_config, serde_json::json!({"marker": 42}));
assert_eq!(initial.inventory.build_features, vec!["ml".to_string()]);
assert_eq!(
initial.config_path,
Some(PathBuf::from("/etc/fluxframe.toml"))
);
}
#[test]
fn handshake_tolerates_refused_config_path() {
let initial = run_handshake(handshake_script(
Response::err("unknown command", None),
v4l2_info("/dev/video10"),
))
.expect("refused config_path must not fail the handshake");
assert_eq!(initial.config_path, None);
assert_eq!(initial.active_preset, "office");
}
#[test]
fn handshake_tolerates_refused_daemon_info() {
let initial = run_handshake(handshake_script(
Response::ok_with(serde_json::Value::Null),
Response::err("invalid command: unknown variant `daemon_info`", None),
))
.expect("refused daemon_info must not fail the handshake");
assert_eq!(initial.daemon_info, None);
assert_eq!(initial.active_preset, "office");
}
#[test]
fn handshake_fails_on_refused_list_effects() {
let Err(err) = run_handshake(vec![(
Command::ListEffects,
Response::err("boom", Some("restart".to_string())),
)]) else {
panic!("refused list_effects must fail the handshake");
};
assert!(err.contains("list_effects"), "got: {err}");
assert!(err.contains("boom"), "got: {err}");
}
#[test]
fn parse_config_path_decodes_daemon_shapes() {
assert_eq!(parse_config_path(&serde_json::Value::Null), None);
assert_eq!(
parse_config_path(&serde_json::json!({"path": "/x"})),
Some(PathBuf::from("/x"))
);
assert_eq!(parse_config_path(&serde_json::json!({})), None);
}
}