use std::fmt;
use serde_json::Value;
pub type TransportError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Transport(TransportError),
Elasticsearch(Box<ElasticsearchError>),
License(Box<LicenseError>),
Conflict(Box<ElasticsearchError>),
Encode(serde_json::Error),
Parameter(String),
Decode {
status: u16,
source: serde_json::Error,
body: String,
},
Row(Box<RowError>),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Transport(e) => write!(f, "transport: {e}"),
Error::Elasticsearch(e) => e.fmt(f),
Error::License(e) => e.fmt(f),
Error::Conflict(e) => e.fmt(f),
Error::Encode(e) => write!(f, "writing the request: {e}"),
Error::Parameter(e) => write!(f, "parameters: {e}"),
Error::Decode {
status,
source,
body,
} => {
write!(f, "reading a {status} response: {source}: {body}")
}
Error::Row(e) => e.fmt(f),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Error::Transport(e) => Some(e.as_ref()),
Error::Encode(e) | Error::Decode { source: e, .. } => Some(e),
_ => None,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct RowError {
pub row: usize,
pub column: Option<String>,
pub message: String,
pub columns: Vec<String>,
}
impl RowError {
pub fn new(
row: usize,
column: Option<String>,
message: impl Into<String>,
columns: Vec<String>,
) -> RowError {
RowError {
row,
column,
message: message.into(),
columns,
}
}
}
impl fmt::Display for RowError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "reading row {}", self.row)?;
if let Some(column) = &self.column {
write!(f, ", column `{column}`")?;
}
write!(
f,
": {} (the columns are {})",
self.message,
self.columns.join(", ")
)
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct ElasticsearchError {
pub status: u16,
pub response: Option<crate::ErrorResponseBase>,
pub body: Value,
}
impl ElasticsearchError {
pub fn error_type(&self) -> Option<&str> {
self.body.pointer("/error/type").and_then(Value::as_str)
}
pub fn reason(&self) -> Option<&str> {
self.body.pointer("/error/reason").and_then(Value::as_str)
}
pub fn causes(&self) -> impl Iterator<Item = &crate::ErrorCause> {
std::iter::successors(
self.response.as_ref().and_then(|r| r.error.as_ref()),
|cause| cause.caused_by.as_deref(),
)
}
}
impl fmt::Display for ElasticsearchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Elasticsearch answered {}", self.status)?;
if let Some(kind) = self.error_type() {
write!(f, ": {kind}")?;
}
if let Some(reason) = self.reason() {
write!(f, ": {reason}")?;
}
Ok(())
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LicenseError {
pub feature: String,
pub error: ElasticsearchError,
}
impl fmt::Display for LicenseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "the cluster's license doesn't include {}", self.feature)
}
}
impl Error {
pub fn from_response(status: u16, body: &[u8]) -> Error {
let body: Value = serde_json::from_slice(body)
.unwrap_or_else(|_| Value::String(String::from_utf8_lossy(body).into_owned()));
let response = serde_json::from_value(body.clone()).ok();
let error = ElasticsearchError {
status,
response,
body,
};
let feature = error
.body
.pointer("/error/root_cause")
.and_then(Value::as_array)
.into_iter()
.flatten()
.chain(error.body.get("error"))
.find_map(|cause| cause.get("license.expired.feature"))
.and_then(Value::as_str)
.map(str::to_owned)
.or_else(|| error.reason().and_then(unlicensed_feature));
match feature {
Some(feature) => Error::License(Box::new(LicenseError { feature, error })),
None if status == 409 => Error::Conflict(Box::new(error)),
None => Error::Elasticsearch(Box::new(error)),
}
}
}
fn unlicensed_feature(reason: &str) -> Option<String> {
const MARKER: &str = "license is non-compliant for ";
let start = reason.to_ascii_lowercase().find(MARKER)? + MARKER.len();
let rest = &reason[start..];
let feature = match rest.strip_prefix('[') {
Some(bracketed) => &bracketed[..bracketed.find(']')?],
None => rest.split(['.', ';']).next()?,
};
let feature = feature.trim();
(!feature.is_empty()).then(|| feature.to_owned())
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn error(body: Value) -> Error {
Error::from_response(403, body.to_string().as_bytes())
}
#[test]
fn license_errors_by_metadata() {
let body = json!({"error": {
"root_cause": [{"type": "security_exception", "reason": "current license is non-compliant for [Reciprocal Rank Fusion (RRF)]", "license.expired.feature": "Reciprocal Rank Fusion (RRF)"}],
"type": "security_exception",
"reason": "current license is non-compliant for [Reciprocal Rank Fusion (RRF)]"
}, "status": 403});
let Error::License(e) = error(body) else {
panic!("not a license error")
};
assert_eq!(e.feature, "Reciprocal Rank Fusion (RRF)");
}
#[test]
fn license_errors_by_reason() {
let body = json!({"error": {
"type": "security_exception",
"reason": "Current license is non-compliant for query rules. Current license is active basic license."
}, "status": 403});
let Error::License(e) = error(body) else {
panic!("not a license error")
};
assert_eq!(e.feature, "query rules");
}
#[test]
fn cause_chains() {
let body = json!({"error": {
"type": "search_phase_execution_exception",
"reason": "all shards failed",
"caused_by": {"type": "illegal_argument_exception", "reason": "bad field",
"caused_by": {"type": "number_format_exception", "reason": "For input string"}}
}, "status": 400});
let Error::Elasticsearch(e) = Error::from_response(400, body.to_string().as_bytes()) else {
panic!("not an Elasticsearch error")
};
let kinds: Vec<_> = e.causes().filter_map(|c| c.r#type.as_deref()).collect();
assert_eq!(
kinds,
[
"search_phase_execution_exception",
"illegal_argument_exception",
"number_format_exception"
]
);
}
#[test]
fn conflicts() {
let body = json!({"error": {"type": "version_conflict_engine_exception", "reason": "[1]: version conflict, required seqNo [0], primary term [1]. current document has seqNo [1] and primary term [1]"}, "status": 409});
let Error::Conflict(e) = Error::from_response(409, body.to_string().as_bytes()) else {
panic!("not a conflict")
};
assert_eq!(e.error_type(), Some("version_conflict_engine_exception"));
}
#[test]
fn other_errors() {
let body = json!({"error": {"type": "index_not_found_exception", "reason": "no such index [x]"}, "status": 404});
let Error::Elasticsearch(e) = Error::from_response(404, body.to_string().as_bytes()) else {
panic!("not an Elasticsearch error")
};
assert_eq!(e.error_type(), Some("index_not_found_exception"));
assert!(e.response.is_some());
}
}