Skip to main content

dima_core/
error.rs

1//! The library's error type and its mapping to process exit classes.
2//!
3//! Every error says *what* failed and *where* (source, record, line, column, byte), and most
4//! carry a hint telling the user how to fix it. Front ends render the error with
5//! [`DimaError::report`] (GUI) or line by line (`error:` / `caused by:` / `hint:`, CLI), and map
6//! [`DimaError::class`] to the documented exit codes.
7
8use std::fmt;
9use std::io;
10use std::path::PathBuf;
11
12/// Convenience alias used throughout the library.
13pub type Result<T, E = DimaError> = std::result::Result<T, E>;
14
15/// Exit classes of the command-line interface (documented exit codes).
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
17pub enum ExitClass {
18    /// Exit 1: a bug in DiMA.
19    Internal,
20    /// Exit 2: invalid command line or parameters.
21    Usage,
22    /// Exit 3: a file or stream could not be opened, read or written, or the operating system
23    /// refused a resource (a thread).
24    Io,
25    /// Exit 4: the input data are malformed or unsupported.
26    InvalidInput,
27    /// Exit 130 (or 143/129, chosen by the front end from the signal received).
28    Cancelled,
29}
30
31impl ExitClass {
32    /// The process exit code (cancellation defaults to 130, the SIGINT convention).
33    #[must_use]
34    pub const fn code(self) -> u8 {
35        match self {
36            Self::Internal => 1,
37            Self::Usage => 2,
38            Self::Io => 3,
39            Self::InvalidInput => 4,
40            Self::Cancelled => 130,
41        }
42    }
43}
44
45/// A position in an input stream. Every field except `source` is optional because not every
46/// error has every coordinate.
47#[derive(Clone, Debug, Default, PartialEq, Eq)]
48pub struct Location {
49    /// Display name of the input: its file name, or `standard input`.
50    pub source: String,
51    /// 1-based FASTA record number.
52    pub record: Option<u64>,
53    /// 1-based line number in the decompressed text.
54    pub line: Option<u64>,
55    /// 1-based alignment column (residue position, whitespace excluded).
56    pub column: Option<u64>,
57    /// 0-based byte offset in the decompressed text.
58    pub byte: Option<u64>,
59}
60
61impl Location {
62    /// A location naming only the source.
63    #[must_use]
64    pub fn new(source: impl Into<String>) -> Self {
65        Self {
66            source: source.into(),
67            ..Self::default()
68        }
69    }
70
71    /// Sets the record number.
72    #[must_use]
73    pub fn record(mut self, record: u64) -> Self {
74        self.record = Some(record);
75        self
76    }
77
78    /// Sets the line number.
79    #[must_use]
80    pub fn line(mut self, line: u64) -> Self {
81        self.line = Some(line);
82        self
83    }
84
85    /// Sets the column.
86    #[must_use]
87    pub fn column(mut self, column: u64) -> Self {
88        self.column = Some(column);
89        self
90    }
91
92    /// Sets the byte offset.
93    #[must_use]
94    pub fn byte(mut self, byte: u64) -> Self {
95        self.byte = Some(byte);
96        self
97    }
98}
99
100/// A file name as shown in messages: control characters (a newline in a name would split the
101/// message) are written as escapes such as `\u{a}`.
102fn shown_name(name: &str) -> std::borrow::Cow<'_, str> {
103    if !name.chars().any(char::is_control) {
104        return name.into();
105    }
106    let mut out = String::with_capacity(name.len() + 8);
107    for c in name.chars() {
108        if c.is_control() {
109            out.extend(c.escape_unicode());
110        } else {
111            out.push(c);
112        }
113    }
114    out.into()
115}
116
117impl fmt::Display for Location {
118    /// `input.fasta: record 12 (line 45, column 7, byte 1234)`.
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        f.write_str(&shown_name(&self.source))?;
121        let mut details = Vec::with_capacity(3);
122        if let Some(l) = self.line {
123            details.push(format!("line {l}"));
124        }
125        if let Some(c) = self.column {
126            details.push(format!("column {c}"));
127        }
128        if let Some(b) = self.byte {
129            details.push(format!("byte {b}"));
130        }
131        match (self.record, details.is_empty()) {
132            (Some(r), true) => write!(f, ": record {r}"),
133            (Some(r), false) => write!(f, ": record {r} ({})", details.join(", ")),
134            (None, false) => write!(f, ": {}", details.join(", ")),
135            (None, true) => Ok(()),
136        }
137    }
138}
139
140/// What an I/O operation was doing when it failed.
141#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
142pub enum IoAction {
143    /// Opening an existing file.
144    Open,
145    /// Reading.
146    Read,
147    /// Creating a new file (including temporary files).
148    Create,
149    /// Writing.
150    Write,
151    /// Flushing data to stable storage.
152    Sync,
153    /// Atomically replacing the destination.
154    Replace,
155    /// Removing a file.
156    Remove,
157    /// Creating a directory.
158    CreateDir,
159    /// Reading file metadata.
160    Inspect,
161}
162
163impl IoAction {
164    const fn verb(self) -> &'static str {
165        match self {
166            Self::Open => "open",
167            Self::Read => "read",
168            Self::Create => "create",
169            Self::Write => "write",
170            Self::Sync => "flush",
171            Self::Replace => "replace",
172            Self::Remove => "remove",
173            Self::CreateDir => "create directory",
174            Self::Inspect => "inspect",
175        }
176    }
177}
178
179/// The file or stream an I/O operation used.
180#[derive(Clone, Debug, PartialEq, Eq)]
181pub enum IoTarget {
182    /// A path on the file system.
183    Path(PathBuf),
184    /// Standard input.
185    Stdin,
186    /// Standard output.
187    Stdout,
188}
189
190impl fmt::Display for IoTarget {
191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192        match self {
193            Self::Path(p) => write!(f, "'{}'", shown_name(&p.display().to_string())),
194            Self::Stdin => f.write_str("standard input"),
195            Self::Stdout => f.write_str("standard output"),
196        }
197    }
198}
199
200/// What to do when the system refuses threads, for this platform: the hint of
201/// [`DimaError::System`] and of the front ends' warning when a run continues with fewer threads
202/// than requested (D110).
203pub const THREAD_LIMIT_HINT: &str = if cfg!(target_os = "macos") {
204    // macOS limits the threads of each process (kern.num_taskthreads); `ulimit -u` counts
205    // processes only.
206    "use fewer threads; macOS limits the number of threads of each process"
207} else if cfg!(windows) {
208    "use fewer threads, or close other programs: every thread needs memory"
209} else {
210    "use fewer threads, or raise the system's limit on processes and threads (`ulimit -u`, or \
211     the container's pids limit)"
212};
213
214/// Every error the library reports.
215#[derive(Debug, thiserror::Error)]
216#[non_exhaustive]
217pub enum DimaError {
218    /// Invalid parameters (exit 2).
219    #[error("{message}")]
220    Usage {
221        /// What is wrong.
222        message: String,
223        /// How to fix it.
224        hint: Option<String>,
225    },
226    /// The input is not a well-formed FASTA alignment (exit 4). Raised in every validation
227    /// mode.
228    #[error("{location}: {message}")]
229    InputFormat {
230        /// Where the problem is (boxed to keep `Result`s small).
231        location: Box<Location>,
232        /// What is wrong.
233        message: String,
234        /// How to fix it.
235        hint: Option<String>,
236    },
237    /// The input is well-formed but its content is invalid or unsupported (exit 4).
238    #[error("{}{message}", location.as_ref().map(|l| format!("{l}: ")).unwrap_or_default())]
239    InputData {
240        /// Where the problem is, when it has a single location.
241        location: Option<Box<Location>>,
242        /// What is wrong.
243        message: String,
244        /// How to fix it.
245        hint: Option<String>,
246    },
247    /// A file or stream could not be opened, read or written (exit 3).
248    #[error("cannot {} {target}", action.verb())]
249    Io {
250        /// The failed operation.
251        action: IoAction,
252        /// The file or stream.
253        target: IoTarget,
254        /// The operating-system error.
255        #[source]
256        source: io::Error,
257    },
258    /// The operating system refused a resource the run needs, such as a thread (exit 3): the
259    /// environment's limits, not the input and not a bug.
260    #[error("cannot start {what}")]
261    System {
262        /// What could not be started, e.g. `8 worker threads`.
263        what: String,
264        /// The operating-system error.
265        #[source]
266        source: io::Error,
267    },
268    /// The input's first batch differs from what a pre-check saw (D108): the file changed
269    /// after it was checked (exit 3; only front ends that pre-check, such as the desktop app,
270    /// set the expectation).
271    #[error("'{source_name}' changed after it was checked")]
272    InputChanged {
273        /// Display name of the input.
274        source_name: String,
275    },
276    /// The operation was cancelled by the user or a signal.
277    #[error("cancelled")]
278    Cancelled,
279    /// A 64-bit counter would overflow (exit 4).
280    #[error("{what} exceeds the 64-bit counter range")]
281    Overflow {
282        /// The quantity that overflowed.
283        what: &'static str,
284    },
285    /// A broken internal invariant: a bug (exit 1).
286    #[error("internal error: {message}")]
287    Internal {
288        /// The invariant that failed.
289        message: String,
290    },
291}
292
293impl DimaError {
294    /// A usage error without a hint.
295    #[must_use]
296    pub fn usage(message: impl Into<String>) -> Self {
297        Self::Usage {
298            message: message.into(),
299            hint: None,
300        }
301    }
302
303    /// A structural input error at `location`.
304    #[must_use]
305    pub fn input_format(location: Location, message: impl Into<String>) -> Self {
306        Self::InputFormat {
307            location: Box::new(location),
308            message: message.into(),
309            hint: None,
310        }
311    }
312
313    /// An invalid-data error, optionally at `location`.
314    #[must_use]
315    pub fn input_data(location: Option<Location>, message: impl Into<String>) -> Self {
316        Self::InputData {
317            location: location.map(Box::new),
318            message: message.into(),
319            hint: None,
320        }
321    }
322
323    /// An I/O error.
324    #[must_use]
325    pub fn io(action: IoAction, target: IoTarget, source: io::Error) -> Self {
326        Self::Io {
327            action,
328            target,
329            source,
330        }
331    }
332
333    /// A thread the run needs could not be started.
334    #[must_use]
335    pub fn system(what: impl Into<String>, source: io::Error) -> Self {
336        Self::System {
337            what: what.into(),
338            source,
339        }
340    }
341
342    /// An internal error (a bug).
343    #[must_use]
344    pub fn internal(message: impl Into<String>) -> Self {
345        Self::Internal {
346            message: message.into(),
347        }
348    }
349
350    /// Names the input of an invalid-data error that has no location yet.
351    #[must_use]
352    pub(crate) fn in_source(mut self, name: &str) -> Self {
353        if let Self::InputData {
354            location: location @ None,
355            ..
356        } = &mut self
357        {
358            *location = Some(Box::new(Location::new(name.to_owned())));
359        }
360        self
361    }
362
363    /// Attaches a hint to errors that carry one; other errors are returned unchanged.
364    #[must_use]
365    pub fn with_hint(mut self, new_hint: impl Into<String>) -> Self {
366        match &mut self {
367            Self::Usage { hint, .. }
368            | Self::InputFormat { hint, .. }
369            | Self::InputData { hint, .. } => *hint = Some(new_hint.into()),
370            Self::Io { .. }
371            | Self::System { .. }
372            | Self::InputChanged { .. }
373            | Self::Cancelled
374            | Self::Overflow { .. }
375            | Self::Internal { .. } => {}
376        }
377        self
378    }
379
380    /// How to fix the error, if known.
381    #[must_use]
382    pub fn hint(&self) -> Option<&str> {
383        match self {
384            Self::Usage { hint, .. }
385            | Self::InputFormat { hint, .. }
386            | Self::InputData { hint, .. } => hint.as_deref(),
387            Self::Io { source, .. } => match source.kind() {
388                io::ErrorKind::NotFound => Some("check the path and the current directory"),
389                io::ErrorKind::PermissionDenied => Some(
390                    "check the permissions of the file and its directory (an output is written \
391                     to a temporary file in its directory first, so the directory must be \
392                     writable)",
393                ),
394                io::ErrorKind::StorageFull => Some("free some disk space and try again"),
395                io::ErrorKind::QuotaExceeded => {
396                    Some("the disk quota is used up; free some space or write elsewhere")
397                }
398                io::ErrorKind::FileTooLarge => Some(
399                    "a file-size limit was reached (see `ulimit -f`); raise it or compress the output",
400                ),
401                io::ErrorKind::ReadOnlyFilesystem => {
402                    Some("the file system is read-only; write the output elsewhere")
403                }
404                _ => None,
405            },
406            Self::InputChanged { .. } => {
407                Some("check the file again, review the settings and start again")
408            }
409            Self::System { .. } => Some(THREAD_LIMIT_HINT),
410            Self::Overflow { .. } => {
411                Some("split the input into smaller alignments and analyse them separately")
412            }
413            Self::Internal { .. } => Some(concat!(
414                "this is a bug in DiMA; please report it at ",
415                env!("CARGO_PKG_REPOSITORY"),
416                "/issues with the command line and, if possible, the input"
417            )),
418            Self::Cancelled => None,
419        }
420    }
421
422    /// The exit class of the error.
423    #[must_use]
424    pub const fn class(&self) -> ExitClass {
425        match self {
426            Self::Usage { .. } => ExitClass::Usage,
427            Self::InputFormat { .. } | Self::InputData { .. } | Self::Overflow { .. } => {
428                ExitClass::InvalidInput
429            }
430            Self::Io { .. } | Self::System { .. } | Self::InputChanged { .. } => ExitClass::Io,
431            Self::Cancelled => ExitClass::Cancelled,
432            Self::Internal { .. } => ExitClass::Internal,
433        }
434    }
435
436    /// `true` for a write to standard output that failed because the reader went away
437    /// (`dima … | head`); front ends treat this as success.
438    #[must_use]
439    pub fn is_broken_pipe(&self) -> bool {
440        let stdout = |t: &IoTarget| match t {
441            IoTarget::Stdout => true,
442            // `-o /dev/stdout` and its aliases are standard output too.
443            IoTarget::Path(p) => {
444                cfg!(unix)
445                    && ["/dev/stdout", "/dev/fd/1", "/proc/self/fd/1"]
446                        .iter()
447                        .any(|alias| p == std::path::Path::new(alias))
448            }
449            IoTarget::Stdin => false,
450        };
451        matches!(
452            self,
453            Self::Io { target, source, .. }
454                if stdout(target) && source.kind() == io::ErrorKind::BrokenPipe
455        )
456    }
457
458    /// The full report as plain text: the message, every `caused by:` line and the hint, one
459    /// per line (used by the GUI and by tests).
460    #[must_use]
461    pub fn report(&self) -> String {
462        let mut out = self.to_string();
463        let mut cause = std::error::Error::source(self);
464        while let Some(c) = cause {
465            out.push_str("\ncaused by: ");
466            out.push_str(&c.to_string());
467            cause = c.source();
468        }
469        if let Some(h) = self.hint() {
470            out.push_str("\nhint: ");
471            out.push_str(h);
472        }
473        out
474    }
475}
476
477#[cfg(test)]
478mod tests {
479    use super::*;
480
481    #[test]
482    fn error_stays_small() {
483        assert!(
484            std::mem::size_of::<DimaError>() <= 64,
485            "{}",
486            std::mem::size_of::<DimaError>()
487        );
488    }
489
490    #[test]
491    fn refused_threads_are_not_bugs() {
492        let e = DimaError::system(
493            "8 worker threads",
494            io::Error::from_raw_os_error(11), // EAGAIN on Linux
495        );
496        assert_eq!(e.to_string(), "cannot start 8 worker threads");
497        assert_eq!(e.class(), ExitClass::Io);
498        assert!(e.hint().unwrap().contains("fewer threads"));
499        assert!(std::error::Error::source(&e).is_some());
500    }
501
502    #[test]
503    fn control_characters_in_names_are_escaped() {
504        let l = Location::new("bad\nname.fa").line(3);
505        assert_eq!(l.to_string(), "bad\\u{a}name.fa: line 3");
506        let t = IoTarget::Path("a\rb.fa".into());
507        assert_eq!(t.to_string(), "'a\\u{d}b.fa'");
508        assert_eq!(shown_name("Zürich spike.fa"), "Zürich spike.fa");
509    }
510
511    #[test]
512    fn location_display() {
513        let l = Location::new("a.fasta")
514            .record(12)
515            .line(45)
516            .column(7)
517            .byte(1234);
518        assert_eq!(
519            l.to_string(),
520            "a.fasta: record 12 (line 45, column 7, byte 1234)"
521        );
522        assert_eq!(
523            Location::new("a.fasta").record(3).to_string(),
524            "a.fasta: record 3"
525        );
526        assert_eq!(
527            Location::new("standard input").line(1).byte(0).to_string(),
528            "standard input: line 1, byte 0"
529        );
530        assert_eq!(Location::new("x").to_string(), "x");
531    }
532
533    #[test]
534    fn classes_and_codes() {
535        let io = DimaError::io(
536            IoAction::Open,
537            IoTarget::Path("missing.fa".into()),
538            io::Error::from(io::ErrorKind::NotFound),
539        );
540        assert_eq!(io.class(), ExitClass::Io);
541        assert_eq!(io.class().code(), 3);
542        assert_eq!(io.to_string(), "cannot open 'missing.fa'");
543        assert_eq!(io.hint(), Some("check the path and the current directory"));
544        assert!(
545            io.report()
546                .starts_with("cannot open 'missing.fa'\ncaused by: ")
547        );
548        assert_eq!(DimaError::usage("bad").class().code(), 2);
549        assert_eq!(
550            DimaError::input_format(Location::new("a"), "x")
551                .class()
552                .code(),
553            4
554        );
555        assert_eq!(DimaError::input_data(None, "x").class().code(), 4);
556        assert_eq!(DimaError::Overflow { what: "support" }.class().code(), 4);
557        assert_eq!(DimaError::internal("x").class().code(), 1);
558        assert_eq!(DimaError::Cancelled.class().code(), 130);
559    }
560
561    #[test]
562    fn hints_and_reports() {
563        let e = DimaError::input_format(Location::new("a.fa").record(2).line(3), "unexpected NUL")
564            .with_hint("convert the file to plain text");
565        assert_eq!(e.to_string(), "a.fa: record 2 (line 3): unexpected NUL");
566        assert_eq!(
567            e.report(),
568            "a.fa: record 2 (line 3): unexpected NUL\nhint: convert the file to plain text"
569        );
570        let d = DimaError::input_data(None, "no positions");
571        assert_eq!(d.to_string(), "no positions");
572        // Hints are ignored by variants that compute their own.
573        assert!(DimaError::Cancelled.with_hint("x").hint().is_none());
574    }
575
576    #[test]
577    fn broken_pipe_detection() {
578        let e = DimaError::io(
579            IoAction::Write,
580            IoTarget::Stdout,
581            io::Error::from(io::ErrorKind::BrokenPipe),
582        );
583        assert!(e.is_broken_pipe());
584        assert_eq!(e.to_string(), "cannot write standard output");
585        let f = DimaError::io(
586            IoAction::Write,
587            IoTarget::Path("o".into()),
588            io::Error::from(io::ErrorKind::BrokenPipe),
589        );
590        assert!(!f.is_broken_pipe());
591    }
592}