Skip to main content

oxsearch_core/
error.rs

1//! What can go wrong in a call.
2
3use std::fmt;
4
5use serde_json::Value;
6
7/// An error from a transport: the request couldn't be sent, or no response
8/// came back.
9pub type TransportError = Box<dyn std::error::Error + Send + Sync>;
10
11/// What can go wrong in a call.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum Error {
15    /// The request couldn't be sent, or no response came back.
16    Transport(TransportError),
17    /// Elasticsearch answered with an error.
18    Elasticsearch(Box<ElasticsearchError>),
19    /// The cluster's license doesn't include a feature the request uses,
20    /// such as server-side RRF on the Basic license.
21    License(Box<LicenseError>),
22    /// A write conditional on a document's version found another version:
23    /// the document changed since it was read (status 409).
24    Conflict(Box<ElasticsearchError>),
25    /// The request couldn't be written as JSON.
26    Encode(serde_json::Error),
27    /// A parameter can't be written in a URL, or no URL fits the parameters
28    /// set.
29    Parameter(String),
30    /// The response didn't fit the type it was read into.
31    Decode {
32        /// The response's status code.
33        status: u16,
34        /// What didn't fit.
35        source: serde_json::Error,
36        /// The start of the response, for diagnosis.
37        body: String,
38    },
39    /// A row of a tabular result, such as an ES|QL query's, didn't fit the
40    /// type it was read into.
41    Row(Box<RowError>),
42}
43
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Error::Transport(e) => write!(f, "transport: {e}"),
48            Error::Elasticsearch(e) => e.fmt(f),
49            Error::License(e) => e.fmt(f),
50            Error::Conflict(e) => e.fmt(f),
51            Error::Encode(e) => write!(f, "writing the request: {e}"),
52            Error::Parameter(e) => write!(f, "parameters: {e}"),
53            Error::Decode {
54                status,
55                source,
56                body,
57            } => {
58                write!(f, "reading a {status} response: {source}: {body}")
59            }
60            Error::Row(e) => e.fmt(f),
61        }
62    }
63}
64
65impl std::error::Error for Error {
66    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
67        match self {
68            Error::Transport(e) => Some(e.as_ref()),
69            Error::Encode(e) | Error::Decode { source: e, .. } => Some(e),
70            _ => None,
71        }
72    }
73}
74
75/// A row of a tabular result that didn't fit the type it was read into.
76#[derive(Debug)]
77#[non_exhaustive]
78pub struct RowError {
79    /// The row, counted from 0.
80    pub row: usize,
81    /// The column that didn't fit, if one did: a nested field's is dotted
82    /// (`author.name`).
83    pub column: Option<String>,
84    /// What didn't fit, such as `missing field `price``.
85    pub message: String,
86    /// The result's columns.
87    pub columns: Vec<String>,
88}
89
90impl RowError {
91    /// The error for a row.
92    pub fn new(
93        row: usize,
94        column: Option<String>,
95        message: impl Into<String>,
96        columns: Vec<String>,
97    ) -> RowError {
98        RowError {
99            row,
100            column,
101            message: message.into(),
102            columns,
103        }
104    }
105}
106
107impl fmt::Display for RowError {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        write!(f, "reading row {}", self.row)?;
110        if let Some(column) = &self.column {
111            write!(f, ", column `{column}`")?;
112        }
113        write!(
114            f,
115            ": {} (the columns are {})",
116            self.message,
117            self.columns.join(", ")
118        )
119    }
120}
121
122/// An error response from Elasticsearch.
123#[derive(Debug)]
124#[non_exhaustive]
125pub struct ElasticsearchError {
126    /// The status code.
127    pub status: u16,
128    /// The error, as Elasticsearch describes it, when the body is one.
129    pub response: Option<crate::ErrorResponseBase>,
130    /// The body, as JSON when it is JSON.
131    pub body: Value,
132}
133
134impl ElasticsearchError {
135    /// The error's type, such as `index_not_found_exception`.
136    pub fn error_type(&self) -> Option<&str> {
137        self.body.pointer("/error/type").and_then(Value::as_str)
138    }
139
140    /// Why it happened.
141    pub fn reason(&self) -> Option<&str> {
142        self.body.pointer("/error/reason").and_then(Value::as_str)
143    }
144
145    /// The error and what caused it, outermost first: the chain of
146    /// `caused_by`.
147    pub fn causes(&self) -> impl Iterator<Item = &crate::ErrorCause> {
148        std::iter::successors(
149            self.response.as_ref().and_then(|r| r.error.as_ref()),
150            |cause| cause.caused_by.as_deref(),
151        )
152    }
153}
154
155impl fmt::Display for ElasticsearchError {
156    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157        write!(f, "Elasticsearch answered {}", self.status)?;
158        if let Some(kind) = self.error_type() {
159            write!(f, ": {kind}")?;
160        }
161        if let Some(reason) = self.reason() {
162            write!(f, ": {reason}")?;
163        }
164        Ok(())
165    }
166}
167
168/// A request Elasticsearch refused because the cluster's license doesn't
169/// include a feature it uses.
170#[derive(Debug)]
171#[non_exhaustive]
172pub struct LicenseError {
173    /// The feature, as Elasticsearch names it, such as `Reciprocal Rank
174    /// Fusion (RRF)`.
175    pub feature: String,
176    /// The error response.
177    pub error: ElasticsearchError,
178}
179
180impl fmt::Display for LicenseError {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        write!(f, "the cluster's license doesn't include {}", self.feature)
183    }
184}
185
186impl Error {
187    /// The error for a response Elasticsearch failed, from its status and
188    /// body: [`Error::License`] when the cluster's license doesn't include a
189    /// feature the request uses, [`Error::Conflict`] for a version
190    /// conflict, else [`Error::Elasticsearch`].
191    pub fn from_response(status: u16, body: &[u8]) -> Error {
192        let body: Value = serde_json::from_slice(body)
193            .unwrap_or_else(|_| Value::String(String::from_utf8_lossy(body).into_owned()));
194        let response = serde_json::from_value(body.clone()).ok();
195        let error = ElasticsearchError {
196            status,
197            response,
198            body,
199        };
200        // Elasticsearch names the feature a license doesn't include in the
201        // root cause's metadata.
202        let feature = error
203            .body
204            .pointer("/error/root_cause")
205            .and_then(Value::as_array)
206            .into_iter()
207            .flatten()
208            .chain(error.body.get("error"))
209            .find_map(|cause| cause.get("license.expired.feature"))
210            .and_then(Value::as_str)
211            .map(str::to_owned)
212            .or_else(|| error.reason().and_then(unlicensed_feature));
213        match feature {
214            Some(feature) => Error::License(Box::new(LicenseError { feature, error })),
215            None if status == 409 => Error::Conflict(Box::new(error)),
216            None => Error::Elasticsearch(Box::new(error)),
217        }
218    }
219}
220
221/// The feature in a license refusal's reason, for refusals without the
222/// metadata that names it: "Current license is non-compliant for query
223/// rules. Current license is …" names `query rules`.
224fn unlicensed_feature(reason: &str) -> Option<String> {
225    const MARKER: &str = "license is non-compliant for ";
226    let start = reason.to_ascii_lowercase().find(MARKER)? + MARKER.len();
227    let rest = &reason[start..];
228    let feature = match rest.strip_prefix('[') {
229        Some(bracketed) => &bracketed[..bracketed.find(']')?],
230        None => rest.split(['.', ';']).next()?,
231    };
232    let feature = feature.trim();
233    (!feature.is_empty()).then(|| feature.to_owned())
234}
235
236#[cfg(test)]
237mod tests {
238    use serde_json::json;
239
240    use super::*;
241
242    fn error(body: Value) -> Error {
243        Error::from_response(403, body.to_string().as_bytes())
244    }
245
246    #[test]
247    fn license_errors_by_metadata() {
248        let body = json!({"error": {
249            "root_cause": [{"type": "security_exception", "reason": "current license is non-compliant for [Reciprocal Rank Fusion (RRF)]", "license.expired.feature": "Reciprocal Rank Fusion (RRF)"}],
250            "type": "security_exception",
251            "reason": "current license is non-compliant for [Reciprocal Rank Fusion (RRF)]"
252        }, "status": 403});
253        let Error::License(e) = error(body) else {
254            panic!("not a license error")
255        };
256        assert_eq!(e.feature, "Reciprocal Rank Fusion (RRF)");
257    }
258
259    #[test]
260    fn license_errors_by_reason() {
261        let body = json!({"error": {
262            "type": "security_exception",
263            "reason": "Current license is non-compliant for query rules. Current license is active basic license."
264        }, "status": 403});
265        let Error::License(e) = error(body) else {
266            panic!("not a license error")
267        };
268        assert_eq!(e.feature, "query rules");
269    }
270
271    #[test]
272    fn cause_chains() {
273        let body = json!({"error": {
274            "type": "search_phase_execution_exception",
275            "reason": "all shards failed",
276            "caused_by": {"type": "illegal_argument_exception", "reason": "bad field",
277                "caused_by": {"type": "number_format_exception", "reason": "For input string"}}
278        }, "status": 400});
279        let Error::Elasticsearch(e) = Error::from_response(400, body.to_string().as_bytes()) else {
280            panic!("not an Elasticsearch error")
281        };
282        let kinds: Vec<_> = e.causes().filter_map(|c| c.r#type.as_deref()).collect();
283        assert_eq!(
284            kinds,
285            [
286                "search_phase_execution_exception",
287                "illegal_argument_exception",
288                "number_format_exception"
289            ]
290        );
291    }
292
293    #[test]
294    fn conflicts() {
295        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});
296        let Error::Conflict(e) = Error::from_response(409, body.to_string().as_bytes()) else {
297            panic!("not a conflict")
298        };
299        assert_eq!(e.error_type(), Some("version_conflict_engine_exception"));
300    }
301
302    #[test]
303    fn other_errors() {
304        let body = json!({"error": {"type": "index_not_found_exception", "reason": "no such index [x]"}, "status": 404});
305        let Error::Elasticsearch(e) = Error::from_response(404, body.to_string().as_bytes()) else {
306            panic!("not an Elasticsearch error")
307        };
308        assert_eq!(e.error_type(), Some("index_not_found_exception"));
309        assert!(e.response.is_some());
310    }
311}