1use core::fmt;
4use std::{io, path::PathBuf, time::Duration};
5
6#[derive(Debug)]
26#[non_exhaustive]
27pub enum Error {
28 Unsupported {
30 what: &'static str,
32 platform: &'static str,
34 },
35 PermissionDenied {
37 what: &'static str,
39 hint: &'static str,
41 },
42 NotFound {
44 what: &'static str,
46 source: &'static str,
48 },
49 Malformed {
51 what: &'static str,
53 source: &'static str,
55 line: Option<u32>,
57 },
58 TooLarge {
60 what: &'static str,
62 limit: u64,
64 },
65 TooSoon {
67 elapsed: Duration,
69 minimum: Duration,
71 },
72 Os {
74 what: &'static str,
76 call: &'static str,
78 code: i32,
80 },
81 Io {
83 what: &'static str,
85 source: io::Error,
87 },
88 InvalidInput {
90 what: &'static str,
92 reason: &'static str,
94 },
95 AlreadyRunning {
97 pid: Option<u32>,
99 lock_file: PathBuf,
101 },
102 RunDirUnavailable {
104 path: PathBuf,
106 source: io::Error,
108 },
109 OpenFilesTooLow {
111 have: u64,
113 need: u64,
115 },
116}
117
118const ISSUES: &str = "https://github.com/jamesgober/sys-lib/issues";
120
121pub type Result<T, E = Error> = core::result::Result<T, E>;
123
124impl Error {
125 #[must_use]
134 pub fn is_unavailable(&self) -> bool {
135 matches!(
136 self,
137 Self::Unsupported { .. } | Self::PermissionDenied { .. } | Self::NotFound { .. }
138 )
139 }
140
141 #[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 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}