Skip to main content

geolith_dataset_builder/
error.rs

1//! The error of every dataset step.
2//!
3//! [`DatasetError`] sorts failures by what went wrong, not by where:
4//!
5//! - **typed** variants carry the facts as fields: the file and the file
6//!   operation ([`DatasetError::Io`]), the URL and the HTTP status
7//!   ([`DatasetError::HttpStatus`]), the external tool and its exit code
8//!   ([`DatasetError::Tool`]), the exit code a step asks for
9//!   ([`DatasetError::Exit`]), and the error of a reader or writer as its
10//!   [`source`](std::error::Error::source);
11//! - **check** variants ([`DatasetError::Usage`], [`DatasetError::Config`],
12//!   [`DatasetError::Data`], [`DatasetError::Stage`],
13//!   [`DatasetError::Storage`], [`DatasetError::Fetch`]) carry the sentence of
14//!   a refused input: the text names the file, row, flag or key that the
15//!   operator has to fix. Each variant is one class of fix: the command line,
16//!   the settings, the input files, the stage, the bucket, the download.
17//!
18//! [`geolith::error::report`] prints an error with its causes on one line.
19
20use std::fmt;
21use std::path::{Path, PathBuf};
22
23use geolith::error::GeolithError;
24
25use crate::exit::Exit;
26
27/// What a file operation was doing when it failed.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[non_exhaustive]
30pub enum IoOp {
31    /// Reading a file.
32    Read,
33    /// Writing a file.
34    Write,
35    /// Creating a file or a directory.
36    Create,
37    /// Opening a file.
38    Open,
39    /// Removing a file or a directory.
40    Remove,
41    /// Renaming a file; the path is the file that moves.
42    Rename,
43    /// Renaming a file; the path is the new name.
44    RenameTo,
45    /// Listing a directory.
46    List,
47    /// Reading the metadata of a file.
48    Stat,
49    /// Moving inside a file.
50    Seek,
51}
52
53impl fmt::Display for IoOp {
54    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
55        f.write_str(match self {
56            Self::Read => "reading",
57            Self::Write => "writing",
58            Self::Create => "creating",
59            Self::Open => "opening",
60            Self::Remove => "removing",
61            Self::Rename => "renaming",
62            Self::RenameTo => "renaming to",
63            Self::List => "listing",
64            Self::Stat => "reading the metadata of",
65            Self::Seek => "seeking in",
66        })
67    }
68}
69
70/// Why a dataset step failed.
71#[derive(Debug, thiserror::Error)]
72#[non_exhaustive]
73pub enum DatasetError {
74    /// A file operation failed on `path`.
75    #[error("{op} {}", path.display())]
76    Io {
77        /// What the step was doing.
78        op: IoOp,
79        /// The file or directory.
80        path: PathBuf,
81        /// What the operating system said.
82        #[source]
83        source: std::io::Error,
84    },
85
86    /// A file operation failed and no path is known.
87    #[error("i/o error")]
88    Os(#[from] std::io::Error),
89
90    /// An i/o step failed that has no single file: `what` says which.
91    #[error("{what}")]
92    IoStep {
93        /// The step, for example `running git rev-parse`.
94        what: String,
95        /// What the operating system said.
96        #[source]
97        source: std::io::Error,
98    },
99
100    /// A reader or writer of the `geolith` library failed on `path`.
101    #[error("{op} {}", path.display())]
102    Reader {
103        /// What the step was doing.
104        op: IoOp,
105        /// The file or directory.
106        path: PathBuf,
107        /// The library error.
108        #[source]
109        source: GeolithError,
110    },
111
112    /// A Parquet file cannot be read or written.
113    #[error("{op} {}", path.display())]
114    ParquetFile {
115        /// What the step was doing.
116        op: IoOp,
117        /// The file.
118        path: PathBuf,
119        /// The Parquet error.
120        #[source]
121        source: parquet::errors::ParquetError,
122    },
123
124    /// A `GeoTIFF` cannot be opened or read.
125    #[error("{op} {}", path.display())]
126    TiffFile {
127        /// What the step was doing.
128        op: IoOp,
129        /// The file.
130        path: PathBuf,
131        /// The TIFF error.
132        #[source]
133        source: tiff::TiffError,
134    },
135
136    /// A shapefile cannot be opened or read.
137    #[error("{op} {}", path.display())]
138    ShapeFile {
139        /// What the step was doing.
140        op: IoOp,
141        /// The file.
142        path: PathBuf,
143        /// The shapefile error.
144        #[source]
145        source: shapefile::Error,
146    },
147
148    /// A JSON file cannot be written, or its value is not the type it must be.
149    #[error("{op} {}", path.display())]
150    JsonFile {
151        /// What the step was doing.
152        op: IoOp,
153        /// The file.
154        path: PathBuf,
155        /// The serde error.
156        #[source]
157        source: serde_json::Error,
158    },
159
160    /// A dBASE table cannot be opened or read.
161    #[error("{op} {}", path.display())]
162    DbfFile {
163        /// What the step was doing.
164        op: IoOp,
165        /// The file.
166        path: PathBuf,
167        /// The dBASE error.
168        #[source]
169        source: shapefile::dbase::Error,
170    },
171
172    /// A `GeoJSON` geometry is not one the step can use.
173    #[error("{what}")]
174    Geometry {
175        /// Which feature, and in which file.
176        what: String,
177        /// The conversion error.
178        #[source]
179        source: Box<geojson::Error>,
180    },
181
182    /// An error with a note on where it happened.
183    #[error("{what}")]
184    Within {
185        /// Where, for example `job 3 of 8`.
186        what: String,
187        /// The error.
188        #[source]
189        source: Box<DatasetError>,
190    },
191
192    /// A path or a C string has a NUL byte.
193    #[error("interior NUL byte")]
194    Nul(#[from] std::ffi::NulError),
195
196    /// A geometry cannot be written as WKB.
197    #[error("geometry error")]
198    Wkb(#[from] geozero::error::GeozeroError),
199
200    /// A path is not below the directory it must be in.
201    #[error("path error")]
202    Prefix(#[from] std::path::StripPrefixError),
203
204    /// The thread pool cannot be built.
205    #[error("thread pool error")]
206    Pool(#[from] rayon::ThreadPoolBuildError),
207
208    /// A text is not UTF-8.
209    #[error("not UTF-8")]
210    Utf8Text(#[from] std::string::FromUtf8Error),
211
212    /// An HTTP request failed.
213    #[error("request failed")]
214    Request(#[source] Box<ureq::Error>),
215
216    /// Bytes are not UTF-8.
217    #[error("not UTF-8")]
218    Utf8Bytes(#[from] std::str::Utf8Error),
219
220    /// The system clock is before 1970.
221    #[error("system clock is before 1970")]
222    Clock(#[source] std::time::SystemTimeError),
223
224    /// JSON could not be parsed or written and no file is known.
225    #[error("json error")]
226    JsonBare(#[from] serde_json::Error),
227
228    /// `path` is not the JSON it must be.
229    #[error("parsing {}", path.display())]
230    Json {
231        /// The file.
232        path: PathBuf,
233        /// The parser error.
234        #[source]
235        source: serde_json::Error,
236    },
237
238    /// JSON that did not come from a file is wrong: `what` says whose.
239    #[error("{what}")]
240    JsonValue {
241        /// The text that is not JSON, for example `the body of <url>`.
242        what: String,
243        /// The parser error.
244        #[source]
245        source: serde_json::Error,
246    },
247
248    /// `what` is not UTF-8.
249    #[error("{what} is not UTF-8")]
250    Utf8 {
251        /// The text, for example a URL or an object key.
252        what: String,
253        /// The decoder error.
254        #[source]
255        source: std::string::FromUtf8Error,
256    },
257
258    /// `what` is not the number it must be.
259    #[error("{what}")]
260    Number {
261        /// The field and its text.
262        what: String,
263        /// The parser error.
264        #[source]
265        source: Box<dyn std::error::Error + Send + Sync>,
266    },
267
268    /// A request could not be sent or its answer not read.
269    #[error("{method} {url}")]
270    Http {
271        /// The HTTP method.
272        method: &'static str,
273        /// The URL.
274        url: String,
275        /// The client error.
276        #[source]
277        source: Box<ureq::Error>,
278    },
279
280    /// A server answered with a status the step cannot use.
281    #[error("{method} {target}: HTTP {status}")]
282    HttpStatus {
283        /// The HTTP method.
284        method: &'static str,
285        /// The URL or the object key.
286        target: String,
287        /// The status code.
288        status: u16,
289    },
290
291    /// An external tool failed.
292    #[error("{tool} {command} failed{}: {stderr}", exit_text(*code))]
293    Tool {
294        /// The program, for example `gdalinfo`.
295        tool: String,
296        /// Its arguments, joined by spaces.
297        command: String,
298        /// Its exit code, if it ran and exited.
299        code: Option<i32>,
300        /// What it wrote to its error output.
301        stderr: String,
302    },
303
304    /// An external tool cannot start.
305    #[error("cannot run {tool}")]
306    ToolStart {
307        /// The program.
308        tool: String,
309        /// What the operating system said.
310        #[source]
311        source: std::io::Error,
312    },
313
314    /// The step asks for a process exit code other than `1`.
315    #[error(transparent)]
316    Exit(#[from] Exit),
317
318    /// A command-line flag or argument is wrong or missing.
319    #[error("{0}")]
320    Usage(String),
321
322    /// The settings, the dataset config or the country config are wrong.
323    #[error("{0}")]
324    Config(String),
325
326    /// An input file or a computed value fails a check.
327    #[error("{0}")]
328    Data(String),
329
330    /// A stage, a build id or a publish step refuses to go on.
331    #[error("{0}")]
332    Stage(String),
333
334    /// The bucket answered in a way the step cannot use.
335    #[error("{0}")]
336    Storage(String),
337
338    /// A download fails or a source host serves the wrong thing.
339    #[error("{0}")]
340    Fetch(String),
341
342    /// A worker thread panicked.
343    #[error("a worker panicked")]
344    WorkerPanicked,
345
346    /// A reader or writer of the `geolith` library failed.
347    #[error(transparent)]
348    Geolith(#[from] GeolithError),
349
350    /// A Parquet file cannot be read or written.
351    #[error("parquet error")]
352    Parquet(#[from] parquet::errors::ParquetError),
353
354    /// An Arrow batch cannot be built or read.
355    #[error("arrow error")]
356    Arrow(#[from] arrow::error::ArrowError),
357
358    /// A `GeoTIFF` cannot be read.
359    #[error("tiff error")]
360    Tiff(#[from] tiff::TiffError),
361}
362
363fn exit_text(code: Option<i32>) -> String {
364    code.map_or_else(String::new, |code| format!(" (exit {code})"))
365}
366
367impl From<ureq::Error> for DatasetError {
368    fn from(source: ureq::Error) -> Self {
369        Self::Request(Box::new(source))
370    }
371}
372
373/// Result of a dataset step.
374pub type Result<T, E = DatasetError> = std::result::Result<T, E>;
375
376impl DatasetError {
377    /// A command-line flag or argument is wrong or missing.
378    #[must_use]
379    pub fn usage(message: impl Into<String>) -> Self {
380        Self::Usage(message.into())
381    }
382
383    /// The settings or a config file are wrong.
384    #[must_use]
385    pub fn config(message: impl Into<String>) -> Self {
386        Self::Config(message.into())
387    }
388
389    /// An input or a value fails a check.
390    #[must_use]
391    pub fn data(message: impl Into<String>) -> Self {
392        Self::Data(message.into())
393    }
394
395    /// A stage or a publish step refuses to go on.
396    #[must_use]
397    pub fn stage(message: impl Into<String>) -> Self {
398        Self::Stage(message.into())
399    }
400
401    /// The bucket answered in a way the step cannot use.
402    #[must_use]
403    pub fn storage(message: impl Into<String>) -> Self {
404        Self::Storage(message.into())
405    }
406
407    /// A download fails.
408    #[must_use]
409    pub fn fetch(message: impl Into<String>) -> Self {
410        Self::Fetch(message.into())
411    }
412
413    /// The [`Exit`] this error asks for, if it is one.
414    #[must_use]
415    pub const fn exit(&self) -> Option<Exit> {
416        match self {
417            Self::Exit(exit) => Some(*exit),
418            _ => None,
419        }
420    }
421
422    /// The process exit code this error asks for: the code of an
423    /// [`Exit`], else `1`.
424    #[must_use]
425    pub const fn exit_code(&self) -> i32 {
426        match self {
427            Self::Exit(exit) => exit.0,
428            _ => 1,
429        }
430    }
431}
432
433/// An error that a file operation raised on a known path.
434pub trait AtPath {
435    /// This error as the [`DatasetError`] of `op` on `path`.
436    fn at_path(self, op: IoOp, path: &Path) -> DatasetError;
437}
438
439macro_rules! at_path {
440    ($($source:ty => $variant:ident),+ $(,)?) => {$(
441        impl AtPath for $source {
442            fn at_path(self, op: IoOp, path: &Path) -> DatasetError {
443                DatasetError::$variant { op, path: path.to_path_buf(), source: self }
444            }
445        }
446    )+};
447}
448
449at_path! {
450    std::io::Error => Io,
451    GeolithError => Reader,
452    parquet::errors::ParquetError => ParquetFile,
453    tiff::TiffError => TiffFile,
454    shapefile::Error => ShapeFile,
455    serde_json::Error => JsonFile,
456    shapefile::dbase::Error => DbfFile,
457}
458
459/// Put a path and a file operation on the result of a reader or writer.
460pub trait IoResultExt<T> {
461    /// The error of `self` as the [`DatasetError`] of `op` on `path`.
462    ///
463    /// # Errors
464    ///
465    /// Returns the error of `self`, with `op` and `path`.
466    fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T>;
467}
468
469impl<T, E: AtPath> IoResultExt<T> for std::result::Result<T, E> {
470    fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T> {
471        self.map_err(|source| source.at_path(op, path.as_ref()))
472    }
473}
474
475/// Put a file on a [`serde_json::Result`].
476pub trait JsonResultExt<T> {
477    /// The error of `self` as [`DatasetError::Json`] of `path`.
478    ///
479    /// # Errors
480    ///
481    /// Returns the error of `self`, with `path`.
482    fn json_at(self, path: impl AsRef<Path>) -> Result<T>;
483
484    /// The error of `self` as [`DatasetError::JsonValue`] of `what`.
485    ///
486    /// # Errors
487    ///
488    /// Returns the error of `self`, with `what`.
489    fn json_of(self, what: impl Into<String>) -> Result<T>;
490}
491
492impl<T> JsonResultExt<T> for serde_json::Result<T> {
493    fn json_at(self, path: impl AsRef<Path>) -> Result<T> {
494        self.map_err(|source| DatasetError::Json {
495            path: path.as_ref().to_path_buf(),
496            source,
497        })
498    }
499
500    fn json_of(self, what: impl Into<String>) -> Result<T> {
501        self.map_err(|source| DatasetError::JsonValue {
502            what: what.into(),
503            source,
504        })
505    }
506}
507
508/// An error of parsing a number from text.
509pub trait NumberError: std::error::Error + Send + Sync + 'static {}
510
511impl NumberError for std::num::ParseIntError {}
512impl NumberError for std::num::ParseFloatError {}
513impl NumberError for std::num::TryFromIntError {}
514
515/// Say what a failed number parse was parsing.
516pub trait NumberResultExt<T> {
517    /// The error of `self` as [`DatasetError::Number`] of `what`.
518    ///
519    /// # Errors
520    ///
521    /// Returns the error of `self`, with `what`.
522    fn number_of(self, what: impl Into<String>) -> Result<T>;
523}
524
525impl<T, E: NumberError> NumberResultExt<T> for std::result::Result<T, E> {
526    fn number_of(self, what: impl Into<String>) -> Result<T> {
527        self.map_err(|source| DatasetError::Number {
528            what: what.into(),
529            source: Box::new(source),
530        })
531    }
532}
533
534/// Say where an error happened and keep it as the cause.
535pub trait WithinExt<T> {
536    /// The error of `self` as [`DatasetError::Within`] of `what`.
537    ///
538    /// # Errors
539    ///
540    /// Returns the error of `self`, with `what`.
541    fn within(self, what: impl Into<String>) -> Result<T>;
542}
543
544impl<T, E: Into<DatasetError>> WithinExt<T> for std::result::Result<T, E> {
545    fn within(self, what: impl Into<String>) -> Result<T> {
546        self.map_err(|source| DatasetError::Within {
547            what: what.into(),
548            source: Box::new(source.into()),
549        })
550    }
551}
552
553/// Say which step of an i/o chain failed.
554pub trait IoStepExt<T> {
555    /// The error of `self` as [`DatasetError::IoStep`] of `what`.
556    ///
557    /// # Errors
558    ///
559    /// Returns the error of `self`, with `what`.
560    fn io_step(self, what: impl Into<String>) -> Result<T>;
561}
562
563impl<T> IoStepExt<T> for std::io::Result<T> {
564    fn io_step(self, what: impl Into<String>) -> Result<T> {
565        self.map_err(|source| DatasetError::IoStep {
566            what: what.into(),
567            source,
568        })
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575
576    #[test]
577    fn an_io_error_names_the_operation_and_the_file() {
578        let err = std::fs::read_to_string("/nonexistent/geolith/areas.geojson")
579            .io_at(IoOp::Read, "/nonexistent/geolith/areas.geojson")
580            .expect_err("the file does not exist");
581        assert_eq!(
582            err.to_string(),
583            "reading /nonexistent/geolith/areas.geojson"
584        );
585        let line = geolith::error::report(&err);
586        assert!(
587            line.starts_with("reading /nonexistent/geolith/areas.geojson: "),
588            "{line}"
589        );
590    }
591
592    #[test]
593    fn an_exit_error_gives_its_code() {
594        assert_eq!(DatasetError::Exit(Exit(3)).exit_code(), 3);
595        assert_eq!(DatasetError::usage("--x").exit_code(), 1);
596    }
597
598    #[test]
599    fn a_tool_error_prints_the_exit_code_when_there_is_one() {
600        let err = DatasetError::Tool {
601            tool: "unzip".to_owned(),
602            command: "a.zip".to_owned(),
603            code: Some(9),
604            stderr: "bad zip".to_owned(),
605        };
606        assert_eq!(err.to_string(), "unzip a.zip failed (exit 9): bad zip");
607    }
608}