geolith-dataset-builder 0.4.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
//! `geolith dataset fetch`: the sources of a dataset, resumable.
//!
//! Ported from the former `scripts/datasets/download.sh` (chirps, overture) and
//! `boundary.sh`. A CHIRPS raster lands in
//! `$DATA_ROOT/datasets/<dataset>/src/<status>/<name>` through a `.part`:
//! the remote size is the `content-length` of the last redirect's 2xx
//! response, a file of that size is skipped, a longer `.part` is discarded
//! and refetched, a shorter one is resumed. Every host is tried in order;
//! what none delivered is printed `FAILED <path>` and exits 1.

use std::fs;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;

use crate::error::{DatasetError, IoOp, IoResultExt as _, Result, WithinExt as _};

use crate::cli::FetchArgs;
use crate::country::{BoundaryFile, BoundarySource};
use crate::exit::Exit;
use crate::layout::{self, Settings, hex, read_json, sha256_file};
use crate::lists::{write_lists, write_lists_quiet};
use crate::settings;

/// Where the final COGs are listed.
const FINAL_LISTING: &str = "/products/CHIRPS/v3.0/pentads/global/cogs/";

/// Where the preliminary TIFs are listed.
const PRELIM_LISTING: &str = "/products/CHIRPS/v3.0/prelim/pentads/global/tifs/";

/// Attempts per request.
const ATTEMPTS: u32 = 10;

/// Delay between attempts, in seconds (`CURL_RETRY_DELAY`).
const RETRY_DELAY: u64 = 10;

/// The default host of the CHIRPS rasters. It answers `https` (HTTP/2) and
/// sends `http` on to it, so there is no cleartext fallback to keep.
const DEFAULT_HOST: &str = "https://data.chc.ucsb.edu";

/// The hosts of the CHIRPS rasters, in order.
///
/// # Errors
///
/// Fails when a configured host is not `https`: the rasters carry no checksum
/// of their own, so the transport is what vouches for them.
fn hosts() -> Result<Vec<String>> {
    checked_hosts(&settings::current().sources.chirps_hosts)
}

/// `configured` when every host is `https`; the default host when it is empty.
fn checked_hosts(configured: &[String]) -> Result<Vec<String>> {
    if configured.is_empty() {
        return Ok(vec![DEFAULT_HOST.to_owned()]);
    }
    if let Some(host) = configured.iter().find(|host| !host.starts_with("https://")) {
        return Err(DatasetError::fetch(format!(
            "the CHIRPS host {host} is not https: rasters are only fetched over TLS"
        )));
    }
    Ok(configured.to_vec())
}

/// A `ureq` agent with the download timeouts. With `https_only`, a request
/// and every redirect it follows must be `https`; TLS is verified either way.
fn agent(https_only: bool) -> Result<ureq::Agent> {
    Ok(ureq::Agent::config_builder()
        .timeout_global(Some(Duration::from_secs(1800)))
        .http_status_as_error(false)
        .https_only(https_only)
        .build()
        .into())
}

/// Whether `bytes` start like a TIFF: classic or `BigTIFF`, either byte order.
/// CHIRPS publishes no checksum, so this and the size are what a download is
/// held to: an error page or a truncated listing of the right length is not a
/// raster.
fn is_tiff_header(bytes: &[u8]) -> bool {
    matches!(
        bytes.get(..4),
        Some(b"II*\0" | b"MM\0*" | b"II+\0" | b"MM\0+")
    )
}

/// Whether the file at `path` starts like a TIFF.
fn starts_like_tiff(path: &Path) -> bool {
    use std::io::Read as _;
    let mut head = [0_u8; 4];
    fs::File::open(path)
        .and_then(|mut file| file.read_exact(&mut head))
        .is_ok()
        && is_tiff_header(&head)
}

/// The `content-length` of `url`'s last 2xx response, or `None`.
fn remote_size(agent: &ureq::Agent, url: &str) -> Option<u64> {
    let response = agent.head(url).call().ok()?;
    if !(200..300).contains(&response.status().as_u16()) {
        return None;
    }
    response
        .headers()
        .get("content-length")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.parse::<u64>().ok())
}

/// The size of `path`, or 0.
fn file_size(path: &Path) -> u64 {
    fs::metadata(path).map(|meta| meta.len()).unwrap_or(0)
}

/// The bytes of `url` from `start`, retried `ATTEMPTS` times.
fn get_from(agent: &ureq::Agent, url: &str, start: u64) -> Result<Vec<u8>> {
    let mut attempt = 0;
    loop {
        attempt += 1;
        let mut request = agent.get(url);
        if start > 0 {
            request = request.header("range", &format!("bytes={start}-"));
        }
        match request.call() {
            Ok(mut response) if (200..300).contains(&response.status().as_u16()) => {
                return response
                    .body_mut()
                    .with_config()
                    .limit(512 * 1024 * 1024)
                    .read_to_vec()
                    .within(format!("reading the body of {url}"));
            }
            Ok(response) => {
                if attempt >= ATTEMPTS {
                    return Err(DatasetError::fetch(format!(
                        "{url} answered {}",
                        response.status()
                    )));
                }
            }
            Err(error) => {
                if attempt >= ATTEMPTS {
                    return Err(error).within(format!("GET {url}"));
                }
            }
        }
        std::thread::sleep(Duration::from_secs(RETRY_DELAY));
    }
}

/// Download `path` into `dest` from the first host that serves it.
///
/// # Errors
///
/// Fails when no host delivers it, or a write fails.
pub fn fetch_one(agent: &ureq::Agent, hosts: &[String], path: &str, dest: &Path) -> Result<()> {
    let name = dest
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let sizes: Vec<Option<u64>> = hosts
        .iter()
        .map(|host| remote_size(agent, &format!("{host}{path}")))
        .collect();
    let part = dest.with_extension("part");
    if sizes.iter().all(Option::is_none) && dest.is_file() && !part.exists() {
        println!("SKIP {name} (no size)");
        return Ok(());
    }
    for (host, size) in hosts.iter().zip(&sizes) {
        let url = format!("{host}{path}");
        if let Some(size) = size {
            if dest.is_file() && file_size(dest) == *size {
                println!("SKIP {name}");
                return Ok(());
            }
            if part.is_file() && file_size(&part) == *size && starts_like_tiff(&part) {
                fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
                println!("OK {name}");
                return Ok(());
            }
            if part.is_file() && file_size(&part) == *size {
                fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
            }
            if part.is_file() && file_size(&part) > *size {
                // A shrunken remote: appending would corrupt the raster.
                fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
            }
        }
        let start = if part.is_file() { file_size(&part) } else { 0 };
        if start > 0 {
            println!("RESUME {name} from {start}");
        }
        if let Some(parent) = dest.parent() {
            fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
        }
        let Ok(bytes) = get_from(agent, &url, start) else {
            continue;
        };
        let mut file = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&part)
            .io_at(IoOp::Open, &part)?;
        file.write_all(&bytes).io_at(IoOp::Write, &part)?;
        drop(file);
        if let Some(size) = size
            && file_size(&part) != *size
        {
            eprintln!(
                "size mismatch for {url}: got {}, expected {size}",
                file_size(&part)
            );
            fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
            continue;
        }
        if !starts_like_tiff(&part) {
            eprintln!("{url} is not a TIFF: discarded");
            fs::remove_file(&part).io_at(IoOp::Remove, &part)?;
            continue;
        }
        fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
        println!("OK {name}");
        return Ok(());
    }
    if sizes.iter().all(Option::is_none) && dest.is_file() {
        println!("SKIP {name} (no size)");
        return Ok(());
    }
    Err(DatasetError::fetch(format!("no host delivered {path}")))
}

/// Download every file of the CHIRPS `list` into `<src>/<status>/`.
///
/// # Errors
///
/// Fails with [`Exit`] `1` when a file is missing, naming each one.
pub fn chirps(list: &Path, src: &Path) -> Result<()> {
    let text = fs::read_to_string(list).io_at(IoOp::Read, list)?;
    let agent = agent(true)?;
    let hosts = hosts()?;
    let mut failed = Vec::new();
    for line in text.lines() {
        let line = line.trim_end();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let (Some(status), Some(path)) = (parts.next(), parts.next()) else {
            eprintln!("bad list line: {line}");
            failed.push(line.to_owned());
            continue;
        };
        if status != "final" && status != "prelim" || !path.starts_with('/') {
            eprintln!("bad list line: {line}");
            failed.push(line.to_owned());
            continue;
        }
        let name = path.rsplit('/').next().unwrap_or_default();
        let dest = src.join(status).join(name);
        if fetch_one(&agent, &hosts, path, &dest).is_err() {
            failed.push(path.to_owned());
        }
    }
    if !failed.is_empty() {
        for path in &failed {
            println!("FAILED {path}");
        }
        return Err(Exit(1).into());
    }
    Ok(())
}

/// Download `url` (retried) and return its bytes.
///
/// # Errors
///
/// Fails when no attempt succeeds.
fn get_text(agent: &ureq::Agent, url: &str) -> Result<String> {
    let bytes = get_from(agent, url, 0)?;
    String::from_utf8(bytes).within(format!("{url} is not UTF-8"))
}

/// Fetch both listings into `lists`, then write the three lists.
fn fetch_listings(s: &Settings) -> Result<PathBuf> {
    let lists = s
        .data_root
        .join("datasets")
        .join(&s.dataset)
        .join(&s.cc)
        .join("lists");
    fs::create_dir_all(&lists).io_at(IoOp::Create, &lists)?;
    let agent = agent(true)?;
    let hosts = hosts()?;
    for (listing, name) in [
        (FINAL_LISTING, "listing-final.html"),
        (PRELIM_LISTING, "listing-prelim.html"),
    ] {
        let mut written = false;
        for host in &hosts {
            if let Ok(text) = get_text(&agent, &format!("{host}{listing}")) {
                let path = lists.join(name);
                let partial = path.with_extension("partial");
                fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
                fs::rename(&partial, &path).io_at(IoOp::RenameTo, &path)?;
                written = true;
                break;
            }
        }
        if !written {
            return Err(DatasetError::fetch(format!(
                "no host of {hosts:?} served the listing {listing}"
            )));
        }
    }
    Ok(lists)
}

/// A country's boundary archives, unzipped in place.
///
/// # Errors
///
/// Fails with [`Exit`] `3` on a sha256 mismatch, and when a download or an
/// unzip fails.
pub fn boundaries(s: &Settings) -> Result<PathBuf> {
    let config = crate::country::CountryConfig::load(&s.country_config_path)?;
    if config.boundaries.source != BoundarySource::Shapefile {
        return Err(DatasetError::fetch(format!(
            "{} has no boundary download",
            s.cc
        )));
    }
    let dir = s
        .data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join("src")
        .join(&config.boundaries.release);
    fs::create_dir_all(&dir).io_at(IoOp::Create, &dir)?;
    // Every boundary archive is held to the sha256 of its config, so the agent
    // may follow a configured mirror over any scheme.
    let agent = agent(false)?;
    let archives: Vec<(PathBuf, &BoundaryFile)> = [
        config.boundaries.units.as_ref(),
        config.boundaries.parents.as_ref(),
    ]
    .into_iter()
    .flatten()
    .map(|file| {
        let name = file.url.rsplit('/').next().unwrap_or_default().to_owned();
        (dir.join(name), file)
    })
    .collect();
    for (dest, file) in &archives {
        fetch_archive(&agent, dest, file)?;
    }
    for (dest, file) in &archives {
        unzip_members(dest, &dir, file)?;
    }
    for (dest, file) in &archives {
        let member = dir.join(file.member.rsplit('/').next().unwrap_or(&file.member));
        if !member.is_file() {
            return Err(DatasetError::fetch(format!(
                "{} holds no {}",
                dest.display(),
                file.member
            )));
        }
    }
    println!("{}", dir.display());
    Ok(dir)
}

/// Download one boundary archive and check its sha256.
fn fetch_archive(agent: &ureq::Agent, dest: &Path, file: &BoundaryFile) -> Result<()> {
    let name = dest
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    if dest.is_file() {
        let digest = hex(&sha256_file(dest)?);
        if digest == file.sha256 {
            println!("SKIP {name} ({digest})");
            return Ok(());
        }
    }
    let url = settings::current()
        .sources
        .boundaries_url_base
        .as_deref()
        .map_or_else(
            || file.url.clone(),
            |base| format!("{}/{name}", base.trim_end_matches('/')),
        );
    let part = dest.with_extension("part");
    let start = if part.is_file() { file_size(&part) } else { 0 };
    let bytes = get_from(agent, &url, start).within(format!("downloading {url}"))?;
    let mut out = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&part)
        .io_at(IoOp::Open, &part)?;
    out.write_all(&bytes).io_at(IoOp::Write, &part)?;
    drop(out);
    fs::rename(&part, dest).io_at(IoOp::Rename, &part)?;
    let digest = hex(&sha256_file(dest)?);
    if digest != file.sha256 {
        return Err(DatasetError::Exit(Exit(3)));
    }
    println!("FETCHED {name} ({digest})");
    Ok(())
}

/// Unzip every member of `archive` into `dir`, as `boundary.sh` does.
///
/// # Errors
///
/// Fails when `unzip` is absent or cannot read the archive.
fn unzip_members(archive: &Path, dir: &Path, file: &BoundaryFile) -> Result<()> {
    let output = Command::new("unzip")
        .args(["-o", "-q"])
        .arg(archive)
        .arg("-d")
        .arg(dir)
        .output();
    match output {
        Ok(output) if output.status.success() => {
            let _ = file;
            Ok(())
        }
        Ok(output) => Err(DatasetError::fetch(format!(
            "unzip {} failed (exit {}): {}",
            archive.display(),
            output.status.code().unwrap_or(1),
            String::from_utf8_lossy(&output.stderr).trim()
        ))),
        Err(error) => Err(DatasetError::fetch(format!("cannot run unzip: {error}"))),
    }
}

/// Sync the Overture divisions of `release` with `s5cmd`.
///
/// # Errors
///
/// Fails with the install hint when `s5cmd` is absent, and on its failure.
pub fn overture(release: &str, data_root: &Path) -> Result<()> {
    let dest = data_root
        .join("overture")
        .join(release)
        .join("theme=divisions/type=division_area");
    fs::create_dir_all(&dest).io_at(IoOp::Create, &dest)?;
    let source = format!(
        "s3://overturemaps-us-west-2/release/{release}/theme=divisions/type=division_area/*"
    );
    let output = Command::new("s5cmd")
        .args(["--no-sign-request", "sync", &source])
        .arg(&dest)
        .output();
    match output {
        Ok(output) if output.status.success() => Ok(()),
        Ok(output) => Err(DatasetError::fetch(format!(
            "s5cmd sync failed (exit {}): {}",
            output.status.code().unwrap_or(1),
            String::from_utf8_lossy(&output.stderr).trim()
        ))),
        Err(error) => Err(DatasetError::fetch(format!(
            "cannot run s5cmd: {error} (brew install s5cmd)"
        ))),
    }
}

/// Fetch both CHIRPS listings and write the three lists of `s`; returns the
/// `lists` directory. `quiet` keeps the verb's report off stdout, for the
/// refresh, whose own log is the transcript.
///
/// # Errors
///
/// Fails when no host serves a listing, the season start is unreadable, or a
/// list cannot be written.
pub fn source_lists(s: &Settings, quiet: bool) -> Result<PathBuf> {
    let lists = fetch_listings(s)?;
    let season_start = season_start(s)?;
    let final_listing = lists.join("listing-final.html");
    let prelim_listing = lists.join("listing-prelim.html");
    if quiet {
        write_lists_quiet(
            &final_listing,
            &prelim_listing,
            &season_start,
            &s.baseline,
            &lists,
        )?;
    } else {
        write_lists(
            &final_listing,
            &prelim_listing,
            &season_start,
            &s.baseline,
            &lists,
        )?;
    }
    Ok(lists)
}

/// Run `geolith dataset fetch`.
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a usage error, `3` on a boundary sha mismatch
/// or when the NDVI clip has no GDAL, and when a download fails.
pub fn run(args: &FetchArgs) -> Result<()> {
    let s = layout::settings(args.dataset.as_deref(), Some(args.country.as_str()))?;
    if args.boundaries {
        boundaries(&s)?;
        return Ok(());
    }
    if s.dataset == "ndvi" {
        return ndvi(args, &s);
    }
    if args.mode.is_some() {
        return Err(DatasetError::Exit(Exit(2)));
    }
    if s.dataset == "ndvi" {
        return ndvi(args, &s);
    }
    let lists = source_lists(&s, false)?;
    let src = s.data_root.join("datasets").join(&s.dataset).join("src");
    let mut failed = false;
    for name in if args.baseline {
        vec!["series.txt", "season.txt", "baseline.txt"]
    } else {
        vec!["series.txt", "season.txt"]
    } {
        if chirps(&lists.join(name), &src).is_err() {
            failed = true;
        }
    }
    if let Some(config) = s.country_config()
        && config.boundaries.source == BoundarySource::Overture
        && !s
            .data_root
            .join("overture")
            .join(&s.boundary_release)
            .is_dir()
    {
        overture(&s.boundary_release, &s.data_root)?;
    }
    if failed {
        return Err(Exit(1).into());
    }
    Ok(())
}

/// Fetch the NDVI dekads of the series list, clipped to the country's window
/// (`mode` `clip`) or whole (`mode` `full`).
///
/// # Errors
///
/// Fails with [`Exit`] `2` on a bad mode, `3` when the clip has no GDAL, and
/// when a list or a download fails.
fn ndvi(args: &FetchArgs, s: &Settings) -> Result<()> {
    let mode = args.mode.as_deref().unwrap_or("clip");
    if !matches!(mode, "clip" | "full") {
        return Err(DatasetError::Exit(Exit(2)));
    }
    if args.baseline {
        return crate::baseline::run(&crate::cli::BaselinePassArgs {
            mode: args.mode.clone(),
            country: args.country.clone(),
            dataset: args.dataset.clone(),
            min_free_gb: None,
        });
    }
    let list = crate::cdse::source_lists(s, false)?.join("series.txt");
    let src = s
        .data_root
        .join("datasets")
        .join(&s.dataset)
        .join("src")
        .join(&s.cc)
        .join("final");
    if mode == "full" {
        return crate::cdse::download_full(&list, &src);
    }
    // The window needs the areas, and an Overture source needs the divisions.
    let country = s.country_config();
    if let Some(config) = &country
        && config.boundaries.source == BoundarySource::Overture
        && !s
            .data_root
            .join("overture")
            .join(&s.boundary_release)
            .is_dir()
    {
        overture(&s.boundary_release, &s.data_root)?;
    }
    let areas = crate::run::ensure_areas(s)?.join("areas.geojson");
    let outline = country
        .as_ref()
        .filter(|config| config.boundaries.holds_soi_land)
        .map(|_| s.data_root.join("india/india-composite.geojson"));
    let window = crate::cdse::window(
        &areas,
        outline.as_deref(),
        &s.cc.to_uppercase(),
        crate::cdse::NDVI_GRID,
        512,
    )?;
    println!("window {} {} {} {}", window.0, window.1, window.2, window.3);
    crate::cdse::probe(&list, window)?;
    crate::cdse::download_clip(&list, &src, window)
}

/// The config's season start, a pentad start.
fn season_start(s: &Settings) -> Result<String> {
    read_json(&s.config_path)?
        .get("season_start")
        .and_then(serde_json::Value::as_str)
        .map(str::to_owned)
        .ok_or_else(|| {
            DatasetError::fetch(format!("{} has no season_start", s.config_path.display()))
        })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufRead as _, BufReader};
    use std::net::{TcpListener, TcpStream};

    /// A tiny HTTP/1.1 server with one object and Range support.
    fn serve(body: Vec<u8>, seen: std::sync::Arc<std::sync::Mutex<Vec<String>>>) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
        let address = listener.local_addr().expect("address").to_string();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(stream) = stream else { continue };
                let body = body.clone();
                let seen = std::sync::Arc::clone(&seen);
                std::thread::spawn(move || {
                    let _ = answer(stream, &body, &seen);
                });
            }
        });
        address
    }

    fn answer(
        mut stream: TcpStream,
        body: &[u8],
        seen: &std::sync::Arc<std::sync::Mutex<Vec<String>>>,
    ) -> std::io::Result<()> {
        let mut reader = BufReader::new(stream.try_clone()?);
        let mut line = String::new();
        reader.read_line(&mut line)?;
        let mut method = line.split_whitespace();
        let verb = method.next().unwrap_or_default().to_owned();
        let mut range: Option<String> = None;
        loop {
            let mut header = String::new();
            reader.read_line(&mut header)?;
            if header.trim().is_empty() {
                break;
            }
            if let Some(value) = header
                .to_ascii_lowercase()
                .strip_prefix("range:")
                .map(str::trim)
                .map(str::to_owned)
            {
                seen.lock().expect("seen").push(value.clone());
                range = Some(value);
            }
        }
        let (status, slice) = match range {
            Some(range) => {
                let from = range
                    .trim_start_matches("bytes=")
                    .split('-')
                    .next()
                    .and_then(|value| value.parse::<usize>().ok())
                    .unwrap_or(0);
                ("206 Partial Content", &body[from.min(body.len())..])
            }
            None => ("200 OK", body),
        };
        if verb == "HEAD" {
            let head = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );
            stream.write_all(head.as_bytes())?;
            return stream.flush();
        }
        let head = format!(
            "HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
            slice.len()
        );
        stream.write_all(head.as_bytes())?;
        stream.write_all(slice)?;
        stream.flush()
    }

    /// A body that starts like a little-endian TIFF (`II*\0`), as every CHIRPS
    /// raster does, then counts.
    fn one_file(size: usize) -> Vec<u8> {
        let mut bytes = vec![0_u8; size];
        for (index, byte) in bytes.iter_mut().enumerate() {
            *byte = u8::try_from(index % 251).unwrap_or_default();
        }
        bytes[..4].copy_from_slice(b"II*\0");
        bytes
    }

    #[test]
    fn the_default_hosts_are_https_only() {
        for host in hosts().expect("the default hosts") {
            assert!(host.starts_with("https://"), "{host}");
        }
    }

    #[test]
    fn a_configured_http_host_is_refused() {
        let error = checked_hosts(&[
            "https://a.example.test".into(),
            "http://b.example.test".into(),
        ])
        .expect_err("a cleartext host");
        assert!(
            error.to_string().contains("http://b.example.test"),
            "{error}"
        );
        assert_eq!(
            checked_hosts(&["https://a.example.test".into()]).expect("https"),
            vec!["https://a.example.test".to_owned()]
        );
        assert_eq!(
            checked_hosts(&[]).expect("default"),
            vec!["https://data.chc.ucsb.edu".to_owned()]
        );
    }

    /// With `https_only`, a request to an `http` URL fails before any bytes
    /// go out, so a redirect to cleartext cannot be followed either.
    #[test]
    fn the_download_agent_refuses_cleartext() {
        let address = serve(one_file(100), std::sync::Arc::default());
        let agent = agent(true).expect("agent");
        assert!(agent.get(&format!("http://{address}/file")).call().is_err());
    }

    /// The first bytes of a TIFF are the structural check: an error page, a
    /// truncated listing or a redirect body of the right length is not a raster.
    #[test]
    fn a_download_that_is_not_a_tiff_is_discarded() {
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = vec![b'<'; 400];
        let address = serve(body, std::sync::Arc::clone(&seen));
        let dir = tempfile::tempdir().expect("a temp dir");
        let dest = dir.path().join("chirps.cog");
        let agent = agent(false).expect("agent");
        let result = fetch_one(&agent, &[format!("http://{address}")], "/file", &dest);
        assert!(result.is_err(), "an HTML body is not a raster");
        assert!(!dest.exists());
        assert!(!dest.with_extension("part").exists());
    }

    #[test]
    fn a_file_with_a_tiff_header_is_accepted_in_every_byte_order() {
        for magic in [&b"II*\0"[..], b"MM\0*", b"II+\0", b"MM\0+"] {
            let mut body = vec![1_u8; 300];
            body[..4].copy_from_slice(magic);
            let address = serve(body.clone(), std::sync::Arc::default());
            let dir = tempfile::tempdir().expect("a temp dir");
            let dest = dir.path().join("chirps.tif");
            let agent = agent(false).expect("agent");
            fetch_one(&agent, &[format!("http://{address}")], "/file", &dest)
                .unwrap_or_else(|e| panic!("{magic:?}: {e}"));
            assert_eq!(fs::read(&dest).expect("read"), body);
        }
    }

    #[test]
    fn a_partial_file_is_resumed_from_its_length() {
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = one_file(1000);
        let address = serve(body.clone(), std::sync::Arc::clone(&seen));
        let dir = tempfile::tempdir().expect("a temp dir");
        let dest = dir.path().join("src/final/chirps.cog");
        fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir");
        fs::write(dest.with_extension("part"), &body[..400]).expect("write");
        let agent = agent(false).expect("agent");
        let url = format!("http://{address}/file");
        let start = file_size(&dest.with_extension("part"));
        let bytes = get_from(&agent, &url, start).expect("resume");
        let mut file = fs::OpenOptions::new()
            .append(true)
            .open(dest.with_extension("part"))
            .expect("open");
        file.write_all(&bytes).expect("write");
        drop(file);
        assert_eq!(fs::read(dest.with_extension("part")).expect("read"), body);
        assert_eq!(seen.lock().expect("seen").as_slice(), ["bytes=400-"]);
    }

    #[test]
    fn a_part_longer_than_the_remote_is_discarded() {
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = one_file(500);
        let address = serve(body.clone(), std::sync::Arc::clone(&seen));
        let dir = tempfile::tempdir().expect("a temp dir");
        let dest = dir.path().join("chirps.cog");
        fs::write(dest.with_extension("part"), vec![9_u8; 900]).expect("write");
        let agent = agent(false).expect("agent");
        fetch_one(&agent, &[format!("http://{address}")], "/file", &dest).expect("fetch");
        assert_eq!(fs::read(&dest).expect("read"), body);
        assert!(!dest.with_extension("part").exists());
    }

    #[test]
    fn a_file_of_the_remote_size_is_skipped() {
        let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let body = one_file(321);
        let address = serve(body.clone(), std::sync::Arc::clone(&seen));
        let dir = tempfile::tempdir().expect("a temp dir");
        let dest = dir.path().join("chirps.cog");
        fs::write(&dest, &body).expect("write");
        let agent = agent(false).expect("agent");
        fetch_one(&agent, &[format!("http://{address}")], "/file", &dest).expect("fetch");
        // A skip asks for the size and fetches no body, so no range is seen.
        assert!(seen.lock().expect("seen").is_empty());
    }

    #[test]
    fn a_malformed_list_line_is_named_and_fails() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let list = dir.path().join("series.txt");
        fs::write(&list, "midday /somewhere/x.cog\n").expect("write");
        let err = chirps(&list, &dir.path().join("src")).expect_err("a failure");
        let exit = err.exit();
        assert_eq!(exit, Some(Exit(1)));
    }
}