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, 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 {
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>,
}
const READ_TIMEOUT: Duration = Duration::from_secs(5);
pub struct IpcWorker {
stream: Option<BufferedStream>,
}
struct BufferedStream {
reader: BufReader<UnixStream>,
writer: UnixStream,
}
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");
stream.set_read_timeout(Some(READ_TIMEOUT))?;
let writer = stream.try_clone()?;
Ok(Self {
reader: BufReader::new(stream),
writer,
})
}
#[tracing::instrument(skip(self), level = "debug")]
fn round_trip(&mut self, cmd: &Command) -> Result<Response, String> {
tracing::debug!(?cmd, "ipc round trip start");
let payload =
serde_json::to_string(cmd).map_err(|e| format!("serialise command failed: {e}"))?;
self.writer
.write_all(payload.as_bytes())
.and_then(|()| self.writer.write_all(b"\n"))
.and_then(|()| self.writer.flush())
.map_err(|e| format!("write failed: {e}"))?;
let mut line = String::new();
let n = self
.reader
.read_line(&mut line)
.map_err(|e| format!("read failed: {e}"))?;
if n == 0 {
return Err("daemon closed the connection".into());
}
serde_json::from_str::<Response>(line.trim_end())
.map_err(|e| format!("parse response failed: {e}"))
}
}
impl Worker for IpcWorker {
type Init = PathBuf;
type Input = WorkerInput;
type Output = WorkerOutput;
fn init(socket_path: Self::Init, sender: ComponentSender<Self>) -> Self {
match BufferedStream::connect(&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 });
Self { stream: None }
}
},
Err(e) => {
let _ = sender.output(WorkerOutput::Disconnected {
reason: format!("connect to {} failed: {e}", socket_path.display()),
});
Self { stream: None }
}
}
}
fn update(&mut self, msg: Self::Input, sender: ComponentSender<Self>) {
let WorkerInput::Send { tag, command } = msg;
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(reason) => {
self.stream = None;
let _ = sender.output(WorkerOutput::Reply {
tag,
response: Response::err(reason.clone(), None),
});
let _ = sender.output(WorkerOutput::Disconnected { reason });
}
}
}
}
#[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}")),
};
Ok(InitialState {
inventory,
presets,
active_preset,
active_config,
config_path,
})
}
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)? {
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})"))
}