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
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
//! `geolith dataset upload` and `publish`: the two owner-run gates.
//!
//! The guards run first, before any network call and also under
//! `--dry-run`: the bucket must be `storage.bucket`, the endpoint's host must
//! belong to `storage.account_id` when one is set, and every key must be a
//! dated key of the layout under `storage.prefix` (`publish` writes the one
//! pointer key). The store, its keys and the prefix come from the deployment
//! settings ([`crate::settings`]); the credentials come from the
//! environment or a mode-600 file, never from an argument and never printed.

use std::fs;
use std::path::Path;

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

use crate::cli::PublishArgs;
use crate::layout::{
    Settings, StageFile, current_key, layout_key_refusal, read_json, settings, utc_now,
};
use crate::s3::sigv4::Credentials;
use crate::s3::{PutOutcome, S3, Verdict, compare_object};
use crate::settings::{self as deployment, Target};
use crate::stage::{parse_pointer, public_objects, read_stage, staged_pointer};

/// A client of the target's bucket. `bucket` (the `--bucket` flag) may only
/// confirm it: any other bucket is refused.
///
/// # Errors
///
/// Fails when the flag names another bucket or the endpoint is not a URL.
pub fn client_of(target: &Target, credentials: Credentials, bucket: Option<&str>) -> Result<S3> {
    if let Some(name) = bucket {
        target.check_bucket(name)?;
    }
    S3::new(
        &target.endpoint,
        &target.region,
        &target.bucket,
        credentials,
    )
}

/// A client of the configured store.
///
/// # Errors
///
/// Fails naming the setting that is missing, when a guard refuses the target
/// or the flag's bucket, or when the credentials are missing or readable by
/// others.
pub fn connect(bucket: Option<&str>) -> Result<S3> {
    let current = deployment::current();
    let target = current.target()?;
    if let Some(name) = bucket {
        target.check_bucket(name)?;
    }
    client_of(&target, current.storage_credentials()?, bucket)
}

/// The sha256 a stage file records, as bytes.
fn digest_of(file: &StageFile) -> Result<[u8; 32]> {
    let text = file.sha256.as_str();
    let mut out = [0_u8; 32];
    if text.len() != 64 {
        return Err(DatasetError::stage(format!(
            "{} has no sha256 in stage.json",
            file.key
        )));
    }
    for (index, pair) in text.as_bytes().chunks(2).enumerate() {
        out[index] = std::str::from_utf8(pair)
            .ok()
            .and_then(|digits| u8::from_str_radix(digits, 16).ok())
            .ok_or_else(|| {
                DatasetError::stage(format!("{} has a bad sha256 in stage.json", file.key))
            })?;
    }
    Ok(out)
}

/// The plan of an upload: which keys are copied and which are skipped.
///
/// # Errors
///
/// Fails when a key is there with other bytes: nothing is written then.
pub fn upload_plan(s: &Settings, id: &str, client: &S3) -> Result<(Vec<StageFile>, Vec<bool>)> {
    let stage = read_stage(s, id)?;
    let objects = public_objects(s, &stage, id)?.to_vec();
    let mut copy = Vec::with_capacity(objects.len());
    for file in &objects {
        match client.head(&file.key)? {
            Some(facts) if facts.bytes != file.bytes => {
                return Err(DatasetError::stage(format!(
                    "{} is in {} with {} bytes, the stage has {}: never overwritten",
                    file.key,
                    client.bucket(),
                    facts.bytes,
                    file.bytes
                )));
            }
            Some(facts) => {
                let local = stage.dir.join(&file.key);
                match compare_object(&facts, &local, file.bytes, &digest_of(file)?)? {
                    Verdict::Same => {}
                    Verdict::Different(how) => {
                        return Err(DatasetError::stage(format!(
                            "{} is in {} {how}: never overwritten",
                            file.key,
                            client.bucket()
                        )));
                    }
                    Verdict::Unverifiable(why) => {
                        return Err(DatasetError::stage(format!(
                            "{} is in {} and its bytes cannot be verified ({why}): \
                             never overwritten",
                            file.key,
                            client.bucket()
                        )));
                    }
                }
                copy.push(false);
            }
            None => copy.push(true),
        }
    }
    Ok((objects, copy))
}

/// Upload `id` through `client`; `dry_run` writes nothing.
///
/// # Errors
///
/// Fails when `verify` fails, a key conflicts, or a write fails.
fn run_upload(s: &Settings, client: &S3, build_id: &str, dry_run: bool) -> Result<()> {
    let dir = s.stage_root.join(build_id);
    if !dir.join("stage.json").is_file() {
        return Err(DatasetError::stage(format!(
            "no complete stage {build_id} in {}",
            s.stage_root.display()
        )));
    }
    let report = crate::verify::check(&dir, s)?;
    if !report.failures.is_empty() {
        for failure in &report.failures {
            println!("VERIFY FAIL {failure}");
        }
        return Err(DatasetError::stage(format!(
            "verify failed on {build_id}: nothing uploaded"
        )));
    }
    copy_upload(s, client, build_id, dry_run)
}

/// The copy half of an upload, after `verify` has passed.
///
/// # Errors
///
/// Fails when a key conflicts, a write fails, or a marker cannot be written.
fn copy_upload(s: &Settings, client: &S3, build_id: &str, dry_run: bool) -> Result<()> {
    let (objects, copy) = upload_plan(s, build_id, client)?;
    let total: u64 = objects.iter().map(|file| file.bytes).sum();
    if dry_run {
        for (file, copy) in objects.iter().zip(&copy) {
            println!("PLAN {} {}", if *copy { "copy" } else { "skip" }, file.key);
        }
        return Ok(());
    }
    let stage = read_stage(s, build_id)?;
    for (file, copy) in objects.iter().zip(&copy) {
        if *copy {
            match client.put_new(&file.key, &stage.dir.join(&file.key))? {
                PutOutcome::Copied { .. } => println!("COPY {}", file.key),
                PutOutcome::Skipped => println!("SKIP {}", file.key),
                PutOutcome::Refused(refusal) => {
                    return Err(DatasetError::stage(refusal.to_string()));
                }
            }
        } else {
            println!("SKIP {}", file.key);
        }
    }
    write_marker(
        &stage.dir.join("uploaded.json"),
        &serde_json::json!({
            "build_id": build_id,
            "remote": "r2",
            "bucket": client.bucket(),
            "objects": objects.len(),
            "bytes": total,
            "finished_at": utc_now(),
        }),
    )?;
    println!(
        "UPLOAD OK {build_id} {} objects {total} bytes",
        objects.len()
    );
    Ok(())
}

/// Publish `id` through `client`; `dry_run` writes nothing.
///
/// # Errors
///
/// Fails when the stage was not uploaded, a key is missing remotely, the
/// pointer would go backwards, or a write fails.
fn run_publish(s: &Settings, client: &S3, args: &PublishArgs) -> Result<()> {
    let build_id = args.build_id.as_str();
    let stage = read_stage(s, build_id)?;
    if !stage.dir.join("uploaded.json").is_file() {
        return Err(DatasetError::stage(format!(
            "{build_id} has no uploaded.json: run `geolith dataset upload {build_id}` first"
        )));
    }
    if args.rollback {
        let marker = stage.dir.join("published.json");
        if !marker.is_file() {
            return Err(DatasetError::stage(format!(
                "{build_id} was never published: --rollback returns to a live build only"
            )));
        }
        let was = read_json(&marker)?;
        if was.get("build_id").and_then(serde_json::Value::as_str) != Some(build_id) {
            return Err(DatasetError::stage(format!(
                "published.json of {build_id} names {}: --rollback returns to a live build only",
                was.get("build_id")
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("none")
            )));
        }
    }
    let next = staged_pointer(s, &stage, build_id)?;
    let objects = public_objects(s, &stage, build_id)?;
    let mut missing = Vec::new();
    for file in objects {
        if client.head(&file.key)?.map(|facts| facts.bytes) != Some(file.bytes) {
            missing.push(file.key.clone());
        }
    }
    if !missing.is_empty() {
        return Err(DatasetError::stage(format!(
            "not in {} with the staged bytes: {}",
            client.bucket(),
            missing.join(", ")
        )));
    }
    let key = current_key(s);
    if let Some(refusal) = layout_key_refusal(&s.key_root, &key, true) {
        return Err(DatasetError::stage(refusal.to_string()));
    }
    let local = stage.dir.join(&key);
    let previous = match client.head(&key)? {
        Some(_) => {
            let text = client.get(&key)?;
            let value: serde_json::Value = serde_json::from_slice(&text).json_of(format!(
                "{key} is not JSON: unreadable pointer: fix it by hand"
            ))?;
            Some(parse_pointer(&value).within({
                format!(
                    "{key} lacks a period_end or a build_id: unreadable pointer: fix it by hand"
                )
            })?)
        }
        None => None,
    };
    if let Some(previous) = &previous
        && !args.rollback
        && (previous.period_end > next.period_end
            || (previous.period_end == next.period_end && previous.build_id.as_str() > build_id))
    {
        return Err(DatasetError::stage(format!(
            "{key} points at {} (period_end {}), newer than {build_id} (period_end {})",
            previous.build_id, previous.period_end, next.period_end
        )));
    }
    if args.dry_run {
        println!("PLAN publish {key} {build_id}");
        return Ok(());
    }
    let bytes = fs::read(&local).io_at(IoOp::Read, &local)?;
    client.put_overwrite(&key, &bytes)?;
    write_marker(
        &stage.dir.join("published.json"),
        &serde_json::json!({
            "build_id": build_id,
            "remote": "r2",
            "bucket": client.bucket(),
            "key": key,
            "previous_build_id": previous.map(|previous| previous.build_id),
            "finished_at": utc_now(),
        }),
    )?;
    println!("PUBLISH OK {build_id}");
    Ok(())
}

/// Check every staged key of `id` in the bucket: its size, and its bytes. A
/// key that carries the `x-amz-meta-sha256` of its upload is checked against
/// the digest in `stage.json`; a large key without it is compared with the
/// staged file ([`compare_object`]: never by reading an `ETag` as an md5 when
/// it is a multipart one). Returns the number of keys checked.
///
/// # Errors
///
/// Fails when the stage cannot be read, a key is missing or differs, or a
/// remote read fails.
pub fn check_remote(s: &Settings, id: &str, client: &S3) -> Result<usize> {
    let stage = read_stage(s, id)?;
    let objects = public_objects(s, &stage, id)?.to_vec();
    let large = |key: &str| {
        key.ends_with("tiles.pmtiles")
            || key.ends_with("areas.pmtiles")
            || key.ends_with("numbers.parquet")
            || key.ends_with("areas.parquet")
    };
    let mut failures: Vec<String> = Vec::new();
    let mut checked = 0_usize;
    for file in &objects {
        if file.key.ends_with("current.json") {
            continue;
        }
        match client.head(&file.key)? {
            None => {
                failures.push(format!("{}: not in {}", file.key, client.bucket()));
                continue;
            }
            Some(facts) if facts.bytes != file.bytes => {
                failures.push(format!(
                    "{}: {} bytes in the bucket, {} staged",
                    file.key, facts.bytes, file.bytes
                ));
                continue;
            }
            Some(facts) => {
                let wrong = if facts.sha256.is_some() || large(&file.key) {
                    match compare_object(
                        &facts,
                        &stage.dir.join(&file.key),
                        file.bytes,
                        &digest_of(file)?,
                    )? {
                        Verdict::Same => None,
                        Verdict::Different(how) => Some(format!("bytes differ ({how})")),
                        Verdict::Unverifiable(why) => Some(format!("cannot be verified ({why})")),
                    }
                } else {
                    None
                };
                if let Some(wrong) = wrong {
                    failures.push(format!("{}: {wrong}", file.key));
                    continue;
                }
            }
        }
        checked += 1;
    }
    if !failures.is_empty() {
        for failure in &failures {
            eprintln!("remote: {failure}");
        }
        return Err(DatasetError::stage(format!(
            "{} of {} keys differ in the bucket",
            failures.len(),
            objects.len()
        )));
    }
    Ok(checked)
}

/// Run `geolith dataset upload`.
///
/// # Errors
///
/// Fails when a setting of the store is missing, a guard, the credentials,
/// `verify`, a remote read or a write fails.
pub fn upload(args: &crate::cli::UploadArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let client = connect(args.bucket.as_deref())?;
    run_upload(&s, &client, &args.build_id, args.dry_run)
}

/// Run `geolith dataset publish`, or its `--rollback`.
///
/// # Errors
///
/// Fails when a setting of the store is missing, a guard, the credentials or
/// `run_publish` fails.
pub fn publish(args: &PublishArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let client = connect(args.bucket.as_deref())?;
    run_publish(&s, &client, args)
}

/// Write the JSON at `path` through `<name>.partial` and a rename.
fn write_marker(path: &Path, value: &serde_json::Value) -> Result<()> {
    let mut text = serde_json::to_string_pretty(value).json_of("serializing a marker")?;
    text.push('\n');
    let partial = path.with_extension("partial");
    fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
    fs::rename(&partial, path).io_at(IoOp::RenameTo, path)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::{Settings, sha256_hex};
    use crate::s3::fake::FakeS3;

    /// A made-up store target.
    fn target() -> Target {
        Target {
            endpoint: "http://127.0.0.1:9".to_owned(),
            region: "eu-test-1".to_owned(),
            bucket: "made-up-bucket".to_owned(),
            key_root: "mirror/ds/".to_owned(),
        }
    }

    fn credentials() -> Credentials {
        Credentials {
            key_id: "AKIAIOSFODNN7EXAMPLE".to_owned(),
            secret: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_owned(),
        }
    }

    #[test]
    fn a_flag_naming_another_bucket_is_refused_before_a_client_exists() {
        let error = client_of(&target(), credentials(), Some("other-bucket"))
            .unwrap_err()
            .to_string();
        assert!(error.contains("bucket \"other-bucket\" refused"), "{error}");
        assert!(error.contains("made-up-bucket"), "{error}");
        let client = client_of(&target(), credentials(), Some("made-up-bucket")).expect("client");
        assert_eq!(client.bucket(), "made-up-bucket");
        let client = client_of(&target(), credentials(), None).expect("client");
        assert_eq!(client.host(), "127.0.0.1:9");
    }

    /// A stage of one build dir (two files and a pointer) under `root`, its
    /// keys under `key_root`.
    fn staged_in(root: &Path, key_root: &str) -> (Settings, String) {
        let id = "2026-11-20.20261120T0000Z";
        let s = Settings {
            dataset: "rainfall".to_owned(),
            cc: "in".to_owned(),
            data_root: root.join("data"),
            repo: root.join("repo"),
            key_root: key_root.to_owned(),
            boundary_release: "2026-10-21.0".to_owned(),
            boundary_tiles_revision: 2,
            baseline: "1991-2020".to_owned(),
            config_path: root.join("repo/packages/dataset-builder/data/datasets/rainfall.json"),
            country_config_path: root
                .join("repo/packages/dataset-builder/data/datasets/countries/in.json"),
            published_csv: root
                .join("repo/packages/dataset-builder/data/datasets/in/published.csv"),
            stage_root: root.join("data/datasets/stage"),
        };
        let dir = s.stage_root.join(id);
        let pointer_key = format!("{key_root}rainfall/in/current.json");
        let base = format!("{key_root}rainfall/in/{id}");
        std::fs::create_dir_all(dir.join(&base)).expect("mkdir");
        std::fs::write(
            dir.join(&base).join("index.json"),
            b"{\"attribution\":\"x\"}",
        )
        .expect("write");
        std::fs::write(
            dir.join(&base).join("numbers.csv"),
            b"id,attribution\na,x\n",
        )
        .expect("write");
        std::fs::write(
            dir.join(&pointer_key),
            format!(r#"{{"build_id":"{id}","period_end":"2026-11-18"}}"#),
        )
        .expect("write");
        let entries: Vec<String> = [
            format!("{base}/index.json"),
            format!("{base}/numbers.csv"),
            pointer_key.clone(),
        ]
        .iter()
        .map(|key| {
            let path = dir.join(key);
            format!(
                r#"{{"key":"{key}","bytes":{},"sha256":"{}"}}"#,
                std::fs::metadata(&path).expect("metadata").len(),
                sha256_hex(&path).expect("digest")
            )
        })
        .collect();
        std::fs::write(
            dir.join("stage.json"),
            format!(
                r#"{{"build_id":"{id}","files":[{}],"staged_at":"2026-11-21T00:00:00Z"}}"#,
                entries.join(",")
            ),
        )
        .expect("write");
        (s, id.to_owned())
    }

    /// [`staged_in`] under the default prefix.
    fn staged(root: &Path) -> (Settings, String) {
        staged_in(root, "datasets/")
    }

    /// [`staged`] with a 33 MiB `tiles.pmtiles` besides, as a refresh stages
    /// the tiles of a build: large enough for a multipart upload.
    fn staged_with_a_large_file(root: &Path) -> (Settings, String) {
        let (s, id) = staged(root);
        let dir = s.stage_root.join(&id);
        let key = format!("datasets/rainfall/in/{id}/tiles.pmtiles");
        let bytes: Vec<u8> = (0..33 * 1024 * 1024)
            .map(|i: usize| (i as u8).wrapping_mul(7))
            .collect();
        std::fs::write(dir.join(&key), &bytes).expect("write");
        let manifest = std::fs::read_to_string(dir.join("stage.json")).expect("read");
        let entry = format!(
            r#"{{"key":"{key}","bytes":{},"sha256":"{}"}},"#,
            bytes.len(),
            sha256_hex(&dir.join(&key)).expect("digest")
        );
        std::fs::write(
            dir.join("stage.json"),
            manifest.replacen("\"files\":[", &format!("\"files\":[{entry}"), 1),
        )
        .expect("write");
        (s, id)
    }

    /// The refresh runs `upload`, `upload_plan` again and `check_remote`: all
    /// three must pass for an object that went up in parts, whose `ETag` is
    /// not an md5.
    #[test]
    fn a_large_object_passes_the_plan_and_the_remote_check_after_its_upload() {
        let fake = FakeS3::start();
        let client = fake.client();
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged_with_a_large_file(dir.path());
        copy_upload(&s, &client, &id, false).expect("upload");
        assert!(
            fake.multipart_parts_seen() > 1,
            "the large file went up in parts"
        );
        let (objects, copy) = upload_plan(&s, &id, &client).expect("a second plan");
        assert!(
            copy.iter().all(|copy| !copy),
            "nothing is left to copy: {objects:?}"
        );
        let checked = check_remote(&s, &id, &client).expect("the remote check");
        assert_eq!(
            checked,
            objects.len(),
            "every staged key: index, numbers, tiles"
        );
        assert_eq!(checked, 3);
    }

    #[test]
    fn the_remote_check_fails_when_a_large_object_has_other_bytes() {
        let fake = FakeS3::start();
        let client = fake.client();
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged_with_a_large_file(dir.path());
        copy_upload(&s, &client, &id, false).expect("upload");
        let key = format!("datasets/rainfall/in/{id}/tiles.pmtiles");
        let mut other: Vec<u8> = fake.objects().get(&key).expect("object").clone();
        other[1000] ^= 0xff;
        fake.plant(&key, &other, Some(8 * 1024 * 1024));
        let error = check_remote(&s, &id, &client).unwrap_err().to_string();
        assert!(error.contains("differ"), "{error}");
    }

    #[test]
    fn a_dry_run_plan_copies_every_key_and_writes_nothing() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged(dir.path());
        let fake = FakeS3::start();
        let client = fake.client();
        copy_upload(&s, &client, &id, true).expect("plan");
        assert!(fake.writes().is_empty());
        assert!(fake.objects().is_empty());
        assert!(!s.stage_root.join(&id).join("uploaded.json").exists());
    }

    #[test]
    fn an_upload_writes_every_key_except_the_pointer_and_marks_the_stage() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged(dir.path());
        let fake = FakeS3::start();
        let client = fake.client();
        copy_upload(&s, &client, &id, false).expect("upload");
        let objects = fake.objects();
        let base = format!("datasets/rainfall/in/{id}");
        assert_eq!(objects.len(), 2);
        assert!(objects.contains_key(&format!("{base}/index.json")));
        assert!(objects.contains_key(&format!("{base}/numbers.csv")));
        assert!(!objects.contains_key("datasets/rainfall/in/current.json"));
        let marker = read_json(&s.stage_root.join(&id).join("uploaded.json")).expect("marker");
        assert_eq!(
            marker.get("objects").and_then(serde_json::Value::as_u64),
            Some(2)
        );
    }

    #[test]
    fn a_publish_needs_an_upload_and_then_moves_the_pointer() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged(dir.path());
        let fake = FakeS3::start();
        let client = fake.client();
        let args = PublishArgs {
            build_id: id.clone(),
            dry_run: false,
            bucket: None,
            rollback: false,
            dataset: None,
            country: None,
        };
        let error = run_publish(&s, &client, &args).unwrap_err().to_string();
        assert!(error.contains("has no uploaded.json"), "{error}");
        copy_upload(&s, &client, &id, false).expect("upload");
        run_publish(&s, &client, &args).expect("publish");
        assert!(
            fake.objects()
                .contains_key("datasets/rainfall/in/current.json")
        );
        let marker = read_json(&s.stage_root.join(&id).join("published.json")).expect("marker");
        assert_eq!(
            marker.get("build_id").and_then(serde_json::Value::as_str),
            Some(id.as_str())
        );
    }

    #[test]
    fn a_publish_refuses_a_newer_pointer_unless_it_rolls_back() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged(dir.path());
        let fake = FakeS3::start();
        let client = fake.client();
        copy_upload(&s, &client, &id, false).expect("upload");
        // A pointer at a later period, as another build would leave it.
        fake.client()
            .put_overwrite(
                "datasets/rainfall/in/current.json",
                br#"{"build_id":"2026-12-20.20261220T0000Z","period_end":"2026-12-18"}"#,
            )
            .expect("pointer");
        let args = PublishArgs {
            build_id: id.clone(),
            dry_run: false,
            bucket: None,
            rollback: false,
            dataset: None,
            country: None,
        };
        let error = run_publish(&s, &client, &args).unwrap_err().to_string();
        assert!(error.contains("newer than"), "{error}");
        // A rollback still needs this build to have been published before.
        let rollback = PublishArgs {
            rollback: true,
            ..args
        };
        let error = run_publish(&s, &client, &rollback).unwrap_err().to_string();
        assert!(error.contains("was never published"), "{error}");
    }

    #[test]
    fn a_made_up_deployment_reaches_the_fake_store_at_its_endpoint_bucket_and_prefix() {
        let fake = FakeS3::start_with_bucket("made-up-bucket");
        let json = format!(
            r#"{{"storage":{{"endpoint":"http://{}","region":"eu-test-1",
                "bucket":"made-up-bucket","prefix":"mirror/ds"}}}}"#,
            fake.address()
        );
        let env = |name: &str| match name {
            "GEOLITH_STORAGE_ACCESS_KEY_ID" => Some("AKIAIOSFODNN7EXAMPLE".to_owned()),
            "GEOLITH_STORAGE_SECRET_ACCESS_KEY" => {
                Some("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_owned())
            }
            _ => None,
        };
        let deployment =
            deployment::Deployment::resolve(None, Some(&json), &env).expect("a made-up config");
        let target = deployment.target().expect("target");
        let client = client_of(
            &target,
            deployment.storage_credentials().expect("credentials"),
            None,
        )
        .expect("client");
        let dir = tempfile::tempdir().expect("a temp dir");
        let (s, id) = staged_in(dir.path(), deployment.key_root());
        copy_upload(&s, &client, &id, false).expect("upload");

        let objects = fake.objects();
        let base = format!("mirror/ds/rainfall/in/{id}");
        let mut keys: Vec<&str> = objects.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            vec![
                format!("{base}/index.json").as_str(),
                format!("{base}/numbers.csv").as_str()
            ]
        );
        let requests = fake.requests();
        assert!(!requests.is_empty());
        for (method, target) in &requests {
            assert!(
                target.starts_with("/made-up-bucket/mirror/ds/rainfall/in/"),
                "{method} {target}"
            );
        }
        let puts = fake.writes();
        assert_eq!(puts.len(), 2, "{puts:?}");
    }
}