geolith-dataset-builder 0.5.0

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! The error of every dataset step.
//!
//! [`DatasetError`] sorts failures by what went wrong, not by where:
//!
//! - **typed** variants carry the facts as fields: the file and the file
//!   operation ([`DatasetError::Io`]), the URL and the HTTP status
//!   ([`DatasetError::HttpStatus`]), the external tool and its exit code
//!   ([`DatasetError::Tool`]), the exit code a step asks for
//!   ([`DatasetError::Exit`]), and the error of a reader or writer as its
//!   [`source`](std::error::Error::source);
//! - **check** variants ([`DatasetError::Usage`], [`DatasetError::Config`],
//!   [`DatasetError::Data`], [`DatasetError::Stage`],
//!   [`DatasetError::Storage`], [`DatasetError::Fetch`]) carry the sentence of
//!   a refused input: the text names the file, row, flag or key that the
//!   operator has to fix. Each variant is one class of fix: the command line,
//!   the settings, the input files, the stage, the bucket, the download.
//!
//! [`geolith::error::report`] prints an error with its causes on one line.

use std::fmt;
use std::path::{Path, PathBuf};

use geolith::error::GeolithError;

use crate::exit::Exit;

/// What a file operation was doing when it failed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IoOp {
    /// Reading a file.
    Read,
    /// Writing a file.
    Write,
    /// Creating a file or a directory.
    Create,
    /// Opening a file.
    Open,
    /// Removing a file or a directory.
    Remove,
    /// Renaming a file; the path is the file that moves.
    Rename,
    /// Renaming a file; the path is the new name.
    RenameTo,
    /// Listing a directory.
    List,
    /// Reading the metadata of a file.
    Stat,
    /// Moving inside a file.
    Seek,
}

impl fmt::Display for IoOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Read => "reading",
            Self::Write => "writing",
            Self::Create => "creating",
            Self::Open => "opening",
            Self::Remove => "removing",
            Self::Rename => "renaming",
            Self::RenameTo => "renaming to",
            Self::List => "listing",
            Self::Stat => "reading the metadata of",
            Self::Seek => "seeking in",
        })
    }
}

/// Why a dataset step failed.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DatasetError {
    /// A file operation failed on `path`.
    #[error("{op} {}", path.display())]
    Io {
        /// What the step was doing.
        op: IoOp,
        /// The file or directory.
        path: PathBuf,
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// A file operation failed and no path is known.
    #[error("i/o error")]
    Os(#[from] std::io::Error),

    /// An i/o step failed that has no single file: `what` says which.
    #[error("{what}")]
    IoStep {
        /// The step, for example `running git rev-parse`.
        what: String,
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// A reader or writer of the `geolith` library failed on `path`.
    #[error("{op} {}", path.display())]
    Reader {
        /// What the step was doing.
        op: IoOp,
        /// The file or directory.
        path: PathBuf,
        /// The library error.
        #[source]
        source: GeolithError,
    },

    /// A Parquet file cannot be read or written.
    #[error("{op} {}", path.display())]
    ParquetFile {
        /// What the step was doing.
        op: IoOp,
        /// The file.
        path: PathBuf,
        /// The Parquet error.
        #[source]
        source: parquet::errors::ParquetError,
    },

    /// A `GeoTIFF` cannot be opened or read.
    #[error("{op} {}", path.display())]
    TiffFile {
        /// What the step was doing.
        op: IoOp,
        /// The file.
        path: PathBuf,
        /// The TIFF error.
        #[source]
        source: tiff::TiffError,
    },

    /// A shapefile cannot be opened or read.
    #[error("{op} {}", path.display())]
    ShapeFile {
        /// What the step was doing.
        op: IoOp,
        /// The file.
        path: PathBuf,
        /// The shapefile error.
        #[source]
        source: shapefile::Error,
    },

    /// A JSON file cannot be written, or its value is not the type it must be.
    #[error("{op} {}", path.display())]
    JsonFile {
        /// What the step was doing.
        op: IoOp,
        /// The file.
        path: PathBuf,
        /// The serde error.
        #[source]
        source: serde_json::Error,
    },

    /// A dBASE table cannot be opened or read.
    #[error("{op} {}", path.display())]
    DbfFile {
        /// What the step was doing.
        op: IoOp,
        /// The file.
        path: PathBuf,
        /// The dBASE error.
        #[source]
        source: shapefile::dbase::Error,
    },

    /// A `GeoJSON` geometry is not one the step can use.
    #[error("{what}")]
    Geometry {
        /// Which feature, and in which file.
        what: String,
        /// The conversion error.
        #[source]
        source: Box<geojson::Error>,
    },

    /// An error with a note on where it happened.
    #[error("{what}")]
    Within {
        /// Where, for example `job 3 of 8`.
        what: String,
        /// The error.
        #[source]
        source: Box<DatasetError>,
    },

    /// A path or a C string has a NUL byte.
    #[error("interior NUL byte")]
    Nul(#[from] std::ffi::NulError),

    /// A geometry cannot be written as WKB.
    #[error("geometry error")]
    Wkb(#[from] geozero::error::GeozeroError),

    /// A path is not below the directory it must be in.
    #[error("path error")]
    Prefix(#[from] std::path::StripPrefixError),

    /// The thread pool cannot be built.
    #[error("thread pool error")]
    Pool(#[from] rayon::ThreadPoolBuildError),

    /// A text is not UTF-8.
    #[error("not UTF-8")]
    Utf8Text(#[from] std::string::FromUtf8Error),

    /// An HTTP request failed.
    #[error("request failed")]
    Request(#[source] Box<ureq::Error>),

    /// Bytes are not UTF-8.
    #[error("not UTF-8")]
    Utf8Bytes(#[from] std::str::Utf8Error),

    /// The system clock is before 1970.
    #[error("system clock is before 1970")]
    Clock(#[source] std::time::SystemTimeError),

    /// JSON could not be parsed or written and no file is known.
    #[error("json error")]
    JsonBare(#[from] serde_json::Error),

    /// `path` is not the JSON it must be.
    #[error("parsing {}", path.display())]
    Json {
        /// The file.
        path: PathBuf,
        /// The parser error.
        #[source]
        source: serde_json::Error,
    },

    /// JSON that did not come from a file is wrong: `what` says whose.
    #[error("{what}")]
    JsonValue {
        /// The text that is not JSON, for example `the body of <url>`.
        what: String,
        /// The parser error.
        #[source]
        source: serde_json::Error,
    },

    /// `what` is not UTF-8.
    #[error("{what} is not UTF-8")]
    Utf8 {
        /// The text, for example a URL or an object key.
        what: String,
        /// The decoder error.
        #[source]
        source: std::string::FromUtf8Error,
    },

    /// `what` is not the number it must be.
    #[error("{what}")]
    Number {
        /// The field and its text.
        what: String,
        /// The parser error.
        #[source]
        source: Box<dyn std::error::Error + Send + Sync>,
    },

    /// A request could not be sent or its answer not read.
    #[error("{method} {url}")]
    Http {
        /// The HTTP method.
        method: &'static str,
        /// The URL.
        url: String,
        /// The client error.
        #[source]
        source: Box<ureq::Error>,
    },

    /// A server answered with a status the step cannot use.
    #[error("{method} {target}: HTTP {status}")]
    HttpStatus {
        /// The HTTP method.
        method: &'static str,
        /// The URL or the object key.
        target: String,
        /// The status code.
        status: u16,
    },

    /// An external tool failed.
    #[error("{tool} {command} failed{}: {stderr}", exit_text(*code))]
    Tool {
        /// The program, for example `gdalinfo`.
        tool: String,
        /// Its arguments, joined by spaces.
        command: String,
        /// Its exit code, if it ran and exited.
        code: Option<i32>,
        /// What it wrote to its error output.
        stderr: String,
    },

    /// An external tool cannot start.
    #[error("cannot run {tool}")]
    ToolStart {
        /// The program.
        tool: String,
        /// What the operating system said.
        #[source]
        source: std::io::Error,
    },

    /// The step asks for a process exit code other than `1`.
    #[error(transparent)]
    Exit(#[from] Exit),

    /// A command-line flag or argument is wrong or missing.
    #[error("{0}")]
    Usage(String),

    /// The settings, the dataset config or the country config are wrong.
    #[error("{0}")]
    Config(String),

    /// An input file or a computed value fails a check.
    #[error("{0}")]
    Data(String),

    /// A stage, a build id or a publish step refuses to go on.
    #[error("{0}")]
    Stage(String),

    /// The bucket answered in a way the step cannot use.
    #[error("{0}")]
    Storage(String),

    /// A download fails or a source host serves the wrong thing.
    #[error("{0}")]
    Fetch(String),

    /// A worker thread panicked.
    #[error("a worker panicked")]
    WorkerPanicked,

    /// A reader or writer of the `geolith` library failed.
    #[error(transparent)]
    Geolith(#[from] GeolithError),

    /// A Parquet file cannot be read or written.
    #[error("parquet error")]
    Parquet(#[from] parquet::errors::ParquetError),

    /// An Arrow batch cannot be built or read.
    #[error("arrow error")]
    Arrow(#[from] arrow::error::ArrowError),

    /// A `GeoTIFF` cannot be read.
    #[error("tiff error")]
    Tiff(#[from] tiff::TiffError),
}

fn exit_text(code: Option<i32>) -> String {
    code.map_or_else(String::new, |code| format!(" (exit {code})"))
}

impl From<ureq::Error> for DatasetError {
    fn from(source: ureq::Error) -> Self {
        Self::Request(Box::new(source))
    }
}

/// Result of a dataset step.
pub type Result<T, E = DatasetError> = std::result::Result<T, E>;

impl DatasetError {
    /// A command-line flag or argument is wrong or missing.
    #[must_use]
    pub fn usage(message: impl Into<String>) -> Self {
        Self::Usage(message.into())
    }

    /// The settings or a config file are wrong.
    #[must_use]
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config(message.into())
    }

    /// An input or a value fails a check.
    #[must_use]
    pub fn data(message: impl Into<String>) -> Self {
        Self::Data(message.into())
    }

    /// A stage or a publish step refuses to go on.
    #[must_use]
    pub fn stage(message: impl Into<String>) -> Self {
        Self::Stage(message.into())
    }

    /// The bucket answered in a way the step cannot use.
    #[must_use]
    pub fn storage(message: impl Into<String>) -> Self {
        Self::Storage(message.into())
    }

    /// A download fails.
    #[must_use]
    pub fn fetch(message: impl Into<String>) -> Self {
        Self::Fetch(message.into())
    }

    /// The [`Exit`] this error asks for, if it is one.
    #[must_use]
    pub const fn exit(&self) -> Option<Exit> {
        match self {
            Self::Exit(exit) => Some(*exit),
            _ => None,
        }
    }

    /// The process exit code this error asks for: the code of an
    /// [`Exit`], else `1`.
    #[must_use]
    pub const fn exit_code(&self) -> i32 {
        match self {
            Self::Exit(exit) => exit.0,
            _ => 1,
        }
    }
}

/// An error that a file operation raised on a known path.
pub trait AtPath {
    /// This error as the [`DatasetError`] of `op` on `path`.
    fn at_path(self, op: IoOp, path: &Path) -> DatasetError;
}

macro_rules! at_path {
    ($($source:ty => $variant:ident),+ $(,)?) => {$(
        impl AtPath for $source {
            fn at_path(self, op: IoOp, path: &Path) -> DatasetError {
                DatasetError::$variant { op, path: path.to_path_buf(), source: self }
            }
        }
    )+};
}

at_path! {
    std::io::Error => Io,
    GeolithError => Reader,
    parquet::errors::ParquetError => ParquetFile,
    tiff::TiffError => TiffFile,
    shapefile::Error => ShapeFile,
    serde_json::Error => JsonFile,
    shapefile::dbase::Error => DbfFile,
}

/// Put a path and a file operation on the result of a reader or writer.
pub trait IoResultExt<T> {
    /// The error of `self` as the [`DatasetError`] of `op` on `path`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `op` and `path`.
    fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T>;
}

impl<T, E: AtPath> IoResultExt<T> for std::result::Result<T, E> {
    fn io_at(self, op: IoOp, path: impl AsRef<Path>) -> Result<T> {
        self.map_err(|source| source.at_path(op, path.as_ref()))
    }
}

/// Put a file on a [`serde_json::Result`].
pub trait JsonResultExt<T> {
    /// The error of `self` as [`DatasetError::Json`] of `path`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `path`.
    fn json_at(self, path: impl AsRef<Path>) -> Result<T>;

    /// The error of `self` as [`DatasetError::JsonValue`] of `what`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `what`.
    fn json_of(self, what: impl Into<String>) -> Result<T>;
}

impl<T> JsonResultExt<T> for serde_json::Result<T> {
    fn json_at(self, path: impl AsRef<Path>) -> Result<T> {
        self.map_err(|source| DatasetError::Json {
            path: path.as_ref().to_path_buf(),
            source,
        })
    }

    fn json_of(self, what: impl Into<String>) -> Result<T> {
        self.map_err(|source| DatasetError::JsonValue {
            what: what.into(),
            source,
        })
    }
}

/// An error of parsing a number from text.
pub trait NumberError: std::error::Error + Send + Sync + 'static {}

impl NumberError for std::num::ParseIntError {}
impl NumberError for std::num::ParseFloatError {}
impl NumberError for std::num::TryFromIntError {}

/// Say what a failed number parse was parsing.
pub trait NumberResultExt<T> {
    /// The error of `self` as [`DatasetError::Number`] of `what`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `what`.
    fn number_of(self, what: impl Into<String>) -> Result<T>;
}

impl<T, E: NumberError> NumberResultExt<T> for std::result::Result<T, E> {
    fn number_of(self, what: impl Into<String>) -> Result<T> {
        self.map_err(|source| DatasetError::Number {
            what: what.into(),
            source: Box::new(source),
        })
    }
}

/// Say where an error happened and keep it as the cause.
pub trait WithinExt<T> {
    /// The error of `self` as [`DatasetError::Within`] of `what`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `what`.
    fn within(self, what: impl Into<String>) -> Result<T>;
}

impl<T, E: Into<DatasetError>> WithinExt<T> for std::result::Result<T, E> {
    fn within(self, what: impl Into<String>) -> Result<T> {
        self.map_err(|source| DatasetError::Within {
            what: what.into(),
            source: Box::new(source.into()),
        })
    }
}

/// Say which step of an i/o chain failed.
pub trait IoStepExt<T> {
    /// The error of `self` as [`DatasetError::IoStep`] of `what`.
    ///
    /// # Errors
    ///
    /// Returns the error of `self`, with `what`.
    fn io_step(self, what: impl Into<String>) -> Result<T>;
}

impl<T> IoStepExt<T> for std::io::Result<T> {
    fn io_step(self, what: impl Into<String>) -> Result<T> {
        self.map_err(|source| DatasetError::IoStep {
            what: what.into(),
            source,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_io_error_names_the_operation_and_the_file() {
        let err = std::fs::read_to_string("/nonexistent/geolith/areas.geojson")
            .io_at(IoOp::Read, "/nonexistent/geolith/areas.geojson")
            .expect_err("the file does not exist");
        assert_eq!(
            err.to_string(),
            "reading /nonexistent/geolith/areas.geojson"
        );
        let line = geolith::error::report(&err);
        assert!(
            line.starts_with("reading /nonexistent/geolith/areas.geojson: "),
            "{line}"
        );
    }

    #[test]
    fn an_exit_error_gives_its_code() {
        assert_eq!(DatasetError::Exit(Exit(3)).exit_code(), 3);
        assert_eq!(DatasetError::usage("--x").exit_code(), 1);
    }

    #[test]
    fn a_tool_error_prints_the_exit_code_when_there_is_one() {
        let err = DatasetError::Tool {
            tool: "unzip".to_owned(),
            command: "a.zip".to_owned(),
            code: Some(9),
            stderr: "bad zip".to_owned(),
        };
        assert_eq!(err.to_string(), "unzip a.zip failed (exit 9): bad zip");
    }
}