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
//! `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 anyhow::{Context, Result, bail};

use crate::cli::PublishArgs;
use crate::layout::{
    Settings, StageFile, current_key, hex, layout_key_refusal, read_json, settings, utc_now,
};
use crate::s3::sigv4::Credentials;
use crate::s3::{PutOutcome, S3, md5_of};
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 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 => bail!(
                "{} 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);
                if facts.md5 != Some(md5_of(&local)?) {
                    bail!(
                        "{} is in {} with other bytes of the same size: 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() {
        bail!("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}");
        }
        bail!("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) => bail!("{refusal}"),
            }
        } 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() {
        bail!("{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() {
            bail!("{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) {
            bail!(
                "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() {
        bail!(
            "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) {
        bail!("{refusal}");
    }
    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).with_context(|| {
                format!("{key} is not JSON: unreadable pointer: fix it by hand")
            })?;
            Some(parse_pointer(&value).with_context(|| {
                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))
    {
        bail!(
            "{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).with_context(|| format!("reading {}", local.display()))?;
    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 the md5 of the
/// large files. 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) => {
                if large(&file.key) {
                    let local = crate::s3::md5_of(&stage.dir.join(&file.key))?;
                    if facts.md5 != Some(local) {
                        failures.push(format!(
                            "{}: md5 {} in the bucket, {} staged",
                            file.key,
                            facts.md5.map_or_else(|| "none".to_owned(), |md5| hex(&md5)),
                            hex(&local)
                        ));
                        continue;
                    }
                }
            }
        }
        checked += 1;
    }
    if !failures.is_empty() {
        for failure in &failures {
            eprintln!("remote: {failure}");
        }
        bail!(
            "{} 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).context("serializing a marker")?;
    text.push('\n');
    let partial = path.with_extension("partial");
    fs::write(&partial, text).with_context(|| format!("writing {}", partial.display()))?;
    fs::rename(&partial, path).with_context(|| format!("renaming to {}", path.display()))
}

#[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/")
    }

    #[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:?}");
    }
}