1use std::fmt;
4
5use serde_json::Value;
6
7pub type TransportError = Box<dyn std::error::Error + Send + Sync>;
10
11#[derive(Debug)]
13#[non_exhaustive]
14pub enum Error {
15 Transport(TransportError),
17 Elasticsearch(Box<ElasticsearchError>),
19 License(Box<LicenseError>),
22 Conflict(Box<ElasticsearchError>),
25 Encode(serde_json::Error),
27 Parameter(String),
30 Decode {
32 status: u16,
34 source: serde_json::Error,
36 body: String,
38 },
39 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#[derive(Debug)]
77#[non_exhaustive]
78pub struct RowError {
79 pub row: usize,
81 pub column: Option<String>,
84 pub message: String,
86 pub columns: Vec<String>,
88}
89
90impl RowError {
91 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#[derive(Debug)]
124#[non_exhaustive]
125pub struct ElasticsearchError {
126 pub status: u16,
128 pub response: Option<crate::ErrorResponseBase>,
130 pub body: Value,
132}
133
134impl ElasticsearchError {
135 pub fn error_type(&self) -> Option<&str> {
137 self.body.pointer("/error/type").and_then(Value::as_str)
138 }
139
140 pub fn reason(&self) -> Option<&str> {
142 self.body.pointer("/error/reason").and_then(Value::as_str)
143 }
144
145 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#[derive(Debug)]
171#[non_exhaustive]
172pub struct LicenseError {
173 pub feature: String,
176 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 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 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
221fn 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}