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 serde::{Deserialize, Serialize};
5
6/// The kind of failure, stable across releases; the message is not.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
8#[serde(rename_all = "snake_case")]
9pub enum ErrorCode {
10    /// The request could not be read: not JSON, or not a known command.
11    BadRequest,
12    /// A query with none of pattern, kind, symbol, name.
13    BadQuery,
14    /// A pattern or node kind the language's grammar rejects.
15    BadPattern,
16    /// A selection naming rows or ids the search did not find.
17    BadSelection,
18    /// A template naming a capture the match does not have.
19    BadTemplate,
20    /// No declaration by that name (and kind).
21    NoSuchSymbol,
22    /// Several declarations share the name; `declared_in` picks one.
23    AmbiguousSymbol,
24    /// No registered language claims the file.
25    NoLanguage,
26    /// The language has no layout: paths cannot be followed, files not moved.
27    NoLayout,
28    /// A position past the end of the file.
29    NoSuchPosition,
30    /// The destination already exists.
31    Exists,
32    /// A file, or the file declaring a name, could not be found.
33    NotFound,
34    /// The layout refuses the move: a root, across packages, into itself.
35    Unmovable,
36    /// Two edits of one plan overlap, or a file is moved twice.
37    Conflict,
38    /// A file changed since the plan (or the apply to undo) was made.
39    Stale,
40    /// Nothing to undo, or a history file that cannot be read.
41    NoHistory,
42    /// Reading or writing the tree failed.
43    Io,
44}
45
46/// A failed request, as the wire carries it.
47#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48pub struct Failure {
49    pub code: ErrorCode,
50    pub message: String,
51    /// What to try instead, when there is something.
52    #[serde(default, skip_serializing_if = "Option::is_none")]
53    pub hint: Option<String>,
54}
55
56impl Failure {
57    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
58        Self {
59            code,
60            message: message.into(),
61            hint: None,
62        }
63    }
64
65    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
66        self.hint = Some(hint.into());
67        self
68    }
69}
70
71impl std::fmt::Display for Failure {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.write_str(&self.message)
74    }
75}
76
77#[cfg(test)]
78mod tests {
79    use super::ErrorCode;
80
81    /// A client branches on `code`, so its spelling is part of the protocol
82    /// and renaming one is a breaking change. The exhaustive `match` makes a
83    /// new variant a compile error here until its spelling joins the table.
84    #[test]
85    fn every_code_keeps_its_wire_spelling() {
86        for code in [
87            ErrorCode::BadRequest,
88            ErrorCode::BadQuery,
89            ErrorCode::BadPattern,
90            ErrorCode::BadSelection,
91            ErrorCode::BadTemplate,
92            ErrorCode::NoSuchSymbol,
93            ErrorCode::AmbiguousSymbol,
94            ErrorCode::NoLanguage,
95            ErrorCode::NoLayout,
96            ErrorCode::NoSuchPosition,
97            ErrorCode::Exists,
98            ErrorCode::NotFound,
99            ErrorCode::Unmovable,
100            ErrorCode::Conflict,
101            ErrorCode::Stale,
102            ErrorCode::NoHistory,
103            ErrorCode::Io,
104        ] {
105            let documented = match code {
106                ErrorCode::BadRequest => "bad_request",
107                ErrorCode::BadQuery => "bad_query",
108                ErrorCode::BadPattern => "bad_pattern",
109                ErrorCode::BadSelection => "bad_selection",
110                ErrorCode::BadTemplate => "bad_template",
111                ErrorCode::NoSuchSymbol => "no_such_symbol",
112                ErrorCode::AmbiguousSymbol => "ambiguous_symbol",
113                ErrorCode::NoLanguage => "no_language",
114                ErrorCode::NoLayout => "no_layout",
115                ErrorCode::NoSuchPosition => "no_such_position",
116                ErrorCode::Exists => "exists",
117                ErrorCode::NotFound => "not_found",
118                ErrorCode::Unmovable => "unmovable",
119                ErrorCode::Conflict => "conflict",
120                ErrorCode::Stale => "stale",
121                ErrorCode::NoHistory => "no_history",
122                ErrorCode::Io => "io",
123            };
124            assert_eq!(
125                serde_json::to_value(code).unwrap(),
126                documented,
127                "docs/protocol.md documents `{documented}`"
128            );
129        }
130    }
131}