zsync-rs 0.2.2

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

use clap::Parser;
use zsync_rs::ZsyncAssembly;

#[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 (default: 256)
    #[arg(long, value_name = "KIB", default_value_t = 256)]
    range_gap: u64,

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

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 download callback and the main thread.
///
/// The library's callback is `Fn + Send + Sync` and owns its closure, so it
/// cannot hold a plain `&mut` to local state. A mutex-guarded reporter gives
/// the callback and the main thread one place to write without duplicating
/// the throttle logic.
struct Reporter {
    mode: Mode,
    started: Instant,
    last_emit: Option<Instant>,
    last_percent: i32,
    bar_drawn: bool,
    download_finished: bool,
}

impl Reporter {
    fn new(mode: Mode) -> Self {
        Self {
            mode,
            started: Instant::now(),
            last_emit: None,
            last_percent: -1,
            bar_drawn: false,
            download_finished: false,
        }
    }

    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 download progress event 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.download_finished {
            return;
        }
        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 => {
                let elapsed_ms = self.started.elapsed().as_millis();
                self.write_line(&format!(
                    "{{\"event\":\"progress\",\"phase\":\"download\",\"done_bytes\":{done},\"total_bytes\":{total},\"elapsed_ms\":{elapsed_ms}}}"
                ));
            }
            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 terminal download event, bypassing the throttle.
    ///
    /// A consumer must always see the completed count, even when the last
    /// block lands inside a throttle window. Human modes print it only when a
    /// download printed progress, and lines mode only when it would not repeat
    /// the last line.
    fn finish_download(&mut self, done: u64, total: u64) {
        if self.download_finished {
            return;
        }
        self.download_finished = true;

        match self.mode {
            Mode::Json => {
                let elapsed_ms = self.started.elapsed().as_millis();
                self.write_line(&format!(
                    "{{\"event\":\"progress\",\"phase\":\"download\",\"done_bytes\":{done},\"total_bytes\":{total},\"elapsed_ms\":{elapsed_ms},\"final\":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_error(&mut self, message: &str) {
        self.end_bar();
        if self.mode != Mode::Json {
            return;
        }
        self.write_line(&format!(
            "{{\"event\":\"error\",\"message\":\"{}\"}}",
            json_escape(message)
        ));
    }
}

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
}

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(|| {
        PathBuf::from(
            cli.url
                .trim_end_matches(".zsync")
                .rsplit('/')
                .next()
                .unwrap_or("output"),
        )
    });

    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 * 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());
        }
    }

    for input_path in &cli.input {
        match assembly.submit_source_file(input_path) {
            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
    if !cli.input.is_empty() && !assembly.is_complete() {
        match assembly.submit_self_referential() {
            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}"),
        }
    }

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

        loop {
            match assembly.download_missing_blocks() {
                Ok(0) => break,
                Ok(_) => {}
                Err(e) => {
                    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);
                }
            }
        }
    }

    if let Ok(mut r) = reporter.lock() {
        let (done, total) = assembly.progress();
        r.finish_download(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 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%"));
    }
}