Files
zesdex/src/ipc/conn.rs
T

52 lines
1.9 KiB
Rust
Raw Normal View History

//! Framed Unix-socket connection shared by both the server (`server.rs`)
//! and client (`client.rs`) sides of the IPC layer.
//!
//! Flow: `Connection` wraps a `UnixStream` (either accepted by the server
//! or dialed by the client) → `send` serializes a value to JSON and
//! writes it as one length-prefixed frame (`frame::write_frame`) →
//! `receive` reads one frame and deserializes it back to the caller's
//! type, propagating a clean peer-close as `Ok(None)`.
use std::os::unix::net::UnixStream;
use anyhow::Result;
use super::frame;
/// A framed Unix-socket connection shared by client and server sides of
/// the IPC layer; each `send`/`receive` moves one length-prefixed JSON frame.
pub struct Connection {
inner: UnixStream,
}
impl Connection {
/// Wrap an already-connected/accepted `UnixStream`.
pub fn from_stream(stream: UnixStream) -> Result<Self> {
Ok(Connection { inner: stream })
}
/// Open a new Unix-socket connection to `path`.
pub fn connect_unix(path: &str) -> Result<Self> {
let stream = UnixStream::connect(path)?;
Ok(Connection { inner: stream })
}
/// Serialize `value` to JSON and write it as one length-prefixed frame.
pub fn send<T: serde::Serialize>(&mut self, value: &T) -> Result<()> {
let data = frame::serialize_frame(value)?;
frame::write_frame(&mut self.inner, &data)
}
/// Read one length-prefixed frame and deserialize it as `T`.
///
/// Return: `Ok(None)` on clean EOF (peer closed the connection).
pub fn receive<T: serde::de::DeserializeOwned>(&mut self) -> Result<Option<T>> {
let data = frame::read_frame(&mut self.inner)?;
match data {
Some(bytes) => {
let value: T = frame::deserialize_frame(&bytes)?;
Ok(Some(value))
}
None => Ok(None),
}
}
}