OXYGENHUB

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

808 of 1788 lines run, 92 of 413 functions · run #186 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;
4101×
        let tmp = path.with_extension("toml.tmp");
4111×
        let mut f = crate::portable::private(std::fs::OpenOptions::new().write(true).create(true).truncate(true)).open(&tmp)?;
4121×
        f.write_all(text.as_bytes())?;
4131×
        f.sync_all()?;
4141×
        std::fs::rename(&tmp, &path)?;
415
    }
4161×
    Ok(got)
4171×
}
418
419
/// Waits before trying a hub request again after a server error.
420
const RETRY_DELAYS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(4)];
421
422
/// Waits for what a job leaves behind (oxygenflow#49): three minutes in
423
/// all, longer than a hub takes to restart.
424
/// Check an input's bytes against the blob the producing job's receipt
425
/// names, then write them at its path under `tree` (the workspace's `/src`).
4266×
fn place_input(tree: &Path, i: &flow_core::api::ArtifactInput, bytes: &[u8]) -> Result<[u8; 32]> {
4276×
    let Some(rel) = i.path.strip_prefix("/src/").filter(|r| r.split('/').all(|p| !p.is_empty() && p != "." && p != ".." && p != ".oxy"))
428
    else {
4294×
        bail!("path {:?} is not a clean path under /src", i.path);
430
    };
4312×
    let blob = Repo::blob_ref(bytes);
4322×
    if blob.to_hex() != i.blob {
4331×
        bail!("it is not what {}'s receipt names (blob {}, not {})", i.from, &blob.to_hex()[..12], &i.blob[..i.blob.len().min(12)]);
4341×
    }
4351×
    let dest = tree.join(rel);
4361×
    if let Some(dir) = dest.parent() {
4371×
        std::fs::create_dir_all(dir)?;
4380×
    }
4391×
    std::fs::write(&dest, bytes)?;
4401×
    Ok(blob.0)
4416×
}
442
443
/// The largest input a job takes: the hub's artifact limit.
444
pub const MAX_INPUT_BYTES: usize = 512 << 20;
445
446
const PATIENT_DELAYS: [Duration; 15] = {
447
    let mut d = [Duration::from_secs(15); 15];
448
    d[0] = Duration::from_secs(1);
449
    d[1] = Duration::from_secs(2);
450
    d[2] = Duration::from_secs(4);
451
    d[3] = Duration::from_secs(8);
452
    d
453
};
454
455
/// Send a request until the hub answers, waiting `delays` in turn after a
456
/// server error (5xx: nothing was committed) and, when `connection`, after
457
/// the hub could not be reached at all. A refusal (4xx) is final, as a
458
/// [`Refused`] the caller can look at.
45914×
fn retrying(
46014×
    url: &str,
46114×
    delays: &[Duration],
46214×
    connection: bool,
46314×
    mut send: impl FnMut() -> Result<ureq::Response, Box<ureq::Error>>,
46414×
) -> Result<ureq::Response> {
46514×
    let mut delays = delays.iter();
466
    loop {
46723×
        let why = match send().map_err(|e| *e) {
4688×
            Ok(r) => return Ok(r),
4699×
            Err(ureq::Error::Status(code, r)) if code < 500 => {
4702×
                let text = r.into_string().unwrap_or_default();
4712×
                return Err(anyhow::Error::new(Refused { code, text }).context(url.to_string()));
472
            }
4737×
            Err(ureq::Error::Status(code, r)) => format!("HTTP {code}: {}", r.into_string().unwrap_or_default()),
4743×
            Err(e) if connection => e.to_string(),
4753×
            Err(e) => bail!("{url}: {e}"),
476
        };
47710×
        match delays.next() {
4789×
            Some(d) => std::thread::sleep(*d),
4791×
            None => bail!("{url}: {why}"),
480
        }
481
    }
48214×
}
483
484
/// What the runner may run at once (flow.toml `[runner]`): at most
485
/// `max_jobs` jobs, whose sandboxes together fit `memory_mib` and `cpus`.
486
#[derive(Debug, Default, PartialEq, Eq)]
487
pub struct Budget {
488
    pub max_jobs: usize,
489
    pub memory_mib: Option<u32>,
490
    pub cpus: Option<u32>,
491
}
492
493
/// What is in use now.
494
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
495
pub struct Used {
496
    pub jobs: usize,
497
    pub memory_mib: u32,
498
    pub cpus: u32,
499
}
500
501
impl Budget {
5020×
    pub fn of(cfg: &RunnerConfig) -> Budget {
5030×
        Budget { max_jobs: cfg.max_jobs.unwrap_or(1).max(1), memory_mib: cfg.memory_mib, cpus: cfg.cpus }
5040×
    }
505
506
    /// The room to ask the hub for, or `None` when no job more can start.
507
    /// A lone job may use the whole budget even if it asks for more, so a
508
    /// large sandbox is never starved.
5097×
    pub fn room(&self, used: Used) -> Option<(Option<u32>, Option<u32>)> {
5107×
        if used.jobs >= self.max_jobs {
5112×
            return None;
5125×
        }
5135×
        if used.jobs == 0 {
5142×
            return Some((None, None));
5153×
        }
5163×
        let mem = self.memory_mib.map(|m| m.saturating_sub(used.memory_mib));
5173×
        let cpus = self.cpus.map(|c| c.saturating_sub(used.cpus));
5183×
        if mem == Some(0) || cpus == Some(0) {
5191×
            return None;
5202×
        }
5212×
        Some((mem, cpus))
5227×
    }
523
}
524
525
/// The isolation tiers this machine can honour now (spec §11.1): the
526
/// MicroVM tier when `/dev/kvm` opens for reading and writing and
527
/// flow.toml pins Firecracker; the syscall tier when this binary may use
528
/// user namespaces, Landlock and seccomp and manage a delegated cgroup.
529
/// `Err` says why there are none; the reasons for missing tiers come back
530
/// with the ones there are.
5313×
pub fn tiers(home: &Home) -> std::result::Result<(Vec<String>, Vec<String>), String> {
5323×
    let mut have = Vec::new();
5333×
    let mut missing = Vec::new();
5343×
    let kvm = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm");
5353×
    match (kvm, home.config.microvm.is_some()) {
5360×
        (Ok(_), true) => have.push("microvm".to_string()),
5370×
        (Ok(_), false) => missing.push("microvm: flow.toml has no [microvm] section".to_string()),
5383×
        (Err(e), _) => missing.push(format!(
539
            "microvm: /dev/kvm cannot be opened ({e}); the tier needs hardware virtualisation and this user in the kvm group"
540
        )),
541
    }
5423×
    match crate::syscall::available() {
5430×
        Ok(()) => have.push("syscall".to_string()),
5443×
        Err(e) => missing.push(format!("syscall: {e}")),
545
    }
546
    // wasmtime runs on every machine this binary does (oxygenflow#75).
5473×
    have.push("wasm".to_string());
5483×
    if have.is_empty() {
5490×
        return Err(format!("no isolation tier can run here: {}", missing.join("; ")));
5503×
    }
5513×
    Ok((have, missing))
5523×
}
553
554
/// Fetch `claim`'s image from the hub when this home lacks it
555
/// (oxygenflow#39), saying so in the job's log. A hub that does not hold it
556
/// leaves it missing, and the preflight declines the job as before.
5570×
fn fetch_image(home: &Home, hub: &Hub, cfg: &RunnerConfig, swarm: Option<&crate::swarm::Swarm>, claim: &Claim) {
5580×
    let hash = &claim.sandbox.rootfs;
5590×
    if hash.is_empty() || home.rootfs(hash).is_file() || !jet::images::is_hash(hash) {
5600×
        return;
5610×
    }
5620×
    let note = |text: String| {
5630×
        eprintln!("job {}: {text}", claim.job_id);
5640×
        hub.log(claim.job_id, vec![Record { t: 0, stream: "flow".into(), text }]).ok();
5650×
    };
566
    // One fetch of an image at a time: two jobs wanting it wait for one.
567
    static FETCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
5680×
    let _one = FETCHING.lock().unwrap_or_else(|p| p.into_inner());
5690×
    if home.rootfs(hash).is_file() {
5700×
        return;
5710×
    }
5720×
    let client = match crate::images::Client::new(&cfg.hub, &cfg.token, cfg.ca.as_deref()) {
5730×
        Ok(c) => c,
5740×
        Err(e) => return note(format!("image {}: cannot reach the hub: {e:#}", &hash[..12])),
575
    };
5760×
    let fetched = match swarm {
5770×
        Some(sw) => {
5780×
            note(format!("image {} is not on this runner: fetching it from its peers and the hub", &hash[..12]));
5790×
            sw.fetch(home, hash)
580
        }
581
        None => {
5820×
            note(format!("image {} is not on this runner: fetching it from the hub", &hash[..12]));
5830×
            client.fetch(home, hash)
584
        }
585
    };
5860×
    match fetched {
5870×
        Ok(Some(m)) => note(format!(
588
            "image {}: fetched {} chunks, {}{} in {:.1} s",
5890×
            &hash[..12],
590
            m.chunks,
5910×
            crate::images::human(m.bytes),
5920×
            if swarm.is_some() { format!(" ({} from peers)", crate::images::human(m.peer_bytes)) } else { String::new() },
5930×
            m.elapsed.as_secs_f64()
594
        )),
5950×
        Ok(None) => note(format!("image {}: the hub does not hold it either", &hash[..12])),
5960×
        Err(e) => note(format!("image {}: fetch failed: {e:#}", &hash[..12])),
597
    }
5980×
}
599
600
/// Why this runner cannot run `claim` now (spec §11.5), checked before
601
/// anything is fetched: the tier, the architecture, the image and the
602
/// memory. The hub chose it from what the runner last said, which may be
603
/// out of date.
6040×
fn preflight(home: &Home, claim: &Claim) -> Option<String> {
6050×
    let sb = &claim.sandbox;
6060×
    match sb.runtime {
607
        flow_core::Runtime::Microvm => {
6080×
            if let Err(e) = std::fs::OpenOptions::new().read(true).write(true).open("/dev/kvm") {
6090×
                return Some(format!("the MicroVM tier needs /dev/kvm, which cannot be opened here ({e})"));
6100×
            }
6110×
            if home.config.microvm.is_none() {
6120×
                return Some("the MicroVM tier is not set up here (flow.toml has no [microvm] section)".into());
6130×
            }
614
        }
615
        flow_core::Runtime::Syscall => {
6160×
            if let Err(e) = crate::syscall::available() {
6170×
                return Some(format!("the syscall tier cannot run here: {e}"));
6180×
            }
619
        }
620
        // No image and no architecture: only the memory matters.
621
        flow_core::Runtime::Wasm => {
6220×
            return available_memory_mib()
6230×
                .filter(|free| *free < u64::from(sb.memory_mib))
6240×
                .map(|free| format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
625
        }
626
    }
6270×
    sandbox_problem(home, sb, std::env::consts::ARCH, available_memory_mib())
6280×
}
629
630
/// What stops `sb` running on this home's images, on a machine of
631
/// architecture `here` with `free_mib` of memory free.
6328×
fn sandbox_problem(home: &Home, sb: &flow_core::Sandbox, here: &str, free_mib: Option<u64>) -> Option<String> {
6338×
    if let Some(want) = sb.arch.as_deref().filter(|a| *a != here) {
6341×
        return Some(format!("the sandbox needs {want}; this runner is {here}"));
6357×
    }
6367×
    let short = &sb.rootfs[..12.min(sb.rootfs.len())];
6377×
    let image = home.rootfs(&sb.rootfs);
6387×
    if !image.is_file() {
6391×
        return Some(format!("rootfs {short} is not on this runner"));
6406×
    }
6416×
    if let Some(arch) = home.image_arch(&sb.rootfs).filter(|a| a != here) {
6422×
        return Some(format!("rootfs {short} is for {arch}; this runner is {here}"));
6434×
    }
6444×
    if let Err(e) = home.verified(&image, &sb.rootfs) {
6451×
        return Some(format!("rootfs {short} does not verify here: {e:#}"));
6463×
    }
6473×
    if let Some(free) = free_mib.filter(|free| *free < u64::from(sb.memory_mib)) {
6481×
        return Some(format!("only {free} MiB of memory is free here; the sandbox needs {} MiB", sb.memory_mib));
6492×
    }
6502×
    None
6518×
}
652
653
/// `MemAvailable` from /proc/meminfo, in MiB.
6540×
fn available_memory_mib() -> Option<u64> {
6550×
    let info = std::fs::read_to_string("/proc/meminfo").ok()?;
6560×
    let kib: u64 = info.lines().find_map(|l| l.strip_prefix("MemAvailable:"))?.trim().trim_end_matches("kB").trim().parse().ok()?;
6570×
    Some(kib / 1024)
6580×
}
659
6600×
pub fn serve(home: &Home) -> Result<()> {
6610×
    drain_on_stop();
6620×
    crate::update::note_runner(&home.root);
663
    // `flow runner update` swapped a new build in and asks this one to
664
    // leave with the notice it gave (#85).
665
    #[cfg(unix)]
6660×
    {
6670×
        let handler = on_update as extern "C" fn(libc::c_int) as libc::sighandler_t;
6680×
        unsafe { libc::signal(libc::SIGUSR1, handler) };
6690×
    }
6700×
    if let Some(p) = crate::update::pending(&home.root) {
671
        // On trial: a build that does not reach the hub in time goes back.
6720×
        let root = home.root.clone();
6730×
        std::thread::spawn(move || {
6740×
            std::thread::sleep(crate::update::PROVE_WITHIN);
6750×
            if crate::update::pending(&root).is_some_and(|now| now.to == p.to && now.at_ms == p.at_ms) {
6760×
                let why = format!("did not reach the hub within {} minutes", crate::update::PROVE_WITHIN.as_secs() / 60);
6770×
                if crate::update::roll_back(&root, &p, &why).is_ok() {
6780×
                    std::process::exit(1);
6790×
                }
6800×
            }
6810×
        });
6820×
    }
6830×
    let served = serve_until_drained(home);
6840×
    crate::update::forget_runner(&home.root);
6850×
    served
6860×
}
687
688
/// Set by SIGUSR1: a new build is in place; leave for it.
689
static UPDATE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
690
691
#[cfg(unix)]
6920×
extern "C" fn on_update(_: libc::c_int) {
6930×
    UPDATE.store(true, std::sync::atomic::Ordering::SeqCst);
6940×
}
695
696
/// The runner as a library, as the Android app runs it (oxygenhub-android#8):
697
/// no signal handlers; [`stop`] drains it, and this returns once the jobs
698
/// it holds are done and reported. It may be started again afterwards.
6990×
pub fn serve_embedded(home: &Home) -> Result<()> {
7000×
    STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
7010×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = None;
7020×
    serve_until_drained(home)
7030×
}
704
705
/// A departure ([`leave_within`]): why, and when the runner must be gone.
706
#[derive(Clone, Debug)]
707
struct Leave {
708
    reason: String,
709
    by: Instant,
710
}
711
712
/// Set once the runner is leaving: a job whose expected rest fits before
713
/// the deadline finishes; the others are stopped and handed back
714
/// (oxygenflow#76).
715
static LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
716
7170×
fn leaving() -> Option<String> {
7180×
    LEAVING.lock().unwrap_or_else(|p| p.into_inner()).as_ref().map(|l| l.reason.clone())
7190×
}
720
721
/// Ask a runner started with [`serve_embedded`] to leave now: claim nothing
722
/// more, stop the jobs it holds and hand them back to the hub, which queues
723
/// them ahead of new work for another runner (oxygenflow#76), then return.
724
/// For a departure with no time to finish: a phone off the allowed network.
7250×
pub fn leave(reason: &str) {
7260×
    leave_within(reason, Duration::ZERO);
7270×
}
728
729
/// [`leave`], with `notice`: a job the hub expects to finish within it
730
/// (the claim's `expected_ms`, less the time it has run) finishes and is
731
/// reported; the others, and any still running when the notice is up, are
732
/// handed back. For a phone taken off charge, a spot reclaim.
7330×
pub fn leave_within(reason: &str, notice: Duration) {
7340×
    *LEAVING.lock().unwrap_or_else(|p| p.into_inner()) = Some(Leave { reason: reason.to_string(), by: Instant::now() + notice });
7350×
    stop();
7360×
}
737
738
/// Ask a runner started with [`serve_embedded`] to drain: claim nothing
739
/// more, finish and report what it holds, then return (oxygenflow#76's
740
/// drain, for a phone taken off charge or off the allowed network).
7411×
pub fn stop() {
7421×
    STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7431×
}
744
7450×
fn serve_until_drained(home: &Home) -> Result<()> {
7460×
    let cfg = home.config.runner.clone().context("flow.toml has no [runner] section")?;
747
    // A runner offers only what it can run: a machine without KVM claims
748
    // nothing rather than taking MicroVM jobs and failing them (#36).
7490×
    let (runtimes, missing) = tiers(home).map_err(|why| anyhow::anyhow!("flow runner: {why}"))?;
7500×
    for why in &missing {
7510×
        eprintln!("flow runner: not offering {why}");
7520×
    }
7530×
    let hub = Hub::new(&cfg)?;
7540×
    let name = cfg.name.clone().unwrap_or_else(|| "flow".into());
7550×
    let budget = Budget::of(&cfg);
7560×
    let key = home.runner_key(&name)?;
757
    // The swarm (docs/jetstream.md §8.1): a runner that cannot serve its
758
    // peers still runs jobs, fetching images from the hub alone.
7590×
    let swarm = crate::swarm::Swarm::start(home, &cfg).unwrap_or_else(|e| {
7600×
        eprintln!("flow runner: not joining the swarm: {e:#}");
7610×
        None
7620×
    });
7630×
    eprintln!(
764
        "flow runner {name}: polling {} (up to {} jobs at once, tiers {}), signing receipts as {}",
765
        cfg.hub,
766
        budget.max_jobs,
7670×
        runtimes.join(", "),
7680×
        key.identity.hash().to_hex()
769
    );
7700×
    if let Some(addr) = &cfg.metrics {
7710×
        crate::metrics::serve(addr, cfg.metrics_token.clone(), name.clone());
7720×
    }
7730×
    let used = std::sync::Mutex::new(Used::default());
7740×
    let mut idle = Duration::from_secs(2);
7750×
    let pending = report_pending(home);
776
    // The jobs held now, told to the hub at each claim so it can end the
777
    // ones this runner lost: a job is held from its claim until its result
778
    // is reported.
7790×
    let held = std::sync::Mutex::new(std::collections::BTreeSet::<i64>::new());
7800×
    held.lock().unwrap().extend(pending.iter().map(|(job, _)| *job));
7810×
    std::thread::scope(|scope| {
7820×
        for (job, f) in pending {
7830×
            let (hub, held) = (&hub, &held);
7840×
            scope.spawn(move || {
7850×
                eprintln!("job {job}: reporting the result kept from before the restart");
7860×
                report_finish(home, hub, job, &f);
7870×
                held.lock().unwrap().remove(&job);
7880×
            });
789
        }
790
        // The speed (spec §11.1): measured now, and again every 15 minutes
791
        // while no job runs, so a job never shares the CPU with it.
7920×
        let measure = || {
7930×
            let (speed, ms) = crate::facts::bench();
7940×
            eprintln!("flow runner {name}: speed {speed} (class {}), benchmark {ms} ms", flow_core::api::Facts::class_of(speed));
7950×
            speed
7960×
        };
7970×
        let mut speed = measure();
7980×
        let mut benched = Instant::now();
7990×
        let mut said_draining = false;
800
        // When the hub last heard from us (oxygenhub#243): a claim, or a
801
        // heartbeat while there is no room to claim.
8020×
        let mut heard = Instant::now();
8030×
        let beat = |heard: &mut Instant| {
8040×
            if heard.elapsed() >= HUB_HEARTBEAT {
8050×
                if let Err(e) = hub.heartbeat() {
8060×
                    eprintln!("flow runner {name}: heartbeat: {e:#}");
8070×
                }
8080×
                *heard = Instant::now();
8090×
            }
8100×
        };
8110×
        let mut on_trial = crate::update::pending(&home.root).is_some();
812
        // Runner updates (oxygenhub#322): asked of the hub once it has
813
        // answered a claim, then every 15 minutes.
8140×
        let mut update_asked: Option<Instant> = None;
8150×
        let mut update_said = String::new();
816
        loop {
8170×
            if UPDATE.swap(false, std::sync::atomic::Ordering::SeqCst) {
8180×
                let p = crate::update::pending(&home.root);
8190×
                let notice = Duration::from_secs(p.as_ref().map_or(0, |p| p.notice_secs));
8200×
                let to = p.map_or_else(|| "a new build".to_string(), |p| format!("flow {}", p.to));
8210×
                eprintln!("flow runner {name}: updating to {to}: leaving within {} s", notice.as_secs());
8220×
                leave_within(&format!("updating to {to}"), notice);
8230×
            }
824
            // Draining (oxygenflow#50): told to stop, claim nothing more and
825
            // stop once every job held is done and reported.
8260×
            if stopping() {
8270×
                let (jobs, holding) = (used.lock().unwrap().jobs, held.lock().unwrap().len());
8280×
                if jobs == 0 && holding == 0 {
8290×
                    eprintln!("flow runner {name}: drained, stopping");
8300×
                    break;
8310×
                }
8320×
                if !said_draining {
8330×
                    eprintln!("flow runner {name}: draining: claiming nothing more, stopping when the {jobs} job(s) held are done (stop again to stop now)");
8340×
                    said_draining = true;
8350×
                }
8360×
                beat(&mut heard);
8370×
                std::thread::sleep(Duration::from_millis(500));
8380×
                continue;
8390×
            }
8400×
            if used.lock().unwrap().jobs == 0 && benched.elapsed() >= Duration::from_secs(15 * 60) {
8410×
                speed = measure();
8420×
                benched = Instant::now();
8430×
            }
8440×
            let room = budget.room(*used.lock().unwrap());
8450×
            let Some((free_memory_mib, free_cpus)) = room else {
8460×
                beat(&mut heard);
8470×
                std::thread::sleep(Duration::from_millis(500));
8480×
                continue;
849
            };
8500×
            heard = Instant::now();
8510×
            let cache_times = crate::cache::Pool::new(&home.root, cfg.cache_gb).slot_times();
8520×
            let req = ClaimRequest {
8530×
                runner: name.clone(),
8540×
                runtimes: runtimes.clone(),
8550×
                free_memory_mib,
8560×
                free_cpus,
8570×
                info: Some(RunnerInfo {
8580×
                    version: env!("OXY_VERSION_LONG").into(),
8590×
                    ..RunnerInfo::here(cfg.offered_labels(), budget.max_jobs as u32, cfg.memory_mib, cfg.cpus)
8600×
                }),
861
                // Read each time: an image imported while the runner runs counts.
8620×
                images: Some(home.images()),
8630×
                image_archs: Some(home.image_archs()),
8640×
                holding: Some(held.lock().unwrap().iter().copied().collect()),
865
                fetches_images: true,
8660×
                facts: Some(crate::facts::now(home, Some(speed))),
8670×
                swarm: swarm.as_ref().map(|s| s.addr.clone()),
8680×
                caches: Some(cache_times.keys().cloned().collect()),
8690×
                cache_times: Some(cache_times),
870
            };
8710×
            let answer = hub.claim(&req);
8720×
            if on_trial && answer.is_ok() {
8730×
                crate::update::proven(&home.root);
8740×
                on_trial = false;
8750×
            }
8760×
            if answer.is_ok() && update_asked.is_none_or(|t| t.elapsed() >= UPDATE_EVERY) {
8770×
                update_asked = Some(Instant::now());
8780×
                if let Some(note) = crate::update::take_note(&home.root) {
8790×
                    let _ = hub.report_update(&note);
8800×
                }
8810×
                consider_update(home, &hub, &mut update_said);
8820×
            }
8830×
            match answer {
8840×
                Ok(Some(claim)) => {
8850×
                    idle = Duration::from_secs(2);
8860×
                    crate::metrics::CLAIMS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8870×
                    let (mem, cpus) = (claim.sandbox.memory_mib, claim.sandbox.cpus);
8880×
                    {
8890×
                        let mut u = used.lock().unwrap();
8900×
                        u.jobs += 1;
8910×
                        u.memory_mib += mem;
8920×
                        u.cpus += cpus;
8930×
                    }
8940×
                    held.lock().unwrap().insert(claim.job_id);
8950×
                    let (home, hub, cfg, used, key, held, swarm) = (home, &hub, &cfg, &used, &key, &held, swarm.as_ref());
8960×
                    scope.spawn(move || {
8970×
                        let id = claim.job_id;
8980×
                        fetch_image(home, hub, cfg, swarm, &claim);
8990×
                        if let Some(why) = preflight(home, &claim) {
9000×
                            eprintln!("job {id}: declined: {why}");
9010×
                            crate::metrics::DECLINED.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9020×
                            if let Err(e) = hub.decline(id, &why) {
9030×
                                eprintln!("job {id}: decline: {e:#}");
9040×
                            }
9050×
                            held.lock().unwrap().remove(&id);
9060×
                            let mut u = used.lock().unwrap();
9070×
                            u.jobs -= 1;
9080×
                            u.memory_mib -= mem;
9090×
                            u.cpus -= cpus;
9100×
                            return;
9110×
                        }
9120×
                        eprintln!(
913
                            "job {id}: {} {} on {}",
914
                            claim.repo,
915
                            claim.job.name,
9160×
                            claim.heads.first().map(|h| &h[..12]).unwrap_or("-")
917
                        );
9180×
                        crate::metrics::RUNNING.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9190×
                        let finish = run_claim(home, hub, cfg, key, &claim).unwrap_or_else(|e| Finish {
9200×
                            exit_code: None,
921
                            duration_ms: 0,
9220×
                            receipt: None,
9230×
                            signed_receipt: None,
9240×
                            error: Some(format!("{e:#}")),
9250×
                            peak_disk_mib: None,
9260×
                            peak_memory_mib: None,
9270×
                        });
9280×
                        eprintln!(
929
                            "job {id}: exit {:?}{}",
930
                            finish.exit_code,
9310×
                            finish.error.as_deref().map(|e| format!(" ({e})")).unwrap_or_default()
932
                        );
9330×
                        crate::metrics::RUNNING.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
9340×
                        let cancelled = finish.error.as_deref() == Some(CANCELLED);
9350×
                        crate::metrics::finished(finish.exit_code, finish.error.as_deref(), finish.duration_ms, cancelled);
9360×
                        match leaving() {
937
                            // Stopped as the runner leaves: another runner takes it.
9380×
                            Some(why) if cancelled => {
9390×
                                eprintln!("job {id}: handed back: {why}");
9400×
                                if let Err(e) = hub.release(id, &why) {
9410×
                                    eprintln!("job {id}: handing back: {e:#}; the hub requeues it once this runner's lease lapses");
9420×
                                }
943
                            }
9440×
                            _ if !cancelled => report_finish(home, hub, id, &finish),
9450×
                            _ => {}
946
                        }
9470×
                        held.lock().unwrap().remove(&id);
9480×
                        let mut u = used.lock().unwrap();
9490×
                        u.jobs -= 1;
9500×
                        u.memory_mib -= mem;
9510×
                        u.cpus -= cpus;
9520×
                    });
953
                }
9540×
                Ok(None) => std::thread::sleep(idle),
9550×
                Err(e) => {
9560×
                    eprintln!("claim: {e:#}");
9570×
                    std::thread::sleep(idle);
9580×
                    idle = (idle * 2).min(Duration::from_secs(60));
9590×
                }
960
            }
961
        }
9620×
        Ok(())
9630×
    })
9640×
}
965
966
/// Pack and keep a handed-back job's checkpoints (oxygenflow#77); what
967
/// happened goes to its log, and a failure only means the next attempt
968
/// starts again.
969
#[allow(clippy::too_many_arguments)]
9700×
fn save_checkpoint(hub: &Hub, id: i64, job: &flow_core::Job, scratch: &Path, dir_tier: bool, wasm: bool, mut say: impl FnMut(String)) {
9710×
    if !dir_tier {
9720×
        say("checkpoint: only the WASM and syscall tiers save one yet; the next attempt starts again".into());
9730×
        return;
9740×
    }
9750×
    let dirs: Vec<(String, PathBuf)> = job
9760×
        .checkpoints
9770×
        .iter()
9780×
        .filter_map(|c| crate::checkpoint::host_dir(c, job, &scratch.join("tree"), scratch, wasm).map(|d| (c.clone(), d)))
9790×
        .collect();
9800×
    match crate::checkpoint::pack(&dirs).and_then(|(bytes, n)| Ok((hub.save_checkpoint(id, &bytes)?, n))) {
9810×
        Ok((blob, n)) => {
9820×
            say(format!("checkpoint {}: {} files, {} bytes, kept for the next attempt", &blob[..12.min(blob.len())], n.files, n.bytes))
983
        }
9840×
        Err(e) => say(format!("checkpoint: not kept ({e:#}); the next attempt starts again")),
985
    }
9860×
}
987
988
/// How many times the runner was told to stop (SIGTERM or SIGINT).
989
static STOPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
990
9911×
extern "C" fn on_stop(_: libc::c_int) {
992
    // A second stop means now: only async-signal-safe calls here.
9931×
    if STOPS.fetch_add(1, std::sync::atomic::Ordering::SeqCst) >= 1 {
9940×
        unsafe { libc::_exit(143) };
9951×
    }
9961×
}
997
998
/// Drain instead of dying on the first SIGTERM or SIGINT (oxygenflow#50),
999
/// so restarting a runner never kills the job it runs: the unit's
1000
/// `KillMode=mixed` sends the signal to the runner alone, not its microVMs.
10010×
fn drain_on_stop() {
10020×
    let handler = on_stop as extern "C" fn(libc::c_int) as libc::sighandler_t;
10030×
    unsafe {
10040×
        libc::signal(libc::SIGTERM, handler);
10050×
        libc::signal(libc::SIGINT, handler);
10060×
    }
10070×
}
1008
10093×
fn stopping() -> bool {
10103×
    STOPS.load(std::sync::atomic::Ordering::SeqCst) > 0
10113×
}
1012
1013
/// Batches records to the hub every second (or every 200 lines). A quiet
1014
/// job's sink still asks the hub every few seconds whether the job runs,
1015
/// with an empty batch; once the hub answers 409 the job is not wanted.
1016
struct LogSink<'a> {
1017
    hub: &'a Hub,
1018
    job: i64,
1019
    buf: Vec<Record>,
1020
    last: Instant,
1021
    gone: bool,
1022
    /// Set when the runner leaves ([`LEAVING`]): the job stops, to be
1023
    /// handed back, unless its expected rest fits the notice.
1024
    leaving: &'a std::sync::Mutex<Option<Leave>>,
1025
    /// When the job started, and how long the hub expects it to take.
1026
    started: Instant,
1027
    expected: Option<Duration>,
1028
}
1029
1030
/// The most log lines sent at once, as a busy job's sink flushes them.
1031
const BATCH: usize = 200;
1032
1033
/// The most log lines kept while the hub cannot be reached.
1034
const MAX_UNSENT: usize = 50_000;
1035
1036
/// How often a quiet job asks whether it was cancelled.
1037
const HEARTBEAT: Duration = Duration::from_secs(5);
1038
1039
impl microvm::Sink for LogSink<'_> {
10401×
    fn record(&mut self, r: Record) {
10411×
        self.push(r)
10421×
    }
1043
104410×
    fn cancelled(&mut self) -> bool {
104510×
        let leave = self.leaving.lock().unwrap_or_else(|p| p.into_inner()).clone();
104610×
        if let Some(l) = leave {
1047
            // Finished if what is left of it fits the notice; else handed
1048
            // back as the runner leaves, what the job said so far first.
10495×
            let now = Instant::now();
10505×
            let fits = self.expected.is_some_and(|e| now + e.saturating_sub(self.started.elapsed()) <= l.by);
10515×
            if !fits || now >= l.by {
10524×
                self.flush();
10534×
                return true;
10541×
            }
10555×
        }
10566×
        if !self.gone && self.last.elapsed() >= HEARTBEAT {
10572×
            self.send();
10584×
        }
10596×
        self.gone
106010×
    }
1061
}
1062
1063
impl LogSink<'_> {
10641×
    fn push(&mut self, mut r: Record) {
10651×
        if self.gone {
10661×
            return;
10670×
        }
10680×
        if r.text.len() > MAX_RECORD_TEXT {
10690×
            let mut cut = MAX_RECORD_TEXT;
10700×
            while !r.text.is_char_boundary(cut) {
10710×
                cut -= 1;
10720×
            }
10730×
            r.text.truncate(cut);
10740×
        }
10750×
        self.buf.push(r);
10760×
        if self.buf.len() >= BATCH || self.last.elapsed() >= Duration::from_secs(1) {
10770×
            self.flush();
10780×
        }
10791×
    }
1080
10815×
    fn flush(&mut self) {
10825×
        if !self.buf.is_empty() {
10831×
            self.send();
10844×
        }
10855×
        self.last = Instant::now();
10865×
    }
1087
1088
    /// Send what is buffered, even nothing, in batches of at most
1089
    /// `BATCH` lines.
10906×
    fn send(&mut self) {
1091
        loop {
10928×
            if self.gone {
10930×
                return;
10948×
            }
10958×
            let n = self.buf.len().min(BATCH);
10968×
            let batch: Vec<Record> = self.buf.drain(..n).collect();
10978×
            match self.hub.log(self.job, batch.clone()) {
10985×
                Ok(()) => {}
10993×
                Err(e) if job_gone(&e) => self.gone = true,
11002×
                Err(e) => {
1101
                    // The hub is away (a restart, say): keep the lines for
1102
                    // the next batch, up to a bound, so the log loses none
1103
                    // (oxygenflow#49).
11042×
                    eprintln!("job {}: log: {e:#}; kept for the next batch", self.job);
11052×
                    let mut kept = batch;
11062×
                    kept.append(&mut self.buf);
11072×
                    let over = kept.len().saturating_sub(MAX_UNSENT);
11082×
                    if over > 0 {
11091×
                        kept.drain(..over);
11101×
                        kept.insert(
11111×
                            0,
11121×
                            Record {
11131×
                                t: 0,
11141×
                                stream: "flow".into(),
11151×
                                text: format!("({over} log lines lost while the hub could not be reached)"),
11161×
                            },
11171×
                        );
11181×
                    }
11192×
                    self.buf = kept;
11202×
                    break;
1121
                }
1122
            }
11236×
            if self.buf.is_empty() {
11244×
                break;
11252×
            }
1126
        }
11276×
        self.last = Instant::now();
11286×
    }
1129
}
1130
1131
/// How often a runner with no room to claim tells the hub it is there:
1132
/// well inside the hub's 90 s before it shows a runner offline.
1133
const HUB_HEARTBEAT: Duration = Duration::from_secs(30);
1134
1135
/// How often a runner asks the hub whether it should run another build.
1136
const UPDATE_EVERY: Duration = Duration::from_secs(15 * 60);
1137
1138
/// Notice a runner gives itself to leave for an update the hub offered.
1139
const UPDATE_NOTICE: Duration = Duration::from_secs(600);
1140
1141
/// Ask the hub for this runner's update, and act on it: download the build
1142
/// it offers, check it against the hub's BLAKE3 and as a runner build, and
1143
/// install it, or for a dry run say what would happen. What it did goes to
1144
/// the hub once per outcome (`said`).
11450×
fn consider_update(home: &Home, hub: &Hub, said: &mut String) {
11460×
    let answer = match hub.update_answer() {
11470×
        Ok(Some(a)) => a,
11480×
        Ok(None) => return,
11490×
        Err(e) => {
11500×
            eprintln!("flow runner: asking for an update: {e:#}");
11510×
            return;
1152
        }
1153
    };
11540×
    let Some(offer) = answer.offer else { return };
11550×
    let mut say = |note: String| {
11560×
        if *said != note {
11570×
            eprintln!("flow runner: {note}");
11580×
            if let Err(e) = hub.report_update(&note) {
11590×
                eprintln!("flow runner: telling the hub: {e:#}");
11600×
            }
11610×
            *said = note;
11620×
        }
11630×
    };
11640×
    if home.config.runner.as_ref().and_then(|r| r.update.as_ref()).is_some_and(|u| !u.allow) {
11650×
        return say(format!("refuses flow {}: flow.toml says [runner.update] allow = false", offer.version));
11660×
    }
11670×
    let dir = home.root.join("updates");
11680×
    let file = dir.join(format!("flow-{}", offer.version));
11690×
    let fresh = std::fs::read(&file).is_ok_and(|b| blake3::hash(&b).to_hex().as_str() == offer.blake3);
11700×
    if !fresh {
11710×
        if let Err(e) = std::fs::create_dir_all(&dir).map_err(anyhow::Error::from).and_then(|_| hub.download_build(&offer, &file)) {
11720×
            return say(format!("flow {}: not fetched: {e:#}", offer.version));
11730×
        }
11740×
    }
11750×
    let exe = match std::env::current_exe() {
11760×
        Ok(e) => e,
11770×
        Err(e) => return say(format!("flow {}: cannot find its own binary: {e}", offer.version)),
1178
    };
11790×
    match crate::update::install(home, &exe, &file, UPDATE_NOTICE, answer.policy.dry_run, offer.older) {
11800×
        Ok(done) if answer.policy.dry_run => say(format!("dry run: flow {} checks out here and would replace flow {}", done.to, done.from)),
11810×
        Ok(done) => {
11820×
            let _ = std::fs::remove_file(&file);
11830×
            say(format!("installed flow {} (was {}); leaving within {} s to start it", done.to, done.from, UPDATE_NOTICE.as_secs()))
1184
        }
11850×
        Err(e) => say(format!("flow {}: not installed: {e:#}", offer.version)),
1186
    }
11870×
}
1188
1189
/// Held while a job takes its cache disks and images its workspace (see
1190
/// `run_claim`): one job at a time on the runner's disk and cache pool.
1191
static PREPARE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1192
1193
/// Held while the first clone of any repository passes its token through
1194
/// the process environment.
1195
static CLONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
1196
1197
/// One lock per cached repository: fetches into it, and exports from it,
1198
/// never overlap, while jobs of other repositories go on. A slow repository
1199
/// (one kept in a bucket, say) once held every job on the runner waiting
1200
/// behind a single global lock.
12010×
fn repo_lock(name: &str) -> std::sync::Arc<std::sync::Mutex<()>> {
1202
    static LOCKS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::sync::Arc<std::sync::Mutex<()>>>>> =
1203
        std::sync::OnceLock::new();
12040×
    let mut locks = LOCKS.get_or_init(Default::default).lock().unwrap_or_else(|p| p.into_inner());
12050×
    locks.entry(name.to_string()).or_default().clone()
12060×
}
1207
1208
/// Seconds, to one decimal place, for the job's log.
12090×
fn secs(d: std::time::Duration) -> String {
12100×
    format!("{:.1} s", d.as_secs_f64())
12110×
}
1212
12130×
fn run_claim(home: &Home, hub: &Hub, cfg: &RunnerConfig, key: &RunnerKey, claim: &Claim) -> Result<Finish> {
12140×
    let started = Instant::now();
12150×
    let mut sink = LogSink {
12160×
        hub,
12170×
        job: claim.job_id,
12180×
        buf: Vec::new(),
12190×
        last: Instant::now(),
12200×
        gone: false,
12210×
        leaving: &LEAVING,
12220×
        started: Instant::now(),
12230×
        expected: claim.expected_ms.map(Duration::from_millis),
12240×
    };
12250×
    let note =
12260×
        |sink: &mut LogSink, text: String| sink.push(Record { t: started.elapsed().as_millis() as u64, stream: "flow".into(), text });
12270×
    let heads: Vec<ChangeHash> = claim.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad head")).collect::<Result<_>>()?;
12280×
    note(&mut sink, format!("fetching {} for state {}", claim.repo, claim.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+")));
1229
    // Preparing a workspace: fetches into a cached repository, and exports
1230
    // from it, are one job at a time per repository (`repo_lock`); taking
1231
    // cache disks and imaging the workspace are one job at a time on the
1232
    // runner (`PREPARE`); a first clone, whose token goes through the process
1233
    // environment, one at a time (`CLONE`).
12340×
    let main_lock = repo_lock(&claim.repo);
12350×
    let asked = Instant::now();
12360×
    let mut main_guard = Some(main_lock.lock().unwrap_or_else(|p| p.into_inner()));
12370×
    if asked.elapsed().as_secs() >= 2 {
12380×
        note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), claim.repo));
12390×
    }
12400×
    let fetching = Instant::now();
12410×
    let repo = cached_repo(home, cfg, claim)?;
12420×
    let fetched = fetching.elapsed();
12430×
    let mut preparing = None;
12440×
    let scratch = home.root.join("work").join(format!("job-{}", claim.job_id));
12450×
    let _ = std::fs::remove_dir_all(&scratch);
12460×
    std::fs::create_dir_all(scratch.join("tree"))?;
12470×
    let result = (|| -> Result<Finish> {
12480×
        let exporting = Instant::now();
12490×
        let mut files = workspace::export_state(&repo, &heads, &scratch.join("tree"))?;
12500×
        main_guard.take();
12510×
        note(&mut sink, format!("fetched in {}, {} files exported in {}", secs(fetched), files.len(), secs(exporting.elapsed())));
1252
        // Pinned subrepos (Oxygen spec §7.8), at their paths, as part of the
1253
        // workspace and of the scope hash.
12540×
        for sub in &claim.subrepos {
12550×
            if sub.path.split('/').any(|p| p.is_empty() || p == "." || p == ".." || p == ".oxy") {
12560×
                bail!("subrepo path {:?} is not a clean relative path", sub.path);
12570×
            }
12580×
            note(
12590×
                &mut sink,
12600×
                format!(
1261
                    "fetching subrepo {} at {} for {}",
1262
                    sub.repo,
12630×
                    sub.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
1264
                    sub.path
1265
                ),
1266
            );
12670×
            let sub_lock = repo_lock(&sub.repo);
12680×
            let asked = Instant::now();
12690×
            let sub_guard = sub_lock.lock().unwrap_or_else(|p| p.into_inner());
12700×
            if asked.elapsed().as_secs() >= 2 {
12710×
                note(&mut sink, format!("waited {} for another job fetching {}", secs(asked.elapsed()), sub.repo));
12720×
            }
12730×
            let sub_repo = cached_repo_at(home, cfg, &sub.repo, &sub.clone_url, &claim.token)?;
12740×
            let sub_heads: Vec<ChangeHash> =
12750×
                sub.heads.iter().map(|h| ChangeHash::from_hex(h).context("bad subrepo head")).collect::<Result<_>>()?;
12760×
            let dir = scratch.join("tree").join(&sub.path);
12770×
            std::fs::create_dir_all(&dir)?;
12780×
            let sub_files = workspace::export_state(&sub_repo, &sub_heads, &dir)?;
12790×
            drop(sub_guard);
12800×
            files.extend(sub_files.into_iter().map(|(p, h)| (format!("{}/{p}", sub.path), h)));
1281
        }
12820×
        let scope_hash = scope_tree_hash(&claim.job.scope, files.iter().map(|(p, h)| (p.as_str(), *h)));
1283
        // Inputs (oxygenflow#58): each producing job's artifact, checked
1284
        // against the blob its receipt names, then put at its path. Not part
1285
        // of the scope: they are the run's, not the repository's.
12860×
        let mut input_blobs = Vec::new();
12870×
        for (index, i) in claim.inputs.iter().enumerate() {
12880×
            let what = format!("input {} from {}", i.artifact, i.from);
12890×
            let bytes = hub.input(claim.job_id, index).with_context(|| format!("{what}: fetching it"))?;
12900×
            let blob = place_input(&scratch.join("tree"), i, &bytes).with_context(|| what.clone())?;
12910×
            note(&mut sink, format!("{what}: {} bytes at {}, blob {} as its receipt names", bytes.len(), i.path, &i.blob[..12]));
12920×
            input_blobs.push(blob);
1293
        }
1294
        // The syscall tier runs on the tree itself; a microVM gets an image.
12950×
        let syscall_tier = claim.sandbox.runtime == flow_core::Runtime::Syscall;
12960×
        let wasm_tier = claim.sandbox.runtime == flow_core::Runtime::Wasm;
1297
        // The syscall and WASM tiers see the job's files as a directory;
1298
        // the MicroVM tier as an ext4 image.
12990×
        let dir_tier = syscall_tier || wasm_tier;
13000×
        let job = claim.job.in_sandbox(&claim.sandbox).with_flow_env(&claim.flow_env());
1301
        // Disk mounts that name a cache start from a kept disk (#28): a
1302
        // microVM takes an image already in place as it is, the syscall tier
1303
        // a directory (#70). Taken before the workspace is imaged: the
1304
        // sources the disk was built from give unchanged files their old
1305
        // times back (#52).
13060×
        let asked = Instant::now();
13070×
        preparing = Some(PREPARE.lock().unwrap_or_else(|p| p.into_inner()));
13080×
        if asked.elapsed().as_secs() >= 2 {
13090×
            note(&mut sink, format!("waited {} for another job imaging its workspace", secs(asked.elapsed())));
13100×
        }
13110×
        let pool = crate::cache::Pool::new(&home.root, cfg.cache_gb);
13120×
        let form = if dir_tier { crate::cache::Form::Dir } else { crate::cache::Form::Image };
13130×
        let cache_ctx =
13140×
            crate::cache::Ctx { repo: &claim.repo, bookmark: &claim.bookmark, job: &claim.job.name, image: &claim.sandbox.rootfs, form };
13150×
        let mut cached: Vec<(usize, String, String)> = Vec::new();
13160×
        let mut built_from: Option<crate::cache::Sources> = None;
13170×
        for (i, m) in job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).enumerate() {
13180×
            let Some(name) = &m.cache else { continue };
13190×
            let key = crate::cache::Pool::key(&cache_ctx, m, |p| files.iter().find(|(f, _)| f == p).map(|(_, h)| hex::encode(h)));
13200×
            let how = match pool.take(&cache_ctx, m, &key, &crate::cache::disk_path(form, &scratch, i)) {
13210×
                Some(t) => {
13220×
                    if built_from.is_none() {
13230×
                        built_from = t.sources;
13240×
                    }
13250×
                    t.how
1326
                }
13270×
                None => format!("cache {name}: none kept yet, an empty disk"),
1328
            };
13290×
            note(&mut sink, format!("{} ({})", how, m.target));
1330
            // What the job reads is seen when the disk is pruned (#72).
13310×
            if let Err(e) = crate::cache::forget_reads(form, &crate::cache::disk_path(form, &scratch, i)) {
13320×
                note(&mut sink, format!("cache {name}: {e:#}"));
13330×
            }
13340×
            cached.push((i, key, how));
1335
        }
1336
        // What the job reads or writes on its cache from now on is what it
1337
        // used; the rest may be pruned before the cache is kept (#72).
13380×
        let cache_started = if cached.is_empty() { std::time::SystemTime::now() } else { flow_init::prune::start_clock() };
13390×
        let sources = if cached.is_empty() {
13400×
            crate::cache::Sources::new()
1341
        } else {
13420×
            let (sources, restored) = workspace::restore_times(&scratch.join("tree"), &files, built_from.as_ref());
13430×
            if built_from.is_some() {
13440×
                note(
13450×
                    &mut sink,
13460×
                    format!(
13470×
                        "cache: {restored} of {} files and directories unchanged since the cached build, their times kept",
13480×
                        sources.len()
13490×
                    ),
13500×
                );
13510×
            }
13520×
            sources
1353
        };
1354
        // An earlier attempt's checkpoint (oxygenflow#77): back in place,
1355
        // over the cache, before the same exec runs again; the receipt
1356
        // lists it among the job's inputs.
13570×
        if let Some(blob) = &claim.checkpoint {
13580×
            if dir_tier {
13590×
                let bytes = hub.checkpoint(claim.job_id).context("fetching the checkpoint")?;
13600×
                if Repo::blob_ref(&bytes).to_hex() != *blob {
13610×
                    bail!("the checkpoint fetched is not blob {}, as the claim names", &blob[..12.min(blob.len())]);
13620×
                }
13630×
                let place = |root: &str| crate::checkpoint::host_dir(root, &job, &scratch.join("tree"), &scratch, wasm_tier);
13640×
                let n = crate::checkpoint::unpack(&bytes, &job.checkpoints, place)?;
13650×
                note(
13660×
                    &mut sink,
13670×
                    format!("restored checkpoint {}: {} files, {} bytes, from the attempt handed back", &blob[..12], n.files, n.bytes),
13680×
                );
13690×
                input_blobs.push(Repo::blob_ref(&bytes).0);
13700×
            } else {
13710×
                note(&mut sink, "a checkpoint was saved, but only the WASM and syscall tiers restore one yet: starting again".into());
13720×
            }
13730×
        }
13740×
        if !dir_tier {
13750×
            workspace::image(&scratch.join("tree"), &scratch.join("workspace.ext4"))?;
13760×
            std::fs::remove_dir_all(scratch.join("tree"))?;
13770×
        }
13780×
        preparing.take();
1379
        // Cancelled while it was being prepared: no sandbox.
13800×
        if microvm::Sink::cancelled(&mut sink) {
13810×
            return Ok(cancelled());
13820×
        }
13830×
        if wasm_tier {
13840×
            note(&mut sink, format!("starting WASM (wasmtime {}): {} MiB", crate::wasm::WASMTIME, claim.sandbox.memory_mib));
13850×
        } else {
13860×
            note(
13870×
                &mut sink,
13880×
                format!(
1389
                    "{}: {} {}, {} MiB, rootfs {}",
13900×
                    if syscall_tier { "starting a syscall sandbox" } else { "booting a microVM" },
1391
                    claim.sandbox.cpus,
13920×
                    if syscall_tier { "CPU" } else { "vCPU" },
1393
                    claim.sandbox.memory_mib,
13940×
                    &claim.sandbox.rootfs[..12]
1395
                ),
1396
            );
1397
        }
13980×
        let timeout = Duration::from_secs(claim.timeout_s);
13990×
        let mut outcome = if wasm_tier {
14000×
            crate::wasm::run(&claim.sandbox, &job, &scratch.join("tree"), &scratch, timeout, &mut sink)?
14010×
        } else if syscall_tier {
14020×
            let group = format!("job-{}", claim.job_id);
14030×
            crate::syscall::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("tree"), &scratch, timeout, &mut sink, &group)?
1404
        } else {
14050×
            microvm::run(home, &claim.sandbox, &job, &claim.secrets, &scratch.join("workspace.ext4"), &scratch, timeout, &mut sink)?
1406
        };
14070×
        if outcome.cancelled {
1408
            // Handed back as the runner leaves: its checkpoints first, for
1409
            // the next attempt (oxygenflow#77).
14100×
            if leaving().is_some() && !job.checkpoints.is_empty() {
14110×
                save_checkpoint(hub, claim.job_id, &job, &scratch, dir_tier, wasm_tier, |t| note(&mut sink, t));
14120×
            }
14130×
            return Ok(cancelled());
14140×
        }
1415
        // The receipt says what a cached disk started from.
14160×
        let disk_mounts: Vec<&flow_core::pipeline::Mount> =
14170×
            job.mounts.iter().filter(|m| m.source == flow_core::pipeline::MountSource::Disk).collect();
14180×
        for (i, key, how) in &cached {
14190×
            outcome.environment.parts.push((format!("cache {}", disk_mounts[*i].target), format!("{key}: {how}")));
14200×
        }
1421
        // A passing job's artifacts, read from its disks and uploaded; a
1422
        // declared artifact that cannot be kept fails the job. A failing
1423
        // job keeps only its `when "always"` ones (oxygenflow#37), outside
1424
        // its receipt, and one it cannot keep is only noted.
14250×
        let mut outputs = vec![];
14260×
        let mut output_error = None;
14270×
        let passed = outcome.exit_code == Some(0);
14280×
        let wanted = claim.job.outputs.iter().filter(|o| passed || o.always);
14290×
        for o in wanted {
14300×
            if o.kind == flow_core::OutputKind::Report {
14310×
                let read = if dir_tier {
14320×
                    let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14330×
                    crate::outputs::read_report_dir(&dir, &inner)
1434
                } else {
14350×
                    let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14360×
                    crate::outputs::read_report(&image, &inner, &scratch)
1437
                };
14380×
                let kept = read.and_then(|files| upload_report(hub, claim.job_id, &o.name, &files));
14390×
                match kept {
14400×
                    Ok((blob, files, bytes)) => {
14410×
                        let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
14420×
                        let hex = blob.to_hex();
14430×
                        note(&mut sink, format!("report {}: {files} files, {bytes} bytes, manifest {}{unattested}", o.name, &hex[..12]));
14440×
                        if passed {
14450×
                            outputs.push(blob.0);
14460×
                        }
1447
                    }
14480×
                    Err(e) if passed => {
14490×
                        output_error = Some(format!("report {}: {e:#}", o.name));
14500×
                        break;
1451
                    }
14520×
                    Err(e) => note(&mut sink, format!("report {}: not kept: {e:#}", o.name)),
1453
                }
14540×
                continue;
14550×
            }
14560×
            let read = if dir_tier {
14570×
                let (dir, inner) = crate::outputs::locate_dir(&claim.job, &scratch.join("tree"), &scratch, &o.path);
14580×
                crate::outputs::read_dir_file(&dir, &inner)
1459
            } else {
14600×
                let (image, inner) = crate::outputs::locate(&claim.job, &scratch.join("workspace.ext4"), &scratch, &o.path);
14610×
                crate::outputs::read(&image, &inner, &scratch)
1462
            };
14630×
            let kept = read.and_then(|bytes| {
14640×
                let blob = Repo::blob_ref(&bytes);
14650×
                let named = hub.artifact(claim.job_id, &o.name, &bytes)?;
14660×
                if named != blob.to_hex() {
14670×
                    bail!("the hub kept it as {named}, not {}", blob.to_hex());
14680×
                }
14690×
                let unattested = if passed { "" } else { " (the job failed: not in its receipt)" };
14700×
                note(&mut sink, format!("artifact {}: {} bytes, blob {}{unattested}", o.name, bytes.len(), &named[..12]));
14710×
                Ok(blob.0)
14720×
            });
14730×
            match kept {
14740×
                Ok(b) if passed => outputs.push(b),
14750×
                Ok(_) => {}
14760×
                Err(e) if passed => {
14770×
                    output_error = Some(format!("artifact {}: {e:#}", o.name));
14780×
                    break;
1479
                }
14800×
                Err(e) => note(&mut sink, format!("artifact {}: not kept: {e:#}", o.name)),
1481
            }
1482
        }
14830×
        if let Some(e) = &output_error {
14840×
            note(&mut sink, e.clone());
14850×
        }
14860×
        let receipt = outcome.exit_code.filter(|_| output_error.is_none()).map(|code| Receipt {
14870×
            job_name: claim.job.name.clone(),
14880×
            pipeline_hash: hex32(&claim.pipeline_hash),
14890×
            scope_tree_hash: scope_hash,
14900×
            inputs: input_blobs.clone(),
14910×
            environment: outcome.environment.hash(),
14920×
            outputs,
14930×
            exit_code: code as u32,
14940×
            duration_ms: outcome.duration_ms,
14950×
        });
14960×
        let signed_receipt = match &receipt {
14970×
            Some(r) => {
14980×
                let mut signed = sign_receipt(&repo, &heads, cfg, key, claim, r)?;
14990×
                if cfg.keyless {
15000×
                    match sign_keyless(&repo, &heads, cfg, hub, claim, r) {
15010×
                        Ok(k) => signed = k,
15020×
                        Err(e) => {
15030×
                            note(&mut sink, format!("receipt: signed with the runner's key; a short-lived key was not certified: {e:#}"))
1504
                        }
1505
                    }
15060×
                }
15070×
                Some(hex::encode(signed.encode()))
1508
            }
15090×
            None => None,
1510
        };
1511
        // Measured before a cached disk leaves the scratch directory.
15120×
        let peak_disk_mib = crate::facts::allocated_mib(&scratch);
1513
        // A passing job's cached disks are pruned and kept (#72); a
1514
        // failing job's are thrown away, so nothing it wrote reaches a
1515
        // later job.
15160×
        let kept = passed && output_error.is_none();
15170×
        for (i, key, _) in &cached {
15180×
            let disk = crate::cache::disk_path(form, &scratch, *i);
15190×
            let m = disk_mounts[*i];
15200×
            let prune = crate::cache::Prune {
15210×
                started: cache_started,
15220×
                percent: cfg.cache_prune_percent.unwrap_or(flow_init::prune::DEFAULT_PERCENT),
15230×
                guest: outcome.pruned.iter().find(|(t, _)| *t == m.target).map(|(_, p)| p),
1524
            };
15250×
            match pool.settle(&cache_ctx, m, key, &disk, &sources, kept, &prune) {
15260×
                Ok(Some(line)) => note(&mut sink, line),
15270×
                Ok(None) => {}
15280×
                Err(e) => note(&mut sink, format!("cache: not {}: {e:#}", if kept { "kept" } else { "discarded" })),
1529
            }
1530
        }
1531
        Ok(Finish {
15320×
            exit_code: outcome.exit_code,
15330×
            duration_ms: started.elapsed().as_millis() as u64,
15340×
            receipt,
15350×
            signed_receipt,
15360×
            error: output_error.or_else(|| outcome.timed_out.then(|| "stopped at the time limit".to_string())),
1537
            // What the job took (oxygenflow#41): its disks are sparse files
1538
            // in the scratch directory, so their blocks now are their peak.
15390×
            peak_disk_mib,
15400×
            peak_memory_mib: outcome.peak_memory_mib,
1541
        })
1542
    })();
15430×
    let _ = workspace::remove_tree(&scratch);
15440×
    sink.flush();
15450×
    result
15460×
}
1547
1548
/// Bind `receipt` to the state of `heads` in `repo` and sign it as the
1549
/// runner (Oxygen spec §14.6). The state is computed here, not taken from
1550
/// the claim, so the runner vouches only for what it fetched.
1551
/// Upload a report's files, then its manifest under the report's name, and
1552
/// check the hub kept each as the blob it should (oxygenhub#127). Answers
1553
/// the manifest's blob, the file count and their total size.
15540×
fn upload_report(hub: &Hub, job: i64, name: &str, files: &[(String, Vec<u8>)]) -> Result<(oxy_core::hash::ObjectRef, usize, u64)> {
15550×
    let mut listed = Vec::with_capacity(files.len());
15560×
    let mut total = 0u64;
15570×
    for (path, bytes) in files {
15580×
        let blob = Repo::blob_ref(bytes).to_hex();
15590×
        let named = hub.report_file(job, name, path, bytes).with_context(|| format!("uploading {path}"))?;
15600×
        if named != blob {
15610×
            bail!("the hub kept {path} as {named}, not {blob}");
15620×
        }
15630×
        total += bytes.len() as u64;
15640×
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1565
    }
15660×
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed }))?;
15670×
    let blob = Repo::blob_ref(&manifest);
15680×
    let named = hub.artifact(job, name, &manifest)?;
15690×
    if named != blob.to_hex() {
15700×
        bail!("the hub kept the manifest as {named}, not {}", blob.to_hex());
15710×
    }
15720×
    Ok((blob, files.len(), total))
15730×
}
1574
15750×
fn sign_receipt(
15760×
    repo: &Repo,
15770×
    heads: &[ChangeHash],
15780×
    cfg: &RunnerConfig,
15790×
    key: &RunnerKey,
15800×
    claim: &Claim,
15810×
    receipt: &Receipt,
15820×
) -> Result<oxy_core::receipt::SignedReceipt> {
15830×
    let state = state_of(heads);
15840×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
15850×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &key.identity, &key.secret))
15860×
}
1587
1588
/// Sign `receipt` with a fresh key the hub certifies for this job now,
1589
/// just before signing, so the certificate covers the moment the hub
1590
/// accepts it (keyless, oxygenhub#241). The key is dropped with the
1591
/// receipt signed: nothing long-lived signs.
15920×
fn sign_keyless(
15930×
    repo: &Repo,
15940×
    heads: &[ChangeHash],
15950×
    cfg: &RunnerConfig,
15960×
    hub: &Hub,
15970×
    claim: &Claim,
15980×
    receipt: &Receipt,
15990×
) -> Result<oxy_core::receipt::SignedReceipt> {
16000×
    let sk = oxy_core::identity::SecretKey::generate();
16010×
    let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0);
16020×
    let name = format!("{} job {}", cfg.name.as_deref().unwrap_or("runner"), claim.job_id);
16030×
    let id = sk.identity(&name, "", now);
16040×
    let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge(&claim.token)).map_err(|e| anyhow::anyhow!("{e}"))?;
16050×
    let (cert, issuer) = hub.certify(&claim.token, &id, &proof)?;
16060×
    let state = state_of(heads);
16070×
    let run = format!("{}/{}/flow/{}", cfg.hub.trim_end_matches('/'), claim.repo, claim.run_number);
16080×
    Ok(oxy_core::receipt::SignedReceipt::sign(receipt.to_oxy(), repo.id()?, state, &run, &id, &sk).with_certificate(cert, issuer))
16090×
}
1610
1611
/// The ObjectRef of the state whose heads are `heads` (Oxygen spec §10.1).
16120×
pub fn state_of(heads: &[ChangeHash]) -> oxy_core::hash::ObjectRef {
1613
    use oxy_core::hash::{hash_object, ObjectType};
16140×
    hash_object(ObjectType::State, &oxy_core::objects::StateObject::new(heads.to_vec()).encode())
16150×
}
1616
16170×
fn hex32(s: &str) -> [u8; 32] {
16180×
    let mut out = [0; 32];
16190×
    if let Ok(v) = hex::decode(s) {
16200×
        if v.len() == 32 {
16210×
            out.copy_from_slice(&v);
16220×
        }
16230×
    }
16240×
    out
16250×
}
1626
1627
/// Whether a network error is worth another try: DNS, a refused or reset
1628
/// connection, a timeout, or a gateway answering 502, 503 or 504 while the
1629
/// hub restarts (oxygenhub#111).
16308×
fn transient(msg: &str) -> bool {
16318×
    let m = msg.to_lowercase();
16328×
    [
16338×
        "dns failed",
16348×
        "name resolution",
16358×
        "connection refused",
16368×
        "connection reset",
16378×
        "timed out",
16388×
        "timeout",
16398×
        "http 502",
16408×
        "http 503",
16418×
        "http 504",
16428×
        "broken pipe",
16438×
        "unexpected eof",
16448×
    ]
16458×
    .iter()
164647×
    .any(|k| m.contains(k))
16478×
}
1648
1649
/// Run `f` again after a transient network error, waiting `waits` between
1650
/// tries (about a minute in all), and give up on any other error at once.
16513×
fn with_retries<T>(waits: &[Duration], mut f: impl FnMut() -> Result<T>) -> Result<T> {
16523×
    let mut tries = waits.iter();
1653
    loop {
16547×
        match f() {
16551×
            Ok(v) => return Ok(v),
16566×
            Err(e) => match tries.next() {
16575×
                Some(w) if transient(&format!("{e:#}")) => std::thread::sleep(*w),
16582×
                _ => return Err(e),
1659
            },
1660
        }
1661
    }
16623×
}
1663
1664
/// The waits between tries of a fetch: 2, 4, 8, 16 and 30 seconds.
1665
const FETCH_WAITS: [Duration; 5] =
1666
    [Duration::from_secs(2), Duration::from_secs(4), Duration::from_secs(8), Duration::from_secs(16), Duration::from_secs(30)];
1667
1668
/// The runner's copy of a repository, fetched up to date with the job's token.
16690×
fn cached_repo(home: &Home, cfg: &RunnerConfig, claim: &Claim) -> Result<Repo> {
16700×
    cached_repo_at(home, cfg, &claim.repo, &claim.clone_url, &claim.token)
16710×
}
1672
1673
/// The runner's copy of `repo`, cloned or fetched with `token`.
16740×
fn cached_repo_at(home: &Home, cfg: &RunnerConfig, repo_name: &str, clone_url: &str, token: &str) -> Result<Repo> {
16750×
    let dir: PathBuf = home.root.join("repos").join(repo_name.replace('/', "__"));
16760×
    let set_remote = |repo: &mut Repo| -> Result<()> {
16770×
        repo.config.set("remote.origin.url", clone_url).map_err(|e| anyhow::anyhow!("{e}"))?;
16780×
        repo.config.set("remote.origin.token", token).map_err(|e| anyhow::anyhow!("{e}"))?;
16790×
        if let Some(ca) = &cfg.ca {
16800×
            repo.config.set("remote.origin.ca", &ca.to_string_lossy()).map_err(|e| anyhow::anyhow!("{e}"))?;
16810×
        }
16820×
        repo.save_config().map_err(|e| anyhow::anyhow!("{e}"))
16830×
    };
16840×
    if dir.join(".oxy").is_dir() {
16850×
        let mut repo = Repo::open(&dir).map_err(|e| anyhow::anyhow!("{e}"))?;
16860×
        set_remote(&mut repo)?;
16870×
        with_retries(&FETCH_WAITS, || repo.fetch("origin").map(|_| ()).map_err(|e| anyhow::anyhow!("fetch {clone_url}: {e}")))?;
16880×
        return Ok(repo);
16890×
    }
1690
    // First job for this repository: clone with the job's token, which goes
1691
    // through the process environment, so one clone at a time.
16920×
    let _clone = CLONE.lock().unwrap_or_else(|p| p.into_inner());
16930×
    std::env::set_var("OXY_TOKEN", token);
16940×
    if let Some(ca) = &cfg.ca {
16950×
        std::env::set_var("OXY_CA", ca);
16960×
    }
16970×
    let cloned = with_retries(&FETCH_WAITS, || {
16980×
        let _ = std::fs::remove_dir_all(&dir);
16990×
        Repo::clone(clone_url, &dir).map_err(|e| anyhow::anyhow!("{e}"))
17000×
    });
17010×
    std::env::remove_var("OXY_TOKEN");
17020×
    std::env::remove_var("OXY_CA");
17030×
    let mut repo = cloned.map_err(|e| {
17040×
        let _ = std::fs::remove_dir_all(&dir);
17050×
        anyhow::anyhow!("clone {}: {e}", clone_url)
17060×
    })?;
17070×
    set_remote(&mut repo)?;
17080×
    Ok(repo)
17090×
}
1710
1711
#[cfg(test)]
1712
mod tests {
1713
1714
    #[test]
17151×
    fn an_input_is_placed_only_when_it_is_what_the_receipt_names() {
17161×
        let dir = tempfile::tempdir().unwrap();
17171×
        let bytes = b"the reviewed plan";
17181×
        let blob = Repo::blob_ref(bytes).to_hex();
17191×
        let input = |path: &str, blob: &str| flow_core::api::ArtifactInput {
17206×
            artifact: "tfplan".into(),
17216×
            from: "plan".into(),
17226×
            path: path.into(),
17236×
            blob: blob.into(),
17246×
        };
17251×
        let got = super::place_input(dir.path(), &input("/src/plans/tfplan", &blob), bytes).unwrap();
17261×
        assert_eq!(hex::encode(got), blob);
17271×
        assert_eq!(std::fs::read(dir.path().join("plans/tfplan")).unwrap(), bytes);
17281×
        let wrong = super::place_input(dir.path(), &input("/src/other", &"0".repeat(64)), bytes).unwrap_err();
17291×
        assert!(format!("{wrong:#}").contains("not what plan's receipt names"), "{wrong:#}");
17301×
        assert!(!dir.path().join("other").exists(), "nothing written when it does not match");
17314×
        for bad in ["/etc/passwd", "/src/../x", "/src/.oxy/x", "/src/"] {
17324×
            assert!(super::place_input(dir.path(), &input(bad, &blob), bytes).is_err(), "{bad}");
1733
        }
17341×
    }
1735
1736
    use super::*;
1737
1738
    #[test]
17391×
    fn a_runner_names_what_stops_a_sandbox() {
17401×
        let dir = tempfile::tempdir().unwrap();
17411×
        let home = Home::locate(Some(dir.path())).unwrap();
17421×
        let bytes = b"not really ext4";
17431×
        let hash = blake3::hash(bytes).to_hex().to_string();
17441×
        let mut sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
17451×
            "name": "s", "runtime": "syscall", "rootfs": "ab".repeat(32), "memory_mib": 1024, "cpus": 1, "network": "isolated"
1746
        }))
17471×
        .unwrap();
17486×
        let problem = |sb: &flow_core::Sandbox, free| sandbox_problem(&home, sb, "x86_64", free);
17491×
        assert_eq!(problem(&sb, None).unwrap(), "rootfs abababababab is not on this runner");
17501×
        std::fs::write(home.rootfs(&hash), bytes).unwrap();
17511×
        sb.rootfs = hash.clone();
17521×
        assert_eq!(problem(&sb, Some(4096)), None);
17531×
        assert_eq!(problem(&sb, Some(512)).unwrap(), "only 512 MiB of memory is free here; the sandbox needs 1024 MiB");
17541×
        std::fs::write(home.image_manifest(&hash), r#"{"arch":"riscv64"}"#).unwrap();
17551×
        assert_eq!(problem(&sb, None).unwrap(), format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12]));
17561×
        sb.arch = Some("aarch64".into());
17571×
        assert_eq!(problem(&sb, None).unwrap(), "the sandbox needs aarch64; this runner is x86_64");
17581×
        sb.arch = None;
17591×
        std::fs::remove_file(home.image_manifest(&hash)).unwrap();
17601×
        std::fs::write(home.rootfs(&hash), b"changed").unwrap();
17611×
        assert!(problem(&sb, None).unwrap().contains("does not verify"));
17621×
    }
1763
1764
    #[test]
17651×
    fn a_runner_reads_an_unrecorded_images_architecture_and_declines_another() {
1766
        // An image fetched or imported with no recorded architecture, built
1767
        // for riscv64: the runner reads its shell, records it, and declines
1768
        // instead of running it and failing (spec §11.2, §11.5).
17691×
        let dir = tempfile::tempdir().unwrap();
17701×
        let home = Home::locate(Some(dir.path().join("home").as_path())).unwrap();
17711×
        let tree = dir.path().join("tree");
17721×
        std::fs::create_dir_all(tree.join("bin")).unwrap();
17731×
        let mut elf = vec![0u8; 64];
17741×
        elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
17751×
        elf[18..20].copy_from_slice(&0xF3u16.to_le_bytes());
17761×
        std::fs::write(tree.join("bin/sh"), &elf).unwrap();
17771×
        let img = dir.path().join("rootfs.ext4");
17781×
        let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
17791×
        if !made.is_ok_and(|s| s.success()) {
17800×
            eprintln!("mkfs.ext4 not found: skipped");
17810×
            return;
17821×
        }
17831×
        let hash = crate::home::hash_file(&img).unwrap();
17841×
        std::fs::create_dir_all(home.rootfs(&hash).parent().unwrap()).unwrap();
17851×
        std::fs::rename(&img, home.rootfs(&hash)).unwrap();
17861×
        assert!(!home.image_manifest(&hash).exists());
17871×
        let sb: flow_core::Sandbox = serde_json::from_value(serde_json::json!({
17881×
            "name": "s", "runtime": "syscall", "rootfs": hash, "memory_mib": 64, "cpus": 1, "network": "isolated"
1789
        }))
17901×
        .unwrap();
17911×
        assert_eq!(
17921×
            sandbox_problem(&home, &sb, "x86_64", None).unwrap(),
17931×
            format!("rootfs {} is for riscv64; this runner is x86_64", &hash[..12])
1794
        );
17951×
        assert_eq!(sandbox_problem(&home, &sb, "riscv64", None), None, "a riscv64 runner takes it");
1796
        // Learned: recorded once, and reported with the runner's claims.
17971×
        let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(home.image_manifest(&hash)).unwrap()).unwrap();
17981×
        assert_eq!(manifest["arch"], "riscv64");
17991×
        assert_eq!(home.image_archs().get(&hash).map(String::as_str), Some("riscv64"));
18001×
    }
1801
1802
    #[test]
18031×
    fn transient_network_errors_are_tried_again_and_others_are_not() {
18041×
        assert!(transient("fetch x: Dns Failed: resolve dns name 'oxygenhub.io:443': Temporary failure in name resolution"));
18051×
        assert!(transient("HTTP 503: the hub is restarting"));
18061×
        assert!(!transient("HTTP 404: no such repository"));
18071×
        let mut n = 0;
18083×
        let got: Result<u32> = with_retries(&[Duration::ZERO, Duration::ZERO], || {
18093×
            n += 1;
18103×
            if n < 3 {
18112×
                Err(anyhow::anyhow!("connection refused"))
1812
            } else {
18131×
                Ok(7)
1814
            }
18153×
        });
18161×
        assert_eq!((got.unwrap(), n), (7, 3), "two retries, then success");
18171×
        let mut m = 0;
18181×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 4], || {
18191×
            m += 1;
18201×
            Err(anyhow::anyhow!("HTTP 403: forbidden"))
18211×
        });
18221×
        assert!(got.is_err());
18231×
        assert_eq!(m, 1, "a refusal is not tried again");
18241×
        let mut k = 0;
18253×
        let got: Result<u32> = with_retries(&[Duration::ZERO; 2], || {
18263×
            k += 1;
18273×
            Err(anyhow::anyhow!("timed out"))
18283×
        });
18291×
        assert!(got.is_err());
18301×
        assert_eq!(k, 3, "gives up after the last wait");
18311×
    }
1832
1833
    /// A hub that answers each request with the next of `codes`, counting them.
18349×
    fn fake_hub(codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
18359×
        fake_hub_on(std::net::TcpListener::bind("127.0.0.1:0").unwrap(), codes)
18369×
    }
1837
1838
    /// A hub at `listener` answering each request with the next of `codes`.
183911×
    fn fake_hub_on(listener: std::net::TcpListener, codes: Vec<u16>) -> (String, std::sync::Arc<std::sync::atomic::AtomicUsize>) {
1840
        use std::io::{Read, Write};
184111×
        let addr = listener.local_addr().unwrap();
184211×
        let seen = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
184311×
        let count = seen.clone();
184411×
        std::thread::spawn(move || {
184522×
            for code in codes {
184622×
                let (mut s, _) = listener.accept().unwrap();
1847
                // Read the whole request (headers, then Content-Length bytes
1848
                // of body) before answering: closing early would reset the
1849
                // connection while the client is still sending.
185022×
                let mut req = Vec::new();
185122×
                let mut buf = [0u8; 8192];
1852
                loop {
185331×
                    let n = s.read(&mut buf).unwrap_or(0);
185431×
                    if n == 0 {
18550×
                        break;
185631×
                    }
185731×
                    req.extend_from_slice(&buf[..n]);
185831×
                    let text = String::from_utf8_lossy(&req);
185931×
                    if let Some(end) = text.find("\r\n\r\n") {
186031×
                        let len = text[..end]
186131×
                            .lines()
1862242×
                            .find_map(|l| {
1863242×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
1864242×
                            })
186531×
                            .unwrap_or(0);
186631×
                        if req.len() >= end + 4 + len {
186722×
                            break;
18689×
                        }
18690×
                    }
1870
                }
187122×
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
187222×
                let reason = if code == 204 { "No Content" } else { "Error" };
187322×
                let _ = write!(s, "HTTP/1.1 {code} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
1874
            }
187511×
        });
187611×
        (format!("http://{addr}"), seen)
187711×
    }
1878
1879
    /// A hub that answers one request with `body` (status 200) and hands
1880
    /// back what it was sent.
18811×
    fn fake_json_hub(body: &'static str) -> (String, std::sync::mpsc::Receiver<String>) {
1882
        use std::io::{Read, Write};
18831×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
18841×
        let addr = listener.local_addr().unwrap();
18851×
        let (tx, rx) = std::sync::mpsc::channel();
18861×
        std::thread::spawn(move || {
18871×
            let (mut s, _) = listener.accept().unwrap();
18881×
            let mut req = Vec::new();
18891×
            let mut buf = [0u8; 65536];
1890
            loop {
18911×
                let n = s.read(&mut buf).unwrap_or(0);
18921×
                if n == 0 {
18930×
                    break;
18941×
                }
18951×
                req.extend_from_slice(&buf[..n]);
18961×
                let text = String::from_utf8_lossy(&req);
18971×
                if let Some(end) = text.find("\r\n\r\n") {
18981×
                    let len = text[..end]
18991×
                        .lines()
19007×
                        .find_map(|l| {
19017×
                            l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
19027×
                        })
19031×
                        .unwrap_or(0);
19041×
                    if req.len() >= end + 4 + len {
19051×
                        break;
19060×
                    }
19070×
                }
1908
            }
19091×
            tx.send(String::from_utf8_lossy(&req).into_owned()).unwrap();
19101×
            let _ = write!(
19111×
                s,
1912
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
19131×
                body.len()
1914
            );
19151×
        });
19161×
        (format!("http://{addr}"), rx)
19171×
    }
1918
1919
    #[test]
19201×
    fn registering_binds_the_key_and_keeps_the_credential_private() {
1921
        use std::os::unix::fs::PermissionsExt;
19221×
        let dir = tempfile::tempdir().unwrap();
19231×
        let home = Home::locate(Some(dir.path())).unwrap();
19241×
        let (hub, sent) = fake_json_hub(r#"{"id":7,"name":"plex","credential":"flowrunner_secret"}"#);
19251×
        let got = register(&home, &hub, " reg-token ", "plex", None, vec!["gpu".into()]).unwrap();
19261×
        assert_eq!((got.id, got.name.as_str()), (7, "plex"));
19271×
        let req = sent.recv().unwrap();
19281×
        assert!(req.starts_with("POST /api/v1/flow/runners/register"), "{req}");
19291×
        let body: Register = serde_json::from_str(&req[req.find("\r\n\r\n").unwrap() + 4..]).unwrap();
19301×
        assert_eq!((body.token.as_str(), body.info.labels.clone()), ("reg-token", vec!["gpu".to_string()]));
19311×
        let key = home.runner_key("plex").unwrap();
19321×
        assert_eq!(body.identity, hex::encode(key.identity.encode()), "the runner's signing identity");
19331×
        let path = dir.path().join(crate::home::RUNNER_TOML);
19341×
        assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
1935
        // The runner then starts from runner.toml.
19361×
        let again = Home::locate(Some(dir.path())).unwrap();
19371×
        let cfg = again.config.runner.unwrap();
19381×
        assert_eq!((cfg.hub.as_str(), cfg.token.as_str(), cfg.name.as_deref()), (hub.as_str(), "flowrunner_secret", Some("plex")));
19391×
        assert_eq!(cfg.labels, ["gpu"]);
19401×
    }
1941
1942
    /// A hub that answers certify with a certificate `sign_as` signs for
1943
    /// `cert_key`, and publishes `published` as its key: two requests.
19443×
    fn fake_certify_hub(
19453×
        sign_as: (oxy_core::identity::Identity, oxy_core::identity::SecretKey),
19463×
        cert_key: oxy_core::identity::Identity,
19473×
        published: oxy_core::identity::Identity,
19483×
    ) -> String {
1949
        use std::io::{Read, Write};
19503×
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
19513×
        let addr = listener.local_addr().unwrap();
19523×
        std::thread::spawn(move || {
19533×
            for _ in 0..2 {
19546×
                let Ok((mut s, _)) = listener.accept() else { return };
19556×
                let mut req = Vec::new();
19566×
                let mut buf = [0u8; 65536];
1957
                loop {
19587×
                    let n = s.read(&mut buf).unwrap_or(0);
19597×
                    if n == 0 {
19600×
                        break;
19617×
                    }
19627×
                    req.extend_from_slice(&buf[..n]);
19637×
                    let text = String::from_utf8_lossy(&req);
19647×
                    if let Some(end) = text.find("\r\n\r\n") {
19657×
                        let len = text[..end]
19667×
                            .lines()
196747×
                            .find_map(|l| {
196847×
                                l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0))
196947×
                            })
19707×
                            .unwrap_or(0);
19717×
                        if req.len() >= end + 4 + len {
19726×
                            break;
19731×
                        }
19740×
                    }
1975
                }
19766×
                let line = String::from_utf8_lossy(&req).lines().next().unwrap_or("").to_string();
19776×
                let body: Vec<u8> = if line.contains("/keyless/certify") {
19783×
                    let cert = oxy_core::cert::SignedCertificate::sign(
19793×
                        oxy_core::cert::Certificate {
19803×
                            key: cert_key.clone(),
19813×
                            issuer: sign_as.0.hash(),
19823×
                            subject: "repo:andy/demo:bookmark:main".into(),
19833×
                            claims: vec![],
19843×
                            scope: oxy_core::identity::Scope::SEAL,
19853×
                            not_before: 1,
19863×
                            expires: 600_001,
19873×
                            grant: None,
19883×
                        },
19893×
                        &sign_as.0,
19903×
                        &sign_as.1,
1991
                    );
19923×
                    serde_json::json!({ "certificate": oxy_core::dsse::base64(&cert.encode()) }).to_string().into_bytes()
1993
                } else {
19943×
                    published.encode()
1995
                };
19966×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len());
19976×
                let _ = s.write_all(&body);
1998
            }
19993×
        });
20003×
        format!("http://{addr}")
20013×
    }
2002
2003
    /// keyless (oxygenhub#241): the runner takes a certificate only when it
2004
    /// is for its fresh key and signed by the key the hub publishes.
2005
    #[test]
20061×
    fn a_certificate_is_taken_only_for_this_key_from_the_hubs_key() {
2007
        use oxy_core::identity::SecretKey;
20081×
        let hub_sk = SecretKey::generate();
20091×
        let hub_id = hub_sk.identity("hub", "", 1);
20101×
        let sk = SecretKey::generate();
20111×
        let id = sk.identity("earth-1 job 7", "", 1);
20121×
        let proof = sk.sign_challenge(&id.hash(), &oxy_core::cert::certify_challenge("flowjob_x")).unwrap();
2013
20141×
        let base = fake_certify_hub((hub_id.clone(), hub_sk.clone()), id.clone(), hub_id.clone());
20151×
        let (cert, issuer) = hub_at(base).certify("flowjob_x", &id, &proof).unwrap();
20161×
        assert_eq!((cert.cert.key_id(), issuer.hash()), (id.hash(), hub_id.hash()));
2017
20181×
        let mallory_sk = SecretKey::generate();
20191×
        let mallory = mallory_sk.identity("mallory", "", 1);
20201×
        let base = fake_certify_hub((mallory.clone(), mallory_sk), id.clone(), hub_id.clone());
20211×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20221×
        assert!(e.contains("not signed by the hub's published key"), "{e}");
2023
20241×
        let other = SecretKey::generate().identity("other", "", 1);
20251×
        let base = fake_certify_hub((hub_id.clone(), hub_sk), other, hub_id);
20261×
        let e = hub_at(base).certify("flowjob_x", &id, &proof).unwrap_err().to_string();
20271×
        assert!(e.contains("another key"), "{e}");
20281×
    }
2029
203016×
    fn hub_at(base: String) -> Hub {
203116×
        Hub { base, token: "t".into(), agent: ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build() }
203216×
    }
2033
2034
    /// oxygenhub#322: an offered build is kept only if it is the bytes the
2035
    /// hub attests; a peer or a proxy cannot change what is installed.
2036
    #[test]
20371×
    fn a_build_is_kept_only_if_it_matches_the_hubs_blake3() {
20381×
        let (body, other) = (b"#!flow build 0.3.2".to_vec(), b"#!something else!!".to_vec());
20392×
        let serve = |bytes: Vec<u8>| {
20402×
            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
20412×
            let addr = listener.local_addr().unwrap();
20422×
            std::thread::spawn(move || {
2043
                use std::io::{Read, Write};
20442×
                let (mut s, _) = listener.accept().unwrap();
20452×
                let mut buf = [0u8; 4096];
20462×
                let _ = s.read(&mut buf);
20472×
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", bytes.len());
20482×
                let _ = s.write_all(&bytes);
20492×
            });
20502×
            format!("http://{addr}")
20512×
        };
20521×
        let offer = flow_core::api::UpdateOffer {
20531×
            version: "0.3.2".into(),
20541×
            asset: "flow-linux-x86_64".into(),
20551×
            url: "/andy/oxygenflow/asset/1/flow-linux-x86_64".into(),
20561×
            blake3: blake3::hash(&body).to_hex().to_string(),
20571×
            size: body.len() as u64,
20581×
            ..Default::default()
20591×
        };
20601×
        let dir = tempfile::tempdir().unwrap();
20611×
        let to = dir.path().join("flow-0.3.2");
20621×
        hub_at(serve(body.clone())).download_build(&offer, &to).unwrap();
20631×
        assert_eq!(std::fs::read(&to).unwrap(), body);
20641×
        std::fs::remove_file(&to).unwrap();
20651×
        let e = hub_at(serve(other)).download_build(&offer, &to).unwrap_err();
20661×
        assert!(e.to_string().contains("does not match what the hub attests"), "{e:#}");
20671×
        assert!(!to.exists() && !to.with_extension("partial").exists(), "nothing of it is left");
20681×
    }
2069
2070
    /// oxygenhub#71: a job's result is offered until the hub takes it,
2071
    /// through server errors, and a refusal ends the trying at once.
2072
    #[test]
20731×
    fn a_result_is_reported_until_the_hub_takes_it() {
20741×
        let f = Finish {
20751×
            exit_code: Some(0),
20761×
            duration_ms: 1,
20771×
            receipt: None,
20781×
            signed_receipt: None,
20791×
            error: None,
20801×
            peak_disk_mib: None,
20811×
            peak_memory_mib: None,
20821×
        };
20831×
        let quick = Duration::from_millis(10);
20841×
        let (base, seen) = fake_hub(vec![502, 503, 500, 500, 204]);
20851×
        hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).unwrap();
20861×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 5, "kept trying through four server errors");
20871×
        let (base, seen) = fake_hub(vec![409]);
20881×
        assert!(hub_at(base).finish_until_accepted(7, &f, Duration::from_secs(30), quick).is_err());
20891×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
20901×
    }
2091
2092
    #[test]
20931×
    fn server_errors_are_tried_again_and_client_errors_are_not() {
20941×
        let quick = [Duration::from_millis(10); 3];
20951×
        let (base, seen) = fake_hub(vec![500, 503, 204]);
20961×
        let r = hub_at(base).post_with("/flow/jobs/1/log", &serde_json::json!({}), &quick).unwrap();
20971×
        assert!(r.is_none());
20981×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 3, "two retries, then accepted");
2099
21001×
        let (base, seen) = fake_hub(vec![500, 500, 500, 500]);
21011×
        let e = hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).unwrap_err().to_string();
21021×
        assert!(e.contains("HTTP 500"), "{e}");
21031×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 4, "gives up after the last delay");
2104
21051×
        let (base, seen) = fake_hub(vec![401]);
21061×
        assert!(hub_at(base).post_with("/flow/claim", &serde_json::json!({}), &quick).is_err());
21071×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1, "a refusal is final");
21081×
    }
2109
2110
    static NOT_LEAVING: std::sync::Mutex<Option<Leave>> = std::sync::Mutex::new(None);
2111
2112
    /// oxygenflow#76: once the runner leaves, a job's sink says it is
2113
    /// cancelled, having sent what the job said so far, and the job is
2114
    /// handed back to the hub.
2115
    #[test]
21161×
    fn a_leaving_runner_stops_its_job_and_hands_it_back() {
2117
        use microvm::Sink;
21181×
        let leaving = std::sync::Mutex::new(None);
21191×
        let (base, seen) = fake_hub(vec![204, 204]);
21201×
        let hub = hub_at(base);
21211×
        let mut sink = LogSink {
21221×
            hub: &hub,
21231×
            job: 7,
21241×
            buf: Vec::new(),
21251×
            last: Instant::now(),
21261×
            gone: false,
21271×
            leaving: &leaving,
21281×
            started: Instant::now(),
21291×
            expected: None,
21301×
        };
21311×
        sink.buf.push(Record { t: 1, stream: "out".into(), text: "step 1".into() });
21321×
        assert!(!sink.cancelled());
21331×
        *leaving.lock().unwrap() = Some(Leave { reason: "off Wi-Fi".into(), by: Instant::now() });
21341×
        assert!(sink.cancelled());
21351×
        assert!(sink.buf.is_empty(), "flushed before the job stops");
21361×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 1);
21371×
        hub.release(7, "off Wi-Fi").unwrap();
21381×
        assert_eq!(seen.load(std::sync::atomic::Ordering::SeqCst), 2);
21391×
    }
2140
2141
    /// oxygenflow#76: with notice, a job the hub expects to finish within
2142
    /// it runs on; one that will not, or whose time is unknown, is handed
2143
    /// back at once, and any job still running when the notice is up.
2144
    #[test]
21451×
    fn a_job_that_fits_the_notice_finishes_and_the_others_go_back() {
2146
        use microvm::Sink;
21471×
        let (base, _) = fake_hub(vec![204; 8]);
21481×
        let hub = hub_at(base);
21491×
        let leaving = std::sync::Mutex::new(Some(Leave { reason: "off charge".into(), by: Instant::now() + Duration::from_secs(60) }));
21501×
        let sink = |expected: Option<u64>, ran: u64| LogSink {
21514×
            hub: &hub,
2152
            job: 1,
21534×
            buf: Vec::new(),
21544×
            last: Instant::now(),
2155
            gone: false,
21564×
            leaving: &leaving,
21574×
            started: Instant::now() - Duration::from_secs(ran),
21584×
            expected: expected.map(Duration::from_secs),
21594×
        };
21601×
        assert!(!sink(Some(70), 30).cancelled(), "40 s left of it, within a minute: it finishes");
21611×
        assert!(sink(Some(600), 30).cancelled(), "nearly ten minutes left: handed back");
21621×
        assert!(sink(None, 0).cancelled(), "no idea how long: handed back");
21631×
        *leaving.lock().unwrap() = Some(Leave { reason: "off charge".into(), by: Instant::now() - Duration::from_secs(1) });
21641×
        assert!(sink(Some(70), 30).cancelled(), "the notice is up: handed back whatever was expected");
21651×
    }
2166
2167
    /// oxygenflow#32: a quiet job asks the hub every few seconds whether
2168
    /// it still runs; a 409 marks it cancelled, and nothing more is sent.
2169
    #[test]
21701×
    fn a_quiet_job_learns_that_its_run_was_cancelled() {
2171
        use microvm::Sink;
21722×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
21731×
        let quiet = Instant::now() - HEARTBEAT - Duration::from_secs(1);
21741×
        let (base, seen) = fake_hub(vec![204]);
21751×
        let hub = hub_at(base);
21761×
        let mut sink = LogSink {
21771×
            hub: &hub,
21781×
            job: 1,
21791×
            buf: Vec::new(),
21801×
            last: quiet,
21811×
            gone: false,
21821×
            leaving: &NOT_LEAVING,
21831×
            started: Instant::now(),
21841×
            expected: None,
21851×
        };
21861×
        assert!(!sink.cancelled());
21871×
        assert!(!sink.cancelled(), "asked again only after the heartbeat");
21881×
        assert_eq!(n(&seen), 1);
2189
21901×
        let (base, seen) = fake_hub(vec![409]);
21911×
        let hub = hub_at(base);
21921×
        let mut sink = LogSink {
21931×
            hub: &hub,
21941×
            job: 1,
21951×
            buf: Vec::new(),
21961×
            last: quiet,
21971×
            gone: false,
21981×
            leaving: &NOT_LEAVING,
21991×
            started: Instant::now(),
22001×
            expected: None,
22011×
        };
22021×
        assert!(sink.cancelled());
22031×
        sink.record(Record { t: 0, stream: "out".into(), text: "late".into() });
22041×
        sink.flush();
22051×
        assert!(sink.cancelled());
22061×
        assert_eq!(n(&seen), 1, "nothing is sent for a cancelled job");
22071×
    }
2208
2209
    /// oxygenflow#49: a hub that is away for a while (a deploy restarting
2210
    /// it) costs a job's uploads a wait, not the upload, and costs its log
2211
    /// no lines.
2212
    #[test]
22131×
    fn a_job_outlasts_a_hub_restart() {
22142×
        let n = |seen: &std::sync::Arc<std::sync::atomic::AtomicUsize>| seen.load(std::sync::atomic::Ordering::SeqCst);
2215
        // A port nobody listens on yet: the hub is restarting.
22161×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22171×
        let base = format!("http://127.0.0.1:{port}");
22181×
        let hub = hub_at(base.clone());
2219
2220
        // Log lines sent while it is away are kept, and go when it is back.
22211×
        let mut sink = LogSink {
22221×
            hub: &hub,
22231×
            job: 1,
22241×
            buf: Vec::new(),
22251×
            last: Instant::now(),
22261×
            gone: false,
22271×
            leaving: &NOT_LEAVING,
22281×
            started: Instant::now(),
22291×
            expected: None,
22301×
        };
2231450×
        for i in 0..450 {
2232450×
            sink.buf.push(Record { t: i, stream: "out".into(), text: format!("line {i}") });
2233450×
        }
22341×
        sink.send();
22351×
        assert_eq!(sink.buf.len(), 450, "nothing lost while the hub is away");
22361×
        let (_, seen) = fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![204, 204, 204]);
22371×
        sink.send();
22381×
        assert!(sink.buf.is_empty() && !sink.gone);
22391×
        assert_eq!(n(&seen), 3, "in batches of 200: 200, 200 and 50");
2240
2241
        // An upload waits for the hub to come back, through refused
2242
        // connections and server errors alike.
22431×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22441×
        let url = format!("http://127.0.0.1:{port}/x");
22451×
        let agent = ureq::AgentBuilder::new().timeout(Duration::from_secs(5)).build();
22461×
        let later = std::thread::spawn(move || {
22471×
            std::thread::sleep(Duration::from_millis(150));
22481×
            fake_hub_on(std::net::TcpListener::bind(("127.0.0.1", port)).unwrap(), vec![502, 204])
22491×
        });
22501×
        let quick = [Duration::from_millis(50); 20];
22515×
        let r = retrying(&url, &quick, true, || agent.post(&url).send_string("{}").map_err(Box::new)).unwrap();
22521×
        assert_eq!(r.status(), 204);
22531×
        assert_eq!(n(&later.join().unwrap().1), 2, "a 502 from the proxy, then the hub");
2254
        // Without `connection`, a hub that cannot be reached ends it at once.
22551×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22561×
        let url = format!("http://127.0.0.1:{port}/x");
22571×
        assert!(retrying(&url, &quick, false, || agent.post(&url).send_string("{}").map_err(Box::new)).is_err());
22581×
        assert!(PATIENT_DELAYS.iter().sum::<Duration>() >= Duration::from_secs(180), "longer than a hub takes to restart");
22591×
    }
2260
2261
    /// oxygenflow#50: the first stop drains (the second, not called here,
2262
    /// exits at once).
2263
    #[test]
22641×
    fn a_stop_drains_the_runner() {
22651×
        assert!(!stopping());
22661×
        on_stop(libc::SIGTERM);
22671×
        assert!(stopping(), "told to stop, it claims nothing more");
2268
        // An embedded runner starts afresh, and stop() drains it the same way.
22691×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
22701×
        stop();
22711×
        assert!(stopping());
22721×
        STOPS.store(0, std::sync::atomic::Ordering::SeqCst);
22731×
    }
2274
2275
    /// Lines kept for a hub that stays away are bounded, saying how many went.
2276
    #[test]
22771×
    fn unsent_log_lines_are_bounded() {
22781×
        let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
22791×
        let hub = hub_at(format!("http://127.0.0.1:{port}"));
22801×
        let mut sink = LogSink {
22811×
            hub: &hub,
22821×
            job: 1,
22831×
            buf: Vec::new(),
22841×
            last: Instant::now(),
22851×
            gone: false,
22861×
            leaving: &NOT_LEAVING,
22871×
            started: Instant::now(),
22881×
            expected: None,
22891×
        };
229050010×
        sink.buf = (0..MAX_UNSENT as u64 + 10).map(|i| Record { t: i, stream: "out".into(), text: String::new() }).collect();
22911×
        sink.send();
22921×
        assert_eq!(sink.buf.len(), MAX_UNSENT + 1);
22931×
        assert_eq!(sink.buf[0].text, "(10 log lines lost while the hub could not be reached)");
22941×
        assert_eq!(sink.buf[1].t, 10, "the oldest go first");
22951×
    }
2296
2297
    #[test]
22981×
    fn the_budget_admits_jobs_that_fit() {
22991×
        let b = Budget { max_jobs: 3, memory_mib: Some(24_576), cpus: Some(8) };
23007×
        let used = |jobs, memory_mib, cpus| Used { jobs, memory_mib, cpus };
23011×
        assert_eq!(b.room(used(0, 0, 0)), Some((None, None)), "a lone job may take everything");
23021×
        assert_eq!(b.room(used(1, 8192, 4)), Some((Some(16_384), Some(4))));
23031×
        assert_eq!(b.room(used(2, 16_384, 8)), None, "no vCPU left");
23041×
        assert_eq!(b.room(used(3, 1024, 1)), None, "at max_jobs");
23051×
        let one = Budget { max_jobs: 1, memory_mib: None, cpus: None };
23061×
        assert_eq!(one.room(used(0, 0, 0)), Some((None, None)));
23071×
        assert_eq!(one.room(used(1, 0, 0)), None, "the default runs one job at a time");
23081×
        let open = Budget { max_jobs: 2, memory_mib: None, cpus: None };
23091×
        assert_eq!(open.room(used(1, 8192, 4)), Some((None, None)), "no limits configured");
23101×
    }
2311
}