OXYGENHUB

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

242 of 396 lines run, 40 of 134 functions · run #193 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
/// Check a build as the runner would run it: this machine's target, it
159
/// starts and names its version, and it finds the tiers this home offers.
160
/// Returns its version.
1610×
pub fn check(file: &Path, home: &Path) -> Result<String> {
1620×
    let mut head = vec![0u8; 4096];
1630×
    let n = std::io::Read::read(&mut std::fs::File::open(file).with_context(|| format!("opening {}", file.display()))?, &mut head)?;
1640×
    if cfg!(windows) {
1650×
        check_pe(&head[..n])?;
166
    } else {
1670×
        check_target(&head[..n])?;
168
    }
1690×
    let limit = Duration::from_secs(30);
1700×
    let line = run(file, &["--version"], limit)?;
1710×
    let version = parse_version(&line).with_context(|| format!("{} does not say it is flow: {:?}", file.display(), line.trim()))?;
1720×
    let home_s = home.to_string_lossy();
1730×
    let tiers = run(file, &["--home", &home_s, "tiers"], limit)?;
1740×
    if !tiers.lines().any(|l| l.ends_with(": available")) {
1750×
        bail!("flow {version} finds no tier it can run here:\n{}", tiers.trim());
1760×
    }
1770×
    Ok(version)
1780×
}
179
1802×
fn now_ms() -> u64 {
1812×
    std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
1822×
}
183
1842×
fn log(home: &Path, event: &str, from: &str, to: &str, why: &str) {
185
    use std::io::Write;
1862×
    let line = serde_json::json!({"at_ms": now_ms(), "event": event, "from": from, "to": to, "why": why});
1872×
    if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(home.join(LOG)) {
1882×
        let _ = writeln!(f, "{line}");
1892×
    }
1902×
}
191
192
/// The update not yet proven, if any.
1939×
pub fn pending(home: &Path) -> Option<Pending> {
1949×
    serde_json::from_slice(&std::fs::read(home.join(PENDING)).ok()?).ok()
1959×
}
196
1975×
fn save(home: &Path, p: &Pending) -> Result<()> {
1985×
    let tmp = home.join(format!("{PENDING}.tmp"));
1995×
    std::fs::write(&tmp, serde_json::to_vec_pretty(p)?)?;
2005×
    std::fs::rename(&tmp, home.join(PENDING))?;
2015×
    Ok(())
2025×
}
203
204
/// Whether `p` is the program running now.
2050×
fn is_self(p: &Path) -> bool {
2060×
    let canon = |p: &Path| std::fs::canonicalize(p).ok();
2070×
    std::env::current_exe().ok().and_then(|me| canon(&me)).is_some_and(|me| Some(me) == canon(p))
2080×
}
209
210
/// Rename program `from` to `to`. On Windows a running program cannot
211
/// rename its own file (other programs can), so a copy of it, run as
212
/// `flow __rename`, does it then.
2130×
fn rename_exe(from: &Path, to: &Path) -> Result<()> {
2140×
    if cfg!(windows) && is_self(from) {
2150×
        let helper = beside(from, "flow.rename");
2160×
        std::fs::copy(from, &helper).with_context(|| format!("copying {} to rename it", from.display()))?;
2170×
        let out = std::process::Command::new(&helper).arg("__rename").arg(from).arg(to).output();
2180×
        let _ = std::fs::remove_file(&helper);
2190×
        let out = out.with_context(|| format!("starting {}", helper.display()))?;
2200×
        if !out.status.success() {
2210×
            bail!("{}", String::from_utf8_lossy(&out.stderr).trim());
2220×
        }
2230×
        return Ok(());
2240×
    }
2250×
    Ok(crate::portable::rename(from, to)?)
2260×
}
227
228
/// Put `staged` in place of `exe`, keeping `exe` as [`PREV`] beside it.
229
/// `exe` is never missing: it is copied aside, then replaced in one rename.
230
/// On Windows, where a running program cannot be replaced but can be
231
/// renamed, `exe` is renamed aside and `staged` into its place.
2321×
pub fn swap(exe: &Path, staged: &Path) -> Result<()> {
2331×
    let prev = beside(exe, PREV);
2341×
    if cfg!(windows) {
2350×
        let _ = std::fs::remove_file(&prev);
2360×
        rename_exe(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?;
2370×
        if let Err(e) = crate::portable::rename(staged, exe) {
2380×
            let _ = crate::portable::rename(&prev, exe);
2390×
            return Err(e).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()));
2400×
        }
2410×
        return Ok(());
2421×
    }
2431×
    let _ = std::fs::remove_file(&prev);
2441×
    if std::fs::hard_link(exe, &prev).is_err() {
2450×
        std::fs::copy(exe, &prev).with_context(|| format!("keeping {} as {}", exe.display(), prev.display()))?;
2461×
    }
2471×
    std::fs::rename(staged, exe).with_context(|| format!("putting {} in place of {}", staged.display(), exe.display()))?;
2481×
    Ok(())
2491×
}
250
251
/// Put [`PREV`] back in place of `exe`.
2521×
pub fn restore(exe: &Path) -> Result<()> {
2531×
    let prev = beside(exe, PREV);
2541×
    if !prev.is_file() {
2550×
        bail!("{} is not there to go back to", prev.display());
2561×
    }
2571×
    if cfg!(windows) {
258
        // The failed build may be the one running: rename it aside first.
2590×
        let failed = beside(exe, "flow.failed");
2600×
        let _ = std::fs::remove_file(&failed);
2610×
        rename_exe(exe, &failed).with_context(|| format!("moving {} aside", exe.display()))?;
2620×
        return crate::portable::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()));
2631×
    }
2641×
    std::fs::rename(&prev, exe).with_context(|| format!("putting {} back", prev.display()))?;
2651×
    Ok(())
2661×
}
267
268
/// Check `file`, stage it beside `exe`, and unless `dry_run` swap it in and
269
/// tell the running runner (if any) to leave within `notice`, finishing
270
/// what fits and handing back the rest, so its unit starts the new build.
2710×
pub fn install(home: &crate::home::Home, exe: &Path, file: &Path, notice: Duration, dry_run: bool, allow_older: bool) -> Result<Installed> {
2720×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
2730×
        bail!("flow.toml says [runner.update] allow = false: this runner takes no updates");
2740×
    }
2750×
    if let Some(p) = pending(&home.root) {
2760×
        bail!("the update from {} to {} is not proven yet; wait for it (or for its rollback)", p.from, p.to);
2770×
    }
2780×
    let from = env!("CARGO_PKG_VERSION").to_string();
2790×
    let staged = beside(exe, NEW);
2800×
    let _ = std::fs::remove_file(&staged);
2810×
    std::fs::copy(file, &staged).with_context(|| format!("staging {} as {}", file.display(), staged.display()))?;
2820×
    crate::portable::set_mode(&staged, 0o755)?;
2830×
    let checked = check(&staged, &home.root).and_then(|to| {
2840×
        if older(&to, &from) && !allow_older {
2850×
            bail!("flow {to} is older than this runner's {from} (--allow-older to go back)");
2860×
        }
2870×
        Ok(to)
2880×
    });
2890×
    let to = match checked {
2900×
        Ok(v) => v,
2910×
        Err(e) => {
2920×
            let _ = std::fs::remove_file(&staged);
2930×
            return Err(e);
294
        }
295
    };
2960×
    if dry_run {
2970×
        let _ = std::fs::remove_file(&staged);
2980×
        return Ok(Installed { from, to, exe: exe.to_path_buf(), told: None });
2990×
    }
3000×
    if let Err(e) = swap(exe, &staged) {
3010×
        let _ = std::fs::remove_file(&staged);
3020×
        return Err(e);
3030×
    }
3040×
    let p =
3050×
        Pending { from: from.clone(), to: to.clone(), exe: exe.to_path_buf(), at_ms: now_ms(), notice_secs: notice.as_secs(), starts: 0 };
3060×
    save(&home.root, &p)?;
3070×
    log(&home.root, "installed", &from, &to, "flow runner update --from");
3080×
    let told = running(&home.root).filter(|pid| cfg!(not(unix)) || tell(*pid));
3090×
    Ok(Installed { from, to, exe: exe.to_path_buf(), told })
3100×
}
311
312
/// Ask runner `pid` to leave for the new build (SIGUSR1).
313
#[cfg(unix)]
3140×
fn tell(pid: u32) -> bool {
3150×
    unsafe { libc::kill(pid as libc::pid_t, libc::SIGUSR1) == 0 }
3160×
}
317
318
/// On Windows: a request in the runner's home, which its loop reads.
319
#[cfg(not(unix))]
320
fn tell(_pid: u32) -> bool {
321
    false
322
}
323
324
/// In the runner's home: drain (claim nothing more, finish what it holds,
325
/// then stop), as SIGTERM asks on Linux: `flow runner drain`, for Windows.
326
const DRAIN: &str = "drain.request";
327
328
/// Ask the runner of `home` to drain; whether one is running to ask.
3292×
pub fn ask_to_drain(home: &Path) -> std::io::Result<bool> {
3302×
    std::fs::write(home.join(DRAIN), "")?;
3312×
    Ok(home.join(PID).is_file())
3322×
}
333
334
/// Whether the runner has been asked, by file, to drain (once).
3353×
pub fn drain_requested(home: &Path) -> bool {
3363×
    std::fs::remove_file(home.join(DRAIN)).is_ok()
3373×
}
338
339
/// Whether the runner has been asked, by file, to leave for a new build
340
/// (and forget the asking).
3414×
pub fn requested(home: &Path) -> bool {
3424×
    std::fs::remove_file(home.join(REQUEST)).is_ok()
3434×
}
344
345
/// The running runner's process id, from its pid file, if that process is
346
/// still a `flow runner`: a stale file's pid may be another program's now,
347
/// and SIGUSR1 would end it. Builds before #85 write no pid file (and do
348
/// not listen for SIGUSR1), so they are never told.
349
#[cfg(unix)]
3501×
fn running(home: &Path) -> Option<u32> {
3511×
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
3521×
    let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
3531×
    is_runner(&cmdline).then_some(pid)
3541×
}
355
356
/// On Windows: a runner of this home has a pid file, and is asked by a
357
/// request file it reads (a stale one is cleared when a runner starts).
358
#[cfg(not(unix))]
359
fn running(home: &Path) -> Option<u32> {
360
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
361
    std::fs::write(home.join(REQUEST), pid.to_string()).ok()?;
362
    Some(pid)
363
}
364
365
/// Whether a NUL-separated command line is `flow … runner` with no subcommand.
366
#[cfg_attr(not(unix), allow(dead_code))]
3676×
fn is_runner(cmdline: &[u8]) -> bool {
368230×
    let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).filter(|a| !a.is_empty()).collect();
3696×
    let Some((argv0, rest)) = args.split_first() else { return false };
37039×
    let name = argv0.rsplit(|b| *b == b'/').next().unwrap_or(argv0);
3715×
    name.starts_with(b"flow") && rest.last() == Some(&&b"runner"[..])
3726×
}
373
374
/// Note this process as the home's runner, for `flow runner update` to tell.
3753×
pub fn note_runner(home: &Path) {
3763×
    let _ = std::fs::remove_file(home.join(REQUEST));
3773×
    let _ = std::fs::remove_file(home.join(DRAIN));
3783×
    let _ = std::fs::write(home.join(PID), std::process::id().to_string());
3793×
}
380
381
/// The runner stopped: forget its pid.
3820×
pub fn forget_runner(home: &Path) {
3830×
    if std::fs::read_to_string(home.join(PID)).is_ok_and(|p| p.trim() == std::process::id().to_string()) {
3840×
        let _ = std::fs::remove_file(home.join(PID));
3850×
    }
3860×
}
387
388
/// What a runner starting up should do about an update.
389
#[derive(Debug, PartialEq, Eq)]
390
pub enum Start {
391
    /// No update waits to be proven.
392
    Settled,
393
    /// The new build is on trial: prove it within [`PROVE_WITHIN`].
394
    Trial(Pending),
395
    /// It failed too often; the previous build is back and should be run.
396
    RolledBack(Pending),
397
}
398
399
/// Count this start of an unproven build; after [`MAX_STARTS`], put the
400
/// previous build back.
4016×
pub fn on_start(home: &Path) -> Result<Start> {
4026×
    let Some(mut p) = pending(home) else { return Ok(Start::Settled) };
4034×
    p.starts += 1;
4044×
    if p.starts > MAX_STARTS {
4051×
        roll_back(home, &p, &format!("{MAX_STARTS} starts without reaching the hub"))?;
4061×
        return Ok(Start::RolledBack(p));
4073×
    }
4083×
    save(home, &p)?;
4093×
    Ok(Start::Trial(p))
4106×
}
411
412
/// In the runner's home: what to tell the hub once it answers.
413
const NOTE: &str = "update.note";
414
415
/// Keep `note` to tell the hub (a proof, a rollback) once it answers.
4162×
fn note(home: &Path, note: &str) {
4172×
    let _ = std::fs::write(home.join(NOTE), note);
4182×
}
419
420
/// What there is to tell the hub, once.
4210×
pub fn take_note(home: &Path) -> Option<String> {
4220×
    let n = std::fs::read_to_string(home.join(NOTE)).ok()?;
4230×
    let _ = std::fs::remove_file(home.join(NOTE));
4240×
    Some(n).filter(|n| !n.trim().is_empty())
4250×
}
426
427
/// The new build reached the hub: it stays.
4281×
pub fn proven(home: &Path) {
4291×
    if let Some(p) = pending(home) {
4301×
        let _ = std::fs::remove_file(home.join(PENDING));
4311×
        log(home, "proven", &p.from, &p.to, "reached the hub");
4321×
        note(home, &format!("runs flow {} (was {}); proven", p.to, p.from));
4331×
        eprintln!("flow runner: flow {} proven (it reached the hub); flow {} stays as {}", p.to, p.from, beside(&p.exe, PREV).display());
4341×
    }
4351×
}
436
437
/// Put the previous build back and forget the update.
4381×
pub fn roll_back(home: &Path, p: &Pending, why: &str) -> Result<()> {
4391×
    restore(&p.exe)?;
4401×
    let _ = std::fs::remove_file(home.join(PENDING));
4411×
    log(home, "rolled back", &p.to, &p.from, why);
4421×
    note(home, &format!("rolled back from flow {} to {}: {why}", p.to, p.from));
4431×
    eprintln!("flow runner: rolled back from flow {} to {} ({why})", p.to, p.from);
4441×
    Ok(())
4451×
}
446
447
#[cfg(test)]
448
mod tests {
449
    use super::*;
450
451
    #[test]
4521×
    fn versions_are_read_and_compared() {
4531×
        assert_eq!(parse_version("flow 0.3.1 (local build)\n").as_deref(), Some("0.3.1"));
4541×
        assert_eq!(parse_version("flow 0.10.0"), Some("0.10.0".into()));
4551×
        assert_eq!(parse_version("oxy 0.6.0"), None);
4561×
        assert_eq!(parse_version("flow banana"), None);
4571×
        assert!(older("0.3.1", "0.10.0"), "by number, not by text");
4581×
        assert!(!older("0.3.1", "0.3.1"));
4591×
        assert!(older("0.3", "0.3.1"));
4601×
    }
461
462
    #[test]
4631×
    fn only_a_build_for_this_machine_passes() {
4641×
        let me = std::fs::read(std::env::current_exe().unwrap()).unwrap();
4651×
        check_target(&me[..64]).unwrap();
4661×
        assert!(check_target(b"#!/bin/sh\necho flow 9.9.9\n").unwrap_err().to_string().contains("not an ELF"));
4671×
        let mut other = me[..64].to_vec();
4681×
        other[18..20].copy_from_slice(&(if std::env::consts::ARCH == "riscv64" { 62u16 } else { 243u16 }).to_le_bytes());
4691×
        assert!(check_target(&other).unwrap_err().to_string().contains("another machine"));
4701×
    }
471
472
    #[test]
4731×
    fn a_swap_keeps_the_old_build_and_three_failed_starts_bring_it_back() {
4741×
        let dir = tempfile::tempdir().unwrap();
4751×
        let (bin, home) = (dir.path().join("bin"), dir.path().join("home"));
4761×
        std::fs::create_dir_all(&bin).unwrap();
4771×
        std::fs::create_dir_all(&home).unwrap();
4781×
        let exe = bin.join("flow");
4791×
        std::fs::write(&exe, "old").unwrap();
4801×
        std::fs::write(bin.join(NEW), "new").unwrap();
4811×
        swap(&exe, &bin.join(NEW)).unwrap();
4821×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "new");
4831×
        assert_eq!(std::fs::read_to_string(bin.join(PREV)).unwrap(), "old");
4841×
        assert!(!bin.join(NEW).exists());
485
4861×
        assert_eq!(on_start(&home).unwrap(), Start::Settled, "no update, nothing to do");
4871×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 600, starts: 0 };
4881×
        save(&home, &p).unwrap();
4893×
        for n in 1..=MAX_STARTS {
4903×
            assert_eq!(on_start(&home).unwrap(), Start::Trial(Pending { starts: n, ..p.clone() }));
491
        }
4921×
        assert!(matches!(on_start(&home).unwrap(), Start::RolledBack(_)));
4931×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "old", "the previous build is back");
4941×
        assert!(pending(&home).is_none());
4951×
        let log = std::fs::read_to_string(home.join(LOG)).unwrap();
4961×
        assert!(log.contains("rolled back") && log.contains("0.3.2"), "{log}");
4971×
    }
498
499
    #[test]
5001×
    fn a_windows_build_is_checked_as_pe_and_named_beside_with_its_extension() {
5011×
        let mut pe = vec![0u8; 0x100];
5021×
        pe[..2].copy_from_slice(b"MZ");
5031×
        pe[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
5041×
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
5051×
        pe[0x84..0x86].copy_from_slice(&0x8664u16.to_le_bytes());
5061×
        if std::env::consts::ARCH == "x86_64" {
5071×
            check_pe(&pe).unwrap();
5081×
        }
5091×
        pe[0x84..0x86].copy_from_slice(&0x01c4u16.to_le_bytes());
5101×
        assert!(check_pe(&pe).is_err(), "another machine");
5111×
        assert!(check_pe(b"\x7fELF and more bytes than enough for a header, really, quite a few more")
5121×
            .unwrap_err()
5131×
            .to_string()
5141×
            .contains("not a Windows"));
5151×
        assert_eq!(beside(Path::new("C:/flow/flow.exe"), PREV), Path::new("C:/flow/flow.prev.exe"));
5161×
        assert_eq!(beside(Path::new("/usr/local/bin/flow"), NEW), Path::new("/usr/local/bin/flow.new"));
5171×
    }
518
519
    #[test]
5201×
    fn a_drain_is_asked_by_file_once() {
5211×
        let dir = tempfile::tempdir().unwrap();
5221×
        assert!(!ask_to_drain(dir.path()).unwrap(), "no runner running");
5231×
        assert!(drain_requested(dir.path()) && !drain_requested(dir.path()));
5241×
        note_runner(dir.path());
5251×
        assert!(ask_to_drain(dir.path()).unwrap());
5261×
        note_runner(dir.path());
5271×
        assert!(!drain_requested(dir.path()), "a starting runner clears a stale request");
5281×
    }
529
530
    #[test]
5311×
    fn a_request_file_asks_once() {
5321×
        let dir = tempfile::tempdir().unwrap();
5331×
        assert!(!requested(dir.path()));
5341×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5351×
        assert!(requested(dir.path()) && !requested(dir.path()), "read once");
5361×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5371×
        note_runner(dir.path());
5381×
        assert!(!requested(dir.path()), "a starting runner clears a stale request");
5391×
    }
540
541
    #[test]
5421×
    fn only_a_running_runner_is_told() {
5431×
        assert!(is_runner(b"/usr/local/bin/flow\0runner\0"));
5441×
        assert!(is_runner(b"flow\0--home\0/srv/flow\0runner\0"));
5451×
        assert!(!is_runner(b"flow\0runner\0update\0--from\0x\0"), "not the update command itself");
5461×
        assert!(!is_runner(b"/usr/bin/vim\0runner\0"));
5471×
        assert!(!is_runner(b""));
5481×
        let dir = tempfile::tempdir().unwrap();
5491×
        std::fs::write(dir.path().join(PID), std::process::id().to_string()).unwrap();
5501×
        assert_eq!(running(dir.path()), None, "this test is not a flow runner");
5511×
    }
552
553
    #[test]
5541×
    fn a_proven_build_stays() {
5551×
        let dir = tempfile::tempdir().unwrap();
5561×
        let exe = dir.path().join("flow");
5571×
        std::fs::write(&exe, "new").unwrap();
5581×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 0, starts: 1 };
5591×
        save(dir.path(), &p).unwrap();
5601×
        proven(dir.path());
5611×
        assert!(pending(dir.path()).is_none());
5621×
        assert_eq!(on_start(dir.path()).unwrap(), Start::Settled);
5631×
        assert!(std::fs::read_to_string(dir.path().join(LOG)).unwrap().contains("proven"));
5641×
    }
565
}