Diffinery

homeflare/celldpublic

celld/crates/ltx/src/error.rs
353 lines · 13.5 KBRaw History
1//! error.rs — thiserror-based error model + `Result` alias.
2//!
3//! Ported from [email protected] litestream.go:32-93
4//!
5//! The sentinel errors (`ErrNoSnapshots`, `ErrChecksumMismatch`,
6//! `ErrLTXCorrupted`, `ErrLTXMissing`) and the structured `LTXError` type with
7//! its `IsAutoRecoverable` logic are direct ports of the equivalent Go values.
8
9use std::io;
10use thiserror::Error;
11
12/// Crate-wide `Result` alias.
13pub type Result<T> = std::result::Result<T, Error>;
14
15/// Top-level error enum for `rustyriver`.
16///
17/// Variants map 1-to-1 to the sentinel errors and error categories in
18/// `litestream.go`; additional variants cover I/O and other infrastructure.
19#[derive(Debug, Error)]
20pub enum Error {
21 /// No snapshot is available for restore.
22 ///
23 /// Corresponds to `ErrNoSnapshots` in litestream.go:33.
24 #[error("no snapshots available")]
25 NoSnapshots,
26
27 /// The replica's rolling checksum does not match what was expected.
28 ///
29 /// Corresponds to `ErrChecksumMismatch` in litestream.go:34.
30 #[error("invalid replica, checksum mismatch")]
31 ChecksumMismatch,
32
33 /// An LTX file's contents are corrupt (bad magic, truncated, bad CRC, etc.).
34 ///
35 /// Corresponds to `ErrLTXCorrupted` in litestream.go:35.
36 #[error("ltx file corrupted")]
37 LTXCorrupted,
38
39 /// An expected LTX file is absent from the replica.
40 ///
41 /// Corresponds to `ErrLTXMissing` in litestream.go:36.
42 #[error("ltx file missing")]
43 LTXMissing,
44
45 /// The requested transaction does not exist on the replica (no backup chain
46 /// reaches it).
47 ///
48 /// Corresponds to `ErrTxNotAvailable` in store.go:27.
49 #[error("transaction not available")]
50 TxNotAvailable,
51
52 /// Structured LTX error with operation context and recovery hints.
53 ///
54 /// Corresponds to `LTXError` in litestream.go:40-93.
55 #[error("{0}")]
56 Ltx(#[from] Box<LTXError>),
57
58 /// Underlying I/O error.
59 #[error("io error: {0}")]
60 Io(#[from] io::Error),
61
62 /// Any other error not yet given a dedicated variant.
63 #[error("{0}")]
64 Other(#[from] Box<dyn std::error::Error + Send + Sync>),
65}
66
67// ── LTXError ─────────────────────────────────────────────────────────────────
68
69/// Structured error for LTX file operations.
70///
71/// Provides operation context, file path, TXID range, and an optional
72/// human-readable recovery hint. Ported from `LTXError` in
73/// [email protected] litestream.go:40-93.
74#[derive(Debug)]
75pub struct LTXError {
76 /// Operation that failed (e.g., `"open"`, `"read"`, `"validate"`).
77 pub op: String,
78 /// File path, if known.
79 pub path: String,
80 /// LTX compaction level (0 = L0).
81 pub level: i32,
82 /// Minimum transaction ID in the file.
83 pub min_txid: u64,
84 /// Maximum transaction ID in the file.
85 pub max_txid: u64,
86 /// Underlying cause.
87 pub err: Box<dyn std::error::Error + Send + Sync>,
88 /// Human-readable recovery hint (empty when not applicable).
89 pub hint: String,
90}
91
92impl std::fmt::Display for LTXError {
93 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94 // Matches the Go Error() method:
95 // if e.Path != "" { return e.Op + " ltx file " + e.Path + ": " + e.Err.Error() }
96 // return e.Op + " ltx file: " + e.Err.Error()
97 if self.path.is_empty() {
98 write!(f, "{} ltx file: {}", self.op, self.err)
99 } else {
100 write!(f, "{} ltx file {}: {}", self.op, self.path, self.err)
101 }
102 }
103}
104
105impl std::error::Error for LTXError {
106 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
107 Some(self.err.as_ref())
108 }
109}
110
111impl LTXError {
112 /// Returns `true` when the error represents local state corruption that
113 /// can be fixed by resetting and re-downloading from the remote replica.
114 ///
115 /// Returns `false` for transient OS errors (permission denied, I/O error)
116 /// that should be retried with back-off instead.
117 ///
118 /// Ported from `LTXError.IsAutoRecoverable` in litestream.go:63-71.
119 ///
120 /// Uses chain-walking (via `source()`) to mirror Go's `errors.Is` semantics:
121 /// a context-wrapped sentinel (e.g. `Error::Other(Box::new(Error::LTXCorrupted))`,
122 /// mirroring `fmt.Errorf("%w: bad data", ErrLTXCorrupted)`) is still
123 /// recognized as auto-recoverable.
124 pub fn is_auto_recoverable(&self) -> bool {
125 let err_ref: &dyn std::error::Error = self.err.as_ref();
126 // os.IsNotExist equivalent: walk chain for io::ErrorKind::NotFound
127 if chain_contains_not_found(err_ref) {
128 return true;
129 }
130 // errors.Is(e.Err, ErrLTXMissing) — walk chain for marker or sentinel
131 if chain_contains::<LTXMissingMarker>(err_ref)
132 || chain_contains_error_variant(err_ref, ErrorVariantKind::LTXMissing)
133 {
134 return true;
135 }
136 // errors.Is(e.Err, ErrLTXCorrupted) || errors.Is(e.Err, ErrChecksumMismatch)
137 // Walk chain for marker types or bare sentinel variants.
138 if chain_contains::<LTXCorruptedMarker>(err_ref)
139 || chain_contains_error_variant(err_ref, ErrorVariantKind::LTXCorrupted)
140 || chain_contains::<ChecksumMismatchMarker>(err_ref)
141 || chain_contains_error_variant(err_ref, ErrorVariantKind::ChecksumMismatch)
142 {
143 return true;
144 }
145 false
146 }
147}
148
149// ── Chain-walking helpers ─────────────────────────────────────────────────────
150//
151// Go's `errors.Is` walks the full error chain via `Unwrap()`. Rust's
152// `std::error::Error::source()` is the equivalent. The helpers below replicate
153// that chain-walking so that a context-wrapped sentinel (e.g.
154// `Error::Other(Box::new(Error::LTXCorrupted))`) is still detected as a
155// recoverable cause — matching litestream.go:63-70.
156
157/// Returns `true` if any error in the `source()` chain can be downcast to `E`.
158fn chain_contains<E: std::error::Error + 'static>(err: &(dyn std::error::Error + 'static)) -> bool {
159 if err.downcast_ref::<E>().is_some() {
160 return true;
161 }
162 if let Some(src) = err.source() {
163 return chain_contains::<E>(src);
164 }
165 false
166}
167
168/// Returns `true` if any error in the `source()` chain is an `io::Error` with
169/// kind `ErrorKind::NotFound`.
170fn chain_contains_not_found(err: &(dyn std::error::Error + 'static)) -> bool {
171 if let Some(io_err) = err.downcast_ref::<io::Error>() {
172 if io_err.kind() == io::ErrorKind::NotFound {
173 return true;
174 }
175 }
176 if let Some(src) = err.source() {
177 return chain_contains_not_found(src);
178 }
179 false
180}
181
182/// Discriminator for which `Error` sentinel variant we are searching for.
183#[derive(Clone, Copy)]
184enum ErrorVariantKind {
185 LTXCorrupted,
186 LTXMissing,
187 ChecksumMismatch,
188}
189
190/// Returns `true` if any error in the `source()` chain is an `Error` enum
191/// variant matching `kind`.
192///
193/// This handles the case where an `Error` sentinel is wrapped inside
194/// `Error::Other(...)`, mirroring Go's `errors.Is(err, ErrLTXCorrupted)`.
195fn chain_contains_error_variant(
196 err: &(dyn std::error::Error + 'static),
197 kind: ErrorVariantKind,
198) -> bool {
199 if let Some(e) = err.downcast_ref::<Error>() {
200 let matches = match kind {
201 ErrorVariantKind::LTXCorrupted => matches!(e, Error::LTXCorrupted),
202 ErrorVariantKind::LTXMissing => matches!(e, Error::LTXMissing),
203 ErrorVariantKind::ChecksumMismatch => matches!(e, Error::ChecksumMismatch),
204 };
205 if matches {
206 return true;
207 }
208 }
209 if let Some(src) = err.source() {
210 return chain_contains_error_variant(src, kind);
211 }
212 false
213}
214
215// ── Marker error types for downcast detection ─────────────────────────────────
216//
217// The Go code uses `errors.Is` against sentinel `var` values. Rust's
218// `thiserror` approach is to use concrete unit-struct error types that we can
219// `downcast_ref` to. These are internal implementation details; callers use
220// the public `new_ltx_error` constructor which accepts `Error` values and
221// wraps them appropriately.
222
223/// Marker wrapping `Error::LTXMissing` so `LTXError::is_auto_recoverable` can
224/// detect it via `downcast_ref`.
225#[derive(Debug)]
226struct LTXMissingMarker;
227impl std::fmt::Display for LTXMissingMarker {
228 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
229 f.write_str("ltx file missing")
230 }
231}
232impl std::error::Error for LTXMissingMarker {}
233
234/// Marker wrapping `Error::LTXCorrupted`.
235#[derive(Debug)]
236struct LTXCorruptedMarker;
237impl std::fmt::Display for LTXCorruptedMarker {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 f.write_str("ltx file corrupted")
240 }
241}
242impl std::error::Error for LTXCorruptedMarker {}
243
244/// Marker wrapping `Error::ChecksumMismatch`.
245#[derive(Debug)]
246struct ChecksumMismatchMarker;
247impl std::fmt::Display for ChecksumMismatchMarker {
248 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
249 f.write_str("invalid replica, checksum mismatch")
250 }
251}
252impl std::error::Error for ChecksumMismatchMarker {}
253
254// ── Public constructor ─────────────────────────────────────────────────────────
255
256/// Creates a new [`LTXError`] with appropriate recovery hints based on the
257/// underlying error kind.
258///
259/// Ported from `NewLTXError` in [email protected] litestream.go:74-93.
260///
261/// Uses chain-walking (matching Go's `errors.Is` semantics) so that a
262/// context-wrapped sentinel — e.g. `Error::Other(Box::new(Error::LTXCorrupted))`,
263/// mirroring `fmt.Errorf("%w: bad data", ErrLTXCorrupted)` — is still
264/// classified and hinted correctly.
265///
266/// # Arguments
267/// * `op` – Operation name (e.g. `"open"`, `"read"`).
268/// * `path` – File path (empty string if unknown).
269/// * `level` – LTX compaction level.
270/// * `min_txid` – Minimum TXID in the file.
271/// * `max_txid` – Maximum TXID in the file.
272/// * `err` – Cause; accepts `Error` or any boxed error.
273pub fn new_ltx_error(
274 op: impl Into<String>,
275 path: impl Into<String>,
276 level: i32,
277 min_txid: u64,
278 max_txid: u64,
279 err: Error,
280) -> LTXError {
281 let op = op.into();
282 let path = path.into();
283
284 // Choose the boxed inner error and hint based on the error kind.
285 // We use chain-walking helpers (matching Go's errors.Is semantics) so that
286 // a context-wrapped sentinel — e.g. Error::Other(Box::new(Error::LTXCorrupted))
287 // mirroring fmt.Errorf("%w: bad data", ErrLTXCorrupted) — is classified
288 // correctly. The marker wrappers ensure is_auto_recoverable() can detect the
289 // kind via downcast_ref after the boxed error is stored.
290 //
291 // Ported from NewLTXError [email protected] litestream.go:74-93.
292 let err_as_std: &dyn std::error::Error = &err;
293
294 let (inner, hint): (Box<dyn std::error::Error + Send + Sync>, String) =
295 if chain_contains_not_found(err_as_std) {
296 let hint = "LTX file is missing. This can happen after VACUUM, manual checkpoint, \
297 or state corruption. Run 'litestream reset <db>' or delete the \
298 .sqlite-litestream directory and restart."
299 .to_string();
300 // Preserve the original NotFound error for source() chain fidelity.
301 (
302 Box::new(io::Error::new(io::ErrorKind::NotFound, err.to_string())),
303 hint,
304 )
305 } else if matches!(&err, Error::LTXMissing)
306 || chain_contains::<LTXMissingMarker>(err_as_std)
307 || chain_contains_error_variant(err_as_std, ErrorVariantKind::LTXMissing)
308 {
309 let hint = "LTX file is missing. This can happen after VACUUM, manual checkpoint, \
310 or state corruption. Run 'litestream reset <db>' or delete the \
311 .sqlite-litestream directory and restart."
312 .to_string();
313 (Box::new(LTXMissingMarker), hint)
314 } else if matches!(&err, Error::LTXCorrupted)
315 || chain_contains::<LTXCorruptedMarker>(err_as_std)
316 || chain_contains_error_variant(err_as_std, ErrorVariantKind::LTXCorrupted)
317 {
318 let hint = "LTX file is corrupted. Delete the .sqlite-litestream directory and \
319 restart to recover from replica."
320 .to_string();
321 (Box::new(LTXCorruptedMarker), hint)
322 } else if matches!(&err, Error::ChecksumMismatch)
323 || chain_contains::<ChecksumMismatchMarker>(err_as_std)
324 || chain_contains_error_variant(err_as_std, ErrorVariantKind::ChecksumMismatch)
325 {
326 let hint = "LTX file is corrupted. Delete the .sqlite-litestream directory and \
327 restart to recover from replica."
328 .to_string();
329 (Box::new(ChecksumMismatchMarker), hint)
330 } else {
331 (Box::new(OpaqueError(err.to_string())), String::new())
332 };
333
334 LTXError {
335 op,
336 path,
337 level,
338 min_txid,
339 max_txid,
340 err: inner,
341 hint,
342 }
343}
344
345/// Thin wrapper so we can box an arbitrary `Error` string for the catch-all arm.
346#[derive(Debug)]
347struct OpaqueError(String);
348impl std::fmt::Display for OpaqueError {
349 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
350 f.write_str(&self.0)
351 }
352}
353impl std::error::Error for OpaqueError {}