geolith-dataset-builder 0.2.2

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
//! Discovery of the source rasters and the period each one covers.
//!
//! A raster folder holds `final/` and `prelim/` subfolders. Each file name
//! is matched against the config template to find its period (pentad or
//! dekad); when both a final and a prelim file exist for one period, the
//! final one is used.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};

use anyhow::{Context, bail};
use serde::{Deserialize, Serialize};

use crate::config::PeriodKind;

/// One period of a month: the `index`-th pentad (1–6) or dekad (1–3).
///
/// Pentad `p` covers days `5(p−1)+1 ..= 5p`, dekad `d` days
/// `10(d−1)+1 ..= 10d`; the last period of a month runs to its last day.
/// Ordered by `(year, month, index, kind)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Period {
    /// Calendar year.
    pub year: i32,
    /// Month, 1–12.
    pub month: u8,
    /// Period within the month, 1–6 (pentad) or 1–3 (dekad).
    pub index: u8,
    /// Pentad or dekad; not serialised (pentad when read back).
    #[serde(skip)]
    pub kind: PeriodKind,
}

impl Period {
    /// First day as `(year, month, day)`.
    #[must_use]
    pub const fn start(&self) -> (i32, u8, u8) {
        (
            self.year,
            self.month,
            self.index
                .saturating_sub(1)
                .saturating_mul(self.length())
                .saturating_add(1),
        )
    }

    /// Days of every period of the month but the last: 5 or 10.
    const fn length(&self) -> u8 {
        match self.kind {
            PeriodKind::Pentad => 5,
            PeriodKind::Dekad => 10,
        }
    }

    /// Last day as `(year, month, day)`.
    #[must_use]
    pub const fn end(&self) -> (i32, u8, u8) {
        let day = if self.index >= self.kind.periods_per_month() {
            days_in_month(self.year, self.month)
        } else {
            self.length().saturating_mul(self.index)
        };
        (self.year, self.month, day)
    }

    /// Number of days, `end − start + 1`: 5 for pentads 1–5; 3 to 6 for
    /// pentad 6, by the length of the month; 10 for dekads 1–2, 8 to 11 for
    /// dekad 3.
    #[must_use]
    pub fn days(&self) -> u8 {
        self.end()
            .2
            .saturating_sub(self.start().2)
            .saturating_add(1)
    }

    /// First day as `YYYY-MM-DD`.
    #[must_use]
    pub fn start_iso(&self) -> String {
        let (y, m, d) = self.start();
        format!("{y:04}-{m:02}-{d:02}")
    }

    /// Last day as `YYYY-MM-DD`.
    #[must_use]
    pub fn end_iso(&self) -> String {
        let (y, m, d) = self.end();
        format!("{y:04}-{m:02}-{d:02}")
    }

    /// The year-independent slot `MM-I`, for example `10-3`.
    #[must_use]
    pub fn slot(&self) -> String {
        format!("{:02}-{}", self.month, self.index)
    }
}

/// Whether a raster is the final or the preliminary release.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    /// Final release, from `final/`.
    Final,
    /// Preliminary release, from `prelim/`.
    Prelim,
}

/// The raster chosen for one period.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RasterFile {
    /// Period the raster covers.
    pub period: Period,
    /// Release the raster comes from.
    pub status: Status,
    /// Path of the raster file.
    pub path: PathBuf,
}

/// The period named by `file_name` under `template`, if the whole name
/// matches.
///
/// `{year}` is 4 digits, `{month}` 1–2 digits (1–12), `{pentad}` 1 digit
/// (1–6) or `{dekad}` 1 digit (1–3); every other character must match
/// literally. A template with both or neither of `{pentad}` and `{dekad}`
/// matches nothing.
#[must_use]
pub fn match_template(template: &str, file_name: &str) -> Option<Period> {
    let mut fields = Fields::default();
    if !match_from(template.as_bytes(), file_name.as_bytes(), &mut fields) {
        return None;
    }
    let (index, kind) = match (fields.pentad, fields.dekad) {
        (Some(index), None) => (index, PeriodKind::Pentad),
        (None, Some(index)) => (index, PeriodKind::Dekad),
        _ => return None,
    };
    Some(Period {
        year: fields.year?,
        month: fields.month?,
        index,
        kind,
    })
}

/// Fields captured while matching a template.
#[derive(Debug, Clone, Copy, Default)]
struct Fields {
    year: Option<i32>,
    month: Option<u8>,
    pentad: Option<u8>,
    dekad: Option<u8>,
}

/// Match `name` against `template` from the start, backtracking over the
/// width of `{month}`.
fn match_from(template: &[u8], name: &[u8], fields: &mut Fields) -> bool {
    let placeholders: [(&[u8], usize, usize); 4] = [
        (b"{year}", 4, 4),
        (b"{month}", 1, 2),
        (b"{pentad}", 1, 1),
        (b"{dekad}", 1, 1),
    ];
    for (token, min, max) in placeholders {
        let Some(rest) = template.strip_prefix(token) else {
            continue;
        };
        for width in min..=max.min(name.len()) {
            let (digits, tail) = name.split_at(width);
            let Some(value) = parse_digits(digits) else {
                continue;
            };
            let mut next = *fields;
            let valid = match token {
                b"{year}" => {
                    next.year = i32::try_from(value).ok();
                    true
                }
                b"{month}" => {
                    next.month = u8::try_from(value).ok();
                    (1..=12).contains(&value)
                }
                b"{dekad}" => {
                    next.dekad = u8::try_from(value).ok();
                    (1..=3).contains(&value)
                }
                _ => {
                    next.pentad = u8::try_from(value).ok();
                    (1..=6).contains(&value)
                }
            };
            if valid && match_from(rest, tail, &mut next) {
                *fields = next;
                return true;
            }
        }
        return false;
    }
    match (template.split_first(), name.split_first()) {
        (None, None) => true,
        (Some((t, trest)), Some((n, nrest))) if t == n => match_from(trest, nrest, fields),
        _ => false,
    }
}

/// The value of an all-ASCII-digit byte string, `None` otherwise.
fn parse_digits(digits: &[u8]) -> Option<u32> {
    digits.iter().try_fold(0u32, |acc, &b| {
        b.is_ascii_digit().then(|| acc * 10 + u32::from(b - b'0'))
    })
}

/// The best raster for every period found under `dir/final` and
/// `dir/prelim`, sorted by period.
///
/// A missing subfolder counts as empty. Names in `final/` are matched
/// against `final_template`, names in `prelim/` against `prelim_template`;
/// others, and entries that are not regular files (after following
/// symlinks), are skipped. A final raster wins over a prelim one for the
/// same period.
///
/// # Errors
///
/// Fails when a subfolder exists but cannot be listed, or when two files of
/// one subfolder name the same period (for example `2026.1.3` and
/// `2026.01.3`), naming both.
pub fn discover(
    dir: &Path,
    final_template: &str,
    prelim_template: &str,
) -> anyhow::Result<Vec<RasterFile>> {
    let mut best: BTreeMap<Period, RasterFile> = BTreeMap::new();
    let mut seen: HashMap<(Period, Status), PathBuf> = HashMap::new();
    for (sub, status, template) in [
        ("final", Status::Final, final_template),
        ("prelim", Status::Prelim, prelim_template),
    ] {
        let folder = dir.join(sub);
        let entries = match fs::read_dir(&folder) {
            Ok(entries) => entries,
            Err(e) if e.kind() == ErrorKind::NotFound => continue,
            Err(e) => {
                return Err(e).with_context(|| format!("listing {}", folder.display()));
            }
        };
        let mut paths = entries
            .map(|entry| entry.map(|e| e.path()))
            .collect::<Result<Vec<_>, _>>()
            .with_context(|| format!("listing {}", folder.display()))?;
        paths.sort();
        for path in paths {
            let period = path
                .file_name()
                .and_then(|n| n.to_str())
                .and_then(|n| match_template(template, n));
            let Some(period) = period else {
                tracing::debug!(path = %path.display(), "skipping file that does not match the template");
                continue;
            };
            if !path.is_file() {
                tracing::debug!(path = %path.display(), "skipping entry that is not a regular file");
                continue;
            }
            if let Some(first) = seen.insert((period, status), path.clone()) {
                bail!(
                    "{} and {} both hold period {}",
                    first.display(),
                    path.display(),
                    period.start_iso()
                );
            }
            best.entry(period).or_insert(RasterFile {
                period,
                status,
                path,
            });
        }
    }
    Ok(best.into_values().collect())
}

/// `unix_secs` in UTC as `YYYYMMDDTHHMMZ`.
#[must_use]
pub fn utc_compact(unix_secs: i64) -> String {
    let (y, mo, d, h, mi, _) = civil_utc(unix_secs);
    format!("{y:04}{mo:02}{d:02}T{h:02}{mi:02}Z")
}

/// `unix_secs` in UTC as `YYYY-MM-DDTHH:MM:SSZ`.
#[must_use]
pub fn utc_iso(unix_secs: i64) -> String {
    let (y, mo, d, h, mi, s) = civil_utc(unix_secs);
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{mi:02}:{s:02}Z")
}

/// `day` (`(year, month, day)`) plus `days`, as `YYYY-MM-DD`.
#[must_use]
pub fn date_plus_days(day: (i32, u8, u8), days: u16) -> String {
    let (year, month, day) = day;
    let (y, m, d) = civil_from_days(days_from_civil(year, month, day) + i64::from(days));
    format!("{y:04}-{m:02}-{d:02}")
}

/// Days since 1970-01-01 of a Gregorian date (Howard Hinnant's
/// `days_from_civil`).
fn days_from_civil(year: i32, month: u8, day: u8) -> i64 {
    let (month, day) = (i64::from(month), i64::from(day));
    let year = i64::from(year) - i64::from(month <= 2);
    let era = year.div_euclid(400);
    let yoe = year.rem_euclid(400);
    let mp = (month + 9) % 12;
    let doy = (153 * mp + 2) / 5 + day - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// `(year, month, day, hour, minute, second)` of `unix_secs` in UTC.
fn civil_utc(unix_secs: i64) -> (i64, i64, i64, i64, i64, i64) {
    let days = unix_secs.div_euclid(86_400);
    let secs = unix_secs.rem_euclid(86_400);
    let (y, m, d) = civil_from_days(days);
    (y, m, d, secs / 3600, secs % 3600 / 60, secs % 60)
}

/// Gregorian `(year, month, day)` of a count of days since 1970-01-01
/// (Howard Hinnant's `civil_from_days`).
fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let day = doy - (153 * mp + 2) / 5 + 1;
    let month = if mp < 10 { mp + 3 } else { mp - 9 };
    let year = yoe + era * 400 + i64::from(month <= 2);
    (year, month, day)
}

/// Number of days in `month` of `year` (Gregorian).
const fn days_in_month(year: i32, month: u8) -> u8 {
    match month {
        2 if (year % 4 == 0 && year % 100 != 0) || year % 400 == 0 => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

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

    const TEMPLATE: &str = "chirps-v3.0.{year}.{month}.{pentad}.tif";

    fn period(year: i32, month: u8, index: u8) -> Period {
        Period {
            year,
            month,
            index,
            kind: PeriodKind::Pentad,
        }
    }

    fn dekad(year: i32, month: u8, index: u8) -> Period {
        Period {
            year,
            month,
            index,
            kind: PeriodKind::Dekad,
        }
    }

    #[test]
    fn a_dekad_runs_to_the_month_end() {
        let leap_third = dekad(2024, 2, 3);
        assert_eq!(leap_third.start(), (2024, 2, 21));
        assert_eq!(leap_third.end(), (2024, 2, 29));
        assert_eq!(leap_third.days(), 9);
        let first = dekad(2024, 2, 1);
        assert_eq!((first.start().2, first.end().2, first.days()), (1, 10, 10));
        let second = dekad(2026, 11, 2);
        assert_eq!(second.start_iso(), "2026-11-11");
        assert_eq!(second.end_iso(), "2026-11-20");
        assert_eq!(second.slot(), "11-2");
        assert_eq!(dekad(2026, 7, 3).end_iso(), "2026-07-31");
    }

    #[test]
    fn a_template_with_both_period_tokens_matches_nothing() {
        assert_eq!(
            match_template("n.{year}.{month}.{pentad}.{dekad}", "n.2026.1.2.3"),
            None
        );
    }

    fn touch(dir: &Path, sub: &str, name: &str) {
        let folder = dir.join(sub);
        fs::create_dir_all(&folder).unwrap();
        fs::write(folder.join(name), b"x").unwrap();
    }

    #[test]
    fn pentad_three_of_october_is_the_eleventh_to_the_fifteenth() {
        let p = period(2026, 10, 3);
        assert_eq!(p.start_iso(), "2026-10-11");
        assert_eq!(p.end_iso(), "2026-10-15");
        assert_eq!(p.slot(), "10-3");
    }

    #[test]
    fn pentad_six_ends_on_the_last_day() {
        for (year, month, last) in [
            (2028, 2, "2028-02-29"),
            (2026, 2, "2026-02-28"),
            (2026, 7, "2026-07-31"),
            (1900, 2, "1900-02-28"),
            (2000, 2, "2000-02-29"),
        ] {
            assert_eq!(period(year, month, 6).end_iso(), last);
        }
    }

    #[test]
    fn a_period_counts_its_days() {
        // Pentads 1-5 have 5 days; pentad 6 runs from the 26th to the last
        // day of the month: 3 (Feb), 4 (leap Feb), 5 (30-day), 6 (31-day).
        for (year, month, index, days) in [
            (2026, 10, 3, 5),
            (2026, 2, 6, 3),
            (2024, 2, 6, 4),
            (1900, 2, 6, 3),
            (2026, 11, 6, 5),
            (2026, 1, 6, 6),
        ] {
            assert_eq!(
                period(year, month, index).days(),
                days,
                "{year}-{month} pentad {index}"
            );
        }
    }

    #[test]
    fn the_template_matches_whole_names() {
        assert_eq!(
            match_template(TEMPLATE, "chirps-v3.0.2026.10.3.tif"),
            Some(period(2026, 10, 3))
        );
        for name in [
            "chirps-v3.0.2026.10.3.tif.part",
            "chirps-v3.0.2026.13.3.tif",
            "chirps-v3.0.2026.10.7.tif",
            "x-chirps-v3.0.2026.10.3.tif",
        ] {
            assert_eq!(match_template(TEMPLATE, name), None, "{name}");
        }
    }

    #[test]
    fn final_wins_over_prelim_for_the_same_period() {
        let dir = tempfile::tempdir().unwrap();
        touch(dir.path(), "final", "chirps-v3.0.2026.10.3.tif");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.10.3.tif");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.10.4.tif");
        let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
        assert_eq!(files.len(), 2);
        let third = files
            .iter()
            .find(|f| f.period == period(2026, 10, 3))
            .unwrap();
        assert_eq!(third.status, Status::Final);
        assert!(third.path.to_string_lossy().contains("/final/"));
        let fourth = files
            .iter()
            .find(|f| f.period == period(2026, 10, 4))
            .unwrap();
        assert_eq!(fourth.status, Status::Prelim);
    }

    #[test]
    fn foreign_and_partial_files_are_skipped() {
        let dir = tempfile::tempdir().unwrap();
        touch(dir.path(), "final", "chirps-v3.0.2026.10.3.tif");
        touch(dir.path(), "final", "README.txt");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.10.5.tif.part");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.10.5.tif.aria2");
        let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
        assert!(files.iter().all(|f| f.period.slot() != "10-5"));
        assert!(files.iter().any(|f| f.period == period(2026, 10, 3)));
    }

    #[test]
    fn discovery_does_not_depend_on_creation_order() {
        let dir = tempfile::tempdir().unwrap();
        for (month, pentad) in [(12, 6), (11, 2), (10, 4), (10, 1), (1, 3)] {
            touch(
                dir.path(),
                "prelim",
                &format!("chirps-v3.0.2026.{month}.{pentad}.tif"),
            );
        }
        touch(dir.path(), "final", "chirps-v3.0.2025.12.6.tif");
        let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
        assert_eq!(files.len(), 6);
        for pair in files.windows(2) {
            assert!(pair[0].period < pair[1].period, "{:?}", pair);
        }
    }

    #[test]
    fn finals_and_prelims_use_their_own_templates() {
        // CHIRPS v3.0 finals are `.cog`, prelims `.tif` (real host listing).
        let final_template = "chirps-v3.0.{year}.{month}.{pentad}.cog";
        let dir = tempfile::tempdir().unwrap();
        touch(dir.path(), "final", "chirps-v3.0.2026.10.6.cog");
        touch(dir.path(), "final", "chirps-v3.0.2026.10.5.tif");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.11.2.tif");
        touch(dir.path(), "prelim", "chirps-v3.0.2026.11.1.cog");
        let files = discover(dir.path(), final_template, TEMPLATE).unwrap();
        let october = files
            .iter()
            .find(|f| f.period == period(2026, 10, 6))
            .expect("the final .cog is found");
        assert_eq!(october.status, Status::Final);
        let november = files
            .iter()
            .find(|f| f.period == period(2026, 11, 2))
            .expect("the prelim .tif is found");
        assert_eq!(november.status, Status::Prelim);
        assert!(
            files
                .iter()
                .all(|f| f.period != period(2026, 10, 5) && f.period != period(2026, 11, 1)),
            "a name matching only the other folder's template is skipped: {files:?}"
        );
    }

    #[test]
    fn a_directory_matching_the_template_is_skipped() {
        let dir = tempfile::tempdir().unwrap();
        fs::create_dir_all(dir.path().join("final/chirps-v3.0.2026.10.3.tif")).unwrap();
        touch(dir.path(), "final", "chirps-v3.0.2026.10.4.tif");
        let files = discover(dir.path(), TEMPLATE, TEMPLATE).unwrap();
        assert!(
            files.iter().all(|f| f.period != period(2026, 10, 3)),
            "{files:?}"
        );
        let fourth = files
            .iter()
            .find(|f| f.period == period(2026, 10, 4))
            .expect("the regular file is found");
        assert!(fourth.path.is_file());
    }

    #[test]
    fn two_names_for_one_period_fail_naming_both() {
        let template = "chirps-v3.0.{year}.{month}.{pentad}.cog";
        let dir = tempfile::tempdir().unwrap();
        touch(dir.path(), "final", "chirps-v3.0.2026.1.3.cog");
        touch(dir.path(), "final", "chirps-v3.0.2026.01.3.cog");
        let err = discover(dir.path(), template, TEMPLATE).expect_err("two names, one period");
        let text = format!("{err:#}");
        assert!(text.contains("chirps-v3.0.2026.1.3.cog"), "{text}");
        assert!(text.contains("chirps-v3.0.2026.01.3.cog"), "{text}");
    }

    #[test]
    fn utc_formats_match_known_instants() {
        assert_eq!(utc_compact(0), "19700101T0000Z");
        // Expected value printed by `date -u -r 1794859463 +%Y%m%dT%H%MZ`.
        assert_eq!(utc_compact(1_794_859_463), "20261116T2004Z");
        assert_eq!(utc_iso(951_782_400), "2000-02-29T00:00:00Z");
    }

    #[test]
    fn days_are_added_across_months_years_and_leap_days() {
        // Expected values from `date -u -j -v+18d -f %F <day> +%F` (BSD date).
        assert_eq!(date_plus_days((2026, 11, 10), 18), "2026-11-28");
        assert_eq!(date_plus_days((2026, 12, 31), 18), "2027-01-18");
        assert_eq!(date_plus_days((2028, 2, 20), 18), "2028-03-09");
        assert_eq!(date_plus_days((2027, 2, 20), 18), "2027-03-10");
        assert_eq!(date_plus_days((2026, 6, 5), 0), "2026-06-05");
    }
}