loveyu-kit 0.2.0

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

use ::elasticsearch::http::{
    Url,
    transport::{SingleNodeConnectionPool, TransportBuilder},
};

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

pub use ::elasticsearch::{
    Elasticsearch as ElasticsearchClient, auth::Credentials as ElasticsearchCredentials,
};

/// Elasticsearch 官方 HTTP 客户端连接器。
#[derive(Clone)]
#[must_use = "连接器配置需要传给 connect 才会生效"]
pub struct ElasticsearchConnector {
    name: String,
    enabled: bool,
    url: String,
    credentials: Option<ElasticsearchCredentials>,
    timeout: Duration,
}

impl ElasticsearchConnector {
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            name: "elasticsearch".to_owned(),
            enabled: true,
            url: url.into(),
            credentials: None,
            timeout: Duration::from_secs(10),
        }
    }

    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_credentials(mut self, credentials: ElasticsearchCredentials) -> Self {
        self.credentials = Some(credentials);
        self
    }

    /// 设置 Elasticsearch HTTP 请求的全局超时,默认 10 秒。
    pub const fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }
}

impl fmt::Debug for ElasticsearchConnector {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ElasticsearchConnector")
            .field("name", &self.name)
            .field("enabled", &self.enabled)
            .field("url", &"[已隐藏]")
            .field(
                "credentials",
                &self.credentials.as_ref().map(|_| "[已隐藏]"),
            )
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl ConnectionSpec for ElasticsearchConnector {
    type Connection = ElasticsearchClient;
    type Error = ConnectionError;

    fn name(&self) -> &str {
        &self.name
    }

    fn enabled(&self) -> bool {
        self.enabled
    }
}

impl Connect for ElasticsearchConnector {
    fn connect(&self) -> BoxConnectionFuture<'_, Self::Connection, Self::Error> {
        Box::pin(async move {
            if self.timeout.is_zero() {
                return Err(ConnectionError::InvalidConfig {
                    connector: "Elasticsearch",
                    message: "请求超时必须大于 0",
                });
            }
            let url = Url::parse(&self.url).map_err(|_| ConnectionError::InvalidConfig {
                connector: "Elasticsearch",
                message: "节点 URL 无法解析",
            })?;
            if !url.username().is_empty() || url.password().is_some() {
                return Err(ConnectionError::InvalidConfig {
                    connector: "Elasticsearch",
                    message: "节点 URL 不能包含用户名或密码,请使用 with_credentials",
                });
            }
            let mut builder =
                TransportBuilder::new(SingleNodeConnectionPool::new(url)).timeout(self.timeout);
            if let Some(credentials) = self.credentials.clone() {
                builder = builder.auth(credentials);
            }
            let transport = builder.build().map_err(::elasticsearch::Error::from)?;
            Ok(ElasticsearchClient::new(transport))
        })
    }
}

impl Verify for ElasticsearchConnector {
    fn verify<'a>(
        &'a self,
        connection: &'a Self::Connection,
    ) -> BoxConnectionFuture<'a, (), Self::Error> {
        Box::pin(async move {
            let response = connection.ping().send().await?;
            let status = response.status_code();
            if !status.is_success() {
                return Err(ConnectionError::ElasticsearchHealth(status.as_u16()));
            }
            Ok(())
        })
    }
}

impl Close for ElasticsearchConnector {
    fn close(&self, connection: Self::Connection) -> BoxConnectionFuture<'_, (), Self::Error> {
        Box::pin(async move {
            // HTTP 连接池没有异步关闭 API,释放客户端后由底层传输层回收连接。
            drop(connection);
            Ok(())
        })
    }
}