OXYGENHUB

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

225 of 379 lines run, 37 of 129 functions · run #190 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
/// Whether the runner has been asked, by file, to leave for a new build
325
/// (and forget the asking).
3264×
pub fn requested(home: &Path) -> bool {
3274×
    std::fs::remove_file(home.join(REQUEST)).is_ok()
3284×
}
329
330
/// The running runner's process id, from its pid file, if that process is
331
/// still a `flow runner`: a stale file's pid may be another program's now,
332
/// and SIGUSR1 would end it. Builds before #85 write no pid file (and do
333
/// not listen for SIGUSR1), so they are never told.
334
#[cfg(unix)]
3351×
fn running(home: &Path) -> Option<u32> {
3361×
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
3371×
    let cmdline = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
3381×
    is_runner(&cmdline).then_some(pid)
3391×
}
340
341
/// On Windows: a runner of this home has a pid file, and is asked by a
342
/// request file it reads (a stale one is cleared when a runner starts).
343
#[cfg(not(unix))]
344
fn running(home: &Path) -> Option<u32> {
345
    let pid: u32 = std::fs::read_to_string(home.join(PID)).ok()?.trim().parse().ok()?;
346
    std::fs::write(home.join(REQUEST), pid.to_string()).ok()?;
347
    Some(pid)
348
}
349
350
/// Whether a NUL-separated command line is `flow … runner` with no subcommand.
351
#[cfg_attr(not(unix), allow(dead_code))]
3526×
fn is_runner(cmdline: &[u8]) -> bool {
353230×
    let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).filter(|a| !a.is_empty()).collect();
3546×
    let Some((argv0, rest)) = args.split_first() else { return false };
35539×
    let name = argv0.rsplit(|b| *b == b'/').next().unwrap_or(argv0);
3565×
    name.starts_with(b"flow") && rest.last() == Some(&&b"runner"[..])
3576×
}
358
359
/// Note this process as the home's runner, for `flow runner update` to tell.
3601×
pub fn note_runner(home: &Path) {
3611×
    let _ = std::fs::remove_file(home.join(REQUEST));
3621×
    let _ = std::fs::write(home.join(PID), std::process::id().to_string());
3631×
}
364
365
/// The runner stopped: forget its pid.
3660×
pub fn forget_runner(home: &Path) {
3670×
    if std::fs::read_to_string(home.join(PID)).is_ok_and(|p| p.trim() == std::process::id().to_string()) {
3680×
        let _ = std::fs::remove_file(home.join(PID));
3690×
    }
3700×
}
371
372
/// What a runner starting up should do about an update.
373
#[derive(Debug, PartialEq, Eq)]
374
pub enum Start {
375
    /// No update waits to be proven.
376
    Settled,
377
    /// The new build is on trial: prove it within [`PROVE_WITHIN`].
378
    Trial(Pending),
379
    /// It failed too often; the previous build is back and should be run.
380
    RolledBack(Pending),
381
}
382
383
/// Count this start of an unproven build; after [`MAX_STARTS`], put the
384
/// previous build back.
3856×
pub fn on_start(home: &Path) -> Result<Start> {
3866×
    let Some(mut p) = pending(home) else { return Ok(Start::Settled) };
3874×
    p.starts += 1;
3884×
    if p.starts > MAX_STARTS {
3891×
        roll_back(home, &p, &format!("{MAX_STARTS} starts without reaching the hub"))?;
3901×
        return Ok(Start::RolledBack(p));
3913×
    }
3923×
    save(home, &p)?;
3933×
    Ok(Start::Trial(p))
3946×
}
395
396
/// In the runner's home: what to tell the hub once it answers.
397
const NOTE: &str = "update.note";
398
399
/// Keep `note` to tell the hub (a proof, a rollback) once it answers.
4002×
fn note(home: &Path, note: &str) {
4012×
    let _ = std::fs::write(home.join(NOTE), note);
4022×
}
403
404
/// What there is to tell the hub, once.
4050×
pub fn take_note(home: &Path) -> Option<String> {
4060×
    let n = std::fs::read_to_string(home.join(NOTE)).ok()?;
4070×
    let _ = std::fs::remove_file(home.join(NOTE));
4080×
    Some(n).filter(|n| !n.trim().is_empty())
4090×
}
410
411
/// The new build reached the hub: it stays.
4121×
pub fn proven(home: &Path) {
4131×
    if let Some(p) = pending(home) {
4141×
        let _ = std::fs::remove_file(home.join(PENDING));
4151×
        log(home, "proven", &p.from, &p.to, "reached the hub");
4161×
        note(home, &format!("runs flow {} (was {}); proven", p.to, p.from));
4171×
        eprintln!("flow runner: flow {} proven (it reached the hub); flow {} stays as {}", p.to, p.from, beside(&p.exe, PREV).display());
4181×
    }
4191×
}
420
421
/// Put the previous build back and forget the update.
4221×
pub fn roll_back(home: &Path, p: &Pending, why: &str) -> Result<()> {
4231×
    restore(&p.exe)?;
4241×
    let _ = std::fs::remove_file(home.join(PENDING));
4251×
    log(home, "rolled back", &p.to, &p.from, why);
4261×
    note(home, &format!("rolled back from flow {} to {}: {why}", p.to, p.from));
4271×
    eprintln!("flow runner: rolled back from flow {} to {} ({why})", p.to, p.from);
4281×
    Ok(())
4291×
}
430
431
#[cfg(test)]
432
mod tests {
433
    use super::*;
434
435
    #[test]
4361×
    fn versions_are_read_and_compared() {
4371×
        assert_eq!(parse_version("flow 0.3.1 (local build)\n").as_deref(), Some("0.3.1"));
4381×
        assert_eq!(parse_version("flow 0.10.0"), Some("0.10.0".into()));
4391×
        assert_eq!(parse_version("oxy 0.6.0"), None);
4401×
        assert_eq!(parse_version("flow banana"), None);
4411×
        assert!(older("0.3.1", "0.10.0"), "by number, not by text");
4421×
        assert!(!older("0.3.1", "0.3.1"));
4431×
        assert!(older("0.3", "0.3.1"));
4441×
    }
445
446
    #[test]
4471×
    fn only_a_build_for_this_machine_passes() {
4481×
        let me = std::fs::read(std::env::current_exe().unwrap()).unwrap();
4491×
        check_target(&me[..64]).unwrap();
4501×
        assert!(check_target(b"#!/bin/sh\necho flow 9.9.9\n").unwrap_err().to_string().contains("not an ELF"));
4511×
        let mut other = me[..64].to_vec();
4521×
        other[18..20].copy_from_slice(&(if std::env::consts::ARCH == "riscv64" { 62u16 } else { 243u16 }).to_le_bytes());
4531×
        assert!(check_target(&other).unwrap_err().to_string().contains("another machine"));
4541×
    }
455
456
    #[test]
4571×
    fn a_swap_keeps_the_old_build_and_three_failed_starts_bring_it_back() {
4581×
        let dir = tempfile::tempdir().unwrap();
4591×
        let (bin, home) = (dir.path().join("bin"), dir.path().join("home"));
4601×
        std::fs::create_dir_all(&bin).unwrap();
4611×
        std::fs::create_dir_all(&home).unwrap();
4621×
        let exe = bin.join("flow");
4631×
        std::fs::write(&exe, "old").unwrap();
4641×
        std::fs::write(bin.join(NEW), "new").unwrap();
4651×
        swap(&exe, &bin.join(NEW)).unwrap();
4661×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "new");
4671×
        assert_eq!(std::fs::read_to_string(bin.join(PREV)).unwrap(), "old");
4681×
        assert!(!bin.join(NEW).exists());
469
4701×
        assert_eq!(on_start(&home).unwrap(), Start::Settled, "no update, nothing to do");
4711×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 600, starts: 0 };
4721×
        save(&home, &p).unwrap();
4733×
        for n in 1..=MAX_STARTS {
4743×
            assert_eq!(on_start(&home).unwrap(), Start::Trial(Pending { starts: n, ..p.clone() }));
475
        }
4761×
        assert!(matches!(on_start(&home).unwrap(), Start::RolledBack(_)));
4771×
        assert_eq!(std::fs::read_to_string(&exe).unwrap(), "old", "the previous build is back");
4781×
        assert!(pending(&home).is_none());
4791×
        let log = std::fs::read_to_string(home.join(LOG)).unwrap();
4801×
        assert!(log.contains("rolled back") && log.contains("0.3.2"), "{log}");
4811×
    }
482
483
    #[test]
4841×
    fn a_windows_build_is_checked_as_pe_and_named_beside_with_its_extension() {
4851×
        let mut pe = vec![0u8; 0x100];
4861×
        pe[..2].copy_from_slice(b"MZ");
4871×
        pe[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
4881×
        pe[0x80..0x84].copy_from_slice(b"PE\0\0");
4891×
        pe[0x84..0x86].copy_from_slice(&0x8664u16.to_le_bytes());
4901×
        if std::env::consts::ARCH == "x86_64" {
4911×
            check_pe(&pe).unwrap();
4921×
        }
4931×
        pe[0x84..0x86].copy_from_slice(&0x01c4u16.to_le_bytes());
4941×
        assert!(check_pe(&pe).is_err(), "another machine");
4951×
        assert!(check_pe(b"\x7fELF and more bytes than enough for a header, really, quite a few more")
4961×
            .unwrap_err()
4971×
            .to_string()
4981×
            .contains("not a Windows"));
4991×
        assert_eq!(beside(Path::new("C:/flow/flow.exe"), PREV), Path::new("C:/flow/flow.prev.exe"));
5001×
        assert_eq!(beside(Path::new("/usr/local/bin/flow"), NEW), Path::new("/usr/local/bin/flow.new"));
5011×
    }
502
503
    #[test]
5041×
    fn a_request_file_asks_once() {
5051×
        let dir = tempfile::tempdir().unwrap();
5061×
        assert!(!requested(dir.path()));
5071×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5081×
        assert!(requested(dir.path()) && !requested(dir.path()), "read once");
5091×
        std::fs::write(dir.path().join(REQUEST), "1").unwrap();
5101×
        note_runner(dir.path());
5111×
        assert!(!requested(dir.path()), "a starting runner clears a stale request");
5121×
    }
513
514
    #[test]
5151×
    fn only_a_running_runner_is_told() {
5161×
        assert!(is_runner(b"/usr/local/bin/flow\0runner\0"));
5171×
        assert!(is_runner(b"flow\0--home\0/srv/flow\0runner\0"));
5181×
        assert!(!is_runner(b"flow\0runner\0update\0--from\0x\0"), "not the update command itself");
5191×
        assert!(!is_runner(b"/usr/bin/vim\0runner\0"));
5201×
        assert!(!is_runner(b""));
5211×
        let dir = tempfile::tempdir().unwrap();
5221×
        std::fs::write(dir.path().join(PID), std::process::id().to_string()).unwrap();
5231×
        assert_eq!(running(dir.path()), None, "this test is not a flow runner");
5241×
    }
525
526
    #[test]
5271×
    fn a_proven_build_stays() {
5281×
        let dir = tempfile::tempdir().unwrap();
5291×
        let exe = dir.path().join("flow");
5301×
        std::fs::write(&exe, "new").unwrap();
5311×
        let p = Pending { from: "0.3.1".into(), to: "0.3.2".into(), exe: exe.clone(), at_ms: 1, notice_secs: 0, starts: 1 };
5321×
        save(dir.path(), &p).unwrap();
5331×
        proven(dir.path());
5341×
        assert!(pending(dir.path()).is_none());
5351×
        assert_eq!(on_start(dir.path()).unwrap(), Start::Settled);
5361×
        assert!(std::fs::read_to_string(dir.path().join(LOG)).unwrap().contains("proven"));
5371×
    }
538
}