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,
};
#[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
}
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 {
drop(connection);
Ok(())
})
}
}