OXYGENHUB

Coverage / crates/flow/src/update.rs 62.9%

264 of 420 lines run, 42 of 141 functions · run #226 on main · run missed

1
//! Runner updates, the runner's side (docs/jetstream.md §8.2, #85): check
2
//! a new `flow` build, stage it beside the running one, swap it in keeping
3
//! the old one as `flow.prev`, and have the running runner leave with
4
//! notice so its unit starts the new build. The new build proves itself by
5
//! reaching the hub; three failed starts, or ten minutes without the hub,
6
//! put `flow.prev` back.
7
8
use anyhow::{bail, Context, Result};
9
use serde::{Deserialize, Serialize};
10
use std::path::{Path, PathBuf};
11
use std::time::Duration;
12
13
/// The staged build, beside the installed one.
14
pub const NEW: &str = "flow.new";
15
/// The build an update replaced, kept to go back to.
16
pub const PREV: &str = "flow.prev";
17
/// In the runner's home: the update not yet proven.
18
const PENDING: &str = "update.json";
19
/// In the runner's home: every update and rollback, a JSON line each.
20
const LOG: &str = "updates.log";
21
/// In the runner's home: the running runner's process id.
22
const PID: &str = "runner.pid";
23
/// In the runner's home: a new build is in place, leave for it. How a
24
/// runner is told on Windows, which has no SIGUSR1.
25
const REQUEST: &str = "update.request";
26
/// Starts of an unproven build after which the previous one comes back.
27
pub const MAX_STARTS: u32 = 3;
28
/// How long a new build has to reach the hub.
29
pub const PROVE_WITHIN: Duration = Duration::from_secs(10 * 60);
30
31
/// An update swapped in and not yet proven.
32
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
33
pub struct Pending {
34
    pub from: String,
35
    pub to: String,
36
    /// The installed binary the update replaced.
37
    pub exe: PathBuf,
38
    pub at_ms: u64,
39
    /// How long the running runner had to finish what it held.
40
    pub notice_secs: u64,
41
    /// Starts of the new build so far.
42
    pub starts: u32,
43
}
44
45
/// What [`install`] did, or would do.
46
#[derive(Debug, PartialEq, Eq)]
47
pub struct Installed {
48
    pub from: String,
49
    pub to: String,
50
    pub exe: PathBuf,
51
    /// The running runner told to leave, by process id.
52
    pub told: Option<u32>,
53
}
54
55
/// The version a `flow --version` line names: `flow 0.3.1 (build)` → `0.3.1`.
564×
pub fn parse_version(line: &str) -> Option<String> {
574×
    let v = line.trim().strip_prefix("flow ")?.split_whitespace().next()?;
588×
    v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())).then(|| v.to_string())
594×
}
60
61
/// Whether version `a` is older than `b`, part by part.
623×
pub fn older(a: &str, b: &str) -> bool {
6317×
    let parts = |v: &str| v.split('.').map(|p| p.parse::<u64>().unwrap_or(0)).collect::<Vec<_>>();
643×
    parts(a) < parts(b)
653×
}
66
67
/// `exe`'s sibling named `stem`, with `exe`'s extension (`flow.prev.exe`
68
/// beside `flow.exe` on Windows, `flow.prev` beside `flow` elsewhere).
695×
pub fn beside(exe: &Path, stem: &str) -> PathBuf {
705×
    match exe.extension() {
711×
        Some(e) => exe.with_file_name(format!("{stem}.{}", e.to_string_lossy())),
724×
        None => exe.with_file_name(stem),
73
    }
745×
}
75
76
/// The PE machine number of this build's architecture (Windows).
772×
fn pe_machine_here() -> Option<u16> {
782×
    Some(match std::env::consts::ARCH {
792×
        "x86_64" => 0x8664,
800×
        "aarch64" => 0xAA64,
810×
        _ => return None,
82
    })
832×
}
84
85
/// Refuse a file that is not a PE executable for this machine (Windows).
863×
pub fn check_pe(bytes: &[u8]) -> Result<()> {
873×
    if bytes.len() < 0x40 || &bytes[..2] != b"MZ" {
881×
        bail!("not a Windows executable");
892×
    }
902×
    let at = u32::from_le_bytes([bytes[0x3c], bytes[0x3d], bytes[0x3e], bytes[0x3f]]) as usize;
912×
    if bytes.len() < at + 6 || &bytes[at..at + 4] != b"PE\0\0" {
920×
        bail!("not a Windows executable (no PE header in its first {} bytes)", bytes.len());
932×
    }
942×
    let machine = u16::from_le_bytes([bytes[at + 4], bytes[at + 5]]);
952×
    match pe_machine_here() {
962×
        Some(m) if m == machine => Ok(()),
971×
        Some(_) => bail!("a build for another machine (PE machine {machine:#x}); this runner is {}", std::env::consts::ARCH),
980×
        None => bail!("updates are not supported on {}", std::env::consts::ARCH),
99
    }
1003×
}
101
102
/// The ELF machine number of this build's architecture.
1032×
fn machine_here() -> Option<u16> {
1042×
    Some(match std::env::consts::ARCH {
1052×
        "x86_64" => 62,
1060×
        "aarch64" => 183,
1070×
        "riscv64" => 243,
1080×
        _ => return None,
109
    })
1102×
}
111
112
/// Refuse a file that is not a 64-bit little-endian ELF executable for this
113
/// machine: a build for another target would not start, and the rollback
114
/// would only notice after three tries.
1153×
pub fn check_target(bytes: &[u8]) -> Result<()> {
1163×
    if bytes.len() < 20 || &bytes[..4] != b"\x7fELF" {
1171×
        bail!("not an ELF executable");
1182×
    }
1192×
    if bytes[4] != 2 || bytes[5] != 1 {
1200×
        bail!("not a 64-bit little-endian build");
1212×
    }
1222×
    let machine = u16::from_le_bytes([bytes[18], bytes[19]]);
1232×
    match machine_here() {
1242×
        Some(m) if m == machine => Ok(()),
1251×
        Some(_) => bail!("a build for another machine (ELF machine {machine}); this runner is {}", std::env::consts::ARCH),
1260×
        None => bail!("updates are not supported on {}", std::env::consts::ARCH),
127
    }
1283×
}
129
130
/// Run `file args…` with a time limit, returning its standard output.
1310×
fn run(file: &Path, args: &[&str], limit: Duration) -> Result<String> {
1320×
    let mut child = std::process::Command::new(file)
1330×
        .args(args)
1340×
        .stdin(std::process::Stdio::null())
1350×
        .stdout(std::process::Stdio::piped())
1360×
        .stderr(std::process::Stdio::piped())
1370×
        .spawn()
1380×
        .with_context(|| format!("starting {}", file.display()))?;
1390×
    let start = std::time::Instant::now();
140
    loop {
1410×
        if child.try_wait()?.is_some() {
1420×
            break;
1430×
        }
1440×
        if start.elapsed() > limit {
1450×
            let _ = child.kill();
1460×
            let _ = child.wait();
1470×
            bail!("`{} {}` did not finish within {} s", file.display(), args.join(" "), limit.as_secs());
1480×
        }
1490×
        std::thread::sleep(Duration::from_millis(50));
150
    }
1510×
    let out = child.wait_with_output()?;
1520×
    if !out.status.success() {
1530×
        bail!("`{} {}` failed ({}): {}", file.display(), args.join(" "), out.status, String::from_utf8_lossy(&out.stderr).trim());
1540×
    }
1550×
    Ok(String::from_utf8_lossy(&out.stdout).into_owned())
1560×
}
157
158
/// Copy `from` to `to` if it is `size` bytes with BLAKE3 `blake3`, as the
159
/// hub attests a build: a part file renamed into place, so `to` is either
160
/// the whole checked build or absent.
1613×
pub fn copy_checked(from: &Path, to: &Path, size: u64, blake3: &str) -> Result<()> {
1623×
    let bytes = std::fs::read(from).with_context(|| format!("reading {}", from.display()))?;
1633×
    let got = blake3::hash(&bytes).to_hex().to_string();
1643×
    if bytes.len() as u64 != size || got != blake3 {
1652×
        bail!("{} is not the build the hub attests ({} bytes, BLAKE3 {}…)", from.display(), bytes.len(), &got[..12]);
1661×
    }
1671×
    let part = to.with_extension("partial");
1681×
    std::fs::write(&part, &bytes).with_context(|| format!("writing {}", part.display()))?;
1691×
    std::fs::rename(&part, to)?;
1701×
    Ok(())
1713×
}
172
173
/// Check a build as the runner would run it: this machine's target, it
174
/// starts and names its version, and it finds the tiers this home offers.
175
/// Returns its version.
1760×
pub fn check(file: &Path, home: &Path) -> Result<String> {
1770×
    let mut head = vec![0u8; 4096];
1780×
    let n = std::io::Read::read(&mut std::fs::File::open(file).with_context(|| format!("opening {}", file.display()))?, &mut head)?;
1790×
    if cfg!(windows) {
1800×
        check_pe(&head[..n])?;
181
    } else {
1820×
        check_target(&head[..n])?;
183
    }
1840×
    let limit = Duration::from_secs(30);
1850×
    let line = run(file, &["--version"], limit)?;
1860×
    let version = parse_version(&line).with_context(|| format!("{} does not say it is flow: {:?}", file.display(), line.trim()))?;
1870×
    let home_s = home.to_string_lossy();
1880×
    let tiers = run(file, &["--home", &home_s, "tiers"], limit)?;
1890×
    if !tiers.lines().any(|l| l.ends_with(": available")) {
1900×
        bail!("flow {version} finds no tier it can run here:\n{}", tiers.trim());
1910×
    }
1920×
    Ok(version)
1930×
}
194
1952×
fn now_ms() -> u64 {
1962×
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
1972×
}
198
1992×
fn log(home: &Path, event: &str, from: &str, to: &str, why: &str) {
200
    use std::io::Write;
2012×
    let line = serde_json::json!({"at_ms": now_ms(), "event": event, "from": from, "to": to, "why": why});
2022×
    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(home.join(LOG)) {
2032×
        let _ = writeln!(f, "{line}");
2042×
    }
2052×
}
206
207
/// The update not yet proven, if any.
2089×
pub fn pending(home: &Path) -> Option<Pending> {
2099×
    serde_json::from_slice(&std::fs::read(home.join(PENDING)).ok()?).ok()
2109×
}
211
2125×
fn save(home: &Path, p: &Pending) -> Result<()> {
2135×
    let tmp = home.join(format!("{PENDING}.tmp"));
2145×
    std::fs::write(&tmp, serde_json::to_vec_pretty(p)?)?;
2155×
    std::fs::rename(&tmp, home.join(PENDING))?;
2165×
    Ok(())
2175×
}
218
219
/// Whether `p` is the program running now.
2200×
fn is_self(p: &Path) -> bool {
2210×
    let canon = |p: &Path| std::fs::canonicalize(p).ok();
2220×
    std::env::current_exe().ok().and_then(|me| canon(&me)).is_some_and(|me| Some(me) == canon(p))
2230×
}
224
225
/// Rename program `from` to `to`. On Windows a running program cannot
226
/// rename its own file (other programs can), so a copy of it, run as
227
/// `flow __rename`, does it then.
2280×
fn rename_exe(from: &Path, to: &Path) -> Result<()> {
2290×
    if cfg!(windows) && is_self(from) {
2300×
        let helper = beside(from, "flow.rename");
2310×
        std::fs::copy(from, &helper).with_context(|| format!("copying {} to rename it", from.display()))?;
2320×
        let out = std::process::Command::new(&helper).arg("__rename").arg(from).arg(to).output();
2330×
        let _ = std::fs::remove_file(&helper);
2340×
        let out = out.with_context(|| format!("starting {}", helper.display()))?;
2350×
        if !out.status.success() {
2360×
            bail!("{}", String::from_utf8_lossy(&out.stderr).trim());
2370×
        }
2380×
        return Ok(());
2390×
    }
2400×
    Ok(crate::portable::rename(from, to)?)
2410×
}
242
243
/// Put `staged` in place of `exe`, keeping `exe` as [`PREV`] beside it.
244
/// `exe` is never missing: it is copied aside, then replaced in one rename.
245
/// On Windows, where a running program cannot be replaced but can be
246
/// renamed, `exe` is renamed aside and `staged` into its place.
2471×
pub fn swap(exe: &Path, staged: &Path) -> Result<()> {
2481×
    let prev = beside(exe, PREV);
2491×
    if cfg!(windows) {
2500×
        let _ = std::fs::remove_file(&prev);
2510×
        rename_exe(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?;
2520×
        if let Err(e) = crate::portable::rename(staged, exe) {
2530×
            let _ = crate::portable::rename(&prev, exe);
2540×
            return Err(e).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()));
2550×
        }
2560×
        return Ok(());
2571×
    }
2581×
    let _ = std::fs::remove_file(&prev);
2591×
    if std::fs::hard_link(exe, &prev).is_err() {
2600×
        std::fs::copy(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?;
2611×
    }
2621×
    std::fs::rename(staged, exe).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()))?;
2631×
    Ok(())
2641×
}
265
266
/// Put [`PREV`] back in place of `exe`.
2671×
pub fn restore(exe: &Path) -> Result<()> {
2681×
    let prev = beside(exe, PREV);
2691×
    if !prev.is_file() {
2700×
        bail!("{} is not there to go back to", prev.display());
2711×
    }
2721×
    if cfg!(windows) {
273
        // The failed build may be the one running: rename it aside first.
2740×
        let failed = beside(exe, "flow.failed");
2750×
        let _ = std::fs::remove_file(&failed);
2760×
        rename_exe(exe, &failed).with_context(|| format!("moving {} aside", exe.display()))?;
2770×
        return crate::portable::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()));
2781×
    }
2791×
    std::fs::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()))?;
2801×
    Ok(())
2811×
}
282
283
/// Check `file`, stage it beside `exe`, and unless `dry_run` swap it in and
284
/// tell the running runner (if any) to leave within `notice`, finishing
285
/// what fits and handing back the rest, so its unit starts the new build.
2860×
pub fn install(home: &crate::home::Home, exe: &Path, file: &Path, notice: Duration, dry_run: bool, allow_older: bool) -> Result<Installed> {
2870×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
2880×
        bail!("flow.toml says [runner.update] allow = false: this runner takes no updates");
2890×
    }
2900×
    if let Some(p) = pending(&home.root) {
2910×
        bail!("the update from {} to {} is not proven yet; wait for it (or for its rollback)", p.from, p.to);
2920×
    }
2930×
    let from = env!("CARGO_PKG_VERSION").to_string();
2940×
    let staged = beside(exe, NEW);
2950×
    let _ = std::fs::remove_file(&staged);
2960×
    std::fs::copy(file, &staged).with_context(|| format!("staging {} as {}", file.display(), staged.display()))?;
2970×
    crate::portable::set_mode(&staged, 0o755)?;
2980×
    let checked = check(&staged, &home.root).and_then(|to| {
2990×
        if older(&to, &from) && !allow_older {
3000×
            bail!("flow {to} is older than this runner's {from} (--allow-older to go back)");
3010×
        }
3020×
        Ok(to)
3030×
    });
3040×
    let to = match checked {
3050×
        Ok(v) => v,
3060×
        Err(e) => {
3070×
            let _ = std::fs::remove_file(&staged);
3080×
            return Err(e);
309
        }
310
    };
3110×
    if dry_run {
3120×
        let _ = std::fs::remove_file(&staged);
3130×
        return Ok(Installed { from, to, exe: exe.to_path_buf(), told: None });
3140×
    }
3150×
    if let Err(e) = swap(exe, &staged) {
3160×
        let _ = std::fs::remove_file(&staged);
3170×
        return Err(e);
3180×
    }
3190×
    let p =
3200×
        Pending { from: from.clone(), to: to.clone(), exe: exe.to_path_buf(), at_ms: now_ms(), notice_secs: notice.as_secs(), starts: 0 };
3210×
    save(&home.root, &p)?;
3220×
    log(&home.root, "installed", &from, &to, "flow runner update --from");
3230×
    let told = running(&home.root).filter(|pid| cfg!(not(unix)) || tell(*pid));
3240×
    Ok(Installed { from, to, exe: exe.to_path_buf(), told })
3250×
}
326
327
/// Ask runner `pid` to leave for the new build (SIGUSR1).
328
#[cfg(unix)]
3290×
fn tell(pid: u32) -> bool {
3300×
    unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) == 0 }
3310×
}
332
333
/// On Windows: a request in the runner's home, which its loop reads.
334
#[cfg(not(unix))]
335
fn tell(_pid: u32) -> bool {
336
    false
337
}
338
339
/// In the runner's home: drain (claim nothing more, finish what it holds,
340
/// then stop), as SIGTERM asks on Linux: `flow runner drain`, for Windows.
341
const DRAIN: &str = "drain.request";
342
343
/// Ask the runner of `home` to drain; whether one is running to ask.
3442×
pub fn ask_to_drain(home: &Path) -> std::io::Result<bool> {
3452×
    std::fs::write(home.join(DRAIN), "")?;
3462×
    Ok(home.join(PID).is_file())
3472×
}
348
349
/// Whether the runner has been asked, by file, to drain (once).
3503×
pub fn drain_requested(home: &Path) -> bool {
3513×
    std::fs::remove_file(home.join(DRAIN)).is_ok()
3523×
}
353
354
/// Whether the runner has been asked, by file, to leave for a new build
355
/// (and forget the asking).
3564×
pub fn requested(home: &Path) -> bool {
3574×
    std::fs::remove_file(home.join(REQUEST)).is_ok()
3584×
}
359
360
/// The running runner's process id, from its pid file, if that process is
361
/// still a `flow runner`: a stale file's pid may be another program's now,
362
/// and SIGUSR1 would end it. Builds before #85 write no pid file (and do
363
/// not listen for SIGUSR1), so they are never told.
364
#[cfg(unix)]
3651×
fn running(home: &Path) -> Option<u32> {
3661×
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
3671×
    let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
3681×
    is_runner(&cmdline).then_some(pid)
3691×
}
370
371
/// On Windows: a runner of this home has a pid file, and is asked by a
372
/// request file it reads (a stale one is cleared when a runner starts).
373
#[cfg(not(unix))]
374
fn running(home: &Path) -> Option<u32> {
375
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
376
    std::fs::write(home.join(REQUEST), pid.to_string()).ok()?;
377
    Some(pid)
378
}
379
380
/// Whether a NUL-separated command line is `flow … runner` with no subcommand.
381
#[cfg_attr(not(unix), allow(dead_code))]
3826×
fn is_runner(cmdline: &[u8]) -> bool {
383230×
    let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).filter(|a| !a.is_empty()).collect();
3846×
    let Some((argv0, rest)) = args.split_first() else { return false };
38539×
    let name = argv0.rsplit(|b| *b == b'/').next().unwrap_or(argv0);
3865×
    name.starts_with(b"flow") && rest.last() == Some(&&b"runner"[..])
3876×
}
388
389
/// Note this process as the home's runner, for `flow runner update` to tell.
3903×
pub fn note_runner(home: &Path) {
3913×
    let _ = std::fs::remove_file(home.join(REQUEST));
3923×
    let _ = std::fs::remove_file(home.join(DRAIN));
3933×
    let _ = std::fs::write(home.join(PID), std::process::id().to_string());
3943×
}
395
396
/// The runner stopped: forget its pid.
3970×
pub fn forget_runner(home: &Path) {
3980×
    if std::fs::read_to_string(home.join(PID)).is_ok_and(|p| p.trim() == std::process::id().to_string()) {
3990×
        let _ = std::fs::remove_file(home.join(PID));
4000×
    }
4010×
}
402
403
/// What a runner starting up should do about an update.
404
#[derive(Debug, PartialEq, Eq)]
405
pub enum Start {
406
    /// No update waits to be proven.
407
    Settled,
408
    /// The new build is on trial: prove it within [`PROVE_WITHIN`].
409
    Trial(Pending),
410
    /// It failed too often; the previous build is back and should be run.
411
    RolledBack(Pending),
412
}
413
414
/// Count this start of an unproven build; after [`MAX_STARTS`], put the
415
/// previous build back.
4166×
pub fn on_start(home: &Path) -> Result<Start> {
4176×
    let Some(mut p) = pending(home) else { return Ok(Start::Settled) };
4184×
    p.starts += 1;
4194×
    if p.starts > MAX_STARTS {
4201×
        roll_back(home, &p, &format!("{MAX_STARTS} starts without reaching the hub"))?;
4211×
        return Ok(Start::RolledBack(p));
4223×
    }
4233×
    save(home, &p)?;
4243×
    Ok(Start::Trial(p))
4256×
}
426
427
/// In the runner's home: what to tell the hub once it answers.
428
const NOTE: &str = "update.note";
429
430
/// Keep `note` to tell the hub (a proof, a rollback) once it answers.
4312×
fn note(home: &Path, note: &str) {
4322×
    let _ = std::fs::write(home.join(NOTE), note);
4332×
}
434
435
/// What there is to tell the hub, once.
4360×
pub fn take_note(home: &Path) -> Option<String> {
4370×
    let n = std::fs::read_to_string(home.join(NOTE)).ok()?;
4380×
    let _ = std::fs::remove_file(home.join(NOTE));
4390×
    Some(n).filter(|n| !n.trim().is_empty())
4400×
}
441
442
/// The new build reached the hub: it stays.
4431×
pub fn proven(home: &Path) {
4441×
    if let Some(p) = pending(home) {
4451×
        let _ = std::fs::remove_file(home.join(PENDING));
4461×
        log(home, "proven", &p.from, &p.to, "reached the hub");
4471×
        note(home, &format!("runs flow {} (was {}); proven", p.to, p.from));
4481×
        eprintln!("flow runner: flow {} proven (it reached the hub); flow {} stays as {}", p.to, p.from, beside(&p.exe, PREV).display());
4491×
    }
4501×
}
451
452
/// Put the previous build back and forget the update.
4531×
pub fn roll_back(home: &Path, p: &Pending, why: &str) -> Result<()> {
4541×
    restore(&p.exe)?;
4551×
    let _ = std::fs::remove_file(home.join(PENDING));
4561×
    log(home, "rolled back", &p.to, &p.from, why);
4571×
    note(home, &format!("rolled back from flow {} to {}: {why}", p.to, p.from));
4581×
    eprintln!("flow runner: rolled back from flow {} to {} ({why})", p.to, p.from);
4591×
    Ok(())
4601×
}
461
462
#[cfg(test)]
463
mod tests {
464
465
    #[test]
4661×
    fn a_build_from_the_swarm_is_copied_only_when_it_is_the_one_attested() {
4671×
        let dir = tempfile::tempdir().unwrap();
4681×
        let (from, to) = (dir.path().join("cas.ext4"), dir.path().join("flow-0.5.2"));
4691×
        std::fs::write(&from, b"flow build").unwrap();
4701×
        let hash = blake3::hash(b"flow build").to_hex().to_string();
4711×
        assert!(copy_checked(&from, &to, 9, &hash).is_err(), "the wrong size");
4721×
        assert!(copy_checked(&from, &to, 10, &"0".repeat(64)).is_err(), "the wrong hash");
4731×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing left behind");
4741×
        copy_checked(&from, &to, 10, &hash).unwrap();
4751×
        assert_eq!(std::fs::read(&to).unwrap(), b"flow build");
4761×
    }
477
    use super::*;
478
479
    #[test]
4801×
    fn versions_are_read_and_compared() {
4811×
        assert_eq!(parse_version("flow 0.3.1 (local build)\n").as_deref(), Some("0.3.1"));
4821×
        assert_eq!(parse_version("flow 0.10.0"), Some("0.10.0".into()));
4831×
        assert_eq!(parse_version("oxy 0.6.0"), None);
4841×
        assert_eq!(parse_version("flow banana"), None);
4851×
        assert!(older("0.3.1", "0.10.0"), "by number, not by text");
4861×
        assert!(!older("0.3.1", "0.3.1"));
4871×
        assert!(older("0.3", "0.3.1"));
4881×
    }
489
490
    #[test]
4911×
    fn only_a_build_for_this_machine_passes() {
4921×
        let me = std::fs::read(std::env::current_exe().unwrap()).unwrap();
4931×
        check_target(&me[..64]).unwrap();
4941×
        assert!(check_target(b"#!/bin/sh\necho flow 9.9.9\n").unwrap_err().to_string().contains("not an ELF"));
4951×
        let mut other = me[..64].to_vec();
4961×
        other[18..20].copy_from_slice(&(if std::env::consts::ARCH == "riscv64" { 62u16 } else { 243u16 }).to_le_bytes());
4971×
        assert!(check_target(&other).unwrap_err().to_string().contains("another machine"));
4981×
    }
499
500
    #[test]
5011×
    fn a_swap_keeps_the_old_build_and_three_failed_starts_bring_it_back() {
5021×
        let dir = tempfile::tempdir().unwrap();
5031×
        let (bin, home) = (dir.path().join("bin"), dir.path().join("home"));
5041×
        std::fs::create_dir_all(&bin).unwrap();
5051×
        std::fs::create_dir_all(&home).unwrap();
5061×
        let exe = bin.join("flow");
5071×
        std::fs::write(&exe, "old").unwrap();
5081×
        std::fs::write(bin.join(NEW), "new").unwrap();
5091×
        swap(&exe, &bin.join(NEW)).unwrap();
5101×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "new");
5111×
        assert_eq!(std::fs::read_to_string(bin.join(PREV)).unwrap(), "old");
5121×
        assert!(!bin.join(NEW).exists());
513
5141×
        assert_eq!(on_start(&home).unwrap(), Start::Settled, "no update, nothing to do");
5151×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 600, starts: 0 };
5161×
        save(&home, &p).unwrap();
5173×
        for n in 1..=MAX_STARTS {
5183×
            assert_eq!(on_start(&home).unwrap(), Start::Trial(Pending { starts: n, ..p.clone() }));
519
        }
5201×
        assert!(matches!(on_start(&home).unwrap(), Start::RolledBack(_)));
5211×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "old", "the previous build is back");
5221×
        assert!(pending(&home).is_none());
5231×
        let log = std::fs::read_to_string(home.join(LOG)).unwrap();
5241×
        assert!(log.contains("rolled back") && log.contains("0.3.2"), "{log}");
5251×
    }
526
527
    #[test]
5281×
    fn a_windows_build_is_checked_as_pe_and_named_beside_with_its_extension() {
5291×
        let mut pe = vec![0u8; 0x100];
5301×
        pe[..2].copy_from_slice(b"MZ");
5311×
        pe[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
5321×
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
5331×
        pe[0x84..0x86].copy_from_slice(&0x8664u16.to_le_bytes());
5341×
        if std::env::consts::ARCH == "x86_64" {
5351×
            check_pe(&pe).unwrap();
5361×
        }
5371×
        pe[0x84..0x86].copy_from_slice(&0x01c4u16.to_le_bytes());
5381×
        assert!(check_pe(&pe).is_err(), "another machine");
5391×
        assert!(check_pe(b"\x7fELF and more bytes than enough for a header, really, quite a few more")
5401×
            .unwrap_err()
5411×
            .to_string()
5421×
            .contains("not a Windows"));
5431×
        assert_eq!(beside(Path::new("C:/flow/flow.exe"), PREV), Path::new("C:/flow/flow.prev.exe"));
5441×
        assert_eq!(beside(Path::new("/usr/local/bin/flow"), NEW), Path::new("/usr/local/bin/flow.new"));
5451×
    }
546
547
    #[test]
5481×
    fn a_drain_is_asked_by_file_once() {
5491×
        let dir = tempfile::tempdir().unwrap();
5501×
        assert!(!ask_to_drain(dir.path()).unwrap(), "no runner running");
5511×
        assert!(drain_requested(dir.path()) && !drain_requested(dir.path()));
5521×
        note_runner(dir.path());
5531×
        assert!(ask_to_drain(dir.path()).unwrap());
5541×
        note_runner(dir.path());
5551×
        assert!(!drain_requested(dir.path()), "a starting runner clears a stale request");
5561×
    }
557
558
    #[test]
5591×
    fn a_request_file_asks_once() {
5601×
        let dir = tempfile::tempdir().unwrap();
5611×
        assert!(!requested(dir.path()));
5621×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5631×
        assert!(requested(dir.path()) && !requested(dir.path()), "read once");
5641×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5651×
        note_runner(dir.path());
5661×
        assert!(!requested(dir.path()), "a starting runner clears a stale request");
5671×
    }
568
569
    #[test]
5701×
    fn only_a_running_runner_is_told() {
5711×
        assert!(is_runner(b"/usr/local/bin/flow\0runner\0"));
5721×
        assert!(is_runner(b"flow\0--home\0/srv/flow\0runner\0"));
5731×
        assert!(!is_runner(b"flow\0runner\0update\0--from\0x\0"), "not the update command itself");
5741×
        assert!(!is_runner(b"/usr/bin/vim\0runner\0"));
5751×
        assert!(!is_runner(b""));
5761×
        let dir = tempfile::tempdir().unwrap();
5771×
        std::fs::write(dir.path().join(PID), std::process::id().to_string()).unwrap();
5781×
        assert_eq!(running(dir.path()), None, "this test is not a flow runner");
5791×
    }
580
581
    #[test]
5821×
    fn a_proven_build_stays() {
5831×
        let dir = tempfile::tempdir().unwrap();
5841×
        let exe = dir.path().join("flow");
5851×
        std::fs::write(&exe, "new").unwrap();
5861×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 0, starts: 1 };
5871×
        save(dir.path(), &p).unwrap();
5881×
        proven(dir.path());
5891×
        assert!(pending(dir.path()).is_none());
5901×
        assert_eq!(on_start(dir.path()).unwrap(), Start::Settled);
5911×
        assert!(std::fs::read_to_string(dir.path().join(LOG)).unwrap().contains("proven"));
5921×
    }
593
}