use std::time::Duration;
use reqwest::{Client, header::HeaderValue};
use serde::Serialize;
use qql_core::error::QqlError;
use crate::client::AliasAction;
pub const ROUTE_AFFINITY_HEADER: &str = "X-Qdrant-Route-Affinity";
#[derive(Clone)]
pub struct RestQdrant {
pub(crate) base_url: String,
pub(crate) api_key: Option<String>,
pub(crate) route_affinity: Option<String>,
pub(crate) api_key_header: Option<HeaderValue>,
pub(crate) affinity_header: Option<HeaderValue>,
pub(crate) client: Client,
}
fn preparse_header(value: Option<&str>) -> Option<HeaderValue> {
value.and_then(|v| HeaderValue::from_str(v).ok())
}
impl std::fmt::Debug for RestQdrant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RestQdrant")
.field("base_url", &self.base_url)
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
.field("route_affinity", &self.route_affinity)
.field(
"api_key_header",
&self.api_key_header.as_ref().map(|_| "<redacted>"),
)
.field(
"affinity_header",
&self.affinity_header.as_ref().map(|_| "<redacted>"),
)
.field("client", &self.client)
.finish()
}
}
impl RestQdrant {
pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {
let base_url = base_url.into();
Self::with_timeout(base_url.clone(), api_key.clone(), Duration::from_secs(30))
.unwrap_or_else(|_| Self::with_client(base_url, api_key, Client::new()))
}
pub fn with_timeout(
base_url: impl Into<String>,
api_key: Option<String>,
timeout: Duration,
) -> Result<Self, QqlError> {
let base_url = base_url.into();
let client = Client::builder()
.timeout(timeout)
.connect_timeout(Duration::from_secs(10).min(timeout))
.build()
.map_err(|e| {
QqlError::transport(
"QQL-TRANSPORT-BUILD",
format!("failed to build HTTP client: {e}"),
None,
)
})?;
Ok(Self {
base_url: base_url.trim_end_matches('/').to_string(),
api_key_header: preparse_header(api_key.as_deref()),
affinity_header: None,
api_key,
route_affinity: None,
client,
})
}
pub fn with_client(base_url: String, api_key: Option<String>, client: Client) -> Self {
Self {
base_url: base_url.trim_end_matches('/').to_string(),
api_key_header: preparse_header(api_key.as_deref()),
affinity_header: None,
api_key,
route_affinity: None,
client,
}
}
pub fn with_read_timeout(
base_url: impl Into<String>,
api_key: Option<String>,
read_timeout: Duration,
) -> Result<Self, QqlError> {
let base_url = base_url.into();
let client = Client::builder()
.connect_timeout(Duration::from_secs(10))
.read_timeout(read_timeout)
.build()
.map_err(|e| {
QqlError::transport(
"QQL-TRANSPORT-BUILD",
format!("failed to build HTTP client: {e}"),
None,
)
})?;
Ok(Self {
base_url: base_url.trim_end_matches('/').to_string(),
api_key_header: preparse_header(api_key.as_deref()),
affinity_header: None,
api_key,
route_affinity: None,
client,
})
}
pub fn with_route_affinity(mut self, affinity: impl Into<String>) -> Self {
let value = affinity.into();
self.route_affinity = if value.is_empty() { None } else { Some(value) };
self.affinity_header = preparse_header(self.route_affinity.as_deref());
self
}
pub fn route_affinity(&self) -> Option<&str> {
self.route_affinity.as_deref()
}
}
#[derive(Debug, Clone, Serialize)]
pub(crate) struct ChangeAliasesBody {
actions: Vec<ChangeAliasesAction>,
}
#[derive(Debug, Clone, Serialize)]
enum ChangeAliasesAction {
#[serde(rename = "delete_alias")]
DeleteAlias { alias_name: String },
#[serde(rename = "create_alias")]
CreateAlias {
collection_name: String,
alias_name: String,
},
}
impl ChangeAliasesBody {
pub(crate) fn from_actions(actions: &[AliasAction]) -> Self {
Self {
actions: actions
.iter()
.map(|action| match action {
AliasAction::Delete { alias } => ChangeAliasesAction::DeleteAlias {
alias_name: alias.clone(),
},
AliasAction::Create { collection, alias } => ChangeAliasesAction::CreateAlias {
collection_name: collection.clone(),
alias_name: alias.clone(),
},
})
.collect(),
}
}
}
pub(crate) fn http_method(method: qql_plan::types::Method) -> reqwest::Method {
match method {
qql_plan::types::Method::Get => reqwest::Method::GET,
qql_plan::types::Method::Post => reqwest::Method::POST,
qql_plan::types::Method::Put => reqwest::Method::PUT,
qql_plan::types::Method::Patch => reqwest::Method::PATCH,
qql_plan::types::Method::Delete => reqwest::Method::DELETE,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn change_aliases_body_matches_alias_wire_shape() {
let body = ChangeAliasesBody::from_actions(&[
AliasAction::Delete {
alias: "old".into(),
},
AliasAction::Create {
collection: "docs".into(),
alias: "new".into(),
},
]);
let value = serde_json::to_value(&body).expect("serializes");
assert_eq!(
value,
serde_json::json!({
"actions": [
{"delete_alias": {"alias_name": "old"}},
{"create_alias": {"collection_name": "docs", "alias_name": "new"}},
],
})
);
}
}