OXYGENHUB
# dc59d1b56c3d oxygenhub / crates / hub / src / db / flow.rs
40.6 KiB · Rust · last changed Approval gates: a job waits for a person with the role 20 days ago source blame history raw
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`, `manual` or `rerun:N` (migration 0020).
14
    #[sqlx(default)]
15
    pub trigger: String,
16
    pub bookmark: String,
17
    pub state: String,
18
    pub heads: String,
19
    pub pipeline_hash: String,
20
    pub status: String,
21
    pub error: String,
22
    pub actor: String,
23
    pub created_ms: i64,
24
    pub finished_ms: Option<i64>,
25
}
26
27
impl Run {
28
    /// How the run page says what started it.
29
    pub fn started_by(&self) -> String {
30
        match self.trigger.as_str() {
31
            "manual" => format!("started by {}", self.actor),
32
            "schedule" => "started on schedule".to_string(),
33
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
34
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
35
            _ => format!("pushed by {}", self.actor),
36
        }
37
    }
38
39
    /// The run a rerun repeats: `N` of `rerun:N` or `rerun:N:EVENT`.
40
    pub fn rerun_of(&self) -> Option<&str> {
41
        let rest = self.trigger.strip_prefix("rerun:")?;
42
        Some(rest.split(':').next().unwrap_or(rest))
43
    }
44
45
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
46
    pub fn trigger_label(&self) -> String {
47
        match self.rerun_of() {
48
            Some(n) => format!("rerun:{n}"),
49
            None => self.trigger.clone(),
50
        }
51
    }
52
53
    pub fn head_list(&self) -> Vec<&str> {
54
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
55
    }
56
57
    pub fn live(&self) -> bool {
58
        matches!(self.status.as_str(), "queued" | "running")
59
    }
60
}
61
62
#[derive(Clone, Debug, Default, FromRow)]
63
pub struct Job {
64
    pub id: i64,
65
    pub run_id: i64,
66
    pub name: String,
67
    pub depth: i64,
68
    pub depends: String,
69
    pub spec: String,
70
    pub sandbox: String,
71
    pub runtime: String,
72
    pub status: String,
73
    pub runner: String,
74
    pub token_hash: String,
75
    pub started_ms: Option<i64>,
76
    pub finished_ms: Option<i64>,
77
    pub exit_code: Option<i64>,
78
    pub error: String,
79
    pub receipt: String,
80
    pub receipt_hash: String,
81
    pub log_count: i64,
82
    /// Comma-separated ids of other repositories the job token may read.
83
    pub also_read: String,
84
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
85
    pub receipt_attest: String,
86
    /// Who signed it: the runner's identity name.
87
    pub receipt_signer: String,
88
    /// Why a signed receipt was not kept.
89
    pub receipt_note: String,
90
    /// Why a queued job no runner can take waits (spec §11.4), from the
91
    /// last placement pass; empty when it is only waiting its turn.
92
    pub waiting: String,
93
    /// What it took, as its runner reported (oxygenflow#41), in MiB.
94
    pub peak_disk_mib: Option<i64>,
95
    pub peak_memory_mib: Option<i64>,
96
    /// The free disk it needs, learned from past runs of the same job.
97
    pub need_disk_mib: Option<i64>,
98
    /// Why it ran on its runner (oxygenflow#42).
99
    pub placed: String,
100
    /// `waiting` for a person, `approved`, or empty (oxygenflow#57).
101
    pub approval: String,
102
    /// Who approved or rejected it, and when.
103
    pub approved_by: String,
104
    pub approved_ms: Option<i64>,
105
}
106
107
impl Job {
108
    pub fn depends_on(&self) -> Vec<String> {
109
        serde_json::from_str(&self.depends).unwrap_or_default()
110
    }
111
112
    pub fn done(&self) -> bool {
113
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
114
    }
115
}
116
117
#[derive(Clone, Debug, FromRow)]
118
pub struct LogLine {
119
    pub seq: i64,
120
    pub t: i64,
121
    pub stream: String,
122
    pub text: String,
123
}
124
125
/// A job as the trigger creates it.
126
pub struct NewJob {
127
    pub name: String,
128
    pub depth: i64,
129
    pub depends: Vec<String>,
130
    pub spec: String,
131
    pub sandbox: String,
132
    pub runtime: String,
133
    /// The free disk it needs, from [`learned_disk_need`].
134
    pub need_disk_mib: Option<i64>,
135
}
136
137
/// Runs of a job whose peaks set its next need.
138
const NEED_FROM_RUNS: i64 = 5;
139
140
/// The free disk a new run of job `name` in repository `repo_id` needs
141
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
142
/// for a job that has not run here yet.
143
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
144
    let peak: Option<i64> = sqlx::query_scalar(
145
        "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 \
146
         WHERE r.repo_id = ? AND j.name = ? AND j.peak_disk_mib IS NOT NULL ORDER BY j.id DESC LIMIT ?)",
147
    )
148
    .bind(repo_id)
149
    .bind(name)
150
    .bind(NEED_FROM_RUNS)
151
    .fetch_one(pool)
152
    .await?;
153
    Ok(peak.map(|p| p + p / 4 + 64))
154
}
155
156
/// Record why job `job_id` ran where it did.
157
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
158
    sqlx::query("UPDATE flow_jobs SET placed = ? WHERE id = ?").bind(placed).bind(job_id).execute(pool).await?;
159
    Ok(())
160
}
161
162
/// Keep what a job took, as its runner reported.
163
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
164
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = ?, peak_memory_mib = ? WHERE id = ?")
165
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
166
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
167
        .bind(job_id)
168
        .execute(pool)
169
        .await?;
170
    Ok(())
171
}
172
173
pub struct NewRun<'a> {
174
    pub repo_id: i64,
175
    pub bookmark: &'a str,
176
    pub state: &'a str,
177
    pub heads: &'a str,
178
    pub pipeline_hash: &'a str,
179
    pub actor: &'a str,
180
    /// `push`, `manual` or `rerun:N`.
181
    pub trigger: &'a str,
182
    /// Problems when the pipeline is invalid: the run is recorded in error.
183
    pub error: Option<&'a str>,
184
}
185
186
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
187
    let mut tx = super::begin_write(pool).await?;
188
    let now = now_ms();
189
    let status = if r.error.is_some() { "error" } else { "queued" };
190
    let id: i64 = sqlx::query_scalar(
191
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
192
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
193
    )
194
    .bind(r.repo_id)
195
    .bind(r.repo_id)
196
    .bind(r.bookmark)
197
    .bind(r.state)
198
    .bind(r.heads)
199
    .bind(r.pipeline_hash)
200
    .bind(status)
201
    .bind(r.error.unwrap_or(""))
202
    .bind(r.actor)
203
    .bind(r.trigger)
204
    .bind(now)
205
    .bind(r.error.map(|_| now))
206
    .fetch_one(&mut *tx)
207
    .await?;
208
    for j in jobs {
209
        sqlx::query(
210
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval) \
211
             VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)",
212
        )
213
        .bind(id)
214
        .bind(&j.name)
215
        .bind(j.depth)
216
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
217
        .bind(&j.spec)
218
        .bind(&j.sandbox)
219
        .bind(&j.runtime)
220
        .bind(j.need_disk_mib)
221
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
222
        .execute(&mut *tx)
223
        .await?;
224
    }
225
    tx.commit().await?;
226
    Ok(id)
227
}
228
229
/// Whether a compiled job asks for approval (oxygenflow#57).
230
fn needs_approval(spec: &str) -> bool {
231
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
232
}
233
234
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
235
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
236
    let mut out: Vec<String> = [spec, sandbox]
237
        .iter()
238
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
239
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
240
        .filter_map(|l| l.as_str().map(String::from))
241
        .collect();
242
    out.sort();
243
    out.dedup();
244
    out
245
}
246
247
impl Job {
248
    /// The runner labels this job needs.
249
    pub fn needs(&self) -> Vec<String> {
250
        labels_in(&self.spec, &self.sandbox)
251
    }
252
253
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
254
    pub fn arch(&self) -> Option<String> {
255
        arch_in(&self.sandbox)
256
    }
257
}
258
259
/// The architecture a sandbox's JSON asks for, if any.
260
fn arch_in(sandbox: &str) -> Option<String> {
261
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
262
}
263
264
/// A job waiting for or held by a runner, with where it comes from.
265
#[derive(Clone, Debug, FromRow)]
266
pub struct QueueEntry {
267
    pub job_id: i64,
268
    pub run_id: i64,
269
    pub repo_id: i64,
270
    pub owner: String,
271
    pub name: String,
272
    pub visibility: String,
273
    pub run_number: i64,
274
    pub job: String,
275
    pub status: String,
276
    /// The runner holding it, when running.
277
    pub runner: String,
278
    pub spec: String,
279
    pub sandbox: String,
280
}
281
282
impl QueueEntry {
283
    /// The runner labels the job needs.
284
    pub fn needs(&self) -> Vec<String> {
285
        labels_in(&self.spec, &self.sandbox)
286
    }
287
288
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
289
    pub fn arch(&self) -> Option<String> {
290
        arch_in(&self.sandbox)
291
    }
292
}
293
294
/// Every job of a live run that is running or queued: running ones first,
295
/// then queued ones in the order runners claim them (hub spec §13.2).
296
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
297
    sqlx::query_as(
298
        "SELECT j.id AS job_id, j.run_id, r.repo_id, p.owner, p.name, p.visibility, r.number AS run_number, j.name AS job, j.status, j.runner, j.spec, j.sandbox \
299
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
300
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
301
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
302
    )
303
    .fetch_all(pool)
304
    .await
305
}
306
307
/// A repository's runs, newest first, numbered below `before`.
308
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
309
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
310
        .bind(repo_id)
311
        .bind(before.unwrap_or(i64::MAX))
312
        .bind(limit)
313
        .fetch_all(pool)
314
        .await
315
}
316
317
/// The latest run on this bookmark of this repository, for what a push
318
/// changed since (a job's scope).
319
/// The run a push to `bookmark` is scoped against: the newest that was not
320
/// cancelled, nor a push run still going (a new push supersedes it), so
321
/// that what a cancelled run would have checked is checked by the next.
322
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
323
    sqlx::query_as(
324
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND heads != '' AND status != 'cancelled'
325
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
326
    )
327
    .bind(repo_id)
328
    .bind(bookmark)
329
    .fetch_optional(pool)
330
    .await
331
}
332
333
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
334
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
335
        .bind(repo_id)
336
        .bind(before.unwrap_or(i64::MAX))
337
        .bind(limit)
338
        .fetch_all(pool)
339
        .await
340
}
341
342
/// A repository's run by its number there.
343
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
344
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
345
}
346
347
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
348
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
349
}
350
351
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
352
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
353
}
354
355
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
356
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
357
}
358
359
/// The running job a job token belongs to, while it may still be used.
360
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
361
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
362
        .bind(token_hash)
363
        .bind(now_ms() - max_age_ms)
364
        .fetch_optional(pool)
365
        .await
366
}
367
368
/// Take the oldest queued job whose dependencies all passed and whose tier
369
/// the runner offers, and mark it running for `runner` with a token.
370
/// Let a job's token also read these repositories (its pinned subrepos).
371
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
372
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
373
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
374
    Ok(())
375
}
376
377
impl Job {
378
    pub fn also_read_ids(&self) -> Vec<i64> {
379
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
380
    }
381
}
382
383
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
384
/// limit, and the rootfs images it holds, `None` when it does not say.
385
#[derive(Clone, Debug, Default)]
386
pub struct Room {
387
    pub memory_mib: Option<u32>,
388
    pub cpus: Option<u32>,
389
    pub images: Option<std::collections::HashSet<String>>,
390
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
391
    pub arch: String,
392
    /// Each image's architecture as runners have reported it (`flow_images`).
393
    pub image_archs: std::collections::HashMap<String, String>,
394
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
395
    pub declined: std::collections::HashSet<i64>,
396
    /// Images the hub holds that this runner would fetch when it lacks
397
    /// them (oxygenflow#39); empty for a runner that does not fetch.
398
    pub fetchable: std::collections::HashSet<String>,
399
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
400
    /// when it does not say.
401
    pub free_disk_mib: Option<u64>,
402
}
403
404
impl Room {
405
    /// Whether a job needing `need` MiB of disk fits in its free disk.
406
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
407
        match (need, self.free_disk_mib) {
408
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
409
            _ => true,
410
        }
411
    }
412
}
413
414
impl Room {
415
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
416
    /// and its rootfs image among the runner's (oxygenhub#73).
417
    pub fn fits(&self, sandbox_json: &str) -> bool {
418
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
419
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
420
        let rootfs = v["rootfs"].as_str().unwrap_or("");
421
        // The architecture: the sandbox's own ask, else the image's as read
422
        // or learned from its passes (oxygenhub#173); one nobody has read
423
        // or run yet matches (OxygenFlow spec §11.3).
424
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
425
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
426
        arch_ok
427
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
428
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
429
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
430
    }
431
}
432
433
/// Remember which architecture each image is for, as a runner reports it.
434
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
435
    for (hash, arch) in archs.iter().take(500) {
436
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
437
            continue;
438
        }
439
        sqlx::query("INSERT INTO flow_images (hash, arch, seen_ms) VALUES (?, ?, ?) ON CONFLICT (hash) DO UPDATE SET arch = excluded.arch, seen_ms = excluded.seen_ms")
440
        .bind(hash.to_ascii_lowercase())
441
        .bind(arch)
442
        .bind(now_ms())
443
        .execute(pool)
444
        .await?;
445
    }
446
    Ok(())
447
}
448
449
/// Give every image nobody has read the architecture of the runners its
450
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
451
/// each pass. Never overrides a known architecture.
452
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
453
    let r = sqlx::query(
454
        "INSERT INTO flow_images (hash, arch, seen_ms)
455
         SELECT lower(json_extract(j.sandbox, '$.rootfs')), MIN(r.arch), ? FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
456
         WHERE j.status = 'passed' AND r.arch != '' AND length(json_extract(j.sandbox, '$.rootfs')) = 64
457
         GROUP BY lower(json_extract(j.sandbox, '$.rootfs'))
458
         ON CONFLICT (hash) DO NOTHING",
459
    )
460
    .bind(now_ms())
461
    .execute(pool)
462
    .await?;
463
    Ok(r.rows_affected())
464
}
465
466
/// Every image's architecture the hub knows.
467
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
468
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
469
    Ok(rows.into_iter().collect())
470
}
471
472
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
473
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
474
}
475
476
/// The oldest runnable job that fits in `room`.
477
/// The first queued job a runner with these tiers, this room and this
478
/// scope may take, now running under `runner`. A scoped runner never sees
479
/// another scope's jobs (oxygenhub#41).
480
pub async fn claim_within(
481
    pool: &Pool,
482
    runtimes: &[String],
483
    runner: &str,
484
    token_hash: &str,
485
    room: Room,
486
    scope: &super::runners::Scope,
487
    labels: &[String],
488
) -> sqlx::Result<Option<Job>> {
489
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
490
}
491
492
/// [`claim_within`], passing over a job `elsewhere` says a better runner
493
/// should take (oxygenflow#42).
494
#[allow(clippy::too_many_arguments)]
495
pub async fn claim_ranked(
496
    pool: &Pool,
497
    runtimes: &[String],
498
    runner: &str,
499
    token_hash: &str,
500
    room: Room,
501
    scope: &super::runners::Scope,
502
    labels: &[String],
503
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
504
) -> sqlx::Result<Option<Job>> {
505
    let mut tx = super::begin_write(pool).await?;
506
    let queued: Vec<Job> = sqlx::query_as(
507
        "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 \
508
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
509
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
510
         AND NOT (? = '' AND ? IS NULL AND rep.flow = 'own') \
511
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
512
    )
513
    .bind(&scope.owner)
514
    .bind(&scope.owner)
515
    .bind(scope.repo_id)
516
    .bind(scope.repo_id)
517
    // A repository on its own runners only (#225): the site's runners skip it.
518
    .bind(&scope.owner)
519
    .bind(scope.repo_id)
520
    .fetch_all(&mut *tx)
521
    .await?;
522
    for j in queued {
523
        if !runtimes.iter().any(|r| r == &j.runtime)
524
            || !room.fits(&j.sandbox)
525
            || !room.disk_fits(j.need_disk_mib)
526
            || room.declined.contains(&j.id)
527
        {
528
            continue;
529
        }
530
        // Every label the job and its sandbox ask for (`runs-on`).
531
        if !j.needs().iter().all(|l| labels.contains(l)) {
532
            continue;
533
        }
534
        let deps = j.depends_on();
535
        if !deps.is_empty() {
536
            let mut passed = 0i64;
537
            for d in &deps {
538
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
539
                    .bind(j.run_id)
540
                    .bind(d)
541
                    .fetch_optional(&mut *tx)
542
                    .await?;
543
                if st.as_deref() == Some("passed") {
544
                    passed += 1;
545
                }
546
            }
547
            if passed != deps.len() as i64 {
548
                continue;
549
            }
550
        }
551
        if elsewhere(&j) {
552
            continue;
553
        }
554
        let now = now_ms();
555
        let done = sqlx::query(
556
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
557
        )
558
        .bind(runner)
559
        .bind(token_hash)
560
        .bind(now)
561
        .bind(j.id)
562
        .execute(&mut *tx)
563
        .await?;
564
        if done.rows_affected() == 1 {
565
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
566
                .bind(j.run_id)
567
                .execute(&mut *tx)
568
                .await?;
569
            tx.commit().await?;
570
            return job(pool, j.id).await;
571
        }
572
    }
573
    tx.commit().await?;
574
    Ok(None)
575
}
576
577
/// How long a decline keeps a job from its runner when the runner's
578
/// profile stays the same: a reason such as memory in use passes.
579
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
580
581
/// The jobs runner `runner_id` declined with this profile, recently.
582
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
583
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = ? AND profile = ? AND ms > ?")
584
        .bind(runner_id)
585
        .bind(profile)
586
        .bind(now_ms() - DECLINE_HOLDS_MS)
587
        .fetch_all(pool)
588
        .await?;
589
    Ok(rows.into_iter().map(|(j,)| j).collect())
590
}
591
592
/// A decline: one runner's reason for handing a job back.
593
#[derive(Clone, Debug, sqlx::FromRow)]
594
pub struct DeclineRow {
595
    pub job_id: i64,
596
    pub runner_id: i64,
597
    pub runner: String,
598
    pub reason: String,
599
    pub ms: i64,
600
}
601
602
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
603
/// is kept (one per job and runner, the latest), and the job is queued
604
/// again. Returns every decline the job has had, or `None` when the job
605
/// was not running on that runner.
606
pub async fn decline(
607
    pool: &Pool,
608
    job_id: i64,
609
    runner_id: i64,
610
    runner: &str,
611
    profile: &str,
612
    reason: &str,
613
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
614
    let mut tx = super::begin_write(pool).await?;
615
    let back = sqlx::query(
616
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
617
         WHERE id = ? AND status = 'running' AND runner_id = ?",
618
    )
619
    .bind(job_id)
620
    .bind(runner_id)
621
    .execute(&mut *tx)
622
    .await?;
623
    if back.rows_affected() != 1 {
624
        tx.rollback().await?;
625
        return Ok(None);
626
    }
627
    sqlx::query(
628
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES (?, ?, ?, ?, ?, ?) \
629
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
630
    )
631
    .bind(job_id)
632
    .bind(runner_id)
633
    .bind(runner)
634
    .bind(profile)
635
    .bind(reason)
636
    .bind(now_ms())
637
    .execute(&mut *tx)
638
    .await?;
639
    let all: Vec<DeclineRow> =
640
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
641
            .bind(job_id)
642
            .fetch_all(&mut *tx)
643
            .await?;
644
    tx.commit().await?;
645
    Ok(Some(all))
646
}
647
648
/// The declines of job `job_id`, oldest first.
649
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
650
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
651
        .bind(job_id)
652
        .fetch_all(pool)
653
        .await
654
}
655
656
/// A runner's latest declines, newest first, with where the job is.
657
#[derive(Clone, Debug, sqlx::FromRow)]
658
pub struct RunnerDecline {
659
    pub job_id: i64,
660
    pub job: String,
661
    pub run_number: i64,
662
    pub owner: String,
663
    pub name: String,
664
    pub reason: String,
665
    pub ms: i64,
666
}
667
668
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
669
    sqlx::query_as(
670
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
671
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
672
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = ? ORDER BY d.ms DESC LIMIT ?",
673
    )
674
    .bind(runner_id)
675
    .bind(limit)
676
    .fetch_all(pool)
677
    .await
678
}
679
680
/// Queued jobs whose dependencies have passed, in their live runs, with
681
/// their repositories (owner, id): the ones a runner could take now.
682
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
683
    let queued: Vec<Job> = sqlx::query_as(
684
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
685
         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",
686
    )
687
    .fetch_all(pool)
688
    .await?;
689
    let mut out = Vec::new();
690
    for j in queued {
691
        let mut ready = true;
692
        for d in j.depends_on() {
693
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
694
                .bind(j.run_id)
695
                .bind(&d)
696
                .fetch_optional(pool)
697
                .await?;
698
            if st.as_deref() != Some("passed") {
699
                ready = false;
700
                break;
701
            }
702
        }
703
        if !ready {
704
            continue;
705
        }
706
        let repo: Option<(String, i64)> =
707
            sqlx::query_as("SELECT rep.owner, rep.id FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id WHERE r.id = ?")
708
                .bind(j.run_id)
709
                .fetch_optional(pool)
710
                .await?;
711
        if let Some((owner, id)) = repo {
712
            out.push((j, owner, id));
713
        }
714
    }
715
    Ok(out)
716
}
717
718
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
719
    sqlx::query("UPDATE flow_jobs SET waiting = ? WHERE id = ? AND waiting <> ?")
720
        .bind(waiting)
721
        .bind(job_id)
722
        .bind(waiting)
723
        .execute(pool)
724
        .await?;
725
    Ok(())
726
}
727
728
/// Append records; returns how many were kept (the rest exceed the cap).
729
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
730
    let mut tx = super::begin_write(pool).await?;
731
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
732
    let room = (cap - count).max(0) as usize;
733
    let keep = &records[..records.len().min(room)];
734
    for (i, r) in keep.iter().enumerate() {
735
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
736
            .bind(job_id)
737
            .bind(count + i as i64 + 1)
738
            .bind(r.t as i64)
739
            .bind(&r.stream)
740
            .bind(&r.text)
741
            .execute(&mut *tx)
742
            .await?;
743
    }
744
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
745
        .bind(keep.len() as i64)
746
        .bind(job_id)
747
        .execute(&mut *tx)
748
        .await?;
749
    tx.commit().await?;
750
    Ok(keep.len())
751
}
752
753
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
754
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
755
        .bind(job_id)
756
        .bind(after)
757
        .bind(limit)
758
        .fetch_all(pool)
759
        .await
760
}
761
762
/// Jobs running since before `ms` (the oldest first).
763
/// Jobs still running at `now` past their own time limit (`default_s` for
764
/// one claimed without) plus `grace_ms`.
765
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
766
    sqlx::query_as(
767
        "SELECT * FROM flow_jobs WHERE status = 'running' \
768
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE ? END) * 1000 + ? < ? ORDER BY started_ms",
769
    )
770
    .bind(default_s as i64)
771
    .bind(grace_ms)
772
    .bind(now)
773
    .fetch_all(pool)
774
    .await
775
}
776
777
/// Record the limit a claimed job runs under.
778
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
779
    sqlx::query("UPDATE flow_jobs SET timeout_s = ? WHERE id = ?").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
780
    Ok(())
781
}
782
783
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
784
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
785
        .bind(ms)
786
        .fetch_all(pool)
787
        .await
788
}
789
790
/// The jobs running on the runner with this id.
791
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
792
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = ? ORDER BY id").bind(runner_id).fetch_all(pool).await
793
}
794
795
pub struct Outcome<'a> {
796
    pub status: &'a str,
797
    pub exit_code: Option<i64>,
798
    pub error: &'a str,
799
    pub receipt: &'a str,
800
    pub receipt_hash: &'a str,
801
}
802
803
/// Record a job's end, skip the jobs that can no longer run, and settle the
804
/// run. Returns the jobs whose status changed (for their checks).
805
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
806
    let mut tx = super::begin_write(pool).await?;
807
    let now = now_ms();
808
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
809
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
810
        .bind(o.status)
811
        .bind(o.exit_code)
812
        .bind(o.error)
813
        .bind(o.receipt)
814
        .bind(o.receipt_hash)
815
        .bind(now)
816
        .bind(job_id)
817
        .execute(&mut *tx)
818
        .await?;
819
    // A pass teaches what its image is for, when nobody has read it
820
    // (oxygenhub#173): the architecture of the runner it passed on.
821
    if o.status == "passed" {
822
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
823
            .ok()
824
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
825
            .unwrap_or_default();
826
        if rootfs.len() == 64 {
827
            sqlx::query(
828
                "INSERT INTO flow_images (hash, arch, seen_ms) SELECT ?, r.arch, ? FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
829
                 WHERE j.id = ? AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
830
            )
831
            .bind(&rootfs)
832
            .bind(now)
833
            .bind(job_id)
834
            .execute(&mut *tx)
835
            .await?;
836
        }
837
    }
838
    let mut changed = vec![job_id];
839
    // Dependents of anything that did not pass are skipped, transitively.
840
    loop {
841
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
842
        let blocked: Vec<i64> = all
843
            .iter()
844
            .filter(|x| x.status == "queued")
845
            .filter(|x| {
846
                x.depends_on()
847
                    .iter()
848
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
849
            })
850
            .map(|x| x.id)
851
            .collect();
852
        if blocked.is_empty() {
853
            break;
854
        }
855
        for id in blocked {
856
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
857
                .bind(now)
858
                .bind(id)
859
                .execute(&mut *tx)
860
                .await?;
861
            changed.push(id);
862
        }
863
    }
864
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
865
    if all.iter().all(Job::done) {
866
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
867
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
868
            .bind(status)
869
            .bind(now)
870
            .bind(j.run_id)
871
            .execute(&mut *tx)
872
            .await?;
873
    }
874
    tx.commit().await?;
875
    let mut out = Vec::new();
876
    for id in changed {
877
        if let Some(x) = job(pool, id).await? {
878
            out.push(x);
879
        }
880
    }
881
    Ok(out)
882
}
883
884
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
885
/// and so does the run. A runner learns of it when the hub next refuses
886
/// its log lines, and stops the job. Returns the jobs whose status changed.
887
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
888
    let now = now_ms();
889
    let mut tx = pool.begin().await?;
890
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = ? AND status IN ('queued', 'running')")
891
        .bind(run_id)
892
        .fetch_all(&mut *tx)
893
        .await?;
894
    sqlx::query(
895
        "UPDATE flow_jobs SET status = 'cancelled', error = ?, finished_ms = ?, token_hash = ''
896
         WHERE run_id = ? AND status IN ('queued', 'running')",
897
    )
898
    .bind(why)
899
    .bind(now)
900
    .bind(run_id)
901
    .execute(&mut *tx)
902
    .await?;
903
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = ? WHERE id = ? AND status IN ('queued', 'running')")
904
        .bind(now)
905
        .bind(run_id)
906
        .execute(&mut *tx)
907
        .await?;
908
    tx.commit().await?;
909
    let mut out = Vec::new();
910
    for (id,) in ids {
911
        if let Some(x) = job(pool, id).await? {
912
            out.push(x);
913
        }
914
    }
915
    Ok(out)
916
}
917
918
/// Run job `name` of finished run `run_id` again, with every job that
919
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
920
/// artifacts and reports gone, and the run running again. The jobs they
921
/// depend on keep their results. The jobs reset; none when there is no
922
/// such job.
923
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
924
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(run_id).fetch_all(pool).await?;
925
    if !all.iter().any(|j| j.name == name) {
926
        return Ok(Vec::new());
927
    }
928
    let mut again = vec![name.to_string()];
929
    loop {
930
        let more: Vec<String> = all
931
            .iter()
932
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
933
            .map(|j| j.name.clone())
934
            .collect();
935
        if more.is_empty() {
936
            break;
937
        }
938
        again.extend(more);
939
    }
940
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
941
    let mut tx = pool.begin().await?;
942
    for id in &ids {
943
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
944
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = ?")).bind(id).execute(&mut *tx).await?;
945
        }
946
        sqlx::query(
947
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
948
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
949
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
950
             peak_memory_mib = NULL, approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
951
             approved_ms = NULL WHERE id = ?",
952
        )
953
        .bind(id)
954
        .execute(&mut *tx)
955
        .await?;
956
    }
957
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = ?").bind(run_id).execute(&mut *tx).await?;
958
    tx.commit().await?;
959
    let mut out = Vec::new();
960
    for id in ids {
961
        if let Some(x) = job(pool, id).await? {
962
            out.push(x);
963
        }
964
    }
965
    Ok(out)
966
}
967
968
/// The push runs of `bookmark` still going, older than run `number`.
969
pub async fn live_push_runs_before(pool: &Pool, repo_id: i64, bookmark: &str, number: i64) -> sqlx::Result<Vec<Run>> {
970
    sqlx::query_as(
971
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND number < ? AND trigger = 'push'
972
         AND status IN ('queued', 'running') ORDER BY id",
973
    )
974
    .bind(repo_id)
975
    .bind(bookmark)
976
    .bind(number)
977
    .fetch_all(pool)
978
    .await
979
}
980
981
/// The newest run of exactly this state (heads joined with `+`, sorted).
982
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
983
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
984
        .bind(repo_id)
985
        .bind(heads)
986
        .fetch_optional(pool)
987
        .await
988
}
989
990
/// Record what became of job `job_id`'s signed receipt.
991
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
992
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
993
        .bind(attest)
994
        .bind(signer)
995
        .bind(note)
996
        .bind(job_id)
997
        .execute(pool)
998
        .await?;
999
    Ok(())
1000
}
1001
1002
/// A job's artifact, kept as a blob of the run's repository.
1003
#[derive(Clone, Debug, FromRow)]
1004
pub struct Artifact {
1005
    pub job_id: i64,
1006
    pub name: String,
1007
    pub path: String,
1008
    pub blob: String,
1009
    pub size: i64,
1010
    /// BLAKE3 of the bytes.
1011
    pub content: String,
1012
    pub created_ms: i64,
1013
}
1014
1015
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
1016
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
1017
        .bind(a.job_id)
1018
        .bind(&a.name)
1019
        .bind(&a.path)
1020
        .bind(&a.blob)
1021
        .bind(a.size)
1022
        .bind(&a.content)
1023
        .bind(a.created_ms)
1024
        .execute(pool)
1025
        .await?;
1026
    Ok(())
1027
}
1028
1029
/// Every artifact blob a repository's runs keep, for garbage collection to
1030
/// keep too (#126): the database is the only thing that names them.
1031
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
1032
    sqlx::query_scalar(
1033
        "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 = ?",
1034
    )
1035
    .bind(repo_id)
1036
    .fetch_all(pool)
1037
    .await
1038
}
1039
1040
/// Job `job_id`'s artifacts, by name.
1041
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1042
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
1043
}
1044
1045
/// Where an artifact with given content came from: the run and job that
1046
/// built it, and the job's signed receipt when one was kept.
1047
#[derive(Clone, Debug, FromRow)]
1048
pub struct Provenance {
1049
    pub run_number: i64,
1050
    pub job: String,
1051
    pub name: String,
1052
    pub receipt_attest: String,
1053
    pub receipt_signer: String,
1054
}
1055
1056
/// The build of the bytes whose BLAKE3 is `content` in repository
1057
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1058
/// run first.
1059
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
1060
    sqlx::query_as(
1061
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
1062
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
1063
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
1064
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
1065
    )
1066
    .bind(repo_id)
1067
    .bind(content)
1068
    .fetch_optional(pool)
1069
    .await
1070
}
1071
1072
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1073
/// whether it was.
1074
pub async fn approve_job(pool: &Pool, id: i64, who: &str) -> sqlx::Result<bool> {
1075
    let r = sqlx::query(
1076
        "UPDATE flow_jobs SET approval = 'approved', approved_by = ?, approved_ms = ? WHERE id = ? AND status = 'queued' AND approval = 'waiting'",
1077
    )
1078
    .bind(who)
1079
    .bind(now_ms())
1080
    .bind(id)
1081
    .execute(pool)
1082
    .await?;
1083
    Ok(r.rows_affected() > 0)
1084
}
1085
1086
/// Note who rejected job `id` (it is then finished as cancelled).
1087
pub async fn note_rejection(pool: &Pool, id: i64, who: &str) -> sqlx::Result<()> {
1088
    sqlx::query("UPDATE flow_jobs SET approved_by = ?, approved_ms = ? WHERE id = ?")
1089
        .bind(who)
1090
        .bind(now_ms())
1091
        .bind(id)
1092
        .execute(pool)
1093
        .await?;
1094
    Ok(())
1095
}
1096
1097
/// Jobs waiting for a person, in runs still going.
1098
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
1099
    sqlx::query_as(
1100
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1101
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
1102
    )
1103
    .fetch_all(pool)
1104
    .await
1105
}