Skip to main content

indexedlog/
errors.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8//! Errors used by the crate
9//!
10//! See [`Error`] for the main type.
11
12use std::fmt;
13use std::io;
14use std::path::Path;
15
16// Error design goals:
17// - Callsites can test whether an error is caused by data corruption or other
18//   issues (for example, permission or resource issues).
19//   This is important because it allows callsites (including within the
20//   crate like RotateLog) to decide whether to remove the bad data and
21//   try auto recovery.
22// - The library can change error structure internals. That means accesses
23//   to the error object are via public methods instead of struct or enum
24//   fields. `Error` is the only opaque public error type.
25// - Compatible with std Error. Therefore anyhow::Error is supported too.
26
27/// Represents all possible errors that can occur when using indexedlog.
28pub struct Error {
29    // Boxing makes `Result<Error, _>` smaller.
30    inner: Box<Inner>,
31}
32
33pub type Result<T> = std::result::Result<T, Error>;
34
35#[derive(Default)]
36struct Inner {
37    sources: Vec<Box<dyn std::error::Error + Send + Sync + 'static>>,
38    messages: Vec<String>,
39    is_corruption: bool,
40    io_error_kind: Option<io::ErrorKind>,
41}
42
43impl Error {
44    /// Return `true` if the error is considered as (filesystem) data
45    /// corruption.
46    ///
47    /// Application can use this information to decide whether to try the
48    /// expensive `repair` API.
49    ///
50    /// Data corruption is in general when the data can be confidently read,
51    /// but does not meet integrity expectation. Note: a "file not found" error
52    /// is a piece of information that is "confidently read", because it's
53    /// unexpected to get a different error by using different users, or
54    /// process settings. So "file not found" is not always a corruption.
55    ///
56    /// For example, those are data corruption errors:
57    /// - XxHash checksum does not match the data
58    /// - Some data says "read this file in 100..200 byte range", but logically,
59    ///   the file only has 150 bytes.
60    /// - A byte is expected to only be 1 or 2. But it turns out to be 0.
61    /// - Both file "a" and "b" are expected to exist in a directory, but "a"
62    ///   can be found, while "b" does not exist.
63    ///
64    /// Those are not data corruption:
65    /// - Cannot open a file due to permission issues or exceeding the file
66    ///   descriptor limit.
67    /// - Programming errors and API misuse. For example, a user-provided
68    ///   index function says `data[5..10] is the index key` while `data`
69    /// - Both file "a" and "b" are expected to exist in a directory, but "a"
70    ///   can be found, while "b" cannot be opened due to permission issues.
71    ///
72    /// It's expected that data corruption can *only* happen when the managed
73    /// files or directories are changed without using this crate.  For example,
74    /// a hard reboot, deleting lock files while multiple processes are
75    /// attempting to write, deleting or changing files in some ways. Issues
76    /// like "disk is full", "permission errors", "process killed at random
77    /// time" are expected to not cause data corruption (but only data loss).
78    pub fn is_corruption(&self) -> bool {
79        self.inner.is_corruption
80    }
81
82    pub fn io_error_kind(&self) -> io::ErrorKind {
83        self.inner.io_error_kind.unwrap_or(io::ErrorKind::Other)
84    }
85
86    // Following methods are used by this crate only.
87    // External code should not construct or modify `Error`.
88
89    pub(crate) fn message(mut self, message: impl ToString) -> Self {
90        self.inner.messages.push(message.to_string());
91        self
92    }
93
94    pub(crate) fn source(self, source: impl std::error::Error + Send + Sync + 'static) -> Self {
95        self.source_dyn(Box::new(source))
96    }
97
98    pub(crate) fn source_dyn(
99        mut self,
100        source: Box<dyn std::error::Error + Send + Sync + 'static>,
101    ) -> Self {
102        // Inherit the data corruption flag.
103        if let Some(err) = source.downcast_ref::<Error>() {
104            if err.is_corruption() {
105                self = self.mark_corruption();
106            }
107        }
108
109        self.inner.sources.push(source);
110        self
111    }
112
113    pub(crate) fn mark_corruption(mut self) -> Self {
114        self.inner.is_corruption = true;
115        self
116    }
117
118    pub(crate) fn blank() -> Self {
119        Error {
120            inner: Default::default(),
121        }
122    }
123
124    /// A ProgrammingError that breaks some internal assumptions.
125    /// For example, passing an invalid parameter to an API.
126    #[inline(never)]
127    pub(crate) fn programming(message: impl ToString) -> Self {
128        Self::blank().message(format!("ProgrammingError: {}", message.to_string()))
129    }
130
131    /// A data corruption error with path.
132    ///
133    /// If there is an [`IOError`], use [`IoResultExt::context`] instead.
134    #[inline(never)]
135    pub(crate) fn corruption(path: &Path, message: impl ToString) -> Self {
136        let message = format!("{:?}: {}", path, message.to_string());
137        Self::blank().mark_corruption().message(message)
138    }
139
140    /// An error with a path that is not a data corruption.
141    ///
142    /// If there is an [`IOError`], use [`IoResultExt::context`] instead.
143    #[inline(never)]
144    pub(crate) fn path(path: &Path, message: impl ToString) -> Self {
145        let message = format!("{:?}: {}", path, message.to_string());
146        Self::blank().message(message)
147    }
148
149    /// Wrap a dynamic stdlib error.
150    #[inline(never)]
151    pub(crate) fn wrap(
152        err: Box<dyn std::error::Error + Send + Sync + 'static>,
153        message: impl LazyToString,
154    ) -> Self {
155        Self::blank()
156            .message(message.to_string_costly())
157            .source_dyn(err)
158    }
159}
160
161/// Create an Error from a message.
162impl From<&str> for Error {
163    fn from(s: &str) -> Self {
164        Self::blank().message(s)
165    }
166}
167
168/// Create an Error from a message and another error.
169impl<E: std::error::Error + Send + Sync + 'static> From<(&str, E)> for Error {
170    fn from(s: (&str, E)) -> Self {
171        Self::blank().message(s.0).source(s.1)
172    }
173}
174
175impl fmt::Display for Error {
176    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
177        let mut lines = Vec::new();
178        for message in &self.inner.messages {
179            lines.push(message.to_string());
180        }
181        if !self.inner.sources.is_empty() {
182            lines.push(format!("Caused by {} errors:", self.inner.sources.len()));
183            for source in &self.inner.sources {
184                lines.push(indent(format!("{source}"), 2, '-'));
185            }
186        }
187        write!(f, "{}", lines.join("\n"))
188    }
189}
190
191impl fmt::Debug for Error {
192    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
193        let mut lines = Vec::new();
194        for message in &self.inner.messages {
195            lines.push(message.to_string());
196        }
197        if self.is_corruption() {
198            lines.push("(This error is considered as a data corruption)".to_string())
199        }
200        if !self.inner.sources.is_empty() {
201            lines.push(format!("Caused by {} errors:", self.inner.sources.len()));
202            for source in &self.inner.sources {
203                lines.push(indent(format!("{source:?}"), 2, '-'));
204            }
205        }
206        write!(f, "{}", lines.join("\n"))
207    }
208}
209
210fn indent(s: String, spaces: usize, first_line_prefix: char) -> String {
211    if spaces == 0 {
212        s
213    } else {
214        format!(
215            "{}{}{}",
216            first_line_prefix,
217            " ".repeat(spaces - 1),
218            s.lines()
219                .collect::<Vec<_>>()
220                .join(&format!("\n{}", " ".repeat(spaces)))
221        )
222    }
223}
224
225pub(crate) trait ResultExt<T> {
226    /// Mark the error as data corruption.
227    fn corruption(self) -> Self;
228
229    /// Add a string message as context.
230    fn context<S: LazyToString>(self, message: S) -> Self;
231
232    /// Add an error source.
233    fn source<E: std::error::Error + Send + Sync + 'static>(self, source: E) -> Self;
234}
235
236impl<T> ResultExt<T> for Result<T> {
237    fn corruption(self) -> Self {
238        self.map_err(|err| err.mark_corruption())
239    }
240
241    fn context<S: LazyToString>(self, message: S) -> Self {
242        self.map_err(|err| err.message(message.to_string_costly()))
243    }
244
245    fn source<E: std::error::Error + Send + Sync + 'static>(self, source: E) -> Self {
246        self.map_err(|err| err.source(source))
247    }
248}
249
250impl std::error::Error for Error {
251    // This 'Error' type is designed to be opaque (internal states are
252    // private, including inner errors), and takes responsibility
253    // of displaying a -chain- tree of errors. So it might be desirable
254    // not implementing `source` here, and expose public APIs for all
255    // use-needs.
256}
257
258pub(crate) trait IoResultExt<T> {
259    /// Wrap [`io::Result`] in [`Result`] with extra context about filesystem
260    /// path and the operation name.
261    ///
262    /// Mark InvalidData and UnexpectedEof as data corruption automatically.
263    ///
264    /// Consider using [`ResultExt::corruption`] to mark the error as data
265    /// corruption if appropriate.
266    fn context<TS: LazyToString>(self, path: &Path, message: TS) -> Result<T>;
267
268    /// Wrap an infallible Result. For example, writing to memory.
269    fn infallible(self) -> Result<T>;
270}
271
272impl<T> IoResultExt<T> for std::io::Result<T> {
273    fn context<TS: LazyToString>(self, path: &Path, message: TS) -> Result<T> {
274        self.map_err(|err| {
275            use std::io::ErrorKind;
276            let kind = err.kind().clone();
277            let corruption = match kind {
278                // For example, try to mmap 200 bytes, but the file
279                // only has 100 bytes. This is unlikely caused by
280                // non-data-corruption issues.
281                ErrorKind::UnexpectedEof | ErrorKind::InvalidData => true,
282                _ => false,
283            };
284            let is_eperm = kind == ErrorKind::PermissionDenied;
285
286            let mut err = Error::blank().source(err).message(format!(
287                "{:?}: {}",
288                path,
289                message.to_string_costly()
290            ));
291            if corruption {
292                err = err.mark_corruption();
293            }
294            err.inner.io_error_kind = Some(kind);
295
296            // Provide more context for PermissionDenied
297            if is_eperm {
298                #[cfg(unix)]
299                #[allow(clippy::redundant_closure_call)]
300                {
301                    let add_stat_context = |path: &Path, err: Error| {
302                        use std::os::unix::fs::MetadataExt;
303                        if let Ok(meta) = path.metadata() {
304                            let msg = format!(
305                                "stat({:?}) = dev:{} ino:{} mode:0o{:o} uid:{} gid:{} mtime:{}",
306                                path,
307                                meta.dev(),
308                                meta.ino(),
309                                meta.mode(),
310                                meta.uid(),
311                                meta.gid(),
312                                meta.mtime()
313                            );
314                            err.message(msg)
315                        } else {
316                            err
317                        }
318                    };
319                    err = add_stat_context(path, err);
320                    // For EPERM on mkdir, parent directory stat is useful.
321                    if let Some(parent) = path.parent() {
322                        err = add_stat_context(parent, err);
323                    }
324                }
325            }
326
327            err
328        })
329    }
330
331    fn infallible(self) -> Result<T> {
332        self.map_err(|err| Error::blank().source(err).message("Unexpected failure"))
333    }
334}
335
336pub(crate) trait LazyToString {
337    fn to_string_costly(&self) -> String;
338}
339
340// &'static str is cheap.
341impl LazyToString for &'static str {
342    fn to_string_costly(&self) -> String {
343        (*self).to_string()
344    }
345}
346
347impl<F: Fn() -> String> LazyToString for F {
348    fn to_string_costly(&self) -> String {
349        self()
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356
357    #[test]
358    fn test_error_format() {
359        let mut e = Error::blank();
360
361        assert_eq!(format!("{e}"), "");
362
363        // Attach messages.
364
365        e = e.message("Error Message 1");
366        e = e.message("Error Message 2");
367        assert_eq!(
368            format!("{e}"),
369            r#"Error Message 1
370Error Message 2"#
371        );
372
373        // Attach error sources.
374        e = e.source(Error::blank().message("Inner Error 1"));
375        e = e.source(
376            Error::blank()
377                .message("Inner Error 2")
378                .source(Error::blank().message("Nested Error 1")),
379        );
380        assert_eq!(
381            format!("{e}"),
382            r#"Error Message 1
383Error Message 2
384Caused by 2 errors:
385- Inner Error 1
386- Inner Error 2
387  Caused by 1 errors:
388  - Nested Error 1"#
389        );
390
391        // Mark as data corruption.
392        e = e.mark_corruption();
393        assert_eq!(
394            format!("{e:?}"),
395            r#"Error Message 1
396Error Message 2
397(This error is considered as a data corruption)
398Caused by 2 errors:
399- Inner Error 1
400- Inner Error 2
401  Caused by 1 errors:
402  - Nested Error 1"#
403        );
404    }
405
406    #[test]
407    fn test_result_ext() {
408        let result: Result<()> = Err(Error::blank()).corruption();
409        assert!(result.unwrap_err().is_corruption());
410    }
411
412    #[test]
413    fn test_inherit_corruption() {
414        assert!(!Error::blank().is_corruption());
415        assert!(!Error::blank().source(Error::blank()).is_corruption());
416        assert!(
417            Error::blank()
418                .source(Error::blank().mark_corruption())
419                .is_corruption()
420        );
421        assert!(
422            Error::blank()
423                .source(Error::blank().source(Error::blank().mark_corruption()))
424                .is_corruption()
425        );
426    }
427
428    #[test]
429    fn test_io_result_ext() {
430        let err = io_result().context(Path::new("a.txt"), "cannot open for reading");
431        assert_eq!(
432            format!("{}", err.unwrap_err()),
433            r#""a.txt": cannot open for reading
434Caused by 1 errors:
435- io::Error: something wrong happened"#
436        );
437
438        let name = "b.txt";
439        let err = io_result().context(Path::new(&name), || format!("cannot open {name}"));
440        assert_eq!(
441            format!("{}", err.unwrap_err()),
442            r#""b.txt": cannot open b.txt
443Caused by 1 errors:
444- io::Error: something wrong happened"#
445        );
446    }
447
448    fn io_result() -> std::io::Result<()> {
449        Err(std::io::Error::other("io::Error: something wrong happened"))
450    }
451}