Skip to main content

mariadb_cli/error/
mod.rs

1//! Structured failure: one closed shape for every way the product can fail.
2//!
3//! A failure is never bare text. It always carries a category, a stable code,
4//! a message, a hint and a retry mark, so a caller decides its next step
5//! without parsing prose. Absence of any of those fields is a defect.
6
7pub mod category;
8pub mod render;
9
10pub use category::{Category, ExitNumber};
11
12use std::fmt;
13
14/// A single machine-readable failure.
15///
16/// Construct through the category helpers rather than the struct literal, so
17/// the retry mark stays consistent with the category.
18#[derive(Debug, Clone)]
19pub struct Failure {
20    category: Category,
21    code: &'static str,
22    message: String,
23    hint: Option<String>,
24    /// Overrides the category default when the concrete condition is known.
25    retryable_override: Option<bool>,
26    /// What the failure carries beyond its four mandatory fields.
27    ///
28    /// Held behind a pointer, and absent altogether on the ordinary failure
29    /// that carries none of it. A failure travels inside every `Result` this
30    /// product returns, so every field written here is paid for on every call
31    /// that never fails at all.
32    extras: Option<Box<Extras>>,
33}
34
35/// The parts of a failure that most failures do not have.
36#[derive(Debug, Clone, Default)]
37struct Extras {
38    /// The chain of causes, outermost first.
39    causes: Vec<String>,
40    /// Conditions the server reported beyond the first one.
41    extra_conditions: Vec<String>,
42    /// The measured values this failure was built around, each under its name.
43    ///
44    /// A catalogue words the sentence and substitutes these in, so the source
45    /// never has to build a sentence in one language for every reader.
46    details: Vec<(&'static str, String)>,
47}
48
49impl Failure {
50    /// Builds a failure in the given category.
51    ///
52    /// `code` is a stable identifier callers may branch on; it never changes
53    /// meaning between releases. `message` is human prose and is never used as
54    /// an identifier.
55    #[must_use]
56    pub fn new(category: Category, code: &'static str, message: impl Into<String>) -> Self {
57        Self {
58            category,
59            code,
60            message: message.into(),
61            hint: None,
62            retryable_override: None,
63            extras: None,
64        }
65    }
66
67    /// Records one measured value under the name a catalogue substitutes it by.
68    ///
69    /// This is how a failure keeps its measurements without wording a sentence
70    /// around them: the source supplies the value, and the catalogue of the
71    /// reader's language supplies the words.
72    #[must_use]
73    pub fn with_detail(mut self, name: &'static str, value: impl Into<String>) -> Self {
74        self.extras
75            .get_or_insert_with(Box::default)
76            .details
77            .push((name, value.into()));
78        self
79    }
80
81    /// Attaches a concrete next action for the caller.
82    #[must_use]
83    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
84        self.hint = Some(hint.into());
85        self
86    }
87
88    /// Overrides the category's default retry mark.
89    ///
90    /// Used for server conditions, where whether repeating helps depends on the
91    /// condition rather than on the category.
92    #[must_use]
93    pub const fn with_retryable(mut self, retryable: bool) -> Self {
94        self.retryable_override = Some(retryable);
95        self
96    }
97
98    /// Appends one link to the cause chain, outermost first.
99    #[must_use]
100    pub fn with_cause(mut self, cause: impl Into<String>) -> Self {
101        self.extras
102            .get_or_insert_with(Box::default)
103            .causes
104            .push(cause.into());
105        self
106    }
107
108    /// Records a server condition beyond the first one.
109    ///
110    /// The server may report several conditions for one statement; reporting
111    /// only the first hides the rest from the caller.
112    #[must_use]
113    pub fn with_extra_condition(mut self, condition: impl Into<String>) -> Self {
114        self.extras
115            .get_or_insert_with(Box::default)
116            .extra_conditions
117            .push(condition.into());
118        self
119    }
120
121    /// The failure category.
122    #[must_use]
123    pub const fn category(&self) -> Category {
124        self.category
125    }
126
127    /// The stable identifier for this failure.
128    #[must_use]
129    pub const fn code(&self) -> &'static str {
130        self.code
131    }
132
133    /// The human-readable message.
134    #[must_use]
135    pub fn message(&self) -> &str {
136        &self.message
137    }
138
139    /// The suggested next action, when one exists.
140    #[must_use]
141    pub fn hint(&self) -> Option<&str> {
142        self.hint.as_deref()
143    }
144
145    /// The cause chain, outermost first.
146    #[must_use]
147    pub fn causes(&self) -> &[String] {
148        self.extras
149            .as_deref()
150            .map_or(&[], |extras| extras.causes.as_slice())
151    }
152
153    /// Server conditions beyond the first.
154    #[must_use]
155    pub fn extra_conditions(&self) -> &[String] {
156        self.extras
157            .as_deref()
158            .map_or(&[], |extras| extras.extra_conditions.as_slice())
159    }
160
161    /// The measured values this failure carries, each under its name.
162    #[must_use]
163    pub fn details(&self) -> &[(&'static str, String)] {
164        self.extras
165            .as_deref()
166            .map_or(&[], |extras| extras.details.as_slice())
167    }
168
169    /// Whether repeating the same call may succeed without changing the input.
170    #[must_use]
171    pub fn is_retryable(&self) -> bool {
172        self.retryable_override
173            .unwrap_or_else(|| self.category.is_retryable())
174    }
175
176    /// The exit number this failure produces.
177    #[must_use]
178    pub const fn exit_number(&self) -> ExitNumber {
179        self.category.exit_number()
180    }
181}
182
183impl fmt::Display for Failure {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        write!(f, "{}: {}", self.code, self.message)
186    }
187}
188
189impl std::error::Error for Failure {}
190
191/// The result type used across the whole product.
192pub type Result<T> = std::result::Result<T, Failure>;
193
194/// Constructors grouped by category, so the retry mark is never set by hand.
195impl Failure {
196    /// The caller's input to this tool is wrong.
197    #[must_use]
198    pub fn usage(code: &'static str, message: impl Into<String>) -> Self {
199        Self::new(Category::Usage, code, message)
200    }
201
202    /// Analysis refused the statement before it was sent.
203    #[must_use]
204    pub fn validation(code: &'static str, message: impl Into<String>) -> Self {
205        Self::new(Category::Validation, code, message)
206    }
207
208    /// A profile or setting is missing or invalid.
209    #[must_use]
210    pub fn config(code: &'static str, message: impl Into<String>) -> Self {
211        Self::new(Category::Config, code, message)
212    }
213
214    /// The server could not be reached.
215    #[must_use]
216    pub fn network(code: &'static str, message: impl Into<String>) -> Self {
217        Self::new(Category::Network, code, message)
218    }
219
220    /// The credential was refused.
221    #[must_use]
222    pub fn authentication(code: &'static str, message: impl Into<String>) -> Self {
223        Self::new(Category::Authentication, code, message)
224    }
225
226    /// The credential may not do what was asked.
227    #[must_use]
228    pub fn permission(code: &'static str, message: impl Into<String>) -> Self {
229        Self::new(Category::Permission, code, message)
230    }
231
232    /// The requested object does not exist.
233    #[must_use]
234    pub fn absence(code: &'static str, message: impl Into<String>) -> Self {
235        Self::new(Category::Absence, code, message)
236    }
237
238    /// The change hit a lock, a deadlock or a constraint.
239    #[must_use]
240    pub fn conflict(code: &'static str, message: impl Into<String>) -> Self {
241        Self::new(Category::Conflict, code, message)
242    }
243
244    /// Some phase exceeded its time budget.
245    #[must_use]
246    pub fn timeout(code: &'static str, message: impl Into<String>) -> Self {
247        Self::new(Category::Timeout, code, message)
248    }
249
250    /// The server returned an error of its own.
251    #[must_use]
252    pub fn server(code: &'static str, message: impl Into<String>) -> Self {
253        Self::new(Category::Server, code, message)
254    }
255
256    /// A size, row or packet ceiling was reached.
257    #[must_use]
258    pub fn limit(code: &'static str, message: impl Into<String>) -> Self {
259        Self::new(Category::Limit, code, message)
260    }
261
262    /// The work was cancelled from outside.
263    #[must_use]
264    pub fn interrupted(code: &'static str, message: impl Into<String>) -> Self {
265        Self::new(Category::Interrupted, code, message)
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    /// The retry mark follows the category unless a concrete condition
274    /// overrides it.
275    #[test]
276    fn retry_mark_follows_category_by_default() {
277        let transient = Failure::network("net.unreachable", "server not reached");
278        assert!(transient.is_retryable());
279
280        let permanent = Failure::usage("usage.bad_flag", "unknown value");
281        assert!(!permanent.is_retryable());
282    }
283
284    /// A server condition decides its own retry mark, because the category
285    /// alone cannot tell a deadlock from a syntax error.
286    #[test]
287    fn server_condition_overrides_the_retry_mark() {
288        let retryable = Failure::server("server.1213", "deadlock found").with_retryable(true);
289        assert!(retryable.is_retryable());
290        assert_eq!(retryable.exit_number(), ExitNumber::Server);
291
292        let permanent = Failure::server("server.1064", "syntax error");
293        assert!(!permanent.is_retryable());
294    }
295
296    /// All server conditions are kept, not just the first one.
297    #[test]
298    fn every_server_condition_is_kept() {
299        let failure = Failure::server("server.1364", "field has no default")
300            .with_extra_condition("column `b` has no default")
301            .with_extra_condition("column `c` has no default");
302        assert_eq!(failure.extra_conditions().len(), 2);
303    }
304}