use std::fmt;
use std::path::PathBuf;
use std::time::Duration;
use super::rmux::{connect_or_start_transport, connect_transport_to_endpoint, Rmux};
use crate::bootstrap::discovery;
use crate::{Result, RmuxEndpoint};
pub struct RmuxBuilder {
endpoint: RmuxEndpoint,
default_timeout: Option<Duration>,
}
impl RmuxBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn endpoint(mut self, endpoint: RmuxEndpoint) -> Self {
self.endpoint = endpoint;
self
}
#[must_use]
pub fn unix_socket(self, path: impl Into<PathBuf>) -> Self {
self.endpoint(RmuxEndpoint::UnixSocket(path.into()))
}
#[must_use]
pub fn windows_pipe(self, pipe: impl Into<String>) -> Self {
self.endpoint(RmuxEndpoint::WindowsPipe(pipe.into()))
}
#[must_use]
pub fn default_endpoint(self) -> Self {
self.endpoint(RmuxEndpoint::Default)
}
#[must_use]
pub fn default_timeout(mut self, timeout: Duration) -> Self {
self.default_timeout = Some(timeout);
self
}
#[must_use]
pub fn configured_endpoint(&self) -> &RmuxEndpoint {
&self.endpoint
}
#[must_use]
pub const fn configured_default_timeout(&self) -> Option<Duration> {
self.default_timeout
}
pub fn resolved_endpoint(&self) -> Result<RmuxEndpoint> {
discovery::resolve_endpoint(&self.endpoint)
}
#[must_use]
pub fn resolved_timeout(&self, per_operation_timeout: Option<Duration>) -> Option<Duration> {
discovery::resolve_timeout(per_operation_timeout, self.default_timeout)
}
#[must_use]
pub fn build(self) -> Rmux {
Rmux::from_config(self.endpoint, self.default_timeout)
}
pub async fn connect(self) -> Result<Rmux> {
let endpoint = discovery::resolve_endpoint(&self.endpoint)?;
let timeout = discovery::resolve_timeout(None, self.default_timeout);
let transport = connect_transport_to_endpoint(&endpoint, timeout).await?;
Ok(Rmux::from_connected_transport(
endpoint,
self.default_timeout,
transport,
))
}
pub async fn connect_or_start(self) -> Result<Rmux> {
let endpoint = discovery::resolve_endpoint(&self.endpoint)?;
let transport = connect_or_start_transport(&endpoint, self.default_timeout).await?;
Ok(Rmux::from_connected_transport(
endpoint,
self.default_timeout,
transport,
))
}
}
impl Default for RmuxBuilder {
fn default() -> Self {
Self {
endpoint: RmuxEndpoint::Default,
default_timeout: None,
}
}
}
impl fmt::Debug for RmuxBuilder {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("RmuxBuilder")
.finish_non_exhaustive()
}
}