OXYGENHUB

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

1034 of 1067 lines run, 175 of 358 functions · run #503 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.
9422×
    pub fn started_by(&self) -> String {
9522×
        match self.trigger.as_str() {
9622×
            "manual" => format!("started by {}", self.actor),
9720×
            "schedule" => "started on schedule".to_string(),
9820×
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
9920×
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
10019×
            _ => format!("pushed by {}", self.actor),
101
        }
10222×
    }
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
118396×
    pub fn head_list(&self) -> Vec<&str> {
119528×
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
120396×
    }
121
122171×
    pub fn live(&self) -> bool {
123171×
        matches!(self.status.as_str(), "queued" | "running")
124171×
    }
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.
19851×
    pub fn phase_list(&self) -> Vec<(String, u64)> {
19951×
        let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(&self.phases).unwrap_or_default();
200204×
        ["image", "prepare", "run", "finish"].iter().filter_map(|p| m.get(*p).map(|ms| (p.to_string(), *ms))).collect()
20151×
    }
202
203
    /// The run whose pass this job reused (#265), if it did.
204127×
    pub fn reused_from(&self) -> Option<i64> {
205127×
        self.error.strip_prefix("reused from run #")?.parse().ok()
206127×
    }
207
208399×
    pub fn depends_on(&self) -> Vec<String> {
209399×
        serde_json::from_str(&self.depends).unwrap_or_default()
210399×
    }
211
212244×
    pub fn done(&self) -> bool {
213244×
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
214244×
    }
215
}
216
217
#[derive(Clone, Debug, FromRow)]
218
pub struct LogLine {
219
    pub seq: i64,
220
    pub t: i64,
221
    pub stream: String,
222
    pub text: String,
223
}
224
225
/// A job as the trigger creates it.
226
pub struct NewJob {
227
    pub name: String,
228
    pub depth: i64,
229
    pub depends: Vec<String>,
230
    pub spec: String,
231
    pub sandbox: String,
232
    pub runtime: String,
233
    /// The free disk it needs, from [`learned_disk_need`].
234
    pub need_disk_mib: Option<i64>,
235
    /// A pass on the same state to reuse instead of running it (#265): the
236
    /// job is created passed, with that pass's receipt.
237
    pub reused: Option<Reused>,
238
}
239
240
/// A job's earlier pass on the same state, spec and sandbox (#265).
241
#[derive(Clone, Debug)]
242
pub struct Reused {
243
    /// The run it passed in.
244
    pub run_number: i64,
245
    pub receipt: String,
246
    pub receipt_hash: String,
247
    pub receipt_attest: String,
248
    pub receipt_signer: String,
249
    pub receipt_note: String,
250
}
251
252
impl Reused {
253
    /// What the reused job says, and how [`Job::reused_from`] reads it back.
2549×
    pub fn note(&self) -> String {
2559×
        format!("reused from run #{}", self.run_number)
2569×
    }
257
}
258
259
/// The newest pass of job `name` with exactly this spec and sandbox on
260
/// `state` in this repository (#265).
261291×
pub async fn passed_on_state(
262291×
    pool: &Pool,
263291×
    repo_id: i64,
264291×
    state: &str,
265291×
    name: &str,
266291×
    spec: &str,
267291×
    sandbox: &str,
268291×
) -> sqlx::Result<Option<Reused>> {
269291×
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
270291×
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
271291×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
272291×
         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' \
273291×
         ORDER BY j.id DESC LIMIT 1",
274291×
    )
275291×
    .bind(repo_id)
276291×
    .bind(state)
277291×
    .bind(name)
278291×
    .bind(spec)
279291×
    .bind(sandbox)
280291×
    .fetch_optional(pool)
281291×
    .await?;
282291×
    Ok(row.map(|(run_number, receipt, receipt_hash, receipt_attest, receipt_signer, receipt_note)| Reused {
2839×
        run_number,
2849×
        receipt,
2859×
        receipt_hash,
2869×
        receipt_attest,
2879×
        receipt_signer,
2889×
        receipt_note,
2899×
    }))
290291×
}
291
292
/// Runs of a job whose peaks set its next need.
293
const NEED_FROM_RUNS: i64 = 5;
294
295
/// The free disk a new run of job `name` in repository `repo_id` needs
296
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
297
/// for a job that has not run here yet.
298360×
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
299360×
    let peak: Option<i64> = sqlx::query_scalar(
300360×
        "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 \
301360×
         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",
302360×
    )
303360×
    .bind(repo_id)
304360×
    .bind(name)
305360×
    .bind(NEED_FROM_RUNS)
306360×
    .fetch_one(pool)
307360×
    .await?;
308360×
    Ok(peak.map(|p| p + p / 4 + 64))
309360×
}
310
311
/// Record why job `job_id` ran where it did.
312156×
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
313156×
    sqlx::query("UPDATE flow_jobs SET placed = $1 WHERE id = $2").bind(placed).bind(job_id).execute(pool).await?;
314156×
    Ok(())
315156×
}
316
317
/// Keep what a job took, as its runner reported.
31895×
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
31995×
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = $1, peak_memory_mib = $2 WHERE id = $3")
32095×
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
32195×
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
32295×
        .bind(job_id)
32395×
        .execute(pool)
32495×
        .await?;
32595×
    Ok(())
32695×
}
327
328
/// Where a finished job's time went, as its runner reported (oxygenflow#35).
32995×
pub async fn set_phases(pool: &Pool, job_id: i64, phases: &std::collections::BTreeMap<String, u64>) -> sqlx::Result<()> {
33095×
    let json = if phases.is_empty() { String::new() } else { serde_json::to_string(phases).unwrap_or_default() };
33195×
    sqlx::query("UPDATE flow_jobs SET phases = $1 WHERE id = $2").bind(json).bind(job_id).execute(pool).await?;
33295×
    Ok(())
33395×
}
334
335
pub struct NewRun<'a> {
336
    pub repo_id: i64,
337
    pub bookmark: &'a str,
338
    pub state: &'a str,
339
    pub heads: &'a str,
340
    pub pipeline_hash: &'a str,
341
    pub actor: &'a str,
342
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
343
    /// `rerun:N:EVENT`.
344
    pub trigger: &'a str,
345
    /// Problems when the pipeline is invalid: the run is recorded in error.
346
    pub error: Option<&'a str>,
347
}
348
349
/// A push that asked for no run (#284): recorded, finished, as skipped,
350
/// with `why` (which change asked, and who pushed it) as its note.
3511×
pub async fn create_skipped_run(pool: &Pool, r: NewRun<'_>, why: &str) -> sqlx::Result<i64> {
3521×
    let mut tx = super::begin_write(pool).await?;
3531×
    let now = now_ms();
3541×
    let id: i64 = sqlx::query_scalar(
3551×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
3561×
         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",
3571×
    )
3581×
    .bind(r.repo_id)
3591×
    .bind(r.repo_id)
3601×
    .bind(r.bookmark)
3611×
    .bind(r.state)
3621×
    .bind(r.heads)
3631×
    .bind(r.pipeline_hash)
3641×
    .bind(why)
3651×
    .bind(r.actor)
3661×
    .bind(r.trigger)
3671×
    .bind(now)
3681×
    .bind(now)
3691×
    .fetch_one(&mut *tx)
3701×
    .await?;
3711×
    tx.commit().await?;
3721×
    Ok(id)
3731×
}
374
375140×
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
376140×
    let mut tx = super::begin_write(pool).await?;
377140×
    let now = now_ms();
378140×
    let status = if r.error.is_some() { "error" } else { "queued" };
379140×
    let id: i64 = sqlx::query_scalar(
380140×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
381140×
         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",
382
    )
383140×
    .bind(r.repo_id)
384140×
    .bind(r.repo_id)
385140×
    .bind(r.bookmark)
386140×
    .bind(r.state)
387140×
    .bind(r.heads)
388140×
    .bind(r.pipeline_hash)
389140×
    .bind(status)
390140×
    .bind(r.error.unwrap_or(""))
391140×
    .bind(r.actor)
392140×
    .bind(r.trigger)
393140×
    .bind(now)
394140×
    .bind(r.error.map(|_| now))
395140×
    .fetch_one(&mut *tx)
396140×
    .await?;
397364×
    for j in jobs {
398364×
        let job_id: i64 = sqlx::query_scalar(
399364×
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
400364×
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
401
        )
402364×
        .bind(id)
403364×
        .bind(&j.name)
404364×
        .bind(j.depth)
405364×
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
406364×
        .bind(&j.spec)
407364×
        .bind(&j.sandbox)
408364×
        .bind(&j.runtime)
409364×
        .bind(j.need_disk_mib)
410364×
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
411364×
        .bind(environment_of(&j.spec))
412364×
        .bind(priority_of(&j.spec))
413364×
        .bind(now)
414364×
        .fetch_one(&mut *tx)
415364×
        .await?;
416
        // A pass reused (#265): done before any runner can claim it.
417364×
        if let Some(r) = &j.reused {
4189×
            sqlx::query(
4199×
                "UPDATE flow_jobs SET status = 'passed', exit_code = 0, error = $1, receipt = $2, receipt_hash = $3, receipt_attest = $4, \
4209×
                 receipt_signer = $5, receipt_note = $6, started_ms = $7, finished_ms = $7 WHERE id = $8",
4219×
            )
4229×
            .bind(r.note())
4239×
            .bind(&r.receipt)
4249×
            .bind(&r.receipt_hash)
4259×
            .bind(&r.receipt_attest)
4269×
            .bind(&r.receipt_signer)
4279×
            .bind(&r.receipt_note)
4289×
            .bind(now)
4299×
            .bind(job_id)
4309×
            .execute(&mut *tx)
4319×
            .await?;
432355×
        }
433
    }
434
    // Every job reused: the run has passed already.
435144×
    if !jobs.is_empty() && jobs.iter().all(|j| j.reused.is_some()) {
4362×
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
437138×
    }
438140×
    tx.commit().await?;
439140×
    Ok(id)
440140×
}
441
442
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
443364×
fn environment_of(spec: &str) -> String {
444364×
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
445364×
}
446
447
/// A compiled job's own priority (`low`, `normal`), or empty; anything
448
/// else is not one a pipeline may give (oxygenhub#244).
449364×
fn priority_of(spec: &str) -> String {
450364×
    serde_json::from_str::<serde_json::Value>(spec)
451364×
        .ok()
452364×
        .and_then(|v| v["priority"].as_str().map(String::from))
453364×
        .filter(|p| p == "low" || p == "normal")
454364×
        .unwrap_or_default()
455364×
}
456
457
/// Whether a compiled job asks for approval (oxygenflow#57).
458364×
fn needs_approval(spec: &str) -> bool {
459364×
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
460364×
}
461
462
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
463202×
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
464202×
    let mut out: Vec<String> = [spec, sandbox]
465202×
        .iter()
466404×
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
467404×
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
468202×
        .filter_map(|l| l.as_str().map(String::from))
469202×
        .collect();
470202×
    out.sort();
471202×
    out.dedup();
472202×
    out
473202×
}
474
475
impl Job {
476
    /// The runner labels this job needs.
477191×
    pub fn needs(&self) -> Vec<String> {
478191×
        labels_in(&self.spec, &self.sandbox)
479191×
    }
480
481
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
48232×
    pub fn arch(&self) -> Option<String> {
48332×
        arch_in(&self.sandbox)
48432×
    }
485
}
486
487
/// The architecture a sandbox's JSON asks for, if any.
48842×
fn arch_in(sandbox: &str) -> Option<String> {
48942×
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
49042×
}
491
492
/// A job waiting for or held by a runner, with where it comes from.
493
#[derive(Clone, Debug, FromRow)]
494
pub struct QueueEntry {
495
    pub job_id: i64,
496
    pub run_id: i64,
497
    pub repo_id: i64,
498
    pub owner: String,
499
    pub name: String,
500
    pub visibility: String,
501
    pub run_number: i64,
502
    pub job: String,
503
    pub status: String,
504
    /// The runner holding it, when running.
505
    pub runner: String,
506
    pub spec: String,
507
    pub sandbox: String,
508
    /// When it started running.
509
    pub started_ms: Option<i64>,
510
    /// Its level (0 urgent … 3 low, oxygenhub#244) and, when expedited, who
511
    /// did it and why.
512
    pub priority_rank: i64,
513
    pub priority_note: String,
514
}
515
516
impl QueueEntry {
51722×
    pub fn priority(&self) -> &'static str {
51822×
        PRIORITIES.get(self.priority_rank as usize).copied().unwrap_or("normal")
51922×
    }
520
}
521
522
impl QueueEntry {
523
    /// The runner labels the job needs.
52411×
    pub fn needs(&self) -> Vec<String> {
52511×
        labels_in(&self.spec, &self.sandbox)
52611×
    }
527
528
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
52910×
    pub fn arch(&self) -> Option<String> {
53010×
        arch_in(&self.sandbox)
53110×
    }
532
}
533
534
/// Every job of a live run that is running or queued: running ones first,
535
/// then queued ones in the order runners claim them (hub spec §13.2).
536265×
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
537265×
    sqlx::query_as(&format!(
538265×
        "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, \
539265×
           CAST({PRIORITY_RANK} AS BIGINT) AS priority_rank, {PRIORITY_NOTE} AS priority_note \
540265×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
541265×
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
542265×
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, \
543265×
           CASE j.status WHEN 'running' THEN 0 ELSE {PRIORITY_RANK} END, \
544265×
           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) \
545265×
           + (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, \
546265×
           j.run_id, j.depth, j.id"
547265×
    ))
548265×
    .fetch_all(pool)
549265×
    .await
550265×
}
551
552
/// A repository's runs, newest first, numbered below `before`.
5532×
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
5542×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3")
5552×
        .bind(repo_id)
5562×
        .bind(before.unwrap_or(i64::MAX))
5572×
        .bind(limit)
5582×
        .fetch_all(pool)
5592×
        .await
5602×
}
561
562
/// The latest run on this bookmark of this repository, for what a push
563
/// changed since (a job's scope).
564
/// The run a push to `bookmark` is scoped against: the newest that was not
565
/// cancelled, nor a push run still going (a new push supersedes it), so
566
/// that what a cancelled run would have checked is checked by the next.
567147×
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
568147×
    sqlx::query_as(
569147×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
570147×
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
571147×
    )
572147×
    .bind(repo_id)
573147×
    .bind(bookmark)
574147×
    .fetch_optional(pool)
575147×
    .await
576147×
}
577
578300×
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
579300×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3")
580300×
        .bind(repo_id)
581300×
        .bind(before.unwrap_or(i64::MAX))
582300×
        .bind(limit)
583300×
        .fetch_all(pool)
584300×
        .await
585300×
}
586
587
/// A repository's run by its number there.
58892×
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
58992×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
59092×
}
591
592966×
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
593966×
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
594966×
}
595
596262×
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
597262×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
598262×
}
599
600478×
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
601478×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
602478×
}
603
604
/// The running job a job token belongs to, while it may still be used.
60531×
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
60631×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = $1 AND status = 'running' AND started_ms >= $2")
60731×
        .bind(token_hash)
60831×
        .bind(now_ms() - max_age_ms)
60931×
        .fetch_optional(pool)
61031×
        .await
61131×
}
612
613
/// Take the oldest queued job whose dependencies all passed and whose tier
614
/// the runner offers, and mark it running for `runner` with a token.
615
/// Let a job's token also read these repositories (its pinned subrepos).
61628×
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
61729×
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
61828×
    sqlx::query("UPDATE flow_jobs SET also_read = $1 WHERE id = $2").bind(list.join(",")).bind(job_id).execute(pool).await?;
61928×
    Ok(())
62028×
}
621
622
impl Job {
62310×
    pub fn also_read_ids(&self) -> Vec<i64> {
62415×
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
62510×
    }
626
}
627
628
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
629
/// limit, and the rootfs images it holds, `None` when it does not say.
630
#[derive(Clone, Debug, Default)]
631
pub struct Room {
632
    pub memory_mib: Option<u32>,
633
    pub cpus: Option<u32>,
634
    pub images: Option<std::collections::HashSet<String>>,
635
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
636
    pub arch: String,
637
    /// Each image's architecture as runners have reported it (`flow_images`).
638
    pub image_archs: std::collections::HashMap<String, String>,
639
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
640
    pub declined: std::collections::HashSet<i64>,
641
    /// Images the hub holds that this runner would fetch when it lacks
642
    /// them (oxygenflow#39); empty for a runner that does not fetch.
643
    pub fetchable: std::collections::HashSet<String>,
644
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
645
    /// when it does not say.
646
    pub free_disk_mib: Option<u64>,
647
}
648
649
impl Room {
650
    /// Whether a job needing `need` MiB of disk fits in its free disk.
651168×
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
652168×
        match (need, self.free_disk_mib) {
6532×
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
654166×
            _ => true,
655
        }
656168×
    }
657
}
658
659
impl Room {
660
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
661
    /// and its rootfs image among the runner's (oxygenhub#73).
662177×
    pub fn fits(&self, sandbox_json: &str) -> bool {
663177×
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
664177×
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
665177×
        let rootfs = v["rootfs"].as_str().unwrap_or("");
666
        // The architecture: the sandbox's own ask, else the image's as read
667
        // or learned from its passes (oxygenhub#173); one nobody has read
668
        // or run yet matches (OxygenFlow spec §11.3).
669177×
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
670177×
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
671177×
        arch_ok
672172×
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
673172×
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
674172×
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
675177×
    }
676
}
677
678
/// Remember which architecture each image is for, as a runner reports it.
67912×
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
68012×
    for (hash, arch) in archs.iter().take(500) {
68110×
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
6820×
            continue;
68310×
        }
68410×
        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")
68510×
        .bind(hash.to_ascii_lowercase())
68610×
        .bind(arch)
68710×
        .bind(now_ms())
68810×
        .execute(pool)
68910×
        .await?;
690
    }
69112×
    Ok(())
69212×
}
693
694
/// Give every image nobody has read the architecture of the runners its
695
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
696
/// each pass. Never overrides a known architecture.
697193×
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
698193×
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
699193×
    let r = sqlx::query(&format!(
700193×
        "INSERT INTO flow_images (hash, arch, seen_ms)
701193×
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
702193×
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
703193×
         GROUP BY lower({rootfs})
704193×
         ON CONFLICT (hash) DO NOTHING"
705193×
    ))
706193×
    .bind(now_ms())
707193×
    .execute(pool)
708193×
    .await?;
709192×
    Ok(r.rows_affected())
710192×
}
711
712
/// Every image's architecture the hub knows.
713454×
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
714454×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
715454×
    Ok(rows.into_iter().collect())
716454×
}
717
7180×
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
7190×
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
7200×
}
721
722
/// The first queued job a runner with these tiers, this room and this
723
/// scope may take, now running under `runner`. Repositories take turns
724
/// (fair share, oxygenhub#244): a job's turn is its place in its own
725
/// repository's queue plus that repository's running jobs, lowest first,
726
/// oldest first among equals, so one repository's burst can't hold up the
727
/// rest. A scoped runner never sees
728
/// another scope's jobs (oxygenhub#41).
7290×
pub async fn claim_within(
7300×
    pool: &Pool,
7310×
    runtimes: &[String],
7320×
    runner: &str,
7330×
    token_hash: &str,
7340×
    room: Room,
7350×
    scope: &super::runners::Scope,
7360×
    labels: &[String],
7370×
) -> sqlx::Result<Option<Job>> {
7380×
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
7390×
}
740
741
/// [`claim_within`], passing over a job `elsewhere` says a better runner
742
/// should take (oxygenflow#42).
743
#[allow(clippy::too_many_arguments)]
744222×
pub async fn claim_ranked(
745222×
    pool: &Pool,
746222×
    runtimes: &[String],
747222×
    runner: &str,
748222×
    token_hash: &str,
749222×
    room: Room,
750222×
    scope: &super::runners::Scope,
751222×
    labels: &[String],
752222×
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
753222×
) -> sqlx::Result<Option<Job>> {
754222×
    let mut tx = super::begin_write(pool).await?;
755222×
    let queued: Vec<Job> = sqlx::query_as(&format!(
756222×
        "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 \
757222×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
758222×
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
759222×
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
760222×
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
761222×
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
762222×
           + (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), \
763222×
           j.run_id, j.depth, j.id LIMIT 200"
764222×
    ))
765222×
    .bind(&scope.owner)
766222×
    .bind(&scope.owner)
767222×
    .bind(scope.repo_id)
768222×
    .bind(scope.repo_id)
769222×
    // A repository on its own runners only (#225): the site's runners skip it.
770222×
    .bind(&scope.owner)
771222×
    .bind(scope.repo_id)
772222×
    .fetch_all(&mut *tx)
773222×
    .await?;
774222×
    for j in queued {
775180×
        if !runtimes.iter().any(|r| r == &j.runtime)
776177×
            || !room.fits(&j.sandbox)
777168×
            || !room.disk_fits(j.need_disk_mib)
778167×
            || room.declined.contains(&j.id)
779
        {
78014×
            continue;
781166×
        }
782
        // Every label the job and its sandbox ask for (`runs-on`).
783166×
        if !j.needs().iter().all(|l| labels.contains(l)) {
7842×
            continue;
785164×
        }
786164×
        let deps = j.depends_on();
787
        // When it became ready: queued, its dependencies passed, approved.
788164×
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
789164×
        if !deps.is_empty() {
79035×
            let mut passed = 0i64;
79135×
            for d in &deps {
79235×
                let st: Option<(String, Option<i64>)> =
79335×
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
79435×
                        .bind(j.run_id)
79535×
                        .bind(d)
79635×
                        .fetch_optional(&mut *tx)
79735×
                        .await?;
79835×
                if let Some((status, finished)) = st {
79935×
                    if status == "passed" {
80030×
                        passed += 1;
80130×
                        ready = ready.max(finished.unwrap_or(0));
80230×
                    }
8030×
                }
804
            }
80535×
            if passed != deps.len() as i64 {
8065×
                continue;
80730×
            }
808129×
        }
809159×
        if elsewhere(&j) {
8103×
            continue;
811156×
        }
812156×
        let now = now_ms();
813156×
        let done = sqlx::query(
814156×
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
815156×
             WHERE id = $4 AND status = 'queued'",
816
        )
817156×
        .bind(runner)
818156×
        .bind(token_hash)
819156×
        .bind(now)
820156×
        .bind(j.id)
821156×
        .bind(if ready > 0 { ready.min(now) } else { now })
822156×
        .execute(&mut *tx)
823156×
        .await?;
824156×
        if done.rows_affected() == 1 {
825156×
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
826156×
                .bind(j.run_id)
827156×
                .execute(&mut *tx)
828156×
                .await?;
829156×
            tx.commit().await?;
830156×
            return job(pool, j.id).await;
8310×
        }
832
    }
83366×
    tx.commit().await?;
83466×
    Ok(None)
835222×
}
836
837
/// How long a decline keeps a job from its runner when the runner's
838
/// profile stays the same: a reason such as memory in use passes.
839
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
840
841
/// The jobs runner `runner_id` declined with this profile, recently.
842222×
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
843222×
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
844222×
        .bind(runner_id)
845222×
        .bind(profile)
846222×
        .bind(now_ms() - DECLINE_HOLDS_MS)
847222×
        .fetch_all(pool)
848222×
        .await?;
849222×
    Ok(rows.into_iter().map(|(j,)| j).collect())
850222×
}
851
852
/// A decline: one runner's reason for handing a job back.
853
#[derive(Clone, Debug, sqlx::FromRow)]
854
pub struct DeclineRow {
855
    pub job_id: i64,
856
    pub runner_id: i64,
857
    pub runner: String,
858
    pub reason: String,
859
    pub ms: i64,
860
}
861
862
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
863
/// is kept (one per job and runner, the latest), and the job is queued
864
/// again. Returns every decline the job has had, or `None` when the job
865
/// was not running on that runner.
8664×
pub async fn decline(
8674×
    pool: &Pool,
8684×
    job_id: i64,
8694×
    runner_id: i64,
8704×
    runner: &str,
8714×
    profile: &str,
8724×
    reason: &str,
8734×
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
8744×
    let mut tx = super::begin_write(pool).await?;
8754×
    let back = sqlx::query(
8764×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
8774×
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
8784×
    )
8794×
    .bind(job_id)
8804×
    .bind(runner_id)
8814×
    .execute(&mut *tx)
8824×
    .await?;
8834×
    if back.rows_affected() != 1 {
8841×
        tx.rollback().await?;
8851×
        return Ok(None);
8863×
    }
8873×
    sqlx::query(
8883×
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
8893×
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
8903×
    )
8913×
    .bind(job_id)
8923×
    .bind(runner_id)
8933×
    .bind(runner)
8943×
    .bind(profile)
8953×
    .bind(reason)
8963×
    .bind(now_ms())
8973×
    .execute(&mut *tx)
8983×
    .await?;
8993×
    let all: Vec<DeclineRow> =
9003×
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
9013×
            .bind(job_id)
9023×
            .fetch_all(&mut *tx)
9033×
            .await?;
9043×
    tx.commit().await?;
9053×
    Ok(Some(all))
9064×
}
907
908
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
909
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
910
/// its runner's lease lapsed. Its log is kept and its next attempt's
911
/// follows on. Returns how many times it has now been handed back, or
912
/// `None` when it was not running there.
9133×
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
9143×
    let mut tx = super::begin_write(pool).await?;
9153×
    let now = now_ms();
9163×
    let back = sqlx::query(
9173×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
9183×
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
9193×
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
9203×
    )
9213×
    .bind(now)
9223×
    .bind(now)
9233×
    .bind(job_id)
9243×
    .bind(runner_id)
9253×
    .bind(runner_id)
9263×
    .execute(&mut *tx)
9273×
    .await?;
9283×
    if back.rows_affected() != 1 {
9291×
        tx.rollback().await?;
9301×
        return Ok(None);
9312×
    }
9322×
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
9332×
    tx.commit().await?;
9342×
    Ok(Some(n))
9353×
}
936
937
/// How long job `name` of repository `repo_id` is expected to take: the
938
/// median of its last five passing runs (claimed to finished), passes
939
/// reused from another run left out (oxygenflow#76). `None` before it has
940
/// passed: a runner leaving then hands it back rather than guess.
941156×
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
942156×
    let mut times: Vec<i64> = sqlx::query_scalar(
943156×
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
944156×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
945156×
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
946156×
    )
947156×
    .bind(repo_id)
948156×
    .bind(name)
949156×
    .fetch_all(pool)
950156×
    .await?;
951156×
    times.sort_unstable();
952156×
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
953156×
}
954
955
/// Jobs running on a runner the hub has not heard from since `before`
956
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
9571×
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
9581×
    let rows: Vec<(i64, String)> = sqlx::query_as(
9591×
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
9601×
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
9611×
    )
9621×
    .bind(before)
9631×
    .fetch_all(pool)
9641×
    .await?;
9651×
    let mut out = Vec::new();
9661×
    for (id, runner) in rows {
9671×
        if let Some(j) = job(pool, id).await? {
9681×
            out.push((j, runner));
9691×
        }
970
    }
9711×
    Ok(out)
9721×
}
973
974
/// The declines of job `job_id`, oldest first.
97513×
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
97613×
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
97713×
        .bind(job_id)
97813×
        .fetch_all(pool)
97913×
        .await
98013×
}
981
982
/// A runner's latest declines, newest first, with where the job is.
983
#[derive(Clone, Debug, sqlx::FromRow)]
984
pub struct RunnerDecline {
985
    pub job_id: i64,
986
    pub job: String,
987
    pub run_number: i64,
988
    pub owner: String,
989
    pub name: String,
990
    pub reason: String,
991
    pub ms: i64,
992
}
993
9944×
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
9954×
    sqlx::query_as(
9964×
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
9974×
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
9984×
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
9994×
    )
10004×
    .bind(runner_id)
10014×
    .bind(limit)
10024×
    .fetch_all(pool)
10034×
    .await
10044×
}
1005
1006
/// Queued jobs whose dependencies have passed, in their live runs, with
1007
/// their repositories (owner, id): the ones a runner could take now.
1008
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
1009
/// (#259: how many ready jobs come first).
10107×
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
10117×
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
10127×
        "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 \
10137×
         WHERE j.status = 'queued'"
10147×
    ))
10157×
    .fetch_all(pool)
10167×
    .await?;
10177×
    Ok(rows.into_iter().collect())
10187×
}
1019
1020
/// How many jobs each runner is running now, by runner id (#259).
10217×
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
10227×
    let rows: Vec<(i64, i64)> =
10237×
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
10247×
            .fetch_all(pool)
10257×
            .await?;
10267×
    Ok(rows.into_iter().collect())
10277×
}
1028
102911×
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
103011×
    let queued: Vec<Job> = sqlx::query_as(
103111×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
103211×
         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",
103311×
    )
103411×
    .fetch_all(pool)
103511×
    .await?;
103611×
    let mut out = Vec::new();
103719×
    for j in queued {
103819×
        let mut ready = true;
103919×
        for d in j.depends_on() {
10407×
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
10417×
                .bind(j.run_id)
10427×
                .bind(&d)
10437×
                .fetch_optional(pool)
10447×
                .await?;
10457×
            if st.as_deref() != Some("passed") {
10467×
                ready = false;
10477×
                break;
10480×
            }
1049
        }
105019×
        if !ready {
10517×
            continue;
105212×
        }
105312×
        let repo: Option<(String, i64)> =
105412×
            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")
105512×
                .bind(j.run_id)
105612×
                .fetch_optional(pool)
105712×
                .await?;
105812×
        if let Some((owner, id)) = repo {
105912×
            out.push((j, owner, id));
106012×
        }
1061
    }
106211×
    Ok(out)
106311×
}
1064
106514×
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
106614×
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
106714×
        .bind(waiting)
106814×
        .bind(job_id)
106914×
        .bind(waiting)
107014×
        .execute(pool)
107114×
        .await?;
107214×
    Ok(())
107314×
}
1074
1075
/// Append records; returns how many were kept (the rest exceed the cap).
107644×
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
107744×
    let mut tx = super::begin_write(pool).await?;
107844×
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
107944×
    let room = (cap - count).max(0) as usize;
108044×
    let keep = &records[..records.len().min(room)];
1081361×
    for (i, r) in keep.iter().enumerate() {
1082361×
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1083361×
            .bind(job_id)
1084361×
            .bind(count + i as i64 + 1)
1085361×
            .bind(r.t as i64)
1086361×
            .bind(&r.stream)
1087361×
            .bind(&r.text)
1088361×
            .execute(&mut *tx)
1089361×
            .await?;
1090
    }
109144×
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
109244×
        .bind(keep.len() as i64)
109344×
        .bind(job_id)
109444×
        .execute(&mut *tx)
109544×
        .await?;
109644×
    tx.commit().await?;
109744×
    Ok(keep.len())
109844×
}
1099
110070×
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
110170×
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
110270×
        .bind(job_id)
110370×
        .bind(after)
110470×
        .bind(limit)
110570×
        .fetch_all(pool)
110670×
        .await
110770×
}
1108
1109
/// Jobs running since before `ms` (the oldest first).
1110
/// Jobs still running at `now` past their own time limit (`default_s` for
1111
/// one claimed without) plus `grace_ms`.
11123×
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
11133×
    sqlx::query_as(
11143×
        "SELECT * FROM flow_jobs WHERE status = 'running' \
11153×
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
11163×
    )
11173×
    .bind(default_s as i64)
11183×
    .bind(grace_ms)
11193×
    .bind(now)
11203×
    .fetch_all(pool)
11213×
    .await
11223×
}
1123
1124
/// Record the limit a claimed job runs under.
1125156×
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1126156×
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1127156×
    Ok(())
1128156×
}
1129
11300×
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
11310×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
11320×
        .bind(ms)
11330×
        .fetch_all(pool)
11340×
        .await
11350×
}
1136
1137
/// The jobs running on the runner with this id.
11382×
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
11392×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
11402×
}
1141
1142
pub struct Outcome<'a> {
1143
    pub status: &'a str,
1144
    pub exit_code: Option<i64>,
1145
    pub error: &'a str,
1146
    pub receipt: &'a str,
1147
    pub receipt_hash: &'a str,
1148
}
1149
1150
/// Record a job's end, skip the jobs that can no longer run, and settle the
1151
/// run. Returns the jobs whose status changed (for their checks).
1152104×
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1153104×
    let mut tx = super::begin_write(pool).await?;
1154104×
    let now = now_ms();
1155104×
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1156104×
    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")
1157104×
        .bind(o.status)
1158104×
        .bind(o.exit_code)
1159104×
        .bind(o.error)
1160104×
        .bind(o.receipt)
1161104×
        .bind(o.receipt_hash)
1162104×
        .bind(now)
1163104×
        .bind(job_id)
1164104×
        .execute(&mut *tx)
1165104×
        .await?;
1166
    // A pass teaches what its image is for, when nobody has read it
1167
    // (oxygenhub#173): the architecture of the runner it passed on.
1168104×
    if o.status == "passed" {
116985×
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
117085×
            .ok()
117185×
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
117285×
            .unwrap_or_default();
117385×
        if rootfs.len() == 64 {
117485×
            sqlx::query(
117585×
                "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 \
117685×
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
117785×
            )
117885×
            .bind(&rootfs)
117985×
            .bind(now)
118085×
            .bind(job_id)
118185×
            .execute(&mut *tx)
118285×
            .await?;
11830×
        }
118419×
    }
1185104×
    let mut changed = vec![job_id];
1186
    // Dependents of anything that did not pass are skipped, transitively.
1187
    loop {
1188112×
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1189112×
        let blocked: Vec<i64> = all
1190112×
            .iter()
1191315×
            .filter(|x| x.status == "queued")
1192112×
            .filter(|x| {
119392×
                x.depends_on()
119492×
                    .iter()
1195169×
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
119692×
            })
1197112×
            .map(|x| x.id)
1198112×
            .collect();
1199112×
        if blocked.is_empty() {
1200104×
            break;
12018×
        }
12028×
        for id in blocked {
12038×
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
12048×
                .bind(now)
12058×
                .bind(id)
12068×
                .execute(&mut *tx)
12078×
                .await?;
12088×
            changed.push(id);
1209
        }
1210
    }
1211104×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1212104×
    if all.iter().all(Job::done) {
121390×
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
121441×
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
121541×
            .bind(status)
121641×
            .bind(now)
121741×
            .bind(j.run_id)
121841×
            .execute(&mut *tx)
121941×
            .await?;
122063×
    }
1221104×
    tx.commit().await?;
1222104×
    let mut out = Vec::new();
1223112×
    for id in changed {
1224112×
        if let Some(x) = job(pool, id).await? {
1225112×
            out.push(x);
1226112×
        }
1227
    }
1228104×
    Ok(out)
1229104×
}
1230
1231
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1232
/// and so does the run. A runner learns of it when the hub next refuses
1233
/// its log lines, and stops the job. Returns the jobs whose status changed.
123416×
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
123516×
    let now = now_ms();
123616×
    let mut tx = pool.begin().await?;
123716×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
123816×
        .bind(run_id)
123916×
        .fetch_all(&mut *tx)
124016×
        .await?;
124116×
    sqlx::query(
124216×
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
124316×
         WHERE run_id = $3 AND status IN ('queued', 'running')",
124416×
    )
124516×
    .bind(why)
124616×
    .bind(now)
124716×
    .bind(run_id)
124816×
    .execute(&mut *tx)
124916×
    .await?;
125016×
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
125116×
        .bind(now)
125216×
        .bind(run_id)
125316×
        .execute(&mut *tx)
125416×
        .await?;
125516×
    tx.commit().await?;
125616×
    let mut out = Vec::new();
125740×
    for (id,) in ids {
125840×
        if let Some(x) = job(pool, id).await? {
125940×
            out.push(x);
126040×
        }
1261
    }
126216×
    Ok(out)
126316×
}
1264
1265
/// Run job `name` of finished run `run_id` again, with every job that
1266
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1267
/// artifacts and reports gone, and the run running again. The jobs they
1268
/// depend on keep their results. The jobs reset; none when there is no
1269
/// such job.
12702×
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
12712×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
12724×
    if !all.iter().any(|j| j.name == name) {
12730×
        return Ok(Vec::new());
12742×
    }
12752×
    let mut again = vec![name.to_string()];
1276
    loop {
12773×
        let more: Vec<String> = all
12783×
            .iter()
12799×
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
12803×
            .map(|j| j.name.clone())
12813×
            .collect();
12823×
        if more.is_empty() {
12832×
            break;
12841×
        }
12851×
        again.extend(more);
1286
    }
12876×
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
12882×
    let mut tx = pool.begin().await?;
12893×
    for id in &ids {
129018×
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
129118×
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1292
        }
12933×
        sqlx::query(
12943×
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
12953×
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
12963×
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
12973×
             peak_memory_mib = NULL, phases = '', approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
12983×
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
12993×
             handbacks = 0 WHERE id = $1",
13003×
        )
13013×
        .bind(id)
13023×
        .bind(now_ms())
13033×
        .execute(&mut *tx)
13043×
        .await?;
1305
    }
13062×
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
13072×
    tx.commit().await?;
13082×
    let mut out = Vec::new();
13093×
    for id in ids {
13103×
        if let Some(x) = job(pool, id).await? {
13113×
            out.push(x);
13123×
        }
1313
    }
13142×
    Ok(out)
13152×
}
1316
1317
/// The runs of `bookmark` started by `trigger` still going, older than run
1318
/// `number`: those a newer run supersedes (#267). With `running_too`
1319
/// false, only those still queued.
1320121×
pub async fn live_runs_before(
1321121×
    pool: &Pool,
1322121×
    repo_id: i64,
1323121×
    bookmark: &str,
1324121×
    trigger: &str,
1325121×
    number: i64,
1326121×
    running_too: bool,
1327121×
) -> sqlx::Result<Vec<Run>> {
1328121×
    sqlx::query_as(
1329121×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1330121×
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1331121×
    )
1332121×
    .bind(repo_id)
1333121×
    .bind(bookmark)
1334121×
    .bind(number)
1335121×
    .bind(trigger)
1336121×
    .bind(running_too)
1337121×
    .fetch_all(pool)
1338121×
    .await
1339121×
}
1340
1341
/// The runs on `bookmark` that no runner has started yet: queued, with
1342
/// the given trigger, created before `before_ms` (#263).
134340×
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
134440×
    sqlx::query_as(
134540×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
134640×
    )
134740×
    .bind(repo_id)
134840×
    .bind(bookmark)
134940×
    .bind(trigger)
135040×
    .bind(before_ms)
135140×
    .fetch_all(pool)
135240×
    .await
135340×
}
1354
1355
/// The newest run of exactly this state (heads joined with `+`, sorted).
13566×
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
13576×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
13586×
        .bind(repo_id)
13596×
        .bind(heads)
13606×
        .fetch_optional(pool)
13616×
        .await
13626×
}
1363
1364
/// Record what became of job `job_id`'s signed receipt.
13658×
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
13668×
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
13678×
        .bind(attest)
13688×
        .bind(signer)
13698×
        .bind(note)
13708×
        .bind(job_id)
13718×
        .execute(pool)
13728×
        .await?;
13738×
    Ok(())
13748×
}
1375
1376
/// A job's artifact, kept as a blob of the run's repository.
1377
#[derive(Clone, Debug, FromRow)]
1378
pub struct Artifact {
1379
    pub job_id: i64,
1380
    pub name: String,
1381
    pub path: String,
1382
    pub blob: String,
1383
    pub size: i64,
1384
    /// BLAKE3 of the bytes.
1385
    pub content: String,
1386
    pub created_ms: i64,
1387
}
1388
138914×
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
139014×
    sqlx::query(
139114×
        "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",
139214×
    )
139314×
    .bind(a.job_id)
139414×
    .bind(&a.name)
139514×
    .bind(&a.path)
139614×
    .bind(&a.blob)
139714×
    .bind(a.size)
139814×
    .bind(&a.content)
139914×
    .bind(a.created_ms)
140014×
    .execute(pool)
140114×
    .await?;
140214×
    Ok(())
140314×
}
1404
1405
/// Every artifact blob a repository's runs keep, for garbage collection to
1406
/// keep too (#126): the database is the only thing that names them.
14074×
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
14084×
    sqlx::query_scalar(
14094×
        "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",
14104×
    )
14114×
    .bind(repo_id)
14124×
    .fetch_all(pool)
14134×
    .await
14144×
}
1415
1416
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1417
/// receipt names.
1418146×
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1419146×
    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
1420146×
}
1421
1422
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1423
/// artifacts: no pipeline can declare it.
1424
pub const CHECKPOINT: &str = ".checkpoint";
1425
1426
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1427
/// back (oxygenflow#77), if one did.
14283×
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
14293×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
14303×
}
1431
1432
/// An artifact with the run and job that made it, for a repository's list
1433
/// of every run's outputs (oxygenhub#254).
1434
#[derive(Clone, Debug, FromRow)]
1435
pub struct RepoArtifact {
1436
    pub run_number: i64,
1437
    pub bookmark: String,
1438
    pub job: String,
1439
    pub name: String,
1440
    pub path: String,
1441
    pub size: i64,
1442
    pub content: String,
1443
    pub created_ms: i64,
1444
}
1445
1446
/// A repository's newest artifacts, at most `limit`.
14472×
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
14482×
    sqlx::query_as(
14492×
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
14502×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
14512×
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
14522×
    )
14532×
    .bind(repo_id)
14542×
    .bind(limit)
14552×
    .fetch_all(pool)
14562×
    .await
14572×
}
1458
1459
/// Where an artifact with given content came from: the run and job that
1460
/// built it, and the job's signed receipt when one was kept.
1461
#[derive(Clone, Debug, FromRow)]
1462
pub struct Provenance {
1463
    pub run_number: i64,
1464
    pub job: String,
1465
    pub name: String,
1466
    pub receipt_attest: String,
1467
    pub receipt_signer: String,
1468
}
1469
1470
/// The build of the bytes whose BLAKE3 is `content` in repository
1471
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1472
/// run first.
147321×
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
147421×
    sqlx::query_as(
147521×
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
147621×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
147721×
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
147821×
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
147921×
    )
148021×
    .bind(repo_id)
148121×
    .bind(content)
148221×
    .fetch_optional(pool)
148321×
    .await
148421×
}
1485
1486
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1487
/// whether it was.
14882×
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
14892×
    let r = sqlx::query(
14902×
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
14912×
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
14922×
    )
14932×
    .bind(who)
14942×
    .bind(now_ms())
14952×
    .bind(seal)
14962×
    .bind(id)
14972×
    .bind(via)
14982×
    .execute(pool)
14992×
    .await?;
15002×
    Ok(r.rows_affected() > 0)
15012×
}
1502
1503
/// Note who rejected job `id` (it is then finished as cancelled).
15041×
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
15051×
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
15061×
        .bind(who)
15071×
        .bind(now_ms())
15081×
        .bind(id)
15091×
        .bind(via)
15101×
        .execute(pool)
15111×
        .await?;
15121×
    Ok(())
15131×
}
1514
1515
/// Jobs waiting for a person, in runs still going.
15162×
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
15172×
    sqlx::query_as(
15182×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15192×
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
15202×
    )
15212×
    .fetch_all(pool)
15222×
    .await
15232×
}
1524
1525
/// One deployment: a job for an environment that passed.
1526
#[derive(Clone, Debug, FromRow)]
1527
pub struct Deployment {
1528
    pub environment: String,
1529
    pub job: String,
1530
    pub run_number: i64,
1531
    pub state: String,
1532
    pub bookmark: String,
1533
    pub actor: String,
1534
    pub approved_by: String,
1535
    pub finished_ms: i64,
1536
}
1537
1538
/// A repository's deployments, newest first (oxygenflow#59).
15392×
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
15402×
    sqlx::query_as(
15412×
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
15422×
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15432×
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
15442×
    )
15452×
    .bind(repo_id)
15462×
    .bind(limit)
15472×
    .fetch_all(pool)
15482×
    .await
15492×
}