Skip to main content

zu_common/
error.rs

1//! Workspace-wide error type.
2//!
3//! Every error carries a stable `ZU####` code once the catalog in
4//! `docs/errors.md` exists. Variants are added as subsystems land.
5//!
6//! Anything a GQL statement can raise goes through [`ZuError::Gql`],
7//! which carries an ISO/IEC 39075 GQLSTATUS value rather than only a
8//! message. The other variants are engine-internal: an io error opening
9//! a file is not a condition the standard has a code for, and inventing
10//! one would be worse than admitting it.
11
12use crate::gqlstatus::{DiagnosticRecord, GqlStatus, Position, Subject};
13
14/// Top-level error for all zu operations.
15#[derive(Debug, thiserror::Error)]
16pub enum ZuError {
17    /// A GQL condition, with the standard's code and our own detail.
18    #[error("{0}")]
19    Gql(Box<DiagnosticRecord>),
20
21    #[error("io: {0}")]
22    Io(#[from] std::io::Error),
23
24    #[error("corrupt {what}: {detail}")]
25    Corrupt { what: &'static str, detail: String },
26
27    #[error("unsupported {what} id {id}")]
28    Unsupported { what: &'static str, id: u32 },
29
30    #[error("invalid argument: {0}")]
31    InvalidArgument(String),
32
33    /// A compare-and-swap or ownership check lost to a concurrent writer.
34    #[error("conflict: {0}")]
35    Conflict(String),
36
37    /// The caller asked the statement to stop and it did, at the next
38    /// boundary the executor checks ([`crate::Interrupt`]). No condition
39    /// code, because the standard has none for this and the statement
40    /// did not fail: it was stopped, which is a fact about the caller
41    /// rather than about the query.
42    #[error("interrupted")]
43    Interrupted,
44}
45
46impl ZuError {
47    /// Raises `status` with our own account of what happened.
48    pub fn gql(status: GqlStatus, detail: impl Into<String>) -> Self {
49        ZuError::Gql(Box::new(DiagnosticRecord::new(status, detail)))
50    }
51
52    /// The same, raised at a place in the statement text. The message
53    /// reads as it did before, with the line and column ahead of the
54    /// detail, and the pair is also kept as a pair so that a caller can
55    /// point at the token instead of parsing the sentence.
56    pub fn gql_at(status: GqlStatus, position: Position, detail: impl std::fmt::Display) -> Self {
57        ZuError::Gql(Box::new(DiagnosticRecord::at(status, position, detail)))
58    }
59
60    /// The same, raised at a byte offset into the statement text.
61    ///
62    /// The front end raises through this one rather than through
63    /// [`Self::gql_at`], because the source is what turns an offset
64    /// into a line and a column and it is also the only way to quote
65    /// the line back. A caller three layers up has the message and the
66    /// numbers and no longer has the text.
67    pub fn gql_in(
68        status: GqlStatus,
69        source: &str,
70        offset: usize,
71        detail: impl std::fmt::Display,
72    ) -> Self {
73        ZuError::Gql(Box::new(DiagnosticRecord::in_source(
74            status, source, offset, detail,
75        )))
76    }
77
78    /// The same error, about a thing the statement named.
79    ///
80    /// A builder rather than a fourth constructor, so that a raise site
81    /// adds a subject without changing which of the three it went
82    /// through. It does nothing to an engine-internal failure, which
83    /// has no record to put a subject on.
84    pub fn about(mut self, subject: Subject) -> Self {
85        if let ZuError::Gql(record) = &mut self {
86            record.subject = Some(subject);
87        }
88        self
89    }
90
91    /// What the condition is about, when it is about something named.
92    pub fn subject(&self) -> Option<&Subject> {
93        match self {
94            ZuError::Gql(record) => record.subject.as_ref(),
95            _ => None,
96        }
97    }
98
99    /// Where in the statement this was raised, when it was raised
100    /// somewhere. An engine-internal failure and a runtime condition
101    /// both answer `None`.
102    pub fn position(&self) -> Option<Position> {
103        match self {
104            ZuError::Gql(record) => record.position,
105            _ => None,
106        }
107    }
108
109    /// The GQLSTATUS value for this error, if it has one. Engine-internal
110    /// errors return `None` rather than a code that would be a guess.
111    pub fn gqlstatus(&self) -> Option<GqlStatus> {
112        match self {
113            ZuError::Gql(record) => Some(record.status),
114            _ => None,
115        }
116    }
117
118    /// The diagnostic record for this error, if it has one.
119    pub fn diagnostic(&self) -> Option<&DiagnosticRecord> {
120        match self {
121            ZuError::Gql(record) => Some(record),
122            _ => None,
123        }
124    }
125
126    /// The line of the statement this was raised on, when the statement
127    /// text was in hand where it was raised.
128    pub fn excerpt(&self) -> Option<&str> {
129        match self {
130            ZuError::Gql(record) => record.excerpt.as_deref(),
131            _ => None,
132        }
133    }
134
135    /// Whether running the same thing again could succeed, which is the
136    /// one question a caller writing a retry loop is asking.
137    ///
138    /// A lost compare-and-swap is the case: a concurrent writer got
139    /// there first, so the work was not applied and the same call on a
140    /// fresh read may well win. A condition answers for itself, which
141    /// is `40000 transaction rollback` and nothing else. Everything
142    /// remaining is false, including an interruption, which is not the
143    /// engine failing but the caller having asked it to stop.
144    pub fn retryable(&self) -> bool {
145        match self {
146            ZuError::Gql(record) => record.retryable(),
147            ZuError::Conflict(_) => true,
148            _ => false,
149        }
150    }
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156    use crate::gqlstatus::codes;
157
158    #[test]
159    fn a_gql_error_keeps_its_code_and_reads_as_our_detail() {
160        let e = ZuError::gql(codes::C42001, "line 1, column 1: expected MATCH");
161        assert_eq!(e.gqlstatus(), Some(codes::C42001));
162        assert_eq!(e.to_string(), "42001: line 1, column 1: expected MATCH");
163    }
164
165    #[test]
166    fn an_engine_error_has_no_code_rather_than_a_guessed_one() {
167        let e = ZuError::Corrupt {
168            what: "block",
169            detail: "bad crc".into(),
170        };
171        assert_eq!(e.gqlstatus(), None);
172        assert!(e.diagnostic().is_none());
173    }
174
175    #[test]
176    fn an_error_raised_in_a_statement_carries_the_line_it_was_raised_on() {
177        let source = "MATCH (n)\nRETURN n.x + ";
178        let offset = source.find("n.x").expect("n.x");
179        let e = ZuError::gql_in(codes::C42001, source, offset, "expected an expression");
180        assert_eq!(e.excerpt(), Some("RETURN n.x + "));
181        let at = e.position().expect("a place");
182        assert_eq!((at.line, at.column), (2, 8));
183        assert_eq!(&source[at.offset as usize..][..3], "n.x");
184        assert_eq!(
185            e.to_string(),
186            "42001: line 2, column 8: expected an expression"
187        );
188    }
189
190    #[test]
191    fn only_the_failures_worth_repeating_say_so() {
192        // A writer that lost the race did not apply its write, so the
193        // same call on a fresh read is a reasonable next move.
194        assert!(ZuError::Conflict("lost the swap".into()).retryable());
195        assert!(ZuError::gql(codes::C40000, "rolled back").retryable());
196        // Text that will not parse will not parse again, and a caller
197        // that asked for a stop got one.
198        assert!(!ZuError::gql(codes::C42001, "bad syntax").retryable());
199        assert!(!ZuError::Interrupted.retryable());
200        assert!(
201            !ZuError::Corrupt {
202                what: "block",
203                detail: "bad crc".into(),
204            }
205            .retryable()
206        );
207    }
208}