use core::fmt;
use std::{io, path::PathBuf, time::Duration};
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
Unsupported {
what: &'static str,
platform: &'static str,
},
PermissionDenied {
what: &'static str,
hint: &'static str,
},
NotFound {
what: &'static str,
source: &'static str,
},
Malformed {
what: &'static str,
source: &'static str,
line: Option<u32>,
},
TooLarge {
what: &'static str,
limit: u64,
},
TooSoon {
elapsed: Duration,
minimum: Duration,
},
Os {
what: &'static str,
call: &'static str,
code: i32,
},
Io {
what: &'static str,
source: io::Error,
},
InvalidInput {
what: &'static str,
reason: &'static str,
},
AlreadyRunning {
pid: Option<u32>,
lock_file: PathBuf,
},
RunDirUnavailable {
path: PathBuf,
source: io::Error,
},
#[cfg(feature = "device-id")]
#[cfg_attr(docsrs, doc(cfg(feature = "device-id")))]
NoIdentifierSource {
basis: crate::device::Basis,
},
OpenFilesTooLow {
have: u64,
need: u64,
},
}
const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
pub type Result<T, E = Error> = core::result::Result<T, E>;
impl Error {
#[must_use]
pub fn is_unavailable(&self) -> bool {
matches!(
self,
Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
)
}
#[cfg_attr(
not(any(target_os = "linux", target_os = "android", test)),
allow(dead_code)
)]
pub(crate) fn io(what: &'static str, source: &'static str, err: io::Error) -> Self {
match err.kind() {
io::ErrorKind::NotFound => Self::NotFound { what, source },
io::ErrorKind::PermissionDenied => Self::PermissionDenied {
what,
hint: "run as a user that may read it, or treat the value as unknown",
},
_ => Self::Io { what, source: err },
}
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unsupported { what, platform } => write!(
f,
"{what} is not available on {platform}; treat the value as unknown"
),
Self::PermissionDenied { what, hint } => {
write!(f, "reading {what} was refused by the OS; {hint}")
}
Self::NotFound { what, source } => write!(
f,
"{what} could not be read: {source} does not exist; treat the value as unknown \
(minimal containers and sandboxes often lack it)"
),
Self::Malformed { what, source, line } => {
write!(f, "{what} could not be read: {source} does not parse")?;
if let Some(line) = line {
write!(f, " (line {line})")?;
}
write!(
f,
"; treat the value as unknown, and report it at {ISSUES} with the file \
named here"
)
}
Self::TooLarge { what, limit } => write!(
f,
"{what} exceeded its budget of {limit}; treat the value as unknown, and if the \
machine is genuinely that large, report it at {ISSUES}"
),
Self::TooSoon { elapsed, minimum } => write!(
f,
"sampled again after {elapsed:?}, before the OS clock moved; sample at least \
{minimum:?} apart"
),
Self::Os { what, call, code } => write!(
f,
"{what} could not be read: {call} failed with OS error {code}; the code says \
why, and if it is unexpected, report it at {ISSUES}"
),
Self::Io { what, source } => write!(
f,
"{what} could not be read: {source}; treat the value as unknown, and if it is \
unexpected, report it at {ISSUES}"
),
Self::InvalidInput { what, reason } => write!(f, "invalid {what}: {reason}"),
Self::AlreadyRunning { pid, lock_file } => {
write!(f, "another copy is already running")?;
if let Some(pid) = pid {
write!(f, " as process {pid}")?;
}
write!(
f,
" and holds {}; stop it, or give this copy another lock directory",
lock_file.display()
)
}
Self::RunDirUnavailable { path, source } => write!(
f,
"the lock directory {} cannot be used: {source}",
path.display()
),
#[cfg(feature = "device-id")]
Self::NoIdentifierSource { basis } => write!(
f,
"no usable device identifier for {basis:?}: device::report() shows the state of each source"
),
Self::OpenFilesTooLow { have, need } => write!(
f,
"the hard open-file limit is {have}, below the required {need}; raise it \
(LimitNOFILE= in the systemd unit, `ulimit -Hn`, or launchd's HardResourceLimits)"
),
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io { source, .. } | Self::RunDirUnavailable { source, .. } => Some(source),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use std::error::Error as _;
use super::*;
const fn assert_send_sync<T: Send + Sync + 'static>() {}
const _: () = assert_send_sync::<Error>();
fn every_variant() -> Vec<Error> {
vec![
Error::Unsupported {
what: "load average",
platform: "windows",
},
Error::PermissionDenied {
what: "board serial",
hint: "run as root",
},
Error::NotFound {
what: "os-release",
source: "/etc/os-release",
},
Error::Malformed {
what: "cpu list",
source: "/proc/self/status",
line: Some(7),
},
Error::Malformed {
what: "cpu list",
source: "/proc/self/status",
line: None,
},
Error::TooLarge {
what: "mount list",
limit: 4096,
},
Error::TooSoon {
elapsed: Duration::from_millis(1),
minimum: Duration::from_millis(10),
},
Error::Os {
what: "host name",
call: "GetComputerNameExW",
code: 5,
},
Error::Io {
what: "status",
source: io::Error::other("disk on fire"),
},
Error::InvalidInput {
what: "guard name",
reason: "must not contain '/'",
},
Error::AlreadyRunning {
pid: Some(4821),
lock_file: PathBuf::from("/run/site/site.lock"),
},
Error::AlreadyRunning {
pid: None,
lock_file: PathBuf::from("/run/site/site.lock"),
},
Error::RunDirUnavailable {
path: PathBuf::from("/tmp"),
source: io::Error::other("writable by other users; chmod 700 it"),
},
Error::OpenFilesTooLow {
have: 256,
need: 1024,
},
]
}
#[test]
fn test_error_display_every_variant_says_what_to_do() {
for e in every_variant() {
let text = e.to_string();
assert!(!text.is_empty());
assert!(
text.contains(';') || text.contains(':'),
"no explanation in {text:?}"
);
assert!(!text.ends_with(' '), "trailing space in {text:?}");
}
}
#[test]
fn test_error_display_includes_the_specific_values() {
let e = Error::AlreadyRunning {
pid: Some(4821),
lock_file: PathBuf::from("site.lock"),
};
assert!(e.to_string().contains("process 4821"));
let e = Error::OpenFilesTooLow {
have: 256,
need: 1024,
};
assert!(e.to_string().contains("256") && e.to_string().contains("1024"));
let e = Error::Malformed {
what: "x",
source: "/proc/stat",
line: Some(3),
};
assert!(e.to_string().contains("line 3"));
}
#[test]
fn test_error_is_unavailable_only_for_unknown_facts() {
for e in every_variant() {
let expected = matches!(
e,
Error::Unsupported { .. } | Error::PermissionDenied { .. } | Error::NotFound { .. }
);
assert_eq!(e.is_unavailable(), expected, "{e:?}");
}
}
#[test]
fn test_error_source_only_for_wrapped_io() {
for e in every_variant() {
let wraps = matches!(e, Error::Io { .. } | Error::RunDirUnavailable { .. });
assert_eq!(e.source().is_some(), wraps, "{e:?}");
}
}
#[test]
fn test_error_io_maps_not_found_and_permission_denied() {
let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::NotFound));
assert!(matches!(
e,
Error::NotFound {
source: "/proc/x",
..
}
));
let e = Error::io(
"x",
"/proc/x",
io::Error::from(io::ErrorKind::PermissionDenied),
);
assert!(matches!(e, Error::PermissionDenied { .. }));
let e = Error::io("x", "/proc/x", io::Error::from(io::ErrorKind::Interrupted));
assert!(matches!(e, Error::Io { .. }));
}
}