use core::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;
use futures_util::{SinkExt, StreamExt};
use tokio::net::UnixStream;
use tokio_util::codec::{Framed, LengthDelimitedCodec};
use shep_core::protocol::{
Hello, HelloAck, HelloReply, PROTOCOL_VERSION, WireError, codec, decode_frame, encode_frame,
};
pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
pub(crate) type Frames = Framed<UnixStream, LengthDelimitedCodec>;
#[derive(Debug)]
#[non_exhaustive]
pub enum ConnectError {
Connect {
path: PathBuf,
source: std::io::Error,
},
Io(std::io::Error),
Wire(WireError),
HandshakeClosed,
HandshakeTimeout {
after: Duration,
},
ProtocolMismatch {
client: u32,
message: String,
},
}
impl fmt::Display for ConnectError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Connect { path, source } => {
write!(f, "could not connect to `{}`: {source}", path.display())
}
Self::Io(err) => write!(f, "connection I/O error: {err}"),
Self::Wire(err) => write!(f, "handshake frame error: {err}"),
Self::HandshakeClosed => {
f.write_str("the daemon closed the connection during the handshake")
}
Self::HandshakeTimeout { after } => {
write!(f, "the handshake did not complete within {after:?}")
}
Self::ProtocolMismatch { client, message } => {
write!(
f,
"protocol mismatch (this client speaks {client}): {message}"
)
}
}
}
}
impl core::error::Error for ConnectError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Connect { source, .. } | Self::Io(source) => Some(source),
Self::Wire(err) => Some(err),
Self::HandshakeClosed
| Self::HandshakeTimeout { .. }
| Self::ProtocolMismatch { .. } => None,
}
}
}
pub(crate) struct Connection {
frames: Frames,
ack: HelloAck,
}
impl fmt::Debug for Connection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Connection")
.field("ack", &self.ack)
.finish_non_exhaustive()
}
}
impl Connection {
pub(crate) async fn open(socket: &Path, timeout: Duration) -> Result<Self, ConnectError> {
tokio::time::timeout(timeout, Self::open_inner(socket))
.await
.map_err(|_elapsed| ConnectError::HandshakeTimeout { after: timeout })?
}
async fn open_inner(socket: &Path) -> Result<Self, ConnectError> {
let stream = UnixStream::connect(socket)
.await
.map_err(|source| ConnectError::Connect {
path: socket.to_path_buf(),
source,
})?;
let mut frames = Framed::new(stream, codec());
let hello = Hello {
client_version: env!("CARGO_PKG_VERSION").to_string(),
protocol: PROTOCOL_VERSION,
};
let payload = encode_frame(&hello).map_err(ConnectError::Wire)?;
frames.send(payload).await.map_err(ConnectError::Io)?;
let frame = frames
.next()
.await
.ok_or(ConnectError::HandshakeClosed)?
.map_err(ConnectError::Io)?;
let reply: HelloReply = decode_frame(&frame).map_err(ConnectError::Wire)?;
let ack = reply.map_err(|err| ConnectError::ProtocolMismatch {
client: PROTOCOL_VERSION,
message: err.message,
})?;
Ok(Self { frames, ack })
}
pub(crate) fn into_parts(self) -> (Frames, HelloAck) {
(self.frames, self.ack)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::fake_daemon;
use shep_core::protocol::{HelloAck, PROTOCOL_VERSION, RpcError, RpcErrorCode};
use tokio::net::UnixListener;
#[tokio::test]
async fn open_sends_hello_and_returns_the_ack() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("s.sock");
let ack = HelloAck {
daemon_version: "9.9.9".into(),
protocol: PROTOCOL_VERSION,
pid: 4242,
};
let served = fake_daemon(&path, Ok(ack.clone())).await;
let conn = Connection::open(&path, HANDSHAKE_TIMEOUT).await.unwrap();
let (_frames, actual_ack) = conn.into_parts();
assert_eq!(actual_ack, ack);
let hello = served.await.unwrap();
assert_eq!(
hello.protocol, PROTOCOL_VERSION,
"the client must announce the version it speaks"
);
assert_eq!(
hello.client_version,
env!("CARGO_PKG_VERSION"),
"the client must identify its own version"
);
}
#[tokio::test]
async fn a_protocol_refusal_becomes_its_own_error_variant() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("s.sock");
let refusal = RpcError {
code: RpcErrorCode::ProtocolMismatch,
message: "daemon speaks protocol 2, client speaks 1".into(),
};
let _served = fake_daemon(&path, Err(refusal)).await;
let err = Connection::open(&path, HANDSHAKE_TIMEOUT)
.await
.unwrap_err();
let ConnectError::ProtocolMismatch { client, message } = err else {
panic!("a protocol refusal must not be flattened into a generic error, got {err:?}");
};
assert_eq!(
client, PROTOCOL_VERSION,
"`client` is our own version, not the daemon's"
);
assert!(
message.contains("protocol 2"),
"the daemon's own message must survive: {message}"
);
}
#[tokio::test]
async fn a_daemon_that_closes_without_answering_is_not_a_silent_success() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("s.sock");
let listener = UnixListener::bind(&path).unwrap();
tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
drop(stream);
});
let err = Connection::open(&path, HANDSHAKE_TIMEOUT)
.await
.expect_err("a peer that closed without a HelloReply is not a connection");
assert!(
matches!(err, ConnectError::HandshakeClosed | ConnectError::Io(_)),
"a peer that closed mid-handshake must report as unreachable, got {err:?}"
);
}
#[tokio::test]
async fn connecting_to_a_missing_socket_names_the_path() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("absent.sock");
let ConnectError::Connect { path: reported, .. } =
Connection::open(&path, HANDSHAKE_TIMEOUT)
.await
.unwrap_err()
else {
panic!("a missing socket must report which path failed");
};
assert_eq!(reported, path);
}
#[tokio::test]
async fn a_socket_bound_but_never_accepted_from_times_out_rather_than_hanging() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("s.sock");
let _listener = UnixListener::bind(&path).unwrap();
let err = Connection::open(&path, Duration::from_millis(150))
.await
.unwrap_err();
let ConnectError::HandshakeTimeout { after } = err else {
panic!("a backlogged connect must time out, not hang or read as success; got {err:?}");
};
assert_eq!(after, Duration::from_millis(150));
}
}