OXYGENHUB

Coverage / crates/hub/src/db/flow.rs 96.9%

1066 of 1100 lines run, 179 of 366 functions · run #512 on main · run missed

1
//! OxygenFlow runs, jobs and logs (hub spec §13.2).
2
3
use super::{now_ms, Pool};
4
use sqlx::FromRow;
5
6
#[derive(Clone, Debug, FromRow)]
7
pub struct Run {
8
    pub id: i64,
9
    pub repo_id: i64,
10
    /// The run's number within its repository, from 1 (migration 0019).
11
    #[sqlx(default)]
12
    pub number: i64,
13
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
14
    /// `rerun:N:EVENT` (migration 0020).
15
    #[sqlx(default)]
16
    pub trigger: String,
17
    pub bookmark: String,
18
    pub state: String,
19
    pub heads: String,
20
    pub pipeline_hash: String,
21
    pub status: String,
22
    pub error: String,
23
    pub actor: String,
24
    pub created_ms: i64,
25
    pub finished_ms: Option<i64>,
26
    /// `urgent` when expedited (oxygenhub#244), else empty: the run follows
27
    /// its repository's, organisation's or the site's level.
28
    #[sqlx(default)]
29
    pub priority: String,
30
    /// Who expedited it and why.
31
    #[sqlx(default)]
32
    pub priority_note: String,
33
}
34
35
/// The priority levels, most urgent first (oxygenhub#244).
36
pub const PRIORITIES: [&str; 4] = ["urgent", "high", "normal", "low"];
37
38
/// SQL for the level a run's jobs get from where they are, as a rank
39
/// (0 urgent … 3 low): the run's own (expedited), else its repository's,
40
/// its organisation's, the site's (`settings.flow_priority`), else normal.
41
macro_rules! level_rank {
42
    () => {
43
        "CASE COALESCE(NULLIF(r.priority, ''), NULLIF(rep.flow_priority, ''), \
44
           NULLIF((SELECT o.flow_priority FROM organisations o WHERE o.name = rep.owner), ''), \
45
           NULLIF((SELECT s.value FROM settings s WHERE s.key = 'flow_priority'), ''), 'normal') \
46
         WHEN 'urgent' THEN 0 WHEN 'high' THEN 1 WHEN 'low' THEN 3 ELSE 2 END"
47
    };
48
}
49
50
/// SQL for a queued job's level as a rank (0 urgent … 3 low): the level
51
/// its run gets from where it is, lowered by the job's own priority from
52
/// its pipeline (`low`, `normal`), never raised by it; an expedited run is
53
/// urgent whatever its jobs say (oxygenhub#244). Needs `j` (the job), `r`
54
/// (its run) and `rep` (its repository) in the query.
55
pub const PRIORITY_RANK: &str = concat!(
56
    "CASE WHEN r.priority <> '' THEN ",
57
    level_rank!(),
58
    " WHEN j.priority = 'low' THEN 3 WHEN j.priority = 'normal' AND (",
59
    level_rank!(),
60
    ") < 2 THEN 2 ELSE ",
61
    level_rank!(),
62
    " END"
63
);
64
65
/// SQL for why a job stands where it does, beside [`PRIORITY_RANK`]: an
66
/// expedited run's note, else the pipeline's word for a job it lowered.
67
pub const PRIORITY_NOTE: &str =
68
    "CASE WHEN r.priority <> '' THEN r.priority_note WHEN j.priority <> '' THEN 'pipeline: ' || j.priority ELSE r.priority_note END";
69
70
/// How many runs of `owner`'s repositories are expedited and still live.
713×
pub async fn expedited_live(pool: &Pool, owner: &str) -> sqlx::Result<i64> {
723×
    sqlx::query_scalar(
733×
        "SELECT COUNT(*) FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id \
743×
         WHERE rep.owner = $1 AND r.priority = 'urgent' AND r.status IN ('queued', 'running')",
753×
    )
763×
    .bind(owner)
773×
    .fetch_one(pool)
783×
    .await
793×
}
80
81
/// Raise run `run_id` to urgent, saying who and why; a run already ended
82
/// is left alone. Whether it changed.
833×
pub async fn expedite(pool: &Pool, run_id: i64, note: &str) -> sqlx::Result<bool> {
843×
    let r = sqlx::query("UPDATE flow_runs SET priority = 'urgent', priority_note = $1 WHERE id = $2 AND status IN ('queued', 'running')")
853×
        .bind(note)
863×
        .bind(run_id)
873×
        .execute(pool)
883×
        .await?;
893×
    Ok(r.rows_affected() > 0)
903×
}
91
92
impl Run {
93
    /// How the run page says what started it.
9423×
    pub fn started_by(&self) -> String {
9523×
        match self.trigger.as_str() {
9623×
            "manual" => format!("started by {}", self.actor),
9721×
            "schedule" => "started on schedule".to_string(),
9821×
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
9921×
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
10020×
            _ => format!("pushed by {}", self.actor),
101
        }
10223×
    }
103
104
    /// The run a rerun repeats: `N` of `rerun:N` or `rerun:N:EVENT`.
10512×
    pub fn rerun_of(&self) -> Option<&str> {
10612×
        let rest = self.trigger.strip_prefix("rerun:")?;
1072×
        Some(rest.split(':').next().unwrap_or(rest))
10812×
    }
109
110
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
11111×
    pub fn trigger_label(&self) -> String {
11211×
        match self.rerun_of() {
1131×
            Some(n) => format!("rerun:{n}"),
11410×
            None => self.trigger.clone(),
115
        }
11611×
    }
117
118397×
    pub fn head_list(&self) -> Vec<&str> {
119529×
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
120397×
    }
121
122176×
    pub fn live(&self) -> bool {
123176×
        matches!(self.status.as_str(), "queued" | "running")
124176×
    }
125
}
126
127
#[derive(Clone, Debug, Default, FromRow)]
128
pub struct Job {
129
    pub id: i64,
130
    pub run_id: i64,
131
    pub name: String,
132
    pub depth: i64,
133
    pub depends: String,
134
    pub spec: String,
135
    pub sandbox: String,
136
    pub runtime: String,
137
    pub status: String,
138
    pub runner: String,
139
    pub token_hash: String,
140
    pub started_ms: Option<i64>,
141
    pub finished_ms: Option<i64>,
142
    pub exit_code: Option<i64>,
143
    pub error: String,
144
    pub receipt: String,
145
    pub receipt_hash: String,
146
    pub log_count: i64,
147
    /// Comma-separated ids of other repositories the job token may read.
148
    pub also_read: String,
149
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
150
    pub receipt_attest: String,
151
    /// Who signed it: the runner's identity name.
152
    pub receipt_signer: String,
153
    /// Why a signed receipt was not kept.
154
    pub receipt_note: String,
155
    /// Why a queued job no runner can take waits (spec §11.4), from the
156
    /// last placement pass; empty when it is only waiting its turn.
157
    pub waiting: String,
158
    /// What it took, as its runner reported (oxygenflow#41), in MiB.
159
    pub peak_disk_mib: Option<i64>,
160
    pub peak_memory_mib: Option<i64>,
161
    /// Where its time went, JSON of phase to milliseconds (oxygenflow#35).
162
    #[sqlx(default)]
163
    pub phases: String,
164
    /// The free disk it needs, learned from past runs of the same job.
165
    pub need_disk_mib: Option<i64>,
166
    /// Why it ran on its runner (oxygenflow#42).
167
    pub placed: String,
168
    /// `waiting` for a person, `approved`, or empty (oxygenflow#57).
169
    pub approval: String,
170
    /// Who approved or rejected it, and when.
171
    pub approved_by: String,
172
    pub approved_ms: Option<i64>,
173
    /// The agent token it was decided through, if one (oxygenhub#229).
174
    #[sqlx(default)]
175
    pub approved_via: String,
176
    /// The environment it deploys to, or empty (oxygenflow#59).
177
    pub environment: String,
178
    /// The approval attestation that released it, when sealed (#235).
179
    pub approval_seal: String,
180
    /// When it entered the queue (made, or run again), and when it became
181
    /// ready to run: set at its claim (migration 0080, oxygenhub#257).
182
    #[sqlx(default)]
183
    pub queued_ms: Option<i64>,
184
    #[sqlx(default)]
185
    pub ready_ms: Option<i64>,
186
    /// When a runner last handed it back, drained or with its lease lapsed
187
    /// (oxygenflow#76, migration 0094), and how many times: such a job is
188
    /// queued ahead of new work.
189
    #[sqlx(default)]
190
    pub handed_back_ms: Option<i64>,
191
    #[sqlx(default)]
192
    pub handbacks: i64,
193
}
194
195
impl Job {
196
    /// Where its time went, as its runner reported (oxygenflow#35): each
197
    /// phase it took, in the order it took them, with its milliseconds.
19854×
    pub fn phase_list(&self) -> Vec<(String, u64)> {
19954×
        let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(&self.phases).unwrap_or_default();
200216×
        ["image", "prepare", "run", "finish"].iter().filter_map(|p| m.get(*p).map(|ms| (p.to_string(), *ms))).collect()
20154×
    }
202
203
    /// The run whose pass this job reused (#265), if it did: in this
204
    /// repository, or in the one [`Job::reused_repo`] names (#296).
205142×
    pub fn reused_from(&self) -> Option<i64> {
206142×
        self.error.strip_prefix("reused from ")?.rsplit_once("run #")?.1.parse().ok()
207142×
    }
208
209
    /// The repository (`owner/name`) whose pass this job reused, when not
210
    /// its own: a fork reusing what upstream proved (#296).
211105×
    pub fn reused_repo(&self) -> Option<&str> {
212105×
        let rest = self.error.strip_prefix("reused from ")?;
21321×
        let (repo, n) = rest.rsplit_once(" run #")?;
2149×
        n.parse::<i64>().ok()?;
2159×
        Some(repo).filter(|r| !r.is_empty())
216105×
    }
217
218402×
    pub fn depends_on(&self) -> Vec<String> {
219402×
        serde_json::from_str(&self.depends).unwrap_or_default()
220402×
    }
221
222244×
    pub fn done(&self) -> bool {
223244×
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
224244×
    }
225
}
226
227
#[derive(Clone, Debug, FromRow)]
228
pub struct LogLine {
229
    pub seq: i64,
230
    pub t: i64,
231
    pub stream: String,
232
    pub text: String,
233
}
234
235
/// A job as the trigger creates it.
236
pub struct NewJob {
237
    pub name: String,
238
    pub depth: i64,
239
    pub depends: Vec<String>,
240
    pub spec: String,
241
    pub sandbox: String,
242
    pub runtime: String,
243
    /// The free disk it needs, from [`learned_disk_need`].
244
    pub need_disk_mib: Option<i64>,
245
    /// A pass on the same state to reuse instead of running it (#265): the
246
    /// job is created passed, with that pass's receipt.
247
    pub reused: Option<Reused>,
248
}
249
250
/// A job's earlier pass on the same state, spec and sandbox (#265).
251
#[derive(Clone, Debug)]
252
pub struct Reused {
253
    /// The repository it passed in, `owner/name`, when not this one (#296).
254
    pub repo: Option<String>,
255
    /// The run it passed in.
256
    pub run_number: i64,
257
    pub receipt: String,
258
    pub receipt_hash: String,
259
    pub receipt_attest: String,
260
    pub receipt_signer: String,
261
    pub receipt_note: String,
262
}
263
264
impl Reused {
265
    /// What the reused job says, and how [`Job::reused_from`] reads it back.
26612×
    pub fn note(&self) -> String {
26712×
        match &self.repo {
2683×
            Some(r) => format!("reused from {r} run #{}", self.run_number),
2699×
            None => format!("reused from run #{}", self.run_number),
270
        }
27112×
    }
272
}
273
274
/// The newest pass of job `name` with exactly this spec and sandbox on
275
/// `state` in this repository (#265).
276303×
pub async fn passed_on_state(
277303×
    pool: &Pool,
278303×
    repo_id: i64,
279303×
    state: &str,
280303×
    name: &str,
281303×
    spec: &str,
282303×
    sandbox: &str,
283303×
) -> sqlx::Result<Option<Reused>> {
284303×
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
285303×
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
286303×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
287303×
         WHERE r.repo_id = $1 AND r.state = $2 AND j.name = $3 AND j.spec = $4 AND j.sandbox = $5 AND j.status = 'passed' \
288303×
         ORDER BY j.id DESC LIMIT 1",
289303×
    )
290303×
    .bind(repo_id)
291303×
    .bind(state)
292303×
    .bind(name)
293303×
    .bind(spec)
294303×
    .bind(sandbox)
295303×
    .fetch_optional(pool)
296303×
    .await?;
297303×
    Ok(row.map(|(run_number, receipt, receipt_hash, receipt_attest, receipt_signer, receipt_note)| Reused {
29812×
        repo: None,
29912×
        run_number,
30012×
        receipt,
30112×
        receipt_hash,
30212×
        receipt_attest,
30312×
        receipt_signer,
30412×
        receipt_note,
30512×
    }))
306303×
}
307
308
/// How far up a fork's line [`passed_upstream`] looks.
309
const UPSTREAM_DEPTH: usize = 5;
310
311
/// A pass of job `name` with this spec and sandbox on `state` in a
312
/// repository `repo` was forked from, nearest first (#296): the same state
313
/// is the same changes, so what upstream proved holds for the fork. Only
314
/// from an upstream that is public or has the fork's owner, so a private
315
/// repository's receipts never show in another owner's fork.
3166×
pub async fn passed_upstream(
3176×
    pool: &Pool,
3186×
    repo: &super::repos::RepoRow,
3196×
    state: &str,
3206×
    name: &str,
3216×
    spec: &str,
3226×
    sandbox: &str,
3236×
) -> sqlx::Result<Option<Reused>> {
3246×
    let mut parent = repo.forked_from;
3256×
    for _ in 0..UPSTREAM_DEPTH {
3269×
        let Some(id) = parent else { break };
3276×
        let Some(up) = super::repos::get_by_id(pool, id).await? else { break };
3286×
        parent = up.forked_from;
3296×
        if !(up.visibility == "public" || up.owner == repo.owner) {
3303×
            continue;
3313×
        }
3323×
        if let Some(mut r) = passed_on_state(pool, up.id, state, name, spec, sandbox).await? {
3333×
            r.repo = Some(format!("{}/{}", up.owner, up.name));
3343×
            return Ok(Some(r));
3350×
        }
336
    }
3373×
    Ok(None)
3386×
}
339
340
/// Runs of a job whose peaks set its next need.
341
const NEED_FROM_RUNS: i64 = 5;
342
343
/// The free disk a new run of job `name` in repository `repo_id` needs
344
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
345
/// for a job that has not run here yet.
346369×
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
347369×
    let peak: Option<i64> = sqlx::query_scalar(
348369×
        "SELECT MAX(peak_disk_mib) FROM (SELECT j.peak_disk_mib FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
349369×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.peak_disk_mib IS NOT NULL ORDER BY j.id DESC LIMIT $3) recent",
350369×
    )
351369×
    .bind(repo_id)
352369×
    .bind(name)
353369×
    .bind(NEED_FROM_RUNS)
354369×
    .fetch_one(pool)
355369×
    .await?;
356369×
    Ok(peak.map(|p| p + p / 4 + 64))
357369×
}
358
359
/// Record why job `job_id` ran where it did.
360156×
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
361156×
    sqlx::query("UPDATE flow_jobs SET placed = $1 WHERE id = $2").bind(placed).bind(job_id).execute(pool).await?;
362156×
    Ok(())
363156×
}
364
365
/// Keep what a job took, as its runner reported.
36695×
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
36795×
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = $1, peak_memory_mib = $2 WHERE id = $3")
36895×
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
36995×
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
37095×
        .bind(job_id)
37195×
        .execute(pool)
37295×
        .await?;
37395×
    Ok(())
37495×
}
375
376
/// Where a finished job's time went, as its runner reported (oxygenflow#35).
37795×
pub async fn set_phases(pool: &Pool, job_id: i64, phases: &std::collections::BTreeMap<String, u64>) -> sqlx::Result<()> {
37895×
    let json = if phases.is_empty() { String::new() } else { serde_json::to_string(phases).unwrap_or_default() };
37995×
    sqlx::query("UPDATE flow_jobs SET phases = $1 WHERE id = $2").bind(json).bind(job_id).execute(pool).await?;
38095×
    Ok(())
38195×
}
382
383
pub struct NewRun<'a> {
384
    pub repo_id: i64,
385
    pub bookmark: &'a str,
386
    pub state: &'a str,
387
    pub heads: &'a str,
388
    pub pipeline_hash: &'a str,
389
    pub actor: &'a str,
390
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
391
    /// `rerun:N:EVENT`.
392
    pub trigger: &'a str,
393
    /// Problems when the pipeline is invalid: the run is recorded in error.
394
    pub error: Option<&'a str>,
395
}
396
397
/// A push that asked for no run (#284): recorded, finished, as skipped,
398
/// with `why` (which change asked, and who pushed it) as its note.
3991×
pub async fn create_skipped_run(pool: &Pool, r: NewRun<'_>, why: &str) -> sqlx::Result<i64> {
4001×
    let mut tx = super::begin_write(pool).await?;
4011×
    let now = now_ms();
4021×
    let id: i64 = sqlx::query_scalar(
4031×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
4041×
         VALUES ($1, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = $2), $3, $4, $5, $6, 'skipped', $7, $8, $9, $10, $11) RETURNING id",
4051×
    )
4061×
    .bind(r.repo_id)
4071×
    .bind(r.repo_id)
4081×
    .bind(r.bookmark)
4091×
    .bind(r.state)
4101×
    .bind(r.heads)
4111×
    .bind(r.pipeline_hash)
4121×
    .bind(why)
4131×
    .bind(r.actor)
4141×
    .bind(r.trigger)
4151×
    .bind(now)
4161×
    .bind(now)
4171×
    .fetch_one(&mut *tx)
4181×
    .await?;
4191×
    tx.commit().await?;
4201×
    Ok(id)
4211×
}
422
423143×
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
424143×
    let mut tx = super::begin_write(pool).await?;
425143×
    let now = now_ms();
426143×
    let status = if r.error.is_some() { "error" } else { "queued" };
427143×
    let id: i64 = sqlx::query_scalar(
428143×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
429143×
         VALUES ($1, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = $2), $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id",
430
    )
431143×
    .bind(r.repo_id)
432143×
    .bind(r.repo_id)
433143×
    .bind(r.bookmark)
434143×
    .bind(r.state)
435143×
    .bind(r.heads)
436143×
    .bind(r.pipeline_hash)
437143×
    .bind(status)
438143×
    .bind(r.error.unwrap_or(""))
439143×
    .bind(r.actor)
440143×
    .bind(r.trigger)
441143×
    .bind(now)
442143×
    .bind(r.error.map(|_| now))
443143×
    .fetch_one(&mut *tx)
444143×
    .await?;
445373×
    for j in jobs {
446373×
        let job_id: i64 = sqlx::query_scalar(
447373×
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
448373×
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
449
        )
450373×
        .bind(id)
451373×
        .bind(&j.name)
452373×
        .bind(j.depth)
453373×
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
454373×
        .bind(&j.spec)
455373×
        .bind(&j.sandbox)
456373×
        .bind(&j.runtime)
457373×
        .bind(j.need_disk_mib)
458373×
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
459373×
        .bind(environment_of(&j.spec))
460373×
        .bind(priority_of(&j.spec))
461373×
        .bind(now)
462373×
        .fetch_one(&mut *tx)
463373×
        .await?;
464
        // A pass reused (#265): done before any runner can claim it.
465373×
        if let Some(r) = &j.reused {
46612×
            sqlx::query(
46712×
                "UPDATE flow_jobs SET status = 'passed', exit_code = 0, error = $1, receipt = $2, receipt_hash = $3, receipt_attest = $4, \
46812×
                 receipt_signer = $5, receipt_note = $6, started_ms = $7, finished_ms = $7 WHERE id = $8",
46912×
            )
47012×
            .bind(r.note())
47112×
            .bind(&r.receipt)
47212×
            .bind(&r.receipt_hash)
47312×
            .bind(&r.receipt_attest)
47412×
            .bind(&r.receipt_signer)
47512×
            .bind(&r.receipt_note)
47612×
            .bind(now)
47712×
            .bind(job_id)
47812×
            .execute(&mut *tx)
47912×
            .await?;
480361×
        }
481
    }
482
    // Every job reused: the run has passed already.
483149×
    if !jobs.is_empty() && jobs.iter().all(|j| j.reused.is_some()) {
4843×
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
485140×
    }
486143×
    tx.commit().await?;
487143×
    Ok(id)
488143×
}
489
490
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
491373×
fn environment_of(spec: &str) -> String {
492373×
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
493373×
}
494
495
/// A compiled job's own priority (`low`, `normal`), or empty; anything
496
/// else is not one a pipeline may give (oxygenhub#244).
497373×
fn priority_of(spec: &str) -> String {
498373×
    serde_json::from_str::<serde_json::Value>(spec)
499373×
        .ok()
500373×
        .and_then(|v| v["priority"].as_str().map(String::from))
501373×
        .filter(|p| p == "low" || p == "normal")
502373×
        .unwrap_or_default()
503373×
}
504
505
/// Whether a compiled job asks for approval (oxygenflow#57).
506373×
fn needs_approval(spec: &str) -> bool {
507373×
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
508373×
}
509
510
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
511202×
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
512202×
    let mut out: Vec<String> = [spec, sandbox]
513202×
        .iter()
514404×
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
515404×
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
516202×
        .filter_map(|l| l.as_str().map(String::from))
517202×
        .collect();
518202×
    out.sort();
519202×
    out.dedup();
520202×
    out
521202×
}
522
523
impl Job {
524
    /// The runner labels this job needs.
525191×
    pub fn needs(&self) -> Vec<String> {
526191×
        labels_in(&self.spec, &self.sandbox)
527191×
    }
528
529
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
53032×
    pub fn arch(&self) -> Option<String> {
53132×
        arch_in(&self.sandbox)
53232×
    }
533
}
534
535
/// The architecture a sandbox's JSON asks for, if any.
53642×
fn arch_in(sandbox: &str) -> Option<String> {
53742×
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
53842×
}
539
540
/// A job waiting for or held by a runner, with where it comes from.
541
#[derive(Clone, Debug, FromRow)]
542
pub struct QueueEntry {
543
    pub job_id: i64,
544
    pub run_id: i64,
545
    pub repo_id: i64,
546
    pub owner: String,
547
    pub name: String,
548
    pub visibility: String,
549
    pub run_number: i64,
550
    pub job: String,
551
    pub status: String,
552
    /// The runner holding it, when running.
553
    pub runner: String,
554
    pub spec: String,
555
    pub sandbox: String,
556
    /// When it started running.
557
    pub started_ms: Option<i64>,
558
    /// Its level (0 urgent … 3 low, oxygenhub#244) and, when expedited, who
559
    /// did it and why.
560
    pub priority_rank: i64,
561
    pub priority_note: String,
562
}
563
564
impl QueueEntry {
56522×
    pub fn priority(&self) -> &'static str {
56622×
        PRIORITIES.get(self.priority_rank as usize).copied().unwrap_or("normal")
56722×
    }
568
}
569
570
impl QueueEntry {
571
    /// The runner labels the job needs.
57211×
    pub fn needs(&self) -> Vec<String> {
57311×
        labels_in(&self.spec, &self.sandbox)
57411×
    }
575
576
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
57710×
    pub fn arch(&self) -> Option<String> {
57810×
        arch_in(&self.sandbox)
57910×
    }
580
}
581
582
/// Every job of a live run that is running or queued: running ones first,
583
/// then queued ones in the order runners claim them (hub spec §13.2).
584266×
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
585266×
    sqlx::query_as(&format!(
586266×
        "SELECT j.id AS job_id, j.run_id, r.repo_id, rep.owner, rep.name, rep.visibility, r.number AS run_number, j.name AS job, j.status, j.runner, j.spec, j.sandbox, j.started_ms, \
587266×
           CAST({PRIORITY_RANK} AS BIGINT) AS priority_rank, {PRIORITY_NOTE} AS priority_note \
588266×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
589266×
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
590266×
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, \
591266×
           CASE j.status WHEN 'running' THEN 0 ELSE {PRIORITY_RANK} END, \
592266×
           CASE j.status WHEN 'running' THEN 0 ELSE ROW_NUMBER() OVER (PARTITION BY r.repo_id, j.status ORDER BY j.run_id, j.depth, j.id) \
593266×
           + (SELECT COUNT(*) FROM flow_jobs x JOIN flow_runs xr ON xr.id = x.run_id WHERE x.status = 'running' AND xr.repo_id = r.repo_id) END, \
594266×
           j.run_id, j.depth, j.id"
595266×
    ))
596266×
    .fetch_all(pool)
597266×
    .await
598266×
}
599
600
/// A repository's runs, newest first, numbered below `before`.
6012×
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
6022×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3")
6032×
        .bind(repo_id)
6042×
        .bind(before.unwrap_or(i64::MAX))
6052×
        .bind(limit)
6062×
        .fetch_all(pool)
6072×
        .await
6082×
}
609
610
/// The latest run on this bookmark of this repository, for what a push
611
/// changed since (a job's scope).
612
/// The run a push to `bookmark` is scoped against: the newest that was not
613
/// cancelled, nor a push run still going (a new push supersedes it), so
614
/// that what a cancelled run would have checked is checked by the next.
615151×
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
616151×
    sqlx::query_as(
617151×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
618151×
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
619151×
    )
620151×
    .bind(repo_id)
621151×
    .bind(bookmark)
622151×
    .fetch_optional(pool)
623151×
    .await
624151×
}
625
626295×
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
627295×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3")
628295×
        .bind(repo_id)
629295×
        .bind(before.unwrap_or(i64::MAX))
630295×
        .bind(limit)
631295×
        .fetch_all(pool)
632295×
        .await
633295×
}
634
635
/// A repository's run by its number there.
63692×
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
63792×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
63892×
}
639
640978×
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
641978×
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
642978×
}
643
644267×
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
645267×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
646267×
}
647
648481×
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
649481×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
650481×
}
651
652
/// The running job a job token belongs to, while it may still be used.
65331×
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
65431×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = $1 AND status = 'running' AND started_ms >= $2")
65531×
        .bind(token_hash)
65631×
        .bind(now_ms() - max_age_ms)
65731×
        .fetch_optional(pool)
65831×
        .await
65931×
}
660
661
/// Take the oldest queued job whose dependencies all passed and whose tier
662
/// the runner offers, and mark it running for `runner` with a token.
663
/// Let a job's token also read these repositories (its pinned subrepos).
66428×
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
66529×
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
66628×
    sqlx::query("UPDATE flow_jobs SET also_read = $1 WHERE id = $2").bind(list.join(",")).bind(job_id).execute(pool).await?;
66728×
    Ok(())
66828×
}
669
670
impl Job {
67110×
    pub fn also_read_ids(&self) -> Vec<i64> {
67215×
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
67310×
    }
674
}
675
676
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
677
/// limit, and the rootfs images it holds, `None` when it does not say.
678
#[derive(Clone, Debug, Default)]
679
pub struct Room {
680
    pub memory_mib: Option<u32>,
681
    pub cpus: Option<u32>,
682
    pub images: Option<std::collections::HashSet<String>>,
683
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
684
    pub arch: String,
685
    /// Each image's architecture as runners have reported it (`flow_images`).
686
    pub image_archs: std::collections::HashMap<String, String>,
687
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
688
    pub declined: std::collections::HashSet<i64>,
689
    /// Images the hub holds that this runner would fetch when it lacks
690
    /// them (oxygenflow#39); empty for a runner that does not fetch.
691
    pub fetchable: std::collections::HashSet<String>,
692
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
693
    /// when it does not say.
694
    pub free_disk_mib: Option<u64>,
695
}
696
697
impl Room {
698
    /// Whether a job needing `need` MiB of disk fits in its free disk.
699168×
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
700168×
        match (need, self.free_disk_mib) {
7012×
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
702166×
            _ => true,
703
        }
704168×
    }
705
}
706
707
impl Room {
708
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
709
    /// and its rootfs image among the runner's (oxygenhub#73).
710177×
    pub fn fits(&self, sandbox_json: &str) -> bool {
711177×
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
712177×
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
713177×
        let rootfs = v["rootfs"].as_str().unwrap_or("");
714
        // The architecture: the sandbox's own ask, else the image's as read
715
        // or learned from its passes (oxygenhub#173); one nobody has read
716
        // or run yet matches (OxygenFlow spec §11.3).
717177×
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
718177×
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
719177×
        arch_ok
720172×
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
721172×
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
722172×
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
723177×
    }
724
}
725
726
/// Remember which architecture each image is for, as a runner reports it.
72712×
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
72812×
    for (hash, arch) in archs.iter().take(500) {
72910×
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
7300×
            continue;
73110×
        }
73210×
        sqlx::query("INSERT INTO flow_images (hash, arch, seen_ms) VALUES ($1, $2, $3) ON CONFLICT (hash) DO UPDATE SET arch = excluded.arch, seen_ms = excluded.seen_ms")
73310×
        .bind(hash.to_ascii_lowercase())
73410×
        .bind(arch)
73510×
        .bind(now_ms())
73610×
        .execute(pool)
73710×
        .await?;
738
    }
73912×
    Ok(())
74012×
}
741
742
/// Give every image nobody has read the architecture of the runners its
743
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
744
/// each pass. Never overrides a known architecture.
745198×
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
746198×
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
747198×
    let r = sqlx::query(&format!(
748198×
        "INSERT INTO flow_images (hash, arch, seen_ms)
749198×
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
750198×
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
751198×
         GROUP BY lower({rootfs})
752198×
         ON CONFLICT (hash) DO NOTHING"
753198×
    ))
754198×
    .bind(now_ms())
755198×
    .execute(pool)
756198×
    .await?;
757197×
    Ok(r.rows_affected())
758197×
}
759
760
/// Every image's architecture the hub knows.
761456×
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
762456×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
763456×
    Ok(rows.into_iter().collect())
764456×
}
765
7660×
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
7670×
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
7680×
}
769
770
/// The first queued job a runner with these tiers, this room and this
771
/// scope may take, now running under `runner`. Repositories take turns
772
/// (fair share, oxygenhub#244): a job's turn is its place in its own
773
/// repository's queue plus that repository's running jobs, lowest first,
774
/// oldest first among equals, so one repository's burst can't hold up the
775
/// rest. A scoped runner never sees
776
/// another scope's jobs (oxygenhub#41).
7770×
pub async fn claim_within(
7780×
    pool: &Pool,
7790×
    runtimes: &[String],
7800×
    runner: &str,
7810×
    token_hash: &str,
7820×
    room: Room,
7830×
    scope: &super::runners::Scope,
7840×
    labels: &[String],
7850×
) -> sqlx::Result<Option<Job>> {
7860×
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
7870×
}
788
789
/// [`claim_within`], passing over a job `elsewhere` says a better runner
790
/// should take (oxygenflow#42).
791
#[allow(clippy::too_many_arguments)]
792223×
pub async fn claim_ranked(
793223×
    pool: &Pool,
794223×
    runtimes: &[String],
795223×
    runner: &str,
796223×
    token_hash: &str,
797223×
    room: Room,
798223×
    scope: &super::runners::Scope,
799223×
    labels: &[String],
800223×
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
801223×
) -> sqlx::Result<Option<Job>> {
802223×
    let mut tx = super::begin_write(pool).await?;
803223×
    let queued: Vec<Job> = sqlx::query_as(&format!(
804223×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
805223×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
806223×
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
807223×
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
808223×
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
809223×
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
810223×
           + (SELECT COUNT(*) FROM flow_jobs x JOIN flow_runs xr ON xr.id = x.run_id WHERE x.status = 'running' AND xr.repo_id = r.repo_id), \
811223×
           j.run_id, j.depth, j.id LIMIT 200"
812223×
    ))
813223×
    .bind(&scope.owner)
814223×
    .bind(&scope.owner)
815223×
    .bind(scope.repo_id)
816223×
    .bind(scope.repo_id)
817223×
    // A repository on its own runners only (#225): the site's runners skip it.
818223×
    .bind(&scope.owner)
819223×
    .bind(scope.repo_id)
820223×
    .fetch_all(&mut *tx)
821223×
    .await?;
822223×
    for j in queued {
823183×
        if !runtimes.iter().any(|r| r == &j.runtime)
824177×
            || !room.fits(&j.sandbox)
825168×
            || !room.disk_fits(j.need_disk_mib)
826167×
            || room.declined.contains(&j.id)
827
        {
82817×
            continue;
829166×
        }
830
        // Every label the job and its sandbox ask for (`runs-on`).
831166×
        if !j.needs().iter().all(|l| labels.contains(l)) {
8322×
            continue;
833164×
        }
834164×
        let deps = j.depends_on();
835
        // When it became ready: queued, its dependencies passed, approved.
836164×
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
837164×
        if !deps.is_empty() {
83835×
            let mut passed = 0i64;
83935×
            for d in &deps {
84035×
                let st: Option<(String, Option<i64>)> =
84135×
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
84235×
                        .bind(j.run_id)
84335×
                        .bind(d)
84435×
                        .fetch_optional(&mut *tx)
84535×
                        .await?;
84635×
                if let Some((status, finished)) = st {
84735×
                    if status == "passed" {
84830×
                        passed += 1;
84930×
                        ready = ready.max(finished.unwrap_or(0));
85030×
                    }
8510×
                }
852
            }
85335×
            if passed != deps.len() as i64 {
8545×
                continue;
85530×
            }
856129×
        }
857159×
        if elsewhere(&j) {
8583×
            continue;
859156×
        }
860156×
        let now = now_ms();
861156×
        let done = sqlx::query(
862156×
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
863156×
             WHERE id = $4 AND status = 'queued'",
864
        )
865156×
        .bind(runner)
866156×
        .bind(token_hash)
867156×
        .bind(now)
868156×
        .bind(j.id)
869156×
        .bind(if ready > 0 { ready.min(now) } else { now })
870156×
        .execute(&mut *tx)
871156×
        .await?;
872156×
        if done.rows_affected() == 1 {
873156×
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
874156×
                .bind(j.run_id)
875156×
                .execute(&mut *tx)
876156×
                .await?;
877156×
            tx.commit().await?;
878156×
            return job(pool, j.id).await;
8790×
        }
880
    }
88167×
    tx.commit().await?;
88267×
    Ok(None)
883223×
}
884
885
/// How long a decline keeps a job from its runner when the runner's
886
/// profile stays the same: a reason such as memory in use passes.
887
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
888
889
/// The jobs runner `runner_id` declined with this profile, recently.
890223×
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
891223×
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
892223×
        .bind(runner_id)
893223×
        .bind(profile)
894223×
        .bind(now_ms() - DECLINE_HOLDS_MS)
895223×
        .fetch_all(pool)
896223×
        .await?;
897223×
    Ok(rows.into_iter().map(|(j,)| j).collect())
898223×
}
899
900
/// A decline: one runner's reason for handing a job back.
901
#[derive(Clone, Debug, sqlx::FromRow)]
902
pub struct DeclineRow {
903
    pub job_id: i64,
904
    pub runner_id: i64,
905
    pub runner: String,
906
    pub reason: String,
907
    pub ms: i64,
908
}
909
910
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
911
/// is kept (one per job and runner, the latest), and the job is queued
912
/// again. Returns every decline the job has had, or `None` when the job
913
/// was not running on that runner.
9144×
pub async fn decline(
9154×
    pool: &Pool,
9164×
    job_id: i64,
9174×
    runner_id: i64,
9184×
    runner: &str,
9194×
    profile: &str,
9204×
    reason: &str,
9214×
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
9224×
    let mut tx = super::begin_write(pool).await?;
9234×
    let back = sqlx::query(
9244×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
9254×
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
9264×
    )
9274×
    .bind(job_id)
9284×
    .bind(runner_id)
9294×
    .execute(&mut *tx)
9304×
    .await?;
9314×
    if back.rows_affected() != 1 {
9321×
        tx.rollback().await?;
9331×
        return Ok(None);
9343×
    }
9353×
    sqlx::query(
9363×
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
9373×
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
9383×
    )
9393×
    .bind(job_id)
9403×
    .bind(runner_id)
9413×
    .bind(runner)
9423×
    .bind(profile)
9433×
    .bind(reason)
9443×
    .bind(now_ms())
9453×
    .execute(&mut *tx)
9463×
    .await?;
9473×
    let all: Vec<DeclineRow> =
9483×
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
9493×
            .bind(job_id)
9503×
            .fetch_all(&mut *tx)
9513×
            .await?;
9523×
    tx.commit().await?;
9533×
    Ok(Some(all))
9544×
}
955
956
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
957
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
958
/// its runner's lease lapsed. Its log is kept and its next attempt's
959
/// follows on. Returns how many times it has now been handed back, or
960
/// `None` when it was not running there.
9613×
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
9623×
    let mut tx = super::begin_write(pool).await?;
9633×
    let now = now_ms();
9643×
    let back = sqlx::query(
9653×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
9663×
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
9673×
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
9683×
    )
9693×
    .bind(now)
9703×
    .bind(now)
9713×
    .bind(job_id)
9723×
    .bind(runner_id)
9733×
    .bind(runner_id)
9743×
    .execute(&mut *tx)
9753×
    .await?;
9763×
    if back.rows_affected() != 1 {
9771×
        tx.rollback().await?;
9781×
        return Ok(None);
9792×
    }
9802×
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
9812×
    tx.commit().await?;
9822×
    Ok(Some(n))
9833×
}
984
985
/// How long job `name` of repository `repo_id` is expected to take: the
986
/// median of its last five passing runs (claimed to finished), passes
987
/// reused from another run left out (oxygenflow#76). `None` before it has
988
/// passed: a runner leaving then hands it back rather than guess.
989156×
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
990156×
    let mut times: Vec<i64> = sqlx::query_scalar(
991156×
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
992156×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
993156×
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
994156×
    )
995156×
    .bind(repo_id)
996156×
    .bind(name)
997156×
    .fetch_all(pool)
998156×
    .await?;
999156×
    times.sort_unstable();
1000156×
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
1001156×
}
1002
1003
/// Jobs running on a runner the hub has not heard from since `before`
1004
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
10051×
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
10061×
    let rows: Vec<(i64, String)> = sqlx::query_as(
10071×
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
10081×
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
10091×
    )
10101×
    .bind(before)
10111×
    .fetch_all(pool)
10121×
    .await?;
10131×
    let mut out = Vec::new();
10141×
    for (id, runner) in rows {
10151×
        if let Some(j) = job(pool, id).await? {
10161×
            out.push((j, runner));
10171×
        }
1018
    }
10191×
    Ok(out)
10201×
}
1021
1022
/// The declines of job `job_id`, oldest first.
102313×
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
102413×
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
102513×
        .bind(job_id)
102613×
        .fetch_all(pool)
102713×
        .await
102813×
}
1029
1030
/// A runner's latest declines, newest first, with where the job is.
1031
#[derive(Clone, Debug, sqlx::FromRow)]
1032
pub struct RunnerDecline {
1033
    pub job_id: i64,
1034
    pub job: String,
1035
    pub run_number: i64,
1036
    pub owner: String,
1037
    pub name: String,
1038
    pub reason: String,
1039
    pub ms: i64,
1040
}
1041
10424×
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
10434×
    sqlx::query_as(
10444×
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
10454×
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
10464×
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
10474×
    )
10484×
    .bind(runner_id)
10494×
    .bind(limit)
10504×
    .fetch_all(pool)
10514×
    .await
10524×
}
1053
1054
/// Queued jobs whose dependencies have passed, in their live runs, with
1055
/// their repositories (owner, id): the ones a runner could take now.
1056
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
1057
/// (#259: how many ready jobs come first).
10587×
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
10597×
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
10607×
        "SELECT j.id, CAST({PRIORITY_RANK} AS BIGINT) FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
10617×
         WHERE j.status = 'queued'"
10627×
    ))
10637×
    .fetch_all(pool)
10647×
    .await?;
10657×
    Ok(rows.into_iter().collect())
10667×
}
1067
1068
/// How many jobs each runner is running now, by runner id (#259).
10697×
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
10707×
    let rows: Vec<(i64, i64)> =
10717×
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
10727×
            .fetch_all(pool)
10737×
            .await?;
10747×
    Ok(rows.into_iter().collect())
10757×
}
1076
10779×
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
10789×
    let queued: Vec<Job> = sqlx::query_as(
10799×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
10809×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') ORDER BY j.run_id, j.depth, j.id LIMIT 500",
10819×
    )
10829×
    .fetch_all(pool)
10839×
    .await?;
10849×
    let mut out = Vec::new();
108519×
    for j in queued {
108619×
        let mut ready = true;
108719×
        for d in j.depends_on() {
10887×
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
10897×
                .bind(j.run_id)
10907×
                .bind(&d)
10917×
                .fetch_optional(pool)
10927×
                .await?;
10937×
            if st.as_deref() != Some("passed") {
10947×
                ready = false;
10957×
                break;
10960×
            }
1097
        }
109819×
        if !ready {
10997×
            continue;
110012×
        }
110112×
        let repo: Option<(String, i64)> =
110212×
            sqlx::query_as("SELECT rep.owner, rep.id FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id WHERE r.id = $1")
110312×
                .bind(j.run_id)
110412×
                .fetch_optional(pool)
110512×
                .await?;
110612×
        if let Some((owner, id)) = repo {
110712×
            out.push((j, owner, id));
110812×
        }
1109
    }
11109×
    Ok(out)
11119×
}
1112
111314×
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
111414×
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
111514×
        .bind(waiting)
111614×
        .bind(job_id)
111714×
        .bind(waiting)
111814×
        .execute(pool)
111914×
        .await?;
112014×
    Ok(())
112114×
}
1122
1123
/// Append records; returns how many were kept (the rest exceed the cap).
112444×
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
112544×
    let mut tx = super::begin_write(pool).await?;
112644×
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
112744×
    let room = (cap - count).max(0) as usize;
112844×
    let keep = &records[..records.len().min(room)];
1129361×
    for (i, r) in keep.iter().enumerate() {
1130361×
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1131361×
            .bind(job_id)
1132361×
            .bind(count + i as i64 + 1)
1133361×
            .bind(r.t as i64)
1134361×
            .bind(&r.stream)
1135361×
            .bind(&r.text)
1136361×
            .execute(&mut *tx)
1137361×
            .await?;
1138
    }
113944×
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
114044×
        .bind(keep.len() as i64)
114144×
        .bind(job_id)
114244×
        .execute(&mut *tx)
114344×
        .await?;
114444×
    tx.commit().await?;
114544×
    Ok(keep.len())
114644×
}
1147
114873×
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
114973×
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
115073×
        .bind(job_id)
115173×
        .bind(after)
115273×
        .bind(limit)
115373×
        .fetch_all(pool)
115473×
        .await
115573×
}
1156
1157
/// Jobs running since before `ms` (the oldest first).
1158
/// Jobs still running at `now` past their own time limit (`default_s` for
1159
/// one claimed without) plus `grace_ms`.
11603×
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
11613×
    sqlx::query_as(
11623×
        "SELECT * FROM flow_jobs WHERE status = 'running' \
11633×
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
11643×
    )
11653×
    .bind(default_s as i64)
11663×
    .bind(grace_ms)
11673×
    .bind(now)
11683×
    .fetch_all(pool)
11693×
    .await
11703×
}
1171
1172
/// Record the limit a claimed job runs under.
1173156×
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1174156×
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1175156×
    Ok(())
1176156×
}
1177
11780×
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
11790×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
11800×
        .bind(ms)
11810×
        .fetch_all(pool)
11820×
        .await
11830×
}
1184
1185
/// The jobs running on the runner with this id.
11862×
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
11872×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
11882×
}
1189
1190
pub struct Outcome<'a> {
1191
    pub status: &'a str,
1192
    pub exit_code: Option<i64>,
1193
    pub error: &'a str,
1194
    pub receipt: &'a str,
1195
    pub receipt_hash: &'a str,
1196
}
1197
1198
/// Record a job's end, skip the jobs that can no longer run, and settle the
1199
/// run. Returns the jobs whose status changed (for their checks).
1200104×
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1201104×
    let mut tx = super::begin_write(pool).await?;
1202104×
    let now = now_ms();
1203104×
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1204104×
    sqlx::query("UPDATE flow_jobs SET status = $1, exit_code = $2, error = $3, receipt = $4, receipt_hash = $5, finished_ms = $6, token_hash = '' WHERE id = $7")
1205104×
        .bind(o.status)
1206104×
        .bind(o.exit_code)
1207104×
        .bind(o.error)
1208104×
        .bind(o.receipt)
1209104×
        .bind(o.receipt_hash)
1210104×
        .bind(now)
1211104×
        .bind(job_id)
1212104×
        .execute(&mut *tx)
1213104×
        .await?;
1214
    // A pass teaches what its image is for, when nobody has read it
1215
    // (oxygenhub#173): the architecture of the runner it passed on.
1216104×
    if o.status == "passed" {
121785×
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
121885×
            .ok()
121985×
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
122085×
            .unwrap_or_default();
122185×
        if rootfs.len() == 64 {
122285×
            sqlx::query(
122385×
                "INSERT INTO flow_images (hash, arch, seen_ms) SELECT $1, r.arch, $2 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
122485×
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
122585×
            )
122685×
            .bind(&rootfs)
122785×
            .bind(now)
122885×
            .bind(job_id)
122985×
            .execute(&mut *tx)
123085×
            .await?;
12310×
        }
123219×
    }
1233104×
    let mut changed = vec![job_id];
1234
    // Dependents of anything that did not pass are skipped, transitively.
1235
    loop {
1236112×
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1237112×
        let blocked: Vec<i64> = all
1238112×
            .iter()
1239315×
            .filter(|x| x.status == "queued")
1240112×
            .filter(|x| {
124192×
                x.depends_on()
124292×
                    .iter()
1243169×
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
124492×
            })
1245112×
            .map(|x| x.id)
1246112×
            .collect();
1247112×
        if blocked.is_empty() {
1248104×
            break;
12498×
        }
12508×
        for id in blocked {
12518×
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
12528×
                .bind(now)
12538×
                .bind(id)
12548×
                .execute(&mut *tx)
12558×
                .await?;
12568×
            changed.push(id);
1257
        }
1258
    }
1259104×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1260104×
    if all.iter().all(Job::done) {
126190×
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
126241×
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
126341×
            .bind(status)
126441×
            .bind(now)
126541×
            .bind(j.run_id)
126641×
            .execute(&mut *tx)
126741×
            .await?;
126863×
    }
1269104×
    tx.commit().await?;
1270104×
    let mut out = Vec::new();
1271112×
    for id in changed {
1272112×
        if let Some(x) = job(pool, id).await? {
1273112×
            out.push(x);
1274112×
        }
1275
    }
1276104×
    Ok(out)
1277104×
}
1278
1279
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1280
/// and so does the run. A runner learns of it when the hub next refuses
1281
/// its log lines, and stops the job. Returns the jobs whose status changed.
128217×
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
128317×
    let now = now_ms();
128417×
    let mut tx = pool.begin().await?;
128517×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
128617×
        .bind(run_id)
128717×
        .fetch_all(&mut *tx)
128817×
        .await?;
128917×
    sqlx::query(
129017×
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
129117×
         WHERE run_id = $3 AND status IN ('queued', 'running')",
129217×
    )
129317×
    .bind(why)
129417×
    .bind(now)
129517×
    .bind(run_id)
129617×
    .execute(&mut *tx)
129717×
    .await?;
129817×
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
129917×
        .bind(now)
130017×
        .bind(run_id)
130117×
        .execute(&mut *tx)
130217×
        .await?;
130317×
    tx.commit().await?;
130417×
    let mut out = Vec::new();
130543×
    for (id,) in ids {
130643×
        if let Some(x) = job(pool, id).await? {
130743×
            out.push(x);
130843×
        }
1309
    }
131017×
    Ok(out)
131117×
}
1312
1313
/// Run job `name` of finished run `run_id` again, with every job that
1314
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1315
/// artifacts and reports gone, and the run running again. The jobs they
1316
/// depend on keep their results. The jobs reset; none when there is no
1317
/// such job.
13182×
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
13192×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
13204×
    if !all.iter().any(|j| j.name == name) {
13210×
        return Ok(Vec::new());
13222×
    }
13232×
    let mut again = vec![name.to_string()];
1324
    loop {
13253×
        let more: Vec<String> = all
13263×
            .iter()
13279×
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
13283×
            .map(|j| j.name.clone())
13293×
            .collect();
13303×
        if more.is_empty() {
13312×
            break;
13321×
        }
13331×
        again.extend(more);
1334
    }
13356×
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
13362×
    let mut tx = pool.begin().await?;
13373×
    for id in &ids {
133818×
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
133918×
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1340
        }
13413×
        sqlx::query(
13423×
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
13433×
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
13443×
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
13453×
             peak_memory_mib = NULL, phases = '', approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
13463×
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
13473×
             handbacks = 0 WHERE id = $1",
13483×
        )
13493×
        .bind(id)
13503×
        .bind(now_ms())
13513×
        .execute(&mut *tx)
13523×
        .await?;
1353
    }
13542×
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
13552×
    tx.commit().await?;
13562×
    let mut out = Vec::new();
13573×
    for id in ids {
13583×
        if let Some(x) = job(pool, id).await? {
13593×
            out.push(x);
13603×
        }
1361
    }
13622×
    Ok(out)
13632×
}
1364
1365
/// The runs of `bookmark` started by `trigger` still going, older than run
1366
/// `number`: those a newer run supersedes (#267). With `running_too`
1367
/// false, only those still queued.
1368124×
pub async fn live_runs_before(
1369124×
    pool: &Pool,
1370124×
    repo_id: i64,
1371124×
    bookmark: &str,
1372124×
    trigger: &str,
1373124×
    number: i64,
1374124×
    running_too: bool,
1375124×
) -> sqlx::Result<Vec<Run>> {
1376124×
    sqlx::query_as(
1377124×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1378124×
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1379124×
    )
1380124×
    .bind(repo_id)
1381124×
    .bind(bookmark)
1382124×
    .bind(number)
1383124×
    .bind(trigger)
1384124×
    .bind(running_too)
1385124×
    .fetch_all(pool)
1386124×
    .await
1387124×
}
1388
1389
/// The runs on `bookmark` that no runner has started yet: queued, with
1390
/// the given trigger, created before `before_ms` (#263).
139144×
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
139244×
    sqlx::query_as(
139344×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
139444×
    )
139544×
    .bind(repo_id)
139644×
    .bind(bookmark)
139744×
    .bind(trigger)
139844×
    .bind(before_ms)
139944×
    .fetch_all(pool)
140044×
    .await
140144×
}
1402
1403
/// The newest run of exactly this state (heads joined with `+`, sorted).
14046×
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
14056×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
14066×
        .bind(repo_id)
14076×
        .bind(heads)
14086×
        .fetch_optional(pool)
14096×
        .await
14106×
}
1411
1412
/// Record what became of job `job_id`'s signed receipt.
14138×
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
14148×
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
14158×
        .bind(attest)
14168×
        .bind(signer)
14178×
        .bind(note)
14188×
        .bind(job_id)
14198×
        .execute(pool)
14208×
        .await?;
14218×
    Ok(())
14228×
}
1423
1424
/// A job's artifact, kept as a blob of the run's repository.
1425
#[derive(Clone, Debug, FromRow)]
1426
pub struct Artifact {
1427
    pub job_id: i64,
1428
    pub name: String,
1429
    pub path: String,
1430
    pub blob: String,
1431
    pub size: i64,
1432
    /// BLAKE3 of the bytes.
1433
    pub content: String,
1434
    pub created_ms: i64,
1435
}
1436
143714×
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
143814×
    sqlx::query(
143914×
        "INSERT INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES ($1, $2, $3, $4, $5, $6, $7) ON CONFLICT (job_id, name) DO UPDATE SET path = excluded.path, blob = excluded.blob, size = excluded.size, content = excluded.content, created_ms = excluded.created_ms",
144014×
    )
144114×
    .bind(a.job_id)
144214×
    .bind(&a.name)
144314×
    .bind(&a.path)
144414×
    .bind(&a.blob)
144514×
    .bind(a.size)
144614×
    .bind(&a.content)
144714×
    .bind(a.created_ms)
144814×
    .execute(pool)
144914×
    .await?;
145014×
    Ok(())
145114×
}
1452
1453
/// Every artifact blob a repository's runs keep, for garbage collection to
1454
/// keep too (#126): the database is the only thing that names them.
14554×
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
14564×
    sqlx::query_scalar(
14574×
        "SELECT DISTINCT a.blob FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id WHERE r.repo_id = $1",
14584×
    )
14594×
    .bind(repo_id)
14604×
    .fetch_all(pool)
14614×
    .await
14624×
}
1463
1464
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1465
/// receipt names.
1466149×
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1467149×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name NOT LIKE '.%' ORDER BY name").bind(job_id).fetch_all(pool).await
1468149×
}
1469
1470
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1471
/// artifacts: no pipeline can declare it.
1472
pub const CHECKPOINT: &str = ".checkpoint";
1473
1474
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1475
/// back (oxygenflow#77), if one did.
14763×
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
14773×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
14783×
}
1479
1480
/// An artifact with the run and job that made it, for a repository's list
1481
/// of every run's outputs (oxygenhub#254).
1482
#[derive(Clone, Debug, FromRow)]
1483
pub struct RepoArtifact {
1484
    pub run_number: i64,
1485
    pub bookmark: String,
1486
    pub job: String,
1487
    pub name: String,
1488
    pub path: String,
1489
    pub size: i64,
1490
    pub content: String,
1491
    pub created_ms: i64,
1492
}
1493
1494
/// A repository's newest artifacts, at most `limit`.
14952×
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
14962×
    sqlx::query_as(
14972×
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
14982×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
14992×
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
15002×
    )
15012×
    .bind(repo_id)
15022×
    .bind(limit)
15032×
    .fetch_all(pool)
15042×
    .await
15052×
}
1506
1507
/// Where an artifact with given content came from: the run and job that
1508
/// built it, and the job's signed receipt when one was kept.
1509
#[derive(Clone, Debug, FromRow)]
1510
pub struct Provenance {
1511
    pub run_number: i64,
1512
    pub job: String,
1513
    pub name: String,
1514
    pub receipt_attest: String,
1515
    pub receipt_signer: String,
1516
}
1517
1518
/// The build of the bytes whose BLAKE3 is `content` in repository
1519
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1520
/// run first.
152121×
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
152221×
    sqlx::query_as(
152321×
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
152421×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
152521×
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
152621×
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
152721×
    )
152821×
    .bind(repo_id)
152921×
    .bind(content)
153021×
    .fetch_optional(pool)
153121×
    .await
153221×
}
1533
1534
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1535
/// whether it was.
15362×
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
15372×
    let r = sqlx::query(
15382×
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
15392×
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
15402×
    )
15412×
    .bind(who)
15422×
    .bind(now_ms())
15432×
    .bind(seal)
15442×
    .bind(id)
15452×
    .bind(via)
15462×
    .execute(pool)
15472×
    .await?;
15482×
    Ok(r.rows_affected() > 0)
15492×
}
1550
1551
/// Note who rejected job `id` (it is then finished as cancelled).
15521×
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
15531×
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
15541×
        .bind(who)
15551×
        .bind(now_ms())
15561×
        .bind(id)
15571×
        .bind(via)
15581×
        .execute(pool)
15591×
        .await?;
15601×
    Ok(())
15611×
}
1562
1563
/// Jobs waiting for a person, in runs still going.
15642×
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
15652×
    sqlx::query_as(
15662×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15672×
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
15682×
    )
15692×
    .fetch_all(pool)
15702×
    .await
15712×
}
1572
1573
/// One deployment: a job for an environment that passed.
1574
#[derive(Clone, Debug, FromRow)]
1575
pub struct Deployment {
1576
    pub environment: String,
1577
    pub job: String,
1578
    pub run_number: i64,
1579
    pub state: String,
1580
    pub bookmark: String,
1581
    pub actor: String,
1582
    pub approved_by: String,
1583
    pub finished_ms: i64,
1584
}
1585
1586
/// A repository's deployments, newest first (oxygenflow#59).
15872×
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
15882×
    sqlx::query_as(
15892×
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
15902×
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15912×
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
15922×
    )
15932×
    .bind(repo_id)
15942×
    .bind(limit)
15952×
    .fetch_all(pool)
15962×
    .await
15972×
}