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
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use clap::Parser;
use zsync_rs::ZsyncAssembly;
use zsync_rs::http::DEFAULT_RANGE_GAP_THRESHOLD;

#[derive(Parser)]
#[command(name = "zsync")]
#[command(about = "Efficient file transfer using rsync algorithm over HTTP")]
struct Cli {
    /// URL to .zsync control file
    #[arg(value_name = "URL")]
    url: String,

    /// Output filename
    #[arg(short, long, value_name = "FILE")]
    output: Option<PathBuf>,

    /// Source file(s) to use for local matching (can be specified multiple times)
    #[arg(short = 'i', long, value_name = "FILE")]
    input: Vec<PathBuf>,

    /// Gap threshold in KiB for merging HTTP range requests
    #[arg(long, value_name = "KIB", default_value_t = DEFAULT_RANGE_GAP_THRESHOLD / 1024)]
    range_gap: u64,

    /// Emit newline-delimited JSON progress events on stdout
    #[arg(long)]
    json: bool,

    /// Times to retry a download that failed on a network error, waiting
    /// 2 s, then 4 s, and so on
    #[arg(long, value_name = "N", default_value_t = 3)]
    retries: u32,
}

fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;
    const TB: u64 = GB * 1024;

    if bytes >= TB {
        format!("{:.2} TB", bytes as f64 / TB as f64)
    } else if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{bytes} B")
    }
}

fn format_pct(done: usize, total: usize) -> String {
    if total == 0 {
        return "100.00".to_string();
    }
    format!("{:.2}", done as f64 / total as f64 * 100.0)
}

/// How often a progress event may be emitted.
///
/// The library reports once per block, which is thousands of events for a
/// large file. Throttling here keeps terminal output readable and bounds the
/// volume a JSONL consumer has to parse. The library's own behaviour is
/// unchanged; this is presentation only.
const PROGRESS_INTERVAL: Duration = Duration::from_millis(100);

/// Width of the progress bar in characters, excluding the brackets.
const BAR_WIDTH: usize = 30;

/// Where progress goes and how it is drawn.
#[derive(Clone, Copy, PartialEq)]
enum Mode {
    /// A single bar redrawn in place, for a terminal.
    Bar,
    /// One line per update, for stderr redirected to a file or pipe.
    Lines,
    Json,
}

/// Serialises progress events from the library's callbacks and the main
/// thread.
///
/// The library's callbacks are `Fn + Send + Sync` and own their closures, so
/// they cannot hold a plain `&mut` to local state. A mutex-guarded reporter
/// gives the callbacks and the main thread one place to write without
/// duplicating the throttle logic.
///
/// Progress belongs to one phase at a time: a scan of each seed file, the
/// scan of the downloaded data for repeated blocks, then the download.
struct Reporter {
    mode: Mode,
    started: Instant,
    phase: &'static str,
    /// The file the phase works through, already escaped for JSON.
    file: Option<String>,
    /// The last values the library reported, whether or not they were shown.
    latest: Option<(u64, u64)>,
    last_emit: Option<Instant>,
    last_percent: i32,
    bar_drawn: bool,
    finished: bool,
}

impl Reporter {
    fn new(mode: Mode) -> Self {
        Self {
            mode,
            started: Instant::now(),
            phase: "download",
            file: None,
            latest: None,
            last_emit: None,
            last_percent: -1,
            bar_drawn: false,
            finished: false,
        }
    }

    /// Starts reporting a new phase, optionally naming the file it reads.
    fn begin(&mut self, phase: &'static str, file: Option<&Path>) {
        self.phase = phase;
        self.file = file.map(|f| json_escape(&f.display().to_string()));
        self.latest = None;
        self.last_emit = None;
        self.last_percent = -1;
        self.finished = false;
    }

    fn progress_json(&self, done: u64, total: u64, last: bool) -> String {
        let elapsed_ms = self.started.elapsed().as_millis();
        let file = self
            .file
            .as_ref()
            .map(|f| format!(",\"file\":\"{f}\""))
            .unwrap_or_default();
        let last = if last { ",\"final\":true" } else { "" };
        format!(
            "{{\"event\":\"progress\",\"phase\":\"{}\"{file},\"done_bytes\":{done},\"total_bytes\":{total},\"elapsed_ms\":{elapsed_ms}{last}}}",
            self.phase
        )
    }

    fn write_line(&self, line: &str) {
        let mut out = std::io::stdout().lock();
        // A closed consumer must not abort a running transfer.
        let _ = writeln!(out, "{line}");
        let _ = out.flush();
    }

    fn emit_start(&self, total_bytes: u64, total_blocks: usize, blocksize: usize) {
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!(
            "{{\"event\":\"start\",\"total_bytes\":{total_bytes},\"total_blocks\":{total_blocks},\"blocksize\":{blocksize}}}"
        ));
    }

    /// Emits a progress event for the current phase if the throttle allows
    /// it.
    ///
    /// Lines mode additionally drops an event that would repeat the previous
    /// whole percent, so a slow transfer does not print the same line twice.
    fn progress(&mut self, done: u64, total: u64) {
        if self.finished {
            return;
        }
        self.latest = Some((done, total));
        let now = Instant::now();
        if let Some(last) = self.last_emit
            && now.duration_since(last) < PROGRESS_INTERVAL
        {
            return;
        }

        let percent = whole_percent(done, total);
        if self.mode == Mode::Lines && percent == self.last_percent {
            return;
        }

        self.last_emit = Some(now);
        self.last_percent = percent;

        match self.mode {
            Mode::Json => self.write_line(&self.progress_json(done, total, false)),
            Mode::Bar => self.draw_bar(done, total),
            Mode::Lines => {
                eprintln!(
                    "  {} / {} ({percent}%)",
                    format_bytes(done),
                    format_bytes(total)
                );
            }
        }
    }

    fn draw_bar(&mut self, done: u64, total: u64) {
        // `\x1b[K` clears what a longer previous draw left past the cursor.
        eprint!("\r{}\x1b[K", render_bar(done, total));
        self.bar_drawn = true;
    }

    /// Moves past a drawn bar so the next message starts on its own line.
    fn end_bar(&mut self) {
        if self.bar_drawn {
            eprintln!();
            self.bar_drawn = false;
        }
    }

    /// Emits the phase's terminal event, bypassing the throttle.
    ///
    /// A consumer must always see the completed count, even when the last
    /// update lands inside a throttle window. Human modes print it only when
    /// the phase printed progress, and lines mode only when it would not
    /// repeat the last line.
    fn finish(&mut self, done: u64, total: u64) {
        if self.finished {
            return;
        }
        self.finished = true;

        match self.mode {
            Mode::Json => self.write_line(&self.progress_json(done, total, true)),
            Mode::Bar => {
                if self.bar_drawn {
                    self.draw_bar(done, total);
                    self.end_bar();
                }
            }
            Mode::Lines => {
                let percent = whole_percent(done, total);
                if self.last_emit.is_some() && percent != self.last_percent {
                    eprintln!(
                        "  {} / {} ({percent}%)",
                        format_bytes(done),
                        format_bytes(total)
                    );
                }
            }
        }
    }

    fn emit_phase(&self, name: &str) {
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!("{{\"event\":\"phase\",\"phase\":\"{name}\"}}"));
    }

    fn emit_done(&self, path: &str) {
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!(
            "{{\"event\":\"done\",\"path\":\"{}\"}}",
            json_escape(path)
        ));
    }

    fn emit_retry(&mut self, attempt: u32, retries: u32, delay: Duration, message: &str) {
        self.end_bar();
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!(
            "{{\"event\":\"retry\",\"attempt\":{attempt},\"retries\":{retries},\"delay_ms\":{},\"message\":\"{}\"}}",
            delay.as_millis(),
            json_escape(message)
        ));
    }

    fn emit_error(&mut self, message: &str) {
        self.end_bar();
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!(
            "{{\"event\":\"error\",\"message\":\"{}\"}}",
            json_escape(message)
        ));
    }
}

impl Reporter {
    /// Ends a scan with the last values the library reported, or silently
    /// when it reported none because the file was too small to scan.
    fn finish_scan(&mut self) {
        match self.latest {
            Some((done, total)) => self.finish(done, total),
            None => self.finished = true,
        }
    }
}

fn whole_percent(done: u64, total: u64) -> i32 {
    done.saturating_mul(100).checked_div(total).unwrap_or(100) as i32
}

fn render_bar(done: u64, total: u64) -> String {
    let percent = whole_percent(done, total).clamp(0, 100);
    let filled = percent as usize * BAR_WIDTH / 100;
    format!(
        "  [{}{}] {percent:>3}%  {} / {}",
        "#".repeat(filled),
        " ".repeat(BAR_WIDTH - filled),
        format_bytes(done),
        format_bytes(total)
    )
}

/// Escapes a string for embedding in a JSON string literal.
///
/// Handles what a path or error message can contain: quote, backslash, and
/// control characters. Everything else passes through as UTF-8, which is
/// already valid JSON.
fn json_escape(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for ch in input.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

/// The output name for `url` when none is given: its last path segment,
/// without any query, fragment or `.zsync` suffix.
fn default_output(url: &str) -> PathBuf {
    let path = url.split(['?', '#']).next().unwrap_or(url);
    let name = path.rsplit('/').next().unwrap_or(path);
    let name = name.strip_suffix(".zsync").unwrap_or(name);
    PathBuf::from(if name.is_empty() { "output" } else { name })
}

fn main() {
    let cli = Cli::parse();
    let mode = if cli.json {
        Mode::Json
    } else if std::io::stderr().is_terminal() {
        Mode::Bar
    } else {
        Mode::Lines
    };

    let output_path = cli.output.unwrap_or_else(|| default_output(&cli.url));

    let reporter = Arc::new(Mutex::new(Reporter::new(mode)));

    let mut assembly = match ZsyncAssembly::from_url(&cli.url, &output_path) {
        Ok(a) => a,
        Err(e) => {
            let msg = format!("Error initializing: {e}");
            if let Ok(mut r) = reporter.lock() {
                r.emit_error(&msg);
            }
            eprintln!("{msg}");
            std::process::exit(1);
        }
    };

    assembly.set_range_gap_threshold(cli.range_gap.saturating_mul(1024));

    {
        let (_, total_bytes) = assembly.progress();
        let (_, total_blocks) = assembly.block_stats();
        if let Ok(r) = reporter.lock() {
            r.emit_start(total_bytes, total_blocks, assembly.blocksize());
        }
    }

    let scan_reporter = Arc::clone(&reporter);
    assembly.set_scan_progress_callback(move |done, total| {
        if let Ok(mut r) = scan_reporter.lock() {
            r.progress(done, total);
        }
    });

    for input_path in &cli.input {
        eprintln!("Scanning {}...", input_path.display());
        if let Ok(mut r) = reporter.lock() {
            r.begin("scan", Some(input_path));
        }
        let result = assembly.submit_source_file(input_path);
        if let Ok(mut r) = reporter.lock() {
            r.finish_scan();
            r.end_bar();
        }
        match result {
            Ok(blocks) => {
                let (done, total) = assembly.block_stats();
                eprintln!(
                    "Matched {blocks} blocks from {} ({}%)",
                    input_path.display(),
                    format_pct(done, total)
                );
            }
            Err(e) => eprintln!("Warning: failed to read {}: {e}", input_path.display()),
        }
    }

    // Self-referential scan: the temp file may contain duplicate target
    // blocks. It holds nothing until a seed has matched a block.
    if assembly.block_stats().0 > 0 && !assembly.is_complete() {
        eprintln!("Scanning for repeated blocks...");
        if let Ok(mut r) = reporter.lock() {
            r.begin("self_scan", None);
        }
        let result = assembly.submit_self_referential();
        if let Ok(mut r) = reporter.lock() {
            r.finish_scan();
            r.end_bar();
        }
        match result {
            Ok(0) => {}
            Ok(blocks) => {
                let (done, total) = assembly.block_stats();
                eprintln!(
                    "Matched {blocks} additional blocks from self-reference ({}%)",
                    format_pct(done, total)
                );
            }
            Err(e) => eprintln!("Warning: self-referential scan failed: {e}"),
        }
    }

    if let Ok(mut r) = reporter.lock() {
        r.begin("download", None);
    }

    let (done_bytes, total_bytes) = assembly.progress();
    let (done_blocks, total_blocks) = assembly.block_stats();
    let need_bytes = total_bytes - done_bytes;

    eprintln!(
        "Target: {} ({} blocks) - {}% complete",
        format_bytes(total_bytes),
        total_blocks,
        format_pct(done_blocks, total_blocks)
    );
    eprintln!("Need to download: {}", format_bytes(need_bytes));

    if !assembly.is_complete() {
        eprintln!("Downloading missing blocks...");

        let callback_reporter = Arc::clone(&reporter);
        assembly.set_progress_callback(move |done, total| {
            if let Ok(mut r) = callback_reporter.lock() {
                r.progress(done, total);
            }
        });

        // Blocks already written stay known, so a retry fetches only what is
        // still missing. The count resets whenever an attempt made progress,
        // so a long download on a flaky link is not capped at a few drops.
        let mut failures = 0;
        let mut known_at_failure = assembly.block_stats().0;
        loop {
            match assembly.download_missing_blocks() {
                Ok(0) => break,
                Ok(_) => {}
                Err(e) => {
                    let known = assembly.block_stats().0;
                    if known > known_at_failure {
                        failures = 0;
                    }
                    known_at_failure = known;

                    if e.is_transient() && failures < cli.retries {
                        failures += 1;
                        let delay = Duration::from_secs(2u64.saturating_pow(failures).min(60));
                        let msg = format!(
                            "Download error: {e}; retrying in {} s ({failures}/{})",
                            delay.as_secs(),
                            cli.retries
                        );
                        if let Ok(mut r) = reporter.lock() {
                            r.emit_retry(failures, cli.retries, delay, &msg);
                        }
                        eprintln!("{msg}");
                        std::thread::sleep(delay);
                        continue;
                    }

                    let msg = format!("Download error: {e}");
                    if let Ok(mut r) = reporter.lock() {
                        r.emit_error(&msg);
                    }
                    eprintln!("{msg}");
                    // `exit` skips destructors, and dropping removes the temp file.
                    drop(assembly);
                    std::process::exit(1);
                }
            }
        }
    }

    // Downloading stops once a pass adds nothing, so blocks still missing
    // here arrived but did not match their checksums.
    if !assembly.is_complete() {
        let (known, total) = assembly.block_stats();
        let msg = format!(
            "Download error: {} of {total} blocks from the server did not match the control file, \
             so it may be serving a different version of the file",
            total - known
        );
        if let Ok(mut r) = reporter.lock() {
            r.emit_error(&msg);
        }
        eprintln!("{msg}");
        drop(assembly);
        std::process::exit(1);
    }

    if let Ok(mut r) = reporter.lock() {
        let (done, total) = assembly.progress();
        r.finish(done, total);
        r.emit_phase("verify");
    }

    eprintln!("Verifying checksum...");
    if let Err(e) = assembly.complete() {
        let msg = format!("Error: {e}");
        if let Ok(mut r) = reporter.lock() {
            r.emit_error(&msg);
        }
        eprintln!("{msg}");
        std::process::exit(1);
    }

    if let Ok(r) = reporter.lock() {
        r.emit_done(&output_path.display().to_string());
    }
    eprintln!("Done: {}", output_path.display());
}

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

    #[test]
    fn default_output_is_the_last_segment_without_the_suffix() {
        let name = |url| default_output(url).display().to_string();
        assert_eq!(name("https://h/a/app.AppImage.zsync"), "app.AppImage");
        assert_eq!(name("https://h/a/app.zsync?sig=x/y&e=1"), "app");
        assert_eq!(name("https://h/a/app.zsync#part"), "app");
        assert_eq!(name("https://h/a/"), "output");
    }

    #[test]
    fn json_escape_covers_what_a_path_or_message_can_hold() {
        assert_eq!(json_escape(r#"a"b"#), r#"a\"b"#);
        assert_eq!(json_escape(r"C:\dir\f.bin"), r"C:\\dir\\f.bin");
        assert_eq!(json_escape("line\nnext\ttab\r"), r"line\nnext\ttab\r");
        assert_eq!(json_escape("\u{1}"), r"\u0001");
        assert_eq!(json_escape("ünïcode"), "ünïcode");
    }

    #[test]
    fn bar_fills_in_proportion_to_progress() {
        assert_eq!(
            render_bar(0, 1000),
            format!("  [{}]   0%  0 B / 1000 B", " ".repeat(BAR_WIDTH))
        );
        assert_eq!(
            render_bar(500, 1000),
            format!(
                "  [{}{}]  50%  500 B / 1000 B",
                "#".repeat(BAR_WIDTH / 2),
                " ".repeat(BAR_WIDTH - BAR_WIDTH / 2)
            )
        );
        assert_eq!(
            render_bar(1000, 1000),
            format!("  [{}] 100%  1000 B / 1000 B", "#".repeat(BAR_WIDTH))
        );
    }

    #[test]
    fn bar_treats_an_empty_target_as_complete() {
        assert!(render_bar(0, 0).contains("100%"));
    }
}