incpush 0.1.3

Incrementally back up a big local folder to object storage (GCS/S3/Azure), uploading only changed files and preserving previous versions
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
//! End-to-end backup orchestration over a log-structured manifest.
//!
//! Each run:
//!   1. walks the source in canonical sorted order (sorted-DFS — no global sort);
//!   2. merge-joins it against the manifest's merged view ([`Lsm::current`]) to
//!      classify every path, keeping only the *change set* in memory;
//!   3. uploads the changed files;
//!   4. appends **one tiny segment** with just this run's changes + deletions —
//!      the whole manifest is never rewritten per run;
//!   5. compacts periodically once segments accumulate.
//!
//! Peak memory is `O(merge fan-in + largest directory + change set)`.

use anyhow::{Context, Result, bail};
use std::cmp::Ordering;
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Instant, SystemTime};

use futures::stream::{FuturesUnordered, StreamExt};
use serde::{Deserialize, Serialize};

use crate::backend::Backend;
use crate::delta::{
    DELTA_VERSION, DeltaBuilder, DeltaHeader, DeltaRecord, Head, decode_delta, delta_key,
    encode_delta, head_key, snapshot_key,
};
use crate::diff::FileRecord;
use crate::diff::{Decision, DiffMode, RESERVED_DIR, decide, hash_file, walk_source};
use crate::fcm::{Record, path_cmp};
use crate::lsm::Lsm;
use crate::util::human_size;

const TOOL: &str = concat!("incpush/", env!("CARGO_PKG_VERSION"));

/// Compact once the manifest accumulates more than this many segments.
const COMPACT_THRESHOLD: usize = 8;

/// Everything needed to run one backup.
pub struct Config {
    pub source: PathBuf,
    pub dest: String,
    pub mode: DiffMode,
    pub excludes: Vec<String>,
    pub concurrency: usize,
    pub retries: u32,
    pub print: bool,
    pub quiet: bool,
    pub reconcile: bool,
    /// Disable first-run adoption of pre-existing destination objects.
    pub no_adopt: bool,
    /// Skip honoring per-directory `.backupignore` files (they are honored by
    /// default; disabling avoids a per-directory probe — see the walk).
    pub no_backupignore: bool,
    pub snapshot_every: u32,
    pub zstd_level: i32,
}

/// Result counters for one run.
#[derive(Debug, Default, Clone)]
pub struct Summary {
    pub run: i64,
    pub total_files: u64,
    pub total_size: i64,
    pub uploaded_files: u64,
    pub uploaded_size: i64,
    pub touched: u64,
    pub deleted: u64,
    pub adopted: u64,
    pub failed: u64,
    pub snapshot: bool,
    pub elapsed: std::time::Duration,
}

#[derive(Debug, Default, Serialize, Deserialize)]
struct LocalState {
    last_run: i64,
}

/// A file selected for upload, with the record to commit on success.
struct Pending {
    rel_path: String,
    abs_path: PathBuf,
    size: i64,
    new_record: Record,
}

fn diff_mode_str(m: DiffMode) -> &'static str {
    match m {
        DiffMode::Mtime => "mtime",
        DiffMode::Hash => "hash",
        DiffMode::FullHash => "full-hash",
    }
}

fn now_rfc3339() -> String {
    humantime::format_rfc3339_seconds(SystemTime::now()).to_string()
}

fn read_state(path: &Path) -> i64 {
    std::fs::read(path)
        .ok()
        .and_then(|b| serde_json::from_slice::<LocalState>(&b).ok())
        .map(|s| s.last_run)
        .unwrap_or(0)
}

fn write_state(path: &Path, last_run: i64) -> Result<()> {
    let bytes = serde_json::to_vec_pretty(&LocalState { last_run })?;
    std::fs::write(path, bytes).with_context(|| format!("writing {}", path.display()))?;
    Ok(())
}

pub async fn run(cfg: Config) -> Result<Summary> {
    let started = Instant::now();
    let started_ts = now_rfc3339();

    let backend = Arc::new(Backend::from_url(&cfg.dest)?);
    let state_dir = cfg.source.join(RESERVED_DIR);
    let manifest_dir = state_dir.join("manifest");
    let state_path = state_dir.join("state.json");
    let lsm = Lsm::new(&manifest_dir);

    let remote_head = match backend.get_bytes(&head_key()).await? {
        Some(bytes) => Some(Head::decode(&bytes)?),
        None => None,
    };

    if !cfg.print {
        std::fs::create_dir_all(&manifest_dir)
            .with_context(|| format!("creating {}", manifest_dir.display()))?;
    }

    let last_run = ensure_local_manifest(
        &lsm,
        &state_path,
        &backend,
        remote_head.as_ref(),
        cfg.print,
        cfg.zstd_level,
    )
    .await?;
    let run = last_run + 1;
    let is_snapshot = run == 1 || (cfg.snapshot_every > 0 && run % cfg.snapshot_every as i64 == 0);

    // --- Bootstrap onto pre-existing remote data (automatic) -------------------
    // A "bootstrap" run is a genuine first backup (no local manifest, no remote
    // HEAD). If the destination already holds objects from another tool, we
    // reconcile against them instead of re-uploading everything. Listing an empty
    // destination is a single cheap call, so this is on by default; `--no-adopt`
    // forces a full re-upload.
    let bootstrap = remote_head.is_none() && last_run == 0 && !cfg.print;
    let adopt_map = if bootstrap && !cfg.no_adopt {
        let map = backend.list_data(!cfg.quiet).await?;
        if map.is_empty() {
            None
        } else {
            if !cfg.quiet {
                eprintln!(
                    "found {} existing object(s) in the destination; reusing those that match",
                    map.len()
                );
            }
            Some(map)
        }
    } else {
        None
    };

    // --- Walk (canonical sorted order) + merge-join classify -------------------
    let walk = walk_source(&cfg.source, &cfg.excludes, !cfg.no_backupignore)?;
    let mut summary = Summary {
        run,
        snapshot: is_snapshot,
        ..Default::default()
    };
    let mut segment: Vec<Record> = Vec::new(); // this run's change segment
    let mut pending: Vec<Pending> = Vec::new();
    let mut deletes: Vec<String> = Vec::new();
    classify(
        cfg.mode,
        cfg.reconcile,
        &cfg.source,
        lsm.current()?,
        walk,
        adopt_map.as_ref(),
        !cfg.quiet,
        &mut summary,
        &mut segment,
        &mut pending,
        &mut deletes,
    )?;

    // Checkpoint between the (silent) scan and the upload phase, so a big run
    // shows it made it through the walk before uploads start streaming.
    if !cfg.quiet && !cfg.print {
        let mut line = format!(
            "scanned {} files: {} to upload",
            summary.total_files,
            pending.len()
        );
        if summary.adopted > 0 {
            line.push_str(&format!(", {} adopted", summary.adopted));
        }
        if summary.deleted > 0 {
            line.push_str(&format!(", {} deleted", summary.deleted));
        }
        eprintln!("{line}");
    }

    // --- Print / dry-run -------------------------------------------------------
    if cfg.print {
        for p in &pending {
            if !cfg.quiet {
                println!("will upload {} ({})", p.rel_path, human_size(p.size));
            }
            summary.uploaded_files += 1;
            summary.uploaded_size += p.size;
        }
        summary.elapsed = started.elapsed();
        return Ok(summary);
    }

    // --- Upload changed files --------------------------------------------------
    let results = upload_all(&backend, &pending, cfg.concurrency, cfg.retries, cfg.quiet).await;
    let mut all_ok = true;
    let mut uploaded_records: Vec<Record> = Vec::new();
    for (i, ok) in results.iter().enumerate() {
        if *ok {
            summary.uploaded_files += 1;
            summary.uploaded_size += pending[i].size;
            let rec = pending[i].new_record.clone();
            uploaded_records.push(rec.clone());
            segment.push(rec);
        } else {
            // Not recorded -> the manifest keeps the old state, so a rerun retries.
            summary.failed += 1;
            all_ok = false;
        }
    }

    // --- Append this run's segment (only if something changed) -----------------
    if !segment.is_empty() {
        lsm.append_segment(&mut segment, cfg.zstd_level)?;
    }

    if !all_ok {
        summary.elapsed = started.elapsed();
        bail!(
            "{} upload(s) failed; manifest updated so a rerun resumes from here",
            summary.failed
        );
    }

    // --- Ship remote state: delta (or snapshot) + HEAD ------------------------
    let ended_ts = now_rfc3339();
    if is_snapshot {
        // Fold everything into a single base file and upload it as the snapshot.
        lsm.compact(cfg.zstd_level)?;
        let fcm_bytes = std::fs::read(lsm.base_file())
            .with_context(|| "reading compacted base for snapshot".to_string())?;
        backend.put_bytes(&snapshot_key(run), fcm_bytes).await?;
        let head = Head {
            latest_run: run,
            base_snapshot: run,
            deltas: Vec::new(),
            snapshot_every: cfg.snapshot_every,
            tool: TOOL.to_string(),
        };
        backend.put_bytes(&head_key(), head.encode()?).await?;
    } else {
        let mut builder = DeltaBuilder::new();
        for r in &uploaded_records {
            builder.upsert(r.path.clone(), r.size, r.mtime, r.crc32c);
        }
        for d in &deletes {
            builder.delete(d.clone());
        }
        let base_snapshot = remote_head.as_ref().map(|h| h.base_snapshot).unwrap_or(0);
        let header = DeltaHeader {
            v: DELTA_VERSION,
            run,
            base_snapshot,
            prev_run: last_run,
            started: started_ts,
            ended: ended_ts,
            tool: TOOL.to_string(),
            diff: diff_mode_str(cfg.mode).to_string(),
            upserts: builder.upserts(),
            deletes: builder.deletes(),
        };
        let bytes = encode_delta(&header, builder.records(), cfg.zstd_level)?;
        backend.put_bytes(&delta_key(run), bytes).await?;

        let mut deltas = remote_head.map(|h| h.deltas).unwrap_or_default();
        deltas.push(run);
        let head = Head {
            latest_run: run,
            base_snapshot,
            deltas,
            snapshot_every: cfg.snapshot_every,
            tool: TOOL.to_string(),
        };
        backend.put_bytes(&head_key(), head.encode()?).await?;

        // Keep the local segment count bounded.
        if lsm.segment_count()? > COMPACT_THRESHOLD {
            lsm.compact(cfg.zstd_level)?;
        }
    }

    write_state(&state_path, run)?;
    summary.elapsed = started.elapsed();
    Ok(summary)
}

/// Merge-join the manifest's merged view with the sorted walk (both in canonical
/// order), recording only the change set: `segment` (upserts/tombstones for the
/// new segment), `pending` (files to upload), and `deletes` (for the remote delta).
#[allow(clippy::too_many_arguments)]
/// Emit a progress message to stderr: redrawn in place on a TTY (so a running
/// counter stays on one line), or as discrete lines when piped/logged.
fn progress_tick(tty: bool, msg: &str) {
    if tty {
        eprint!("\r\x1b[K{msg}");
        let _ = std::io::stderr().flush();
    } else {
        eprintln!("{msg}");
    }
}

/// Clear the in-place progress line once a phase finishes (no-op when piped).
fn progress_done(tty: bool) {
    if tty {
        eprint!("\r\x1b[K");
        let _ = std::io::stderr().flush();
    }
}

#[allow(clippy::too_many_arguments)]
fn classify(
    mode: DiffMode,
    reconcile: bool,
    source: &Path,
    mut current: impl Iterator<Item = Result<Record>>,
    mut walk: impl Iterator<Item = Result<crate::diff::Entry>>,
    adopt: Option<&std::collections::HashMap<String, crate::backend::RemoteMeta>>,
    progress: bool,
    summary: &mut Summary,
    segment: &mut Vec<Record>,
    pending: &mut Vec<Pending>,
    deletes: &mut Vec<String>,
) -> Result<()> {
    enum Step {
        Old,
        Walk,
        Both,
    }
    // Scanning millions of files stat()s each one with no other output, so emit a
    // live count to stderr — otherwise the tool looks hung between listing and the
    // first upload. `total_files` counts local files seen (Walk + Both steps).
    let tty = std::io::stderr().is_terminal();
    let tick = |n: u64| {
        if progress && n % 10_000 == 0 {
            progress_tick(tty, &format!("scanning… {n} files"));
        }
    };

    let mut o = current.next().transpose()?;
    let mut w = walk.next().transpose()?;

    loop {
        let step = match (o.as_ref(), w.as_ref()) {
            (None, None) => break,
            (Some(_), None) => Step::Old,
            (None, Some(_)) => Step::Walk,
            (Some(orec), Some(e)) => match path_cmp(&orec.path, &e.rel_path) {
                Ordering::Less => Step::Old,
                Ordering::Greater => Step::Walk,
                Ordering::Equal => Step::Both,
            },
        };

        match step {
            // In manifest, gone from disk.
            Step::Old => {
                let orec = o.take().unwrap();
                if reconcile {
                    deletes.push(orec.path.clone());
                    segment.push(Record::tombstone(orec.path));
                    summary.deleted += 1;
                }
                // else: no tombstone -> the file stays tracked (non-destructive).
                o = current.next().transpose()?;
            }
            // On disk, not in manifest -> new file. During an adopt bootstrap it
            // may already exist remotely; otherwise it uploads.
            Step::Walk => {
                let e = w.take().unwrap();
                summary.total_files += 1;
                summary.total_size += e.size;
                tick(summary.total_files);
                // Adopt if the destination already has this path at the same size
                // and the local file wasn't modified after it was stored there.
                // Match on the decoded key so encoded remote keys still reconcile.
                let adopted = adopt
                    .and_then(|m| m.get(&crate::backend::decode_key(&e.rel_path)))
                    .is_some_and(|&(rsize, rmtime)| rsize == e.size as u64 && e.mtime <= rmtime);
                if adopted {
                    summary.adopted += 1;
                    segment.push(Record {
                        path: e.rel_path,
                        size: e.size,
                        mtime: e.mtime,
                        crc32c: None,
                    });
                } else {
                    enqueue_upload(mode, source, &e, pending)?;
                }
                w = walk.next().transpose()?;
            }
            // In both -> decide.
            Step::Both => {
                let orec = o.take().unwrap();
                let e = w.take().unwrap();
                summary.total_files += 1;
                summary.total_size += e.size;
                tick(summary.total_files);
                let prior = FileRecord {
                    size: orec.size,
                    mtime: orec.mtime,
                    crc32c: orec.crc32c,
                };
                let decision = decide(mode, Some(&prior), e.size, e.mtime, || {
                    hash_file(&e.abs_path)
                })?;
                match decision {
                    Decision::Skip => {} // unchanged: manifest already has it
                    Decision::Touch { crc32c } => {
                        summary.touched += 1;
                        segment.push(Record {
                            path: e.rel_path,
                            size: e.size,
                            mtime: e.mtime,
                            crc32c,
                        });
                    }
                    Decision::Upload { crc32c } => push_pending(source, e, crc32c, pending),
                }
                o = current.next().transpose()?;
                w = walk.next().transpose()?;
            }
        }
    }
    if progress {
        progress_done(tty);
    }
    Ok(())
}

fn enqueue_upload(
    mode: DiffMode,
    source: &Path,
    e: &crate::diff::Entry,
    pending: &mut Vec<Pending>,
) -> Result<()> {
    let decision = decide(mode, None, e.size, e.mtime, || hash_file(&e.abs_path))?;
    if let Decision::Upload { crc32c } = decision {
        push_pending(source, e.clone(), crc32c, pending);
    }
    Ok(())
}

fn push_pending(
    source: &Path,
    e: crate::diff::Entry,
    crc32c: Option<u32>,
    pending: &mut Vec<Pending>,
) {
    let abs = if e.abs_path.as_os_str().is_empty() {
        source.join(&e.rel_path)
    } else {
        e.abs_path
    };
    let new_record = Record {
        path: e.rel_path.clone(),
        size: e.size,
        mtime: e.mtime,
        crc32c,
    };
    pending.push(Pending {
        rel_path: e.rel_path,
        abs_path: abs,
        size: e.size,
        new_record,
    });
}

/// Open the local manifest, reconstructing it from the bucket (snapshot FCM +
/// deltas) when no local copy exists but remote state is present. Returns the
/// last completed run number.
async fn ensure_local_manifest(
    lsm: &Lsm,
    state_path: &Path,
    backend: &Backend,
    remote_head: Option<&Head>,
    print: bool,
    zstd_level: i32,
) -> Result<i64> {
    if !lsm.is_empty()? {
        return Ok(read_state(state_path));
    }
    if print {
        return Ok(0);
    }
    let Some(head) = remote_head else {
        return Ok(0); // first backup ever
    };

    // Download the base snapshot (an FCM file) and install it.
    let snap_key = snapshot_key(head.base_snapshot);
    let snap = backend
        .get_bytes(&snap_key)
        .await?
        .with_context(|| format!("HEAD references missing snapshot {snap_key}"))?;
    lsm.install_base(&snap)?;

    // Replay each remote delta as a local segment.
    for run in &head.deltas {
        let key = delta_key(*run);
        let body = backend
            .get_bytes(&key)
            .await?
            .with_context(|| format!("HEAD references missing delta {key}"))?;
        let (_h, records) = decode_delta(&body)?;
        let mut seg: Vec<Record> = records
            .into_iter()
            .map(|rec| match rec {
                DeltaRecord::Upsert {
                    path,
                    size,
                    mtime,
                    crc32c,
                } => Record {
                    path,
                    size,
                    mtime,
                    crc32c,
                },
                DeltaRecord::Delete { path } => Record::tombstone(path),
            })
            .collect();
        lsm.append_segment(&mut seg, zstd_level)?;
    }
    lsm.compact(zstd_level)?;

    write_state(state_path, head.latest_run)?;
    Ok(head.latest_run)
}

/// Upload every pending file with bounded concurrency and per-file retries.
async fn upload_all(
    backend: &Arc<Backend>,
    items: &[Pending],
    concurrency: usize,
    retries: u32,
    quiet: bool,
) -> Vec<bool> {
    let mut results = vec![false; items.len()];
    let mut inflight = FuturesUnordered::new();
    let mut next = 0;

    let spawn = |i: usize| {
        let backend = backend.clone();
        let key = items[i].rel_path.clone();
        let abs = items[i].abs_path.clone();
        let size = items[i].size;
        async move {
            let mut attempt = 0;
            loop {
                match backend.upload_file(&key, &abs).await {
                    Ok(()) => {
                        if !quiet {
                            println!("uploaded {} ({})", key, human_size(size));
                        }
                        return (i, true);
                    }
                    Err(e) => {
                        attempt += 1;
                        if attempt >= retries.max(1) {
                            eprintln!("failed to upload {key}: {e:#}");
                            return (i, false);
                        }
                        let backoff = std::time::Duration::from_millis(200 * (1 << attempt));
                        tokio::time::sleep(backoff).await;
                    }
                }
            }
        }
    };

    let cap = concurrency.max(1);
    while next < items.len() && inflight.len() < cap {
        inflight.push(spawn(next));
        next += 1;
    }
    while let Some((i, ok)) = inflight.next().await {
        results[i] = ok;
        if next < items.len() {
            inflight.push(spawn(next));
            next += 1;
        }
    }
    results
}