loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
use std::{fmt, time::Duration};

use super::{BoxConnectionFuture, Close, Connect, ConnectionError, ConnectionSpec, Verify};

pub use etcd_client::{Client as EtcdClient, ConnectOptions as EtcdConnectOptions};

/// etcd v3 客户端连接器。
#[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())
            // ConnectOptions 可能包含账号和密码,不能直接输出。
            .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 {
            // etcd-client 没有显式关闭 API,释放最后一个客户端句柄即可关闭底层通道。
            drop(connection);
            Ok(())
        })
    }
}