Skip to main content

sys_lib/
error.rs

1//! The error type: every failure says what failed and what to do.
2
3use core::fmt;
4use std::{io, path::PathBuf, time::Duration};
5
6/// Everything that can go wrong in sys-lib.
7///
8/// Every variant's message is one sentence saying what failed, followed by
9/// what to do about it. No variant ever carries file content, registry content,
10/// or identifier values: [`Error::Malformed`] names the source (a constant
11/// path) and a line number only.
12///
13/// # Examples
14///
15/// ```
16/// use sys_lib as sys;
17///
18/// match sys::host::name() {
19///     Ok(name) => println!("host {name}"),
20///     Err(e) if e.is_unavailable() => println!("host name unknown here: {e}"),
21///     Err(e) => return Err(e),
22/// }
23/// # Ok::<(), sys_lib::Error>(())
24/// ```
25#[derive(Debug)]
26#[non_exhaustive]
27pub enum Error {
28    /// This reading does not exist on this platform. Treat the value as unknown.
29    Unsupported {
30        /// The reading.
31        what: &'static str,
32        /// The platform that lacks it.
33        platform: &'static str,
34    },
35    /// The OS refused (root-only files, a sandbox, SELinux, seccomp).
36    PermissionDenied {
37        /// The reading.
38        what: &'static str,
39        /// The permission that would allow it.
40        hint: &'static str,
41    },
42    /// A file or key that should exist does not (a container with a reduced `/proc`).
43    NotFound {
44        /// The reading.
45        what: &'static str,
46        /// The file, key, or call that was missing.
47        source: &'static str,
48    },
49    /// The OS returned data that does not parse.
50    Malformed {
51        /// The reading.
52        what: &'static str,
53        /// The file, key, or call the data came from.
54        source: &'static str,
55        /// The line, when the data is line-based.
56        line: Option<u32>,
57    },
58    /// A file, a list, or a caller's buffer exceeded its budget.
59    TooLarge {
60        /// The reading.
61        what: &'static str,
62        /// The budget that was exceeded.
63        limit: u64,
64    },
65    /// A sampler was asked again before any time passed on the OS clock.
66    TooSoon {
67        /// The time since the previous sample.
68        elapsed: Duration,
69        /// The shortest interval that gives a meaningful value.
70        minimum: Duration,
71    },
72    /// A system call failed.
73    Os {
74        /// The reading.
75        what: &'static str,
76        /// The call that failed.
77        call: &'static str,
78        /// The OS error code (`errno`, a Win32 error, an `NTSTATUS`, a `kern_return_t`).
79        code: i32,
80    },
81    /// File I/O failed outside the cases above.
82    Io {
83        /// The reading.
84        what: &'static str,
85        /// The underlying error.
86        source: io::Error,
87    },
88    /// Invalid input from the caller.
89    InvalidInput {
90        /// The input.
91        what: &'static str,
92        /// The rule it broke.
93        reason: &'static str,
94    },
95    /// The process guard found another copy holding the lock.
96    AlreadyRunning {
97        /// The other copy's process id, when its pid file is readable.
98        pid: Option<u32>,
99        /// The lock file.
100        lock_file: PathBuf,
101    },
102    /// The process guard's lock directory cannot be created, written, or trusted.
103    RunDirUnavailable {
104        /// The directory.
105        path: PathBuf,
106        /// Why, as an I/O error (the kind and a message naming the fix).
107        source: io::Error,
108    },
109    /// The hard open-file limit is below the process guard's minimum.
110    OpenFilesTooLow {
111        /// The hard limit the process has.
112        have: u64,
113        /// The minimum the guard was asked for.
114        need: u64,
115    },
116}
117
118/// Where unexpected OS data is reported.
119const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
120
121/// The result type used throughout sys-lib.
122pub type Result<T, E = Error> = core::result::Result<T, E>;
123
124impl Error {
125    /// True for the errors that mean "this fact is not available here", which a
126    /// caller usually treats as unknown: [`Unsupported`](Error::Unsupported),
127    /// [`PermissionDenied`](Error::PermissionDenied), and [`NotFound`](Error::NotFound).
128    ///
129    /// ```
130    /// let e = sys_lib::Error::Unsupported { what: "load average", platform: "windows" };
131    /// assert!(e.is_unavailable());
132    /// ```
133    #[must_use]
134    pub fn is_unavailable(&self) -> bool {
135        matches!(
136            self,
137            Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
138        )
139    }
140
141    /// An [`Io`](Error::Io) error, or the more specific variant its kind maps to.
142    #[cfg_attr(
143        not(any(target_os = "linux", target_os = "android", test)),
144        allow(dead_code)
145    )]
146    pub(crate) fn io(what: &'static str, source: &'static str, err: io::Error) -> Self {
147        match err.kind() {
148            io::ErrorKind::NotFound => Self::NotFound { what, source },
149            io::ErrorKind::PermissionDenied => Self::PermissionDenied {
150                what,
151                hint: "run as a user that may read it, or treat the value as unknown",
152            },
153            _ => Self::Io { what, source: err },
154        }
155    }
156}
157
158impl fmt::Display for Error {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        match self {
161            Self::Unsupported { what, platform } => write!(
162                f,
163                "{what} is not available on {platform}; treat the value as unknown"
164            ),
165            Self::PermissionDenied { what, hint } => {
166                write!(f, "reading {what} was refused by the OS; {hint}")
167            }
168            Self::NotFound { what, source } => write!(
169                f,
170                "{what} could not be read: {source} does not exist; treat the value as unknown \
171                 (minimal containers and sandboxes often lack it)"
172            ),
173            Self::Malformed { what, source, line } => {
174                write!(f, "{what} could not be read: {source} does not parse")?;
175                if let Some(line) = line {
176                    write!(f, " (line {line})")?;
177                }
178                write!(
179                    f,
180                    "; treat the value as unknown, and report it at {ISSUES} with the file \
181                     named here"
182                )
183            }
184            Self::TooLarge { what, limit } => write!(
185                f,
186                "{what} exceeded its budget of {limit}; treat the value as unknown, and if the \
187                 machine is genuinely that large, report it at {ISSUES}"
188            ),
189            Self::TooSoon { elapsed, minimum } => write!(
190                f,
191                "sampled again after {elapsed:?}, before the OS clock moved; sample at least \
192                 {minimum:?} apart"
193            ),
194            Self::Os { what, call, code } => write!(
195                f,
196                "{what} could not be read: {call} failed with OS error {code}; the code says \
197                 why, and if it is unexpected, report it at {ISSUES}"
198            ),
199            Self::Io { what, source } => write!(
200                f,
201                "{what} could not be read: {source}; treat the value as unknown, and if it is \
202                 unexpected, report it at {ISSUES}"
203            ),
204            Self::InvalidInput { what, reason } => write!(f, "invalid {what}: {reason}"),
205            Self::AlreadyRunning { pid, lock_file } => {
206                write!(f, "another copy is already running")?;
207                if let Some(pid) = pid {
208                    write!(f, " as process {pid}")?;
209                }
210                write!(
211                    f,
212                    " and holds {}; stop it, or give this copy another lock directory",
213                    lock_file.display()
214                )
215            }
216            Self::RunDirUnavailable { path, source } => write!(
217                f,
218                "the lock directory {} cannot be used: {source}",
219                path.display()
220            ),
221            Self::OpenFilesTooLow { have, need } => write!(
222                f,
223                "the hard open-file limit is {have}, below the required {need}; raise it \
224                 (LimitNOFILE= in the systemd unit, `ulimit -Hn`, or launchd's HardResourceLimits)"
225            ),
226        }
227    }
228}
229
230impl std::error::Error for Error {
231    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
232        match self {
233            Self::Io { source, .. } | Self::RunDirUnavailable { source, .. } => Some(source),
234            _ => None,
235        }
236    }
237}
238
239#[cfg(test)]
240mod tests {
241    use std::error::Error as _;
242
243    use super::*;
244
245    const fn assert_send_sync<T: Send + Sync + 'static>() {}
246    const _: () = assert_send_sync::<Error>();
247
248    fn every_variant() -> Vec<Error> {
249        vec![
250            Error::Unsupported {
251                what: "load average",
252                platform: "windows",
253            },
254            Error::PermissionDenied {
255                what: "board serial",
256                hint: "run as root",
257            },
258            Error::NotFound {
259                what: "os-release",
260                source: "/etc/os-release",
261            },
262            Error::Malformed {
263                what: "cpu list",
264                source: "/proc/self/status",
265                line: Some(7),
266            },
267            Error::Malformed {
268                what: "cpu list",
269                source: "/proc/self/status",
270                line: None,
271            },
272            Error::TooLarge {
273                what: "mount list",
274                limit: 4096,
275            },
276            Error::TooSoon {
277                elapsed: Duration::from_millis(1),
278                minimum: Duration::from_millis(10),
279            },
280            Error::Os {
281                what: "host name",
282                call: "GetComputerNameExW",
283                code: 5,
284            },
285            Error::Io {
286                what: "status",
287                source: io::Error::other("disk on fire"),
288            },
289            Error::InvalidInput {
290                what: "guard name",
291                reason: "must not contain '/'",
292            },
293            Error::AlreadyRunning {
294                pid: Some(4821),
295                lock_file: PathBuf::from("/run/site/site.lock"),
296            },
297            Error::AlreadyRunning {
298                pid: None,
299                lock_file: PathBuf::from("/run/site/site.lock"),
300            },
301            Error::RunDirUnavailable {
302                path: PathBuf::from("/tmp"),
303                source: io::Error::other("writable by other users; chmod 700 it"),
304            },
305            Error::OpenFilesTooLow {
306                have: 256,
307                need: 1024,
308            },
309        ]
310    }
311
312    #[test]
313    fn test_error_display_every_variant_says_what_to_do() {
314        // NFR-15: every message names the failure and a next step.
315        for e in every_variant() {
316            let text = e.to_string();
317            assert!(!text.is_empty());
318            assert!(
319                text.contains(';') || text.contains(':'),
320                "no explanation in {text:?}"
321            );
322            assert!(!text.ends_with(' '), "trailing space in {text:?}");
323        }
324    }
325
326    #[test]
327    fn test_error_display_includes_the_specific_values() {
328        let e = Error::AlreadyRunning {
329            pid: Some(4821),
330            lock_file: PathBuf::from("site.lock"),
331        };
332        assert!(e.to_string().contains("process 4821"));
333        let e = Error::OpenFilesTooLow {
334            have: 256,
335            need: 1024,
336        };
337        assert!(e.to_string().contains("256") && e.to_string().contains("1024"));
338        let e = Error::Malformed {
339            what: "x",
340            source: "/proc/stat",
341            line: Some(3),
342        };
343        assert!(e.to_string().contains("line 3"));
344    }
345
346    #[test]
347    fn test_error_is_unavailable_only_for_unknown_facts() {
348        for e in every_variant() {
349            let expected = matches!(
350                e,
351                Error::Unsupported { .. } | Error::PermissionDenied { .. } | Error::NotFound { .. }
352            );
353            assert_eq!(e.is_unavailable(), expected, "{e:?}");
354        }
355    }
356
357    #[test]
358    fn test_error_source_only_for_wrapped_io() {
359        for e in every_variant() {
360            let wraps = matches!(e, Error::Io { .. } | Error::RunDirUnavailable { .. });
361            assert_eq!(e.source().is_some(), wraps, "{e:?}");
362        }
363    }
364
365    #[test]
366    fn test_error_io_maps_not_found_and_permission_denied() {
367        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::NotFound));
368        assert!(matches!(
369            e,
370            Error::NotFound {
371                source: "/proc/x",
372                ..
373            }
374        ));
375        let e = Error::io(
376            "x",
377            "/proc/x",
378            io::Error::from(io::ErrorKind::PermissionDenied),
379        );
380        assert!(matches!(e, Error::PermissionDenied { .. }));
381        let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::Interrupted));
382        assert!(matches!(e, Error::Io { .. }));
383    }
384}