use std::{fmt, time::Duration};
use super::{BoxConnectionFuture, Close, Connect, ConnectionError, ConnectionSpec, Verify};
pub use etcd_client::{Client as EtcdClient, ConnectOptions as EtcdConnectOptions};
#[derive(Clone)]
#[must_use = "连接器配置需要传给 connect 才会生效"]
pub struct EtcdConnector {
name: String,
enabled: bool,
endpoints: Vec<String>,
options: Option<EtcdConnectOptions>,
}
impl EtcdConnector {
pub fn new<I, S>(endpoints: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
name: "etcd".to_owned(),
enabled: true,
endpoints: endpoints.into_iter().map(Into::into).collect(),
options: Some(
EtcdConnectOptions::new()
.with_connect_timeout(Duration::from_secs(5))
.with_timeout(Duration::from_secs(5)),
),
}
}
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
pub const fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn with_options(mut self, options: EtcdConnectOptions) -> Self {
self.options = Some(options);
self
}
}
impl fmt::Debug for EtcdConnector {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("EtcdConnector")
.field("name", &self.name)
.field("enabled", &self.enabled)
.field("endpoint_count", &self.endpoints.len())
.field("options", &self.options.as_ref().map(|_| "[已隐藏]"))
.finish()
}
}
impl ConnectionSpec for EtcdConnector {
type Connection = EtcdClient;
type Error = ConnectionError;
fn name(&self) -> &str {
&self.name
}
fn enabled(&self) -> bool {
self.enabled
}
}
impl Connect for EtcdConnector {
fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
Box::pin(async move {
if self.endpoints.is_empty()
|| self
.endpoints
.iter()
.any(|endpoint| endpoint.trim().is_empty())
{
return Err(ConnectionError::InvalidConfig {
connector: "etcd",
message: "至少需要一个非空节点地址",
});
}
EtcdClient::connect(&self.endpoints, self.options.clone())
.await
.map_err(Into::into)
})
}
}
impl Verify for EtcdConnector {
fn verify<'a>(
&'a self,
connection: &'a Self::Connection,
) -> BoxConnectionFuture<'a, (), Self::Error> {
Box::pin(async move {
let mut client = connection.clone();
client.status().await?;
Ok(())
})
}
}
impl Close for EtcdConnector {
fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
Box::pin(async move {
drop(connection);
Ok(())
})
}
}