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 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),
}
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}"),
}
}
}
impl core::error::Error for RequestError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Wire(err) => Some(err),
Self::Rpc(_) | Self::Timeout { .. } | Self::Closed => None,
}
}
}
pub struct Client {
commands: mpsc::Sender<Command>,
ack: HelloAck,
socket: PathBuf,
}
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)
.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(),
})
}
#[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 + 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)
}