zsync-rs 0.3.0

Efficient file transfer using rsync algorithm over HTTP
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
//! HTTP transport: control files, byte ranges, and planning range requests.
//!
//! [`HttpClient`] fetches a control file and the byte ranges of a target. The
//! free functions turn the block ranges a matcher still needs into byte
//! ranges, and merge ranges separated by small gaps, since one request that
//! re-downloads a few known bytes is usually cheaper than another round trip.

use std::io::Read;
use std::sync::{Mutex, PoisonError};
use std::time::Duration;

use ureq::ResponseExt;

use crate::control::{ControlFile, ParseError};

/// Why a fetch failed.
#[derive(Debug, thiserror::Error)]
pub enum HttpError {
    /// The request could not be made or completed, such as when the host
    /// was unreachable, the connection dropped or TLS failed.
    #[error("HTTP error: {0}")]
    Request(ureq::Error),
    /// The server answered with a status that does not carry the data.
    #[error("HTTP error: server answered with status {0}")]
    Status(u16),
    /// The server answered a range that does not start at zero with the
    /// whole file, so it cannot serve partial downloads.
    #[error("HTTP error: server ignored the Range header, so it cannot serve partial downloads")]
    RangeIgnored,
    /// A fetched control file did not parse.
    #[error("invalid control file: {0}")]
    InvalidControl(#[from] ParseError),
    /// Reading a response body failed.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
    /// A URL could not be used. Not currently returned by this crate.
    #[error("Invalid URL: {0}")]
    InvalidUrl(String),
    /// There was no URL to fetch from. Not currently returned by this crate.
    #[error("No URLs available")]
    NoUrls,
}

impl From<ureq::Error> for HttpError {
    fn from(e: ureq::Error) -> Self {
        match e {
            ureq::Error::StatusCode(status) => Self::Status(status),
            e => Self::Request(e),
        }
    }
}

impl HttpError {
    /// Whether the same request might succeed if made again later.
    ///
    /// True for a dropped or timed-out connection, an unreachable host, and
    /// the statuses a busy or restarting server answers with. False for
    /// anything the server or the request would repeat, such as a missing
    /// file or a server that ignores `Range`.
    pub fn is_transient(&self) -> bool {
        match self {
            Self::Request(e) => matches!(
                e,
                ureq::Error::Io(_)
                    | ureq::Error::Timeout(_)
                    | ureq::Error::HostNotFound
                    | ureq::Error::ConnectionFailed
            ),
            Self::Status(status) => matches!(status, 408 | 429 | 500 | 502 | 503 | 504),
            Self::Io(_) => true,
            Self::RangeIgnored | Self::InvalidControl(_) | Self::InvalidUrl(_) | Self::NoUrls => {
                false
            }
        }
    }
}

/// The body of one range response, capped at the length requested.
///
/// Returned by [`HttpClient::fetch_range_reader`].
pub struct HttpRangeReader {
    reader: Box<dyn std::io::Read + Send + Sync>,
    remaining: u64,
}

impl std::io::Read for HttpRangeReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.remaining == 0 {
            // ureq returns a connection to its pool only once it has seen
            // the end of the body, so one more read is needed for the next
            // request to reuse it. A body longer than asked for is not
            // read further, and its connection is closed instead.
            let _ = self.reader.read(&mut [0u8; 1]);
            self.reader = Box::new(std::io::empty());
            return Ok(0);
        }
        let len = buf
            .len()
            .min(usize::try_from(self.remaining).unwrap_or(usize::MAX));
        let n = self.reader.read(&mut buf[..len])?;
        self.remaining -= n as u64;
        Ok(n)
    }
}

/// Cap on establishing a connection, covering the TCP handshake and TLS
/// setup but never the transfer that follows.
///
/// ureq applies no connect timeout of its own, which leaves an address that
/// silently drops SYNs costing the kernel's full retry schedule, around two
/// minutes each. A mirror redirect that lands on a host with several such
/// addresses stalls for as long as it takes to exhaust them all, and the
/// error raised at the end is an unhelpful synthetic "connection refused".
/// ureq divides this budget across the resolved addresses, so the cap is
/// generous enough that a distant mirror still gets several seconds.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(20);

/// Cap on the DNS lookup, for the same reason as [`CONNECT_TIMEOUT`].
///
/// Deliberately the longer of the two. ureq attributes a timeout to whichever
/// phase would have expired first, so an equal pair reports a connect failure
/// as a resolve one and points whoever reads the error at the wrong thing.
pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(30);

/// HTTP transport for fetching control files and byte ranges.
///
/// The client remembers where the last range URL redirected to and sends
/// later ranges of that URL straight there. Many hosts redirect every
/// download to a signed storage URL, and following the redirect again for
/// each range would add a round trip to every request.
pub struct HttpClient {
    agent: ureq::Agent,
    redirect: Mutex<Option<(String, String)>>,
}

impl Default for HttpClient {
    fn default() -> Self {
        Self::new()
    }
}

impl HttpClient {
    /// A client permitting plain HTTP, with a bound on reaching a host.
    ///
    /// zsync is routinely served over HTTP and across mirror redirects, so
    /// the scheme policy is permissive on purpose. An embedder with a
    /// stricter one, such as one that must refuse a downgrade to HTTP or
    /// pin its own trust roots, should build an agent and pass it to
    /// [`HttpClient::with_agent`] rather than relying on these.
    ///
    /// [`CONNECT_TIMEOUT`] and [`RESOLVE_TIMEOUT`] apply. Neither bounds the
    /// transfer itself, so a mirror that trickles bytes for an hour is left
    /// alone; they only cap how long a host that never answers can cost.
    pub fn new() -> Self {
        Self::with_agent(
            ureq::Agent::config_builder()
                .https_only(false)
                .timeout_connect(Some(CONNECT_TIMEOUT))
                .timeout_resolve(Some(RESOLVE_TIMEOUT))
                .build()
                .new_agent(),
        )
    }

    /// A client using a caller-supplied agent.
    ///
    /// The agent carries the whole transport policy: TLS roots, whether a
    /// redirect may downgrade to HTTP, timeouts and proxies. Supplying one
    /// keeps that decision with the embedder, which is the only place that
    /// knows what the transferred bytes are trusted for.
    pub fn with_agent(agent: ureq::Agent) -> Self {
        Self {
            agent,
            redirect: Mutex::new(None),
        }
    }

    /// Fetches and parses the control file at `url`.
    ///
    /// # Errors
    ///
    /// Returns [`HttpError::Request`] or [`HttpError::Status`] when the
    /// request fails, and [`HttpError::InvalidControl`] when the response
    /// does not parse as a control file.
    pub fn fetch_control_file(&self, url: &str) -> Result<ControlFile, HttpError> {
        let response = self.agent.get(url).call()?;

        let mut reader = response.into_body().into_reader();
        let control = ControlFile::parse(&mut reader)?;
        // Reaching the end of the body lets ureq reuse the connection, which
        // usually goes to the same host as the first range request.
        let _ = std::io::copy(&mut reader.take(64 * 1024), &mut std::io::sink());
        Ok(control)
    }

    /// A reader over `start..=end` of `url`.
    ///
    /// The reader is capped at the requested length. Without that cap the
    /// origin decides how much the client reads: a response longer than
    /// the range is consumed in full, and callers that accumulate it, such
    /// as block assembly, grow a buffer to match. Bytes past the range
    /// were never asked for and are of no use, so they are not read.
    ///
    /// A `200 OK` is accepted only for a range starting at zero. A server
    /// that answers `200` has ignored `Range` and sends the file from its
    /// first byte, which is right for such a range and wrong for any other.
    ///
    /// When an earlier range of `url` was redirected, the request goes to
    /// the redirect target directly. If the target answers with an error
    /// status, as a signed URL does once it expires, the request is made
    /// again to `url`.
    ///
    /// # Errors
    ///
    /// Returns [`HttpError::Request`] when the request fails,
    /// [`HttpError::Status`] when the status is neither 200 nor 206, and
    /// [`HttpError::RangeIgnored`] when it is 200 for a range that does not
    /// start at zero.
    pub fn fetch_range_reader(
        &self,
        url: &str,
        start: u64,
        end: u64,
    ) -> Result<HttpRangeReader, HttpError> {
        let target = self
            .remembered_redirect()
            .and_then(|(from, to)| (from == url).then_some(to));
        if let Some(target) = target {
            match self.open_range(&target, start, end) {
                Err(HttpError::Status(_)) => {}
                result => return result.map(|(reader, _)| reader),
            }
        }

        let (reader, final_url) = self.open_range(url, start, end)?;
        *self.redirect.lock().unwrap_or_else(PoisonError::into_inner) =
            (final_url != url).then(|| (url.to_string(), final_url));
        Ok(reader)
    }

    fn remembered_redirect(&self) -> Option<(String, String)> {
        self.redirect
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .clone()
    }

    /// Requests a range of `url`, returning its body and the URL that
    /// finally answered after any redirects.
    fn open_range(
        &self,
        url: &str,
        start: u64,
        end: u64,
    ) -> Result<(HttpRangeReader, String), HttpError> {
        let range_header = format!("bytes={}-{}", start, end);
        let requested = end.saturating_sub(start).saturating_add(1);

        let response = self.agent.get(url).header("Range", &range_header).call()?;
        let final_url = response.get_uri().to_string();

        let status = response.status();
        if status == 200 && start > 0 {
            return Err(HttpError::RangeIgnored);
        }
        if status != 206 && status != 200 {
            return Err(HttpError::Status(status.as_u16()));
        }

        let reader = HttpRangeReader {
            reader: Box::new(response.into_body().into_reader()),
            remaining: requested,
        };
        Ok((reader, final_url))
    }

    /// Fetches `start..=end` of `url` into memory.
    ///
    /// The same cap and status handling as [`Self::fetch_range_reader`]
    /// apply.
    ///
    /// # Errors
    ///
    /// Returns the errors of [`Self::fetch_range_reader`], and
    /// [`HttpError::Io`] when reading the body fails.
    pub fn fetch_range(&self, url: &str, start: u64, end: u64) -> Result<Vec<u8>, HttpError> {
        let mut reader = self.fetch_range_reader(url, start, end)?;
        let mut buf = Vec::new();
        reader.read_to_end(&mut buf)?;
        Ok(buf)
    }

    /// Fetches each inclusive range in `ranges`, one request at a time.
    ///
    /// Each body is paired with its start offset rounded down to a multiple
    /// of `blocksize`. The ranges are expected to start on a block boundary,
    /// as those from [`byte_ranges_from_block_ranges`] do; otherwise the
    /// offset names a point before the body's first byte.
    ///
    /// # Errors
    ///
    /// Stops at and returns the first error from [`Self::fetch_range`].
    pub fn fetch_ranges(
        &self,
        url: &str,
        ranges: &[(u64, u64)],
        blocksize: usize,
    ) -> Result<Vec<(u64, Vec<u8>)>, HttpError> {
        let mut results = Vec::new();

        for &(start, end) in ranges {
            let data = self.fetch_range(url, start, end)?;
            let aligned_start = (start / blocksize as u64) * blocksize as u64;
            results.push((aligned_start, data));
        }

        Ok(results)
    }
}

/// Default gap threshold for range merging, 16 KiB.
///
/// Larger gaps save requests but chain together where needed blocks are
/// interleaved with known ones. On a real update with about half its
/// blocks reusable, a 256 KiB gap merged the whole file into one range and
/// fetched twice the bytes needed. At 16 KiB, real updates fetched within
/// about 2% of the minimum with far fewer requests than merging only
/// adjacent blocks.
pub const DEFAULT_RANGE_GAP_THRESHOLD: u64 = 16 * 1024;

/// Merge byte ranges to minimize HTTP requests.
///
/// `ranges` are inclusive and sorted by start, without overlap. Two neighbours
/// separated by at most `gap_threshold` bytes become one range that also
/// covers the gap, so a threshold of zero merges only ranges that touch.
pub fn merge_byte_ranges(ranges: &[(u64, u64)], gap_threshold: u64) -> Vec<(u64, u64)> {
    if ranges.len() <= 1 {
        return ranges.to_vec();
    }

    let mut merged = vec![ranges[0]];
    for &(start, end) in &ranges[1..] {
        let last = merged.last_mut().unwrap();
        let gap = start.saturating_sub(last.1 + 1);
        if gap <= gap_threshold {
            last.1 = end;
        } else {
            merged.push((start, end));
        }
    }
    merged
}

/// Converts block ranges into the byte ranges that hold them.
///
/// Each block range is half-open, from its first block to one past its last,
/// as [`BlockMatcher::needed_block_ranges`](crate::BlockMatcher::needed_block_ranges)
/// returns them. Each byte range is inclusive, ready for a `Range` header, and
/// the last one is clamped to `file_length` so a short final block is not
/// requested past the end of the file.
pub fn byte_ranges_from_block_ranges(
    block_ranges: &[(usize, usize)],
    blocksize: usize,
    file_length: u64,
) -> Vec<(u64, u64)> {
    block_ranges
        .iter()
        .map(|&(start_block, end_block)| {
            let start = start_block as u64 * blocksize as u64;
            let end =
                ((end_block as u64 * blocksize as u64).saturating_sub(1)).min(file_length - 1);
            (start, end)
        })
        .collect()
}

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

    /// A server that answers any request with far more data than asked
    /// for, which is what a hostile or broken origin does.
    fn overlong_server(body_len: usize) -> String {
        use std::io::Write;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            if let Ok((mut sock, _)) = listener.accept() {
                let mut req = [0u8; 1024];
                let _ = std::io::Read::read(&mut sock, &mut req);
                let hdr = format!(
                    "HTTP/1.1 206 Partial Content\r\nContent-Range: bytes 0-1023/{}\r\nContent-Length: {}\r\n\r\n",
                    body_len, body_len
                );
                let _ = sock.write_all(hdr.as_bytes());
                let chunk = vec![0u8; 64 * 1024];
                let mut sent = 0;
                while sent < body_len {
                    let n = chunk.len().min(body_len - sent);
                    if sock.write_all(&chunk[..n]).is_err() {
                        break;
                    }
                    sent += n;
                }
            }
        });
        format!("http://{}/f", addr)
    }

    /// A server that ignores `Range` and answers every request with `200`
    /// and the whole body, as a plain static file server without range
    /// support does.
    fn range_ignoring_server(body_len: usize) -> String {
        use std::io::Write;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            for mut sock in listener.incoming().flatten() {
                let mut req = [0u8; 1024];
                let _ = std::io::Read::read(&mut sock, &mut req);
                let hdr = format!(
                    "HTTP/1.1 200 OK\r\nContent-Length: {body_len}\r\nConnection: close\r\n\r\n"
                );
                let _ = sock.write_all(hdr.as_bytes());
                let _ = sock.write_all(&vec![0u8; body_len]);
            }
        });
        format!("http://{}/f", addr)
    }

    /// A server that answers every request with `status` and an empty body.
    fn status_server(status: &'static str) -> String {
        use std::io::Write;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            for mut sock in listener.incoming().flatten() {
                let mut req = [0u8; 1024];
                let _ = std::io::Read::read(&mut sock, &mut req);
                let _ = sock.write_all(
                    format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
                        .as_bytes(),
                );
            }
        });
        format!("http://{}/f", addr)
    }

    #[test]
    fn a_missing_file_is_a_permanent_error() {
        let err = HttpClient::new()
            .fetch_range(&status_server("404 Not Found"), 1024, 2047)
            .expect_err("a 404 must fail");
        assert!(
            matches!(err, HttpError::Status(404)),
            "unexpected error: {err}"
        );
        assert!(!err.is_transient());
    }

    #[test]
    fn a_busy_server_is_a_transient_error() {
        let err = HttpClient::new()
            .fetch_range(&status_server("503 Service Unavailable"), 1024, 2047)
            .expect_err("a 503 must fail");
        assert!(
            matches!(err, HttpError::Status(503)),
            "unexpected error: {err}"
        );
        assert!(err.is_transient());
    }

    #[test]
    fn a_refused_connection_is_a_transient_error() {
        let err = HttpClient::new()
            .fetch_range("http://127.0.0.1:1/f", 0, 1023)
            .expect_err("nothing listens on port 1");
        assert!(err.is_transient(), "unexpected error: {err:?}");
    }

    /// A keep-alive server that answers every range request with `206` and
    /// as many zero bytes as asked for, counting the connections it accepts.
    fn keep_alive_server() -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
        use std::io::{BufRead, Write};
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let connections = std::sync::Arc::new(AtomicUsize::new(0));
        let counter = connections.clone();
        std::thread::spawn(move || {
            for sock in listener.incoming().flatten() {
                counter.fetch_add(1, Ordering::SeqCst);
                std::thread::spawn(move || {
                    let mut reader = std::io::BufReader::new(sock.try_clone().unwrap());
                    let mut sock = sock;
                    loop {
                        let mut range = (0u64, 0u64);
                        loop {
                            let mut line = String::new();
                            if reader.read_line(&mut line).unwrap_or(0) == 0 {
                                return;
                            }
                            if line == "\r\n" {
                                break;
                            }
                            if let Some(spec) =
                                line.to_ascii_lowercase().strip_prefix("range: bytes=")
                            {
                                let (a, b) = spec.trim().split_once('-').unwrap();
                                range = (a.parse().unwrap(), b.parse().unwrap());
                            }
                        }
                        let len = range.1 - range.0 + 1;
                        let head = format!(
                            "HTTP/1.1 206 Partial Content\r\nContent-Length: {len}\r\nContent-Range: bytes {}-{}/1048576\r\n\r\n",
                            range.0, range.1
                        );
                        if sock.write_all(head.as_bytes()).is_err()
                            || sock.write_all(&vec![0u8; len as usize]).is_err()
                        {
                            return;
                        }
                    }
                });
            }
        });
        (format!("http://{addr}/f"), connections)
    }

    #[test]
    fn consecutive_range_requests_share_one_connection() {
        let (url, connections) = keep_alive_server();
        let client = HttpClient::new();
        for i in 0..5 {
            let start = i * 4096;
            let data = client
                .fetch_range(&url, start, start + 4095)
                .expect("fetch");
            assert_eq!(data.len(), 4096);
        }
        assert_eq!(
            connections.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "each range request opened its own connection"
        );
    }

    /// A server where `/f` redirects to `/signed/<generation>`, as a host
    /// redirects a download to a signed storage URL. Only the
    /// current generation is served, so raising it expires earlier targets.
    /// Returns the URL, the generation, and how many times `/f` was asked.
    fn redirecting_server() -> (
        String,
        std::sync::Arc<std::sync::atomic::AtomicUsize>,
        std::sync::Arc<std::sync::atomic::AtomicUsize>,
    ) {
        use std::io::{BufRead, Write};
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let generation = Arc::new(AtomicUsize::new(1));
        let redirects = Arc::new(AtomicUsize::new(0));
        let (current, asked) = (generation.clone(), redirects.clone());
        std::thread::spawn(move || {
            for sock in listener.incoming().flatten() {
                let mut reader = std::io::BufReader::new(sock.try_clone().unwrap());
                let mut sock = sock;
                let mut request = String::new();
                let _ = reader.read_line(&mut request);
                let mut range = (0u64, 0u64);
                loop {
                    let mut line = String::new();
                    if reader.read_line(&mut line).unwrap_or(0) == 0 || line == "\r\n" {
                        break;
                    }
                    if let Some(spec) = line.to_ascii_lowercase().strip_prefix("range: bytes=") {
                        let (a, b) = spec.trim().split_once('-').unwrap();
                        range = (a.parse().unwrap(), b.parse().unwrap());
                    }
                }
                let path = request.split_whitespace().nth(1).unwrap_or("").to_string();
                let now = current.load(Ordering::SeqCst);
                let response = if path == "/f" {
                    asked.fetch_add(1, Ordering::SeqCst);
                    format!(
                        "HTTP/1.1 302 Found\r\nLocation: /signed/{now}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                    )
                    .into_bytes()
                } else if path == format!("/signed/{now}") {
                    let len = range.1 - range.0 + 1;
                    let mut r = format!(
                        "HTTP/1.1 206 Partial Content\r\nContent-Length: {len}\r\nContent-Range: bytes {}-{}/1048576\r\nConnection: close\r\n\r\n",
                        range.0, range.1
                    )
                    .into_bytes();
                    r.extend((range.0..=range.1).map(|i| i as u8));
                    r
                } else {
                    b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_vec()
                };
                let _ = sock.write_all(&response);
            }
        });
        (format!("http://{addr}/f"), generation, redirects)
    }

    #[test]
    fn a_redirect_is_followed_once_for_many_ranges() {
        use std::sync::atomic::Ordering;
        let (url, _, redirects) = redirecting_server();
        let client = HttpClient::new();
        for i in 0..4u64 {
            let start = i * 1000;
            let data = client.fetch_range(&url, start, start + 99).expect("fetch");
            assert_eq!(
                data,
                (start..start + 100).map(|b| b as u8).collect::<Vec<_>>()
            );
        }
        assert_eq!(redirects.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn an_expired_redirect_target_is_resolved_again() {
        use std::sync::atomic::Ordering;
        let (url, generation, redirects) = redirecting_server();
        let client = HttpClient::new();
        client.fetch_range(&url, 0, 99).expect("first fetch");

        generation.store(2, Ordering::SeqCst);
        let data = client
            .fetch_range(&url, 500, 599)
            .expect("an expired target must fall back to the original URL");
        assert_eq!(data, (500..600u64).map(|b| b as u8).collect::<Vec<_>>());
        assert_eq!(redirects.load(Ordering::SeqCst), 2);

        client.fetch_range(&url, 700, 799).expect("fetch");
        assert_eq!(
            redirects.load(Ordering::SeqCst),
            2,
            "the new target was not kept"
        );
    }

    #[test]
    fn a_full_response_to_a_later_range_is_refused() {
        let url = range_ignoring_server(4096);
        let client = HttpClient::new();

        // From byte zero the whole body is the right data.
        assert_eq!(
            client.fetch_range(&url, 0, 1023).expect("fetch").len(),
            1024
        );

        // From anywhere else it is the wrong data, so it must not be read.
        let err = client
            .fetch_range(&url, 2048, 3071)
            .expect_err("a 200 for a later range must be refused");
        assert!(
            matches!(err, HttpError::RangeIgnored),
            "unexpected error: {err}"
        );
        assert!(!err.is_transient());
    }

    #[test]
    fn a_range_response_is_capped_at_what_was_requested() {
        // 1 KiB asked for, 8 MiB offered. Accepting the surplus lets any
        // origin decide how much memory the client spends.
        let url = overlong_server(8 * 1024 * 1024);
        let client = HttpClient::new();
        let data = client.fetch_range(&url, 0, 1023).expect("fetch");
        assert_eq!(
            data.len(),
            1024,
            "a range response must be capped at the requested length"
        );
    }

    #[test]
    fn the_default_client_bounds_reaching_a_host_but_not_the_transfer() {
        let timeouts = HttpClient::new().agent.config().timeouts();

        // Unbounded, a host that drops SYNs costs the kernel's full retry
        // schedule per resolved address, minutes at a time.
        assert_eq!(timeouts.connect, Some(CONNECT_TIMEOUT));
        assert_eq!(timeouts.resolve, Some(RESOLVE_TIMEOUT));

        // Deliberately unbounded: mirrors serving a multi-hundred-megabyte
        // image are often slow, and a cap here would abort a healthy but
        // sluggish transfer.
        assert_eq!(timeouts.global, None);
        assert_eq!(timeouts.per_call, None);
        assert_eq!(timeouts.recv_body, None);
    }

    #[test]
    fn a_supplied_agent_carries_its_own_policy() {
        // The point of `with_agent` is that the embedder's policy reaches
        // the transfer. A client built with an HTTPS-only agent must refuse
        // a plain-HTTP URL, where the default client would allow it.
        let strict = HttpClient::with_agent(
            ureq::Agent::config_builder()
                .https_only(true)
                .build()
                .new_agent(),
        );
        let err = strict
            .fetch_control_file("http://127.0.0.1:1/nothing.zsync")
            .expect_err("an HTTPS-only agent must refuse a plain-HTTP URL");
        let msg = err.to_string();
        assert!(
            msg.to_lowercase().contains("http"),
            "expected a scheme rejection, got: {msg}"
        );
    }

    #[test]
    fn test_byte_ranges_from_block_ranges() {
        let block_ranges = vec![(0, 2), (4, 6)];
        let byte_ranges = byte_ranges_from_block_ranges(&block_ranges, 1024, 10000);
        assert_eq!(byte_ranges, vec![(0, 2047), (4096, 6143)]);
    }

    #[test]
    fn test_byte_ranges_clamped_to_file_length() {
        let block_ranges = vec![(9, 10)];
        let byte_ranges = byte_ranges_from_block_ranges(&block_ranges, 1024, 9500);
        assert_eq!(byte_ranges, vec![(9216, 9499)]);
    }
}