horust_commands_lib/
lib.rs

1extern crate core;
2
3mod client;
4#[rustfmt::skip]
5mod proto;
6mod server;
7use crate::proto::messages::HorustMsgMessage;
8pub use crate::proto::messages::HorustMsgServiceStatus;
9use anyhow::{Context, Result};
10pub use client::ClientHandler;
11use log::debug;
12use prost::Message;
13pub use server::CommandsHandlerTrait;
14use std::io::{Read, Write};
15use std::os::unix::net::UnixStream;
16use std::path::{Path, PathBuf};
17
18/// socket_name should be the pid of the horust process.
19pub fn get_path(socket_folder_path: &Path, horust_pid: i32) -> PathBuf {
20    socket_folder_path.join(format!("horust-{horust_pid}.sock"))
21}
22
23pub struct UdsConnectionHandler {
24    socket: UnixStream,
25}
26impl UdsConnectionHandler {
27    pub fn new(socket: UnixStream) -> Self {
28        Self { socket }
29    }
30    pub fn send_message(&mut self, message: HorustMsgMessage) -> Result<()> {
31        debug!("Sending message: {:?}", message);
32        let mut buf = Vec::new();
33        // Serialize the message into a byte array.
34        message.encode(&mut buf)?;
35        self.socket
36            .write_all(&buf)
37            .context("Failed at writing onto the unix stream")?;
38        Ok(())
39    }
40    pub fn receive_message(&mut self) -> Result<HorustMsgMessage> {
41        let mut buf = Vec::new();
42        self.socket.read_to_end(&mut buf)?;
43        let received = HorustMsgMessage::decode(buf.as_slice())?;
44        debug!("Received message: {:?}", received);
45        Ok(received)
46    }
47}