zc2 0.0.45

P2P compute broker with credit-based billing, WAL, and broker mesh support
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Opt-in periodic self-update for `zc broker` (`ZAKURO_AUTO_UPDATE=1`).
//!
//! LXD brokers run under systemd (`Restart=always`) from `/usr/local/bin/zc`
//! and used to fall behind: newer peers refuse a broker older than their own
//! version. When enabled, one background thread reads the crates.io sparse
//! index for `zc2` every interval. For a strictly newer, non-yanked release it
//! runs `cargo install zc2 --version X --locked` into a scratch root next to
//! the running executable WHILE the broker keeps serving, checks the built
//! binary runs and reports exactly X, waits until the broker is idle (no
//! deadline: the binary is already built), atomically renames it over the
//! running executable and exits with [`RESTART_EXIT_CODE`] so systemd starts
//! it. OFF unless `ZAKURO_AUTO_UPDATE` is `1|true|yes|on`: k8s fleets get
//! their image from CD and must never use it. `zc update` (the manual path)
//! still uses the release mirror and is unaffected.

use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use colored::Colorize;

use super::BrokerState;
use crate::update::{self, FetchError, Fetcher};

pub const ENV_ENABLE: &str = "ZAKURO_AUTO_UPDATE";
pub const ENV_INTERVAL: &str = "ZAKURO_AUTO_UPDATE_INTERVAL";
pub const ENV_INDEX: &str = "ZAKURO_AUTO_UPDATE_INDEX";
pub const ENV_CARGO: &str = "ZAKURO_CARGO";
/// Sparse-index entry for `zc2` (3-character names live under `3/<first char>/`).
pub const DEFAULT_INDEX_URL: &str = "https://index.crates.io/3/z/zc2";
pub const CRATE_NAME: &str = "zc2";
pub const DEFAULT_INTERVAL_SECS: u64 = 600;
pub const MIN_INTERVAL_SECS: u64 = 300;
/// First check happens no sooner than this after startup.
const MIN_FIRST_DELAY_SECS: u64 = 60;
/// Idle must hold on this many consecutive polls...
const IDLE_POLLS_REQUIRED: u32 = 3;
/// ...taken this far apart.
const IDLE_POLL_SECS: u64 = 5;
/// Longest a `cargo install` may run.
const BUILD_TIMEOUT: Duration = Duration::from_secs(60 * 60);
/// Exit code asking systemd to restart us into the new binary (EX_TEMPFAIL).
pub const RESTART_EXIT_CODE: i32 = 75;

/// Parsed configuration.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
    pub enabled: bool,
    pub interval_secs: u64,
}

/// Seconds from `600`, `90s`, `10m` or `2h`. Pure.
pub fn parse_interval(v: &str) -> Option<u64> {
    let v = v.trim();
    let (num, mult) = match v.chars().last()? {
        's' | 'S' => (&v[..v.len() - 1], 1),
        'm' | 'M' => (&v[..v.len() - 1], 60),
        'h' | 'H' => (&v[..v.len() - 1], 3600),
        _ => (v, 1),
    };
    num.trim().parse::<u64>().ok()?.checked_mul(mult)
}

/// Parse the two env values. Pure.
pub fn parse_config(enable: Option<&str>, interval: Option<&str>) -> Config {
    let enabled = enable.is_some_and(|v| {
        matches!(
            v.trim().to_ascii_lowercase().as_str(),
            "1" | "true" | "yes" | "on"
        )
    });
    let interval_secs = interval
        .and_then(parse_interval)
        .unwrap_or(DEFAULT_INTERVAL_SECS)
        .max(MIN_INTERVAL_SECS);
    Config {
        enabled,
        interval_secs,
    }
}

pub fn config_from_env() -> Config {
    parse_config(
        std::env::var(ENV_ENABLE).ok().as_deref(),
        std::env::var(ENV_INTERVAL).ok().as_deref(),
    )
}

/// The sparse-index URL: https only (http for 127.0.0.1/localhost, tests). Pure.
pub fn normalize_index_url(raw: &str) -> Result<String, String> {
    let u = raw.trim();
    let rest = if let Some(r) = u.strip_prefix("https://") {
        r
    } else if let Some(r) = u.strip_prefix("http://") {
        let host = r.split(['/', ':']).next().unwrap_or("");
        if host != "127.0.0.1" && host != "localhost" {
            return Err(format!("{ENV_INDEX} must be https:// (got {raw:?})"));
        }
        r
    } else {
        return Err(format!("{ENV_INDEX} must be an https:// URL (got {raw:?})"));
    };
    if rest.is_empty() || rest.starts_with('/') {
        return Err(format!("{ENV_INDEX} has no host (got {raw:?})"));
    }
    Ok(u.to_string())
}

fn index_url_from_env() -> Result<String, String> {
    match std::env::var(ENV_INDEX) {
        Ok(v) if !v.trim().is_empty() => normalize_index_url(&v),
        _ => Ok(DEFAULT_INDEX_URL.to_string()),
    }
}

/// The highest non-yanked, non-prerelease version in a sparse-index body
/// (newline-delimited JSON). Malformed lines are ignored. Pure.
pub fn parse_sparse_index(body: &[u8]) -> Option<String> {
    let text = String::from_utf8_lossy(body);
    let mut best: Option<((u64, u64, u64), String)> = None;
    for line in text.lines() {
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        let Some(vers) = v.get("vers").and_then(|x| x.as_str()) else {
            continue;
        };
        if v.get("yanked").and_then(|x| x.as_bool()).unwrap_or(false) || vers.contains('-') {
            continue;
        }
        let parts: Vec<&str> = vers.split('.').collect();
        if parts.len() != 3 {
            continue;
        }
        let Some(t) = crate::build_id::version_triple(vers) else {
            continue;
        };
        if best.as_ref().is_none_or(|(b, _)| t > *b) {
            best = Some((t, vers.to_string()));
        }
    }
    best.map(|(_, v)| v)
}

/// Latest published version from the index, through the injectable fetcher.
pub fn check_latest(fetch: &dyn Fetcher, index_url: &str) -> Result<String, String> {
    match fetch.get(index_url) {
        Ok(body) => parse_sparse_index(&body)
            .ok_or_else(|| format!("{index_url}: no usable (non-yanked, stable) version")),
        Err(FetchError::Status(s)) => Err(format!("{index_url}: HTTP {s}")),
        Err(FetchError::Transport(e)) => Err(format!("{index_url}: {e}")),
    }
}

/// Where `cargo` is: `ZAKURO_CARGO`, else on PATH, else `$HOME/.cargo/bin/cargo`.
/// `exists` is injected for tests. Pure.
pub fn resolve_cargo(
    env_cargo: Option<&str>,
    path_var: Option<&str>,
    home: Option<&str>,
    exists: &dyn Fn(&Path) -> bool,
) -> Option<PathBuf> {
    if let Some(c) = env_cargo.map(str::trim).filter(|c| !c.is_empty()) {
        return Some(PathBuf::from(c));
    }
    if let Some(p) = path_var {
        for dir in p.split(':').filter(|d| !d.is_empty()) {
            let c = Path::new(dir).join("cargo");
            if exists(&c) {
                return Some(c);
            }
        }
    }
    let c = Path::new(home?).join(".cargo/bin/cargo");
    exists(&c).then_some(c)
}

fn cargo_from_env() -> Result<PathBuf, String> {
    resolve_cargo(
        std::env::var(ENV_CARGO).ok().as_deref(),
        std::env::var("PATH").ok().as_deref(),
        std::env::var("HOME").ok().as_deref(),
        &|p| p.is_file(),
    )
    .ok_or_else(|| {
        format!(
            "cargo not found: install rustup (https://rustup.rs) or set {ENV_CARGO}; will retry at the next check"
        )
    })
}

/// True only when `latest` is strictly newer than `current`; never a
/// downgrade or a reinstall. An unparseable version is not newer.
pub fn is_newer_version(latest: &str, current: &str) -> bool {
    match (
        crate::build_id::version_triple(latest),
        crate::build_id::version_triple(current),
    ) {
        (Some(l), Some(c)) => l > c,
        _ => false,
    }
}

/// The idle decision. Pure.
pub fn is_idle(in_flight: usize, local_worker_active: u64, settlement_pending: usize) -> bool {
    in_flight == 0 && local_worker_active == 0 && settlement_pending == 0
}

/// Snapshot for `/health`.
#[derive(Debug, Clone, Default)]
struct Status {
    enabled: bool,
    interval_secs: u64,
    last_check_unix: Option<u64>,
    latest_seen: Option<String>,
    last_error: Option<String>,
    building: Option<String>,
}

static STATUS: Mutex<Status> = Mutex::new(Status {
    enabled: false,
    interval_secs: DEFAULT_INTERVAL_SECS,
    last_check_unix: None,
    latest_seen: None,
    last_error: None,
    building: None,
});

fn with_status(f: impl FnOnce(&mut Status)) {
    if let Ok(mut s) = STATUS.lock() {
        f(&mut s);
    }
}

/// The `auto_update` object for `GET /health`.
pub fn health_json() -> serde_json::Value {
    let s = STATUS.lock().map(|s| s.clone()).unwrap_or_default();
    serde_json::json!({
        "enabled": s.enabled,
        "source": "crates.io",
        "interval_secs": s.interval_secs,
        "last_check_unix": s.last_check_unix,
        "latest_seen": s.latest_seen,
        "last_error": s.last_error,
        "building": s.building,
    })
}

fn now_unix() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

/// Cheap jitter without a rand dependency: sub-second clock noise mixed with
/// the pid, so brokers started together still spread out. In `[0, bound)`.
fn jitter(bound: u64) -> u64 {
    if bound == 0 {
        return 0;
    }
    let n = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    let mut x = n ^ ((std::process::id() as u64) << 32) ^ 0x9E37_79B9_7F4A_7C15;
    x ^= x >> 33;
    x = x.wrapping_mul(0xFF51_AFD7_ED55_8CCD);
    x ^= x >> 33;
    x % bound
}

fn log(msg: &str) {
    println!("  {} {}", "[AUTO-UPDATE]".cyan(), msg);
}

fn log_warn(msg: &str) {
    eprintln!("  {} {}", "[AUTO-UPDATE]".yellow(), msg);
}

type VerifyFn = dyn Fn(&[u8], &str) -> Result<(), String>;

/// Everything one check cycle touches, injected so it is testable.
pub struct Cycle<'a> {
    pub fetch: &'a dyn Fetcher,
    pub index_url: &'a str,
    pub current: &'a str,
    /// Build version X and return the built binary's bytes (cleans up after itself).
    pub build: &'a dyn Fn(&str) -> Result<Vec<u8>, String>,
    /// Refuse a binary that does not run or does not report exactly X.
    pub verify: &'a VerifyFn,
    /// Is the broker idle right now?
    pub idle: &'a dyn Fn() -> bool,
    pub sleep: &'a dyn Fn(Duration),
    /// Atomically replace the running executable.
    pub install: &'a dyn Fn(&[u8]) -> Result<(), String>,
}

/// What one cycle did.
#[derive(Debug, PartialEq, Eq)]
pub enum CycleResult {
    UpToDate(String),
    Installed(String),
    BuildFailed(String),
    VerifyFailed(String),
    InstallFailed(String),
    CheckFailed(String),
}

fn fail(msg: String) -> String {
    with_status(|s| s.last_error = Some(msg.clone()));
    log_warn(&msg);
    msg
}

/// One check: read the index; if strictly newer, build, verify, wait for idle
/// (no deadline) and install.
pub fn run_cycle(c: &Cycle) -> CycleResult {
    let latest = match check_latest(c.fetch, c.index_url) {
        Ok(v) => v,
        Err(e) => {
            with_status(|s| s.last_check_unix = Some(now_unix()));
            return CycleResult::CheckFailed(fail(format!("check failed: {e}")));
        }
    };
    with_status(|s| {
        s.last_check_unix = Some(now_unix());
        s.latest_seen = Some(latest.clone());
        s.last_error = None;
    });
    if !is_newer_version(&latest, c.current) {
        log(&format!(
            "running {}, latest {latest} on crates.io: up to date",
            c.current
        ));
        return CycleResult::UpToDate(latest);
    }
    log(&format!(
        "running {}, latest {latest} on crates.io: newer, building (cargo install)",
        c.current
    ));
    with_status(|s| s.building = Some(latest.clone()));
    let built = (c.build)(&latest);
    with_status(|s| s.building = None);
    let bytes = match built {
        Ok(b) => b,
        Err(e) => {
            return CycleResult::BuildFailed(fail(format!(
                "build of {latest} failed: {e}; will retry at the next check"
            )))
        }
    };
    if let Err(e) = (c.verify)(&bytes, &latest) {
        return CycleResult::VerifyFailed(fail(format!(
            "built {latest} refused: {e}; will retry at the next check"
        )));
    }
    log(&format!("built {latest}, waiting for idle to install"));
    wait_until_idle(c.idle, c.sleep);
    match (c.install)(&bytes) {
        Ok(()) => CycleResult::Installed(latest),
        Err(e) => CycleResult::InstallFailed(fail(format!(
            "install of {latest} failed: {e}; will retry at the next check"
        ))),
    }
}

/// Block until `idle` holds on IDLE_POLLS_REQUIRED consecutive polls, with no
/// deadline: the new binary is already built, so restarting is all that is left.
pub fn wait_until_idle(idle: &dyn Fn() -> bool, sleep: &dyn Fn(Duration)) {
    let mut streak = 0;
    loop {
        if idle() {
            streak += 1;
            if streak >= IDLE_POLLS_REQUIRED {
                return;
            }
        } else {
            streak = 0;
        }
        sleep(Duration::from_secs(IDLE_POLL_SECS));
    }
}

/// Removes the scratch root on every path.
struct RootGuard(PathBuf);
impl Drop for RootGuard {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

/// Never two builds at once.
static BUILDING: AtomicBool = AtomicBool::new(false);
struct BuildSlot;
impl BuildSlot {
    fn take() -> Option<Self> {
        BUILDING
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .ok()
            .map(|_| BuildSlot)
    }
}
impl Drop for BuildSlot {
    fn drop(&mut self) {
        BUILDING.store(false, Ordering::SeqCst);
    }
}

/// `cargo install zc2 --version X --locked` into `<exe_dir>/.zc-auto-update-X`;
/// returns the built binary's bytes. The root is removed on every path.
pub fn build_from_crates(version: &str) -> Result<Vec<u8>, String> {
    let _slot = BuildSlot::take().ok_or("a build is already running")?;
    let cargo = cargo_from_env()?;
    let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    let dir = exe.parent().ok_or("executable has no directory")?;
    if !update::dir_writable(dir) {
        return Err(format!("{} is not writable", dir.display()));
    }
    let root = dir.join(format!(".zc-auto-update-{version}"));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).map_err(|e| format!("create {}: {e}", root.display()))?;
    let _guard = RootGuard(root.clone());
    let mut child = std::process::Command::new(&cargo)
        .args(["install", CRATE_NAME, "--version", version])
        .args(["--locked", "--force", "--quiet", "--root"])
        .arg(&root)
        .env("CARGO_TERM_COLOR", "never")
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .map_err(|e| format!("could not run {}: {e}", cargo.display()))?;
    let mut stderr = child.stderr.take();
    let reader = std::thread::spawn(move || {
        use std::io::Read;
        let mut buf = Vec::new();
        if let Some(s) = stderr.as_mut() {
            let _ = s.take(1 << 20).read_to_end(&mut buf);
            // Drain the rest so cargo never blocks on a full pipe.
            let _ = std::io::copy(s, &mut std::io::sink());
        }
        buf
    });
    let deadline = std::time::Instant::now() + BUILD_TIMEOUT;
    let status = loop {
        match child.try_wait() {
            Ok(Some(st)) => break Ok(st),
            Ok(None) if std::time::Instant::now() < deadline => {
                std::thread::sleep(Duration::from_secs(1));
            }
            Ok(None) => {
                let _ = child.kill();
                let _ = child.wait();
                break Err("timed out after 60 minutes".to_string());
            }
            Err(e) => break Err(format!("wait: {e}")),
        }
    };
    let err_text = reader.join().unwrap_or_default();
    let status = status?;
    if !status.success() {
        let text = String::from_utf8_lossy(&err_text);
        let tail: String = text
            .chars()
            .rev()
            .take(2000)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        return Err(format!(
            "cargo install exited with {status}: {}",
            tail.trim()
        ));
    }
    let bin = root.join("bin").join("zc");
    std::fs::read(&bin).map_err(|e| format!("built binary {}: {e}", bin.display()))
}

/// The real verify: it runs, and reports exactly `version`.
fn verify_binary(bytes: &[u8], version: &str) -> Result<(), String> {
    let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    if !update::binary_runs(&exe, bytes) {
        return Err("the built binary does not run on this host".into());
    }
    match update::binary_version(&exe, bytes) {
        Some(v) if v == version => Ok(()),
        Some(v) => Err(format!("it reports version {v}, expected {version}")),
        None => Err("could not read its version".into()),
    }
}

fn install_binary(bytes: &[u8]) -> Result<(), String> {
    let exe = std::env::current_exe().map_err(|e| format!("current_exe: {e}"))?;
    update::replace_binary_atomic(&exe, bytes).map_err(|e| e.to_string())
}

/// Spawn the updater thread when enabled. Never panics the broker.
pub fn spawn(state: Arc<BrokerState>) {
    let cfg = config_from_env();
    with_status(|s| {
        s.enabled = cfg.enabled;
        s.interval_secs = cfg.interval_secs;
    });
    if !cfg.enabled {
        return;
    }
    let index_url = match index_url_from_env() {
        Ok(u) => u,
        Err(e) => {
            log_warn(&e);
            with_status(|s| s.last_error = Some(e));
            return;
        }
    };
    log(&format!(
        "enabled: checking {index_url} every {}s (+jitter), building with cargo and installing only when idle",
        cfg.interval_secs
    ));
    let spawned = std::thread::Builder::new()
        .name("zc-auto-update".into())
        .spawn(move || {
            let interval = Duration::from_secs(cfg.interval_secs);
            let first = MIN_FIRST_DELAY_SECS
                + jitter(
                    cfg.interval_secs
                        .saturating_sub(MIN_FIRST_DELAY_SECS)
                        .max(1),
                );
            std::thread::sleep(Duration::from_secs(first));
            let ua = format!(
                "zc/{} (https://github.com/zakuro-ai/zc)",
                env!("CARGO_PKG_VERSION")
            );
            let fetch = update::UreqFetcher::with_user_agent(&ua);
            let idle = || {
                let local_active: u64 = state
                    .workers
                    .list()
                    .iter()
                    .filter(|w| w.source_node.is_none() && state.is_local_worker(&w.uri))
                    .map(|w| w.active_requests as u64)
                    .sum();
                is_idle(
                    state.active_requests.len(),
                    local_active,
                    state.tx_buffer.pending_count(),
                )
            };
            loop {
                let result = run_cycle(&Cycle {
                    fetch: &fetch,
                    index_url: &index_url,
                    current: env!("CARGO_PKG_VERSION"),
                    build: &build_from_crates,
                    verify: &verify_binary,
                    idle: &idle,
                    sleep: &std::thread::sleep,
                    install: &install_binary,
                });
                if let CycleResult::Installed(v) = result {
                    log(&format!("installed {v}, restarting"));
                    if let (Some(url), Some(key)) = (&state.config.api_url, &state.config.api_key) {
                        state.tx_buffer.flush_to_api(url, key, &state.wal);
                    }
                    let _ = state.wal.flush_buffer();
                    std::process::exit(RESTART_EXIT_CODE);
                }
                let extra = jitter(cfg.interval_secs / 10 + 1);
                std::thread::sleep(interval + Duration::from_secs(extra));
            }
        });
    if let Err(e) = spawned {
        log_warn(&format!("could not start updater thread: {e}"));
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::{Cell, RefCell};

    #[test]
    fn env_enabled_values() {
        for v in ["1", "true", "TRUE", "yes", "On", " on "] {
            assert!(parse_config(Some(v), None).enabled, "{v}");
        }
        for v in ["0", "false", "no", "off", "", "enabled", "2"] {
            assert!(!parse_config(Some(v), None).enabled, "{v}");
        }
        assert!(!parse_config(None, None).enabled);
    }

    #[test]
    fn interval_parsing_default_clamp_and_suffixes() {
        assert_eq!(parse_config(None, None).interval_secs, 600);
        assert_eq!(parse_config(None, Some("garbage")).interval_secs, 600);
        assert_eq!(parse_config(None, Some("10")).interval_secs, 300);
        assert_eq!(parse_config(None, Some("300")).interval_secs, 300);
        assert_eq!(parse_config(None, Some(" 7200 ")).interval_secs, 7200);
        assert_eq!(parse_config(None, Some("10m")).interval_secs, 600);
        assert_eq!(parse_config(None, Some("1h")).interval_secs, 3600);
        assert_eq!(parse_config(None, Some("900s")).interval_secs, 900);
        assert_eq!(parse_config(None, Some("1m")).interval_secs, 300);
        assert_eq!(parse_interval("m"), None);
        assert_eq!(parse_interval("-5m"), None);
    }

    #[test]
    fn index_url_validation() {
        assert!(normalize_index_url("https://index.crates.io/3/z/zc2").is_ok());
        assert!(normalize_index_url("http://127.0.0.1:8080/zc2").is_ok());
        assert!(normalize_index_url("http://localhost/zc2").is_ok());
        assert!(normalize_index_url("http://evil.example/zc2").is_err());
        assert!(normalize_index_url("http://127.0.0.1.evil.com/").is_err());
        assert!(normalize_index_url("ftp://x").is_err());
        assert!(normalize_index_url("https://").is_err());
    }

    #[test]
    fn sparse_index_picks_highest_stable_unyanked() {
        let body = br#"{"name":"zc2","vers":"0.0.9","yanked":false}
{"name":"zc2","vers":"0.0.10","yanked":false}
this is not json
{"name":"zc2","vers":"0.0.11","yanked":true}
{"name":"zc2","vers":"0.1.0-rc.1","yanked":false}
{"name":"zc2","yanked":false}
{"name":"zc2","vers":"0.0.8","yanked":false}
"#;
        assert_eq!(parse_sparse_index(body), Some("0.0.10".into()));
        assert_eq!(parse_sparse_index(b"junk\n"), None);
        assert_eq!(
            parse_sparse_index(br#"{"vers":"0.0.1","yanked":true}"#),
            None
        );
    }

    #[test]
    fn newer_version_decision() {
        assert!(is_newer_version("0.0.10", "0.0.9"));
        assert!(!is_newer_version("0.0.9", "0.0.10"));
        assert!(!is_newer_version("0.0.9", "0.0.9"));
        assert!(!is_newer_version("0.0.8", "0.0.9"));
        assert!(is_newer_version("v0.1.0", "0.0.99"));
        assert!(!is_newer_version("junk", "0.0.1"));
    }

    #[test]
    fn cargo_resolution_order() {
        let all = |_: &Path| true;
        let none = |_: &Path| false;
        // env wins, even if it does not exist
        assert_eq!(
            resolve_cargo(Some("/opt/cargo"), Some("/usr/bin"), Some("/h"), &none),
            Some(PathBuf::from("/opt/cargo"))
        );
        // then PATH
        let in_usr = |p: &Path| p == Path::new("/usr/bin/cargo");
        assert_eq!(
            resolve_cargo(None, Some("/bin:/usr/bin"), Some("/h"), &in_usr),
            Some(PathBuf::from("/usr/bin/cargo"))
        );
        assert_eq!(
            resolve_cargo(Some("  "), Some("/usr/bin"), Some("/h"), &all),
            Some(PathBuf::from("/usr/bin/cargo"))
        );
        // then $HOME/.cargo/bin
        let in_home = |p: &Path| p == Path::new("/h/.cargo/bin/cargo");
        assert_eq!(
            resolve_cargo(None, Some("/bin"), Some("/h"), &in_home),
            Some(PathBuf::from("/h/.cargo/bin/cargo"))
        );
        assert_eq!(resolve_cargo(None, Some("/bin"), Some("/h"), &none), None);
        assert_eq!(resolve_cargo(None, None, None, &all), None);
    }

    #[test]
    fn wait_until_idle_needs_a_fresh_streak() {
        let seq = [false, true, false, true, true, true];
        let i = Cell::new(0);
        let slept = Cell::new(0);
        wait_until_idle(
            &|| {
                let v = seq[i.get()];
                i.set(i.get() + 1);
                v
            },
            &|_| slept.set(slept.get() + 1),
        );
        assert_eq!(i.get(), seq.len());
        assert_eq!(slept.get(), seq.len() - 1);
    }

    #[test]
    fn idle_decision() {
        assert!(is_idle(0, 0, 0));
        assert!(!is_idle(1, 0, 0));
        assert!(!is_idle(0, 2, 0));
        assert!(!is_idle(0, 0, 3));
    }

    struct Index(Result<Vec<u8>, FetchError>);
    impl Fetcher for Index {
        fn get(&self, _url: &str) -> Result<Vec<u8>, FetchError> {
            match &self.0 {
                Ok(b) => Ok(b.clone()),
                Err(FetchError::Status(s)) => Err(FetchError::Status(*s)),
                Err(FetchError::Transport(m)) => Err(FetchError::Transport(m.clone())),
            }
        }
    }

    fn index(versions: &[&str]) -> Index {
        let body: String = versions
            .iter()
            .map(|v| format!("{{\"name\":\"zc2\",\"vers\":\"{v}\",\"yanked\":false}}\n"))
            .collect();
        Index(Ok(body.into_bytes()))
    }

    /// Runs one cycle with a fake builder that "builds" a binary reporting
    /// `built_reports`; verify mirrors the real one's version rule.
    fn run(
        f: &Index,
        current: &str,
        built_reports: &str,
        idle: &dyn Fn() -> bool,
        builds: &Cell<u32>,
        installed: &RefCell<Option<Vec<u8>>>,
    ) -> CycleResult {
        let build = |_v: &str| {
            builds.set(builds.get() + 1);
            Ok(built_reports.as_bytes().to_vec())
        };
        let verify = |b: &[u8], v: &str| {
            if b == v.as_bytes() {
                Ok(())
            } else {
                Err(format!(
                    "it reports version {}, expected {v}",
                    String::from_utf8_lossy(b)
                ))
            }
        };
        let install = |b: &[u8]| {
            *installed.borrow_mut() = Some(b.to_vec());
            Ok(())
        };
        run_cycle(&Cycle {
            fetch: f,
            index_url: "https://index.test/zc2",
            current,
            build: &build,
            verify: &verify,
            idle,
            sleep: &|_| {},
            install: &install,
        })
    }

    #[test]
    fn cycle_builds_verifies_waits_for_idle_then_installs() {
        let f = index(&["0.0.9", "0.0.10"]);
        let (builds, installed) = (Cell::new(0), RefCell::new(None));
        // busy, idle, busy, then idle x3
        let seq = [false, true, false, true, true, true];
        let i = Cell::new(0);
        let idle = || {
            let v = seq[i.get().min(seq.len() - 1)];
            i.set(i.get() + 1);
            v
        };
        let r = run(&f, "0.0.9", "0.0.10", &idle, &builds, &installed);
        assert_eq!(r, CycleResult::Installed("0.0.10".into()));
        assert_eq!(builds.get(), 1);
        assert_eq!(i.get(), seq.len(), "install only after a fresh idle streak");
        assert_eq!(installed.borrow().as_deref(), Some(&b"0.0.10"[..]));
    }

    #[test]
    fn cycle_refuses_a_binary_reporting_the_wrong_version() {
        let f = index(&["0.0.10"]);
        let (builds, installed) = (Cell::new(0), RefCell::new(None));
        let r = run(&f, "0.0.9", "0.0.9", &|| true, &builds, &installed);
        assert!(matches!(r, CycleResult::VerifyFailed(_)), "{r:?}");
        assert!(installed.borrow().is_none());
    }

    #[test]
    fn cycle_does_not_build_for_equal_or_older() {
        let f = index(&["0.0.9"]);
        for cur in ["0.0.9", "0.0.10"] {
            let (builds, installed) = (Cell::new(0), RefCell::new(None));
            let r = run(&f, cur, "x", &|| true, &builds, &installed);
            assert_eq!(r, CycleResult::UpToDate("0.0.9".into()));
            assert_eq!(builds.get(), 0);
        }
    }

    #[test]
    fn cycle_reports_build_and_check_failures() {
        let f = index(&["0.0.10"]);
        let r = run_cycle(&Cycle {
            fetch: &f,
            index_url: "u",
            current: "0.0.9",
            build: &|_| Err("cargo not found: install rustup".into()),
            verify: &|_, _| panic!("no binary"),
            idle: &|| true,
            sleep: &|_| {},
            install: &|_| panic!("no install"),
        });
        assert!(matches!(r, CycleResult::BuildFailed(_)));
        let bad = Index(Err(FetchError::Status(503)));
        let r = run_cycle(&Cycle {
            fetch: &bad,
            index_url: "u",
            current: "0.0.9",
            build: &|_| panic!("no build"),
            verify: &|_, _| Ok(()),
            idle: &|| true,
            sleep: &|_| {},
            install: &|_| Ok(()),
        });
        assert!(matches!(r, CycleResult::CheckFailed(_)));
    }

    #[test]
    fn jitter_is_bounded() {
        for _ in 0..100 {
            assert!(jitter(60) < 60);
        }
        assert_eq!(jitter(0), 0);
    }
}