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";
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;
const MIN_FIRST_DELAY_SECS: u64 = 60;
const IDLE_POLLS_REQUIRED: u32 = 3;
const IDLE_POLL_SECS: u64 = 5;
const BUILD_TIMEOUT: Duration = Duration::from_secs(60 * 60);
pub const RESTART_EXIT_CODE: i32 = 75;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
pub enabled: bool,
pub interval_secs: u64,
}
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)
}
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(),
)
}
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()),
}
}
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)
}
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}")),
}
}
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"
)
})
}
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,
}
}
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
}
#[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);
}
}
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)
}
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>;
pub struct Cycle<'a> {
pub fetch: &'a dyn Fetcher,
pub index_url: &'a str,
pub current: &'a str,
pub build: &'a dyn Fn(&str) -> Result<Vec<u8>, String>,
pub verify: &'a VerifyFn,
pub idle: &'a dyn Fn() -> bool,
pub sleep: &'a dyn Fn(Duration),
pub install: &'a dyn Fn(&[u8]) -> Result<(), String>,
}
#[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
}
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"
))),
}
}
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));
}
}
struct RootGuard(PathBuf);
impl Drop for RootGuard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
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);
}
}
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);
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()))
}
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())
}
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;
assert_eq!(
resolve_cargo(Some("/opt/cargo"), Some("/usr/bin"), Some("/h"), &none),
Some(PathBuf::from("/opt/cargo"))
);
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"))
);
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()))
}
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));
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);
}
}