use core::fmt;
use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot};
use shep_core::protocol::{HelloAck, Request, Response, RpcError, WireError};
use crate::actor::{self, Command};
use crate::connection::{ConnectError, Connection, HANDSHAKE_TIMEOUT};
use crate::events::EventStream;
pub const DEFAULT_DEADLINE: Duration = Duration::from_secs(5);
pub const START_DEADLINE: Duration = Duration::from_secs(30);
pub const RELOAD_DEADLINE: Duration = Duration::from_secs(60);
pub const LOG_PLANE_DEADLINE: Duration = Duration::from_secs(30);
pub const TRIGGER_DEADLINE: Duration = Duration::from_secs(60);
pub const DEADLINE_GRACE: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum RequestError {
Rpc(RpcError),
Timeout {
after: Duration,
},
Closed,
Wire(WireError),
Undecodable(WireError),
UnexpectedReply {
asked: &'static str,
answered: &'static str,
},
}
impl RequestError {
#[must_use]
pub const fn exit_code(&self) -> u8 {
use shep_core::exit;
match self {
Self::Rpc(rpc) => rpc.code.exit_code(),
Self::Timeout { .. } => exit::DEADLINE_EXCEEDED,
Self::Closed => exit::DAEMON_UNREACHABLE,
Self::Wire(_) | Self::UnexpectedReply { .. } => exit::INTERNAL,
Self::Undecodable(_) => exit::FAILURE,
}
}
}
impl fmt::Display for RequestError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rpc(err) => write!(f, "the daemon reported {:?}: {}", err.code, err.message),
Self::Timeout { after } => write!(f, "no reply within {after:?}"),
Self::Closed => f.write_str("the connection closed before a reply arrived"),
Self::Wire(err) => write!(f, "request frame error: {err}"),
Self::Undecodable(err) => write!(
f,
"this client could not decode the daemon's reply ({err}); the daemon is likely newer than this build"
),
Self::UnexpectedReply { asked, answered } => {
write!(f, "the daemon answered {asked} with {answered}")
}
}
}
}
impl core::error::Error for RequestError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Wire(err) | Self::Undecodable(err) => Some(err),
Self::Rpc(_) | Self::Timeout { .. } | Self::Closed | Self::UnexpectedReply { .. } => {
None
}
}
}
}
pub struct Client {
commands: mpsc::Sender<Command>,
ack: HelloAck,
socket: PathBuf,
dog_name: Option<String>,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("socket", &self.socket)
.field("ack", &self.ack)
.field("dog_name", &self.dog_name)
.finish_non_exhaustive()
}
}
impl Client {
pub async fn connect(socket: &Path) -> Result<Self, ConnectError> {
Self::connect_with_timeout(socket, HANDSHAKE_TIMEOUT).await
}
pub async fn connect_with_timeout(
socket: &Path,
timeout: Duration,
) -> Result<Self, ConnectError> {
Self::connect_as(socket, timeout, None).await
}
pub(crate) async fn connect_as(
socket: &Path,
timeout: Duration,
dog_name: Option<&str>,
) -> Result<Self, ConnectError> {
let connection = Connection::open(socket, timeout, dog_name).await?;
let (frames, ack) = connection.into_parts();
let commands = actor::spawn(frames);
Ok(Self {
commands,
ack,
socket: socket.to_path_buf(),
dog_name: dog_name.map(str::to_owned),
})
}
pub(crate) fn dog_name(&self) -> Option<&str> {
self.dog_name.as_deref()
}
pub(crate) fn replace_connection(&mut self, fresh: Self) {
*self = fresh;
}
#[must_use]
pub fn daemon(&self) -> &HelloAck {
&self.ack
}
pub async fn closed(&self) {
self.commands.closed().await;
}
#[must_use]
pub fn socket(&self) -> &Path {
&self.socket
}
pub async fn request(&self, body: Request) -> Result<Response, RequestError> {
self.request_with_deadline(body, None).await
}
pub async fn request_with_deadline(
&self,
body: Request,
deadline: Option<Duration>,
) -> Result<Response, RequestError> {
let deadline = deadline.unwrap_or(DEFAULT_DEADLINE);
let (reply_to, reply_rx) = oneshot::channel();
self.commands
.send(Command::Request {
body,
deadline_ms: Some(millis(deadline)),
reply_to,
})
.await
.map_err(|_send_error| RequestError::Closed)?;
let budget = deadline.saturating_add(DEADLINE_GRACE);
match tokio::time::timeout(budget, reply_rx).await {
Ok(Ok(outcome)) => outcome,
Ok(Err(_recv_error)) => Err(RequestError::Closed),
Err(_elapsed) => Err(RequestError::Timeout { after: budget }),
}
}
pub async fn subscribe(&self, topics: Vec<String>) -> Result<EventStream, RequestError> {
let (reply_to, reply_rx) = oneshot::channel();
self.commands
.send(Command::Subscribe { reply_to })
.await
.map_err(|_send_error| RequestError::Closed)?;
let receiver = reply_rx.await.map_err(|_recv_error| RequestError::Closed)?;
self.request(Request::Subscribe { topics }).await?;
Ok(EventStream::new(receiver))
}
pub async fn close(self) -> Result<(), RequestError> {
drop(self.commands);
Ok(())
}
}
fn millis(d: Duration) -> u64 {
u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
}
#[cfg(test)]
mod tests {
use shep_core::exit;
use shep_core::protocol::RpcErrorCode;
use super::*;
#[test]
fn a_request_error_exits_on_its_causes_code() {
let unsupported = RequestError::Rpc(RpcError {
code: RpcErrorCode::Unsupported,
message: "no such verb".to_owned(),
daemon_version: None,
});
let cases = [
(unsupported, exit::UNSUPPORTED),
(RequestError::Closed, exit::DAEMON_UNREACHABLE),
(
RequestError::Timeout {
after: Duration::from_secs(7),
},
exit::DEADLINE_EXCEEDED,
),
(
RequestError::UnexpectedReply {
asked: "ListFlock",
answered: "Pong",
},
exit::INTERNAL,
),
];
for (err, code) in cases {
assert_eq!(err.exit_code(), code, "{err}");
}
}
}