Skip to main content

wal_db/
error.rs

1//! The crate error type.
2//!
3//! Every fallible operation in `wal-db` returns [`Result<T>`], whose error is
4//! [`WalError`]. The type integrates with the portfolio's `error-forge`
5//! framework — it implements [`error_forge::ForgeError`], so callers get the
6//! stable `kind` / `is_fatal` metadata other crates rely on — while still
7//! exposing the underlying [`std::io::Error`] through [`std::error::Error::source`]
8//! for code that needs to inspect the OS error kind directly.
9
10use std::{fmt, io};
11
12use error_forge::ForgeError;
13
14/// A specialised [`Result`](std::result::Result) for log operations.
15///
16/// Defaults its error to [`WalError`], so most signatures read `Result<T>`.
17pub type Result<T, E = WalError> = std::result::Result<T, E>;
18
19/// Everything that can go wrong while appending to, syncing, or recovering a log.
20///
21/// The type is [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute):
22/// future versions may add variants without a major bump, so a `match` over it
23/// must include a wildcard arm.
24#[non_exhaustive]
25#[derive(Debug)]
26pub enum WalError {
27    /// An underlying I/O operation failed.
28    ///
29    /// `context` names the operation that was attempted (for example
30    /// `"open log file"` or `"flush to stable storage"`) so the message is
31    /// actionable without a backtrace. The original [`io::Error`] is preserved
32    /// as the [`source`](std::error::Error::source); inspect it when the OS
33    /// error kind (disk full, permission denied, interrupted) drives recovery.
34    Io {
35        /// What the log was trying to do when the I/O error occurred.
36        context: &'static str,
37        /// The underlying operating-system error.
38        source: io::Error,
39    },
40
41    /// An append was rejected because the record is larger than the configured
42    /// limit.
43    ///
44    /// Records are bounded by [`WalConfig::max_record_size`](crate::WalConfig::max_record_size)
45    /// so that a single oversized — or maliciously crafted — record cannot force
46    /// an unbounded allocation on the recovery path. The append makes no change
47    /// to the log; the caller may split the payload or raise the limit.
48    RecordTooLarge {
49        /// The length of the rejected record, in bytes.
50        len: usize,
51        /// The configured maximum record size, in bytes.
52        max: u32,
53    },
54
55    /// Recovery reached a record that is not intact.
56    ///
57    /// Either the record's checksum did not match its bytes, or its length
58    /// prefix is implausible. In an append-only log a damaged record means
59    /// everything after it is untrustworthy, so iteration surfaces this once and
60    /// then stops. `offset` is the byte position of the record where the break
61    /// was detected.
62    Corruption {
63        /// Byte offset of the record at which recovery stopped.
64        offset: u64,
65        /// A short, human-readable reason the record was rejected.
66        reason: &'static str,
67    },
68
69    /// A typed record could not be encoded or decoded.
70    ///
71    /// Produced only by the typed-record API (the `pack-io` and `pack-io-2`
72    /// features): `Wal::append_typed` or `Wal::append_pack` when a value fails
73    /// to serialise, or `Record::decode`, `unpack`, or `unpack_with` when a
74    /// record's bytes do not deserialise into the requested type.
75    /// `detail` carries the underlying codec error's message.
76    Encoding {
77        /// The underlying serialization error, as text.
78        detail: String,
79    },
80}
81
82impl WalError {
83    /// Wrap an [`io::Error`] with the static context describing the operation.
84    pub(crate) fn io(context: &'static str, source: io::Error) -> Self {
85        WalError::Io { context, source }
86    }
87
88    /// Build a [`WalError::Corruption`] for the record at `offset`.
89    pub(crate) fn corruption(offset: u64, reason: &'static str) -> Self {
90        WalError::Corruption { offset, reason }
91    }
92
93    /// Build a [`WalError::Encoding`] from a codec error's message.
94    #[cfg(any(feature = "pack-io", feature = "pack-io-2"))]
95    pub(crate) fn encoding(detail: impl core::fmt::Display) -> Self {
96        WalError::Encoding {
97            detail: detail.to_string(),
98        }
99    }
100}
101
102impl fmt::Display for WalError {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        match self {
105            WalError::Io { context, source } => {
106                write!(f, "i/o error while {context}: {source}")
107            }
108            WalError::RecordTooLarge { len, max } => {
109                write!(
110                    f,
111                    "record of {len} bytes exceeds the maximum of {max} bytes"
112                )
113            }
114            WalError::Corruption { offset, reason } => {
115                write!(f, "log corruption at byte offset {offset}: {reason}")
116            }
117            WalError::Encoding { detail } => {
118                write!(f, "typed record codec error: {detail}")
119            }
120        }
121    }
122}
123
124impl std::error::Error for WalError {
125    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
126        match self {
127            WalError::Io { source, .. } => Some(source),
128            WalError::RecordTooLarge { .. }
129            | WalError::Corruption { .. }
130            | WalError::Encoding { .. } => None,
131        }
132    }
133}
134
135/// A bare [`io::Error`] converts into [`WalError::Io`] with a generic context.
136///
137/// Call sites that know what they were doing attach a specific context instead;
138/// this exists for the `?` ergonomics of code that does not.
139impl From<io::Error> for WalError {
140    fn from(source: io::Error) -> Self {
141        WalError::Io {
142            context: "performing a log i/o operation",
143            source,
144        }
145    }
146}
147
148impl ForgeError for WalError {
149    fn kind(&self) -> &'static str {
150        match self {
151            WalError::Io { .. } => "Io",
152            WalError::RecordTooLarge { .. } => "RecordTooLarge",
153            WalError::Corruption { .. } => "Corruption",
154            WalError::Encoding { .. } => "Encoding",
155        }
156    }
157
158    fn caption(&self) -> &'static str {
159        "write-ahead log error"
160    }
161
162    /// Corruption is unrecoverable by retry: the bytes on disk are already
163    /// damaged. I/O and size errors are left non-fatal for the caller to judge.
164    fn is_fatal(&self) -> bool {
165        matches!(self, WalError::Corruption { .. })
166    }
167}
168
169#[cfg(test)]
170#[allow(clippy::unwrap_used, clippy::expect_used)]
171mod tests {
172    use super::*;
173
174    #[test]
175    fn test_io_error_exposes_source() {
176        let inner = io::Error::new(io::ErrorKind::PermissionDenied, "denied");
177        let err = WalError::io("open log file", inner);
178        let source = std::error::Error::source(&err).expect("io error has a source");
179        let io_source = source
180            .downcast_ref::<io::Error>()
181            .expect("source downcasts to io::Error");
182        assert_eq!(io_source.kind(), io::ErrorKind::PermissionDenied);
183    }
184
185    #[test]
186    fn test_record_too_large_has_no_source() {
187        let err = WalError::RecordTooLarge {
188            len: 4096,
189            max: 1024,
190        };
191        assert!(std::error::Error::source(&err).is_none());
192    }
193
194    #[test]
195    fn test_corruption_is_fatal_others_are_not() {
196        assert!(WalError::corruption(128, "checksum mismatch").is_fatal());
197        assert!(!WalError::RecordTooLarge { len: 1, max: 0 }.is_fatal());
198        let io = WalError::io("x", io::Error::from(io::ErrorKind::Other));
199        assert!(!io.is_fatal());
200    }
201
202    #[test]
203    fn test_kind_matches_variant() {
204        assert_eq!(WalError::corruption(0, "x").kind(), "Corruption");
205        assert_eq!(
206            WalError::RecordTooLarge { len: 1, max: 0 }.kind(),
207            "RecordTooLarge"
208        );
209    }
210
211    #[test]
212    fn test_display_is_actionable() {
213        let err = WalError::RecordTooLarge {
214            len: 4096,
215            max: 1024,
216        };
217        assert_eq!(
218            err.to_string(),
219            "record of 4096 bytes exceeds the maximum of 1024 bytes"
220        );
221    }
222}