OXYGENHUB

Coverage / crates/flow/src/runner.rs 45.2%

808 of 1786 lines run, 92 of 413 functions · run #185 on main · run missed

1
//! `flow runner` (docs/m0.md §5): claim a job from OxygenHub, fetch the
2
//! repository into a cache with the job's token, write the state into a
3
//! workspace, run it in its tier, stream the log, report the receipt.
4
//! One job at a time.
5
6
use crate::home::{Home, RunnerConfig, RunnerKey};
7
use crate::{microvm, workspace};
8
use anyhow::{bail, Context, Result};
9
use flow_core::api::{Claim, ClaimRequest, Decline, Finish, LogBatch, Record, Register, Registered, RunnerInfo, MAX_RECORD_TEXT};
10
use flow_core::{scope_tree_hash, Receipt};
11
use oxy_core::hash::ChangeHash;
12
use oxy_core::repo::Repo;
13
use std::path::{Path, PathBuf};
14
use std::time::{Duration, Instant};
15
16
/// A request the hub refused (4xx). On a job's endpoints, 409 means the
17
/// job no longer runs: it was cancelled, or given up.
18
#[derive(Debug)]
19
pub struct Refused {
20
    pub code: u16,
21
    pub text: String,
22
}
23
24
impl std::fmt::Display for Refused {
250×
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260×
        write!(f, "HTTP {}: {}", self.code, self.text)
270×
    }
28
}
29
30
impl std::error::Error for Refused {}
31
32
/// Whether `e` is the hub saying the job no longer runs.
333×
fn job_gone(e: &anyhow::Error) -> bool {
343×
    e.downcast_ref::<Refused>().is_some_and(|r| r.code == 409)
353×
}
36
37
/// What a job ends with when its run was cancelled: nothing is reported,
38
/// as the hub has ended it already.
39
const CANCELLED: &str = "the run was cancelled";
40
410×
fn cancelled() -> Finish {
420×
    Finish {
430×
        exit_code: None,
440×
        duration_ms: 0,
450×
        receipt: None,
460×
        signed_receipt: None,
470×
        error: Some(CANCELLED.into()),
480×
        peak_disk_mib: None,
490×
        peak_memory_mib: None,
500×
    }
510×
}
52
53
pub struct Hub {
54
    base: String,
55
    token: String,
56
    agent: ureq::Agent,
57
}
58
59
impl Hub {
600×
    pub fn new(cfg: &RunnerConfig) -> Result<Hub> {
610×
        let tls = oxy_core::protocol::tls_client_config(cfg.ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
620×
        let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
630×
        Ok(Hub { base: cfg.hub.trim_end_matches('/').to_string(), token: cfg.token.clone(), agent })
640×
    }
65
66
    /// POST to the hub. A server error (5xx) means nothing was committed,
67
    /// so it is tried again after 1, 2 and 4 seconds before giving up: a
68
    /// busy hub costs a job a few seconds, not its log lines or its claim.
698×
    fn post(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
708×
        self.post_with(path, body, &RETRY_DELAYS)
718×
    }
72
7311×
    fn post_with(&self, path: &str, body: &impl serde::Serialize, delays: &[Duration]) -> Result<Option<ureq::Response>> {
7411×
        let url = format!("{}/api/v1{path}", self.base);
7516×
        let r = retrying(&url, delays, false, || {
7616×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
7716×
        })?;
786×
        Ok(if r.status() == 204 { None } else { Some(r) })
7911×
    }
80
81
    /// POST what a job leaves behind (oxygenflow#49): through a hub that is
82
    /// away for a few minutes, as while a deploy restarts it, so a job's
83
    /// declines and uploads outlast it.
841×
    fn post_patiently(&self, path: &str, body: &impl serde::Serialize) -> Result<Option<ureq::Response>> {
851×
        let url = format!("{}/api/v1{path}", self.base);
861×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
871×
            self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(body).map_err(Box::new)
881×
        })?;
891×
        Ok(if r.status() == 204 { None } else { Some(r) })
901×
    }
91
920×
    pub fn claim(&self, req: &ClaimRequest) -> Result<Option<Claim>> {
930×
        match self.post("/flow/claim", req)? {
940×
            Some(r) => Ok(Some(r.into_json()?)),
950×
            None => Ok(None),
96
        }
970×
    }
98
99
    /// Hand job `job` back, saying why this runner will not run it.
1000×
    pub fn decline(&self, job: i64, reason: &str) -> Result<()> {
1010×
        self.post_patiently(&format!("/flow/jobs/{job}/decline"), &Decline { reason: reason.into() })?;
1020×
        Ok(())
1030×
    }
104
105
    /// Hand back a job this runner holds as it leaves (oxygenflow#76): the
106
    /// hub queues it again ahead of new work for another runner.
1071×
    pub fn release(&self, job: i64, reason: &str) -> Result<()> {
1081×
        self.post_patiently(&format!("/flow/jobs/{job}/release"), &Decline { reason: reason.into() })?;
1091×
        Ok(())
1101×
    }
111
112
    /// Say this runner is there while it claims nothing: its slots are full,
113
    /// or it is draining (oxygenhub#243). Once, no retries: the next comes
114
    /// soon. A hub without the endpoint (404) is not an error.
115
    /// A ten-minute certificate for `identity`, asked with a job's token
116
    /// (keyless, oxygenhub#241), and the identity of the hub's key that
117
    /// issued it, from `/.well-known/oxyhub-key`.
1183×
    pub fn certify(
1193×
        &self,
1203×
        job_token: &str,
1213×
        identity: &oxy_core::identity::Identity,
1223×
        proof: &oxy_core::identity::Signature,
1233×
    ) -> Result<(oxy_core::cert::SignedCertificate, oxy_core::identity::Identity)> {
124
        use oxy_core::dsse::{base64, base64_decode};
1253×
        let body = serde_json::json!({
1263×
            "identity": base64(&identity.encode()),
1273×
            "proof": base64(&oxy_core::cbor::encode(&proof.to_value())),
1283×
            "scope": "seal",
129
        });
1303×
        let url = format!("{}/api/v1/keyless/certify", self.base);
1313×
        let r = self
1323×
            .agent
1333×
            .post(&url)
1343×
            .set("Authorization", &format!("Bearer {job_token}"))
1353×
            .send_json(body)
1363×
            .map_err(|e| anyhow::anyhow!("asking the hub to certify the key: {e}"))?;
1373×
        let v: serde_json::Value = r.into_json()?;
1383×
        let cert = base64_decode(v["certificate"].as_str().unwrap_or(""))
1393×
            .context("the hub's answer has no certificate")
1403×
            .and_then(|b| oxy_core::cert::SignedCertificate::decode(&b).map_err(|e| anyhow::anyhow!("{e}")))?;
1413×
        let mut bytes = Vec::new();
1423×
        std::io::Read::read_to_end(
1433×
            &mut self.agent.get(&format!("{}/.well-known/oxyhub-key", self.base)).call()?.into_reader(),
1443×
            &mut bytes,
1450×
        )?;
1463×
        let issuer = oxy_core::identity::Identity::decode(&bytes)?;
1473×
        if issuer.hash() != cert.cert.issuer || cert.verify(&issuer).is_err() {
1481×
            bail!("the certificate is not signed by the hub's published key");
1492×
        }
1502×
        if cert.cert.key_id() != identity.hash() {
1511×
            bail!("the hub certified another key");
1521×
        }
1531×
        Ok((cert, issuer))
1543×
    }
155
1560×
    pub fn heartbeat(&self) -> Result<()> {
1570×
        match self.post_with("/flow/runners/heartbeat", &serde_json::json!({}), &[]) {
1580×
            Ok(_) => Ok(()),
1590×
            Err(e) if format!("{e:#}").contains("404") => Ok(()),
1600×
            Err(e) => Err(e),
161
        }
1620×
    }
163
164
    /// The update policy for this runner and the build it should run
165
    /// (oxygenhub#322); `None` from a hub without runner updates.
1660×
    pub fn update_answer(&self) -> Result<Option<flow_core::api::UpdateAnswer>> {
1670×
        let url = format!("{}/api/v1/flow/runner/update", self.base);
1680×
        match self.agent.get(&url).set("Authorization", &format!("Bearer {}", self.token)).call() {
1690×
            Ok(r) => Ok(Some(r.into_json()?)),
1700×
            Err(ureq::Error::Status(404, _)) => Ok(None),
1710×
            Err(e) => Err(anyhow::anyhow!("{url}: {e}")),
172
        }
1730×
    }
174
175
    /// Tell the hub what this runner did about its update.
1760×
    pub fn report_update(&self, note: &str) -> Result<()> {
1770×
        self.post_with("/flow/runner/update", &flow_core::api::UpdateReport { note: note.to_string() }, &[])?;
1780×
        Ok(())
1790×
    }
180
181
    /// Download an offered build to `to`, refusing it unless its BLAKE3
182
    /// is the one the hub attests and it is the size it said.
1832×
    pub fn download_build(&self, offer: &flow_core::api::UpdateOffer, to: &Path) -> Result<()> {
184
        use std::io::{Read, Write};
1852×
        let url = format!("{}{}", self.base, offer.url);
1862×
        let r = self.agent.get(&url).timeout(Duration::from_secs(1800)).call().map_err(|e| anyhow::anyhow!("{url}: {e}"))?;
1872×
        let part = to.with_extension("partial");
1882×
        let mut out = std::fs::File::create(&part).with_context(|| format!("writing {}", part.display()))?;
1892×
        let (mut hasher, mut n, mut buf) = (blake3::Hasher::new(), 0u64, vec![0u8; 1 << 16]);
1902×
        let mut body = r.into_reader().take(offer.size + 1);
191
        loop {
1924×
            let k = body.read(&mut buf)?;
1934×
            if k == 0 {
1942×
                break;
1952×
            }
1962×
            hasher.update(&buf[..k]);
1972×
            out.write_all(&buf[..k])?;
1982×
            n += k as u64;
199
        }
2002×
        drop(out);
2012×
        let got = hasher.finalize().to_hex().to_string();
2022×
        if n != offer.size || got != offer.blake3 {
2031×
            let _ = std::fs::remove_file(&part);
2041×
            bail!("{} does not match what the hub attests ({n} bytes, BLAKE3 {}…)", offer.asset, &got[..12]);
2051×
        }
2061×
        std::fs::rename(&part, to)?;
2071×
        Ok(())
2082×
    }
209
2108×
    pub fn log(&self, job: i64, records: Vec<Record>) -> Result<()> {
2118×
        self.post(&format!("/flow/jobs/{job}/log"), &LogBatch { records })?;
2125×
        Ok(())
2138×
    }
214
215
    /// Upload artifact `name` of job `job` (spec §5.2); the hub keeps it as
216
    /// a blob of the job's repository and answers with its ObjectRef.
2170×
    pub fn artifact(&self, job: i64, name: &str, bytes: &[u8]) -> Result<String> {
2180×
        let url = format!("{}/api/v1/flow/jobs/{job}/artifacts/{name}", self.base);
2190×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2200×
            self.agent
2210×
                .post(&url)
2220×
                .timeout(Duration::from_secs(600))
2230×
                .set("Authorization", &format!("Bearer {}", self.token))
2240×
                .set("Content-Type", "application/octet-stream")
2250×
                .send_bytes(bytes)
2260×
                .map_err(Box::new)
2270×
        })?;
2280×
        let v: serde_json::Value = r.into_json()?;
2290×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2300×
    }
231
232
    /// Keep a checkpoint of job `job` (oxygenflow#77) as its runner hands
233
    /// it back: the hub answers with its blob, which the next attempt's
234
    /// claim names.
2350×
    pub fn save_checkpoint(&self, job: i64, bytes: &[u8]) -> Result<String> {
2360×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2370×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2380×
            self.agent
2390×
                .post(&url)
2400×
                .timeout(Duration::from_secs(600))
2410×
                .set("Authorization", &format!("Bearer {}", self.token))
2420×
                .set("Content-Type", "application/octet-stream")
2430×
                .send_bytes(bytes)
2440×
                .map_err(Box::new)
2450×
        })?;
2460×
        let v: serde_json::Value = r.into_json()?;
2470×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
2480×
    }
249
250
    /// The checkpoint an earlier attempt of job `job` saved (oxygenflow#77),
251
    /// which the caller checks against the blob its claim names.
2520×
    pub fn checkpoint(&self, job: i64) -> Result<Vec<u8>> {
2530×
        let url = format!("{}/api/v1/flow/jobs/{job}/checkpoint", self.base);
2540×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2550×
            self.agent
2560×
                .get(&url)
2570×
                .timeout(Duration::from_secs(600))
2580×
                .set("Authorization", &format!("Bearer {}", self.token))
2590×
                .call()
2600×
                .map_err(Box::new)
2610×
        })?;
2620×
        let mut bytes = Vec::new();
2630×
        std::io::Read::read_to_end(&mut std::io::Read::take(r.into_reader(), crate::checkpoint::MAX_BYTES as u64 + 1), &mut bytes)?;
2640×
        Ok(bytes)
2650×
    }
266
267
    /// Input `index` of job `job` (oxygenflow#58): the bytes of the
268
    /// producing job's artifact, which the caller checks against the blob the
269
    /// claim names.
2700×
    pub fn input(&self, job: i64, index: usize) -> Result<Vec<u8>> {
2710×
        let url = format!("{}/api/v1/flow/jobs/{job}/inputs/{index}", self.base);
2720×
        let r = retrying(&url, &PATIENT_DELAYS, false, || {
2730×
            self.agent
2740×
                .get(&url)
2750×
                .timeout(Duration::from_secs(600))
2760×
                .set("Authorization", &format!("Bearer {}", self.token))
2770×
                .call()
2780×
                .map_err(Box::new)
2790×
        })?;
2800×
        let mut bytes = Vec::new();
2810×
        let mut reader = r.into_reader();
2820×
        std::io::Read::read_to_end(&mut std::io::Read::take(&mut reader, MAX_INPUT_BYTES as u64 + 1), &mut bytes)?;
2830×
        if bytes.len() > MAX_INPUT_BYTES {
2840×
            bail!("larger than {} MiB", MAX_INPUT_BYTES >> 20);
2850×
        }
2860×
        Ok(bytes)
2870×
    }
288
289
    /// Upload file `path` of report `name` of job `job` (oxygenhub#127);
290
    /// the hub keeps it as a blob and answers with its ObjectRef. The
291
    /// report's manifest follows through [`Hub::artifact`].
2920×
    pub fn report_file(&self, job: i64, name: &str, path: &str, bytes: &[u8]) -> Result<String> {
2930×
        let url = format!("{}/api/v1/flow/jobs/{job}/reports/{name}/files", self.base);
2940×
        let r = retrying(&url, &PATIENT_DELAYS, true, || {
2950×
            self.agent
2960×
                .post(&url)
2970×
                .timeout(Duration::from_secs(600))
2980×
                .set("Authorization", &format!("Bearer {}", self.token))
2990×
                .set("Content-Type", "application/octet-stream")
3000×
                .set("X-Flow-Report-Path", path)
3010×
                .send_bytes(bytes)
3020×
                .map_err(Box::new)
3030×
        })?;
3040×
        let v: serde_json::Value = r.into_json()?;
3050×
        v["blob"].as_str().map(String::from).context("the hub named no blob")
3060×
    }
307
308
    /// Report a job's end until the hub has it (oxygenhub#71): while the hub
309
    /// cannot be reached or fails (5xx), try again after `first_wait`,
310
    /// doubling to a minute, for up to `patience`. A refusal (4xx: the job was ended
311
    /// already, say) is final. A result lost here leaves the job running
312
    /// on the hub until its time limit.
3132×
    pub fn finish_until_accepted(&self, job: i64, f: &Finish, patience: Duration, first_wait: Duration) -> Result<()> {
3142×
        let url = format!("{}/api/v1/flow/jobs/{job}/finish", self.base);
3152×
        let deadline = std::time::Instant::now() + patience;
3162×
        let mut wait = first_wait;
317
        loop {
3186×
            let why = match self.agent.post(&url).set("Authorization", &format!("Bearer {}", self.token)).send_json(f) {
3191×
                Ok(_) => return Ok(()),
3205×
                Err(ureq::Error::Status(code, r)) if code < 500 => {
3211×
                    bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default())
322
                }
3234×
                Err(ureq::Error::Status(code, _)) => format!("HTTP {code}"),
3240×
                Err(e) => e.to_string(),
325
            };
3264×
            if std::time::Instant::now() + wait > deadline {
3270×
                bail!("{url}: gave up after {} minutes: {why}", patience.as_secs() / 60);
3284×
            }
3294×
            eprintln!("job {job}: the hub did not take the result ({why}); trying again in {} s", wait.as_secs());
3304×
            std::thread::sleep(wait);
3314×
            wait = (wait * 2).min(Duration::from_secs(60));
332
        }
3332×
    }
334
}
335
336
/// How long a runner keeps trying to report a job's end.
337
const FINISH_PATIENCE: Duration = Duration::from_secs(2 * 3600);
338
339
/// Where a job's result waits until the hub has it, so a runner that
340
/// restarts still reports it.
3410×
fn pending_path(home: &Home, job: i64) -> PathBuf {
3420×
    home.root.join("pending").join(format!("{job}.json"))
3430×
}
344
345
/// Report `f`, keeping it on disk until the hub has it.
3460×
fn report_finish(home: &Home, hub: &Hub, job: i64, f: &Finish) {
3470×
    let path = pending_path(home, job);
3480×
    let kept = std::fs::create_dir_all(path.parent().unwrap())
3490×
        .and_then(|_| std::fs::write(&path, serde_json::to_vec(f).unwrap_or_default()))
3500×
        .is_ok();
3510×
    match hub.finish_until_accepted(job, f, FINISH_PATIENCE, Duration::from_secs(5)) {
3520×
        Ok(()) => {}
3530×
        Err(e) => eprintln!("job {job}: reporting failed: {e:#}"),
354
    }
3550×
    if kept {
3560×
        let _ = std::fs::remove_file(&path);
3570×
    }
3580×
}
359
360
/// Results a previous run of the runner could not report, to send again.
3610×
fn report_pending(home: &Home) -> Vec<(i64, Finish)> {
3620×
    let Ok(dir) = std::fs::read_dir(home.root.join("pending")) else {
3630×
        return Vec::new();
364
    };
3650×
    dir.filter_map(|e| {
3660×
        let p = e.ok()?.path();
3670×
        let job: i64 = p.file_stem()?.to_str()?.parse().ok()?;
3680×
        let f: Finish = serde_json::from_slice(&std::fs::read(&p).ok()?).ok()?;
3690×
        Some((job, f))
3700×
    })
3710×
    .collect()
3720×
}
373
374
/// `flow runner register`: exchange a one-time registration token from
375
/// the hub for this runner's credential, binding the runner's signing key,
376
/// and keep hub, credential and name in runner.toml.
3771×
pub fn register(home: &Home, hub: &str, token: &str, name: &str, ca: Option<PathBuf>, labels: Vec<String>) -> Result<Registered> {
3781×
    if home.config.runner.is_some() && !home.root.join(crate::home::RUNNER_TOML).is_file() {
3790×
        bail!("flow.toml already has a [runner] section; remove it to register this runner instead");
3801×
    }
3811×
    let key = home.runner_key(name)?;
3821×
    let hub = hub.trim_end_matches('/').to_string();
3831×
    let tls = oxy_core::protocol::tls_client_config(ca.as_deref()).map_err(|e| anyhow::anyhow!("{e}"))?;
3841×
    let agent = ureq::AgentBuilder::new().tls_config(tls).timeout(Duration::from_secs(60)).build();
3851×
    let req = Register {
3861×
        token: token.trim().to_string(),
3871×
        name: name.to_string(),
3881×
        identity: hex::encode(key.identity.encode()),
3891×
        info: RunnerInfo { version: env!("OXY_VERSION_LONG").into(), ..RunnerInfo::here(labels.clone(), 1, None, None) },
3901×
    };
3911×
    let url = format!("{hub}/api/v1/flow/runners/register");
3921×
    let got: Registered = match agent.post(&url).send_json(&req) {
3931×
        Ok(r) => r.into_json()?,
3940×
        Err(ureq::Error::Status(code, r)) => bail!("{url}: HTTP {code}: {}", r.into_string().unwrap_or_default()),
3950×
        Err(e) => bail!("{url}: {e}"),
396
    };
3971×
    let mut text = format!(
398
        "# Written by `flow runner register`; the credential is secret.\nhub = {hub:?}\ntoken = {:?}\nname = {:?}\n",
399
        got.credential, got.name
400
    );
4011×
    if let Some(ca) = &ca {
4020×
        text.push_str(&format!("ca = {:?}\n", ca.display().to_string()));
4031×
    }
4041×
    if !labels.is_empty() {
4051×
        text.push_str(&format!("labels = {labels:?}\n"));
4061×
    }
4071×
    let path = home.root.join(crate::home::RUNNER_TOML);
408
    {
409
        use std::io::Write;
410
        use std::os::unix::fs::OpenOptionsExt;
4111×
        let tmp = path.with_extension("toml.tmp");
4121×
        let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp)?;
4131×
        f.write_all(text.as_bytes())?;
4141×
        f.sync_all()?;
4151×
        std::fs::rename(&tmp, &path)?;
416
    }
4171×
    Ok(got)
4181×
}
419
420
/// Waits before trying a hub request again after a server error.
421
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
422
423
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
424
/// all, longer than a hub takes to restart.
425
/// Check an input's bytes against the blob the producing job's receipt
426
/// names, then write them at its path under `tree` (the workspace's `/src`).
4276×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
4286×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
429
    else {
4304×
        bail!("path {:?} is not a clean path under /src", i.path);
431
    };
4322×
    let blob = Repo::blob_ref(bytes);
4332×
    if blob.to_hex() != i.blob {
4341×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
4351×
    }
4361×
    let dest = tree.join(rel);
4371×
    if let Some(dir) = dest.parent() {
4381×
        std::fs::create_dir_all(dir)?;
4390×
    }
4401×
    std::fs::write(&dest, bytes)?;
4411×
    Ok(blob.0)
4426×
}
443
444
/// The largest input a job takes: the hub's artifact limit.
445
pub const MAX_INPUT_BYTES: usize = 512 << 20;
446
447
const PATIENT_DELAYS: [Duration; 15] = {
448
    let mut d = [Duration::from_secs(15); 15];
449
    d[0] = Duration::from_secs(1);
450
    d[1] = Duration::from_secs(2);
451
    d[2] = Duration::from_secs(4);
452
    d[3] = Duration::from_secs(8);
453
    d
454
};
455
456
/// Send a request until the hub answers, waiting `delays` in turn after a
457
/// server error (5xx: nothing was committed) and, when `connection`, after
458
/// the hub could not be reached at all. A refusal (4xx) is final, as a
459
/// [`Refused`] the caller can look at.
46014×
fn retrying(
46114×
    url: &str,
46214×
    delays: &[Duration],
46314×
    connection: bool,
46414×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
46514×
) -> Result<ureq::Response> {
46614×
    let mut delays = delays.iter();
467
    loop {
46823×
        let why = match send().map_err(|e| *e) {
4698×
            Ok(r) => return Ok(r),
4709×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4712×
                let text = r.into_string().unwrap_or_default();
4722×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
473
            }
4747×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4753×
            Err(e) if connection => e.to_string(),
4763×
            Err(e) => bail!("{url}: {e}"),
477
        };
47810×
        match delays.next() {
4799×
            Some(d) => std::thread::sleep(*d),
4801×
            None => bail!("{url}: {why}"),
481
        }
482
    }
48314×
}
484
485
/// What the runner may run at once (flow.toml `[runner]`): at most
486
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
487
#[derive(Debug, Default, PartialEq, Eq)]
488
pub struct Budget {
489
    pub max_jobs: usize,
490
    pub memory_mib: Option<u32>,
491
    pub cpus: Option<u32>,
492
}
493
494
/// What is in use now.
495
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
496
pub struct Used {
497
    pub jobs: usize,
498
    pub memory_mib: u32,
499
    pub cpus: u32,
500
}
501
502
impl Budget {
5030×
    pub fn of(cfg: &RunnerConfig) -> Budget {
5040×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
5050×
    }
506
507
    /// The room to ask the hub for, or `None` when no job more can start.
508
    /// A lone job may use the whole budget even if it asks for more, so a
509
    /// large sandbox is never starved.
5107×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
5117×
        if used.jobs >= self.max_jobs {
5122×
            return None;
5135×
        }
5145×
        if used.jobs == 0 {
5152×
            return Some((None, None));
5163×
        }
5173×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
5183×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
5193×
        if mem == Some(0) || cpus == Some(0) {
5201×
            return None;
5212×
        }
5222×
        Some((mem, cpus))
5237×
    }
524
}
525
526
/// The isolation tiers this machine can honour now (spec §11.1): the
527
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
528
/// flow.toml pins Firecracker; the syscall tier when this binary may use
529
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
530
/// `Err` says why there are none; the reasons for missing tiers come back
531
/// with the ones there are.
5323×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
5333×
    let mut have = Vec::new();
5343×
    let mut missing = Vec::new();
5353×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
5363×
    match (kvm, home.config.microvm.is_some()) {
5370×
        (Ok(_), true) => have.push("microvm".to_string()),
5380×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
5393×
        (Err(e), _) => missing.push(format!(
540
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
541
        )),
542
    }
5433×
    match crate::syscall::available() {
5440×
        Ok(()) => have.push("syscall".to_string()),
5453×
        Err(e) => missing.push(format!("syscall: {e}")),
546
    }
547
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5483×
    have.push("wasm".to_string());
5493×
    if have.is_empty() {
5500×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5513×
    }
5523×
    Ok((have, missing))
5533×
}
554
555
/// Fetch `claim`'s image from the hub when this home lacks it
556
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
557
/// leaves it missing, and the preflight declines the job as before.
5580×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) {
5590×
    let hash = &claim.sandbox.rootfs;
5600×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5610×
        return;
5620×
    }
5630×
    let note = |text: String| {
5640×
        eprintln!("job {}: {text}", claim.job_id);
5650×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5660×
    };
567
    // One fetch of an image at a time: two jobs wanting it wait for one.
568
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5690×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5700×
    if home.rootfs(hash).is_file() {
5710×
        return;
5720×
    }
5730×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5740×
        Ok(c) => c,
5750×
        Err(e) => return note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12])),
576
    };
5770×
    let fetched = match swarm {
5780×
        Some(sw) => {
5790×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5800×
            sw.fetch(home, hash)
581
        }
582
        None => {
5830×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
5840×
            client.fetch(home, hash)
585
        }
586
    };
5870×
    match fetched {
5880×
        Ok(Some(m)) => note(format!(
589
            "image {}: fetched {} chunks, {}{} in {:.1} s",
5900×
            &hash[..12],
591
            m.chunks,
5920×
            crate::images::human(m.bytes),
5930×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
5940×
            m.elapsed.as_secs_f64()
595
        )),
5960×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
5970×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
598
    }
5990×
}
600
601
/// Why this runner cannot run `claim` now (spec §11.5), checked before
602
/// anything is fetched: the tier, the architecture, the image and the
603
/// memory. The hub chose it from what the runner last said, which may be
604
/// out of date.
6050×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6060×
    let sb = &claim.sandbox;
6070×
    match sb.runtime {
608
        flow_core::Runtime::Microvm => {
6090×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6100×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6110×
            }
6120×
            if home.config.microvm.is_none() {
6130×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6140×
            }
615
        }
616
        flow_core::Runtime::Syscall => {
6170×
            if let Err(e) = crate::syscall::available() {
6180×
                return Some(format!("the syscall tier cannot run here: {e}"));
6190×
            }
620
        }
621
        // No image and no architecture: only the memory matters.
622
        flow_core::Runtime::Wasm => {
6230×
            return available_memory_mib()
6240×
                .filter(|free| *free < u64::from(sb.memory_mib))
6250×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
626
        }
627
    }
6280×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6290×
}
630
631
/// What stops `sb` running on this home's images, on a machine of
632
/// architecture `here` with `free_mib` of memory free.
6338×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6348×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6351×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6367×
    }
6377×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6387×
    let image = home.rootfs(&sb.rootfs);
6397×
    if !image.is_file() {
6401×
        return Some(format!("rootfs {short} is not on this runner"));
6416×
    }
6426×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6432×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6444×
    }
6454×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6461×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6473×
    }
6483×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6491×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6502×
    }
6512×
    None
6528×
}
653
654
/// `MemAvailable` from /proc/meminfo, in MiB.
6550×
fn available_memory_mib() -> Option<u64> {
6560×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6570×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6580×
    Some(kib / 1024)
6590×
}
660
6610×
pub fn serve(home: &Home) -> Result<()> {
6620×
    drain_on_stop();
6630×
    crate::update::note_runner(&home.root);
664
    // `flow runner update` swapped a new build in and asks this one to
665
    // leave with the notice it gave (#85).
6660×
    let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
6670×
    unsafe { libc::signal(libc::SIGUSR1, handler) };
6680×
    if let Some(p) = crate::update::pending(&home.root) {
669
        // On trial: a build that does not reach the hub in time goes back.
6700×
        let root = home.root.clone();
6710×
        std::thread::spawn(move || {
6720×
            std::thread::sleep(crate::update::PROVE_WITHIN);
6730×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
6740×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
6750×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
6760×
                    std::process::exit(1);
6770×
                }
6780×
            }
6790×
        });
6800×
    }
6810×
    let served = serve_until_drained(home);
6820×
    crate::update::forget_runner(&home.root);
6830×
    served
6840×
}
685
686
/// Set by SIGUSR1: a new build is in place; leave for it.
687
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
688
6890×
extern "C" fn on_update(_: libc::c_int) {
6900×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
6910×
}
692
693
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
694
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
695
/// it holds are done and reported. It may be started again afterwards.
6960×
pub fn serve_embedded(home: &Home) -> Result<()> {
6970×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
6980×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
6990×
    serve_until_drained(home)
7000×
}
701
702
/// A departure ([`leave_within`]): why, and when the runner must be gone.
703
#[derive(Clone, Debug)]
704
struct Leave {
705
    reason: String,
706
    by: Instant,
707
}
708
709
/// Set once the runner is leaving: a job whose expected rest fits before
710
/// the deadline finishes; the others are stopped and handed back
711
/// (oxygenflow#76).
712
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
713
7140×
fn leaving() -> Option<String> {
7150×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7160×
}
717
718
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
719
/// more, stop the jobs it holds and hand them back to the hub, which queues
720
/// them ahead of new work for another runner (oxygenflow#76), then return.
721
/// For a departure with no time to finish: a phone off the allowed network.
7220×
pub fn leave(reason: &str) {
7230×
    leave_within(reason, Duration::ZERO);
7240×
}
725
726
/// [`leave`], with `notice`: a job the hub expects to finish within it
727
/// (the claim's `expected_ms`, less the time it has run) finishes and is
728
/// reported; the others, and any still running when the notice is up, are
729
/// handed back. For a phone taken off charge, a spot reclaim.
7300×
pub fn leave_within(reason: &str, notice: Duration) {
7310×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7320×
    stop();
7330×
}
734
735
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
736
/// more, finish and report what it holds, then return (oxygenflow#76's
737
/// drain, for a phone taken off charge or off the allowed network).
7381×
pub fn stop() {
7391×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7401×
}
741
7420×
fn serve_until_drained(home: &Home) -> Result<()> {
7430×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
744
    // A runner offers only what it can run: a machine without KVM claims
745
    // nothing rather than taking MicroVM jobs and failing them (#36).
7460×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7470×
    for why in &missing {
7480×
        eprintln!("flow runner: not offering {why}");
7490×
    }
7500×
    let hub = Hub::new(&cfg)?;
7510×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
7520×
    let budget = Budget::of(&cfg);
7530×
    let key = home.runner_key(&name)?;
754
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
755
    // peers still runs jobs, fetching images from the hub alone.
7560×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
7570×
        eprintln!("flow runner: not joining the swarm: {e:#}");
7580×
        None
7590×
    });
7600×
    eprintln!(
761
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
762
        cfg.hub,
763
        budget.max_jobs,
7640×
        runtimes.join(", "),
7650×
        key.identity.hash().to_hex()
766
    );
7670×
    if let Some(addr) = &cfg.metrics {
7680×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
7690×
    }
7700×
    let used = std::sync::Mutex::new(Used::default());
7710×
    let mut idle = Duration::from_secs(2);
7720×
    let pending = report_pending(home);
773
    // The jobs held now, told to the hub at each claim so it can end the
774
    // ones this runner lost: a job is held from its claim until its result
775
    // is reported.
7760×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
7770×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
7780×
    std::thread::scope(|scope| {
7790×
        for (job, f) in pending {
7800×
            let (hub, held) = (&hub, &held);
7810×
            scope.spawn(move || {
7820×
                eprintln!("job {job}: reporting the result kept from before the restart");
7830×
                report_finish(home, hub, job, &f);
7840×
                held.lock().unwrap().remove(&job);
7850×
            });
786
        }
787
        // The speed (spec §11.1): measured now, and again every 15 minutes
788
        // while no job runs, so a job never shares the CPU with it.
7890×
        let measure = || {
7900×
            let (speed, ms) = crate::facts::bench();
7910×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
7920×
            speed
7930×
        };
7940×
        let mut speed = measure();
7950×
        let mut benched = Instant::now();
7960×
        let mut said_draining = false;
797
        // When the hub last heard from us (oxygenhub#243): a claim, or a
798
        // heartbeat while there is no room to claim.
7990×
        let mut heard = Instant::now();
8000×
        let beat = |heard: &mut Instant| {
8010×
            if heard.elapsed() >= HUB_HEARTBEAT {
8020×
                if let Err(e) = hub.heartbeat() {
8030×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8040×
                }
8050×
                *heard = Instant::now();
8060×
            }
8070×
        };
8080×
        let mut on_trial = crate::update::pending(&home.root).is_some();
809
        // Runner updates (oxygenhub#322): asked of the hub once it has
810
        // answered a claim, then every 15 minutes.
8110×
        let mut update_asked: Option<Instant> = None;
8120×
        let mut update_said = String::new();
813
        loop {
8140×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) {
8150×
                let p = crate::update::pending(&home.root);
8160×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8170×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8180×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8190×
                leave_within(&format!("updating to {to}"), notice);
8200×
            }
821
            // Draining (oxygenflow#50): told to stop, claim nothing more and
822
            // stop once every job held is done and reported.
8230×
            if stopping() {
8240×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8250×
                if jobs == 0 && holding == 0 {
8260×
                    eprintln!("flow runner {name}: drained, stopping");
8270×
                    break;
8280×
                }
8290×
                if !said_draining {
8300×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
8310×
                    said_draining = true;
8320×
                }
8330×
                beat(&mut heard);
8340×
                std::thread::sleep(Duration::from_millis(500));
8350×
                continue;
8360×
            }
8370×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
8380×
                speed = measure();
8390×
                benched = Instant::now();
8400×
            }
8410×
            let room = budget.room(*used.lock().unwrap());
8420×
            let Some((free_memory_mib, free_cpus)) = room else {
8430×
                beat(&mut heard);
8440×
                std::thread::sleep(Duration::from_millis(500));
8450×
                continue;
846
            };
8470×
            heard = Instant::now();
8480×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
8490×
            let req = ClaimRequest {
8500×
                runner: name.clone(),
8510×
                runtimes: runtimes.clone(),
8520×
                free_memory_mib,
8530×
                free_cpus,
8540×
                info: Some(RunnerInfo {
8550×
                    version: env!("OXY_VERSION_LONG").into(),
8560×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
8570×
                }),
858
                // Read each time: an image imported while the runner runs counts.
8590×
                images: Some(home.images()),
8600×
                image_archs: Some(home.image_archs()),
8610×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
862
                fetches_images: true,
8630×
                facts: Some(crate::facts::now(home, Some(speed))),
8640×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
8650×
                caches: Some(cache_times.keys().cloned().collect()),
8660×
                cache_times: Some(cache_times),
867
            };
8680×
            let answer = hub.claim(&req);
8690×
            if on_trial && answer.is_ok() {
8700×
                crate::update::proven(&home.root);
8710×
                on_trial = false;
8720×
            }
8730×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
8740×
                update_asked = Some(Instant::now());
8750×
                if let Some(note) = crate::update::take_note(&home.root) {
8760×
                    let _ = hub.report_update(&note);
8770×
                }
8780×
                consider_update(home, &hub, &mut update_said);
8790×
            }
8800×
            match answer {
8810×
                Ok(Some(claim)) => {
8820×
                    idle = Duration::from_secs(2);
8830×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8840×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
8850×
                    {
8860×
                        let mut u = used.lock().unwrap();
8870×
                        u.jobs += 1;
8880×
                        u.memory_mib += mem;
8890×
                        u.cpus += cpus;
8900×
                    }
8910×
                    held.lock().unwrap().insert(claim.job_id);
8920×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
8930×
                    scope.spawn(move || {
8940×
                        let id = claim.job_id;
8950×
                        fetch_image(home, hub, cfg, swarm, &claim);
8960×
                        if let Some(why) = preflight(home, &claim) {
8970×
                            eprintln!("job {id}: declined: {why}");
8980×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8990×
                            if let Err(e) = hub.decline(id, &why) {
9000×
                                eprintln!("job {id}: decline: {e:#}");
9010×
                            }
9020×
                            held.lock().unwrap().remove(&id);
9030×
                            let mut u = used.lock().unwrap();
9040×
                            u.jobs -= 1;
9050×
                            u.memory_mib -= mem;
9060×
                            u.cpus -= cpus;
9070×
                            return;
9080×
                        }
9090×
                        eprintln!(
910
                            "job {id}: {} {} on {}",
911
                            claim.repo,
912
                            claim.job.name,
9130×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
914
                        );
9150×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9160×
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
9170×
                            exit_code: None,
918
                            duration_ms: 0,
9190×
                            receipt: None,
9200×
                            signed_receipt: None,
9210×
                            error: Some(format!("{e:#}")),
9220×
                            peak_disk_mib: None,
9230×
                            peak_memory_mib: None,
9240×
                        });
9250×
                        eprintln!(
926
                            "job {id}: exit {:?}{}",
927
                            finish.exit_code,
9280×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
929
                        );
9300×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
9310×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
9320×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
9330×
                        match leaving() {
934
                            // Stopped as the runner leaves: another runner takes it.
9350×
                            Some(why) if cancelled => {
9360×
                                eprintln!("job {id}: handed back: {why}");
9370×
                                if let Err(e) = hub.release(id, &why) {
9380×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
9390×
                                }
940
                            }
9410×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
9420×
                            _ => {}
943
                        }
9440×
                        held.lock().unwrap().remove(&id);
9450×
                        let mut u = used.lock().unwrap();
9460×
                        u.jobs -= 1;
9470×
                        u.memory_mib -= mem;
9480×
                        u.cpus -= cpus;
9490×
                    });
950
                }
9510×
                Ok(None) => std::thread::sleep(idle),
9520×
                Err(e) => {
9530×
                    eprintln!("claim: {e:#}");
9540×
                    std::thread::sleep(idle);
9550×
                    idle = (idle * 2).min(Duration::from_secs(60));
9560×
                }
957
            }
958
        }
9590×
        Ok(())
9600×
    })
9610×
}
962
963
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
964
/// happened goes to its log, and a failure only means the next attempt
965
/// starts again.
966
#[allow(clippy::too_many_arguments)]
9670×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
9680×
    if !dir_tier {
9690×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
9700×
        return;
9710×
    }
9720×
    let dirs: Vec<(String, PathBuf)> = job
9730×
        .checkpoints
9740×
        .iter()
9750×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
9760×
        .collect();
9770×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
9780×
        Ok((blob, n)) => {
9790×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
980
        }
9810×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
982
    }
9830×
}
984
985
/// How many times the runner was told to stop (SIGTERM or SIGINT).
986
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
987
9881×
extern "C" fn on_stop(_: libc::c_int) {
989
    // A second stop means now: only async-signal-safe calls here.
9901×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
9910×
        unsafe { libc::_exit(143) };
9921×
    }
9931×
}
994
995
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
996
/// so restarting a runner never kills the job it runs: the unit's
997
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
9980×
fn drain_on_stop() {
9990×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10000×
    unsafe {
10010×
        libc::signal(libc::SIGTERM, handler);
10020×
        libc::signal(libc::SIGINT, handler);
10030×
    }
10040×
}
1005
10063×
fn stopping() -> bool {
10073×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10083×
}
1009
1010
/// Batches records to the hub every second (or every 200 lines). A quiet
1011
/// job's sink still asks the hub every few seconds whether the job runs,
1012
/// with an empty batch; once the hub answers 409 the job is not wanted.
1013
struct LogSink<'a> {
1014
    hub: &'a Hub,
1015
    job: i64,
1016
    buf: Vec<Record>,
1017
    last: Instant,
1018
    gone: bool,
1019
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1020
    /// handed back, unless its expected rest fits the notice.
1021
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1022
    /// When the job started, and how long the hub expects it to take.
1023
    started: Instant,
1024
    expected: Option<Duration>,
1025
}
1026
1027
/// The most log lines sent at once, as a busy job's sink flushes them.
1028
const BATCH: usize = 200;
1029
1030
/// The most log lines kept while the hub cannot be reached.
1031
const MAX_UNSENT: usize = 50_000;
1032
1033
/// How often a quiet job asks whether it was cancelled.
1034
const HEARTBEAT: Duration = Duration::from_secs(5);
1035
1036
impl microvm::Sink for LogSink<'_> {
10371×
    fn record(&mut self, r: Record) {
10381×
        self.push(r)
10391×
    }
1040
104110×
    fn cancelled(&mut self) -> bool {
104210×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
104310×
        if let Some(l) = leave {
1044
            // Finished if what is left of it fits the notice; else handed
1045
            // back as the runner leaves, what the job said so far first.
10465×
            let now = Instant::now();
10475×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
10485×
            if !fits || now >= l.by {
10494×
                self.flush();
10504×
                return true;
10511×
            }
10525×
        }
10536×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
10542×
            self.send();
10554×
        }
10566×
        self.gone
105710×
    }
1058
}
1059
1060
impl LogSink<'_> {
10611×
    fn push(&mut self, mut r: Record) {
10621×
        if self.gone {
10631×
            return;
10640×
        }
10650×
        if r.text.len() > MAX_RECORD_TEXT {
10660×
            let mut cut = MAX_RECORD_TEXT;
10670×
            while !r.text.is_char_boundary(cut) {
10680×
                cut -= 1;
10690×
            }
10700×
            r.text.truncate(cut);
10710×
        }
10720×
        self.buf.push(r);
10730×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
10740×
            self.flush();
10750×
        }
10761×
    }
1077
10785×
    fn flush(&mut self) {
10795×
        if !self.buf.is_empty() {
10801×
            self.send();
10814×
        }
10825×
        self.last = Instant::now();
10835×
    }
1084
1085
    /// Send what is buffered, even nothing, in batches of at most
1086
    /// `BATCH` lines.
10876×
    fn send(&mut self) {
1088
        loop {
10898×
            if self.gone {
10900×
                return;
10918×
            }
10928×
            let n = self.buf.len().min(BATCH);
10938×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
10948×
            match self.hub.log(self.job, batch.clone()) {
10955×
                Ok(()) => {}
10963×
                Err(e) if job_gone(&e) => self.gone = true,
10972×
                Err(e) => {
1098
                    // The hub is away (a restart, say): keep the lines for
1099
                    // the next batch, up to a bound, so the log loses none
1100
                    // (oxygenflow#49).
11012×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11022×
                    let mut kept = batch;
11032×
                    kept.append(&mut self.buf);
11042×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11052×
                    if over > 0 {
11061×
                        kept.drain(..over);
11071×
                        kept.insert(
11081×
                            0,
11091×
                            Record {
11101×
                                t: 0,
11111×
                                stream: "flow".into(),
11121×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11131×
                            },
11141×
                        );
11151×
                    }
11162×
                    self.buf = kept;
11172×
                    break;
1118
                }
1119
            }
11206×
            if self.buf.is_empty() {
11214×
                break;
11222×
            }
1123
        }
11246×
        self.last = Instant::now();
11256×
    }
1126
}
1127
1128
/// How often a runner with no room to claim tells the hub it is there:
1129
/// well inside the hub's 90 s before it shows a runner offline.
1130
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1131
1132
/// How often a runner asks the hub whether it should run another build.
1133
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1134
1135
/// Notice a runner gives itself to leave for an update the hub offered.
1136
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1137
1138
/// Ask the hub for this runner's update, and act on it: download the build
1139
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1140
/// install it, or for a dry run say what would happen. What it did goes to
1141
/// the hub once per outcome (`said`).
11420×
fn consider_update(home: &Home, hub: &Hub, said: &mut String) {
11430×
    let answer = match hub.update_answer() {
11440×
        Ok(Some(a)) => a,
11450×
        Ok(None) => return,
11460×
        Err(e) => {
11470×
            eprintln!("flow runner: asking for an update: {e:#}");
11480×
            return;
1149
        }
1150
    };
11510×
    let Some(offer) = answer.offer else { return };
11520×
    let mut say = |note: String| {
11530×
        if *said != note {
11540×
            eprintln!("flow runner: {note}");
11550×
            if let Err(e) = hub.report_update(&note) {
11560×
                eprintln!("flow runner: telling the hub: {e:#}");
11570×
            }
11580×
            *said = note;
11590×
        }
11600×
    };
11610×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
11620×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
11630×
    }
11640×
    let dir = home.root.join("updates");
11650×
    let file = dir.join(format!("flow-{}", offer.version));
11660×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
11670×
    if !fresh {
11680×
        if let Err(e) = std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| hub.download_build(&offer, &file)) {
11690×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
11700×
        }
11710×
    }
11720×
    let exe = match std::env::current_exe() {
11730×
        Ok(e) => e,
11740×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1175
    };
11760×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
11770×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
11780×
        Ok(done) => {
11790×
            let _ = std::fs::remove_file(&file);
11800×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1181
        }
11820×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1183
    }
11840×
}
1185
1186
/// Held while a job takes its cache disks and images its workspace (see
1187
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1188
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1189
1190
/// Held while the first clone of any repository passes its token through
1191
/// the process environment.
1192
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1193
1194
/// One lock per cached repository: fetches into it, and exports from it,
1195
/// never overlap, while jobs of other repositories go on. A slow repository
1196
/// (one kept in a bucket, say) once held every job on the runner waiting
1197
/// behind a single global lock.
11980×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1199
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1200
        std::sync::OnceLock::new();
12010×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
12020×
    locks.entry(name.to_string()).or_default().clone()
12030×
}
1204
1205
/// Seconds, to one decimal place, for the job's log.
12060×
fn secs(d: std::time::Duration) -> String {
12070×
    format!("{:.1} s", d.as_secs_f64())
12080×
}
1209
12100×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
12110×
    let started = Instant::now();
12120×
    let mut sink = LogSink {
12130×
        hub,
12140×
        job: claim.job_id,
12150×
        buf: Vec::new(),
12160×
        last: Instant::now(),
12170×
        gone: false,
12180×
        leaving: &LEAVING,
12190×
        started: Instant::now(),
12200×
        expected: claim.expected_ms.map(Duration::from_millis),
12210×
    };
12220×
    let note =
12230×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
12240×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
12250×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1226
    // Preparing a workspace: fetches into a cached repository, and exports
1227
    // from it, are one job at a time per repository (`repo_lock`); taking
1228
    // cache disks and imaging the workspace are one job at a time on the
1229
    // runner (`PREPARE`); a first clone, whose token goes through the process
1230
    // environment, one at a time (`CLONE`).
12310×
    let main_lock = repo_lock(&claim.repo);
12320×
    let asked = Instant::now();
12330×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
12340×
    if asked.elapsed().as_secs() >= 2 {
12350×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
12360×
    }
12370×
    let fetching = Instant::now();
12380×
    let repo = cached_repo(home, cfg, claim)?;
12390×
    let fetched = fetching.elapsed();
12400×
    let mut preparing = None;
12410×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
12420×
    let _ = std::fs::remove_dir_all(&scratch);
12430×
    std::fs::create_dir_all(scratch.join("tree"))?;
12440×
    let result = (|| -> Result<Finish> {
12450×
        let exporting = Instant::now();
12460×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
12470×
        main_guard.take();
12480×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1249
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1250
        // workspace and of the scope hash.
12510×
        for sub in &claim.subrepos {
12520×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
12530×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
12540×
            }
12550×
            note(
12560×
                &mut sink,
12570×
                format!(
1258
                    "fetching subrepo {} at {} for {}",
1259
                    sub.repo,
12600×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1261
                    sub.path
1262
                ),
1263
            );
12640×
            let sub_lock = repo_lock(&sub.repo);
12650×
            let asked = Instant::now();
12660×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
12670×
            if asked.elapsed().as_secs() >= 2 {
12680×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
12690×
            }
12700×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
12710×
            let sub_heads: Vec<ChangeHash> =
12720×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
12730×
            let dir = scratch.join("tree").join(&sub.path);
12740×
            std::fs::create_dir_all(&dir)?;
12750×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
12760×
            drop(sub_guard);
12770×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1278
        }
12790×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1280
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1281
        // against the blob its receipt names, then put at its path. Not part
1282
        // of the scope: they are the run's, not the repository's.
12830×
        let mut input_blobs = Vec::new();
12840×
        for (index, i) in claim.inputs.iter().enumerate() {
12850×
            let what = format!("input {} from {}", i.artifact, i.from);
12860×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
12870×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
12880×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
12890×
            input_blobs.push(blob);
1290
        }
1291
        // The syscall tier runs on the tree itself; a microVM gets an image.
12920×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
12930×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1294
        // The syscall and WASM tiers see the job's files as a directory;
1295
        // the MicroVM tier as an ext4 image.
12960×
        let dir_tier = syscall_tier || wasm_tier;
12970×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1298
        // Disk mounts that name a cache start from a kept disk (#28): a
1299
        // microVM takes an image already in place as it is, the syscall tier
1300
        // a directory (#70). Taken before the workspace is imaged: the
1301
        // sources the disk was built from give unchanged files their old
1302
        // times back (#52).
13030×
        let asked = Instant::now();
13040×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
13050×
        if asked.elapsed().as_secs() >= 2 {
13060×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
13070×
        }
13080×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
13090×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
13100×
        let cache_ctx =
13110×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
13120×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
13130×
        let mut built_from: Option<crate::cache::Sources> = None;
13140×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
13150×
            let Some(name) = &m.cache else { continue };
13160×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
13170×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
13180×
                Some(t) => {
13190×
                    if built_from.is_none() {
13200×
                        built_from = t.sources;
13210×
                    }
13220×
                    t.how
1323
                }
13240×
                None => format!("cache {name}: none kept yet, an empty disk"),
1325
            };
13260×
            note(&mut sink, format!("{} ({})", how, m.target));
1327
            // What the job reads is seen when the disk is pruned (#72).
13280×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
13290×
                note(&mut sink, format!("cache {name}: {e:#}"));
13300×
            }
13310×
            cached.push((i, key, how));
1332
        }
1333
        // What the job reads or writes on its cache from now on is what it
1334
        // used; the rest may be pruned before the cache is kept (#72).
13350×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
13360×
        let sources = if cached.is_empty() {
13370×
            crate::cache::Sources::new()
1338
        } else {
13390×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
13400×
            if built_from.is_some() {
13410×
                note(
13420×
                    &mut sink,
13430×
                    format!(
13440×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
13450×
                        sources.len()
13460×
                    ),
13470×
                );
13480×
            }
13490×
            sources
1350
        };
1351
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1352
        // over the cache, before the same exec runs again; the receipt
1353
        // lists it among the job's inputs.
13540×
        if let Some(blob) = &claim.checkpoint {
13550×
            if dir_tier {
13560×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
13570×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
13580×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
13590×
                }
13600×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
13610×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
13620×
                note(
13630×
                    &mut sink,
13640×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
13650×
                );
13660×
                input_blobs.push(Repo::blob_ref(&bytes).0);
13670×
            } else {
13680×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
13690×
            }
13700×
        }
13710×
        if !dir_tier {
13720×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
13730×
            std::fs::remove_dir_all(scratch.join("tree"))?;
13740×
        }
13750×
        preparing.take();
1376
        // Cancelled while it was being prepared: no sandbox.
13770×
        if microvm::Sink::cancelled(&mut sink) {
13780×
            return Ok(cancelled());
13790×
        }
13800×
        if wasm_tier {
13810×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
13820×
        } else {
13830×
            note(
13840×
                &mut sink,
13850×
                format!(
1386
                    "{}: {} {}, {} MiB, rootfs {}",
13870×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1388
                    claim.sandbox.cpus,
13890×
                    if syscall_tier { "CPU" } else { "vCPU" },
1390
                    claim.sandbox.memory_mib,
13910×
                    &claim.sandbox.rootfs[..12]
1392
                ),
1393
            );
1394
        }
13950×
        let timeout = Duration::from_secs(claim.timeout_s);
13960×
        let mut outcome = if wasm_tier {
13970×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
13980×
        } else if syscall_tier {
13990×
            let group = format!("job-{}", claim.job_id);
14000×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1401
        } else {
14020×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1403
        };
14040×
        if outcome.cancelled {
1405
            // Handed back as the runner leaves: its checkpoints first, for
1406
            // the next attempt (oxygenflow#77).
14070×
            if leaving().is_some() && !job.checkpoints.is_empty() {
14080×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
14090×
            }
14100×
            return Ok(cancelled());
14110×
        }
1412
        // The receipt says what a cached disk started from.
14130×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
14140×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
14150×
        for (i, key, how) in &cached {
14160×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
14170×
        }
1418
        // A passing job's artifacts, read from its disks and uploaded; a
1419
        // declared artifact that cannot be kept fails the job. A failing
1420
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1421
        // its receipt, and one it cannot keep is only noted.
14220×
        let mut outputs = vec![];
14230×
        let mut output_error = None;
14240×
        let passed = outcome.exit_code == Some(0);
14250×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
14260×
        for o in wanted {
14270×
            if o.kind == flow_core::OutputKind::Report {
14280×
                let read = if dir_tier {
14290×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14300×
                    crate::outputs::read_report_dir(&dir, &inner)
1431
                } else {
14320×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14330×
                    crate::outputs::read_report(&image, &inner, &scratch)
1434
                };
14350×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
14360×
                match kept {
14370×
                    Ok((blob, files, bytes)) => {
14380×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
14390×
                        let hex = blob.to_hex();
14400×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
14410×
                        if passed {
14420×
                            outputs.push(blob.0);
14430×
                        }
1444
                    }
14450×
                    Err(e) if passed => {
14460×
                        output_error = Some(format!("report {}: {e:#}", o.name));
14470×
                        break;
1448
                    }
14490×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1450
                }
14510×
                continue;
14520×
            }
14530×
            let read = if dir_tier {
14540×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14550×
                crate::outputs::read_dir_file(&dir, &inner)
1456
            } else {
14570×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14580×
                crate::outputs::read(&image, &inner, &scratch)
1459
            };
14600×
            let kept = read.and_then(|bytes| {
14610×
                let blob = Repo::blob_ref(&bytes);
14620×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
14630×
                if named != blob.to_hex() {
14640×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
14650×
                }
14660×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
14670×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
14680×
                Ok(blob.0)
14690×
            });
14700×
            match kept {
14710×
                Ok(b) if passed => outputs.push(b),
14720×
                Ok(_) => {}
14730×
                Err(e) if passed => {
14740×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
14750×
                    break;
1476
                }
14770×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1478
            }
1479
        }
14800×
        if let Some(e) = &output_error {
14810×
            note(&mut sink, e.clone());
14820×
        }
14830×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
14840×
            job_name: claim.job.name.clone(),
14850×
            pipeline_hash: hex32(&claim.pipeline_hash),
14860×
            scope_tree_hash: scope_hash,
14870×
            inputs: input_blobs.clone(),
14880×
            environment: outcome.environment.hash(),
14890×
            outputs,
14900×
            exit_code: code as u32,
14910×
            duration_ms: outcome.duration_ms,
14920×
        });
14930×
        let signed_receipt = match &receipt {
14940×
            Some(r) => {
14950×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
14960×
                if cfg.keyless {
14970×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
14980×
                        Ok(k) => signed = k,
14990×
                        Err(e) => {
15000×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1501
                        }
1502
                    }
15030×
                }
15040×
                Some(hex::encode(signed.encode()))
1505
            }
15060×
            None => None,
1507
        };
1508
        // Measured before a cached disk leaves the scratch directory.
15090×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1510
        // A passing job's cached disks are pruned and kept (#72); a
1511
        // failing job's are thrown away, so nothing it wrote reaches a
1512
        // later job.
15130×
        let kept = passed && output_error.is_none();
15140×
        for (i, key, _) in &cached {
15150×
            let disk = crate::cache::disk_path(form, &scratch, *i);
15160×
            let m = disk_mounts[*i];
15170×
            let prune = crate::cache::Prune {
15180×
                started: cache_started,
15190×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
15200×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1521
            };
15220×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
15230×
                Ok(Some(line)) => note(&mut sink, line),
15240×
                Ok(None) => {}
15250×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1526
            }
1527
        }
1528
        Ok(Finish {
15290×
            exit_code: outcome.exit_code,
15300×
            duration_ms: started.elapsed().as_millis() as u64,
15310×
            receipt,
15320×
            signed_receipt,
15330×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1534
            // What the job took (oxygenflow#41): its disks are sparse files
1535
            // in the scratch directory, so their blocks now are their peak.
15360×
            peak_disk_mib,
15370×
            peak_memory_mib: outcome.peak_memory_mib,
1538
        })
1539
    })();
15400×
    let _ = workspace::remove_tree(&scratch);
15410×
    sink.flush();
15420×
    result
15430×
}
1544
1545
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1546
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1547
/// the claim, so the runner vouches only for what it fetched.
1548
/// Upload a report's files, then its manifest under the report's name, and
1549
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1550
/// the manifest's blob, the file count and their total size.
15510×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
15520×
    let mut listed = Vec::with_capacity(files.len());
15530×
    let mut total = 0u64;
15540×
    for (path, bytes) in files {
15550×
        let blob = Repo::blob_ref(bytes).to_hex();
15560×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
15570×
        if named != blob {
15580×
            bail!("the hub kept {path} as {named}, not {blob}");
15590×
        }
15600×
        total += bytes.len() as u64;
15610×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1562
    }
15630×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
15640×
    let blob = Repo::blob_ref(&manifest);
15650×
    let named = hub.artifact(job, name, &manifest)?;
15660×
    if named != blob.to_hex() {
15670×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
15680×
    }
15690×
    Ok((blob, files.len(), total))
15700×
}
1571
15720×
fn sign_receipt(
15730×
    repo: &Repo,
15740×
    heads: &[ChangeHash],
15750×
    cfg: &RunnerConfig,
15760×
    key: &RunnerKey,
15770×
    claim: &Claim,
15780×
    receipt: &Receipt,
15790×
) -> Result<oxy_core::receipt::SignedReceipt> {
15800×
    let state = state_of(heads);
15810×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
15820×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
15830×
}
1584
1585
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1586
/// just before signing, so the certificate covers the moment the hub
1587
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1588
/// receipt signed: nothing long-lived signs.
15890×
fn sign_keyless(
15900×
    repo: &Repo,
15910×
    heads: &[ChangeHash],
15920×
    cfg: &RunnerConfig,
15930×
    hub: &Hub,
15940×
    claim: &Claim,
15950×
    receipt: &Receipt,
15960×
) -> Result<oxy_core::receipt::SignedReceipt> {
15970×
    let sk = oxy_core::identity::SecretKey::generate();
15980×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
15990×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
16000×
    let id = sk.identity(&name, "", now);
16010×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
16020×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
16030×
    let state = state_of(heads);
16040×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16050×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
16060×
}
1607
1608
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
16090×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1610
    use oxy_core::hash::{hash_object, ObjectType};
16110×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
16120×
}
1613
16140×
fn hex32(s: &str) -> [u8; 32] {
16150×
    let mut out = [0; 32];
16160×
    if let Ok(v) = hex::decode(s) {
16170×
        if v.len() == 32 {
16180×
            out.copy_from_slice(&v);
16190×
        }
16200×
    }
16210×
    out
16220×
}
1623
1624
/// Whether a network error is worth another try: DNS, a refused or reset
1625
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1626
/// hub restarts (oxygenhub#111).
16278×
fn transient(msg: &str) -> bool {
16288×
    let m = msg.to_lowercase();
16298×
    [
16308×
        "dns failed",
16318×
        "name resolution",
16328×
        "connection refused",
16338×
        "connection reset",
16348×
        "timed out",
16358×
        "timeout",
16368×
        "http 502",
16378×
        "http 503",
16388×
        "http 504",
16398×
        "broken pipe",
16408×
        "unexpected eof",
16418×
    ]
16428×
    .iter()
164347×
    .any(|k| m.contains(k))
16448×
}
1645
1646
/// Run `f` again after a transient network error, waiting `waits` between
1647
/// tries (about a minute in all), and give up on any other error at once.
16483×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
16493×
    let mut tries = waits.iter();
1650
    loop {
16517×
        match f() {
16521×
            Ok(v) => return Ok(v),
16536×
            Err(e) => match tries.next() {
16545×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
16552×
                _ => return Err(e),
1656
            },
1657
        }
1658
    }
16593×
}
1660
1661
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1662
const FETCH_WAITS: [Duration; 5] =
1663
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1664
1665
/// The runner's copy of a repository, fetched up to date with the job's token.
16660×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
16670×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
16680×
}
1669
1670
/// The runner's copy of `repo`, cloned or fetched with `token`.
16710×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
16720×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
16730×
    let set_remote = |repo: &mut Repo| -> Result<()> {
16740×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
16750×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
16760×
        if let Some(ca) = &cfg.ca {
16770×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
16780×
        }
16790×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
16800×
    };
16810×
    if dir.join(".oxy").is_dir() {
16820×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
16830×
        set_remote(&mut repo)?;
16840×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
16850×
        return Ok(repo);
16860×
    }
1687
    // First job for this repository: clone with the job's token, which goes
1688
    // through the process environment, so one clone at a time.
16890×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
16900×
    std::env::set_var("OXY_TOKEN", token);
16910×
    if let Some(ca) = &cfg.ca {
16920×
        std::env::set_var("OXY_CA", ca);
16930×
    }
16940×
    let cloned = with_retries(&FETCH_WAITS, || {
16950×
        let _ = std::fs::remove_dir_all(&dir);
16960×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
16970×
    });
16980×
    std::env::remove_var("OXY_TOKEN");
16990×
    std::env::remove_var("OXY_CA");
17000×
    let mut repo = cloned.map_err(|e| {
17010×
        let _ = std::fs::remove_dir_all(&dir);
17020×
        anyhow::anyhow!("clone {}: {e}", clone_url)
17030×
    })?;
17040×
    set_remote(&mut repo)?;
17050×
    Ok(repo)
17060×
}
1707
1708
#[cfg(test)]
1709
mod tests {
1710
1711
    #[test]
17121×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
17131×
        let dir = tempfile::tempdir().unwrap();
17141×
        let bytes = b"the reviewed plan";
17151×
        let blob = Repo::blob_ref(bytes).to_hex();
17161×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
17176×
            artifact: "tfplan".into(),
17186×
            from: "plan".into(),
17196×
            path: path.into(),
17206×
            blob: blob.into(),
17216×
        };
17221×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
17231×
        assert_eq!(hex::encode(got), blob);
17241×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
17251×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
17261×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
17271×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
17284×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
17294×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1730
        }
17311×
    }
1732
1733
    use super::*;
1734
1735
    #[test]
17361×
    fn a_runner_names_what_stops_a_sandbox() {
17371×
        let dir = tempfile::tempdir().unwrap();
17381×
        let home = Home::locate(Some(dir.path())).unwrap();
17391×
        let bytes = b"not really ext4";
17401×
        let hash = blake3::hash(bytes).to_hex().to_string();
17411×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
17421×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1743
        }))
17441×
        .unwrap();
17456×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
17461×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
17471×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
17481×
        sb.rootfs = hash.clone();
17491×
        assert_eq!(problem(&sb, Some(4096)), None);
17501×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
17511×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
17521×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
17531×
        sb.arch = Some("aarch64".into());
17541×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
17551×
        sb.arch = None;
17561×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
17571×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
17581×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
17591×
    }
1760
1761
    #[test]
17621×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1763
        // An image fetched or imported with no recorded architecture, built
1764
        // for riscv64: the runner reads its shell, records it, and declines
1765
        // instead of running it and failing (spec §11.2, §11.5).
17661×
        let dir = tempfile::tempdir().unwrap();
17671×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
17681×
        let tree = dir.path().join("tree");
17691×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
17701×
        let mut elf = vec![0u8; 64];
17711×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
17721×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
17731×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
17741×
        let img = dir.path().join("rootfs.ext4");
17751×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
17761×
        if !made.is_ok_and(|s| s.success()) {
17770×
            eprintln!("mkfs.ext4 not found: skipped");
17780×
            return;
17791×
        }
17801×
        let hash = crate::home::hash_file(&img).unwrap();
17811×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
17821×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
17831×
        assert!(!home.image_manifest(&hash).exists());
17841×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
17851×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1786
        }))
17871×
        .unwrap();
17881×
        assert_eq!(
17891×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
17901×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1791
        );
17921×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1793
        // Learned: recorded once, and reported with the runner's claims.
17941×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
17951×
        assert_eq!(manifest["arch"], "riscv64");
17961×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
17971×
    }
1798
1799
    #[test]
18001×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
18011×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
18021×
        assert!(transient("HTTP 503: the hub is restarting"));
18031×
        assert!(!transient("HTTP 404: no such repository"));
18041×
        let mut n = 0;
18053×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
18063×
            n += 1;
18073×
            if n < 3 {
18082×
                Err(anyhow::anyhow!("connection refused"))
1809
            } else {
18101×
                Ok(7)
1811
            }
18123×
        });
18131×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
18141×
        let mut m = 0;
18151×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
18161×
            m += 1;
18171×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
18181×
        });
18191×
        assert!(got.is_err());
18201×
        assert_eq!(m, 1, "a refusal is not tried again");
18211×
        let mut k = 0;
18223×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
18233×
            k += 1;
18243×
            Err(anyhow::anyhow!("timed out"))
18253×
        });
18261×
        assert!(got.is_err());
18271×
        assert_eq!(k, 3, "gives up after the last wait");
18281×
    }
1829
1830
    /// A hub that answers each request with the next of `codes`, counting them.
18319×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
18329×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
18339×
    }
1834
1835
    /// A hub at `listener` answering each request with the next of `codes`.
183611×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1837
        use std::io::{Read, Write};
183811×
        let addr = listener.local_addr().unwrap();
183911×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
184011×
        let count = seen.clone();
184111×
        std::thread::spawn(move || {
184221×
            for code in codes {
184321×
                let (mut s, _) = listener.accept().unwrap();
1844
                // Read the whole request (headers, then Content-Length bytes
1845
                // of body) before answering: closing early would reset the
1846
                // connection while the client is still sending.
184721×
                let mut req = Vec::new();
184821×
                let mut buf = [0u8; 8192];
1849
                loop {
185027×
                    let n = s.read(&mut buf).unwrap_or(0);
185127×
                    if n == 0 {
18520×
                        break;
185327×
                    }
185427×
                    req.extend_from_slice(&buf[..n]);
185527×
                    let text = String::from_utf8_lossy(&req);
185627×
                    if let Some(end) = text.find("\r\n\r\n") {
185727×
                        let len = text[..end]
185827×
                            .lines()
1859210×
                            .find_map(|l| {
1860210×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1861210×
                            })
186227×
                            .unwrap_or(0);
186327×
                        if req.len() >= end + 4 + len {
186421×
                            break;
18656×
                        }
18660×
                    }
1867
                }
186821×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
186921×
                let reason = if code == 204 { "No Content" } else { "Error" };
187021×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1871
            }
187211×
        });
187311×
        (format!("http://{addr}"), seen)
187411×
    }
1875
1876
    /// A hub that answers one request with `body` (status 200) and hands
1877
    /// back what it was sent.
18781×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1879
        use std::io::{Read, Write};
18801×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
18811×
        let addr = listener.local_addr().unwrap();
18821×
        let (tx, rx) = std::sync::mpsc::channel();
18831×
        std::thread::spawn(move || {
18841×
            let (mut s, _) = listener.accept().unwrap();
18851×
            let mut req = Vec::new();
18861×
            let mut buf = [0u8; 65536];
1887
            loop {
18882×
                let n = s.read(&mut buf).unwrap_or(0);
18892×
                if n == 0 {
18900×
                    break;
18912×
                }
18922×
                req.extend_from_slice(&buf[..n]);
18932×
                let text = String::from_utf8_lossy(&req);
18942×
                if let Some(end) = text.find("\r\n\r\n") {
18952×
                    let len = text[..end]
18962×
                        .lines()
189714×
                        .find_map(|l| {
189814×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
189914×
                        })
19002×
                        .unwrap_or(0);
19012×
                    if req.len() >= end + 4 + len {
19021×
                        break;
19031×
                    }
19040×
                }
1905
            }
19061×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
19071×
            let _ = write!(
19081×
                s,
1909
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
19101×
                body.len()
1911
            );
19121×
        });
19131×
        (format!("http://{addr}"), rx)
19141×
    }
1915
1916
    #[test]
19171×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1918
        use std::os::unix::fs::PermissionsExt;
19191×
        let dir = tempfile::tempdir().unwrap();
19201×
        let home = Home::locate(Some(dir.path())).unwrap();
19211×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
19221×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
19231×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
19241×
        let req = sent.recv().unwrap();
19251×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
19261×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
19271×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
19281×
        let key = home.runner_key("plex").unwrap();
19291×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
19301×
        let path = dir.path().join(crate::home::RUNNER_TOML);
19311×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1932
        // The runner then starts from runner.toml.
19331×
        let again = Home::locate(Some(dir.path())).unwrap();
19341×
        let cfg = again.config.runner.unwrap();
19351×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
19361×
        assert_eq!(cfg.labels, ["gpu"]);
19371×
    }
1938
1939
    /// A hub that answers certify with a certificate `sign_as` signs for
1940
    /// `cert_key`, and publishes `published` as its key: two requests.
19413×
    fn fake_certify_hub(
19423×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
19433×
        cert_key: oxy_core::identity::Identity,
19443×
        published: oxy_core::identity::Identity,
19453×
    ) -> String {
1946
        use std::io::{Read, Write};
19473×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19483×
        let addr = listener.local_addr().unwrap();
19493×
        std::thread::spawn(move || {
19503×
            for _ in 0..2 {
19516×
                let Ok((mut s, _)) = listener.accept() else { return };
19526×
                let mut req = Vec::new();
19536×
                let mut buf = [0u8; 65536];
1954
                loop {
19556×
                    let n = s.read(&mut buf).unwrap_or(0);
19566×
                    if n == 0 {
19570×
                        break;
19586×
                    }
19596×
                    req.extend_from_slice(&buf[..n]);
19606×
                    let text = String::from_utf8_lossy(&req);
19616×
                    if let Some(end) = text.find("\r\n\r\n") {
19626×
                        let len = text[..end]
19636×
                            .lines()
196439×
                            .find_map(|l| {
196539×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
196639×
                            })
19676×
                            .unwrap_or(0);
19686×
                        if req.len() >= end + 4 + len {
19696×
                            break;
19700×
                        }
19710×
                    }
1972
                }
19736×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
19746×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
19753×
                    let cert = oxy_core::cert::SignedCertificate::sign(
19763×
                        oxy_core::cert::Certificate {
19773×
                            key: cert_key.clone(),
19783×
                            issuer: sign_as.0.hash(),
19793×
                            subject: "repo:andy/demo:bookmark:main".into(),
19803×
                            claims: vec![],
19813×
                            scope: oxy_core::identity::Scope::SEAL,
19823×
                            not_before: 1,
19833×
                            expires: 600_001,
19843×
                            grant: None,
19853×
                        },
19863×
                        &sign_as.0,
19873×
                        &sign_as.1,
1988
                    );
19893×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
1990
                } else {
19913×
                    published.encode()
1992
                };
19936×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
19946×
                let _ = s.write_all(&body);
1995
            }
19963×
        });
19973×
        format!("http://{addr}")
19983×
    }
1999
2000
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2001
    /// is for its fresh key and signed by the key the hub publishes.
2002
    #[test]
20031×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2004
        use oxy_core::identity::SecretKey;
20051×
        let hub_sk = SecretKey::generate();
20061×
        let hub_id = hub_sk.identity("hub", "", 1);
20071×
        let sk = SecretKey::generate();
20081×
        let id = sk.identity("earth-1 job 7", "", 1);
20091×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2010
20111×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
20121×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
20131×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2014
20151×
        let mallory_sk = SecretKey::generate();
20161×
        let mallory = mallory_sk.identity("mallory", "", 1);
20171×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
20181×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20191×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2020
20211×
        let other = SecretKey::generate().identity("other", "", 1);
20221×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
20231×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20241×
        assert!(e.contains("another key"), "{e}");
20251×
    }
2026
202716×
    fn hub_at(base: String) -> Hub {
202816×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
202916×
    }
2030
2031
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2032
    /// hub attests; a peer or a proxy cannot change what is installed.
2033
    #[test]
20341×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
20351×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
20362×
        let serve = |bytes: Vec<u8>| {
20372×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20382×
            let addr = listener.local_addr().unwrap();
20392×
            std::thread::spawn(move || {
2040
                use std::io::{Read, Write};
20412×
                let (mut s, _) = listener.accept().unwrap();
20422×
                let mut buf = [0u8; 4096];
20432×
                let _ = s.read(&mut buf);
20442×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
20452×
                let _ = s.write_all(&bytes);
20462×
            });
20472×
            format!("http://{addr}")
20482×
        };
20491×
        let offer = flow_core::api::UpdateOffer {
20501×
            version: "0.3.2".into(),
20511×
            asset: "flow-linux-x86_64".into(),
20521×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
20531×
            blake3: blake3::hash(&body).to_hex().to_string(),
20541×
            size: body.len() as u64,
20551×
            ..Default::default()
20561×
        };
20571×
        let dir = tempfile::tempdir().unwrap();
20581×
        let to = dir.path().join("flow-0.3.2");
20591×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
20601×
        assert_eq!(std::fs::read(&to).unwrap(), body);
20611×
        std::fs::remove_file(&to).unwrap();
20621×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
20631×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
20641×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
20651×
    }
2066
2067
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2068
    /// through server errors, and a refusal ends the trying at once.
2069
    #[test]
20701×
    fn a_result_is_reported_until_the_hub_takes_it() {
20711×
        let f = Finish {
20721×
            exit_code: Some(0),
20731×
            duration_ms: 1,
20741×
            receipt: None,
20751×
            signed_receipt: None,
20761×
            error: None,
20771×
            peak_disk_mib: None,
20781×
            peak_memory_mib: None,
20791×
        };
20801×
        let quick = Duration::from_millis(10);
20811×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
20821×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
20831×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
20841×
        let (base, seen) = fake_hub(vec![409]);
20851×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
20861×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
20871×
    }
2088
2089
    #[test]
20901×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
20911×
        let quick = [Duration::from_millis(10); 3];
20921×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
20931×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
20941×
        assert!(r.is_none());
20951×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2096
20971×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
20981×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
20991×
        assert!(e.contains("HTTP 500"), "{e}");
21001×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2101
21021×
        let (base, seen) = fake_hub(vec![401]);
21031×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
21041×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21051×
    }
2106
2107
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2108
2109
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2110
    /// cancelled, having sent what the job said so far, and the job is
2111
    /// handed back to the hub.
2112
    #[test]
21131×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2114
        use microvm::Sink;
21151×
        let leaving = std::sync::Mutex::new(None);
21161×
        let (base, seen) = fake_hub(vec![204, 204]);
21171×
        let hub = hub_at(base);
21181×
        let mut sink = LogSink {
21191×
            hub: &hub,
21201×
            job: 7,
21211×
            buf: Vec::new(),
21221×
            last: Instant::now(),
21231×
            gone: false,
21241×
            leaving: &leaving,
21251×
            started: Instant::now(),
21261×
            expected: None,
21271×
        };
21281×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
21291×
        assert!(!sink.cancelled());
21301×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
21311×
        assert!(sink.cancelled());
21321×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
21331×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
21341×
        hub.release(7, "off Wi-Fi").unwrap();
21351×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
21361×
    }
2137
2138
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2139
    /// it runs on; one that will not, or whose time is unknown, is handed
2140
    /// back at once, and any job still running when the notice is up.
2141
    #[test]
21421×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2143
        use microvm::Sink;
21441×
        let (base, _) = fake_hub(vec![204; 8]);
21451×
        let hub = hub_at(base);
21461×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
21471×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
21484×
            hub: &hub,
2149
            job: 1,
21504×
            buf: Vec::new(),
21514×
            last: Instant::now(),
2152
            gone: false,
21534×
            leaving: &leaving,
21544×
            started: Instant::now() - Duration::from_secs(ran),
21554×
            expected: expected.map(Duration::from_secs),
21564×
        };
21571×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
21581×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
21591×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
21601×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
21611×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
21621×
    }
2163
2164
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2165
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2166
    #[test]
21671×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2168
        use microvm::Sink;
21692×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
21701×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
21711×
        let (base, seen) = fake_hub(vec![204]);
21721×
        let hub = hub_at(base);
21731×
        let mut sink = LogSink {
21741×
            hub: &hub,
21751×
            job: 1,
21761×
            buf: Vec::new(),
21771×
            last: quiet,
21781×
            gone: false,
21791×
            leaving: &NOT_LEAVING,
21801×
            started: Instant::now(),
21811×
            expected: None,
21821×
        };
21831×
        assert!(!sink.cancelled());
21841×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
21851×
        assert_eq!(n(&seen), 1);
2186
21871×
        let (base, seen) = fake_hub(vec![409]);
21881×
        let hub = hub_at(base);
21891×
        let mut sink = LogSink {
21901×
            hub: &hub,
21911×
            job: 1,
21921×
            buf: Vec::new(),
21931×
            last: quiet,
21941×
            gone: false,
21951×
            leaving: &NOT_LEAVING,
21961×
            started: Instant::now(),
21971×
            expected: None,
21981×
        };
21991×
        assert!(sink.cancelled());
22001×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
22011×
        sink.flush();
22021×
        assert!(sink.cancelled());
22031×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
22041×
    }
2205
2206
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2207
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2208
    /// no lines.
2209
    #[test]
22101×
    fn a_job_outlasts_a_hub_restart() {
22112×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2212
        // A port nobody listens on yet: the hub is restarting.
22131×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22141×
        let base = format!("http://127.0.0.1:{port}");
22151×
        let hub = hub_at(base.clone());
2216
2217
        // Log lines sent while it is away are kept, and go when it is back.
22181×
        let mut sink = LogSink {
22191×
            hub: &hub,
22201×
            job: 1,
22211×
            buf: Vec::new(),
22221×
            last: Instant::now(),
22231×
            gone: false,
22241×
            leaving: &NOT_LEAVING,
22251×
            started: Instant::now(),
22261×
            expected: None,
22271×
        };
2228450×
        for i in 0..450 {
2229450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2230450×
        }
22311×
        sink.send();
22321×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
22331×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
22341×
        sink.send();
22351×
        assert!(sink.buf.is_empty() && !sink.gone);
22361×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2237
2238
        // An upload waits for the hub to come back, through refused
2239
        // connections and server errors alike.
22401×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22411×
        let url = format!("http://127.0.0.1:{port}/x");
22421×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
22431×
        let later = std::thread::spawn(move || {
22441×
            std::thread::sleep(Duration::from_millis(150));
22451×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
22461×
        });
22471×
        let quick = [Duration::from_millis(50); 20];
22485×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
22491×
        assert_eq!(r.status(), 204);
22501×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2251
        // Without `connection`, a hub that cannot be reached ends it at once.
22521×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22531×
        let url = format!("http://127.0.0.1:{port}/x");
22541×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
22551×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
22561×
    }
2257
2258
    /// oxygenflow#50: the first stop drains (the second, not called here,
2259
    /// exits at once).
2260
    #[test]
22611×
    fn a_stop_drains_the_runner() {
22621×
        assert!(!stopping());
22631×
        on_stop(libc::SIGTERM);
22641×
        assert!(stopping(), "told to stop, it claims nothing more");
2265
        // An embedded runner starts afresh, and stop() drains it the same way.
22661×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
22671×
        stop();
22681×
        assert!(stopping());
22691×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
22701×
    }
2271
2272
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2273
    #[test]
22741×
    fn unsent_log_lines_are_bounded() {
22751×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22761×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
22771×
        let mut sink = LogSink {
22781×
            hub: &hub,
22791×
            job: 1,
22801×
            buf: Vec::new(),
22811×
            last: Instant::now(),
22821×
            gone: false,
22831×
            leaving: &NOT_LEAVING,
22841×
            started: Instant::now(),
22851×
            expected: None,
22861×
        };
228750010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
22881×
        sink.send();
22891×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
22901×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
22911×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
22921×
    }
2293
2294
    #[test]
22951×
    fn the_budget_admits_jobs_that_fit() {
22961×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
22977×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
22981×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
22991×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
23001×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
23011×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
23021×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
23031×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
23041×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
23051×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
23061×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
23071×
    }
2308
}