taskers_control/
client.rs1use std::path::{Path, PathBuf};
2
3use anyhow::Result;
4use serde_json::{from_slice, to_vec};
5use tokio::{
6 io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
7 net::UnixStream,
8};
9
10use crate::protocol::{ControlCommand, RequestFrame, ResponseFrame};
11
12#[derive(Debug, Clone)]
13pub struct ControlClient {
14 socket_path: PathBuf,
15}
16
17impl ControlClient {
18 pub fn new(socket_path: impl Into<PathBuf>) -> Self {
19 Self {
20 socket_path: socket_path.into(),
21 }
22 }
23
24 pub fn socket_path(&self) -> &Path {
25 &self.socket_path
26 }
27
28 pub async fn send(&self, command: ControlCommand) -> Result<ResponseFrame> {
29 let mut stream = UnixStream::connect(&self.socket_path).await?;
30 let request = RequestFrame::new(command);
31 let payload = to_vec(&request)?;
32
33 stream.write_all(&payload).await?;
34 stream.write_all(b"\n").await?;
35 stream.flush().await?;
36
37 let mut reader = BufReader::new(stream);
38 let mut response = String::new();
39 reader.read_line(&mut response).await?;
40
41 Ok(from_slice(response.trim_end().as_bytes())?)
42 }
43}