OXYGENHUB

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

1112 of 1148 lines run, 184 of 376 functions · run #515 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.
714×
pub async fn expedited_live(pool: &Pool, owner: &str) -> sqlx::Result<i64> {
724×
    sqlx::query_scalar(
734×
        "SELECT COUNT(*) FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id \
744×
         WHERE rep.owner = $1 AND r.priority = 'urgent' AND r.status IN ('queued', 'running')",
754×
    )
764×
    .bind(owner)
774×
    .fetch_one(pool)
784×
    .await
794×
}
80
81
/// Raise run `run_id` to urgent, saying who and why; a run already ended
82
/// is left alone. Whether it changed.
834×
pub async fn expedite(pool: &Pool, run_id: i64, note: &str) -> sqlx::Result<bool> {
844×
    let r = sqlx::query("UPDATE flow_runs SET priority = 'urgent', priority_note = $1 WHERE id = $2 AND status IN ('queued', 'running')")
854×
        .bind(note)
864×
        .bind(run_id)
874×
        .execute(pool)
884×
        .await?;
894×
    Ok(r.rows_affected() > 0)
904×
}
91
92
impl Run {
93
    /// How the run page says what started it.
9423×
    pub fn started_by(&self) -> String {
9523×
        match self.trigger.as_str() {
9623×
            "manual" => format!("started by {}", self.actor),
9721×
            "schedule" => "started on schedule".to_string(),
9821×
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
9921×
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
10020×
            _ => format!("pushed by {}", self.actor),
101
        }
10223×
    }
103
104
    /// The run a rerun repeats: `N` of `rerun:N` or `rerun:N:EVENT`.
10513×
    pub fn rerun_of(&self) -> Option<&str> {
10613×
        let rest = self.trigger.strip_prefix("rerun:")?;
1072×
        Some(rest.split(':').next().unwrap_or(rest))
10813×
    }
109
110
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
11112×
    pub fn trigger_label(&self) -> String {
11212×
        match self.rerun_of() {
1131×
            Some(n) => format!("rerun:{n}"),
11411×
            None => self.trigger.clone(),
115
        }
11612×
    }
117
118410×
    pub fn head_list(&self) -> Vec<&str> {
119542×
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
120410×
    }
121
122177×
    pub fn live(&self) -> bool {
123177×
        matches!(self.status.as_str(), "queued" | "running")
124177×
    }
125
}
126
127
#[derive(Clone, Debug, Default, FromRow)]
128
pub struct Job {
129
    pub id: i64,
130
    pub run_id: i64,
131
    pub name: String,
132
    pub depth: i64,
133
    pub depends: String,
134
    pub spec: String,
135
    pub sandbox: String,
136
    pub runtime: String,
137
    pub status: String,
138
    pub runner: String,
139
    pub token_hash: String,
140
    pub started_ms: Option<i64>,
141
    pub finished_ms: Option<i64>,
142
    pub exit_code: Option<i64>,
143
    pub error: String,
144
    pub receipt: String,
145
    pub receipt_hash: String,
146
    pub log_count: i64,
147
    /// Comma-separated ids of other repositories the job token may read.
148
    pub also_read: String,
149
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
150
    pub receipt_attest: String,
151
    /// Who signed it: the runner's identity name.
152
    pub receipt_signer: String,
153
    /// Why a signed receipt was not kept.
154
    pub receipt_note: String,
155
    /// Why a queued job no runner can take waits (spec §11.4), from the
156
    /// last placement pass; empty when it is only waiting its turn.
157
    pub waiting: String,
158
    /// What it took, as its runner reported (oxygenflow#41), in MiB.
159
    pub peak_disk_mib: Option<i64>,
160
    pub peak_memory_mib: Option<i64>,
161
    /// Where its time went, JSON of phase to milliseconds (oxygenflow#35).
162
    #[sqlx(default)]
163
    pub phases: String,
164
    /// The free disk it needs, learned from past runs of the same job.
165
    pub need_disk_mib: Option<i64>,
166
    /// Why it ran on its runner (oxygenflow#42).
167
    pub placed: String,
168
    /// `waiting` for a person, `approved`, or empty (oxygenflow#57).
169
    pub approval: String,
170
    /// Who approved or rejected it, and when.
171
    pub approved_by: String,
172
    pub approved_ms: Option<i64>,
173
    /// The agent token it was decided through, if one (oxygenhub#229).
174
    #[sqlx(default)]
175
    pub approved_via: String,
176
    /// The environment it deploys to, or empty (oxygenflow#59).
177
    pub environment: String,
178
    /// The approval attestation that released it, when sealed (#235).
179
    pub approval_seal: String,
180
    /// When it entered the queue (made, or run again), and when it became
181
    /// ready to run: set at its claim (migration 0080, oxygenhub#257).
182
    #[sqlx(default)]
183
    pub queued_ms: Option<i64>,
184
    #[sqlx(default)]
185
    pub ready_ms: Option<i64>,
186
    /// When a runner last handed it back, drained or with its lease lapsed
187
    /// (oxygenflow#76, migration 0094), and how many times: such a job is
188
    /// queued ahead of new work.
189
    #[sqlx(default)]
190
    pub handed_back_ms: Option<i64>,
191
    #[sqlx(default)]
192
    pub handbacks: i64,
193
}
194
195
impl Job {
196
    /// Where its time went, as its runner reported (oxygenflow#35): each
197
    /// phase it took, in the order it took them, with its milliseconds.
19854×
    pub fn phase_list(&self) -> Vec<(String, u64)> {
19954×
        let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(&self.phases).unwrap_or_default();
200216×
        ["image", "prepare", "run", "finish"].iter().filter_map(|p| m.get(*p).map(|ms| (p.to_string(), *ms))).collect()
20154×
    }
202
203
    /// The run whose pass this job reused (#265), if it did: in this
204
    /// repository, or in the one [`Job::reused_repo`] names (#296).
205156×
    pub fn reused_from(&self) -> Option<i64> {
206156×
        self.error.strip_prefix("reused from ")?.rsplit_once("run #")?.1.parse().ok()
207156×
    }
208
209
    /// The repository (`owner/name`) whose pass this job reused, when not
210
    /// its own: a fork reusing what upstream proved (#296).
211118×
    pub fn reused_repo(&self) -> Option<&str> {
212118×
        let rest = self.error.strip_prefix("reused from ")?;
21330×
        let (repo, n) = rest.rsplit_once(" run #")?;
21418×
        n.parse::<i64>().ok()?;
21518×
        Some(repo).filter(|r| !r.is_empty())
216118×
    }
217
218415×
    pub fn depends_on(&self) -> Vec<String> {
219415×
        serde_json::from_str(&self.depends).unwrap_or_default()
220415×
    }
221
222252×
    pub fn done(&self) -> bool {
223252×
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
224252×
    }
225
}
226
227
#[derive(Clone, Debug, FromRow)]
228
pub struct LogLine {
229
    pub seq: i64,
230
    pub t: i64,
231
    pub stream: String,
232
    pub text: String,
233
}
234
235
/// A job as the trigger creates it.
236
pub struct NewJob {
237
    pub name: String,
238
    pub depth: i64,
239
    pub depends: Vec<String>,
240
    pub spec: String,
241
    pub sandbox: String,
242
    pub runtime: String,
243
    /// The free disk it needs, from [`learned_disk_need`].
244
    pub need_disk_mib: Option<i64>,
245
    /// A pass on the same state to reuse instead of running it (#265): the
246
    /// job is created passed, with that pass's receipt.
247
    pub reused: Option<Reused>,
248
}
249
250
/// A job's earlier pass on the same state, spec and sandbox (#265).
251
#[derive(Clone, Debug)]
252
pub struct Reused {
253
    /// The repository it passed in, `owner/name`, when not this one (#296).
254
    pub repo: Option<String>,
255
    /// The run it passed in.
256
    pub run_number: i64,
257
    pub receipt: String,
258
    pub receipt_hash: String,
259
    pub receipt_attest: String,
260
    pub receipt_signer: String,
261
    pub receipt_note: String,
262
}
263
264
impl Reused {
265
    /// What the reused job says, and how [`Job::reused_from`] reads it back.
26617×
    pub fn note(&self) -> String {
26717×
        match &self.repo {
2688×
            Some(r) => format!("reused from {r} run #{}", self.run_number),
2699×
            None => format!("reused from run #{}", self.run_number),
270
        }
27117×
    }
272
}
273
274
/// The newest pass of job `name` with exactly this spec and sandbox on
275
/// `state` in this repository (#265).
276306×
pub async fn passed_on_state(
277306×
    pool: &Pool,
278306×
    repo_id: i64,
279306×
    state: &str,
280306×
    name: &str,
281306×
    spec: &str,
282306×
    sandbox: &str,
283306×
) -> sqlx::Result<Option<Reused>> {
284306×
    passed_in(pool, repo_id, state, name, spec, sandbox, false).await
285306×
}
286
287
/// As [`passed_on_state`]; with `ran_here`, only a job that ran in that
288
/// repository, not one it reused: its signed receipt is in that
289
/// repository's store, where another repository's reuse checks it (#296).
290312×
async fn passed_in(
291312×
    pool: &Pool,
292312×
    repo_id: i64,
293312×
    state: &str,
294312×
    name: &str,
295312×
    spec: &str,
296312×
    sandbox: &str,
297312×
    ran_here: bool,
298312×
) -> sqlx::Result<Option<Reused>> {
299312×
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
300312×
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
301312×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
302312×
         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' \
303312×
           AND (NOT $6 OR j.error NOT LIKE 'reused from %') \
304312×
         ORDER BY j.id DESC LIMIT 1",
305312×
    )
306312×
    .bind(repo_id)
307312×
    .bind(state)
308312×
    .bind(name)
309312×
    .bind(spec)
310312×
    .bind(sandbox)
311312×
    .bind(ran_here)
312312×
    .fetch_optional(pool)
313312×
    .await?;
314312×
    Ok(row.map(|(run_number, receipt, receipt_hash, receipt_attest, receipt_signer, receipt_note)| Reused {
31515×
        repo: None,
31615×
        run_number,
31715×
        receipt,
31815×
        receipt_hash,
31915×
        receipt_attest,
32015×
        receipt_signer,
32115×
        receipt_note,
32215×
    }))
323312×
}
324
325
/// How far up a fork's line [`passed_upstream`] looks.
326
const UPSTREAM_DEPTH: usize = 5;
327
328
/// A pass of job `name` with this spec and sandbox on `state` in a
329
/// repository `repo` was forked from, nearest first (#296): the same state
330
/// is the same changes, so what upstream proved holds for the fork. Only
331
/// from an upstream that is public or has the fork's owner, so a private
332
/// repository's receipts never show in another owner's fork.
3336×
pub async fn passed_upstream(
3346×
    pool: &Pool,
3356×
    repo: &super::repos::RepoRow,
3366×
    state: &str,
3376×
    name: &str,
3386×
    spec: &str,
3396×
    sandbox: &str,
3406×
) -> sqlx::Result<Option<Reused>> {
3416×
    let mut parent = repo.forked_from;
3426×
    for _ in 0..UPSTREAM_DEPTH {
3436×
        let Some(id) = parent else { break };
3446×
        let Some(up) = super::repos::get_by_id(pool, id).await? else { break };
3456×
        parent = up.forked_from;
3466×
        if !(up.visibility == "public" || up.owner == repo.owner) {
3470×
            continue;
3486×
        }
3496×
        if let Some(mut r) = passed_in(pool, up.id, state, name, spec, sandbox, true).await? {
3506×
            r.repo = Some(format!("{}/{}", up.owner, up.name));
3516×
            return Ok(Some(r));
3520×
        }
353
    }
3540×
    Ok(None)
3556×
}
356
357
/// A pass of job `name` with this spec and sandbox on `state` in any other
358
/// repository on the hub (#296): a state is its changes, so whoever proved
359
/// it, the proof holds here. Only from a repository that is public or has
360
/// this one's owner, newest first. After [`passed_upstream`], which
361
/// prefers the repository's own line.
362291×
pub async fn passed_elsewhere(
363291×
    pool: &Pool,
364291×
    repo: &super::repos::RepoRow,
365291×
    state: &str,
366291×
    name: &str,
367291×
    spec: &str,
368291×
    sandbox: &str,
369291×
) -> sqlx::Result<Option<Reused>> {
370
    #[derive(FromRow)]
371
    struct Pass {
372
        owner: String,
373
        name: String,
374
        number: i64,
375
        receipt: String,
376
        receipt_hash: String,
377
        receipt_attest: String,
378
        receipt_signer: String,
379
        receipt_note: String,
380
    }
381291×
    let pass: Option<Pass> = sqlx::query_as(
382291×
        "SELECT o.owner, o.name, r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
383291×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories o ON o.id = r.repo_id \
384291×
         WHERE r.state = $1 AND j.name = $2 AND j.spec = $3 AND j.sandbox = $4 AND j.status = 'passed' \
385291×
           AND o.id <> $5 AND (o.visibility = 'public' OR o.owner = $6) AND j.error NOT LIKE 'reused from %' \
386291×
         ORDER BY j.id DESC LIMIT 1",
387291×
    )
388291×
    .bind(state)
389291×
    .bind(name)
390291×
    .bind(spec)
391291×
    .bind(sandbox)
392291×
    .bind(repo.id)
393291×
    .bind(&repo.owner)
394291×
    .fetch_optional(pool)
395291×
    .await?;
396291×
    Ok(pass.map(|p| Reused {
3973×
        repo: Some(format!("{}/{}", p.owner, p.name)),
3983×
        run_number: p.number,
3993×
        receipt: p.receipt,
4003×
        receipt_hash: p.receipt_hash,
4013×
        receipt_attest: p.receipt_attest,
4023×
        receipt_signer: p.receipt_signer,
4033×
        receipt_note: p.receipt_note,
4043×
    }))
405291×
}
406
407
/// Runs of a job whose peaks set its next need.
408
const NEED_FROM_RUNS: i64 = 5;
409
410
/// The free disk a new run of job `name` in repository `repo_id` needs
411
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
412
/// for a job that has not run here yet.
413375×
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
414375×
    let peak: Option<i64> = sqlx::query_scalar(
415375×
        "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 \
416375×
         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",
417375×
    )
418375×
    .bind(repo_id)
419375×
    .bind(name)
420375×
    .bind(NEED_FROM_RUNS)
421375×
    .fetch_one(pool)
422375×
    .await?;
423375×
    Ok(peak.map(|p| p + p / 4 + 64))
424375×
}
425
426
/// Record why job `job_id` ran where it did.
427159×
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
428159×
    sqlx::query("UPDATE flow_jobs SET placed = $1 WHERE id = $2").bind(placed).bind(job_id).execute(pool).await?;
429159×
    Ok(())
430159×
}
431
432
/// Keep what a job took, as its runner reported.
43398×
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
43498×
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = $1, peak_memory_mib = $2 WHERE id = $3")
43598×
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
43698×
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
43798×
        .bind(job_id)
43898×
        .execute(pool)
43998×
        .await?;
44098×
    Ok(())
44198×
}
442
443
/// Where a finished job's time went, as its runner reported (oxygenflow#35).
44498×
pub async fn set_phases(pool: &Pool, job_id: i64, phases: &std::collections::BTreeMap<String, u64>) -> sqlx::Result<()> {
44598×
    let json = if phases.is_empty() { String::new() } else { serde_json::to_string(phases).unwrap_or_default() };
44698×
    sqlx::query("UPDATE flow_jobs SET phases = $1 WHERE id = $2").bind(json).bind(job_id).execute(pool).await?;
44798×
    Ok(())
44898×
}
449
450
pub struct NewRun<'a> {
451
    pub repo_id: i64,
452
    pub bookmark: &'a str,
453
    pub state: &'a str,
454
    pub heads: &'a str,
455
    pub pipeline_hash: &'a str,
456
    pub actor: &'a str,
457
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
458
    /// `rerun:N:EVENT`.
459
    pub trigger: &'a str,
460
    /// Problems when the pipeline is invalid: the run is recorded in error.
461
    pub error: Option<&'a str>,
462
}
463
464
/// A push that asked for no run (#284): recorded, finished, as skipped,
465
/// with `why` (which change asked, and who pushed it) as its note.
4661×
pub async fn create_skipped_run(pool: &Pool, r: NewRun<'_>, why: &str) -> sqlx::Result<i64> {
4671×
    let mut tx = super::begin_write(pool).await?;
4681×
    let now = now_ms();
4691×
    let id: i64 = sqlx::query_scalar(
4701×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
4711×
         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",
4721×
    )
4731×
    .bind(r.repo_id)
4741×
    .bind(r.repo_id)
4751×
    .bind(r.bookmark)
4761×
    .bind(r.state)
4771×
    .bind(r.heads)
4781×
    .bind(r.pipeline_hash)
4791×
    .bind(why)
4801×
    .bind(r.actor)
4811×
    .bind(r.trigger)
4821×
    .bind(now)
4831×
    .bind(now)
4841×
    .fetch_one(&mut *tx)
4851×
    .await?;
4861×
    tx.commit().await?;
4871×
    Ok(id)
4881×
}
489
490145×
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
491145×
    let mut tx = super::begin_write(pool).await?;
492145×
    let now = now_ms();
493145×
    let status = if r.error.is_some() { "error" } else { "queued" };
494145×
    let id: i64 = sqlx::query_scalar(
495145×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
496145×
         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",
497
    )
498145×
    .bind(r.repo_id)
499145×
    .bind(r.repo_id)
500145×
    .bind(r.bookmark)
501145×
    .bind(r.state)
502145×
    .bind(r.heads)
503145×
    .bind(r.pipeline_hash)
504145×
    .bind(status)
505145×
    .bind(r.error.unwrap_or(""))
506145×
    .bind(r.actor)
507145×
    .bind(r.trigger)
508145×
    .bind(now)
509145×
    .bind(r.error.map(|_| now))
510145×
    .fetch_one(&mut *tx)
511145×
    .await?;
512379×
    for j in jobs {
513379×
        let job_id: i64 = sqlx::query_scalar(
514379×
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
515379×
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
516
        )
517379×
        .bind(id)
518379×
        .bind(&j.name)
519379×
        .bind(j.depth)
520379×
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
521379×
        .bind(&j.spec)
522379×
        .bind(&j.sandbox)
523379×
        .bind(&j.runtime)
524379×
        .bind(j.need_disk_mib)
525379×
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
526379×
        .bind(environment_of(&j.spec))
527379×
        .bind(priority_of(&j.spec))
528379×
        .bind(now)
529379×
        .fetch_one(&mut *tx)
530379×
        .await?;
531
        // A pass reused (#265): done before any runner can claim it.
532379×
        if let Some(r) = &j.reused {
53317×
            sqlx::query(
53417×
                "UPDATE flow_jobs SET status = 'passed', exit_code = 0, error = $1, receipt = $2, receipt_hash = $3, receipt_attest = $4, \
53517×
                 receipt_signer = $5, receipt_note = $6, started_ms = $7, finished_ms = $7 WHERE id = $8",
53617×
            )
53717×
            .bind(r.note())
53817×
            .bind(&r.receipt)
53917×
            .bind(&r.receipt_hash)
54017×
            .bind(&r.receipt_attest)
54117×
            .bind(&r.receipt_signer)
54217×
            .bind(&r.receipt_note)
54317×
            .bind(now)
54417×
            .bind(job_id)
54517×
            .execute(&mut *tx)
54617×
            .await?;
547362×
        }
548
    }
549
    // Every job reused: the run has passed already.
550154×
    if !jobs.is_empty() && jobs.iter().all(|j| j.reused.is_some()) {
5514×
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
552141×
    }
553145×
    tx.commit().await?;
554145×
    Ok(id)
555145×
}
556
557
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
558379×
fn environment_of(spec: &str) -> String {
559379×
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
560379×
}
561
562
/// A compiled job's own priority (`low`, `normal`), or empty; anything
563
/// else is not one a pipeline may give (oxygenhub#244).
564379×
fn priority_of(spec: &str) -> String {
565379×
    serde_json::from_str::<serde_json::Value>(spec)
566379×
        .ok()
567379×
        .and_then(|v| v["priority"].as_str().map(String::from))
568379×
        .filter(|p| p == "low" || p == "normal")
569379×
        .unwrap_or_default()
570379×
}
571
572
/// Whether a compiled job asks for approval (oxygenflow#57).
573379×
fn needs_approval(spec: &str) -> bool {
574379×
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
575379×
}
576
577
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
578211×
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
579211×
    let mut out: Vec<String> = [spec, sandbox]
580211×
        .iter()
581422×
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
582422×
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
583211×
        .filter_map(|l| l.as_str().map(String::from))
584211×
        .collect();
585211×
    out.sort();
586211×
    out.dedup();
587211×
    out
588211×
}
589
590
impl Job {
591
    /// The runner labels this job needs.
592200×
    pub fn needs(&self) -> Vec<String> {
593200×
        labels_in(&self.spec, &self.sandbox)
594200×
    }
595
596
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
59738×
    pub fn arch(&self) -> Option<String> {
59838×
        arch_in(&self.sandbox)
59938×
    }
600
}
601
602
/// The architecture a sandbox's JSON asks for, if any.
60348×
fn arch_in(sandbox: &str) -> Option<String> {
60448×
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
60548×
}
606
607
/// A job waiting for or held by a runner, with where it comes from.
608
#[derive(Clone, Debug, FromRow)]
609
pub struct QueueEntry {
610
    pub job_id: i64,
611
    pub run_id: i64,
612
    pub repo_id: i64,
613
    pub owner: String,
614
    pub name: String,
615
    pub visibility: String,
616
    pub run_number: i64,
617
    pub job: String,
618
    pub status: String,
619
    /// The runner holding it, when running.
620
    pub runner: String,
621
    pub spec: String,
622
    pub sandbox: String,
623
    /// When it started running.
624
    pub started_ms: Option<i64>,
625
    /// Its level (0 urgent … 3 low, oxygenhub#244) and, when expedited, who
626
    /// did it and why.
627
    pub priority_rank: i64,
628
    pub priority_note: String,
629
}
630
631
impl QueueEntry {
63222×
    pub fn priority(&self) -> &'static str {
63322×
        PRIORITIES.get(self.priority_rank as usize).copied().unwrap_or("normal")
63422×
    }
635
}
636
637
impl QueueEntry {
638
    /// The runner labels the job needs.
63911×
    pub fn needs(&self) -> Vec<String> {
64011×
        labels_in(&self.spec, &self.sandbox)
64111×
    }
642
643
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
64410×
    pub fn arch(&self) -> Option<String> {
64510×
        arch_in(&self.sandbox)
64610×
    }
647
}
648
649
/// Every job of a live run that is running or queued: running ones first,
650
/// then queued ones in the order runners claim them (hub spec §13.2).
651273×
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
652273×
    sqlx::query_as(&format!(
653273×
        "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, \
654273×
           CAST({PRIORITY_RANK} AS BIGINT) AS priority_rank, {PRIORITY_NOTE} AS priority_note \
655273×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
656273×
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
657273×
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, \
658273×
           CASE j.status WHEN 'running' THEN 0 ELSE {PRIORITY_RANK} END, \
659273×
           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) \
660273×
           + (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, \
661273×
           j.run_id, j.depth, j.id"
662273×
    ))
663273×
    .fetch_all(pool)
664273×
    .await
665273×
}
666
667
/// A repository's runs, newest first, numbered below `before`.
6682×
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
6692×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3")
6702×
        .bind(repo_id)
6712×
        .bind(before.unwrap_or(i64::MAX))
6722×
        .bind(limit)
6732×
        .fetch_all(pool)
6742×
        .await
6752×
}
676
677
/// The latest run on this bookmark of this repository, for what a push
678
/// changed since (a job's scope).
679
/// The run a push to `bookmark` is scoped against: the newest that was not
680
/// cancelled, nor a push run still going (a new push supersedes it), so
681
/// that what a cancelled run would have checked is checked by the next.
682152×
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
683152×
    sqlx::query_as(
684152×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
685152×
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
686152×
    )
687152×
    .bind(repo_id)
688152×
    .bind(bookmark)
689152×
    .fetch_optional(pool)
690152×
    .await
691152×
}
692
693313×
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
694313×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3")
695313×
        .bind(repo_id)
696313×
        .bind(before.unwrap_or(i64::MAX))
697313×
        .bind(limit)
698313×
        .fetch_all(pool)
699313×
        .await
700313×
}
701
702
/// A repository's run by its number there.
70396×
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
70496×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
70596×
}
706
7071005×
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
7081005×
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
7091005×
}
710
711278×
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
712278×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
713278×
}
714
715487×
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
716487×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
717487×
}
718
719
/// The running job a job token belongs to, while it may still be used.
72031×
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
72131×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = $1 AND status = 'running' AND started_ms >= $2")
72231×
        .bind(token_hash)
72331×
        .bind(now_ms() - max_age_ms)
72431×
        .fetch_optional(pool)
72531×
        .await
72631×
}
727
728
/// Take the oldest queued job whose dependencies all passed and whose tier
729
/// the runner offers, and mark it running for `runner` with a token.
730
/// Let a job's token also read these repositories (its pinned subrepos).
73128×
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
73229×
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
73328×
    sqlx::query("UPDATE flow_jobs SET also_read = $1 WHERE id = $2").bind(list.join(",")).bind(job_id).execute(pool).await?;
73428×
    Ok(())
73528×
}
736
737
impl Job {
73810×
    pub fn also_read_ids(&self) -> Vec<i64> {
73915×
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
74010×
    }
741
}
742
743
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
744
/// limit, and the rootfs images it holds, `None` when it does not say.
745
#[derive(Clone, Debug, Default)]
746
pub struct Room {
747
    pub memory_mib: Option<u32>,
748
    pub cpus: Option<u32>,
749
    pub images: Option<std::collections::HashSet<String>>,
750
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
751
    pub arch: String,
752
    /// Each image's architecture as runners have reported it (`flow_images`).
753
    pub image_archs: std::collections::HashMap<String, String>,
754
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
755
    pub declined: std::collections::HashSet<i64>,
756
    /// Images the hub holds that this runner would fetch when it lacks
757
    /// them (oxygenflow#39); empty for a runner that does not fetch.
758
    pub fetchable: std::collections::HashSet<String>,
759
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
760
    /// when it does not say.
761
    pub free_disk_mib: Option<u64>,
762
}
763
764
impl Room {
765
    /// Whether a job needing `need` MiB of disk fits in its free disk.
766171×
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
767171×
        match (need, self.free_disk_mib) {
7682×
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
769169×
            _ => true,
770
        }
771171×
    }
772
}
773
774
impl Room {
775
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
776
    /// and its rootfs image among the runner's (oxygenhub#73).
777180×
    pub fn fits(&self, sandbox_json: &str) -> bool {
778180×
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
779180×
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
780180×
        let rootfs = v["rootfs"].as_str().unwrap_or("");
781
        // The architecture: the sandbox's own ask, else the image's as read
782
        // or learned from its passes (oxygenhub#173); one nobody has read
783
        // or run yet matches (OxygenFlow spec §11.3).
784180×
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
785180×
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
786180×
        arch_ok
787175×
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
788175×
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
789175×
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
790180×
    }
791
}
792
793
/// Remember which architecture each image is for, as a runner reports it.
79412×
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
79512×
    for (hash, arch) in archs.iter().take(500) {
79610×
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
7970×
            continue;
79810×
        }
79910×
        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")
80010×
        .bind(hash.to_ascii_lowercase())
80110×
        .bind(arch)
80210×
        .bind(now_ms())
80310×
        .execute(pool)
80410×
        .await?;
805
    }
80612×
    Ok(())
80712×
}
808
809
/// Give every image nobody has read the architecture of the runners its
810
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
811
/// each pass. Never overrides a known architecture.
812198×
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
813198×
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
814198×
    let r = sqlx::query(&format!(
815198×
        "INSERT INTO flow_images (hash, arch, seen_ms)
816198×
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
817198×
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
818198×
         GROUP BY lower({rootfs})
819198×
         ON CONFLICT (hash) DO NOTHING"
820198×
    ))
821198×
    .bind(now_ms())
822198×
    .execute(pool)
823198×
    .await?;
824198×
    Ok(r.rows_affected())
825198×
}
826
827
/// Every image's architecture the hub knows.
828469×
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
829469×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
830469×
    Ok(rows.into_iter().collect())
831469×
}
832
8330×
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
8340×
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
8350×
}
836
837
/// The first queued job a runner with these tiers, this room and this
838
/// scope may take, now running under `runner`. Repositories take turns
839
/// (fair share, oxygenhub#244): a job's turn is its place in its own
840
/// repository's queue plus that repository's running jobs, lowest first,
841
/// oldest first among equals, so one repository's burst can't hold up the
842
/// rest. A scoped runner never sees
843
/// another scope's jobs (oxygenhub#41).
8440×
pub async fn claim_within(
8450×
    pool: &Pool,
8460×
    runtimes: &[String],
8470×
    runner: &str,
8480×
    token_hash: &str,
8490×
    room: Room,
8500×
    scope: &super::runners::Scope,
8510×
    labels: &[String],
8520×
) -> sqlx::Result<Option<Job>> {
8530×
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
8540×
}
855
856
/// [`claim_within`], passing over a job `elsewhere` says a better runner
857
/// should take (oxygenflow#42).
858
#[allow(clippy::too_many_arguments)]
859229×
pub async fn claim_ranked(
860229×
    pool: &Pool,
861229×
    runtimes: &[String],
862229×
    runner: &str,
863229×
    token_hash: &str,
864229×
    room: Room,
865229×
    scope: &super::runners::Scope,
866229×
    labels: &[String],
867229×
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
868229×
) -> sqlx::Result<Option<Job>> {
869229×
    let mut tx = super::begin_write(pool).await?;
870229×
    let queued: Vec<Job> = sqlx::query_as(&format!(
871229×
        "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 \
872229×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
873229×
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
874229×
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
875229×
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
876229×
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
877229×
           + (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), \
878229×
           j.run_id, j.depth, j.id LIMIT 200"
879229×
    ))
880229×
    .bind(&scope.owner)
881229×
    .bind(&scope.owner)
882229×
    .bind(scope.repo_id)
883229×
    .bind(scope.repo_id)
884229×
    // A repository on its own runners only (#225): the site's runners skip it.
885229×
    .bind(&scope.owner)
886229×
    .bind(scope.repo_id)
887229×
    .fetch_all(&mut *tx)
888229×
    .await?;
889229×
    for j in queued {
890183×
        if !runtimes.iter().any(|r| r == &j.runtime)
891180×
            || !room.fits(&j.sandbox)
892171×
            || !room.disk_fits(j.need_disk_mib)
893170×
            || room.declined.contains(&j.id)
894
        {
89514×
            continue;
896169×
        }
897
        // Every label the job and its sandbox ask for (`runs-on`).
898169×
        if !j.needs().iter().all(|l| labels.contains(l)) {
8992×
            continue;
900167×
        }
901167×
        let deps = j.depends_on();
902
        // When it became ready: queued, its dependencies passed, approved.
903167×
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
904167×
        if !deps.is_empty() {
90536×
            let mut passed = 0i64;
90636×
            for d in &deps {
90736×
                let st: Option<(String, Option<i64>)> =
90836×
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
90936×
                        .bind(j.run_id)
91036×
                        .bind(d)
91136×
                        .fetch_optional(&mut *tx)
91236×
                        .await?;
91336×
                if let Some((status, finished)) = st {
91436×
                    if status == "passed" {
91531×
                        passed += 1;
91631×
                        ready = ready.max(finished.unwrap_or(0));
91731×
                    }
9180×
                }
919
            }
92036×
            if passed != deps.len() as i64 {
9215×
                continue;
92231×
            }
923131×
        }
924162×
        if elsewhere(&j) {
9253×
            continue;
926159×
        }
927159×
        let now = now_ms();
928159×
        let done = sqlx::query(
929159×
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
930159×
             WHERE id = $4 AND status = 'queued'",
931
        )
932159×
        .bind(runner)
933159×
        .bind(token_hash)
934159×
        .bind(now)
935159×
        .bind(j.id)
936159×
        .bind(if ready > 0 { ready.min(now) } else { now })
937159×
        .execute(&mut *tx)
938159×
        .await?;
939159×
        if done.rows_affected() == 1 {
940159×
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
941159×
                .bind(j.run_id)
942159×
                .execute(&mut *tx)
943159×
                .await?;
944159×
            tx.commit().await?;
945159×
            return job(pool, j.id).await;
9460×
        }
947
    }
94870×
    tx.commit().await?;
94970×
    Ok(None)
950229×
}
951
952
/// How long a decline keeps a job from its runner when the runner's
953
/// profile stays the same: a reason such as memory in use passes.
954
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
955
956
/// The jobs runner `runner_id` declined with this profile, recently.
957229×
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
958229×
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
959229×
        .bind(runner_id)
960229×
        .bind(profile)
961229×
        .bind(now_ms() - DECLINE_HOLDS_MS)
962229×
        .fetch_all(pool)
963229×
        .await?;
964229×
    Ok(rows.into_iter().map(|(j,)| j).collect())
965229×
}
966
967
/// A decline: one runner's reason for handing a job back.
968
#[derive(Clone, Debug, sqlx::FromRow)]
969
pub struct DeclineRow {
970
    pub job_id: i64,
971
    pub runner_id: i64,
972
    pub runner: String,
973
    pub reason: String,
974
    pub ms: i64,
975
}
976
977
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
978
/// is kept (one per job and runner, the latest), and the job is queued
979
/// again. Returns every decline the job has had, or `None` when the job
980
/// was not running on that runner.
9814×
pub async fn decline(
9824×
    pool: &Pool,
9834×
    job_id: i64,
9844×
    runner_id: i64,
9854×
    runner: &str,
9864×
    profile: &str,
9874×
    reason: &str,
9884×
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
9894×
    let mut tx = super::begin_write(pool).await?;
9904×
    let back = sqlx::query(
9914×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
9924×
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
9934×
    )
9944×
    .bind(job_id)
9954×
    .bind(runner_id)
9964×
    .execute(&mut *tx)
9974×
    .await?;
9984×
    if back.rows_affected() != 1 {
9991×
        tx.rollback().await?;
10001×
        return Ok(None);
10013×
    }
10023×
    sqlx::query(
10033×
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
10043×
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
10053×
    )
10063×
    .bind(job_id)
10073×
    .bind(runner_id)
10083×
    .bind(runner)
10093×
    .bind(profile)
10103×
    .bind(reason)
10113×
    .bind(now_ms())
10123×
    .execute(&mut *tx)
10133×
    .await?;
10143×
    let all: Vec<DeclineRow> =
10153×
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
10163×
            .bind(job_id)
10173×
            .fetch_all(&mut *tx)
10183×
            .await?;
10193×
    tx.commit().await?;
10203×
    Ok(Some(all))
10214×
}
1022
1023
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
1024
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
1025
/// its runner's lease lapsed. Its log is kept and its next attempt's
1026
/// follows on. Returns how many times it has now been handed back, or
1027
/// `None` when it was not running there.
10283×
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
10293×
    let mut tx = super::begin_write(pool).await?;
10303×
    let now = now_ms();
10313×
    let back = sqlx::query(
10323×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
10333×
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
10343×
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
10353×
    )
10363×
    .bind(now)
10373×
    .bind(now)
10383×
    .bind(job_id)
10393×
    .bind(runner_id)
10403×
    .bind(runner_id)
10413×
    .execute(&mut *tx)
10423×
    .await?;
10433×
    if back.rows_affected() != 1 {
10441×
        tx.rollback().await?;
10451×
        return Ok(None);
10462×
    }
10472×
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
10482×
    tx.commit().await?;
10492×
    Ok(Some(n))
10503×
}
1051
1052
/// How long job `name` of repository `repo_id` is expected to take: the
1053
/// median of its last five passing runs (claimed to finished), passes
1054
/// reused from another run left out (oxygenflow#76). `None` before it has
1055
/// passed: a runner leaving then hands it back rather than guess.
1056159×
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
1057159×
    let mut times: Vec<i64> = sqlx::query_scalar(
1058159×
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1059159×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
1060159×
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
1061159×
    )
1062159×
    .bind(repo_id)
1063159×
    .bind(name)
1064159×
    .fetch_all(pool)
1065159×
    .await?;
1066159×
    times.sort_unstable();
1067159×
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
1068159×
}
1069
1070
/// Jobs running on a runner the hub has not heard from since `before`
1071
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
10721×
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
10731×
    let rows: Vec<(i64, String)> = sqlx::query_as(
10741×
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
10751×
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
10761×
    )
10771×
    .bind(before)
10781×
    .fetch_all(pool)
10791×
    .await?;
10801×
    let mut out = Vec::new();
10811×
    for (id, runner) in rows {
10821×
        if let Some(j) = job(pool, id).await? {
10831×
            out.push((j, runner));
10841×
        }
1085
    }
10861×
    Ok(out)
10871×
}
1088
1089
/// The declines of job `job_id`, oldest first.
109016×
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
109116×
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
109216×
        .bind(job_id)
109316×
        .fetch_all(pool)
109416×
        .await
109516×
}
1096
1097
/// A runner's latest declines, newest first, with where the job is.
1098
#[derive(Clone, Debug, sqlx::FromRow)]
1099
pub struct RunnerDecline {
1100
    pub job_id: i64,
1101
    pub job: String,
1102
    pub run_number: i64,
1103
    pub owner: String,
1104
    pub name: String,
1105
    pub reason: String,
1106
    pub ms: i64,
1107
}
1108
11094×
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
11104×
    sqlx::query_as(
11114×
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
11124×
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
11134×
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
11144×
    )
11154×
    .bind(runner_id)
11164×
    .bind(limit)
11174×
    .fetch_all(pool)
11184×
    .await
11194×
}
1120
1121
/// Queued jobs whose dependencies have passed, in their live runs, with
1122
/// their repositories (owner, id): the ones a runner could take now.
1123
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
1124
/// (#259: how many ready jobs come first).
11258×
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
11268×
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
11278×
        "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 \
11288×
         WHERE j.status = 'queued'"
11298×
    ))
11308×
    .fetch_all(pool)
11318×
    .await?;
11328×
    Ok(rows.into_iter().collect())
11338×
}
1134
1135
/// How many jobs each runner is running now, by runner id (#259).
11368×
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
11378×
    let rows: Vec<(i64, i64)> =
11388×
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
11398×
            .fetch_all(pool)
11408×
            .await?;
11418×
    Ok(rows.into_iter().collect())
11428×
}
1143
114411×
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
114511×
    let queued: Vec<Job> = sqlx::query_as(
114611×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
114711×
         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",
114811×
    )
114911×
    .fetch_all(pool)
115011×
    .await?;
115111×
    let mut out = Vec::new();
115224×
    for j in queued {
115324×
        let mut ready = true;
115424×
        for d in j.depends_on() {
11559×
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
11569×
                .bind(j.run_id)
11579×
                .bind(&d)
11589×
                .fetch_optional(pool)
11599×
                .await?;
11609×
            if st.as_deref() != Some("passed") {
11619×
                ready = false;
11629×
                break;
11630×
            }
1164
        }
116524×
        if !ready {
11669×
            continue;
116715×
        }
116815×
        let repo: Option<(String, i64)> =
116915×
            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")
117015×
                .bind(j.run_id)
117115×
                .fetch_optional(pool)
117215×
                .await?;
117315×
        if let Some((owner, id)) = repo {
117415×
            out.push((j, owner, id));
117515×
        }
1176
    }
117711×
    Ok(out)
117811×
}
1179
118017×
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
118117×
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
118217×
        .bind(waiting)
118317×
        .bind(job_id)
118417×
        .bind(waiting)
118517×
        .execute(pool)
118617×
        .await?;
118717×
    Ok(())
118817×
}
1189
1190
/// Append records; returns how many were kept (the rest exceed the cap).
119144×
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
119244×
    let mut tx = super::begin_write(pool).await?;
119344×
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
119444×
    let room = (cap - count).max(0) as usize;
119544×
    let keep = &records[..records.len().min(room)];
1196361×
    for (i, r) in keep.iter().enumerate() {
1197361×
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1198361×
            .bind(job_id)
1199361×
            .bind(count + i as i64 + 1)
1200361×
            .bind(r.t as i64)
1201361×
            .bind(&r.stream)
1202361×
            .bind(&r.text)
1203361×
            .execute(&mut *tx)
1204361×
            .await?;
1205
    }
120644×
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
120744×
        .bind(keep.len() as i64)
120844×
        .bind(job_id)
120944×
        .execute(&mut *tx)
121044×
        .await?;
121144×
    tx.commit().await?;
121244×
    Ok(keep.len())
121344×
}
1214
121573×
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
121673×
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
121773×
        .bind(job_id)
121873×
        .bind(after)
121973×
        .bind(limit)
122073×
        .fetch_all(pool)
122173×
        .await
122273×
}
1223
1224
/// Jobs running since before `ms` (the oldest first).
1225
/// Jobs still running at `now` past their own time limit (`default_s` for
1226
/// one claimed without) plus `grace_ms`.
12273×
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
12283×
    sqlx::query_as(
12293×
        "SELECT * FROM flow_jobs WHERE status = 'running' \
12303×
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
12313×
    )
12323×
    .bind(default_s as i64)
12333×
    .bind(grace_ms)
12343×
    .bind(now)
12353×
    .fetch_all(pool)
12363×
    .await
12373×
}
1238
1239
/// Record the limit a claimed job runs under.
1240159×
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1241159×
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1242159×
    Ok(())
1243159×
}
1244
12450×
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
12460×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
12470×
        .bind(ms)
12480×
        .fetch_all(pool)
12490×
        .await
12500×
}
1251
1252
/// The jobs running on the runner with this id.
12532×
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
12542×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
12552×
}
1256
1257
pub struct Outcome<'a> {
1258
    pub status: &'a str,
1259
    pub exit_code: Option<i64>,
1260
    pub error: &'a str,
1261
    pub receipt: &'a str,
1262
    pub receipt_hash: &'a str,
1263
}
1264
1265
/// Record a job's end, skip the jobs that can no longer run, and settle the
1266
/// run. Returns the jobs whose status changed (for their checks).
1267107×
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1268107×
    let mut tx = super::begin_write(pool).await?;
1269107×
    let now = now_ms();
1270107×
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1271107×
    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")
1272107×
        .bind(o.status)
1273107×
        .bind(o.exit_code)
1274107×
        .bind(o.error)
1275107×
        .bind(o.receipt)
1276107×
        .bind(o.receipt_hash)
1277107×
        .bind(now)
1278107×
        .bind(job_id)
1279107×
        .execute(&mut *tx)
1280107×
        .await?;
1281
    // A pass teaches what its image is for, when nobody has read it
1282
    // (oxygenhub#173): the architecture of the runner it passed on.
1283107×
    if o.status == "passed" {
128488×
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
128588×
            .ok()
128688×
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
128788×
            .unwrap_or_default();
128888×
        if rootfs.len() == 64 {
128988×
            sqlx::query(
129088×
                "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 \
129188×
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
129288×
            )
129388×
            .bind(&rootfs)
129488×
            .bind(now)
129588×
            .bind(job_id)
129688×
            .execute(&mut *tx)
129788×
            .await?;
12980×
        }
129919×
    }
1300107×
    let mut changed = vec![job_id];
1301
    // Dependents of anything that did not pass are skipped, transitively.
1302
    loop {
1303115×
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1304115×
        let blocked: Vec<i64> = all
1305115×
            .iter()
1306324×
            .filter(|x| x.status == "queued")
1307115×
            .filter(|x| {
130895×
                x.depends_on()
130995×
                    .iter()
1310175×
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
131195×
            })
1312115×
            .map(|x| x.id)
1313115×
            .collect();
1314115×
        if blocked.is_empty() {
1315107×
            break;
13168×
        }
13178×
        for id in blocked {
13188×
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
13198×
                .bind(now)
13208×
                .bind(id)
13218×
                .execute(&mut *tx)
13228×
                .await?;
13238×
            changed.push(id);
1324
        }
1325
    }
1326107×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1327107×
    if all.iter().all(Job::done) {
132893×
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
132942×
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
133042×
            .bind(status)
133142×
            .bind(now)
133242×
            .bind(j.run_id)
133342×
            .execute(&mut *tx)
133442×
            .await?;
133565×
    }
1336107×
    tx.commit().await?;
1337107×
    let mut out = Vec::new();
1338115×
    for id in changed {
1339115×
        if let Some(x) = job(pool, id).await? {
1340115×
            out.push(x);
1341115×
        }
1342
    }
1343107×
    Ok(out)
1344107×
}
1345
1346
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1347
/// and so does the run. A runner learns of it when the hub next refuses
1348
/// its log lines, and stops the job. Returns the jobs whose status changed.
134916×
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
135016×
    let now = now_ms();
135116×
    let mut tx = pool.begin().await?;
135216×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
135316×
        .bind(run_id)
135416×
        .fetch_all(&mut *tx)
135516×
        .await?;
135616×
    sqlx::query(
135716×
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
135816×
         WHERE run_id = $3 AND status IN ('queued', 'running')",
135916×
    )
136016×
    .bind(why)
136116×
    .bind(now)
136216×
    .bind(run_id)
136316×
    .execute(&mut *tx)
136416×
    .await?;
136516×
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
136616×
        .bind(now)
136716×
        .bind(run_id)
136816×
        .execute(&mut *tx)
136916×
        .await?;
137016×
    tx.commit().await?;
137116×
    let mut out = Vec::new();
137240×
    for (id,) in ids {
137340×
        if let Some(x) = job(pool, id).await? {
137440×
            out.push(x);
137540×
        }
1376
    }
137716×
    Ok(out)
137816×
}
1379
1380
/// Run job `name` of finished run `run_id` again, with every job that
1381
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1382
/// artifacts and reports gone, and the run running again. The jobs they
1383
/// depend on keep their results. The jobs reset; none when there is no
1384
/// such job.
13852×
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
13862×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
13874×
    if !all.iter().any(|j| j.name == name) {
13880×
        return Ok(Vec::new());
13892×
    }
13902×
    let mut again = vec![name.to_string()];
1391
    loop {
13923×
        let more: Vec<String> = all
13933×
            .iter()
13949×
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
13953×
            .map(|j| j.name.clone())
13963×
            .collect();
13973×
        if more.is_empty() {
13982×
            break;
13991×
        }
14001×
        again.extend(more);
1401
    }
14026×
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
14032×
    let mut tx = pool.begin().await?;
14043×
    for id in &ids {
140518×
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
140618×
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1407
        }
14083×
        sqlx::query(
14093×
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
14103×
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
14113×
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
14123×
             peak_memory_mib = NULL, phases = '', approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
14133×
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
14143×
             handbacks = 0 WHERE id = $1",
14153×
        )
14163×
        .bind(id)
14173×
        .bind(now_ms())
14183×
        .execute(&mut *tx)
14193×
        .await?;
1420
    }
14212×
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
14222×
    tx.commit().await?;
14232×
    let mut out = Vec::new();
14243×
    for id in ids {
14253×
        if let Some(x) = job(pool, id).await? {
14263×
            out.push(x);
14273×
        }
1428
    }
14292×
    Ok(out)
14302×
}
1431
1432
/// The runs of `bookmark` started by `trigger` still going, older than run
1433
/// `number`: those a newer run supersedes (#267). With `running_too`
1434
/// false, only those still queued.
1435126×
pub async fn live_runs_before(
1436126×
    pool: &Pool,
1437126×
    repo_id: i64,
1438126×
    bookmark: &str,
1439126×
    trigger: &str,
1440126×
    number: i64,
1441126×
    running_too: bool,
1442126×
) -> sqlx::Result<Vec<Run>> {
1443126×
    sqlx::query_as(
1444126×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1445126×
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1446126×
    )
1447126×
    .bind(repo_id)
1448126×
    .bind(bookmark)
1449126×
    .bind(number)
1450126×
    .bind(trigger)
1451126×
    .bind(running_too)
1452126×
    .fetch_all(pool)
1453126×
    .await
1454126×
}
1455
1456
/// The runs on `bookmark` that no runner has started yet: queued, with
1457
/// the given trigger, created before `before_ms` (#263).
145844×
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
145944×
    sqlx::query_as(
146044×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
146144×
    )
146244×
    .bind(repo_id)
146344×
    .bind(bookmark)
146444×
    .bind(trigger)
146544×
    .bind(before_ms)
146644×
    .fetch_all(pool)
146744×
    .await
146844×
}
1469
1470
/// The newest run of exactly this state (heads joined with `+`, sorted).
14716×
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
14726×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
14736×
        .bind(repo_id)
14746×
        .bind(heads)
14756×
        .fetch_optional(pool)
14766×
        .await
14776×
}
1478
1479
/// Record what became of job `job_id`'s signed receipt.
148011×
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
148111×
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
148211×
        .bind(attest)
148311×
        .bind(signer)
148411×
        .bind(note)
148511×
        .bind(job_id)
148611×
        .execute(pool)
148711×
        .await?;
148811×
    Ok(())
148911×
}
1490
1491
/// A job's artifact, kept as a blob of the run's repository.
1492
#[derive(Clone, Debug, FromRow)]
1493
pub struct Artifact {
1494
    pub job_id: i64,
1495
    pub name: String,
1496
    pub path: String,
1497
    pub blob: String,
1498
    pub size: i64,
1499
    /// BLAKE3 of the bytes.
1500
    pub content: String,
1501
    pub created_ms: i64,
1502
}
1503
150414×
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
150514×
    sqlx::query(
150614×
        "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",
150714×
    )
150814×
    .bind(a.job_id)
150914×
    .bind(&a.name)
151014×
    .bind(&a.path)
151114×
    .bind(&a.blob)
151214×
    .bind(a.size)
151314×
    .bind(&a.content)
151414×
    .bind(a.created_ms)
151514×
    .execute(pool)
151614×
    .await?;
151714×
    Ok(())
151814×
}
1519
1520
/// Every artifact blob a repository's runs keep, for garbage collection to
1521
/// keep too (#126): the database is the only thing that names them.
15224×
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
15234×
    sqlx::query_scalar(
15244×
        "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",
15254×
    )
15264×
    .bind(repo_id)
15274×
    .fetch_all(pool)
15284×
    .await
15294×
}
1530
1531
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1532
/// receipt names.
1533152×
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1534152×
    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
1535152×
}
1536
1537
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1538
/// artifacts: no pipeline can declare it.
1539
pub const CHECKPOINT: &str = ".checkpoint";
1540
1541
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1542
/// back (oxygenflow#77), if one did.
15433×
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
15443×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
15453×
}
1546
1547
/// An artifact with the run and job that made it, for a repository's list
1548
/// of every run's outputs (oxygenhub#254).
1549
#[derive(Clone, Debug, FromRow)]
1550
pub struct RepoArtifact {
1551
    pub run_number: i64,
1552
    pub bookmark: String,
1553
    pub job: String,
1554
    pub name: String,
1555
    pub path: String,
1556
    pub size: i64,
1557
    pub content: String,
1558
    pub created_ms: i64,
1559
}
1560
1561
/// A repository's newest artifacts, at most `limit`.
15622×
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
15632×
    sqlx::query_as(
15642×
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
15652×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
15662×
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
15672×
    )
15682×
    .bind(repo_id)
15692×
    .bind(limit)
15702×
    .fetch_all(pool)
15712×
    .await
15722×
}
1573
1574
/// Where an artifact with given content came from: the run and job that
1575
/// built it, and the job's signed receipt when one was kept.
1576
#[derive(Clone, Debug, FromRow)]
1577
pub struct Provenance {
1578
    pub run_number: i64,
1579
    pub job: String,
1580
    pub name: String,
1581
    pub receipt_attest: String,
1582
    pub receipt_signer: String,
1583
}
1584
1585
/// The build of the bytes whose BLAKE3 is `content` in repository
1586
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1587
/// run first.
158821×
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
158921×
    sqlx::query_as(
159021×
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
159121×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
159221×
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
159321×
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
159421×
    )
159521×
    .bind(repo_id)
159621×
    .bind(content)
159721×
    .fetch_optional(pool)
159821×
    .await
159921×
}
1600
1601
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1602
/// whether it was.
16032×
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
16042×
    let r = sqlx::query(
16052×
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
16062×
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
16072×
    )
16082×
    .bind(who)
16092×
    .bind(now_ms())
16102×
    .bind(seal)
16112×
    .bind(id)
16122×
    .bind(via)
16132×
    .execute(pool)
16142×
    .await?;
16152×
    Ok(r.rows_affected() > 0)
16162×
}
1617
1618
/// Note who rejected job `id` (it is then finished as cancelled).
16191×
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
16201×
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
16211×
        .bind(who)
16221×
        .bind(now_ms())
16231×
        .bind(id)
16241×
        .bind(via)
16251×
        .execute(pool)
16261×
        .await?;
16271×
    Ok(())
16281×
}
1629
1630
/// Jobs waiting for a person, in runs still going.
16312×
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
16322×
    sqlx::query_as(
16332×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
16342×
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
16352×
    )
16362×
    .fetch_all(pool)
16372×
    .await
16382×
}
1639
1640
/// One deployment: a job for an environment that passed.
1641
#[derive(Clone, Debug, FromRow)]
1642
pub struct Deployment {
1643
    pub environment: String,
1644
    pub job: String,
1645
    pub run_number: i64,
1646
    pub state: String,
1647
    pub bookmark: String,
1648
    pub actor: String,
1649
    pub approved_by: String,
1650
    pub finished_ms: i64,
1651
}
1652
1653
/// A repository's deployments, newest first (oxygenflow#59).
16542×
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
16552×
    sqlx::query_as(
16562×
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
16572×
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
16582×
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
16592×
    )
16602×
    .bind(repo_id)
16612×
    .bind(limit)
16622×
    .fetch_all(pool)
16632×
    .await
16642×
}