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
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
//! An `S3` client for the bucket the datasets live in (any S3-compatible store).
//!
//! Plain `ureq` over a hand-written [`sigv4`] signer: `HEAD`, `GET`,
//! `GET` with a range, a single `PUT` streamed from a file, multipart above
//! 32 MiB, and a prefix listing. Retries cover 5xx and 429 only; a `4xx` is
//! the answer. Every read of a remote object goes through [`ObjectFacts`] so
//! a caller never branches on how the object got there.
//!
//! An `ETag` is not an md5 for an object that went up in parts: it is the md5
//! of the part md5s and `-<parts>` (R2 documents this). Bytes are compared
//! through [`compare_object`]: the `x-amz-meta-sha256` the uploader writes on
//! every object, else an md5 `ETag`, else a multipart `ETag` rebuilt from the
//! file for the part sizes that fit; an object none of these can vouch for is
//! never trusted.

pub mod sigv4;

#[cfg(test)]
pub mod fake;

use std::collections::BTreeMap;
use std::fs::File;
use std::io::{Read as _, Seek as _, SeekFrom};
use std::path::Path;
use std::time::Duration;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, NumberResultExt as _, Result, WithinExt as _,
};
use md5::{Digest as _, Md5};
use rayon::prelude::*;

use sigv4::{Credentials, SignableRequest, amz_date, empty_payload_sha256, sha256, sign};

/// Objects at least this large take the multipart path.
pub const MULTIPART_THRESHOLD: u64 = 32 * 1024 * 1024;

/// Size of one multipart part.
pub const PART_SIZE: usize = 8 * 1024 * 1024;

/// How many parts are in flight at once.
const PART_CONCURRENCY: usize = 4;

/// Attempts per request on a 5xx or 429.
const ATTEMPTS: u32 = 3;

/// What a `HEAD` says about an object.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObjectFacts {
    /// Content length in bytes.
    pub bytes: u64,
    /// `md5` from the `ETag`, when the object is a single part.
    pub md5: Option<[u8; 16]>,
    /// The md5 of the part md5s and the part count from the `ETag`, when the
    /// object went up in parts.
    pub multipart: Option<([u8; 16], u32)>,
    /// `sha256` metadata, when the upload wrote one.
    pub sha256: Option<[u8; 32]>,
}

/// What a bucket's object says about its bytes next to a local file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Verdict {
    /// The same bytes.
    Same,
    /// Other bytes; the text says how it shows.
    Different(String),
    /// Nothing the bucket reports can vouch for the bytes either way.
    Unverifiable(String),
}

/// What `put_new` did.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PutOutcome {
    /// The object was absent and the file's bytes were written.
    Copied {
        /// Bytes written.
        bytes: u64,
    },
    /// The object is there, with the file's bytes.
    Skipped,
    /// The object is there with other bytes: never overwritten.
    Refused(String),
}

/// One response, its status kept.
#[derive(Debug)]
struct Response {
    status: u16,
    headers: Vec<(String, String)>,
    body: Vec<u8>,
}

/// The body of a request; a file is reopened on every attempt.
enum Body {
    /// No body.
    Empty,
    /// Bytes in memory.
    Bytes(Vec<u8>),
    /// A file, streamed.
    File(std::path::PathBuf),
}

/// An `S3` client of one bucket.
#[derive(Debug)]
pub struct S3 {
    agent: ureq::Agent,
    endpoint: String,
    host: String,
    region: String,
    bucket: String,
    credentials: Credentials,
}

impl S3 {
    /// A client of `bucket` at `endpoint` (`https://s3.example.com`, `http://127.0.0.1:9000`).
    ///
    /// # Errors
    ///
    /// Fails when the endpoint is not a URL.
    pub fn new(
        endpoint: &str,
        region: &str,
        bucket: &str,
        credentials: Credentials,
    ) -> Result<Self> {
        let rest = endpoint
            .split_once("://")
            .map_or(endpoint, |(_, rest)| rest);
        let host = rest.split('/').next().unwrap_or_default();
        if host.is_empty() {
            return Err(DatasetError::storage(format!(
                "endpoint {endpoint} is not a URL"
            )));
        }
        let agent: ureq::Agent = ureq::Agent::config_builder()
            .timeout_global(Some(Duration::from_secs(60)))
            .http_status_as_error(false)
            .build()
            .into();
        Ok(Self {
            agent,
            endpoint: endpoint.trim_end_matches('/').to_owned(),
            host: host.to_owned(),
            region: region.to_owned(),
            bucket: bucket.to_owned(),
            credentials,
        })
    }

    /// The bucket this client writes to.
    #[must_use]
    pub fn bucket(&self) -> &str {
        &self.bucket
    }

    /// The endpoint host, port included.
    #[must_use]
    pub fn host(&self) -> &str {
        &self.host
    }

    /// The URL of `key`.
    fn url(&self, key: &str) -> String {
        if key.is_empty() {
            format!("{}/{}", self.endpoint, self.bucket)
        } else {
            format!("{}/{}/{}", self.endpoint, self.bucket, key)
        }
    }

    /// The signed path of `key`.
    fn path(&self, key: &str) -> String {
        if key.is_empty() {
            format!("/{}", self.bucket)
        } else {
            format!("/{}/{}", self.bucket, key)
        }
    }

    /// Send one signed request, retrying 5xx and 429 with backoff.
    fn request(
        &self,
        method: &str,
        key: &str,
        query: Vec<(String, String)>,
        headers: Vec<(String, String)>,
        payload: &[u8; 32],
        body: &Body,
    ) -> Result<Response> {
        let mut attempt = 0;
        let mut delay = Duration::from_millis(500);
        loop {
            attempt += 1;
            match self.request_once(method, key, &query, &headers, payload, body) {
                Ok(response) if (500..600).contains(&response.status) || response.status == 429 => {
                    if attempt >= ATTEMPTS {
                        return Err(DatasetError::storage(format!(
                            "{method} {key} failed with {} after {attempt} attempts",
                            response.status
                        )));
                    }
                }
                Ok(response) => return Ok(response),
                Err(error) if attempt < ATTEMPTS => {
                    tracing::warn!(%error, method, key, "retrying the request");
                }
                Err(error) => return Err(error),
            }
            std::thread::sleep(delay);
            delay = delay.saturating_mul(2).min(Duration::from_secs(8));
        }
    }

    /// One attempt: sign, send, read the whole body.
    fn request_once(
        &self,
        method: &str,
        key: &str,
        query: &[(String, String)],
        headers: &[(String, String)],
        payload: &[u8; 32],
        body: &Body,
    ) -> Result<Response> {
        let request = SignableRequest {
            method,
            host: &self.host,
            path: &self.path(key),
            query: query.to_vec(),
            headers: headers.to_vec(),
            payload_sha256: *payload,
        };
        let signed = sign(&request, &self.credentials, &self.region, &amz_date(now()))?;
        let mut builder_url = self.url(key);
        if !query.is_empty() {
            builder_url.push('?');
            builder_url.push_str(&sigv4::canonical_query(query));
        }
        let url = builder_url;
        // A macro, because a body-less request builder and a body-carrying
        // one are different types.
        macro_rules! signed_headers {
            ($builder:expr) => {{
                let mut builder = $builder;
                for (name, value) in signed.iter().chain(headers.iter()) {
                    builder = builder.header(name.as_str(), value.as_str());
                }
                builder
            }};
        }
        let mut response = match (method, body) {
            ("GET", _) => signed_headers!(self.agent.get(&url)).call(),
            ("HEAD", _) => signed_headers!(self.agent.head(&url)).call(),
            ("DELETE", _) => signed_headers!(self.agent.delete(&url)).call(),
            ("PUT", Body::Empty) => signed_headers!(self.agent.put(&url)).send(()),
            ("POST", Body::Empty) => signed_headers!(self.agent.post(&url)).send(()),
            ("PUT", Body::Bytes(bytes)) => {
                signed_headers!(self.agent.put(&url)).send(bytes.as_slice())
            }
            ("POST", Body::Bytes(bytes)) => {
                signed_headers!(self.agent.post(&url)).send(bytes.as_slice())
            }
            ("PUT", Body::File(path)) => {
                let file = File::open(path).io_at(IoOp::Open, path)?;
                signed_headers!(self.agent.put(&url)).send(file)
            }
            (other, _) => {
                return Err(DatasetError::storage(format!(
                    "method {other} with this body is not supported"
                )));
            }
        }
        .within(format!("{method} {url}"))?;
        let status = response.status().as_u16();
        let headers: Vec<(String, String)> = response
            .headers()
            .iter()
            .map(|(name, value)| {
                (
                    name.as_str().to_ascii_lowercase(),
                    value.to_str().unwrap_or_default().to_owned(),
                )
            })
            .collect();
        // A HEAD has no body, and its `content-encoding` would make `ureq`
        // try to gunzip an empty stream.
        let body = if method == "HEAD" {
            Vec::new()
        } else {
            response
                .body_mut()
                .with_config()
                .limit(16 * 1024 * 1024)
                .read_to_vec()
                .within(format!("reading the body of {method} {url}"))?
        };
        Ok(Response {
            status,
            headers,
            body,
        })
    }

    /// What the bucket holds at `key`, or `None` when it holds nothing.
    ///
    /// # Errors
    ///
    /// Fails when the request fails with a status other than 404.
    pub fn head(&self, key: &str) -> Result<Option<ObjectFacts>> {
        let response = self.request(
            "HEAD",
            key,
            Vec::new(),
            Vec::new(),
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        match response.status {
            200 => match header(&response.headers, "content-length")
                .and_then(|text| text.parse::<u64>().ok())
            {
                Some(bytes) => {
                    let etag = header(&response.headers, "etag");
                    Ok(Some(ObjectFacts {
                        bytes,
                        md5: etag.and_then(etag_md5),
                        multipart: etag.and_then(etag_multipart),
                        sha256: header(&response.headers, "x-amz-meta-sha256")
                            .and_then(hex32::<32>),
                    }))
                }
                // Some object stores answer HEADs without a length: one byte of a ranged
                // GET carries the total in `content-range`.
                None => self.facts_from_range(key),
            },
            // 403 is not "absent": a token that cannot read cannot tell, and a
            // write on that guess could replace a dated key.
            404 => Ok(None),
            other => Err(DatasetError::storage(format!(
                "HEAD {key} failed with {other}"
            ))),
        }
    }

    /// The facts of `key` from a one-byte ranged `GET`.
    fn facts_from_range(&self, key: &str) -> Result<Option<ObjectFacts>> {
        let response = self.request(
            "GET",
            key,
            Vec::new(),
            vec![("range".to_owned(), "bytes=0-0".to_owned())],
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status == 404 {
            return Ok(None);
        }
        if response.status != 206 && response.status != 200 {
            return Err(DatasetError::storage(format!(
                "GET {key} range 0-0 failed with {}",
                response.status
            )));
        }
        let total = header(&response.headers, "content-range")
            .and_then(|value| value.rsplit('/').next())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| DatasetError::storage(format!("{key}: no content-range")))?;
        let etag = header(&response.headers, "etag");
        Ok(Some(ObjectFacts {
            bytes: total,
            md5: etag.and_then(etag_md5),
            multipart: etag.and_then(etag_multipart),
            sha256: None,
        }))
    }

    /// The bytes `start..=end` of `key`.
    ///
    /// # Errors
    ///
    /// Fails when the object is absent or the range is not served.
    pub fn get_range(&self, key: &str, start: u64, end: u64) -> Result<Vec<u8>> {
        if end < start {
            return Err(DatasetError::storage(format!(
                "range {start}-{end} of {key} is empty"
            )));
        }
        let response = self.request(
            "GET",
            key,
            Vec::new(),
            vec![("range".to_owned(), format!("bytes={start}-{end}"))],
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 206 && response.status != 200 {
            return Err(DatasetError::storage(format!(
                "GET {key} range {start}-{end} failed with {}",
                response.status
            )));
        }
        Ok(response.body)
    }

    /// The whole object at `key`.
    ///
    /// # Errors
    ///
    /// Fails when the object is absent.
    pub fn get(&self, key: &str) -> Result<Vec<u8>> {
        let response = self.request(
            "GET",
            key,
            Vec::new(),
            Vec::new(),
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 200 {
            return Err(DatasetError::storage(format!(
                "GET {key} failed with {}",
                response.status
            )));
        }
        Ok(response.body)
    }

    /// Write `file` at `key` only when the key is absent; never overwrites.
    ///
    /// The write is conditional (`If-None-Match: *`, atomic in R2 on a `PUT`
    /// and on `CompleteMultipartUpload`), so a `HEAD` that missed an object
    /// cannot lead to its replacement. Every object carries
    /// `x-amz-meta-sha256`, and a multipart object's parts are checked
    /// against the md5 each part answers.
    ///
    /// # Errors
    ///
    /// Fails when a request fails (a 403 on the `HEAD` included) or the
    /// object's bytes differ after the write.
    pub fn put_new(&self, key: &str, file: &Path) -> Result<PutOutcome> {
        let local_bytes = std::fs::metadata(file).io_at(IoOp::Read, file)?.len();
        let digest = sha256_file(file)?;
        if let Some(facts) = self.head(key)? {
            return self.existing_outcome(key, file, local_bytes, &digest, &facts);
        }
        let written = if local_bytes >= MULTIPART_THRESHOLD {
            self.put_multipart(key, file, local_bytes, &digest)?
        } else {
            let response = self.request(
                "PUT",
                key,
                Vec::new(),
                vec![
                    ("if-none-match".to_owned(), "*".to_owned()),
                    ("x-amz-meta-sha256".to_owned(), crate::layout::hex(&digest)),
                ],
                &digest,
                &Body::File(file.to_path_buf()),
            )?;
            match response.status {
                200 => true,
                412 => false,
                other => {
                    return Err(DatasetError::storage(format!(
                        "PUT {key} failed with {other}"
                    )));
                }
            }
        };
        if !written {
            // Another writer, or a read that lagged, got there first: whatever
            // is there now is compared, never replaced.
            return match self.head(key)? {
                Some(facts) => self.existing_outcome(key, file, local_bytes, &digest, &facts),
                None => Err(DatasetError::storage(format!(
                    "{key} was refused as existing and is not readable in {}",
                    self.bucket
                ))),
            };
        }
        match self.head(key)? {
            Some(facts)
                if facts.bytes == local_bytes && facts.sha256.is_none_or(|sha| sha == digest) =>
            {
                Ok(PutOutcome::Copied { bytes: local_bytes })
            }
            other => Err(DatasetError::storage(format!(
                "{key} has {} bytes in {} after copy, the stage has {local_bytes}",
                other.map_or_else(|| "no".to_owned(), |facts| facts.bytes.to_string()),
                self.bucket
            ))),
        }
    }

    /// What `put_new` answers for a key that is already there.
    fn existing_outcome(
        &self,
        key: &str,
        file: &Path,
        local_bytes: u64,
        digest: &[u8; 32],
        facts: &ObjectFacts,
    ) -> Result<PutOutcome> {
        Ok(match compare_object(facts, file, local_bytes, digest)? {
            Verdict::Same => PutOutcome::Skipped,
            Verdict::Different(how) => PutOutcome::Refused(format!(
                "{key} is in {} {how}: never overwritten",
                self.bucket
            )),
            Verdict::Unverifiable(why) => PutOutcome::Refused(format!(
                "{key} is in {} and its bytes cannot be verified ({why}): never overwritten",
                self.bucket
            )),
        })
    }

    /// Write `bytes` at `key`, overwriting what is there. The pointer is the
    /// only key a run may overwrite.
    ///
    /// # Errors
    ///
    /// Fails when the write fails or the object's bytes differ afterwards.
    pub fn put_overwrite(&self, key: &str, bytes: &[u8]) -> Result<()> {
        let digest = sha256(bytes);
        let response = self.request(
            "PUT",
            key,
            Vec::new(),
            Vec::new(),
            &digest,
            &Body::Bytes(bytes.to_vec()),
        )?;
        if response.status != 200 {
            return Err(DatasetError::storage(format!(
                "PUT {key} failed with {}",
                response.status
            )));
        }
        match self.head(key)? {
            Some(facts) if facts.bytes == bytes.len() as u64 => Ok(()),
            other => Err(DatasetError::storage(format!(
                "{key} has {} bytes in {} after copy, the stage has {}",
                other.map_or_else(|| "no".to_owned(), |facts| facts.bytes.to_string()),
                self.bucket,
                bytes.len()
            ))),
        }
    }

    /// The keys under `prefix` and their sizes.
    ///
    /// # Errors
    ///
    /// Fails when the listing fails.
    pub fn list(&self, prefix: &str) -> Result<Vec<(String, u64)>> {
        let response = self.request(
            "GET",
            "",
            vec![
                ("list-type".to_owned(), "2".to_owned()),
                ("prefix".to_owned(), prefix.to_owned()),
            ],
            Vec::new(),
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 200 {
            return Err(DatasetError::storage(format!(
                "listing {prefix} failed with {}",
                response.status
            )));
        }
        let text = String::from_utf8_lossy(&response.body);
        let mut out = Vec::new();
        for contents in text.split("<Contents>").skip(1) {
            let Some(key) = between(contents, "<Key>", "</Key>") else {
                continue;
            };
            let bytes = between(contents, "<Size>", "</Size>")
                .and_then(|size| size.parse::<u64>().ok())
                .unwrap_or_default();
            out.push((key.to_owned(), bytes));
        }
        Ok(out)
    }

    /// The multipart upload of `file` at `key`, whose sha256 is `digest`.
    /// `true` when the object was written, `false` when the key already
    /// existed at completion (the conditional write was refused).
    fn put_multipart(&self, key: &str, file: &Path, bytes: u64, digest: &[u8; 32]) -> Result<bool> {
        let response = self.request(
            "POST",
            key,
            vec![("uploads".to_owned(), String::new())],
            vec![("x-amz-meta-sha256".to_owned(), crate::layout::hex(digest))],
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 200 {
            return Err(DatasetError::storage(format!(
                "creating the multipart upload of {key} failed with {}",
                response.status
            )));
        }
        let upload_id = between(
            &String::from_utf8_lossy(&response.body),
            "<UploadId>",
            "</UploadId>",
        )
        .ok_or_else(|| DatasetError::storage(format!("{key}: the upload id is missing")))?
        .to_owned();
        let count = usize::try_from(bytes.div_ceil(PART_SIZE as u64)).unwrap_or(1);
        let parts = self.upload_parts(key, file, &upload_id, count);
        let parts = match parts {
            Ok(parts) => parts,
            Err(error) => {
                let _ = self.abort(key, &upload_id);
                return Err(error);
            }
        };
        let mut xml = String::from("<CompleteMultipartUpload>");
        for (number, etag) in &parts {
            xml.push_str(&format!(
                "<Part><PartNumber>{number}</PartNumber><ETag>{etag}</ETag></Part>"
            ));
        }
        xml.push_str("</CompleteMultipartUpload>");
        let response = self.request(
            "POST",
            key,
            vec![("uploadId".to_owned(), upload_id.clone())],
            vec![
                ("content-type".to_owned(), "application/xml".to_owned()),
                ("if-none-match".to_owned(), "*".to_owned()),
            ],
            &sha256(xml.as_bytes()),
            &Body::Bytes(xml.into_bytes()),
        )?;
        match response.status {
            200 => Ok(true),
            412 => {
                let _ = self.abort(key, &upload_id);
                Ok(false)
            }
            other => {
                let _ = self.abort(key, &upload_id);
                Err(DatasetError::storage(format!(
                    "completing the multipart upload of {key} failed with {other}"
                )))
            }
        }
    }

    /// Upload the parts of `file` with `PART_CONCURRENCY` in flight.
    fn upload_parts(
        &self,
        key: &str,
        file: &Path,
        upload_id: &str,
        count: usize,
    ) -> Result<Vec<(u32, String)>> {
        let pool = rayon::ThreadPoolBuilder::new()
            .num_threads(PART_CONCURRENCY)
            .build()
            .within("building the part pool")?;
        let mut parts = pool.install(|| {
            (0..count)
                .into_par_iter()
                .map(|index| -> Result<(u32, String)> {
                    let mut handle = File::open(file).io_at(IoOp::Open, file)?;
                    handle
                        .seek(SeekFrom::Start((index * PART_SIZE) as u64))
                        .io_at(IoOp::Seek, file)?;
                    let mut buffer = vec![0_u8; PART_SIZE];
                    let mut filled = 0;
                    while filled < PART_SIZE {
                        let read = handle.read(&mut buffer[filled..]).io_at(IoOp::Read, file)?;
                        if read == 0 {
                            break;
                        }
                        filled += read;
                    }
                    buffer.truncate(filled);
                    let number = u32::try_from(index + 1).number_of("part number")?;
                    let part_md5: [u8; 16] = Md5::digest(&buffer).into();
                    let digest = sha256(&buffer);
                    let response = self.request(
                        "PUT",
                        key,
                        vec![
                            ("partNumber".to_owned(), number.to_string()),
                            ("uploadId".to_owned(), upload_id.to_owned()),
                        ],
                        Vec::new(),
                        &digest,
                        &Body::Bytes(buffer),
                    )?;
                    if response.status != 200 {
                        return Err(DatasetError::storage(format!(
                            "part {number} of {key} failed with {}",
                            response.status
                        )));
                    }
                    let etag = header(&response.headers, "etag")
                        .ok_or_else(|| {
                            DatasetError::storage(format!("part {number} of {key} has no ETag"))
                        })?
                        .to_owned();
                    // R2 answers a part with the md5 of the bytes it received:
                    // a different value means the part was damaged on the way.
                    if etag_md5(&etag) != Some(part_md5) {
                        return Err(DatasetError::storage(format!(
                            "part {number} of {key} came back with ETag {etag}, \
                             not the md5 of the bytes sent"
                        )));
                    }
                    Ok((number, etag))
                })
                .collect::<Result<Vec<_>>>()
        })?;
        parts.sort_unstable_by_key(|(number, _)| *number);
        Ok(parts)
    }

    /// Abort a multipart upload, leaving no object.
    fn abort(&self, key: &str, upload_id: &str) -> Result<()> {
        let response = self.request(
            "DELETE",
            key,
            vec![("uploadId".to_owned(), upload_id.to_owned())],
            Vec::new(),
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 204 && response.status != 200 {
            return Err(DatasetError::storage(format!(
                "aborting the upload of {key} failed with {}",
                response.status
            )));
        }
        Ok(())
    }
}

/// The value of `name` in `headers`.
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(key, _)| key == name)
        .map(|(_, value)| value.as_str())
}

/// The `md5` of an `ETag`, when it is a single-part one.
fn etag_md5(value: &str) -> Option<[u8; 16]> {
    let text = value.trim_matches('"');
    if text.len() != 32 || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return None;
    }
    hex32::<16>(text)
}

/// The md5 of the part md5s and the part count of a multipart `ETag`
/// (`<32 hex>-<parts>`).
fn etag_multipart(value: &str) -> Option<([u8; 16], u32)> {
    let (digest, parts) = value.trim_matches('"').split_once('-')?;
    let parts = parts.parse::<u32>().ok().filter(|parts| *parts > 0)?;
    if digest.len() != 32 || !digest.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return None;
    }
    Some((hex32::<16>(&digest.to_ascii_lowercase())?, parts))
}

/// How many part sizes [`compare_object`] tries for a multipart `ETag`.
const CANDIDATE_PART_SIZES: usize = 64;

/// The part sizes, whole MiB, that split `bytes` into exactly `parts` parts
/// (a single part has the size of the file).
fn candidate_part_sizes(bytes: u64, parts: u32) -> Vec<u64> {
    const MIB: u64 = 1024 * 1024;
    if parts <= 1 {
        return vec![bytes.max(1)];
    }
    let parts = u64::from(parts);
    let (low, high) = (bytes.div_ceil(parts), bytes.saturating_sub(1) / (parts - 1));
    (low.div_ceil(MIB).max(1)..)
        .map(|mib| mib * MIB)
        .take_while(|size| *size <= high)
        .take(CANDIDATE_PART_SIZES)
        .collect()
}

/// The multipart `ETag` digest of `path` for parts of `part_size` bytes.
fn multipart_md5(path: &Path, part_size: u64) -> Result<[u8; 16]> {
    let mut file = File::open(path).io_at(IoOp::Open, path)?;
    let mut all = Md5::new();
    let mut part = Md5::new();
    let mut buffer = vec![0_u8; 1 << 20];
    let mut room = part_size;
    let mut started = false;
    loop {
        let want = usize::try_from(room.min(buffer.len() as u64)).unwrap_or(buffer.len());
        let read = file.read(&mut buffer[..want]).io_at(IoOp::Read, path)?;
        if read == 0 {
            break;
        }
        part.update(&buffer[..read]);
        started = true;
        room -= read as u64;
        if room == 0 {
            all.update(std::mem::replace(&mut part, Md5::new()).finalize());
            room = part_size;
            started = false;
        }
    }
    if started {
        all.update(part.finalize());
    }
    Ok(all.finalize().into())
}

/// Whether the object `facts` describes holds the bytes of the local file
/// `path` (`bytes` long, `sha256` the digest of it).
///
/// In order: size; the `x-amz-meta-sha256` the uploader writes; an md5
/// `ETag`; a multipart `ETag` rebuilt from the file for each whole-MiB part
/// size that gives the same part count. An `ETag` is never read as an md5
/// unless it is one.
///
/// # Errors
///
/// Fails when the file cannot be read.
pub fn compare_object(
    facts: &ObjectFacts,
    path: &Path,
    bytes: u64,
    sha256: &[u8; 32],
) -> Result<Verdict> {
    if facts.bytes != bytes {
        return Ok(Verdict::Different(format!(
            "with {} bytes, the stage has {bytes}",
            facts.bytes
        )));
    }
    if let Some(remote) = facts.sha256 {
        return Ok(if &remote == sha256 {
            Verdict::Same
        } else {
            Verdict::Different("with other bytes of the same size".to_owned())
        });
    }
    if let Some(remote) = facts.md5 {
        return Ok(if remote == md5_file(path)? {
            Verdict::Same
        } else {
            Verdict::Different("with other bytes of the same size".to_owned())
        });
    }
    if let Some((remote, parts)) = facts.multipart {
        for size in candidate_part_sizes(bytes, parts) {
            if multipart_md5(path, size)? == remote {
                return Ok(Verdict::Same);
            }
        }
        return Ok(Verdict::Unverifiable(format!(
            "an ETag of {parts} parts that matches no whole-MiB part size, and no sha256 metadata"
        )));
    }
    Ok(Verdict::Unverifiable(
        "no sha256 metadata and no ETag that is a checksum".to_owned(),
    ))
}

/// Decode a lower-case hex digest of `N` bytes.
fn hex32<const N: usize>(text: &str) -> Option<[u8; N]> {
    if text.len() != N * 2 {
        return None;
    }
    let mut out = [0_u8; N];
    for (index, chunk) in text.as_bytes().as_chunks::<2>().0.iter().enumerate() {
        let text = std::str::from_utf8(chunk).ok()?;
        out[index] = u8::from_str_radix(text, 16).ok()?;
    }
    Some(out)
}

/// The `md5` of the file at `path`.
fn md5_file(path: &Path) -> Result<[u8; 16]> {
    let mut file = File::open(path).io_at(IoOp::Open, path)?;
    let mut hasher = Md5::new();
    let mut buffer = vec![0_u8; 1 << 16];
    loop {
        let read = file.read(&mut buffer).io_at(IoOp::Read, path)?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hasher.finalize().into())
}

/// The `sha256` of the file at `path`.
fn sha256_file(path: &Path) -> Result<[u8; 32]> {
    crate::layout::sha256_file(path)
}

/// The text between `open` and `close` in `text`.
fn between<'a>(text: &'a str, open: &str, close: &str) -> Option<&'a str> {
    let start = text.find(open)? + open.len();
    let rest = &text[start..];
    let end = rest.find(close)?;
    Some(&rest[..end])
}

/// The current Unix second.
fn now() -> i64 {
    crate::layout::unix_seconds()
}

/// The listing of `prefix` as a map.
///
/// # Errors
///
/// Fails when the listing fails.
pub fn listing_map(client: &S3, prefix: &str) -> Result<BTreeMap<String, u64>> {
    Ok(client.list(prefix)?.into_iter().collect())
}

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

    fn write_temp(bytes: &[u8]) -> (tempfile::TempDir, std::path::PathBuf) {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("payload");
        std::fs::write(&path, bytes).expect("write");
        (dir, path)
    }

    #[test]
    fn put_new_skips_an_object_with_equal_bytes_and_refuses_a_different_one() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_dir, file) = write_temp(b"payload");
        assert!(matches!(
            client.put_new("datasets/x", &file).expect("put"),
            PutOutcome::Copied { bytes: 7 }
        ));
        assert!(matches!(
            client.put_new("datasets/x", &file).expect("put"),
            PutOutcome::Skipped
        ));
        let (_other, different) = write_temp(b"different");
        let refusal = client.put_new("datasets/x", &different).expect("put");
        assert!(matches!(refusal, PutOutcome::Refused(_)), "{refusal:?}");
        assert_eq!(
            fake.objects().get("datasets/x").map(Vec::as_slice),
            Some(&b"payload"[..])
        );
    }

    #[test]
    fn a_refused_write_sends_no_put() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_dir, file) = write_temp(b"first");
        client.put_new("datasets/y", &file).expect("put");
        let before = fake.writes();
        let (_other, different) = write_temp(b"second");
        let _ = client.put_new("datasets/y", &different).expect("put");
        assert_eq!(fake.writes(), before);
    }

    #[test]
    fn a_multipart_upload_round_trips_and_an_abort_leaves_no_object() {
        let fake = FakeS3::start();
        let big = vec![7_u8; 40 * 1024 * 1024];
        let (dir, file) = write_temp(&big);
        assert!(matches!(
            fake.client().put_new("big", &file).expect("put"),
            PutOutcome::Copied { .. }
        ));
        assert!(fake.multipart_parts_seen() > 1);
        assert_eq!(
            fake.client()
                .head("big")
                .expect("head")
                .expect("object")
                .bytes,
            40 * 1024 * 1024
        );
        let stored = fake.objects();
        assert_eq!(stored.get("big").map(Vec::len), Some(big.len()));
        assert_eq!(stored.get("big"), Some(&big));
        drop(dir);
    }

    const MIB: usize = 1024 * 1024;

    /// `len` bytes that differ from one end to the other, so a part sent in
    /// the wrong place changes a checksum.
    fn pattern(len: usize, seed: u8) -> Vec<u8> {
        (0..len)
            .map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
            .collect()
    }

    fn sha256_hex_of(bytes: &[u8]) -> String {
        use sha2::{Digest as _, Sha256};
        use std::fmt::Write as _;
        Sha256::digest(bytes)
            .iter()
            .fold(String::new(), |mut out, byte| {
                let _ = write!(out, "{byte:02x}");
                out
            })
    }

    /// R2 gives a multipart object the md5 of the part md5s and `-<parts>`, not
    /// an md5: the fake does the same, so no check can read it as one.
    #[test]
    fn a_multipart_object_has_a_multipart_etag_and_is_skipped_by_a_second_put() {
        let fake = FakeS3::start();
        let client = fake.client();
        let big = pattern(40 * MIB, 1);
        let (_dir, file) = write_temp(&big);
        assert!(matches!(
            client.put_new("datasets/big.pmtiles", &file).expect("put"),
            PutOutcome::Copied { .. }
        ));
        let etag = fake.etag("datasets/big.pmtiles").expect("etag");
        assert!(etag.ends_with("-5"), "40 MiB in 8 MiB parts: {etag}");
        let writes = fake.writes().len();
        let second = client.put_new("datasets/big.pmtiles", &file).expect("put");
        assert!(matches!(second, PutOutcome::Skipped), "{second:?}");
        assert_eq!(fake.writes().len(), writes, "a skip writes nothing");
    }

    #[test]
    fn a_multipart_object_with_other_bytes_of_the_same_size_is_refused() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_a, first) = write_temp(&pattern(40 * MIB, 1));
        let (_b, other) = write_temp(&pattern(40 * MIB, 2));
        client.put_new("big", &first).expect("put");
        let refusal = client.put_new("big", &other).expect("put");
        assert!(matches!(refusal, PutOutcome::Refused(_)), "{refusal:?}");
        assert_eq!(fake.objects().get("big"), Some(&pattern(40 * MIB, 1)));
    }

    #[test]
    fn a_multipart_upload_records_the_sha256_of_the_whole_file() {
        let fake = FakeS3::start();
        let big = pattern(33 * MIB, 3);
        let (_dir, file) = write_temp(&big);
        fake.client().put_new("big", &file).expect("put");
        assert_eq!(
            fake.meta("big").get("sha256").map(String::as_str),
            Some(sha256_hex_of(&big).as_str())
        );
        let facts = fake.client().head("big").expect("head").expect("object");
        assert_eq!(
            facts.sha256.map(|digest| digest.to_vec()),
            Some(
                (0..32)
                    .map(
                        |i| u8::from_str_radix(&sha256_hex_of(&big)[2 * i..2 * i + 2], 16).unwrap()
                    )
                    .collect()
            )
        );
    }

    /// Objects a third-party tool (rclone, 5 MiB parts) uploaded carry no
    /// metadata: the client rebuilds the `ETag` for the part sizes that give
    /// the same part count and compares.
    #[test]
    fn a_third_party_multipart_object_is_recognised_by_its_part_size() {
        let fake = FakeS3::start();
        let client = fake.client();
        let big = pattern(33 * MIB, 4);
        let (_dir, file) = write_temp(&big);
        fake.plant("tool-made", &big, Some(5 * MIB));
        let same = client.put_new("tool-made", &file).expect("put");
        assert!(matches!(same, PutOutcome::Skipped), "{same:?}");
        let (_o, other) = write_temp(&pattern(33 * MIB, 5));
        let refusal = client.put_new("tool-made", &other).expect("put");
        assert!(matches!(refusal, PutOutcome::Refused(_)), "{refusal:?}");
    }

    #[test]
    fn an_object_whose_checksum_cannot_be_rebuilt_is_refused_not_trusted() {
        let fake = FakeS3::start();
        let client = fake.client();
        let big = pattern(33 * MIB, 6);
        let (_dir, file) = write_temp(&big);
        // 3.5 MiB parts: not a whole number of MiB, so no candidate matches.
        fake.plant("odd", &big, Some(3 * MIB + MIB / 2));
        let outcome = client.put_new("odd", &file).expect("put");
        let PutOutcome::Refused(text) = outcome else {
            panic!("expected a refusal, got {outcome:?}");
        };
        assert!(text.contains("cannot be verified"), "{text}");
    }

    #[test]
    fn a_forbidden_head_is_an_error_not_an_absent_object() {
        let fake = FakeS3::start();
        fake.deny_head(true);
        let error = fake
            .client()
            .head("anything")
            .expect_err("a 403 is an error");
        assert!(error.to_string().contains("403"), "{error}");
    }

    /// A token that may write but not read must not turn a 403 into "the key
    /// is free": the object that is there stays.
    #[test]
    fn a_denied_head_never_leads_to_an_overwrite() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_a, first) = write_temp(b"first");
        client.put_new("datasets/x", &first).expect("put");
        fake.deny_head(true);
        let (_b, second) = write_temp(b"second");
        let outcome = client.put_new("datasets/x", &second);
        assert!(outcome.is_err(), "{outcome:?}");
        assert_eq!(
            fake.objects().get("datasets/x").map(Vec::as_slice),
            Some(&b"first"[..])
        );
    }

    /// A read that lags a write sees no object: the conditional write still
    /// refuses, so the dated key is never replaced.
    #[test]
    fn a_lagging_head_cannot_overwrite_a_dated_key() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_a, first) = write_temp(b"first");
        client.put_new("datasets/x", &first).expect("put");
        fake.hide_from_head(true);
        let (_b, second) = write_temp(b"second");
        let outcome = client.put_new("datasets/x", &second);
        assert!(
            !matches!(outcome, Ok(PutOutcome::Copied { .. })),
            "{outcome:?}"
        );
        assert_eq!(
            fake.objects().get("datasets/x").map(Vec::as_slice),
            Some(&b"first"[..])
        );
    }

    #[test]
    fn a_lagging_head_cannot_overwrite_a_multipart_object_either() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_a, first) = write_temp(&pattern(33 * MIB, 7));
        client.put_new("big", &first).expect("put");
        fake.hide_from_head(true);
        let (_b, second) = write_temp(&pattern(33 * MIB, 8));
        let outcome = client.put_new("big", &second);
        assert!(
            !matches!(outcome, Ok(PutOutcome::Copied { .. })),
            "{outcome:?}"
        );
        assert_eq!(fake.objects().get("big"), Some(&pattern(33 * MIB, 7)));
    }

    #[test]
    fn a_part_whose_etag_is_not_its_md5_aborts_the_upload() {
        let fake = FakeS3::start();
        fake.corrupt_part_etags(true);
        let (_dir, file) = write_temp(&pattern(33 * MIB, 9));
        let error = fake
            .client()
            .put_new("big", &file)
            .expect_err("corrupt part");
        assert!(error.to_string().contains("part"), "{error}");
        assert!(fake.objects().is_empty(), "no object after an abort");
    }

    #[test]
    fn a_range_read_returns_the_slice() {
        let fake = FakeS3::start();
        let client = fake.client();
        let (_dir, file) = write_temp(b"0123456789");
        client.put_new("range", &file).expect("put");
        assert_eq!(
            client.get_range("range", 2, 5).expect("range"),
            b"2345".to_vec()
        );
        assert_eq!(client.get("range").expect("get"), b"0123456789".to_vec());
    }

    #[test]
    fn an_overwrite_replaces_the_pointer_and_a_listing_names_it() {
        let fake = FakeS3::start();
        let client = fake.client();
        client
            .put_overwrite("datasets/a/current.json", b"one")
            .expect("put");
        client
            .put_overwrite("datasets/a/current.json", b"two")
            .expect("put");
        assert_eq!(
            client.get("datasets/a/current.json").expect("get"),
            b"two".to_vec()
        );
        client
            .put_overwrite("datasets/a/b/c.json", b"x")
            .expect("put");
        let mut listed = client.list("datasets/a/").expect("list");
        listed.sort();
        assert_eq!(
            listed,
            vec![
                ("datasets/a/b/c.json".to_owned(), 1_u64),
                ("datasets/a/current.json".to_owned(), 3),
            ]
        );
    }
}