http-mel 0.11.1

Mélodium HTTP library
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
//! Transfers through prepared requests, made as given with a client of their own: downloads
//! resumed after a cut, and uploads in parts retried one by one.
//!
//! Prepared URLs often are credentials, such as presigned ones: they never appear in errors,
//! which give the status of answers and the `<Code>` of XML error bodies instead.

use crate::client::PreparedRequest;
use core::future::Future;
use core::time::Duration;
use futures::AsyncReadExt;
use trillium::{HeaderName, HeaderValue, Method};
use trillium_client::{Client, Conn, Url};

/// Size of the chunks read from answers.
const CHUNK: usize = 1 << 20;
/// Longest wait between two attempts.
const MAX_BACKOFF: Duration = Duration::from_secs(16);
/// Longest part of an error body read to find its `<Code>`.
const MAX_ERROR_BODY: usize = 4096;

/// Client making prepared requests, without the default headers of any `HttpClient` model.
#[cfg(feature = "real")]
pub(crate) fn client() -> &'static Client {
    static CLIENT: std::sync::OnceLock<Client> = std::sync::OnceLock::new();
    CLIENT.get_or_init(|| {
        Client::new(
            trillium_rustls::RustlsConfig::default()
                .with_tcp_config(trillium_smol::ClientConfig::new().with_nodelay(true)),
        )
        .with_default_pool()
        .with_default_header(
            trillium::KnownHeaderName::UserAgent,
            crate::client::USER_AGENT,
        )
    })
}

/// Whether an answer of `status` is worth another attempt.
pub(crate) fn retriable(status: u16) -> bool {
    status >= 500 || status == 429 || status == 408
}

/// Wait before the attempt following `attempt` failed ones.
pub(crate) fn backoff(attempt: u32) -> Duration {
    Duration::from_millis(500)
        .saturating_mul(1 << attempt.min(8))
        .min(MAX_BACKOFF)
}

/// Waits before the attempt following `attempt` failed ones.
pub(crate) async fn wait(attempt: u32) {
    #[cfg(feature = "real")]
    smol::Timer::after(backoff(attempt)).await;
    #[cfg(feature = "mock")]
    let _ = attempt;
}

/// Describes a refusal from its status and the start of its body, giving the `<Code>` of XML
/// error bodies, as object storage answers, and nothing else of the body.
pub(crate) fn refusal(status: u16, body: &[u8]) -> String {
    let body = String::from_utf8_lossy(body);
    let code = body
        .split_once("<Code>")
        .and_then(|(_, rest)| rest.split_once("</Code>"))
        .map(|(code, _)| code.trim())
        .filter(|code| {
            !code.is_empty()
                && code.len() <= 64
                && code.chars().all(|c| c.is_ascii_alphanumeric() || c == '.')
        });
    match code {
        Some(code) => format!("storage answered {status} ({code})"),
        None => format!("storage answered {status}"),
    }
}

/// Removes `url`, and its parts holding signatures, from `message`.
pub(crate) fn redact(message: String, url: &Url) -> String {
    let mut message = message.replace(url.as_str(), "<prepared URL>");
    if let Some(query) = url.query().filter(|query| !query.is_empty()) {
        message = message.replace(query, "<query>");
    }
    message
}

/// Builds the connection making `request`, with `extra` headers.
pub(crate) fn connection(
    client: &Client,
    request: &PreparedRequest,
    extra: &[(&'static str, String)],
) -> Result<(Conn, Url), String> {
    let url = Url::parse(&request.url).map_err(|_| "the prepared URL is not valid".to_string())?;
    let method = Method::try_from(request.method.as_str())
        .map_err(|_| format!("'{}' is not an HTTP method", request.method))?;
    let mut conn = client.build_conn(method, url.clone());
    for (name, value) in request
        .headers
        .iter()
        .map(|(name, value)| (name.as_str(), value.clone()))
        .chain(extra.iter().map(|(name, value)| (*name, value.clone())))
    {
        let header_name = HeaderName::from(name.to_string());
        let header_value = HeaderValue::from(value);
        if !header_name.is_valid() || !header_value.is_valid() {
            return Err(format!(
                "header '{name}' of the prepared request is not valid"
            ));
        }
        conn.request_headers_mut()
            .insert(header_name.to_owned(), header_value);
    }
    Ok((conn, url))
}

/// Reads at most `MAX_ERROR_BODY` bytes of the body of `conn`.
pub(crate) async fn error_body(conn: &mut Conn) -> Vec<u8> {
    let mut body = Vec::new();
    let _ = conn
        .response_body()
        .take(MAX_ERROR_BODY as u64)
        .read_to_end(&mut body)
        .await;
    body
}

/// Header `name` of the answer of `conn`, if any.
pub(crate) fn header(conn: &Conn, name: &str) -> Option<String> {
    conn.response_headers()
        .get_str(name)
        .map(|value| value.to_string())
}

/// How an attempt of a download ended.
enum Attempt {
    /// Cut, to try again from what was given.
    Cut(String),
    /// Failed for good.
    Failed(String),
}

/// Downloads the object of `request`, giving its bytes through `give`, resuming after a cut
/// up to `retries` times, never giving a byte twice.
///
/// `give` tells whether the bytes were taken: once they are not, the download stops, and
/// `Ok(false)` is given.
pub(crate) async fn download<F, Fut>(
    client: &Client,
    request: &PreparedRequest,
    retries: u32,
    mut give: F,
) -> Result<bool, String>
where
    F: FnMut(Vec<u8>) -> Fut,
    Fut: Future<Output = bool>,
{
    let mut given: u64 = 0;
    let mut etag: Option<String> = None;
    let mut failures = 0;
    loop {
        match attempt(client, request, &mut given, &mut etag, &mut give).await {
            Ok(true) => return Ok(true),
            Ok(false) => return Ok(false),
            Err(Attempt::Cut(_)) if failures < retries => {
                wait(failures).await;
                failures += 1;
            }
            Err(Attempt::Cut(reason)) | Err(Attempt::Failed(reason)) => return Err(reason),
        }
    }
}

/// Makes one attempt of a download, from `given` bytes, pinned to `etag` once known.
async fn attempt<F, Fut>(
    client: &Client,
    request: &PreparedRequest,
    given: &mut u64,
    etag: &mut Option<String>,
    give: &mut F,
) -> Result<bool, Attempt>
where
    F: FnMut(Vec<u8>) -> Fut,
    Fut: Future<Output = bool>,
{
    let mut extra = Vec::new();
    if *given > 0 {
        match etag {
            Some(etag) => {
                extra.push(("Range", format!("bytes={given}-")));
                extra.push(("If-Match", etag.clone()));
            }
            None => {
                return Err(Attempt::Failed(
                    "the download was cut, and storage gave no entity tag to resume it".to_string(),
                ))
            }
        }
    }
    let (conn, url) = connection(client, request, &extra).map_err(Attempt::Failed)?;
    let mut conn = conn
        .await
        .map_err(|err| Attempt::Cut(redact(format!("connection failed: {err}"), &url)))?;
    let status = conn.status().map(|status| status as u16).unwrap_or(0);

    let expected = if *given == 0 {
        if !(200..300).contains(&status) {
            return Err(answer_error(&mut conn, status).await);
        }
        *etag = header(&conn, "etag");
        header(&conn, "content-length").and_then(|length| length.parse::<u64>().ok())
    } else {
        match status {
            206 => {
                let range = header(&conn, "content-range").unwrap_or_default();
                if !range.starts_with(&format!("bytes {given}-")) {
                    return Err(Attempt::Failed(
                        "storage resumed the download from another position".to_string(),
                    ));
                }
                header(&conn, "content-length")
                    .and_then(|length| length.parse::<u64>().ok())
                    .map(|length| *given + length)
            }
            412 => {
                return Err(Attempt::Failed(
                    "the object changed while it was downloaded".to_string(),
                ))
            }
            200 => {
                return Err(Attempt::Failed(
                    "storage did not resume the download".to_string(),
                ))
            }
            status => return Err(answer_error(&mut conn, status).await),
        }
    };

    let mut body = conn.response_body();
    loop {
        let mut chunk = vec![0; CHUNK];
        match body.read(&mut chunk).await {
            Ok(0) => break,
            Ok(read) => {
                chunk.truncate(read);
                *given += read as u64;
                if !give(chunk).await {
                    return Ok(false);
                }
            }
            Err(err) => {
                return Err(Attempt::Cut(redact(
                    format!("the download was cut: {err}"),
                    &url,
                )))
            }
        }
    }
    match expected {
        Some(expected) if *given < expected => Err(Attempt::Cut(format!(
            "the download was cut after {given} of {expected} bytes"
        ))),
        _ => Ok(true),
    }
}

/// Error for an answer of `status`, worth another attempt or not.
async fn answer_error(conn: &mut Conn, status: u16) -> Attempt {
    let reason = refusal(status, &error_body(conn).await);
    if retriable(status) {
        Attempt::Cut(reason)
    } else {
        Attempt::Failed(reason)
    }
}

/// Most parts of an upload object storage takes.
pub(crate) const MAX_PARTS: u32 = 10_000;
/// Size of the first parts of an upload.
const FIRST_PART_SIZE: u64 = 8 << 20;
/// Number of parts of each size before the size doubles.
const PARTS_PER_SIZE: u32 = 1_000;

/// Size of the part `part_number` of an upload, from 1: 8 MiB for parts 1 to 1,000, doubling
/// every 1,000 parts, so that 10,000 parts hold about 8 TiB. Beyond 10,000, the size of the
/// last part is given.
pub(crate) fn part_size(part_number: u32) -> u64 {
    FIRST_PART_SIZE << ((part_number.clamp(1, MAX_PARTS) - 1) / PARTS_PER_SIZE)
}

/// Cuts data into parts of the sizes `size` gives, from part 1.
pub(crate) struct Cutter {
    size: fn(u32) -> u64,
    part: Vec<u8>,
    number: u32,
}

impl Cutter {
    pub(crate) fn new(size: fn(u32) -> u64) -> Self {
        Self {
            size,
            part: Vec::new(),
            number: 1,
        }
    }

    /// Adds `bytes`, giving the parts they complete.
    pub(crate) fn push(&mut self, mut bytes: &[u8]) -> Result<Vec<Vec<u8>>, String> {
        let mut complete = Vec::new();
        while !bytes.is_empty() {
            if self.number > MAX_PARTS {
                return Err(format!("the data needs more than {MAX_PARTS} parts"));
            }
            let size = (self.size)(self.number) as usize;
            if self.part.capacity() < size {
                self.part.reserve_exact(size - self.part.len());
            }
            let taken = (size - self.part.len()).min(bytes.len());
            self.part.extend_from_slice(&bytes[..taken]);
            bytes = &bytes[taken..];
            if self.part.len() == size {
                complete.push(core::mem::take(&mut self.part));
                self.number += 1;
            }
        }
        Ok(complete)
    }

    /// Ends the data, giving the last part: what is left, or an empty part when no part was
    /// given, an upload having at least one.
    pub(crate) fn finish(self) -> Option<Vec<u8>> {
        (!self.part.is_empty() || self.number == 1).then_some(self.part)
    }
}

/// Uploads `part` with `request`, retrying up to `retries` times, and gives the value of the
/// header `tag_header` of the answer.
pub(crate) async fn upload_part(
    client: &Client,
    request: &PreparedRequest,
    part: &[u8],
    tag_header: &str,
    retries: u32,
) -> Result<String, String> {
    let mut failures = 0;
    loop {
        // Errors tell whether another attempt is worth it.
        let result: Result<String, (bool, String)> = async {
            let (conn, url) = connection(client, request, &[]).map_err(|err| (false, err))?;
            let mut conn = conn
                .with_body(part.to_vec())
                .await
                .map_err(|err| (true, redact(format!("connection failed: {err}"), &url)))?;
            let status = conn.status().map(|status| status as u16).unwrap_or(0);
            if (200..300).contains(&status) {
                header(&conn, tag_header).ok_or_else(|| {
                    (
                        false,
                        format!("storage gave no '{tag_header}' for the part"),
                    )
                })
            } else {
                let reason = refusal(status, &error_body(&mut conn).await);
                Err((retriable(status), reason))
            }
        }
        .await;
        match result {
            Ok(tag) => return Ok(tag),
            Err((true, _)) if failures < retries => {
                wait(failures).await;
                failures += 1;
            }
            Err((_, reason)) => return Err(reason),
        }
    }
}

/// Uploads `size` bytes given by `next` with `request`, as they come, in one request.
///
/// Data longer or shorter than `size` fails the upload, its request being dropped.
pub(crate) async fn put<F, Fut>(
    client: &Client,
    request: &PreparedRequest,
    size: u64,
    mut next: F,
) -> Result<(), String>
where
    F: FnMut() -> Fut,
    Fut: Future<Output = Option<Vec<u8>>>,
{
    use async_ringbuf::AsyncHeapRb;

    let (conn, url) = connection(client, request, &[])?;
    let (mut producer, consumer) = AsyncHeapRb::<u8>::new(CHUNK).split();

    let feeding = async move {
        let mut sent: u64 = 0;
        while let Some(bytes) = next().await {
            sent += bytes.len() as u64;
            if sent > size {
                return Err(format!("the data is longer than {size} bytes"));
            }
            if producer.push_iter(bytes.into_iter()).await.is_err() {
                break;
            }
        }
        if sent < size {
            return Err(format!("the data is {sent} bytes, shorter than {size}"));
        }
        producer.close();
        Ok(())
    };
    let sending = async {
        conn.with_body(trillium_client::Body::new_streaming(consumer, Some(size)))
            .await
            .map_err(|err| redact(format!("connection failed: {err}"), &url))
    };

    // A failure of either side drops the other, the request included.
    let (_, mut conn) = futures::future::try_join(feeding, sending).await?;
    let status = conn.status().map(|status| status as u16).unwrap_or(0);
    if (200..300).contains(&status) {
        Ok(())
    } else {
        Err(refusal(status, &error_body(&mut conn).await))
    }
}

#[cfg(all(test, feature = "real"))]
pub(crate) mod tests {
    use super::*;
    use std::collections::BTreeMap;
    use std::io::{BufRead, BufReader, Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::sync::{Arc, Mutex};

    /// A request received by the test server: its first line and headers.
    #[derive(Debug, Clone)]
    pub(crate) struct Received {
        pub line: String,
        pub headers: BTreeMap<String, String>,
        pub body: Vec<u8>,
    }

    /// What the test server does with a request: the bytes it writes back, then whether it
    /// closes the connection right after.
    pub(crate) type Respond = Box<dyn FnMut(usize, &Received) -> Vec<u8> + Send>;

    /// Serves requests on a local port with `respond`, keeping what it received.
    pub(crate) fn serve(mut respond: Respond) -> (u16, Arc<Mutex<Vec<Received>>>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        let received = Arc::new(Mutex::new(Vec::new()));
        let kept = Arc::clone(&received);
        std::thread::spawn(move || {
            for (index, stream) in listener.incoming().enumerate() {
                let Ok(mut stream) = stream else { break };
                let request = read_request(&mut stream);
                kept.lock().unwrap().push(request.clone());
                let _ = stream.write_all(&respond(index, &request));
                let _ = stream.flush();
                let _ = stream.shutdown(std::net::Shutdown::Both);
            }
        });
        (port, received)
    }

    fn read_request(stream: &mut TcpStream) -> Received {
        let mut reader = BufReader::new(stream);
        let mut line = String::new();
        reader.read_line(&mut line).unwrap();
        let mut headers = BTreeMap::new();
        loop {
            let mut header = String::new();
            reader.read_line(&mut header).unwrap();
            let header = header.trim_end();
            if header.is_empty() {
                break;
            }
            if let Some((name, value)) = header.split_once(':') {
                headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());
            }
        }
        // The client waits to be told to send its body, as object storage does.
        if headers.get("expect").map(String::as_str) == Some("100-continue") {
            let _ = reader.get_mut().write_all(b"HTTP/1.1 100 Continue\r\n\r\n");
        }
        let length = headers
            .get("content-length")
            .and_then(|length| length.parse::<usize>().ok())
            .unwrap_or(0);
        let mut body = vec![0; length];
        reader.read_exact(&mut body).unwrap();
        Received {
            line: line.trim_end().to_string(),
            headers,
            body,
        }
    }

    /// An HTTP answer of `status` with `headers` and `body`, its length being `length`.
    pub(crate) fn answer(
        status: &str,
        headers: &[(&str, String)],
        body: &[u8],
        length: usize,
    ) -> Vec<u8> {
        let mut answer =
            format!("HTTP/1.1 {status}\r\nContent-Length: {length}\r\nConnection: close\r\n");
        for (name, value) in headers {
            answer.push_str(&format!("{name}: {value}\r\n"));
        }
        answer.push_str("\r\n");
        let mut answer = answer.into_bytes();
        answer.extend_from_slice(body);
        answer
    }

    pub(crate) fn request(method: &str, port: u16) -> PreparedRequest {
        PreparedRequest {
            method: method.to_string(),
            url: format!("http://127.0.0.1:{port}/object?X-Amz-Signature=sentinel-signature"),
            headers: BTreeMap::from([("x-prepared".to_string(), "yes".to_string())]),
        }
    }

    fn client() -> Client {
        Client::new(trillium_smol::ClientConfig::new())
    }

    fn run(request: &PreparedRequest, retries: u32) -> (Result<bool, String>, Vec<u8>) {
        smol::block_on(async {
            let mut got = Vec::new();
            let result = download(&client(), request, retries, |bytes| {
                got.extend(bytes);
                async { true }
            })
            .await;
            (result, got)
        })
    }

    const OBJECT: &[u8] = b"0123456789abcdefghijklmnopqrstuvwxyz";

    #[test]
    fn downloads_resume_after_a_cut() {
        let (port, received) = serve(Box::new(|index, request| match index {
            // Cut after 10 bytes of 36.
            0 => answer(
                "200 OK",
                &[("ETag", "\"v1\"".to_string())],
                &OBJECT[..10],
                OBJECT.len(),
            ),
            _ => {
                let start: usize = request.headers["range"]
                    .trim_start_matches("bytes=")
                    .trim_end_matches('-')
                    .parse()
                    .unwrap();
                answer(
                    "206 Partial Content",
                    &[
                        ("ETag", "\"v1\"".to_string()),
                        ("Content-Range", format!("bytes {start}-35/36")),
                    ],
                    &OBJECT[start..],
                    OBJECT.len() - start,
                )
            }
        }));
        let (result, got) = run(&request("GET", port), 2);
        assert_eq!(result, Ok(true));
        assert_eq!(got, OBJECT);

        let received = received.lock().unwrap();
        assert_eq!(received.len(), 2);
        assert_eq!(
            received[0].line,
            "GET /object?X-Amz-Signature=sentinel-signature HTTP/1.1"
        );
        assert!(received[0].body.is_empty());
        assert_eq!(received[0].headers["x-prepared"], "yes");
        assert!(!received[0].headers.contains_key("range"));
        assert_eq!(received[1].headers["range"], "bytes=10-");
        assert_eq!(received[1].headers["if-match"], "\"v1\"");
    }

    #[test]
    fn changed_objects_fail() {
        let (port, _) = serve(Box::new(|index, _| match index {
            0 => answer(
                "200 OK",
                &[("ETag", "\"v1\"".to_string())],
                &OBJECT[..10],
                OBJECT.len(),
            ),
            _ => answer("412 Precondition Failed", &[], b"", 0),
        }));
        let (result, got) = run(&request("GET", port), 2);
        assert_eq!(
            result,
            Err("the object changed while it was downloaded".to_string())
        );
        assert_eq!(got, &OBJECT[..10]);
    }

    #[test]
    fn wrong_ranges_fail() {
        let (port, _) = serve(Box::new(|index, _| match index {
            0 => answer(
                "200 OK",
                &[("ETag", "\"v1\"".to_string())],
                &OBJECT[..10],
                OBJECT.len(),
            ),
            _ => answer(
                "206 Partial Content",
                &[("Content-Range", "bytes 0-35/36".to_string())],
                OBJECT,
                OBJECT.len(),
            ),
        }));
        let (result, _) = run(&request("GET", port), 2);
        assert_eq!(
            result,
            Err("storage resumed the download from another position".to_string())
        );
    }

    #[test]
    fn refusals_give_status_and_code_only() {
        let body = b"<?xml version=\"1.0\"?><Error><Code>AccessDenied</Code><Message>Request has expired for http://127.0.0.1/object?X-Amz-Signature=sentinel-signature</Message></Error>";
        let (port, received) = serve(Box::new(move |_, _| {
            answer("403 Forbidden", &[], body, body.len())
        }));
        let (result, _) = run(&request("GET", port), 2);
        assert_eq!(
            result,
            Err("storage answered 403 (AccessDenied)".to_string())
        );
        // Refusals are not worth another attempt.
        assert_eq!(received.lock().unwrap().len(), 1);
    }

    #[test]
    fn retries_end() {
        let (port, received) = serve(Box::new(|_, _| {
            answer("503 Service Unavailable", &[], b"", 0)
        }));
        let (result, _) = run(&request("GET", port), 1);
        assert_eq!(result, Err("storage answered 503".to_string()));
        assert_eq!(received.lock().unwrap().len(), 2);
    }

    #[test]
    fn urls_are_redacted() {
        let url = Url::parse("https://storage.example/object?X-Amz-Signature=sentinel").unwrap();
        let message = redact(
            "failed for https://storage.example/object?X-Amz-Signature=sentinel and X-Amz-Signature=sentinel".to_string(),
            &url,
        );
        assert!(!message.contains("sentinel"), "{message}");
        assert_eq!(
            refusal(500, b"<Code>bad code with spaces</Code>"),
            "storage answered 500"
        );
    }

    #[test]
    fn part_sizes_grow_every_thousand_parts() {
        assert_eq!(part_size(1), 8 << 20);
        assert_eq!(part_size(1_000), 8 << 20);
        assert_eq!(part_size(1_001), 16 << 20);
        assert_eq!(part_size(10_000), 4 << 30);
        // 1,000 parts of each size, from 8 MiB to 4 GiB: about 8 TiB.
        let total: u64 = (1..=MAX_PARTS).map(part_size).sum();
        assert_eq!(total, 1_000 * (8 << 20) * 1_023);
    }

    fn small(part_number: u32) -> u64 {
        if part_number <= 2 {
            4
        } else {
            8
        }
    }

    #[test]
    fn data_is_cut_in_parts() {
        let mut cutter = Cutter::new(small);
        assert!(cutter.push(b"abc").unwrap().is_empty());
        assert_eq!(
            cutter.push(b"defgh").unwrap(),
            vec![b"abcd".to_vec(), b"efgh".to_vec()]
        );
        assert_eq!(
            cutter.push(b"0123456789").unwrap(),
            vec![b"01234567".to_vec()]
        );
        assert_eq!(cutter.finish(), Some(b"89".to_vec()));

        // Parts ending with the data leave no empty last part, and no data gives one.
        let mut exact = Cutter::new(small);
        assert_eq!(exact.push(b"abcd").unwrap().len(), 1);
        assert_eq!(exact.finish(), None);
        assert_eq!(Cutter::new(small).finish(), Some(Vec::new()));
    }

    #[test]
    fn data_needing_too_many_parts_fails() {
        let mut cutter = Cutter::new(|_| 1);
        assert_eq!(
            cutter.push(&vec![0; MAX_PARTS as usize]).unwrap().len(),
            MAX_PARTS as usize
        );
        assert!(cutter.push(b"x").is_err());
    }

    fn upload(request: &PreparedRequest, part: &[u8], retries: u32) -> Result<String, String> {
        smol::block_on(upload_part(&client(), request, part, "etag", retries))
    }

    #[test]
    fn refused_parts_are_retried() {
        let (port, received) = serve(Box::new(|index, _| match index {
            0 => answer("503 Service Unavailable", &[], b"", 0),
            _ => answer("200 OK", &[("ETag", "\"part-1\"".to_string())], b"", 0),
        }));
        assert_eq!(
            upload(&request("PUT", port), b"part data", 2),
            Ok("\"part-1\"".to_string())
        );
        let received = received.lock().unwrap();
        assert_eq!(received.len(), 2);
        for request in received.iter() {
            assert!(request.line.starts_with("PUT /object?"), "{}", request.line);
            assert_eq!(request.headers["content-length"], "9");
            assert_eq!(request.body, b"part data");
        }
    }

    #[test]
    fn parts_without_tag_fail() {
        let (port, _) = serve(Box::new(|_, _| answer("200 OK", &[], b"", 0)));
        assert_eq!(
            upload(&request("PUT", port), b"part data", 2),
            Err("storage gave no 'etag' for the part".to_string())
        );
    }

    fn put_chunks(
        request: &PreparedRequest,
        size: u64,
        chunks: Vec<&'static [u8]>,
    ) -> Result<(), String> {
        smol::block_on(async {
            let mut chunks = chunks.into_iter();
            put(&client(), request, size, || {
                let chunk = chunks.next().map(|chunk| chunk.to_vec());
                async move { chunk }
            })
            .await
        })
    }

    #[test]
    fn single_uploads_have_their_length() {
        let (port, received) = serve(Box::new(|_, _| answer("200 OK", &[], b"", 0)));
        assert_eq!(
            put_chunks(&request("PUT", port), 11, vec![b"hello ", b"world"]),
            Ok(())
        );
        let received = received.lock().unwrap();
        assert_eq!(received[0].headers["content-length"], "11");
        assert_eq!(received[0].body, b"hello world");
    }

    #[test]
    fn single_uploads_of_another_length_fail() {
        let (port, _) = serve(Box::new(|_, _| answer("200 OK", &[], b"", 0)));
        assert_eq!(
            put_chunks(&request("PUT", port), 4, vec![b"hello"]),
            Err("the data is longer than 4 bytes".to_string())
        );
        assert_eq!(
            put_chunks(&request("PUT", port), 40, vec![b"hello"]),
            Err("the data is 5 bytes, shorter than 40".to_string())
        );
    }
}