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