OXYGENHUB

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

1022 of 1055 lines run, 170 of 348 functions · run #497 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
    /// The free disk it needs, learned from past runs of the same job.
162
    pub need_disk_mib: Option<i64>,
163
    /// Why it ran on its runner (oxygenflow#42).
164
    pub placed: String,
165
    /// `waiting` for a person, `approved`, or empty (oxygenflow#57).
166
    pub approval: String,
167
    /// Who approved or rejected it, and when.
168
    pub approved_by: String,
169
    pub approved_ms: Option<i64>,
170
    /// The agent token it was decided through, if one (oxygenhub#229).
171
    #[sqlx(default)]
172
    pub approved_via: String,
173
    /// The environment it deploys to, or empty (oxygenflow#59).
174
    pub environment: String,
175
    /// The approval attestation that released it, when sealed (#235).
176
    pub approval_seal: String,
177
    /// When it entered the queue (made, or run again), and when it became
178
    /// ready to run: set at its claim (migration 0080, oxygenhub#257).
179
    #[sqlx(default)]
180
    pub queued_ms: Option<i64>,
181
    #[sqlx(default)]
182
    pub ready_ms: Option<i64>,
183
    /// When a runner last handed it back, drained or with its lease lapsed
184
    /// (oxygenflow#76, migration 0094), and how many times: such a job is
185
    /// queued ahead of new work.
186
    #[sqlx(default)]
187
    pub handed_back_ms: Option<i64>,
188
    #[sqlx(default)]
189
    pub handbacks: i64,
190
}
191
192
impl Job {
193
    /// The run whose pass this job reused (#265), if it did.
194127×
    pub fn reused_from(&self) -> Option<i64> {
195127×
        self.error.strip_prefix("reused from run #")?.parse().ok()
196127×
    }
197
198399×
    pub fn depends_on(&self) -> Vec<String> {
199399×
        serde_json::from_str(&self.depends).unwrap_or_default()
200399×
    }
201
202244×
    pub fn done(&self) -> bool {
203244×
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
204244×
    }
205
}
206
207
#[derive(Clone, Debug, FromRow)]
208
pub struct LogLine {
209
    pub seq: i64,
210
    pub t: i64,
211
    pub stream: String,
212
    pub text: String,
213
}
214
215
/// A job as the trigger creates it.
216
pub struct NewJob {
217
    pub name: String,
218
    pub depth: i64,
219
    pub depends: Vec<String>,
220
    pub spec: String,
221
    pub sandbox: String,
222
    pub runtime: String,
223
    /// The free disk it needs, from [`learned_disk_need`].
224
    pub need_disk_mib: Option<i64>,
225
    /// A pass on the same state to reuse instead of running it (#265): the
226
    /// job is created passed, with that pass's receipt.
227
    pub reused: Option<Reused>,
228
}
229
230
/// A job's earlier pass on the same state, spec and sandbox (#265).
231
#[derive(Clone, Debug)]
232
pub struct Reused {
233
    /// The run it passed in.
234
    pub run_number: i64,
235
    pub receipt: String,
236
    pub receipt_hash: String,
237
    pub receipt_attest: String,
238
    pub receipt_signer: String,
239
    pub receipt_note: String,
240
}
241
242
impl Reused {
243
    /// What the reused job says, and how [`Job::reused_from`] reads it back.
2449×
    pub fn note(&self) -> String {
2459×
        format!("reused from run #{}", self.run_number)
2469×
    }
247
}
248
249
/// The newest pass of job `name` with exactly this spec and sandbox on
250
/// `state` in this repository (#265).
251291×
pub async fn passed_on_state(
252291×
    pool: &Pool,
253291×
    repo_id: i64,
254291×
    state: &str,
255291×
    name: &str,
256291×
    spec: &str,
257291×
    sandbox: &str,
258291×
) -> sqlx::Result<Option<Reused>> {
259291×
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
260291×
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
261291×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
262291×
         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' \
263291×
         ORDER BY j.id DESC LIMIT 1",
264291×
    )
265291×
    .bind(repo_id)
266291×
    .bind(state)
267291×
    .bind(name)
268291×
    .bind(spec)
269291×
    .bind(sandbox)
270291×
    .fetch_optional(pool)
271291×
    .await?;
272291×
    Ok(row.map(|(run_number, receipt, receipt_hash, receipt_attest, receipt_signer, receipt_note)| Reused {
2739×
        run_number,
2749×
        receipt,
2759×
        receipt_hash,
2769×
        receipt_attest,
2779×
        receipt_signer,
2789×
        receipt_note,
2799×
    }))
280291×
}
281
282
/// Runs of a job whose peaks set its next need.
283
const NEED_FROM_RUNS: i64 = 5;
284
285
/// The free disk a new run of job `name` in repository `repo_id` needs
286
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
287
/// for a job that has not run here yet.
288360×
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
289360×
    let peak: Option<i64> = sqlx::query_scalar(
290360×
        "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 \
291360×
         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",
292360×
    )
293360×
    .bind(repo_id)
294360×
    .bind(name)
295360×
    .bind(NEED_FROM_RUNS)
296360×
    .fetch_one(pool)
297360×
    .await?;
298360×
    Ok(peak.map(|p| p + p / 4 + 64))
299360×
}
300
301
/// Record why job `job_id` ran where it did.
302156×
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
303156×
    sqlx::query("UPDATE flow_jobs SET placed = $1 WHERE id = $2").bind(placed).bind(job_id).execute(pool).await?;
304156×
    Ok(())
305156×
}
306
307
/// Keep what a job took, as its runner reported.
30895×
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
30995×
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = $1, peak_memory_mib = $2 WHERE id = $3")
31095×
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
31195×
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
31295×
        .bind(job_id)
31395×
        .execute(pool)
31495×
        .await?;
31595×
    Ok(())
31695×
}
317
318
pub struct NewRun<'a> {
319
    pub repo_id: i64,
320
    pub bookmark: &'a str,
321
    pub state: &'a str,
322
    pub heads: &'a str,
323
    pub pipeline_hash: &'a str,
324
    pub actor: &'a str,
325
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
326
    /// `rerun:N:EVENT`.
327
    pub trigger: &'a str,
328
    /// Problems when the pipeline is invalid: the run is recorded in error.
329
    pub error: Option<&'a str>,
330
}
331
332
/// A push that asked for no run (#284): recorded, finished, as skipped,
333
/// with `why` (which change asked, and who pushed it) as its note.
3341×
pub async fn create_skipped_run(pool: &Pool, r: NewRun<'_>, why: &str) -> sqlx::Result<i64> {
3351×
    let mut tx = super::begin_write(pool).await?;
3361×
    let now = now_ms();
3371×
    let id: i64 = sqlx::query_scalar(
3381×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
3391×
         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",
3401×
    )
3411×
    .bind(r.repo_id)
3421×
    .bind(r.repo_id)
3431×
    .bind(r.bookmark)
3441×
    .bind(r.state)
3451×
    .bind(r.heads)
3461×
    .bind(r.pipeline_hash)
3471×
    .bind(why)
3481×
    .bind(r.actor)
3491×
    .bind(r.trigger)
3501×
    .bind(now)
3511×
    .bind(now)
3521×
    .fetch_one(&mut *tx)
3531×
    .await?;
3541×
    tx.commit().await?;
3551×
    Ok(id)
3561×
}
357
358140×
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
359140×
    let mut tx = super::begin_write(pool).await?;
360140×
    let now = now_ms();
361140×
    let status = if r.error.is_some() { "error" } else { "queued" };
362140×
    let id: i64 = sqlx::query_scalar(
363140×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
364140×
         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",
365
    )
366140×
    .bind(r.repo_id)
367140×
    .bind(r.repo_id)
368140×
    .bind(r.bookmark)
369140×
    .bind(r.state)
370140×
    .bind(r.heads)
371140×
    .bind(r.pipeline_hash)
372140×
    .bind(status)
373140×
    .bind(r.error.unwrap_or(""))
374140×
    .bind(r.actor)
375140×
    .bind(r.trigger)
376140×
    .bind(now)
377140×
    .bind(r.error.map(|_| now))
378140×
    .fetch_one(&mut *tx)
379140×
    .await?;
380364×
    for j in jobs {
381364×
        let job_id: i64 = sqlx::query_scalar(
382364×
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
383364×
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
384
        )
385364×
        .bind(id)
386364×
        .bind(&j.name)
387364×
        .bind(j.depth)
388364×
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
389364×
        .bind(&j.spec)
390364×
        .bind(&j.sandbox)
391364×
        .bind(&j.runtime)
392364×
        .bind(j.need_disk_mib)
393364×
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
394364×
        .bind(environment_of(&j.spec))
395364×
        .bind(priority_of(&j.spec))
396364×
        .bind(now)
397364×
        .fetch_one(&mut *tx)
398364×
        .await?;
399
        // A pass reused (#265): done before any runner can claim it.
400364×
        if let Some(r) = &j.reused {
4019×
            sqlx::query(
4029×
                "UPDATE flow_jobs SET status = 'passed', exit_code = 0, error = $1, receipt = $2, receipt_hash = $3, receipt_attest = $4, \
4039×
                 receipt_signer = $5, receipt_note = $6, started_ms = $7, finished_ms = $7 WHERE id = $8",
4049×
            )
4059×
            .bind(r.note())
4069×
            .bind(&r.receipt)
4079×
            .bind(&r.receipt_hash)
4089×
            .bind(&r.receipt_attest)
4099×
            .bind(&r.receipt_signer)
4109×
            .bind(&r.receipt_note)
4119×
            .bind(now)
4129×
            .bind(job_id)
4139×
            .execute(&mut *tx)
4149×
            .await?;
415355×
        }
416
    }
417
    // Every job reused: the run has passed already.
418144×
    if !jobs.is_empty() && jobs.iter().all(|j| j.reused.is_some()) {
4192×
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
420138×
    }
421140×
    tx.commit().await?;
422140×
    Ok(id)
423140×
}
424
425
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
426364×
fn environment_of(spec: &str) -> String {
427364×
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
428364×
}
429
430
/// A compiled job's own priority (`low`, `normal`), or empty; anything
431
/// else is not one a pipeline may give (oxygenhub#244).
432364×
fn priority_of(spec: &str) -> String {
433364×
    serde_json::from_str::<serde_json::Value>(spec)
434364×
        .ok()
435364×
        .and_then(|v| v["priority"].as_str().map(String::from))
436364×
        .filter(|p| p == "low" || p == "normal")
437364×
        .unwrap_or_default()
438364×
}
439
440
/// Whether a compiled job asks for approval (oxygenflow#57).
441364×
fn needs_approval(spec: &str) -> bool {
442364×
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
443364×
}
444
445
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
446202×
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
447202×
    let mut out: Vec<String> = [spec, sandbox]
448202×
        .iter()
449404×
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
450404×
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
451202×
        .filter_map(|l| l.as_str().map(String::from))
452202×
        .collect();
453202×
    out.sort();
454202×
    out.dedup();
455202×
    out
456202×
}
457
458
impl Job {
459
    /// The runner labels this job needs.
460191×
    pub fn needs(&self) -> Vec<String> {
461191×
        labels_in(&self.spec, &self.sandbox)
462191×
    }
463
464
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
46532×
    pub fn arch(&self) -> Option<String> {
46632×
        arch_in(&self.sandbox)
46732×
    }
468
}
469
470
/// The architecture a sandbox's JSON asks for, if any.
47142×
fn arch_in(sandbox: &str) -> Option<String> {
47242×
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
47342×
}
474
475
/// A job waiting for or held by a runner, with where it comes from.
476
#[derive(Clone, Debug, FromRow)]
477
pub struct QueueEntry {
478
    pub job_id: i64,
479
    pub run_id: i64,
480
    pub repo_id: i64,
481
    pub owner: String,
482
    pub name: String,
483
    pub visibility: String,
484
    pub run_number: i64,
485
    pub job: String,
486
    pub status: String,
487
    /// The runner holding it, when running.
488
    pub runner: String,
489
    pub spec: String,
490
    pub sandbox: String,
491
    /// When it started running.
492
    pub started_ms: Option<i64>,
493
    /// Its level (0 urgent … 3 low, oxygenhub#244) and, when expedited, who
494
    /// did it and why.
495
    pub priority_rank: i64,
496
    pub priority_note: String,
497
}
498
499
impl QueueEntry {
50022×
    pub fn priority(&self) -> &'static str {
50122×
        PRIORITIES.get(self.priority_rank as usize).copied().unwrap_or("normal")
50222×
    }
503
}
504
505
impl QueueEntry {
506
    /// The runner labels the job needs.
50711×
    pub fn needs(&self) -> Vec<String> {
50811×
        labels_in(&self.spec, &self.sandbox)
50911×
    }
510
511
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
51210×
    pub fn arch(&self) -> Option<String> {
51310×
        arch_in(&self.sandbox)
51410×
    }
515
}
516
517
/// Every job of a live run that is running or queued: running ones first,
518
/// then queued ones in the order runners claim them (hub spec §13.2).
519266×
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
520266×
    sqlx::query_as(&format!(
521266×
        "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, \
522266×
           CAST({PRIORITY_RANK} AS BIGINT) AS priority_rank, {PRIORITY_NOTE} AS priority_note \
523266×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
524266×
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
525266×
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, \
526266×
           CASE j.status WHEN 'running' THEN 0 ELSE {PRIORITY_RANK} END, \
527266×
           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) \
528266×
           + (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, \
529266×
           j.run_id, j.depth, j.id"
530266×
    ))
531266×
    .fetch_all(pool)
532266×
    .await
533266×
}
534
535
/// A repository's runs, newest first, numbered below `before`.
5362×
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
5372×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3")
5382×
        .bind(repo_id)
5392×
        .bind(before.unwrap_or(i64::MAX))
5402×
        .bind(limit)
5412×
        .fetch_all(pool)
5422×
        .await
5432×
}
544
545
/// The latest run on this bookmark of this repository, for what a push
546
/// changed since (a job's scope).
547
/// The run a push to `bookmark` is scoped against: the newest that was not
548
/// cancelled, nor a push run still going (a new push supersedes it), so
549
/// that what a cancelled run would have checked is checked by the next.
550147×
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
551147×
    sqlx::query_as(
552147×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
553147×
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
554147×
    )
555147×
    .bind(repo_id)
556147×
    .bind(bookmark)
557147×
    .fetch_optional(pool)
558147×
    .await
559147×
}
560
561301×
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
562301×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3")
563301×
        .bind(repo_id)
564301×
        .bind(before.unwrap_or(i64::MAX))
565301×
        .bind(limit)
566301×
        .fetch_all(pool)
567301×
        .await
568301×
}
569
570
/// A repository's run by its number there.
57193×
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
57293×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
57393×
}
574
575965×
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
576965×
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
577965×
}
578
579262×
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
580262×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
581262×
}
582
583478×
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
584478×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
585478×
}
586
587
/// The running job a job token belongs to, while it may still be used.
58831×
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
58931×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = $1 AND status = 'running' AND started_ms >= $2")
59031×
        .bind(token_hash)
59131×
        .bind(now_ms() - max_age_ms)
59231×
        .fetch_optional(pool)
59331×
        .await
59431×
}
595
596
/// Take the oldest queued job whose dependencies all passed and whose tier
597
/// the runner offers, and mark it running for `runner` with a token.
598
/// Let a job's token also read these repositories (its pinned subrepos).
59928×
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
60029×
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
60128×
    sqlx::query("UPDATE flow_jobs SET also_read = $1 WHERE id = $2").bind(list.join(",")).bind(job_id).execute(pool).await?;
60228×
    Ok(())
60328×
}
604
605
impl Job {
60610×
    pub fn also_read_ids(&self) -> Vec<i64> {
60715×
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
60810×
    }
609
}
610
611
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
612
/// limit, and the rootfs images it holds, `None` when it does not say.
613
#[derive(Clone, Debug, Default)]
614
pub struct Room {
615
    pub memory_mib: Option<u32>,
616
    pub cpus: Option<u32>,
617
    pub images: Option<std::collections::HashSet<String>>,
618
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
619
    pub arch: String,
620
    /// Each image's architecture as runners have reported it (`flow_images`).
621
    pub image_archs: std::collections::HashMap<String, String>,
622
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
623
    pub declined: std::collections::HashSet<i64>,
624
    /// Images the hub holds that this runner would fetch when it lacks
625
    /// them (oxygenflow#39); empty for a runner that does not fetch.
626
    pub fetchable: std::collections::HashSet<String>,
627
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
628
    /// when it does not say.
629
    pub free_disk_mib: Option<u64>,
630
}
631
632
impl Room {
633
    /// Whether a job needing `need` MiB of disk fits in its free disk.
634168×
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
635168×
        match (need, self.free_disk_mib) {
6362×
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
637166×
            _ => true,
638
        }
639168×
    }
640
}
641
642
impl Room {
643
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
644
    /// and its rootfs image among the runner's (oxygenhub#73).
645177×
    pub fn fits(&self, sandbox_json: &str) -> bool {
646177×
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
647177×
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
648177×
        let rootfs = v["rootfs"].as_str().unwrap_or("");
649
        // The architecture: the sandbox's own ask, else the image's as read
650
        // or learned from its passes (oxygenhub#173); one nobody has read
651
        // or run yet matches (OxygenFlow spec §11.3).
652177×
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
653177×
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
654177×
        arch_ok
655172×
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
656172×
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
657172×
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
658177×
    }
659
}
660
661
/// Remember which architecture each image is for, as a runner reports it.
6629×
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
6639×
    for (hash, arch) in archs.iter().take(500) {
6647×
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
6650×
            continue;
6667×
        }
6677×
        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")
6687×
        .bind(hash.to_ascii_lowercase())
6697×
        .bind(arch)
6707×
        .bind(now_ms())
6717×
        .execute(pool)
6727×
        .await?;
673
    }
6749×
    Ok(())
6759×
}
676
677
/// Give every image nobody has read the architecture of the runners its
678
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
679
/// each pass. Never overrides a known architecture.
680191×
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
681191×
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
682191×
    let r = sqlx::query(&format!(
683191×
        "INSERT INTO flow_images (hash, arch, seen_ms)
684191×
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
685191×
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
686191×
         GROUP BY lower({rootfs})
687191×
         ON CONFLICT (hash) DO NOTHING"
688191×
    ))
689191×
    .bind(now_ms())
690191×
    .execute(pool)
691191×
    .await?;
692191×
    Ok(r.rows_affected())
693191×
}
694
695
/// Every image's architecture the hub knows.
696456×
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
697456×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
698456×
    Ok(rows.into_iter().collect())
699456×
}
700
7010×
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
7020×
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
7030×
}
704
705
/// The first queued job a runner with these tiers, this room and this
706
/// scope may take, now running under `runner`. Repositories take turns
707
/// (fair share, oxygenhub#244): a job's turn is its place in its own
708
/// repository's queue plus that repository's running jobs, lowest first,
709
/// oldest first among equals, so one repository's burst can't hold up the
710
/// rest. A scoped runner never sees
711
/// another scope's jobs (oxygenhub#41).
7120×
pub async fn claim_within(
7130×
    pool: &Pool,
7140×
    runtimes: &[String],
7150×
    runner: &str,
7160×
    token_hash: &str,
7170×
    room: Room,
7180×
    scope: &super::runners::Scope,
7190×
    labels: &[String],
7200×
) -> sqlx::Result<Option<Job>> {
7210×
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
7220×
}
723
724
/// [`claim_within`], passing over a job `elsewhere` says a better runner
725
/// should take (oxygenflow#42).
726
#[allow(clippy::too_many_arguments)]
727223×
pub async fn claim_ranked(
728223×
    pool: &Pool,
729223×
    runtimes: &[String],
730223×
    runner: &str,
731223×
    token_hash: &str,
732223×
    room: Room,
733223×
    scope: &super::runners::Scope,
734223×
    labels: &[String],
735223×
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
736223×
) -> sqlx::Result<Option<Job>> {
737223×
    let mut tx = super::begin_write(pool).await?;
738223×
    let queued: Vec<Job> = sqlx::query_as(&format!(
739223×
        "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 \
740223×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
741223×
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
742223×
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
743223×
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
744223×
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
745223×
           + (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), \
746223×
           j.run_id, j.depth, j.id LIMIT 200"
747223×
    ))
748223×
    .bind(&scope.owner)
749223×
    .bind(&scope.owner)
750223×
    .bind(scope.repo_id)
751223×
    .bind(scope.repo_id)
752223×
    // A repository on its own runners only (#225): the site's runners skip it.
753223×
    .bind(&scope.owner)
754223×
    .bind(scope.repo_id)
755223×
    .fetch_all(&mut *tx)
756223×
    .await?;
757223×
    for j in queued {
758180×
        if !runtimes.iter().any(|r| r == &j.runtime)
759177×
            || !room.fits(&j.sandbox)
760168×
            || !room.disk_fits(j.need_disk_mib)
761167×
            || room.declined.contains(&j.id)
762
        {
76314×
            continue;
764166×
        }
765
        // Every label the job and its sandbox ask for (`runs-on`).
766166×
        if !j.needs().iter().all(|l| labels.contains(l)) {
7672×
            continue;
768164×
        }
769164×
        let deps = j.depends_on();
770
        // When it became ready: queued, its dependencies passed, approved.
771164×
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
772164×
        if !deps.is_empty() {
77335×
            let mut passed = 0i64;
77435×
            for d in &deps {
77535×
                let st: Option<(String, Option<i64>)> =
77635×
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
77735×
                        .bind(j.run_id)
77835×
                        .bind(d)
77935×
                        .fetch_optional(&mut *tx)
78035×
                        .await?;
78135×
                if let Some((status, finished)) = st {
78235×
                    if status == "passed" {
78330×
                        passed += 1;
78430×
                        ready = ready.max(finished.unwrap_or(0));
78530×
                    }
7860×
                }
787
            }
78835×
            if passed != deps.len() as i64 {
7895×
                continue;
79030×
            }
791129×
        }
792159×
        if elsewhere(&j) {
7933×
            continue;
794156×
        }
795156×
        let now = now_ms();
796156×
        let done = sqlx::query(
797156×
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
798156×
             WHERE id = $4 AND status = 'queued'",
799
        )
800156×
        .bind(runner)
801156×
        .bind(token_hash)
802156×
        .bind(now)
803156×
        .bind(j.id)
804156×
        .bind(if ready > 0 { ready.min(now) } else { now })
805156×
        .execute(&mut *tx)
806156×
        .await?;
807156×
        if done.rows_affected() == 1 {
808156×
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
809156×
                .bind(j.run_id)
810156×
                .execute(&mut *tx)
811156×
                .await?;
812156×
            tx.commit().await?;
813156×
            return job(pool, j.id).await;
8140×
        }
815
    }
81667×
    tx.commit().await?;
81767×
    Ok(None)
818223×
}
819
820
/// How long a decline keeps a job from its runner when the runner's
821
/// profile stays the same: a reason such as memory in use passes.
822
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
823
824
/// The jobs runner `runner_id` declined with this profile, recently.
825223×
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
826223×
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
827223×
        .bind(runner_id)
828223×
        .bind(profile)
829223×
        .bind(now_ms() - DECLINE_HOLDS_MS)
830223×
        .fetch_all(pool)
831223×
        .await?;
832223×
    Ok(rows.into_iter().map(|(j,)| j).collect())
833223×
}
834
835
/// A decline: one runner's reason for handing a job back.
836
#[derive(Clone, Debug, sqlx::FromRow)]
837
pub struct DeclineRow {
838
    pub job_id: i64,
839
    pub runner_id: i64,
840
    pub runner: String,
841
    pub reason: String,
842
    pub ms: i64,
843
}
844
845
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
846
/// is kept (one per job and runner, the latest), and the job is queued
847
/// again. Returns every decline the job has had, or `None` when the job
848
/// was not running on that runner.
8494×
pub async fn decline(
8504×
    pool: &Pool,
8514×
    job_id: i64,
8524×
    runner_id: i64,
8534×
    runner: &str,
8544×
    profile: &str,
8554×
    reason: &str,
8564×
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
8574×
    let mut tx = super::begin_write(pool).await?;
8584×
    let back = sqlx::query(
8594×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
8604×
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
8614×
    )
8624×
    .bind(job_id)
8634×
    .bind(runner_id)
8644×
    .execute(&mut *tx)
8654×
    .await?;
8664×
    if back.rows_affected() != 1 {
8671×
        tx.rollback().await?;
8681×
        return Ok(None);
8693×
    }
8703×
    sqlx::query(
8713×
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
8723×
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
8733×
    )
8743×
    .bind(job_id)
8753×
    .bind(runner_id)
8763×
    .bind(runner)
8773×
    .bind(profile)
8783×
    .bind(reason)
8793×
    .bind(now_ms())
8803×
    .execute(&mut *tx)
8813×
    .await?;
8823×
    let all: Vec<DeclineRow> =
8833×
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
8843×
            .bind(job_id)
8853×
            .fetch_all(&mut *tx)
8863×
            .await?;
8873×
    tx.commit().await?;
8883×
    Ok(Some(all))
8894×
}
890
891
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
892
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
893
/// its runner's lease lapsed. Its log is kept and its next attempt's
894
/// follows on. Returns how many times it has now been handed back, or
895
/// `None` when it was not running there.
8963×
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
8973×
    let mut tx = super::begin_write(pool).await?;
8983×
    let now = now_ms();
8993×
    let back = sqlx::query(
9003×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
9013×
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
9023×
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
9033×
    )
9043×
    .bind(now)
9053×
    .bind(now)
9063×
    .bind(job_id)
9073×
    .bind(runner_id)
9083×
    .bind(runner_id)
9093×
    .execute(&mut *tx)
9103×
    .await?;
9113×
    if back.rows_affected() != 1 {
9121×
        tx.rollback().await?;
9131×
        return Ok(None);
9142×
    }
9152×
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
9162×
    tx.commit().await?;
9172×
    Ok(Some(n))
9183×
}
919
920
/// How long job `name` of repository `repo_id` is expected to take: the
921
/// median of its last five passing runs (claimed to finished), passes
922
/// reused from another run left out (oxygenflow#76). `None` before it has
923
/// passed: a runner leaving then hands it back rather than guess.
924156×
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
925156×
    let mut times: Vec<i64> = sqlx::query_scalar(
926156×
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
927156×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
928156×
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
929156×
    )
930156×
    .bind(repo_id)
931156×
    .bind(name)
932156×
    .fetch_all(pool)
933156×
    .await?;
934156×
    times.sort_unstable();
935156×
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
936156×
}
937
938
/// Jobs running on a runner the hub has not heard from since `before`
939
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
9401×
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
9411×
    let rows: Vec<(i64, String)> = sqlx::query_as(
9421×
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
9431×
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
9441×
    )
9451×
    .bind(before)
9461×
    .fetch_all(pool)
9471×
    .await?;
9481×
    let mut out = Vec::new();
9491×
    for (id, runner) in rows {
9501×
        if let Some(j) = job(pool, id).await? {
9511×
            out.push((j, runner));
9521×
        }
953
    }
9541×
    Ok(out)
9551×
}
956
957
/// The declines of job `job_id`, oldest first.
95813×
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
95913×
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
96013×
        .bind(job_id)
96113×
        .fetch_all(pool)
96213×
        .await
96313×
}
964
965
/// A runner's latest declines, newest first, with where the job is.
966
#[derive(Clone, Debug, sqlx::FromRow)]
967
pub struct RunnerDecline {
968
    pub job_id: i64,
969
    pub job: String,
970
    pub run_number: i64,
971
    pub owner: String,
972
    pub name: String,
973
    pub reason: String,
974
    pub ms: i64,
975
}
976
9774×
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
9784×
    sqlx::query_as(
9794×
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
9804×
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
9814×
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
9824×
    )
9834×
    .bind(runner_id)
9844×
    .bind(limit)
9854×
    .fetch_all(pool)
9864×
    .await
9874×
}
988
989
/// Queued jobs whose dependencies have passed, in their live runs, with
990
/// their repositories (owner, id): the ones a runner could take now.
991
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
992
/// (#259: how many ready jobs come first).
9937×
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
9947×
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
9957×
        "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 \
9967×
         WHERE j.status = 'queued'"
9977×
    ))
9987×
    .fetch_all(pool)
9997×
    .await?;
10007×
    Ok(rows.into_iter().collect())
10017×
}
1002
1003
/// How many jobs each runner is running now, by runner id (#259).
10047×
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
10057×
    let rows: Vec<(i64, i64)> =
10067×
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
10077×
            .fetch_all(pool)
10087×
            .await?;
10097×
    Ok(rows.into_iter().collect())
10107×
}
1011
10128×
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
10138×
    let queued: Vec<Job> = sqlx::query_as(
10148×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
10158×
         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",
10168×
    )
10178×
    .fetch_all(pool)
10188×
    .await?;
10198×
    let mut out = Vec::new();
102019×
    for j in queued {
102119×
        let mut ready = true;
102219×
        for d in j.depends_on() {
10237×
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
10247×
                .bind(j.run_id)
10257×
                .bind(&d)
10267×
                .fetch_optional(pool)
10277×
                .await?;
10287×
            if st.as_deref() != Some("passed") {
10297×
                ready = false;
10307×
                break;
10310×
            }
1032
        }
103319×
        if !ready {
10347×
            continue;
103512×
        }
103612×
        let repo: Option<(String, i64)> =
103712×
            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")
103812×
                .bind(j.run_id)
103912×
                .fetch_optional(pool)
104012×
                .await?;
104112×
        if let Some((owner, id)) = repo {
104212×
            out.push((j, owner, id));
104312×
        }
1044
    }
10458×
    Ok(out)
10468×
}
1047
104814×
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
104914×
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
105014×
        .bind(waiting)
105114×
        .bind(job_id)
105214×
        .bind(waiting)
105314×
        .execute(pool)
105414×
        .await?;
105514×
    Ok(())
105614×
}
1057
1058
/// Append records; returns how many were kept (the rest exceed the cap).
105944×
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
106044×
    let mut tx = super::begin_write(pool).await?;
106144×
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
106244×
    let room = (cap - count).max(0) as usize;
106344×
    let keep = &records[..records.len().min(room)];
1064361×
    for (i, r) in keep.iter().enumerate() {
1065361×
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1066361×
            .bind(job_id)
1067361×
            .bind(count + i as i64 + 1)
1068361×
            .bind(r.t as i64)
1069361×
            .bind(&r.stream)
1070361×
            .bind(&r.text)
1071361×
            .execute(&mut *tx)
1072361×
            .await?;
1073
    }
107444×
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
107544×
        .bind(keep.len() as i64)
107644×
        .bind(job_id)
107744×
        .execute(&mut *tx)
107844×
        .await?;
107944×
    tx.commit().await?;
108044×
    Ok(keep.len())
108144×
}
1082
108370×
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
108470×
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
108570×
        .bind(job_id)
108670×
        .bind(after)
108770×
        .bind(limit)
108870×
        .fetch_all(pool)
108970×
        .await
109070×
}
1091
1092
/// Jobs running since before `ms` (the oldest first).
1093
/// Jobs still running at `now` past their own time limit (`default_s` for
1094
/// one claimed without) plus `grace_ms`.
10953×
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
10963×
    sqlx::query_as(
10973×
        "SELECT * FROM flow_jobs WHERE status = 'running' \
10983×
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
10993×
    )
11003×
    .bind(default_s as i64)
11013×
    .bind(grace_ms)
11023×
    .bind(now)
11033×
    .fetch_all(pool)
11043×
    .await
11053×
}
1106
1107
/// Record the limit a claimed job runs under.
1108156×
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1109156×
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1110156×
    Ok(())
1111156×
}
1112
11130×
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
11140×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
11150×
        .bind(ms)
11160×
        .fetch_all(pool)
11170×
        .await
11180×
}
1119
1120
/// The jobs running on the runner with this id.
11212×
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
11222×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
11232×
}
1124
1125
pub struct Outcome<'a> {
1126
    pub status: &'a str,
1127
    pub exit_code: Option<i64>,
1128
    pub error: &'a str,
1129
    pub receipt: &'a str,
1130
    pub receipt_hash: &'a str,
1131
}
1132
1133
/// Record a job's end, skip the jobs that can no longer run, and settle the
1134
/// run. Returns the jobs whose status changed (for their checks).
1135104×
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1136104×
    let mut tx = super::begin_write(pool).await?;
1137104×
    let now = now_ms();
1138104×
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1139104×
    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")
1140104×
        .bind(o.status)
1141104×
        .bind(o.exit_code)
1142104×
        .bind(o.error)
1143104×
        .bind(o.receipt)
1144104×
        .bind(o.receipt_hash)
1145104×
        .bind(now)
1146104×
        .bind(job_id)
1147104×
        .execute(&mut *tx)
1148104×
        .await?;
1149
    // A pass teaches what its image is for, when nobody has read it
1150
    // (oxygenhub#173): the architecture of the runner it passed on.
1151104×
    if o.status == "passed" {
115285×
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
115385×
            .ok()
115485×
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
115585×
            .unwrap_or_default();
115685×
        if rootfs.len() == 64 {
115785×
            sqlx::query(
115885×
                "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 \
115985×
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
116085×
            )
116185×
            .bind(&rootfs)
116285×
            .bind(now)
116385×
            .bind(job_id)
116485×
            .execute(&mut *tx)
116585×
            .await?;
11660×
        }
116719×
    }
1168104×
    let mut changed = vec![job_id];
1169
    // Dependents of anything that did not pass are skipped, transitively.
1170
    loop {
1171112×
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1172112×
        let blocked: Vec<i64> = all
1173112×
            .iter()
1174315×
            .filter(|x| x.status == "queued")
1175112×
            .filter(|x| {
117692×
                x.depends_on()
117792×
                    .iter()
1178169×
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
117992×
            })
1180112×
            .map(|x| x.id)
1181112×
            .collect();
1182112×
        if blocked.is_empty() {
1183104×
            break;
11848×
        }
11858×
        for id in blocked {
11868×
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
11878×
                .bind(now)
11888×
                .bind(id)
11898×
                .execute(&mut *tx)
11908×
                .await?;
11918×
            changed.push(id);
1192
        }
1193
    }
1194104×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1195104×
    if all.iter().all(Job::done) {
119690×
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
119741×
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
119841×
            .bind(status)
119941×
            .bind(now)
120041×
            .bind(j.run_id)
120141×
            .execute(&mut *tx)
120241×
            .await?;
120363×
    }
1204104×
    tx.commit().await?;
1205104×
    let mut out = Vec::new();
1206112×
    for id in changed {
1207112×
        if let Some(x) = job(pool, id).await? {
1208112×
            out.push(x);
1209112×
        }
1210
    }
1211104×
    Ok(out)
1212104×
}
1213
1214
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1215
/// and so does the run. A runner learns of it when the hub next refuses
1216
/// its log lines, and stops the job. Returns the jobs whose status changed.
121716×
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
121816×
    let now = now_ms();
121916×
    let mut tx = pool.begin().await?;
122016×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
122116×
        .bind(run_id)
122216×
        .fetch_all(&mut *tx)
122316×
        .await?;
122416×
    sqlx::query(
122516×
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
122616×
         WHERE run_id = $3 AND status IN ('queued', 'running')",
122716×
    )
122816×
    .bind(why)
122916×
    .bind(now)
123016×
    .bind(run_id)
123116×
    .execute(&mut *tx)
123216×
    .await?;
123316×
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
123416×
        .bind(now)
123516×
        .bind(run_id)
123616×
        .execute(&mut *tx)
123716×
        .await?;
123816×
    tx.commit().await?;
123916×
    let mut out = Vec::new();
124040×
    for (id,) in ids {
124140×
        if let Some(x) = job(pool, id).await? {
124240×
            out.push(x);
124340×
        }
1244
    }
124516×
    Ok(out)
124616×
}
1247
1248
/// Run job `name` of finished run `run_id` again, with every job that
1249
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1250
/// artifacts and reports gone, and the run running again. The jobs they
1251
/// depend on keep their results. The jobs reset; none when there is no
1252
/// such job.
12532×
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
12542×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
12554×
    if !all.iter().any(|j| j.name == name) {
12560×
        return Ok(Vec::new());
12572×
    }
12582×
    let mut again = vec![name.to_string()];
1259
    loop {
12603×
        let more: Vec<String> = all
12613×
            .iter()
12629×
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
12633×
            .map(|j| j.name.clone())
12643×
            .collect();
12653×
        if more.is_empty() {
12662×
            break;
12671×
        }
12681×
        again.extend(more);
1269
    }
12706×
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
12712×
    let mut tx = pool.begin().await?;
12723×
    for id in &ids {
127318×
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
127418×
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1275
        }
12763×
        sqlx::query(
12773×
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
12783×
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
12793×
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
12803×
             peak_memory_mib = NULL, approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
12813×
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
12823×
             handbacks = 0 WHERE id = $1",
12833×
        )
12843×
        .bind(id)
12853×
        .bind(now_ms())
12863×
        .execute(&mut *tx)
12873×
        .await?;
1288
    }
12892×
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
12902×
    tx.commit().await?;
12912×
    let mut out = Vec::new();
12923×
    for id in ids {
12933×
        if let Some(x) = job(pool, id).await? {
12943×
            out.push(x);
12953×
        }
1296
    }
12972×
    Ok(out)
12982×
}
1299
1300
/// The runs of `bookmark` started by `trigger` still going, older than run
1301
/// `number`: those a newer run supersedes (#267). With `running_too`
1302
/// false, only those still queued.
1303120×
pub async fn live_runs_before(
1304120×
    pool: &Pool,
1305120×
    repo_id: i64,
1306120×
    bookmark: &str,
1307120×
    trigger: &str,
1308120×
    number: i64,
1309120×
    running_too: bool,
1310120×
) -> sqlx::Result<Vec<Run>> {
1311120×
    sqlx::query_as(
1312120×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1313120×
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1314120×
    )
1315120×
    .bind(repo_id)
1316120×
    .bind(bookmark)
1317120×
    .bind(number)
1318120×
    .bind(trigger)
1319120×
    .bind(running_too)
1320120×
    .fetch_all(pool)
1321120×
    .await
1322120×
}
1323
1324
/// The runs on `bookmark` that no runner has started yet: queued, with
1325
/// the given trigger, created before `before_ms` (#263).
132640×
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
132740×
    sqlx::query_as(
132840×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
132940×
    )
133040×
    .bind(repo_id)
133140×
    .bind(bookmark)
133240×
    .bind(trigger)
133340×
    .bind(before_ms)
133440×
    .fetch_all(pool)
133540×
    .await
133640×
}
1337
1338
/// The newest run of exactly this state (heads joined with `+`, sorted).
13396×
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
13406×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
13416×
        .bind(repo_id)
13426×
        .bind(heads)
13436×
        .fetch_optional(pool)
13446×
        .await
13456×
}
1346
1347
/// Record what became of job `job_id`'s signed receipt.
13488×
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
13498×
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
13508×
        .bind(attest)
13518×
        .bind(signer)
13528×
        .bind(note)
13538×
        .bind(job_id)
13548×
        .execute(pool)
13558×
        .await?;
13568×
    Ok(())
13578×
}
1358
1359
/// A job's artifact, kept as a blob of the run's repository.
1360
#[derive(Clone, Debug, FromRow)]
1361
pub struct Artifact {
1362
    pub job_id: i64,
1363
    pub name: String,
1364
    pub path: String,
1365
    pub blob: String,
1366
    pub size: i64,
1367
    /// BLAKE3 of the bytes.
1368
    pub content: String,
1369
    pub created_ms: i64,
1370
}
1371
137214×
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
137314×
    sqlx::query(
137414×
        "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",
137514×
    )
137614×
    .bind(a.job_id)
137714×
    .bind(&a.name)
137814×
    .bind(&a.path)
137914×
    .bind(&a.blob)
138014×
    .bind(a.size)
138114×
    .bind(&a.content)
138214×
    .bind(a.created_ms)
138314×
    .execute(pool)
138414×
    .await?;
138514×
    Ok(())
138614×
}
1387
1388
/// Every artifact blob a repository's runs keep, for garbage collection to
1389
/// keep too (#126): the database is the only thing that names them.
13904×
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
13914×
    sqlx::query_scalar(
13924×
        "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",
13934×
    )
13944×
    .bind(repo_id)
13954×
    .fetch_all(pool)
13964×
    .await
13974×
}
1398
1399
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1400
/// receipt names.
1401146×
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1402146×
    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
1403146×
}
1404
1405
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1406
/// artifacts: no pipeline can declare it.
1407
pub const CHECKPOINT: &str = ".checkpoint";
1408
1409
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1410
/// back (oxygenflow#77), if one did.
14113×
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
14123×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
14133×
}
1414
1415
/// An artifact with the run and job that made it, for a repository's list
1416
/// of every run's outputs (oxygenhub#254).
1417
#[derive(Clone, Debug, FromRow)]
1418
pub struct RepoArtifact {
1419
    pub run_number: i64,
1420
    pub bookmark: String,
1421
    pub job: String,
1422
    pub name: String,
1423
    pub path: String,
1424
    pub size: i64,
1425
    pub content: String,
1426
    pub created_ms: i64,
1427
}
1428
1429
/// A repository's newest artifacts, at most `limit`.
14302×
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
14312×
    sqlx::query_as(
14322×
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
14332×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
14342×
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
14352×
    )
14362×
    .bind(repo_id)
14372×
    .bind(limit)
14382×
    .fetch_all(pool)
14392×
    .await
14402×
}
1441
1442
/// Where an artifact with given content came from: the run and job that
1443
/// built it, and the job's signed receipt when one was kept.
1444
#[derive(Clone, Debug, FromRow)]
1445
pub struct Provenance {
1446
    pub run_number: i64,
1447
    pub job: String,
1448
    pub name: String,
1449
    pub receipt_attest: String,
1450
    pub receipt_signer: String,
1451
}
1452
1453
/// The build of the bytes whose BLAKE3 is `content` in repository
1454
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1455
/// run first.
145621×
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
145721×
    sqlx::query_as(
145821×
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
145921×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
146021×
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
146121×
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
146221×
    )
146321×
    .bind(repo_id)
146421×
    .bind(content)
146521×
    .fetch_optional(pool)
146621×
    .await
146721×
}
1468
1469
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1470
/// whether it was.
14712×
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
14722×
    let r = sqlx::query(
14732×
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
14742×
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
14752×
    )
14762×
    .bind(who)
14772×
    .bind(now_ms())
14782×
    .bind(seal)
14792×
    .bind(id)
14802×
    .bind(via)
14812×
    .execute(pool)
14822×
    .await?;
14832×
    Ok(r.rows_affected() > 0)
14842×
}
1485
1486
/// Note who rejected job `id` (it is then finished as cancelled).
14871×
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
14881×
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
14891×
        .bind(who)
14901×
        .bind(now_ms())
14911×
        .bind(id)
14921×
        .bind(via)
14931×
        .execute(pool)
14941×
        .await?;
14951×
    Ok(())
14961×
}
1497
1498
/// Jobs waiting for a person, in runs still going.
14992×
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
15002×
    sqlx::query_as(
15012×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15022×
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
15032×
    )
15042×
    .fetch_all(pool)
15052×
    .await
15062×
}
1507
1508
/// One deployment: a job for an environment that passed.
1509
#[derive(Clone, Debug, FromRow)]
1510
pub struct Deployment {
1511
    pub environment: String,
1512
    pub job: String,
1513
    pub run_number: i64,
1514
    pub state: String,
1515
    pub bookmark: String,
1516
    pub actor: String,
1517
    pub approved_by: String,
1518
    pub finished_ms: i64,
1519
}
1520
1521
/// A repository's deployments, newest first (oxygenflow#59).
15222×
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
15232×
    sqlx::query_as(
15242×
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
15252×
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
15262×
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
15272×
    )
15282×
    .bind(repo_id)
15292×
    .bind(limit)
15302×
    .fetch_all(pool)
15312×
    .await
15322×
}