Skip to main content

vvv_engine/protocol/
failure.rs

1//! What went wrong, as data: a code a client can branch on, the message a
2//! person reads, and the hint that says what to try instead.
3
4use crate::EngineError;
5use serde::{Deserialize, Serialize};
6
7/// The kind of failure, stable across releases; the message is not.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
9#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
10#[serde(rename_all = "snake_case")]
11pub enum ErrorCode {
12    InvalidPlan,
13    PlanExpired,
14    PlanConsumed,
15    CursorExpired,
16    InvalidCursor,
17    RetentionLimit,
18    OutputLimit,
19    /// The caller cancelled the operation.
20    Cancelled,
21    /// Resolution stopped before a complete answer was available.
22    Incomplete,
23    /// The request could not be read: not JSON, or not a known command.
24    BadRequest,
25    /// A query with none of pattern, kind, symbol, name.
26    BadQuery,
27    /// A pattern or node kind the language's grammar rejects.
28    BadPattern,
29    /// A selection naming rows or ids the search did not find.
30    BadSelection,
31    /// A template naming a capture the match does not have.
32    BadTemplate,
33    /// No declaration by that name (and kind).
34    NoSuchSymbol,
35    /// Several declarations share the name; `declared_in` picks one.
36    AmbiguousSymbol,
37    /// No registered language claims the file.
38    NoLanguage,
39    /// The language has no layout: paths cannot be followed, files not moved.
40    NoLayout,
41    /// A position past the end of the file.
42    NoSuchPosition,
43    /// The destination already exists.
44    Exists,
45    /// A file, or the file declaring a name, could not be found.
46    NotFound,
47    /// The layout refuses the move: a root, across packages, into itself.
48    Unmovable,
49    /// Two edits of one plan overlap, or a file is moved twice.
50    Conflict,
51    /// A file changed since the plan (or the apply to undo) was made.
52    Stale,
53    /// Nothing to undo, or a history file that cannot be read.
54    NoHistory,
55    /// Reading or writing the tree failed.
56    Io,
57    /// Recovery could not restore or verify every attempted effect.
58    RecoveryFailed,
59}
60
61/// A failed request, as the wire carries it.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
64pub struct Failure {
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub symbol_move_candidates: Option<Vec<crate::SymbolMoveCandidate>>,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub symbol_move_unsupported: Option<crate::SymbolMoveUnsupported>,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub continuation: Option<ContinuationRecovery>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub output_limit: Option<OutputLimit>,
73    pub code: ErrorCode,
74    pub message: String,
75    /// What to try instead, when there is something.
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub hint: Option<String>,
78    /// Effects that could not be restored after a failed mutation.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub recovery: Option<Recovery>,
81}
82
83impl Failure {
84    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
85        Self {
86            code,
87            message: message.into(),
88            hint: None,
89            recovery: None,
90            output_limit: None,
91            continuation: None,
92            symbol_move_candidates: None,
93            symbol_move_unsupported: None,
94        }
95    }
96
97    pub fn with_recovery(mut self, recovery: Recovery) -> Self {
98        self.recovery = Some(recovery);
99        self
100    }
101
102    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
103        self.hint = Some(hint.into());
104        self
105    }
106}
107
108impl From<&EngineError> for Failure {
109    fn from(error: &EngineError) -> Self {
110        let mut failure = Failure::new(error.code(), format!("{error:#}"));
111        if let EngineError::SymbolMoveSelection { candidates } = error {
112            failure.symbol_move_candidates = Some(candidates.clone());
113        }
114        if let EngineError::UnsupportedSymbolMove { reason, .. } = error {
115            failure.symbol_move_unsupported = Some(*reason);
116        }
117        if let EngineError::Recovery(recovery) = error {
118            failure = failure.with_recovery(recovery.details.clone());
119        }
120        if let EngineError::OutputLimit {
121            max_bytes,
122            required_bytes,
123        } = error
124        {
125            failure.output_limit = Some(OutputLimit {
126                max_bytes: *max_bytes,
127                required_bytes: *required_bytes,
128                anchor: None,
129            });
130        }
131        failure.continuation = match error {
132            EngineError::StaleQuery | EngineError::CursorExpired => {
133                Some(ContinuationRecovery::RestartQuery)
134            }
135            EngineError::InvalidCursor => Some(ContinuationRecovery::CorrectCursor),
136            EngineError::RetentionLimit => Some(ContinuationRecovery::NarrowQuery),
137            EngineError::PageOutputLimit {
138                max_bytes,
139                required_bytes,
140                anchor,
141            } => {
142                failure.output_limit = Some(OutputLimit {
143                    max_bytes: *max_bytes,
144                    required_bytes: *required_bytes,
145                    anchor: anchor.clone().map(Box::new),
146                });
147                Some(ContinuationRecovery::IncreaseBudgetOrNarrowQuery)
148            }
149            EngineError::OutputLimit { .. } => {
150                Some(ContinuationRecovery::IncreaseBudgetOrNarrowQuery)
151            }
152            _ => None,
153        };
154        match error.hint() {
155            Some(hint) => failure.with_hint(hint),
156            None => failure,
157        }
158    }
159}
160
161/// A recovery result; unknown states are separate from confirmed residual effects.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
164pub struct Recovery {
165    pub cause: Box<Failure>,
166    pub failures: Vec<RecoveryIssue>,
167    pub remaining: Vec<RecoveryEffect>,
168    pub unverified: Vec<RecoveryUnverified>,
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
172#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
173pub struct RecoveryIssue {
174    pub operation: RecoveryOperation,
175    pub path: crate::RelPath,
176    pub code: ErrorCode,
177    pub message: String,
178}
179
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
182pub struct RecoveryUnverified {
183    pub path: crate::RelPath,
184    pub expected: RecoveryState,
185    pub code: ErrorCode,
186    pub message: String,
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
190#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
191#[serde(rename_all = "snake_case")]
192pub enum RecoveryOperation {
193    RestoreFile,
194    RestoreMove,
195    RestoreDirectory,
196    RemoveFile,
197    RemoveDirectory,
198}
199
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
202pub struct RecoveryEffect {
203    pub path: crate::RelPath,
204    pub expected: RecoveryState,
205    pub observed: RecoveryState,
206}
207
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
210#[serde(tag = "kind", rename_all = "snake_case")]
211pub enum RecoveryState {
212    Absent,
213    File {
214        fingerprint: String,
215        #[serde(default, skip_serializing_if = "Option::is_none")]
216        spelling: Option<crate::RelPath>,
217    },
218    Directory,
219    Other,
220}
221
222impl std::fmt::Display for Failure {
223    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        f.write_str(&self.message)
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::ErrorCode;
231
232    /// A client branches on `code`, so its spelling is part of the protocol
233    /// and renaming one is a breaking change. The exhaustive `match` makes a
234    /// new variant a compile error here until its spelling joins the table.
235    #[test]
236    fn every_code_keeps_its_wire_spelling() {
237        for code in [
238            ErrorCode::InvalidPlan,
239            ErrorCode::PlanExpired,
240            ErrorCode::PlanConsumed,
241            ErrorCode::CursorExpired,
242            ErrorCode::InvalidCursor,
243            ErrorCode::RetentionLimit,
244            ErrorCode::OutputLimit,
245            ErrorCode::Cancelled,
246            ErrorCode::Incomplete,
247            ErrorCode::BadRequest,
248            ErrorCode::BadQuery,
249            ErrorCode::BadPattern,
250            ErrorCode::BadSelection,
251            ErrorCode::BadTemplate,
252            ErrorCode::NoSuchSymbol,
253            ErrorCode::AmbiguousSymbol,
254            ErrorCode::NoLanguage,
255            ErrorCode::NoLayout,
256            ErrorCode::NoSuchPosition,
257            ErrorCode::Exists,
258            ErrorCode::NotFound,
259            ErrorCode::Unmovable,
260            ErrorCode::Conflict,
261            ErrorCode::Stale,
262            ErrorCode::NoHistory,
263            ErrorCode::Io,
264            ErrorCode::RecoveryFailed,
265        ] {
266            let documented = match code {
267                ErrorCode::InvalidPlan => "invalid_plan",
268                ErrorCode::PlanExpired => "plan_expired",
269                ErrorCode::PlanConsumed => "plan_consumed",
270                ErrorCode::CursorExpired => "cursor_expired",
271                ErrorCode::InvalidCursor => "invalid_cursor",
272                ErrorCode::RetentionLimit => "retention_limit",
273                ErrorCode::OutputLimit => "output_limit",
274                ErrorCode::Cancelled => "cancelled",
275                ErrorCode::Incomplete => "incomplete",
276                ErrorCode::BadRequest => "bad_request",
277                ErrorCode::BadQuery => "bad_query",
278                ErrorCode::BadPattern => "bad_pattern",
279                ErrorCode::BadSelection => "bad_selection",
280                ErrorCode::BadTemplate => "bad_template",
281                ErrorCode::NoSuchSymbol => "no_such_symbol",
282                ErrorCode::AmbiguousSymbol => "ambiguous_symbol",
283                ErrorCode::NoLanguage => "no_language",
284                ErrorCode::NoLayout => "no_layout",
285                ErrorCode::NoSuchPosition => "no_such_position",
286                ErrorCode::Exists => "exists",
287                ErrorCode::NotFound => "not_found",
288                ErrorCode::Unmovable => "unmovable",
289                ErrorCode::Conflict => "conflict",
290                ErrorCode::Stale => "stale",
291                ErrorCode::NoHistory => "no_history",
292                ErrorCode::Io => "io",
293                ErrorCode::RecoveryFailed => "recovery_failed",
294            };
295            assert_eq!(
296                serde_json::to_value(code).unwrap(),
297                documented,
298                "docs/protocol.md documents `{documented}`"
299            );
300        }
301    }
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
306pub struct OutputLimit {
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub anchor: Option<Box<crate::SourceAnchor>>,
309    pub max_bytes: usize,
310    pub required_bytes: usize,
311}
312
313/// A recovery action clients can branch on without parsing the error message.
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
315#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
316#[serde(rename_all = "snake_case")]
317pub enum ContinuationRecovery {
318    RestartQuery,
319    CorrectCursor,
320    IncreaseBudgetOrNarrowQuery,
321    NarrowQuery,
322}