geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
//! 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.

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 anyhow::{Context, Result, bail};
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]>,
    /// `sha256` metadata, when the upload wrote one.
    pub sha256: Option<[u8; 32]>,
}

/// 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() {
            bail!("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 {
                        bail!(
                            "{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).with_context(|| format!("opening {}", path.display()))?;
                signed_headers!(self.agent.put(&url)).send(file)
            }
            (other, _) => bail!("method {other} with this body is not supported"),
        }
        .with_context(|| 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()
                .with_context(|| 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) => Ok(Some(ObjectFacts {
                    bytes,
                    md5: header(&response.headers, "etag").and_then(etag_md5),
                    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),
            },
            404 | 403 => Ok(None),
            other => bail!("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 || response.status == 403 {
            return Ok(None);
        }
        if response.status != 206 && response.status != 200 {
            bail!("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())
            .with_context(|| format!("{key}: no content-range"))?;
        Ok(Some(ObjectFacts {
            bytes: total,
            md5: header(&response.headers, "etag").and_then(etag_md5),
            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 {
            bail!("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 {
            bail!(
                "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 {
            bail!("GET {key} failed with {}", response.status);
        }
        Ok(response.body)
    }

    /// Write `file` at `key` only when the key is absent; never overwrites.
    ///
    /// # Errors
    ///
    /// Fails when a request fails 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)
            .with_context(|| format!("reading {}", file.display()))?
            .len();
        let local_md5 = md5_file(file)?;
        if let Some(facts) = self.head(key)? {
            let same_bytes = facts.bytes == local_bytes;
            let same_md5 = facts.md5 == Some(local_md5);
            return Ok(if same_bytes && same_md5 {
                PutOutcome::Skipped
            } else if same_bytes {
                PutOutcome::Refused(format!(
                    "{key} is in {} with other bytes of the same size: never overwritten",
                    self.bucket
                ))
            } else {
                PutOutcome::Refused(format!(
                    "{key} is in {} with {} bytes, the stage has {local_bytes}: never overwritten",
                    self.bucket, facts.bytes
                ))
            });
        }
        if local_bytes >= MULTIPART_THRESHOLD {
            self.put_multipart(key, file, local_bytes)?;
        } else {
            let digest = sha256_file(file)?;
            let response = self.request(
                "PUT",
                key,
                Vec::new(),
                vec![("x-amz-meta-sha256".to_owned(), crate::layout::hex(&digest))],
                &digest,
                &Body::File(file.to_path_buf()),
            )?;
            if response.status != 200 {
                bail!("PUT {key} failed with {}", response.status);
            }
        }
        match self.head(key)? {
            Some(facts) if facts.bytes == local_bytes => {
                Ok(PutOutcome::Copied { bytes: local_bytes })
            }
            other => bail!(
                "{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
            ),
        }
    }

    /// 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 {
            bail!("PUT {key} failed with {}", response.status);
        }
        match self.head(key)? {
            Some(facts) if facts.bytes == bytes.len() as u64 => Ok(()),
            other => bail!(
                "{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 {
            bail!("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`.
    fn put_multipart(&self, key: &str, file: &Path, bytes: u64) -> Result<()> {
        let response = self.request(
            "POST",
            key,
            vec![("uploads".to_owned(), String::new())],
            Vec::new(),
            &empty_payload_sha256(),
            &Body::Empty,
        )?;
        if response.status != 200 {
            bail!(
                "creating the multipart upload of {key} failed with {}",
                response.status
            );
        }
        let upload_id = between(
            &String::from_utf8_lossy(&response.body),
            "<UploadId>",
            "</UploadId>",
        )
        .with_context(|| 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())],
            &sha256(xml.as_bytes()),
            &Body::Bytes(xml.into_bytes()),
        )?;
        if response.status != 200 {
            let _ = self.abort(key, &upload_id);
            bail!(
                "completing the multipart upload of {key} failed with {}",
                response.status
            );
        }
        Ok(())
    }

    /// 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()
            .context("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).with_context(|| format!("opening {}", file.display()))?;
                    handle
                        .seek(SeekFrom::Start((index * PART_SIZE) as u64))
                        .with_context(|| format!("seeking in {}", file.display()))?;
                    let mut buffer = vec![0_u8; PART_SIZE];
                    let mut filled = 0;
                    while filled < PART_SIZE {
                        let read = handle
                            .read(&mut buffer[filled..])
                            .with_context(|| format!("reading {}", file.display()))?;
                        if read == 0 {
                            break;
                        }
                        filled += read;
                    }
                    buffer.truncate(filled);
                    let number = u32::try_from(index + 1).context("part number")?;
                    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 {
                        bail!("part {number} of {key} failed with {}", response.status);
                    }
                    let etag = header(&response.headers, "etag")
                        .with_context(|| format!("part {number} of {key} has no ETag"))?
                        .to_owned();
                    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 {
            bail!(
                "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)
}

/// 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).with_context(|| format!("opening {}", path.display()))?;
    let mut hasher = Md5::new();
    let mut buffer = vec![0_u8; 1 << 16];
    loop {
        let read = file
            .read(&mut buffer)
            .with_context(|| format!("reading {}", path.display()))?;
        if read == 0 {
            break;
        }
        hasher.update(&buffer[..read]);
    }
    Ok(hasher.finalize().into())
}

/// The `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 `md5` of the file at `path`, as the client compares it with an
/// `ETag`.
///
/// # Errors
///
/// Fails when the file cannot be read.
pub(crate) fn md5_of(path: &Path) -> Result<[u8; 16]> {
    md5_file(path)
}

/// 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);
    }

    #[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),
            ]
        );
    }
}