use crate::error::Error;
use crate::transport::{Transport, WebSocketTransport, HttpTransport};
use super::{Client, ClientOptions, ClientCapabilities};
pub struct ClientBuilder {
options: ClientOptions,
websocket_url: Option<String>,
http_url: Option<String>,
transport: Option<Box<dyn Transport + Send + Sync>>,
}
impl Default for ClientBuilder {
fn default() -> Self {
Self {
options: ClientOptions::default(),
websocket_url: None,
http_url: None,
transport: None,
}
}
}
impl ClientBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn with_implementation(mut self, name: impl Into<String>, version: impl Into<String>) -> Self {
self.options.implementation.name = name.into();
self.options.implementation.version = version.into();
self
}
pub fn with_capabilities(mut self, capabilities: ClientCapabilities) -> Self {
self.options.capabilities = capabilities;
self
}
pub fn with_roots(mut self, enable: bool) -> Self {
self.options.capabilities.roots = enable;
self
}
pub fn with_roots_list_changed(mut self, enable: bool) -> Self {
self.options.capabilities.roots_list_changed = enable;
self
}
pub fn with_sampling(mut self, enable: bool) -> Self {
self.options.capabilities.sampling = enable;
self
}
pub fn with_experimental(mut self, capability: impl Into<String>) -> Self {
self.options.capabilities.experimental.push(capability.into());
self
}
pub fn with_auto_acknowledge_roots_changed(mut self, enable: bool) -> Self {
self.options.auto_acknowledge_roots_changed = enable;
self
}
pub fn with_default_timeout(mut self, timeout_ms: u64) -> Self {
self.options.default_timeout_ms = timeout_ms;
self
}
pub fn with_websocket_url(mut self, url: impl Into<String>) -> Self {
self.websocket_url = Some(url.into());
self.http_url = None; self
}
pub fn with_http_url(mut self, url: impl Into<String>) -> Self {
self.http_url = Some(url.into());
self.websocket_url = None; self
}
pub fn with_transport(mut self, transport: Box<dyn Transport + Send + Sync>) -> Self {
self.transport = Some(transport);
self
}
pub fn build(self) -> Result<(Client, tokio::sync::mpsc::Receiver<super::ClientEvent>), Error> {
let transport: Box<dyn Transport + Send + Sync> = if let Some(transport) = self.transport {
transport
} else if let Some(url) = self.websocket_url {
Box::new(WebSocketTransport::new(&url)?)
} else if let Some(url) = self.http_url {
Box::new(HttpTransport::new(&url)?)
} else {
return Err(Error::ConfigError("No transport, WebSocket URL, or HTTP URL specified".to_string()));
};
Ok(Client::new(transport, self.options))
}
}