OXYGENHUB

Coverage / crates/hub/src/db/runners.rs 96.3%

316 of 328 lines run, 74 of 132 functions · run #468 on main · run missed

1
//! OxygenFlow runners (hub spec §13.2): who may claim jobs, what they are,
2
//! whether they are taking work, and what they have run.
3
4
use super::{now_ms, Pool};
5
use sqlx::FromRow;
6
7
#[derive(Clone, Debug, Default, FromRow)]
8
pub struct Runner {
9
    pub id: i64,
10
    pub name: String,
11
    pub token_hash: String,
12
    pub source: String,
13
    pub key: String,
14
    pub key_name: String,
15
    pub arch: String,
16
    pub os: String,
17
    pub version: String,
18
    pub labels: String,
19
    pub max_jobs: i64,
20
    pub memory_mib: Option<i64>,
21
    pub cpus: Option<i64>,
22
    pub state: String,
23
    pub created_ms: i64,
24
    pub created_by: String,
25
    pub last_seen_ms: Option<i64>,
26
    /// The owner whose repositories it serves; empty for the whole site.
27
    pub scope_owner: String,
28
    /// The one repository it serves, when it serves one.
29
    pub scope_repo_id: Option<i64>,
30
    /// Labels an administrator gave it, beside those it reports (#98).
31
    pub admin_labels: String,
32
    /// A time limit for its jobs in minutes, below the site's, when set.
33
    pub timeout_minutes: Option<i64>,
34
    /// It fetches images it lacks from the hub (oxygenflow#39).
35
    pub fetches_images: bool,
36
    /// What it measured at its last claim (oxygenflow#40): free disk (MiB),
37
    /// the 1-minute load ×100, its speed score and class, its kernel.
38
    pub free_disk_mib: Option<i64>,
39
    pub load_x100: Option<i64>,
40
    pub speed: Option<i64>,
41
    pub speed_class: Option<i64>,
42
    pub kernel: String,
43
    /// The tiers it offered at its last claim, comma-separated.
44
    pub tiers: String,
45
    /// The images it held then (a JSON array); empty when it did not say.
46
    pub images: String,
47
    /// BLAKE3 of what it offers; its declines hold until this changes.
48
    pub profile: String,
49
}
50
51
/// Which repositories' jobs a runner may take (oxygenhub#41).
52
#[derive(Clone, Debug, Default, PartialEq, Eq)]
53
pub struct Scope {
54
    /// Empty: any owner.
55
    pub owner: String,
56
    /// `None`: any of the owner's repositories.
57
    pub repo_id: Option<i64>,
58
}
59
60
impl Scope {
616×
    pub fn is_site(&self) -> bool {
626×
        self.owner.is_empty() && self.repo_id.is_none()
636×
    }
64
}
65
66
/// A runner that has not polled for this long is shown offline.
67
pub const ONLINE_MS: i64 = 90_000;
68
69
impl Runner {
70107×
    pub fn online(&self) -> bool {
71107×
        self.last_seen_ms.is_some_and(|t| now_ms() - t < ONLINE_MS)
72107×
    }
73
74
    /// Whether the hub has heard from it lately (oxygenhub#243): any call it
75
    /// makes counts, a busy runner's heartbeat included.
7631×
    pub fn connectivity(&self) -> &'static str {
7731×
        if self.online() {
7829×
            "online"
79
        } else {
802×
            "offline"
81
        }
8231×
    }
83
84
    /// `online`, `offline`, `draining` or `disabled`.
8532×
    pub fn status(&self) -> &'static str {
8632×
        match self.state.as_str() {
8732×
            "disabled" => "disabled",
8832×
            "draining" => "draining",
8932×
            _ if self.online() => "online",
900×
            _ => "offline",
91
        }
9232×
    }
93
94
    /// Every label it carries: what it reports, and what an administrator
95
    /// gave it.
9651×
    pub fn label_list(&self) -> Vec<&str> {
9751×
        let mut out: Vec<&str> = self.labels.split(',').filter(|l| !l.is_empty()).collect();
9851×
        for l in self.admin_label_list() {
9910×
            if !out.contains(&l) {
10010×
                out.push(l);
10110×
            }
102
        }
10351×
        out
10451×
    }
105
106273×
    pub fn admin_label_list(&self) -> Vec<&str> {
107280×
        self.admin_labels.split(',').filter(|l| !l.is_empty()).collect()
108273×
    }
109
110
    /// The labels it reported itself, as the admin page distinguishes them.
111211×
    pub fn reported_label_list(&self) -> Vec<&str> {
112211×
        self.labels.split(',').filter(|l| !l.is_empty()).collect()
113211×
    }
114
115273×
    pub fn scope(&self) -> Scope {
116273×
        Scope { owner: self.scope_owner.clone(), repo_id: self.scope_repo_id }
117273×
    }
118
}
119
120442×
pub async fn by_token(pool: &Pool, token_hash: &str) -> sqlx::Result<Option<Runner>> {
121442×
    sqlx::query_as("SELECT * FROM flow_runners WHERE token_hash = $1").bind(token_hash).fetch_optional(pool).await
122442×
}
123
12426×
pub async fn get(pool: &Pool, id: i64) -> sqlx::Result<Option<Runner>> {
12526×
    sqlx::query_as("SELECT * FROM flow_runners WHERE id = $1").bind(id).fetch_optional(pool).await
12626×
}
127
128394×
pub async fn list(pool: &Pool) -> sqlx::Result<Vec<Runner>> {
129394×
    sqlx::query_as("SELECT * FROM flow_runners ORDER BY name, id").fetch_all(pool).await
130394×
}
131
132
/// The row of a runner configured with a hub.toml token, made on first sight.
13365×
pub async fn configured(pool: &Pool, token_hash: &str, name: &str) -> sqlx::Result<Runner> {
13465×
    sqlx::query("INSERT INTO flow_runners (name, token_hash, source, created_ms) VALUES ($1, $2, 'config', $3) ON CONFLICT DO NOTHING")
13565×
        .bind(name)
13665×
        .bind(token_hash)
13765×
        .bind(now_ms())
13865×
        .execute(pool)
13965×
        .await?;
14065×
    Ok(by_token(pool, token_hash).await?.expect("just made"))
14165×
}
142
143
/// What a claim says about the runner, and that it was seen now. A
144
/// configured runner takes the name it claims with.
145
/// The administrator's settings for a runner (#98).
1461×
pub async fn set_limits(pool: &Pool, id: i64, admin_labels: &str, timeout_minutes: Option<i64>) -> sqlx::Result<()> {
1471×
    sqlx::query("UPDATE flow_runners SET admin_labels = $1, timeout_minutes = $2 WHERE id = $3")
1481×
        .bind(admin_labels)
1491×
        .bind(timeout_minutes)
1501×
        .bind(id)
1511×
        .execute(pool)
1521×
        .await?;
1531×
    Ok(())
1541×
}
155
156345×
pub async fn seen(pool: &Pool, id: i64, name: Option<&str>, info: Option<&flow_core::api::RunnerInfo>) -> sqlx::Result<()> {
157345×
    let now = now_ms();
158345×
    match info {
15924×
        Some(i) => {
16024×
            sqlx::query(
16124×
                "UPDATE flow_runners SET arch = $1, os = $2, version = $3, labels = $4, max_jobs = $5, memory_mib = $6, cpus = $7, last_seen_ms = $8 WHERE id = $9",
16224×
            )
16324×
            .bind(&i.arch)
16424×
            .bind(&i.os)
16524×
            .bind(&i.version)
16624×
            .bind(i.labels.join(","))
16724×
            .bind(i.max_jobs as i64)
16824×
            .bind(i.memory_mib.map(i64::from))
16924×
            .bind(i.cpus.map(i64::from))
17024×
            .bind(now)
17124×
            .bind(id)
17224×
            .execute(pool)
17324×
            .await?;
174
        }
175
        None => {
176321×
            sqlx::query("UPDATE flow_runners SET last_seen_ms = $1 WHERE id = $2").bind(now).bind(id).execute(pool).await?;
177
        }
178
    }
179345×
    if let Some(n) = name {
180219×
        sqlx::query("UPDATE flow_runners SET name = $1 WHERE id = $2 AND source = 'config'").bind(n).bind(id).execute(pool).await?;
181126×
    }
182345×
    Ok(())
183345×
}
184
185
/// Keep what a runner measured about itself at a claim (oxygenflow#40).
18613×
pub async fn set_facts(pool: &Pool, id: i64, f: &flow_core::api::Facts) -> sqlx::Result<()> {
18713×
    sqlx::query("UPDATE flow_runners SET free_disk_mib = $1, load_x100 = $2, speed = $3, speed_class = $4, kernel = $5 WHERE id = $6")
18813×
        .bind(f.free_disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
18913×
        .bind(f.load_x100.map(i64::from))
19013×
        .bind(f.speed.map(i64::from))
19113×
        .bind(f.speed_class.map(i64::from))
19213×
        .bind(f.kernel.clone().unwrap_or_default())
19313×
        .bind(id)
19413×
        .execute(pool)
19513×
        .await?;
19613×
    Ok(())
19713×
}
198
199
impl Runner {
200
    /// Its facts as words for the Runners page: "speed 100 (class 3) · load
201
    /// 1.12 · 41 GiB free"; empty when it has sent none.
20216×
    pub fn facts_line(&self) -> String {
20316×
        let mut out = Vec::new();
20416×
        if let Some(s) = self.speed {
2051×
            out.push(format!("speed {s} (class {})", self.speed_class.unwrap_or(0)));
20615×
        }
20716×
        if let Some(l) = self.load_x100 {
2081×
            out.push(format!("load {:.2}", l as f64 / 100.0));
20915×
        }
21016×
        if let Some(d) = self.free_disk_mib {
2111×
            out.push(if d >= 1024 { format!("{} GiB free", d / 1024) } else { format!("{d} MiB free") });
21215×
        }
21316×
        out.join(" · ")
21416×
    }
215
}
216
217
/// What a runner offers at a claim (OxygenFlow spec §11.1): its tiers and
218
/// images, and the profile hash over those, its architecture, labels and
219
/// capacity.
220221×
pub async fn set_offer(
221221×
    pool: &Pool,
222221×
    id: i64,
223221×
    tiers: &[String],
224221×
    images: Option<&[String]>,
225221×
    fetches_images: bool,
226221×
    profile: &str,
227221×
) -> sqlx::Result<()> {
228221×
    let images = images.map(|i| serde_json::to_string(i).unwrap_or_default()).unwrap_or_default();
229221×
    sqlx::query("UPDATE flow_runners SET tiers = $1, images = $2, fetches_images = $3, profile = $4 WHERE id = $5")
230221×
        .bind(tiers.join(","))
231221×
        .bind(images)
232221×
        .bind(fetches_images)
233221×
        .bind(profile)
234221×
        .bind(id)
235221×
        .execute(pool)
236221×
        .await?;
237221×
    Ok(())
238221×
}
239
240
impl Runner {
24138×
    pub fn tier_list(&self) -> Vec<&str> {
24245×
        self.tiers.split(',').filter(|t| !t.is_empty()).collect()
24338×
    }
244
245
    /// The images it holds, `None` when it does not say.
246414×
    pub fn image_list(&self) -> Option<Vec<String>> {
247414×
        if self.images.is_empty() {
248342×
            None
249
        } else {
25072×
            serde_json::from_str(&self.images).ok()
251
        }
252414×
    }
253
}
254
2554×
pub async fn set_state(pool: &Pool, id: i64, state: &str) -> sqlx::Result<()> {
2564×
    sqlx::query("UPDATE flow_runners SET state = $1, state_ms = $2 WHERE id = $3")
2574×
        .bind(state)
2584×
        .bind(super::now_ms())
2594×
        .bind(id)
2604×
        .execute(pool)
2614×
        .await?;
2624×
    Ok(())
2634×
}
264
265
/// Whether runner `id`'s last `n` jobs since its state last changed all
266
/// ended in an infrastructure error (oxygenflow#30), with the last one's.
26712×
pub async fn erroring(pool: &Pool, id: i64, n: u32) -> sqlx::Result<Option<String>> {
26812×
    if n == 0 {
2690×
        return Ok(None);
27012×
    }
27112×
    let last: Vec<(String, String)> = sqlx::query_as(
27212×
        "SELECT j.status, j.error FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
27312×
         WHERE j.runner_id = $1 AND j.finished_ms IS NOT NULL AND j.finished_ms >= r.state_ms
27412×
         ORDER BY j.finished_ms DESC, j.id DESC LIMIT $2",
27512×
    )
27612×
    .bind(id)
27712×
    .bind(n as i64)
27812×
    .fetch_all(pool)
27912×
    .await?;
28017×
    Ok((last.len() == n as usize && last.iter().all(|(s, _)| s == "error")).then(|| last[0].1.clone()))
28112×
}
282
283
/// Forget a runner: its credential stops working. Its jobs keep its name.
2843×
pub async fn remove(pool: &Pool, id: i64) -> sqlx::Result<()> {
2853×
    sqlx::query("DELETE FROM flow_runners WHERE id = $1").bind(id).execute(pool).await?;
2863×
    Ok(())
2873×
}
288
289
/// The key a runner signs receipts with: the one bound, or `key` (named
290
/// `name`) when none is yet.
2913×
pub async fn bind_key(pool: &Pool, id: i64, key: &str, name: &str) -> sqlx::Result<String> {
2923×
    sqlx::query("UPDATE flow_runners SET key = $1, key_name = $2 WHERE id = $3 AND key = ''")
2933×
        .bind(key)
2943×
        .bind(name)
2953×
        .bind(id)
2963×
        .execute(pool)
2973×
        .await?;
2983×
    sqlx::query_scalar("SELECT key FROM flow_runners WHERE id = $1").bind(id).fetch_one(pool).await
2993×
}
300
301
/// Keys that runners of this hub sign with.
3025×
pub async fn keys(pool: &Pool) -> sqlx::Result<Vec<String>> {
3035×
    sqlx::query_scalar("SELECT key FROM flow_runners WHERE key != ''").fetch_all(pool).await
3045×
}
305
306
/// A one-time registration token, valid for a day, for a runner of `scope`.
30710×
pub async fn add_registration(pool: &Pool, token_hash: &str, by: &str, scope: &Scope) -> sqlx::Result<()> {
30810×
    let now = now_ms();
30910×
    sqlx::query(
31010×
        "INSERT INTO flow_runner_registrations (token_hash, created_by, created_ms, expires_ms, scope_owner, scope_repo_id) VALUES ($1, $2, $3, $4, $5, $6)",
31110×
    )
31210×
    .bind(token_hash)
31310×
    .bind(by)
31410×
    .bind(now)
31510×
    .bind(now + 24 * 3_600_000)
31610×
    .bind(&scope.owner)
31710×
    .bind(scope.repo_id)
31810×
    .execute(pool)
31910×
    .await?;
32010×
    Ok(())
32110×
}
322
323
/// The runners that may take a repository's jobs: the site's, its owner's
324
/// and its own (oxygenhub#41).
325268×
pub async fn serving(pool: &Pool, owner: &str, repo_id: i64) -> sqlx::Result<Vec<Runner>> {
326268×
    sqlx::query_as(
327268×
        "SELECT * FROM flow_runners WHERE (scope_owner = '' AND scope_repo_id IS NULL) \
328268×
         OR (scope_owner = $1 AND scope_repo_id IS NULL) OR scope_repo_id = $2 ORDER BY name",
329268×
    )
330268×
    .bind(owner)
331268×
    .bind(repo_id)
332268×
    .fetch_all(pool)
333268×
    .await
334268×
}
335
336
/// The runners that serve an owner: the site's, and those scoped to the
337
/// owner or one of its repositories.
33820×
pub async fn serving_owner(pool: &Pool, owner: &str) -> sqlx::Result<Vec<Runner>> {
33920×
    sqlx::query_as("SELECT * FROM flow_runners WHERE (scope_owner = '' AND scope_repo_id IS NULL) OR scope_owner = $1 ORDER BY name")
34020×
        .bind(owner)
34120×
        .fetch_all(pool)
34220×
        .await
34320×
}
344
345
/// Change the repositories a runner serves.
3460×
pub async fn set_scope(pool: &Pool, id: i64, scope: &Scope) -> sqlx::Result<()> {
3470×
    sqlx::query("UPDATE flow_runners SET scope_owner = $1, scope_repo_id = $2 WHERE id = $3")
3480×
        .bind(&scope.owner)
3490×
        .bind(scope.repo_id)
3500×
        .bind(id)
3510×
        .execute(pool)
3520×
        .await?;
3530×
    Ok(())
3540×
}
355
356
/// Registration tokens not used yet and not expired: (created by, created, expires).
35712×
pub async fn pending_registrations(pool: &Pool) -> sqlx::Result<Vec<(String, i64, i64)>> {
35812×
    sqlx::query_as("SELECT created_by, created_ms, expires_ms FROM flow_runner_registrations WHERE used_ms IS NULL AND expires_ms > $1 ORDER BY created_ms DESC")
35912×
        .bind(now_ms())
36012×
        .fetch_all(pool)
36112×
        .await
36212×
}
363
364
/// Use registration token `token_hash` to register a runner: `None` when
365
/// the token is unknown, used or expired.
366
#[allow(clippy::too_many_arguments)]
36711×
pub async fn register(
36811×
    pool: &Pool,
36911×
    registration: &str,
37011×
    name: &str,
37111×
    token_hash: &str,
37211×
    key: &str,
37311×
    key_name: &str,
37411×
    by_default: &str,
37511×
) -> sqlx::Result<Option<Runner>> {
37611×
    let mut tx = super::begin_write(pool).await?;
37711×
    let now = now_ms();
37811×
    let found: Option<(String, String, Option<i64>)> = sqlx::query_as(
37911×
        "SELECT created_by, scope_owner, scope_repo_id FROM flow_runner_registrations WHERE token_hash = $1 AND used_ms IS NULL AND expires_ms > $2",
38011×
    )
38111×
    .bind(registration)
38211×
    .bind(now)
38311×
    .fetch_optional(&mut *tx)
38411×
    .await?;
38511×
    let Some((who, scope_owner, scope_repo_id)) = found else { return Ok(None) };
38610×
    let id: i64 = sqlx::query_scalar(
38710×
        "INSERT INTO flow_runners (name, token_hash, source, key, key_name, created_ms, created_by, scope_owner, scope_repo_id) VALUES ($1, $2, 'registered', $3, $4, $5, $6, $7, $8) RETURNING id",
388
    )
38910×
    .bind(name)
39010×
    .bind(token_hash)
39110×
    .bind(key)
39210×
    .bind(key_name)
39310×
    .bind(now)
39410×
    .bind(if who.is_empty() { by_default } else { &who })
39510×
    .bind(scope_owner)
39610×
    .bind(scope_repo_id)
39710×
    .fetch_one(&mut *tx)
39810×
    .await?;
39910×
    sqlx::query("UPDATE flow_runner_registrations SET used_ms = $1, runner_id = $2 WHERE token_hash = $3")
40010×
        .bind(now)
40110×
        .bind(id)
40210×
        .bind(registration)
40310×
        .execute(&mut *tx)
40410×
        .await?;
40510×
    tx.commit().await?;
40610×
    get(pool, id).await
40711×
}
408
409
/// A job a runner ran, for its history.
410
#[derive(Clone, Debug, FromRow)]
411
pub struct RunnerJob {
412
    pub owner: String,
413
    pub repo: String,
414
    pub run_number: i64,
415
    pub job: String,
416
    pub status: String,
417
    pub started_ms: Option<i64>,
418
    pub finished_ms: Option<i64>,
419
    pub receipt_attest: String,
420
}
421
422
/// Jobs runner `id` ran or is running, newest first.
4234×
pub async fn history(pool: &Pool, id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<RunnerJob>> {
4244×
    sqlx::query_as(
4254×
        "SELECT p.owner AS owner, p.name AS repo, r.number AS run_number, j.name AS job, j.status AS status, j.started_ms AS started_ms, \
4264×
         j.finished_ms AS finished_ms, j.receipt_attest AS receipt_attest \
4274×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
4284×
         WHERE j.runner_id = $1 AND ($2 IS NULL OR j.started_ms < $3) ORDER BY j.started_ms DESC LIMIT $4",
4294×
    )
4304×
    .bind(id)
4314×
    .bind(before)
4324×
    .bind(before)
4334×
    .bind(limit)
4344×
    .fetch_all(pool)
4354×
    .await
4364×
}
437
438
/// (jobs run, passed, busy milliseconds) of runner `id`.
4393×
pub async fn totals(pool: &Pool, id: i64) -> sqlx::Result<(i64, i64, i64)> {
4403×
    sqlx::query_as(
4413×
        "SELECT COUNT(*), COALESCE(SUM(CASE WHEN status = 'passed' THEN 1 ELSE 0 END), 0), CAST(COALESCE(SUM(finished_ms - started_ms), 0) AS BIGINT) \
4423×
         FROM flow_jobs WHERE runner_id = $1 AND finished_ms IS NOT NULL",
4433×
    )
4443×
    .bind(id)
4453×
    .fetch_one(pool)
4463×
    .await
4473×
}
448
449
/// Jobs running on each runner now, by runner id.
450240×
pub async fn running(pool: &Pool) -> sqlx::Result<Vec<(i64, i64)>> {
451240×
    sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
452240×
        .fetch_all(pool)
453240×
        .await
454240×
}
455
456155×
pub async fn set_job_runner(pool: &Pool, job_id: i64, runner_id: i64) -> sqlx::Result<()> {
457155×
    sqlx::query("UPDATE flow_jobs SET runner_id = $1 WHERE id = $2").bind(runner_id).bind(job_id).execute(pool).await?;
458155×
    Ok(())
459155×
}