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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
//! The shared layout of a stage: settings, the public set, the data root.
//!
//! Ported from the former `scripts/datasets/stage.ts`: [`Settings`] resolves the data
//! root, dataset, country, boundary release and tiles revision from the
//! deployment settings ([`crate::settings`]); [`is_public`] is the
//! only definition of what a stage may hold; [`complete_stages`] lists the
//! stages an upload may publish; [`current_key`], [`build_prefix`] and
//! [`boundaries_prefix`] are the object keys, all under the key prefix
//! (`storage.prefix`, `datasets/` when unset).

use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::io::Read as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result, bail};
use serde_json::Value;
use sha2::{Digest as _, Sha256};

use crate::country::CountryConfig;
use crate::settings;

/// Boundary release used when neither the environment nor the country config
/// names one.
pub const DEFAULT_BOUNDARY_RELEASE: &str = "2026-10-21.0";

/// Baseline used when neither the environment nor the dataset config names
/// one.
pub const DEFAULT_BASELINE: &str = "1991-2020";

/// Paths and keys of one dataset and country.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Settings {
    /// Dataset id, e.g. `rainfall`.
    pub dataset: String,
    /// Country code, lower case (object keys).
    pub cc: String,
    /// The data root, absolute and physical.
    pub data_root: PathBuf,
    /// The repo root.
    pub repo: PathBuf,
    /// Prefix of every object key, with a trailing `/` (`storage.prefix`).
    pub key_root: String,
    /// Boundary release of the country.
    pub boundary_release: String,
    /// Revision of the boundaries tiles; revision N ≥ 2 lives in
    /// `<release>-r<N>/`.
    pub boundary_tiles_revision: u8,
    /// Baseline years, `FIRST-LAST`.
    pub baseline: String,
    /// The dataset config JSON.
    pub config_path: PathBuf,
    /// The country config JSON.
    pub country_config_path: PathBuf,
    /// The published list (`PUBLISHED_CSV` when set).
    pub published_csv: PathBuf,
    /// `$DATA_ROOT/datasets/stage`.
    pub stage_root: PathBuf,
}

impl Settings {
    /// A fixed settings value for tests: no environment is read.
    #[cfg(test)]
    #[must_use]
    pub fn for_test(dataset: &str, cc: &str, data_root: &str) -> Self {
        let repo = PathBuf::from("/nonexistent/repo");
        let data_root = PathBuf::from(data_root);
        Self {
            dataset: dataset.to_owned(),
            cc: cc.to_owned(),
            repo: repo.clone(),
            key_root: crate::settings::DEFAULT_KEY_PREFIX.to_owned(),
            config_path: repo
                .join("packages/dataset-builder/data/datasets")
                .join(format!("{dataset}.json")),
            country_config_path: repo
                .join("packages/dataset-builder/data/datasets/countries")
                .join(format!("{cc}.json")),
            published_csv: repo
                .join("packages/dataset-builder/data/datasets")
                .join(cc)
                .join("published.csv"),
            stage_root: data_root.join("datasets/stage"),
            data_root,
            boundary_release: DEFAULT_BOUNDARY_RELEASE.to_owned(),
            boundary_tiles_revision: 1,
            baseline: DEFAULT_BASELINE.to_owned(),
        }
    }

    /// The country config, when it can be read and parsed.
    #[must_use]
    pub fn country_config(&self) -> Option<CountryConfig> {
        CountryConfig::load(&self.country_config_path).ok()
    }

    /// The top folder of a stage: the first segment of every key.
    #[must_use]
    pub fn key_top(&self) -> &str {
        self.key_root.split('/').next().unwrap_or_default()
    }
}

/// The repo root: `GEOLITH_REPO` or `repo` of the config file, else the
/// checkout the binary was built from, else the checkout of the working
/// directory.
///
/// # Errors
///
/// Fails when none of them is a geolith checkout.
pub fn repo_root() -> Result<PathBuf> {
    if let Some(dir) = settings::current().repo.clone() {
        return Ok(dir);
    }
    // The binary of a release build outlives its checkout: the field is only
    // the default, and a run outside the checkout needs GEOLITH_REPO.
    let built = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .map(Path::to_path_buf)
        .context("the crate manifest has no repo root")?;
    if is_checkout(&built) {
        return Ok(built);
    }
    let cwd = env::current_dir().context("reading the working directory")?;
    let output = Command::new("git")
        .arg("-C")
        .arg(&cwd)
        .args(["rev-parse", "--show-toplevel"])
        .output()
        .context("running git rev-parse")?;
    if !output.status.success() {
        bail!(
            "not in a geolith checkout: {} (set GEOLITH_REPO): {}",
            cwd.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
    if !is_checkout(&root) {
        bail!(
            "{} is not a geolith checkout (set GEOLITH_REPO)",
            root.display()
        );
    }
    Ok(root)
}

/// Whether `dir` holds the repo's dataset data folder.
fn is_checkout(dir: &Path) -> bool {
    dir.join("packages/dataset-builder/data/datasets/boundaries.json")
        .is_file()
}

/// The data root: `DATA_ROOT` or `data_root` of the config file, else the
/// `.data` folder of the main checkout (`<git common dir>/../.data`),
/// absolute and physical.
///
/// # Errors
///
/// Fails when git cannot be run or that folder does not exist.
pub fn data_root() -> Result<PathBuf> {
    if let Some(dir) = settings::current().data_root.clone() {
        return Ok(dir);
    }
    let repo = repo_root()?;
    let output = Command::new("git")
        .arg("-C")
        .arg(&repo)
        .args(["rev-parse", "--path-format=absolute", "--git-common-dir"])
        .output()
        .context("running git rev-parse")?;
    if !output.status.success() {
        bail!(
            "not in a git checkout: {} (set DATA_ROOT): {}",
            repo.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    let common = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
    let root = common.join("..").join(".data");
    if !root.is_dir() {
        bail!("data root not found: {} (set DATA_ROOT)", root.display());
    }
    fs::canonicalize(&root).with_context(|| format!("resolving {}", root.display()))
}

/// The settings of `dataset` and `country`, with the shell pipeline's
/// defaults and overrides.
///
/// # Errors
///
/// Fails when the data root or the tiles revision cannot be read.
pub fn settings(dataset: Option<&str>, country: Option<&str>) -> Result<Settings> {
    let data_root = data_root()?;
    let repo = repo_root()?;
    let run = &settings::current().run;
    let dataset = dataset
        .map(str::to_owned)
        .or_else(|| run.dataset.clone())
        .unwrap_or_else(|| "rainfall".to_owned());
    let cc = country
        .map(str::to_owned)
        .or_else(|| run.country.clone())
        .unwrap_or_else(|| "in".to_owned())
        .to_lowercase();
    let datasets = repo.join("packages/dataset-builder/data/datasets");
    let config_path = datasets.join(format!("{dataset}.json"));
    let country_config_path = run
        .country_config
        .clone()
        .unwrap_or_else(|| datasets.join("countries").join(format!("{cc}.json")));
    let boundary_release = run
        .boundary_release
        .clone()
        .or_else(|| country_release(&country_config_path))
        .unwrap_or_else(|| DEFAULT_BOUNDARY_RELEASE.to_owned());
    let boundary_tiles_revision = match &run.boundary_tiles_revision {
        Some(value) => value.parse::<u8>().with_context(|| {
            format!("BOUNDARY_TILES_REVISION {value:?} is not a tiles revision")
        })?,
        None => config_tiles_revision(&datasets.join("boundaries.json"))?,
    };
    if boundary_tiles_revision == 0 {
        bail!(
            "{}: tiles_revision must be an integer 1..99",
            datasets.join("boundaries.json").display()
        );
    }
    let baseline = run
        .baseline
        .clone()
        .or_else(|| {
            read_json(&config_path).ok().and_then(|value| {
                value
                    .get("baseline")
                    .and_then(Value::as_str)
                    .map(str::to_owned)
            })
        })
        .unwrap_or_else(|| DEFAULT_BASELINE.to_owned());
    let published_csv = run
        .published_csv
        .clone()
        .unwrap_or_else(|| datasets.join(&cc).join("published.csv"));
    Ok(Settings {
        dataset,
        cc,
        stage_root: data_root.join("datasets/stage"),
        data_root,
        repo,
        key_root: settings::current().key_root().to_owned(),
        boundary_release,
        boundary_tiles_revision,
        baseline,
        config_path,
        country_config_path,
        published_csv,
    })
}

/// `tiles_revision` of the boundaries config at `path`.
///
/// # Errors
///
/// Fails when the file cannot be read or the value is not an integer 1..=99.
pub fn config_tiles_revision(path: &Path) -> Result<u8> {
    let value = read_json(path)?
        .get("tiles_revision")
        .and_then(Value::as_u64)
        .with_context(|| {
            format!(
                "{}: tiles_revision must be an integer 1..99",
                path.display()
            )
        })?;
    let revision = u8::try_from(value)
        .ok()
        .filter(|revision| (1..=99).contains(revision))
        .with_context(|| {
            format!(
                "{}: tiles_revision must be an integer 1..99",
                path.display()
            )
        })?;
    Ok(revision)
}

/// The boundary release a country config names, when it has one.
fn country_release(path: &Path) -> Option<String> {
    read_json(path)
        .ok()?
        .get("boundaries")?
        .get("release")?
        .as_str()
        .filter(|release| !release.is_empty())
        .map(str::to_owned)
}

/// The JSON value of the file at `path`.
///
/// # Errors
///
/// Fails when the file cannot be read or parsed.
pub fn read_json(path: &Path) -> Result<Value> {
    let text = fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))
}

/// Folder name of the boundaries of the release and tiles revision:
/// `<release>` for revision 1, `<release>-r<N>` after.
#[must_use]
pub fn boundaries_dir(s: &Settings) -> String {
    if s.boundary_tiles_revision >= 2 {
        format!("{}-r{}", s.boundary_release, s.boundary_tiles_revision)
    } else {
        s.boundary_release.clone()
    }
}

/// Object key of a build's folder, with the trailing `/`.
#[must_use]
pub fn build_prefix(s: &Settings, id: &str) -> String {
    format!("{}{}/{}/{id}/", s.key_root, s.dataset, s.cc)
}

/// Object key of the boundaries folder, with the trailing `/`.
#[must_use]
pub fn boundaries_prefix(s: &Settings) -> String {
    format!("{}boundaries/{}/{}/", s.key_root, s.cc, boundaries_dir(s))
}

/// Object key of the pointer.
#[must_use]
pub fn current_key(s: &Settings) -> String {
    format!("{}{}/{}/current.json", s.key_root, s.dataset, s.cc)
}

/// Whether `key` is in the public set of build `id`: its area JSONs,
/// `index.json`, `series.json`, `numbers.csv`, `numbers.parquet`,
/// `tiles.pmtiles` and the period layers `tiles/<YYYY-MM-DD>.pmtiles`, the
/// boundaries' `areas.pmtiles`, `areas.parquet` and `LICENSE.txt`, and the
/// pointer.
#[must_use]
pub fn is_public(s: &Settings, id: &str, key: &str) -> bool {
    let build = build_prefix(s, id);
    if let Some(rest) = key.strip_prefix(&format!("{build}areas/")) {
        return is_area_file(rest);
    }
    if let Some(rest) = key.strip_prefix(&format!("{build}tiles/")) {
        return is_period_layer(rest);
    }
    let boundaries = boundaries_prefix(s);
    [
        format!("{build}index.json"),
        format!("{build}series.json"),
        format!("{build}numbers.csv"),
        format!("{build}numbers.parquet"),
        format!("{build}tiles.pmtiles"),
        format!("{boundaries}areas.pmtiles"),
        format!("{boundaries}areas.parquet"),
        format!("{boundaries}LICENSE.txt"),
        current_key(s),
    ]
    .iter()
    .any(|public| public == key)
}

/// `^[A-Za-z0-9_-][A-Za-z0-9._-]*\.json$`.
fn is_area_file(name: &str) -> bool {
    let Some(stem) = name.strip_suffix(".json") else {
        return false;
    };
    let mut bytes = stem.bytes();
    let Some(first) = bytes.next() else {
        return false;
    };
    if !(first.is_ascii_alphanumeric() || first == b'_' || first == b'-') {
        return false;
    }
    bytes.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-'))
}

/// `^\d{4}-\d{2}-\d{2}\.pmtiles$`.
fn is_period_layer(name: &str) -> bool {
    let Some(date) = name.strip_suffix(".pmtiles") else {
        return false;
    };
    let bytes = date.as_bytes();
    bytes.len() == 10
        && bytes[4] == b'-'
        && bytes[7] == b'-'
        && [0, 1, 2, 3, 5, 6, 8, 9]
            .iter()
            .all(|i| bytes[*i].is_ascii_digit())
}

/// Whether `key` is a dated build or boundaries key of the layout under
/// `key_root`, or (with `pointer`) the key of a `current.json` pointer. The
/// strict layout of `remote.ts`: a build file, a boundaries file, or the
/// pointer.
#[must_use]
pub fn is_layout_key(key_root: &str, key: &str, pointer: bool) -> bool {
    if key.split('/').any(|part| part == ".." || part == ".") {
        return false;
    }
    let Some(rest) = key.strip_prefix(key_root) else {
        return false;
    };
    let parts: Vec<&str> = rest.split('/').collect();
    let Some(head) = parts.first() else {
        return false;
    };
    if *head == "boundaries" {
        // <key_root>boundaries/<cc>/<release>/<file>
        return match parts.as_slice() {
            [_, cc, release, file] => {
                !pointer
                    && is_segment(cc)
                    && is_release(release)
                    && matches!(*file, "areas.pmtiles" | "areas.parquet" | "LICENSE.txt")
            }
            _ => false,
        };
    }
    if !is_segment(head) {
        return false;
    }
    match parts.as_slice() {
        [ds, cc, pointer_file] => {
            pointer && is_segment(ds) && is_segment(cc) && *pointer_file == "current.json"
        }
        [ds, cc, id, file] => {
            !pointer && is_segment(ds) && is_segment(cc) && is_build_id(id) && is_build_file(file)
        }
        [ds, cc, id, dir, file] => {
            !pointer
                && is_segment(ds)
                && is_segment(cc)
                && is_build_id(id)
                && (match *dir {
                    "tiles" => is_period_layer(file),
                    "areas" => is_area_file(file),
                    _ => false,
                })
        }
        _ => false,
    }
}

/// The files a build holds directly under its prefix.
fn is_build_file(name: &str) -> bool {
    matches!(
        name,
        "index.json" | "series.json" | "numbers.csv" | "numbers.parquet" | "tiles.pmtiles"
    )
}

/// `^[a-z0-9][a-z0-9-]*$`.
fn is_segment(text: &str) -> bool {
    let mut bytes = text.bytes();
    let Some(first) = bytes.next() else {
        return false;
    };
    (first.is_ascii_lowercase() || first.is_ascii_digit())
        && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

/// `^\d{4}-\d{2}-\d{2}\.\d{8}T\d{4}Z$`.
#[must_use]
pub fn is_build_id(text: &str) -> bool {
    let bytes = text.as_bytes();
    bytes.len() == 25
        && bytes[4] == b'-'
        && bytes[7] == b'-'
        && bytes[10] == b'.'
        && bytes[19] == b'T'
        && bytes[24] == b'Z'
        && [
            0, 1, 2, 3, 5, 6, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21, 22, 23,
        ]
        .iter()
        .all(|i| bytes[*i].is_ascii_digit())
}

/// `^\d{4}-\d{2}-\d{2}\.\d+(-r[2-9]|-r[1-9][0-9])?$` (a boundaries release
/// folder).
fn is_release(text: &str) -> bool {
    let bytes = text.as_bytes();
    if bytes.len() < 11
        || bytes[4] != b'-'
        || bytes[7] != b'-'
        || bytes[10] != b'.'
        || ![0, 1, 2, 3, 5, 6, 8, 9]
            .iter()
            .all(|i| bytes[*i].is_ascii_digit())
    {
        return false;
    }
    let rest = &text[11..];
    let (number, suffix) = match rest.split_once("-r") {
        Some((number, revision)) => (number, Some(revision)),
        None => (rest, None),
    };
    if number.is_empty() || !number.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    match suffix {
        None => true,
        Some(revision) => match revision.parse::<u8>() {
            Ok(value) => (2..=99).contains(&value) && !revision.starts_with('0'),
            Err(_) => false,
        },
    }
}

/// Why `key` may not be written, or `None`: upload writes only dated build
/// and boundaries keys under `key_root`, publish (`pointer`) only a
/// `current.json`.
#[must_use]
pub fn layout_key_refusal(key_root: &str, key: &str, pointer: bool) -> Option<String> {
    if is_layout_key(key_root, key, pointer) {
        return None;
    }
    let what = if pointer {
        "a current.json pointer"
    } else {
        "a dated dataset key"
    };
    Some(format!("key {key} refused: not {what} under {key_root}"))
}

/// Build ids of the complete stages under `root`, oldest first.
#[must_use]
pub fn complete_stages(root: &Path) -> Vec<String> {
    let Ok(entries) = fs::read_dir(root) else {
        return Vec::new();
    };
    let mut names: Vec<String> = entries
        .filter_map(|entry| entry.ok())
        .filter(|entry| !entry.file_name().to_string_lossy().starts_with('.'))
        .filter(|entry| entry.path().join("stage.json").is_file())
        .map(|entry| entry.file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

/// Every file under `dir`, as `/`-separated paths relative to it, sorted.
///
/// # Errors
///
/// Fails when a directory cannot be read.
pub fn files_under(dir: &Path) -> Result<Vec<String>> {
    fn walk(dir: &Path, prefix: &str, out: &mut Vec<String>) -> Result<()> {
        for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
            let entry = entry.with_context(|| format!("reading {}", dir.display()))?;
            let name = entry.file_name().to_string_lossy().into_owned();
            let path = entry.path();
            if path.is_dir() {
                walk(&path, &format!("{prefix}{name}/"), out)?;
            } else {
                out.push(format!("{prefix}{name}"));
            }
        }
        Ok(())
    }
    let mut out = Vec::new();
    walk(dir, "", &mut out)?;
    out.sort();
    Ok(out)
}

/// The `sha256` digest of the file at `path`.
///
/// # Errors
///
/// Fails when the file cannot be read.
pub fn sha256_file(path: &Path) -> Result<[u8; 32]> {
    let mut file = fs::File::open(path).with_context(|| format!("opening {}", path.display()))?;
    let mut hasher = Sha256::new();
    let mut buffer = vec![0_u8; 1 << 16];
    loop {
        let read = file
            .read(&mut buffer)
            .with_context(|| format!("reading {}", path.display()))?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hasher.finalize().into())
}

/// The hex `sha256` digest of the file at `path`.
///
/// # Errors
///
/// Fails when the file cannot be read.
pub fn sha256_hex(path: &Path) -> Result<String> {
    Ok(hex(&sha256_file(path)?))
}

/// The lower-case hex of a digest.
#[must_use]
pub fn hex(digest: &[u8]) -> String {
    use std::fmt::Write as _;
    digest.iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "{byte:02x}");
        out
    })
}

/// Gregorian `YYYY-MM-DDTHH:MM:SSZ` of the Unix second `secs`.
#[must_use]
pub fn format_utc(secs: i64) -> String {
    let (year, month, day, hour, minute, second) = split_utc(secs);
    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}

/// Gregorian `YYYY-MM-DD` of the Unix second `secs`.
#[must_use]
pub fn date_utc(secs: i64) -> String {
    let (year, month, day, _, _, _) = split_utc(secs);
    format!("{year:04}-{month:02}-{day:02}")
}

/// Gregorian `YYYY-MM-DDTHH:MM:SS.mmmZ` of the Unix millisecond `millis`
/// (`Date#toISOString`).
#[must_use]
pub fn format_utc_millis(millis: i128) -> String {
    let secs = i64::try_from(millis.div_euclid(1000)).unwrap_or(i64::MAX);
    let rest = millis.rem_euclid(1000);
    let (year, month, day, hour, minute, second) = split_utc(secs);
    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{rest:03}Z")
}

/// The current time as `YYYY-MM-DDTHH:MM:SSZ`.
#[must_use]
pub fn utc_now() -> String {
    format_utc(unix_seconds())
}

/// The current UTC date as `YYYY-MM-DD`.
#[must_use]
pub fn today_utc() -> String {
    date_utc(unix_seconds())
}

/// The current Unix second.
#[must_use]
pub fn unix_seconds() -> i64 {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    i64::try_from(now.as_secs()).unwrap_or(i64::MAX)
}

/// The Unix millisecond of a file's modification time, rounded to the
/// nearest millisecond as `Date#getTime` does.
///
/// # Errors
///
/// Fails when the metadata cannot be read.
pub fn modified_millis(path: &Path) -> Result<i128> {
    let modified = fs::metadata(path)
        .with_context(|| format!("reading {}", path.display()))?
        .modified()
        .with_context(|| format!("reading the mtime of {}", path.display()))?;
    let Ok(since) = modified.duration_since(UNIX_EPOCH) else {
        return Ok(0);
    };
    let nanos = i128::from(since.subsec_nanos());
    Ok(i128::from(since.as_secs()) * 1000 + (nanos + 500_000) / 1_000_000)
}

/// `(year, month, day, hour, minute, second)` of a Unix second.
fn split_utc(secs: i64) -> (i64, i64, i64, i64, i64, i64) {
    let days = secs.div_euclid(86_400);
    let rest = secs.rem_euclid(86_400);
    let (year, month, day) = civil_from_days(days);
    (year, month, day, rest / 3600, rest % 3600 / 60, rest % 60)
}

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

/// Gregorian `(year, month, day)` of a count of days since 1970-01-01
/// (Howard Hinnant's `civil_from_days`).
#[must_use]
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)
}

/// The day count of a `YYYY-MM-DD` date, or `None`.
#[must_use]
pub fn days_of_date(date: &str) -> Option<i64> {
    let mut parts = date.split('-');
    let year = parts.next()?.parse::<i64>().ok()?;
    let month = parts.next()?.parse::<i64>().ok()?;
    let day = parts.next()?.parse::<i64>().ok()?;
    if parts.next().is_some() {
        return None;
    }
    Some(days_from_civil(year, month, day))
}

/// The staged files of a stage, keyed by sorted object key.
pub type StagedFiles = BTreeMap<String, StageFile>;

/// One entry of `stage.json`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StageFile {
    /// The object key.
    pub key: String,
    /// Size in bytes.
    pub bytes: u64,
    /// Hex `sha256` of the staged file.
    pub sha256: String,
}

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

    #[test]
    fn the_public_set_is_the_build_files_the_areas_and_the_three_boundary_files() {
        let s = Settings::for_test("rainfall", "in", "/nonexistent/data");
        let base = "datasets/rainfall/in/2026-11-20.20261120T0000Z/";
        for ok in [
            "index.json",
            "numbers.csv",
            "numbers.parquet",
            "tiles.pmtiles",
            "areas/dr-kolkata.json",
        ] {
            assert!(
                is_public(&s, "2026-11-20.20261120T0000Z", &format!("{base}{ok}")),
                "{ok}"
            );
        }
        assert!(is_public(
            &s,
            "2026-11-20.20261120T0000Z",
            "datasets/boundaries/in/2026-10-21.0/LICENSE.txt"
        ));
        assert!(!is_public(
            &s,
            "2026-11-20.20261120T0000Z",
            &format!("{base}manifest.json")
        ));
        assert!(!is_public(
            &s,
            "2026-11-20.20261120T0000Z",
            &format!("{base}stats/notes.csv")
        ));
    }

    #[test]
    fn complete_stages_are_oldest_first_and_need_a_stage_json() {
        let dir = tempfile::tempdir().expect("a temp dir");
        for name in ["2026-11-20.20261120T0000Z", "2026-11-10.20261110T0000Z"] {
            std::fs::create_dir(dir.path().join(name)).expect("mkdir");
            std::fs::write(dir.path().join(name).join("stage.json"), "{}").expect("write");
        }
        std::fs::create_dir(dir.path().join("2026-11-15.20261115T0000Z")).expect("mkdir");
        assert_eq!(
            complete_stages(dir.path()),
            vec![
                "2026-11-10.20261110T0000Z".to_owned(),
                "2026-11-20.20261120T0000Z".to_owned()
            ]
        );
    }

    #[test]
    fn the_tiles_revision_of_the_boundaries_config_is_read() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("boundaries.json");
        std::fs::write(&path, r#"{"tiles_revision": 2}"#).expect("write");
        assert_eq!(config_tiles_revision(&path).expect("revision"), 2);
        std::fs::write(&path, r#"{"tiles_revision": 0}"#).expect("write");
        assert!(config_tiles_revision(&path).is_err());
    }

    #[test]
    fn a_revision_two_boundaries_folder_carries_the_suffix() {
        let mut s = Settings::for_test("rainfall", "in", "/d");
        s.boundary_tiles_revision = 2;
        assert_eq!(boundaries_dir(&s), "2026-10-21.0-r2");
        s.boundary_tiles_revision = 1;
        assert_eq!(boundaries_dir(&s), "2026-10-21.0");
    }

    #[test]
    fn a_deep_key_prefix_moves_every_key_and_the_stage_top() {
        let mut s = Settings::for_test("rainfall", "in", "/d");
        s.key_root = "mirror/ds/".to_owned();
        assert_eq!(s.key_top(), "mirror");
        let id = "2026-11-20.20261120T0000Z";
        assert_eq!(
            build_prefix(&s, id),
            "mirror/ds/rainfall/in/2026-11-20.20261120T0000Z/"
        );
        assert_eq!(current_key(&s), "mirror/ds/rainfall/in/current.json");
        assert_eq!(
            boundaries_prefix(&s),
            "mirror/ds/boundaries/in/2026-10-21.0/"
        );
        assert!(is_public(&s, id, &current_key(&s)));
        // The default prefix's key is not a key of this prefix.
        assert!(!is_public(&s, id, "datasets/rainfall/in/current.json"));
    }

    #[test]
    fn a_release_folder_with_an_r1_suffix_is_not_a_boundaries_key() {
        let root = "datasets/";
        assert!(
            layout_key_refusal(
                root,
                "datasets/boundaries/in/2026-10-21.0-r1/areas.pmtiles",
                false
            )
            .is_some()
        );
        assert!(
            layout_key_refusal(
                root,
                "datasets/boundaries/in/2026-10-21.0-r2/areas.pmtiles",
                false
            )
            .is_none()
        );
    }

    #[test]
    fn a_key_outside_the_prefix_or_with_a_path_traversal_is_refused() {
        let root = "mirror/ds/";
        let pointer = "mirror/ds/rainfall/in/current.json";
        assert!(layout_key_refusal(root, pointer, true).is_none());
        assert!(layout_key_refusal(root, pointer, false).is_some());
        assert!(layout_key_refusal(root, "mirror/ds/../../etc/passwd", false).is_some());
        // Another operator's prefix is not this one's.
        let error =
            layout_key_refusal(root, "datasets/rainfall/in/current.json", true).expect("refused");
        assert!(error.contains("under mirror/ds/"), "{error}");
        // A dated build file, and a build file of a foreign segment shape.
        let build = "mirror/ds/rainfall/in/2026-11-20.20261120T0000Z/tiles.pmtiles";
        assert!(layout_key_refusal(root, build, false).is_none());
        assert!(
            layout_key_refusal(
                root,
                "mirror/ds/Rain/in/2026-11-20.20261120T0000Z/tiles.pmtiles",
                false
            )
            .is_some()
        );
    }

    #[test]
    fn a_formatted_utc_second_is_its_iso_string() {
        // 2026-11-20T00:00:00Z
        assert_eq!(format_utc(1_795_132_800), "2026-11-20T00:00:00Z");
    }

    #[test]
    fn the_sha256_of_an_empty_file_is_the_known_digest() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("empty");
        std::fs::write(&path, b"").expect("write");
        assert_eq!(
            sha256_hex(&path).expect("digest"),
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }
}