OXYGENHUB

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

1117 of 1153 lines run, 186 of 380 functions · run #540 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`.
10517×
    pub fn rerun_of(&self) -> Option<&str> {
10617×
        let rest = self.trigger.strip_prefix("rerun:")?;
1072×
        Some(rest.split(':').next().unwrap_or(rest))
10817×
    }
109
110
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
11116×
    pub fn trigger_label(&self) -> String {
11216×
        match self.rerun_of() {
1131×
            Some(n) => format!("rerun:{n}"),
11415×
            None => self.trigger.clone(),
115
        }
11616×
    }
117
118414×
    pub fn head_list(&self) -> Vec<&str> {
119546×
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
120414×
    }
121
122183×
    pub fn live(&self) -> bool {
123183×
        matches!(self.status.as_str(), "queued" | "running")
124183×
    }
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.
19879×
    pub fn phase_list(&self) -> Vec<(String, u64)> {
19979×
        let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(&self.phases).unwrap_or_default();
200316×
        ["image", "prepare", "run", "finish"].iter().filter_map(|p| m.get(*p).map(|ms| (p.to_string(), *ms))).collect()
20179×
    }
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
218425×
    pub fn depends_on(&self) -> Vec<String> {
219425×
        serde_json::from_str(&self.depends).unwrap_or_default()
220425×
    }
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).
276321×
pub async fn passed_on_state(
277321×
    pool: &Pool,
278321×
    repo_id: i64,
279321×
    state: &str,
280321×
    name: &str,
281321×
    spec: &str,
282321×
    sandbox: &str,
283321×
) -> sqlx::Result<Option<Reused>> {
284321×
    passed_in(pool, repo_id, state, name, spec, sandbox, false).await
285321×
}
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).
290327×
async fn passed_in(
291327×
    pool: &Pool,
292327×
    repo_id: i64,
293327×
    state: &str,
294327×
    name: &str,
295327×
    spec: &str,
296327×
    sandbox: &str,
297327×
    ran_here: bool,
298327×
) -> sqlx::Result<Option<Reused>> {
299327×
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
300327×
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
301327×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
302327×
         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' \
303327×
           AND (NOT $6 OR j.error NOT LIKE 'reused from %') \
304327×
         ORDER BY j.id DESC LIMIT 1",
305327×
    )
306327×
    .bind(repo_id)
307327×
    .bind(state)
308327×
    .bind(name)
309327×
    .bind(spec)
310327×
    .bind(sandbox)
311327×
    .bind(ran_here)
312327×
    .fetch_optional(pool)
313327×
    .await?;
314327×
    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×
    }))
323327×
}
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.
362306×
pub async fn passed_elsewhere(
363306×
    pool: &Pool,
364306×
    repo: &super::repos::RepoRow,
365306×
    state: &str,
366306×
    name: &str,
367306×
    spec: &str,
368306×
    sandbox: &str,
369306×
) -> 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
    }
381306×
    let pass: Option<Pass> = sqlx::query_as(
382306×
        "SELECT o.owner, o.name, r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
383306×
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories o ON o.id = r.repo_id \
384306×
         WHERE r.state = $1 AND j.name = $2 AND j.spec = $3 AND j.sandbox = $4 AND j.status = 'passed' \
385306×
           AND o.id <> $5 AND (o.visibility = 'public' OR o.owner = $6) AND j.error NOT LIKE 'reused from %' \
386306×
         ORDER BY j.id DESC LIMIT 1",
387306×
    )
388306×
    .bind(state)
389306×
    .bind(name)
390306×
    .bind(spec)
391306×
    .bind(sandbox)
392306×
    .bind(repo.id)
393306×
    .bind(&repo.owner)
394306×
    .fetch_optional(pool)
395306×
    .await?;
396306×
    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×
    }))
405306×
}
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.
413390×
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
414390×
    let peak: Option<i64> = sqlx::query_scalar(
415390×
        "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 \
416390×
         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",
417390×
    )
418390×
    .bind(repo_id)
419390×
    .bind(name)
420390×
    .bind(NEED_FROM_RUNS)
421390×
    .fetch_one(pool)
422390×
    .await?;
423390×
    Ok(peak.map(|p| p + p / 4 + 64))
424390×
}
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).
44499×
pub async fn set_phases(pool: &Pool, job_id: i64, phases: &std::collections::BTreeMap<String, u64>) -> sqlx::Result<()> {
44599×
    let json = if phases.is_empty() { String::new() } else { serde_json::to_string(phases).unwrap_or_default() };
44699×
    sqlx::query("UPDATE flow_jobs SET phases = $1 WHERE id = $2").bind(json).bind(job_id).execute(pool).await?;
44799×
    Ok(())
44899×
}
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
490150×
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
491150×
    let mut tx = super::begin_write(pool).await?;
492150×
    let now = now_ms();
493150×
    let status = if r.error.is_some() { "error" } else { "queued" };
494150×
    let id: i64 = sqlx::query_scalar(
495150×
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
496150×
         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
    )
498150×
    .bind(r.repo_id)
499150×
    .bind(r.repo_id)
500150×
    .bind(r.bookmark)
501150×
    .bind(r.state)
502150×
    .bind(r.heads)
503150×
    .bind(r.pipeline_hash)
504150×
    .bind(status)
505150×
    .bind(r.error.unwrap_or(""))
506150×
    .bind(r.actor)
507150×
    .bind(r.trigger)
508150×
    .bind(now)
509150×
    .bind(r.error.map(|_| now))
510150×
    .fetch_one(&mut *tx)
511150×
    .await?;
512394×
    for j in jobs {
513394×
        let job_id: i64 = sqlx::query_scalar(
514394×
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
515394×
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
516
        )
517394×
        .bind(id)
518394×
        .bind(&j.name)
519394×
        .bind(j.depth)
520394×
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
521394×
        .bind(&j.spec)
522394×
        .bind(&j.sandbox)
523394×
        .bind(&j.runtime)
524394×
        .bind(j.need_disk_mib)
525394×
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
526394×
        .bind(environment_of(&j.spec))
527394×
        .bind(priority_of(&j.spec))
528394×
        .bind(now)
529394×
        .fetch_one(&mut *tx)
530394×
        .await?;
531
        // A pass reused (#265): done before any runner can claim it.
532394×
        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?;
547377×
        }
548
    }
549
    // Every job reused: the run has passed already.
550159×
    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?;
552146×
    }
553150×
    tx.commit().await?;
554150×
    Ok(id)
555150×
}
556
557
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
558394×
fn environment_of(spec: &str) -> String {
559394×
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
560394×
}
561
562
/// A compiled job's own priority (`low`, `normal`), or empty; anything
563
/// else is not one a pipeline may give (oxygenhub#244).
564394×
fn priority_of(spec: &str) -> String {
565394×
    serde_json::from_str::<serde_json::Value>(spec)
566394×
        .ok()
567394×
        .and_then(|v| v["priority"].as_str().map(String::from))
568394×
        .filter(|p| p == "low" || p == "normal")
569394×
        .unwrap_or_default()
570394×
}
571
572
/// Whether a compiled job asks for approval (oxygenflow#57).
573394×
fn needs_approval(spec: &str) -> bool {
574394×
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
575394×
}
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.
682155×
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
683155×
    sqlx::query_as(
684155×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
685155×
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
686155×
    )
687155×
    .bind(repo_id)
688155×
    .bind(bookmark)
689155×
    .fetch_optional(pool)
690155×
    .await
691155×
}
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.
703111×
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
704111×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
705111×
}
706
7071026×
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
7081026×
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
7091026×
}
710
711293×
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
712293×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
713293×
}
714
715499×
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
716499×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
717499×
}
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.
79413×
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
79513×
    for (hash, arch) in archs.iter().take(500) {
79611×
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
7970×
            continue;
79811×
        }
79911×
        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")
80011×
        .bind(hash.to_ascii_lowercase())
80111×
        .bind(arch)
80211×
        .bind(now_ms())
80311×
        .execute(pool)
80411×
        .await?;
805
    }
80613×
    Ok(())
80713×
}
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.
812205×
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
813205×
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
814205×
    let r = sqlx::query(&format!(
815205×
        "INSERT INTO flow_images (hash, arch, seen_ms)
816205×
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
817205×
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
818205×
         GROUP BY lower({rootfs})
819205×
         ON CONFLICT (hash) DO NOTHING"
820205×
    ))
821205×
    .bind(now_ms())
822205×
    .execute(pool)
823205×
    .await?;
824204×
    Ok(r.rows_affected())
825204×
}
826
827
/// Every image's architecture the hub knows.
828455×
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
829455×
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
830455×
    Ok(rows.into_iter().collect())
831455×
}
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
/// Keep the runner build job `id` was claimed by (oxygenflow#84), for
857
/// counting the jobs that prove a version in a wave.
858159×
pub async fn set_runner_version(pool: &Pool, id: i64, version: &str) -> sqlx::Result<()> {
859159×
    sqlx::query("UPDATE flow_jobs SET runner_version = $1 WHERE id = $2").bind(version).bind(id).execute(pool).await?;
860159×
    Ok(())
861159×
}
862
863
/// [`claim_within`], passing over a job `elsewhere` says a better runner
864
/// should take (oxygenflow#42).
865
#[allow(clippy::too_many_arguments)]
866222×
pub async fn claim_ranked(
867222×
    pool: &Pool,
868222×
    runtimes: &[String],
869222×
    runner: &str,
870222×
    token_hash: &str,
871222×
    room: Room,
872222×
    scope: &super::runners::Scope,
873222×
    labels: &[String],
874222×
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
875222×
) -> sqlx::Result<Option<Job>> {
876222×
    let mut tx = super::begin_write(pool).await?;
877222×
    let queued: Vec<Job> = sqlx::query_as(&format!(
878222×
        "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 \
879222×
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
880222×
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
881222×
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
882222×
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
883222×
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
884222×
           + (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), \
885222×
           j.run_id, j.depth, j.id LIMIT 200"
886222×
    ))
887222×
    .bind(&scope.owner)
888222×
    .bind(&scope.owner)
889222×
    .bind(scope.repo_id)
890222×
    .bind(scope.repo_id)
891222×
    // A repository on its own runners only (#225): the site's runners skip it.
892222×
    .bind(&scope.owner)
893222×
    .bind(scope.repo_id)
894222×
    .fetch_all(&mut *tx)
895222×
    .await?;
896222×
    for j in queued {
897183×
        if !runtimes.iter().any(|r| r == &j.runtime)
898180×
            || !room.fits(&j.sandbox)
899171×
            || !room.disk_fits(j.need_disk_mib)
900170×
            || room.declined.contains(&j.id)
901
        {
90214×
            continue;
903169×
        }
904
        // Every label the job and its sandbox ask for (`runs-on`).
905169×
        if !j.needs().iter().all(|l| labels.contains(l)) {
9062×
            continue;
907167×
        }
908167×
        let deps = j.depends_on();
909
        // When it became ready: queued, its dependencies passed, approved.
910167×
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
911167×
        if !deps.is_empty() {
91236×
            let mut passed = 0i64;
91336×
            for d in &deps {
91436×
                let st: Option<(String, Option<i64>)> =
91536×
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
91636×
                        .bind(j.run_id)
91736×
                        .bind(d)
91836×
                        .fetch_optional(&mut *tx)
91936×
                        .await?;
92036×
                if let Some((status, finished)) = st {
92136×
                    if status == "passed" {
92231×
                        passed += 1;
92331×
                        ready = ready.max(finished.unwrap_or(0));
92431×
                    }
9250×
                }
926
            }
92736×
            if passed != deps.len() as i64 {
9285×
                continue;
92931×
            }
930131×
        }
931162×
        if elsewhere(&j) {
9323×
            continue;
933159×
        }
934159×
        let now = now_ms();
935159×
        let done = sqlx::query(
936159×
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
937159×
             WHERE id = $4 AND status = 'queued'",
938
        )
939159×
        .bind(runner)
940159×
        .bind(token_hash)
941159×
        .bind(now)
942159×
        .bind(j.id)
943159×
        .bind(if ready > 0 { ready.min(now) } else { now })
944159×
        .execute(&mut *tx)
945159×
        .await?;
946159×
        if done.rows_affected() == 1 {
947159×
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
948159×
                .bind(j.run_id)
949159×
                .execute(&mut *tx)
950159×
                .await?;
951159×
            tx.commit().await?;
952159×
            return job(pool, j.id).await;
9530×
        }
954
    }
95563×
    tx.commit().await?;
95663×
    Ok(None)
957222×
}
958
959
/// How long a decline keeps a job from its runner when the runner's
960
/// profile stays the same: a reason such as memory in use passes.
961
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
962
963
/// The jobs runner `runner_id` declined with this profile, recently.
964222×
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
965222×
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
966222×
        .bind(runner_id)
967222×
        .bind(profile)
968222×
        .bind(now_ms() - DECLINE_HOLDS_MS)
969222×
        .fetch_all(pool)
970222×
        .await?;
971222×
    Ok(rows.into_iter().map(|(j,)| j).collect())
972222×
}
973
974
/// A decline: one runner's reason for handing a job back.
975
#[derive(Clone, Debug, sqlx::FromRow)]
976
pub struct DeclineRow {
977
    pub job_id: i64,
978
    pub runner_id: i64,
979
    pub runner: String,
980
    pub reason: String,
981
    pub ms: i64,
982
}
983
984
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
985
/// is kept (one per job and runner, the latest), and the job is queued
986
/// again. Returns every decline the job has had, or `None` when the job
987
/// was not running on that runner.
9884×
pub async fn decline(
9894×
    pool: &Pool,
9904×
    job_id: i64,
9914×
    runner_id: i64,
9924×
    runner: &str,
9934×
    profile: &str,
9944×
    reason: &str,
9954×
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
9964×
    let mut tx = super::begin_write(pool).await?;
9974×
    let back = sqlx::query(
9984×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
9994×
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
10004×
    )
10014×
    .bind(job_id)
10024×
    .bind(runner_id)
10034×
    .execute(&mut *tx)
10044×
    .await?;
10054×
    if back.rows_affected() != 1 {
10061×
        tx.rollback().await?;
10071×
        return Ok(None);
10083×
    }
10093×
    sqlx::query(
10103×
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
10113×
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
10123×
    )
10133×
    .bind(job_id)
10143×
    .bind(runner_id)
10153×
    .bind(runner)
10163×
    .bind(profile)
10173×
    .bind(reason)
10183×
    .bind(now_ms())
10193×
    .execute(&mut *tx)
10203×
    .await?;
10213×
    let all: Vec<DeclineRow> =
10223×
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
10233×
            .bind(job_id)
10243×
            .fetch_all(&mut *tx)
10253×
            .await?;
10263×
    tx.commit().await?;
10273×
    Ok(Some(all))
10284×
}
1029
1030
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
1031
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
1032
/// its runner's lease lapsed. Its log is kept and its next attempt's
1033
/// follows on. Returns how many times it has now been handed back, or
1034
/// `None` when it was not running there.
10353×
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
10363×
    let mut tx = super::begin_write(pool).await?;
10373×
    let now = now_ms();
10383×
    let back = sqlx::query(
10393×
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
10403×
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
10413×
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
10423×
    )
10433×
    .bind(now)
10443×
    .bind(now)
10453×
    .bind(job_id)
10463×
    .bind(runner_id)
10473×
    .bind(runner_id)
10483×
    .execute(&mut *tx)
10493×
    .await?;
10503×
    if back.rows_affected() != 1 {
10511×
        tx.rollback().await?;
10521×
        return Ok(None);
10532×
    }
10542×
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
10552×
    tx.commit().await?;
10562×
    Ok(Some(n))
10573×
}
1058
1059
/// How long job `name` of repository `repo_id` is expected to take: the
1060
/// median of its last five passing runs (claimed to finished), passes
1061
/// reused from another run left out (oxygenflow#76). `None` before it has
1062
/// passed: a runner leaving then hands it back rather than guess.
1063159×
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
1064159×
    let mut times: Vec<i64> = sqlx::query_scalar(
1065159×
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1066159×
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
1067159×
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
1068159×
    )
1069159×
    .bind(repo_id)
1070159×
    .bind(name)
1071159×
    .fetch_all(pool)
1072159×
    .await?;
1073159×
    times.sort_unstable();
1074159×
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
1075159×
}
1076
1077
/// Jobs running on a runner the hub has not heard from since `before`
1078
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
10791×
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
10801×
    let rows: Vec<(i64, String)> = sqlx::query_as(
10811×
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
10821×
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
10831×
    )
10841×
    .bind(before)
10851×
    .fetch_all(pool)
10861×
    .await?;
10871×
    let mut out = Vec::new();
10881×
    for (id, runner) in rows {
10891×
        if let Some(j) = job(pool, id).await? {
10901×
            out.push((j, runner));
10911×
        }
1092
    }
10931×
    Ok(out)
10941×
}
1095
1096
/// The declines of job `job_id`, oldest first.
109716×
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
109816×
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
109916×
        .bind(job_id)
110016×
        .fetch_all(pool)
110116×
        .await
110216×
}
1103
1104
/// A runner's latest declines, newest first, with where the job is.
1105
#[derive(Clone, Debug, sqlx::FromRow)]
1106
pub struct RunnerDecline {
1107
    pub job_id: i64,
1108
    pub job: String,
1109
    pub run_number: i64,
1110
    pub owner: String,
1111
    pub name: String,
1112
    pub reason: String,
1113
    pub ms: i64,
1114
}
1115
11164×
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
11174×
    sqlx::query_as(
11184×
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
11194×
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
11204×
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
11214×
    )
11224×
    .bind(runner_id)
11234×
    .bind(limit)
11244×
    .fetch_all(pool)
11254×
    .await
11264×
}
1127
1128
/// Queued jobs whose dependencies have passed, in their live runs, with
1129
/// their repositories (owner, id): the ones a runner could take now.
1130
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
1131
/// (#259: how many ready jobs come first).
11328×
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
11338×
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
11348×
        "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 \
11358×
         WHERE j.status = 'queued'"
11368×
    ))
11378×
    .fetch_all(pool)
11388×
    .await?;
11398×
    Ok(rows.into_iter().collect())
11408×
}
1141
1142
/// How many jobs each runner is running now, by runner id (#259).
11438×
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
11448×
    let rows: Vec<(i64, i64)> =
11458×
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
11468×
            .fetch_all(pool)
11478×
            .await?;
11488×
    Ok(rows.into_iter().collect())
11498×
}
1150
11519×
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
11529×
    let queued: Vec<Job> = sqlx::query_as(
11539×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
11549×
         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",
11559×
    )
11569×
    .fetch_all(pool)
11579×
    .await?;
11589×
    let mut out = Vec::new();
115924×
    for j in queued {
116024×
        let mut ready = true;
116124×
        for d in j.depends_on() {
11629×
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
11639×
                .bind(j.run_id)
11649×
                .bind(&d)
11659×
                .fetch_optional(pool)
11669×
                .await?;
11679×
            if st.as_deref() != Some("passed") {
11689×
                ready = false;
11699×
                break;
11700×
            }
1171
        }
117224×
        if !ready {
11739×
            continue;
117415×
        }
117515×
        let repo: Option<(String, i64)> =
117615×
            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")
117715×
                .bind(j.run_id)
117815×
                .fetch_optional(pool)
117915×
                .await?;
118015×
        if let Some((owner, id)) = repo {
118115×
            out.push((j, owner, id));
118215×
        }
1183
    }
11849×
    Ok(out)
11859×
}
1186
118717×
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
118817×
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
118917×
        .bind(waiting)
119017×
        .bind(job_id)
119117×
        .bind(waiting)
119217×
        .execute(pool)
119317×
        .await?;
119417×
    Ok(())
119517×
}
1196
1197
/// Append records; returns how many were kept (the rest exceed the cap).
119844×
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
119944×
    let mut tx = super::begin_write(pool).await?;
120044×
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
120144×
    let room = (cap - count).max(0) as usize;
120244×
    let keep = &records[..records.len().min(room)];
1203361×
    for (i, r) in keep.iter().enumerate() {
1204361×
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1205361×
            .bind(job_id)
1206361×
            .bind(count + i as i64 + 1)
1207361×
            .bind(r.t as i64)
1208361×
            .bind(&r.stream)
1209361×
            .bind(&r.text)
1210361×
            .execute(&mut *tx)
1211361×
            .await?;
1212
    }
121344×
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
121444×
        .bind(keep.len() as i64)
121544×
        .bind(job_id)
121644×
        .execute(&mut *tx)
121744×
        .await?;
121844×
    tx.commit().await?;
121944×
    Ok(keep.len())
122044×
}
1221
122273×
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
122373×
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
122473×
        .bind(job_id)
122573×
        .bind(after)
122673×
        .bind(limit)
122773×
        .fetch_all(pool)
122873×
        .await
122973×
}
1230
1231
/// Jobs running since before `ms` (the oldest first).
1232
/// Jobs still running at `now` past their own time limit (`default_s` for
1233
/// one claimed without) plus `grace_ms`.
12343×
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
12353×
    sqlx::query_as(
12363×
        "SELECT * FROM flow_jobs WHERE status = 'running' \
12373×
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
12383×
    )
12393×
    .bind(default_s as i64)
12403×
    .bind(grace_ms)
12413×
    .bind(now)
12423×
    .fetch_all(pool)
12433×
    .await
12443×
}
1245
1246
/// Record the limit a claimed job runs under.
1247159×
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1248159×
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1249159×
    Ok(())
1250159×
}
1251
12520×
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
12530×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
12540×
        .bind(ms)
12550×
        .fetch_all(pool)
12560×
        .await
12570×
}
1258
1259
/// The jobs running on the runner with this id.
12602×
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
12612×
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
12622×
}
1263
1264
pub struct Outcome<'a> {
1265
    pub status: &'a str,
1266
    pub exit_code: Option<i64>,
1267
    pub error: &'a str,
1268
    pub receipt: &'a str,
1269
    pub receipt_hash: &'a str,
1270
}
1271
1272
/// Record a job's end, skip the jobs that can no longer run, and settle the
1273
/// run. Returns the jobs whose status changed (for their checks).
1274107×
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1275107×
    let mut tx = super::begin_write(pool).await?;
1276107×
    let now = now_ms();
1277107×
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1278107×
    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")
1279107×
        .bind(o.status)
1280107×
        .bind(o.exit_code)
1281107×
        .bind(o.error)
1282107×
        .bind(o.receipt)
1283107×
        .bind(o.receipt_hash)
1284107×
        .bind(now)
1285107×
        .bind(job_id)
1286107×
        .execute(&mut *tx)
1287107×
        .await?;
1288
    // A pass teaches what its image is for, when nobody has read it
1289
    // (oxygenhub#173): the architecture of the runner it passed on.
1290107×
    if o.status == "passed" {
129188×
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
129288×
            .ok()
129388×
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
129488×
            .unwrap_or_default();
129588×
        if rootfs.len() == 64 {
129688×
            sqlx::query(
129788×
                "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 \
129888×
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
129988×
            )
130088×
            .bind(&rootfs)
130188×
            .bind(now)
130288×
            .bind(job_id)
130388×
            .execute(&mut *tx)
130488×
            .await?;
13050×
        }
130619×
    }
1307107×
    let mut changed = vec![job_id];
1308
    // Dependents of anything that did not pass are skipped, transitively.
1309
    loop {
1310115×
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1311115×
        let blocked: Vec<i64> = all
1312115×
            .iter()
1313324×
            .filter(|x| x.status == "queued")
1314115×
            .filter(|x| {
131595×
                x.depends_on()
131695×
                    .iter()
1317175×
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
131895×
            })
1319115×
            .map(|x| x.id)
1320115×
            .collect();
1321115×
        if blocked.is_empty() {
1322107×
            break;
13238×
        }
13248×
        for id in blocked {
13258×
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
13268×
                .bind(now)
13278×
                .bind(id)
13288×
                .execute(&mut *tx)
13298×
                .await?;
13308×
            changed.push(id);
1331
        }
1332
    }
1333107×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1334107×
    if all.iter().all(Job::done) {
133593×
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
133642×
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
133742×
            .bind(status)
133842×
            .bind(now)
133942×
            .bind(j.run_id)
134042×
            .execute(&mut *tx)
134142×
            .await?;
134265×
    }
1343107×
    tx.commit().await?;
1344107×
    let mut out = Vec::new();
1345115×
    for id in changed {
1346115×
        if let Some(x) = job(pool, id).await? {
1347115×
            out.push(x);
1348115×
        }
1349
    }
1350107×
    Ok(out)
1351107×
}
1352
1353
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1354
/// and so does the run. A runner learns of it when the hub next refuses
1355
/// its log lines, and stops the job. Returns the jobs whose status changed.
135620×
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
135720×
    let now = now_ms();
135820×
    let mut tx = pool.begin().await?;
135920×
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
136020×
        .bind(run_id)
136120×
        .fetch_all(&mut *tx)
136220×
        .await?;
136320×
    sqlx::query(
136420×
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
136520×
         WHERE run_id = $3 AND status IN ('queued', 'running')",
136620×
    )
136720×
    .bind(why)
136820×
    .bind(now)
136920×
    .bind(run_id)
137020×
    .execute(&mut *tx)
137120×
    .await?;
137220×
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
137320×
        .bind(now)
137420×
        .bind(run_id)
137520×
        .execute(&mut *tx)
137620×
        .await?;
137720×
    tx.commit().await?;
137820×
    let mut out = Vec::new();
137952×
    for (id,) in ids {
138052×
        if let Some(x) = job(pool, id).await? {
138152×
            out.push(x);
138252×
        }
1383
    }
138420×
    Ok(out)
138520×
}
1386
1387
/// Run job `name` of finished run `run_id` again, with every job that
1388
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1389
/// artifacts and reports gone, and the run running again. The jobs they
1390
/// depend on keep their results. The jobs reset; none when there is no
1391
/// such job.
13922×
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
13932×
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
13944×
    if !all.iter().any(|j| j.name == name) {
13950×
        return Ok(Vec::new());
13962×
    }
13972×
    let mut again = vec![name.to_string()];
1398
    loop {
13993×
        let more: Vec<String> = all
14003×
            .iter()
14019×
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
14023×
            .map(|j| j.name.clone())
14033×
            .collect();
14043×
        if more.is_empty() {
14052×
            break;
14061×
        }
14071×
        again.extend(more);
1408
    }
14096×
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
14102×
    let mut tx = pool.begin().await?;
14113×
    for id in &ids {
141218×
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
141318×
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1414
        }
14153×
        sqlx::query(
14163×
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
14173×
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
14183×
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
14193×
             peak_memory_mib = NULL, phases = '', approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
14203×
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
14213×
             handbacks = 0 WHERE id = $1",
14223×
        )
14233×
        .bind(id)
14243×
        .bind(now_ms())
14253×
        .execute(&mut *tx)
14263×
        .await?;
1427
    }
14282×
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
14292×
    tx.commit().await?;
14302×
    let mut out = Vec::new();
14313×
    for id in ids {
14323×
        if let Some(x) = job(pool, id).await? {
14333×
            out.push(x);
14343×
        }
1435
    }
14362×
    Ok(out)
14372×
}
1438
1439
/// The runs of `bookmark` started by `trigger` still going, older than run
1440
/// `number`: those a newer run supersedes (#267). With `running_too`
1441
/// false, only those still queued.
1442130×
pub async fn live_runs_before(
1443130×
    pool: &Pool,
1444130×
    repo_id: i64,
1445130×
    bookmark: &str,
1446130×
    trigger: &str,
1447130×
    number: i64,
1448130×
    running_too: bool,
1449130×
) -> sqlx::Result<Vec<Run>> {
1450130×
    sqlx::query_as(
1451130×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1452130×
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1453130×
    )
1454130×
    .bind(repo_id)
1455130×
    .bind(bookmark)
1456130×
    .bind(number)
1457130×
    .bind(trigger)
1458130×
    .bind(running_too)
1459130×
    .fetch_all(pool)
1460130×
    .await
1461130×
}
1462
1463
/// The runs on `bookmark` that no runner has started yet: queued, with
1464
/// the given trigger, created before `before_ms` (#263).
146544×
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
146644×
    sqlx::query_as(
146744×
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
146844×
    )
146944×
    .bind(repo_id)
147044×
    .bind(bookmark)
147144×
    .bind(trigger)
147244×
    .bind(before_ms)
147344×
    .fetch_all(pool)
147444×
    .await
147544×
}
1476
1477
/// The newest run of exactly this state (heads joined with `+`, sorted).
14786×
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
14796×
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
14806×
        .bind(repo_id)
14816×
        .bind(heads)
14826×
        .fetch_optional(pool)
14836×
        .await
14846×
}
1485
1486
/// Record what became of job `job_id`'s signed receipt.
148711×
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
148811×
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
148911×
        .bind(attest)
149011×
        .bind(signer)
149111×
        .bind(note)
149211×
        .bind(job_id)
149311×
        .execute(pool)
149411×
        .await?;
149511×
    Ok(())
149611×
}
1497
1498
/// A job's artifact, kept as a blob of the run's repository.
1499
#[derive(Clone, Debug, FromRow)]
1500
pub struct Artifact {
1501
    pub job_id: i64,
1502
    pub name: String,
1503
    pub path: String,
1504
    pub blob: String,
1505
    pub size: i64,
1506
    /// BLAKE3 of the bytes.
1507
    pub content: String,
1508
    pub created_ms: i64,
1509
}
1510
151114×
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
151214×
    sqlx::query(
151314×
        "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",
151414×
    )
151514×
    .bind(a.job_id)
151614×
    .bind(&a.name)
151714×
    .bind(&a.path)
151814×
    .bind(&a.blob)
151914×
    .bind(a.size)
152014×
    .bind(&a.content)
152114×
    .bind(a.created_ms)
152214×
    .execute(pool)
152314×
    .await?;
152414×
    Ok(())
152514×
}
1526
1527
/// Every artifact blob a repository's runs keep, for garbage collection to
1528
/// keep too (#126): the database is the only thing that names them.
15294×
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
15304×
    sqlx::query_scalar(
15314×
        "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",
15324×
    )
15334×
    .bind(repo_id)
15344×
    .fetch_all(pool)
15354×
    .await
15364×
}
1537
1538
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1539
/// receipt names.
1540152×
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1541152×
    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
1542152×
}
1543
1544
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1545
/// artifacts: no pipeline can declare it.
1546
pub const CHECKPOINT: &str = ".checkpoint";
1547
1548
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1549
/// back (oxygenflow#77), if one did.
15503×
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
15513×
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
15523×
}
1553
1554
/// An artifact with the run and job that made it, for a repository's list
1555
/// of every run's outputs (oxygenhub#254).
1556
#[derive(Clone, Debug, FromRow)]
1557
pub struct RepoArtifact {
1558
    pub run_number: i64,
1559
    pub bookmark: String,
1560
    pub job: String,
1561
    pub name: String,
1562
    pub path: String,
1563
    pub size: i64,
1564
    pub content: String,
1565
    pub created_ms: i64,
1566
}
1567
1568
/// A repository's newest artifacts, at most `limit`.
15692×
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
15702×
    sqlx::query_as(
15712×
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
15722×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
15732×
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
15742×
    )
15752×
    .bind(repo_id)
15762×
    .bind(limit)
15772×
    .fetch_all(pool)
15782×
    .await
15792×
}
1580
1581
/// Where an artifact with given content came from: the run and job that
1582
/// built it, and the job's signed receipt when one was kept.
1583
#[derive(Clone, Debug, FromRow)]
1584
pub struct Provenance {
1585
    pub run_number: i64,
1586
    pub job: String,
1587
    pub name: String,
1588
    pub receipt_attest: String,
1589
    pub receipt_signer: String,
1590
}
1591
1592
/// The build of the bytes whose BLAKE3 is `content` in repository
1593
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1594
/// run first.
159521×
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
159621×
    sqlx::query_as(
159721×
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
159821×
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
159921×
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
160021×
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
160121×
    )
160221×
    .bind(repo_id)
160321×
    .bind(content)
160421×
    .fetch_optional(pool)
160521×
    .await
160621×
}
1607
1608
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1609
/// whether it was.
16102×
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
16112×
    let r = sqlx::query(
16122×
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
16132×
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
16142×
    )
16152×
    .bind(who)
16162×
    .bind(now_ms())
16172×
    .bind(seal)
16182×
    .bind(id)
16192×
    .bind(via)
16202×
    .execute(pool)
16212×
    .await?;
16222×
    Ok(r.rows_affected() > 0)
16232×
}
1624
1625
/// Note who rejected job `id` (it is then finished as cancelled).
16261×
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
16271×
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
16281×
        .bind(who)
16291×
        .bind(now_ms())
16301×
        .bind(id)
16311×
        .bind(via)
16321×
        .execute(pool)
16331×
        .await?;
16341×
    Ok(())
16351×
}
1636
1637
/// Jobs waiting for a person, in runs still going.
16382×
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
16392×
    sqlx::query_as(
16402×
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
16412×
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
16422×
    )
16432×
    .fetch_all(pool)
16442×
    .await
16452×
}
1646
1647
/// One deployment: a job for an environment that passed.
1648
#[derive(Clone, Debug, FromRow)]
1649
pub struct Deployment {
1650
    pub environment: String,
1651
    pub job: String,
1652
    pub run_number: i64,
1653
    pub state: String,
1654
    pub bookmark: String,
1655
    pub actor: String,
1656
    pub approved_by: String,
1657
    pub finished_ms: i64,
1658
}
1659
1660
/// A repository's deployments, newest first (oxygenflow#59).
16612×
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
16622×
    sqlx::query_as(
16632×
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
16642×
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
16652×
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
16662×
    )
16672×
    .bind(repo_id)
16682×
    .bind(limit)
16692×
    .fetch_all(pool)
16702×
    .await
16712×
}