1use crate::EngineError;
5use serde::{Deserialize, Serialize};
6
7#[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 Cancelled,
21 Incomplete,
23 BadRequest,
25 BadQuery,
27 BadPattern,
29 BadSelection,
31 BadTemplate,
33 NoSuchSymbol,
35 AmbiguousSymbol,
37 NoLanguage,
39 NoLayout,
41 NoSuchPosition,
43 Exists,
45 NotFound,
47 Unmovable,
49 Conflict,
51 Stale,
53 NoHistory,
55 Io,
57 RecoveryFailed,
59}
60
61#[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 #[serde(default, skip_serializing_if = "Option::is_none")]
77 pub hint: Option<String>,
78 #[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#[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 #[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#[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}