//! 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) -> Self { Connection { inner: stream } } /// Open a new Unix-socket connection to `path`. pub fn connect_unix(path: &str) -> Result { let stream = UnixStream::connect(path)?; Ok(Connection { inner: stream }) } /// Serialize `value` to JSON and write it as one length-prefixed frame. pub fn send(&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(&mut self) -> Result> { 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), } } }