OXYGENHUB
# aeed63c00ad7 oxygenhub / crates / hub / src / db / flow.rs
60.5 KiB · Rust · last changed A fork starts green where upstream proved the same state: a job with no pass of its own reuses one from the repositories it was forked from, public or the fork owner's, and says whose (refs #296) 9 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`, `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
/// Raise run `run_id` to urgent, saying who and why; a run already ended
71
/// is left alone. Whether it changed.
72
pub async fn expedite(pool: &Pool, run_id: i64, note: &str) -> sqlx::Result<bool> {
73
    let r = sqlx::query("UPDATE flow_runs SET priority = 'urgent', priority_note = $1 WHERE id = $2 AND status IN ('queued', 'running')")
74
        .bind(note)
75
        .bind(run_id)
76
        .execute(pool)
77
        .await?;
78
    Ok(r.rows_affected() > 0)
79
}
80
81
impl Run {
82
    /// How the run page says what started it.
83
    pub fn started_by(&self) -> String {
84
        match self.trigger.as_str() {
85
            "manual" => format!("started by {}", self.actor),
86
            "schedule" => "started on schedule".to_string(),
87
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
88
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
89
            _ => format!("pushed by {}", self.actor),
90
        }
91
    }
92
93
    /// The run a rerun repeats: `N` of `rerun:N` or `rerun:N:EVENT`.
94
    pub fn rerun_of(&self) -> Option<&str> {
95
        let rest = self.trigger.strip_prefix("rerun:")?;
96
        Some(rest.split(':').next().unwrap_or(rest))
97
    }
98
99
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
100
    pub fn trigger_label(&self) -> String {
101
        match self.rerun_of() {
102
            Some(n) => format!("rerun:{n}"),
103
            None => self.trigger.clone(),
104
        }
105
    }
106
107
    pub fn head_list(&self) -> Vec<&str> {
108
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
109
    }
110
111
    pub fn live(&self) -> bool {
112
        matches!(self.status.as_str(), "queued" | "running")
113
    }
114
}
115
116
#[derive(Clone, Debug, Default, FromRow)]
117
pub struct Job {
118
    pub id: i64,
119
    pub run_id: i64,
120
    pub name: String,
121
    pub depth: i64,
122
    pub depends: String,
123
    pub spec: String,
124
    pub sandbox: String,
125
    pub runtime: String,
126
    pub status: String,
127
    pub runner: String,
128
    pub token_hash: String,
129
    pub started_ms: Option<i64>,
130
    pub finished_ms: Option<i64>,
131
    pub exit_code: Option<i64>,
132
    pub error: String,
133
    pub receipt: String,
134
    pub receipt_hash: String,
135
    pub log_count: i64,
136
    /// Comma-separated ids of other repositories the job token may read.
137
    pub also_read: String,
138
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
139
    pub receipt_attest: String,
140
    /// Who signed it: the runner's identity name.
141
    pub receipt_signer: String,
142
    /// Why a signed receipt was not kept.
143
    pub receipt_note: String,
144
    /// Why a queued job no runner can take waits (spec §11.4), from the
145
    /// last placement pass; empty when it is only waiting its turn.
146
    pub waiting: String,
147
    /// What it took, as its runner reported (oxygenflow#41), in MiB.
148
    pub peak_disk_mib: Option<i64>,
149
    pub peak_memory_mib: Option<i64>,
150
    /// Where its time went, JSON of phase to milliseconds (oxygenflow#35).
151
    #[sqlx(default)]
152
    pub phases: String,
153
    /// The free disk it needs, learned from past runs of the same job.
154
    pub need_disk_mib: Option<i64>,
155
    /// Why it ran on its runner (oxygenflow#42).
156
    pub placed: String,
157
    /// `waiting` for a person, `approved`, or empty (oxygenflow#57).
158
    pub approval: String,
159
    /// Who approved or rejected it, and when.
160
    pub approved_by: String,
161
    pub approved_ms: Option<i64>,
162
    /// The agent token it was decided through, if one (oxygenhub#229).
163
    #[sqlx(default)]
164
    pub approved_via: String,
165
    /// The environment it deploys to, or empty (oxygenflow#59).
166
    pub environment: String,
167
    /// The approval attestation that released it, when sealed (#235).
168
    pub approval_seal: String,
169
    /// When it entered the queue (made, or run again), and when it became
170
    /// ready to run: set at its claim (migration 0080, oxygenhub#257).
171
    #[sqlx(default)]
172
    pub queued_ms: Option<i64>,
173
    #[sqlx(default)]
174
    pub ready_ms: Option<i64>,
175
    /// When a runner last handed it back, drained or with its lease lapsed
176
    /// (oxygenflow#76, migration 0094), and how many times: such a job is
177
    /// queued ahead of new work.
178
    #[sqlx(default)]
179
    pub handed_back_ms: Option<i64>,
180
    #[sqlx(default)]
181
    pub handbacks: i64,
182
}
183
184
impl Job {
185
    /// Where its time went, as its runner reported (oxygenflow#35): each
186
    /// phase it took, in the order it took them, with its milliseconds.
187
    pub fn phase_list(&self) -> Vec<(String, u64)> {
188
        let m: std::collections::BTreeMap<String, u64> = serde_json::from_str(&self.phases).unwrap_or_default();
189
        ["image", "prepare", "run", "finish"].iter().filter_map(|p| m.get(*p).map(|ms| (p.to_string(), *ms))).collect()
190
    }
191
192
    /// The run whose pass this job reused (#265), if it did: in this
193
    /// repository, or in the one [`Job::reused_repo`] names (#296).
194
    pub fn reused_from(&self) -> Option<i64> {
195
        self.error.strip_prefix("reused from ")?.rsplit_once("run #")?.1.parse().ok()
196
    }
197
198
    /// The repository (`owner/name`) whose pass this job reused, when not
199
    /// its own: a fork reusing what upstream proved (#296).
200
    pub fn reused_repo(&self) -> Option<&str> {
201
        let rest = self.error.strip_prefix("reused from ")?;
202
        let (repo, n) = rest.rsplit_once(" run #")?;
203
        n.parse::<i64>().ok()?;
204
        Some(repo).filter(|r| !r.is_empty())
205
    }
206
207
    pub fn depends_on(&self) -> Vec<String> {
208
        serde_json::from_str(&self.depends).unwrap_or_default()
209
    }
210
211
    pub fn done(&self) -> bool {
212
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
213
    }
214
}
215
216
#[derive(Clone, Debug, FromRow)]
217
pub struct LogLine {
218
    pub seq: i64,
219
    pub t: i64,
220
    pub stream: String,
221
    pub text: String,
222
}
223
224
/// A job as the trigger creates it.
225
pub struct NewJob {
226
    pub name: String,
227
    pub depth: i64,
228
    pub depends: Vec<String>,
229
    pub spec: String,
230
    pub sandbox: String,
231
    pub runtime: String,
232
    /// The free disk it needs, from [`learned_disk_need`].
233
    pub need_disk_mib: Option<i64>,
234
    /// A pass on the same state to reuse instead of running it (#265): the
235
    /// job is created passed, with that pass's receipt.
236
    pub reused: Option<Reused>,
237
}
238
239
/// A job's earlier pass on the same state, spec and sandbox (#265).
240
#[derive(Clone, Debug)]
241
pub struct Reused {
242
    /// The repository it passed in, `owner/name`, when not this one (#296).
243
    pub repo: Option<String>,
244
    /// The run it passed in.
245
    pub run_number: i64,
246
    pub receipt: String,
247
    pub receipt_hash: String,
248
    pub receipt_attest: String,
249
    pub receipt_signer: String,
250
    pub receipt_note: String,
251
}
252
253
impl Reused {
254
    /// What the reused job says, and how [`Job::reused_from`] reads it back.
255
    pub fn note(&self) -> String {
256
        match &self.repo {
257
            Some(r) => format!("reused from {r} run #{}", self.run_number),
258
            None => format!("reused from run #{}", self.run_number),
259
        }
260
    }
261
}
262
263
/// The newest pass of job `name` with exactly this spec and sandbox on
264
/// `state` in this repository (#265).
265
pub async fn passed_on_state(
266
    pool: &Pool,
267
    repo_id: i64,
268
    state: &str,
269
    name: &str,
270
    spec: &str,
271
    sandbox: &str,
272
) -> sqlx::Result<Option<Reused>> {
273
    let row: Option<(i64, String, String, String, String, String)> = sqlx::query_as(
274
        "SELECT r.number, j.receipt, j.receipt_hash, j.receipt_attest, j.receipt_signer, j.receipt_note \
275
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
276
         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' \
277
         ORDER BY j.id DESC LIMIT 1",
278
    )
279
    .bind(repo_id)
280
    .bind(state)
281
    .bind(name)
282
    .bind(spec)
283
    .bind(sandbox)
284
    .fetch_optional(pool)
285
    .await?;
286
    Ok(row.map(|(run_number, receipt, receipt_hash, receipt_attest, receipt_signer, receipt_note)| Reused {
287
        repo: None,
288
        run_number,
289
        receipt,
290
        receipt_hash,
291
        receipt_attest,
292
        receipt_signer,
293
        receipt_note,
294
    }))
295
}
296
297
/// How far up a fork's line [`passed_upstream`] looks.
298
const UPSTREAM_DEPTH: usize = 5;
299
300
/// A pass of job `name` with this spec and sandbox on `state` in a
301
/// repository `repo` was forked from, nearest first (#296): the same state
302
/// is the same changes, so what upstream proved holds for the fork. Only
303
/// from an upstream that is public or has the fork's owner, so a private
304
/// repository's receipts never show in another owner's fork.
305
pub async fn passed_upstream(
306
    pool: &Pool,
307
    repo: &super::repos::RepoRow,
308
    state: &str,
309
    name: &str,
310
    spec: &str,
311
    sandbox: &str,
312
) -> sqlx::Result<Option<Reused>> {
313
    let mut parent = repo.forked_from;
314
    for _ in 0..UPSTREAM_DEPTH {
315
        let Some(id) = parent else { break };
316
        let Some(up) = super::repos::get_by_id(pool, id).await? else { break };
317
        parent = up.forked_from;
318
        if !(up.visibility == "public" || up.owner == repo.owner) {
319
            continue;
320
        }
321
        if let Some(mut r) = passed_on_state(pool, up.id, state, name, spec, sandbox).await? {
322
            r.repo = Some(format!("{}/{}", up.owner, up.name));
323
            return Ok(Some(r));
324
        }
325
    }
326
    Ok(None)
327
}
328
329
/// Runs of a job whose peaks set its next need.
330
const NEED_FROM_RUNS: i64 = 5;
331
332
/// The free disk a new run of job `name` in repository `repo_id` needs
333
/// (oxygenflow#41): the most its last runs took, plus a quarter; `None`
334
/// for a job that has not run here yet.
335
pub async fn learned_disk_need(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
336
    let peak: Option<i64> = sqlx::query_scalar(
337
        "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 \
338
         WHERE r.repo_id = $1 AND j.name = $2 AND j.peak_disk_mib IS NOT NULL ORDER BY j.id DESC LIMIT $3)",
339
    )
340
    .bind(repo_id)
341
    .bind(name)
342
    .bind(NEED_FROM_RUNS)
343
    .fetch_one(pool)
344
    .await?;
345
    Ok(peak.map(|p| p + p / 4 + 64))
346
}
347
348
/// Record why job `job_id` ran where it did.
349
pub async fn set_placed(pool: &Pool, job_id: i64, placed: &str) -> sqlx::Result<()> {
350
    sqlx::query("UPDATE flow_jobs SET placed = $1 WHERE id = $2").bind(placed).bind(job_id).execute(pool).await?;
351
    Ok(())
352
}
353
354
/// Keep what a job took, as its runner reported.
355
pub async fn set_peaks(pool: &Pool, job_id: i64, disk_mib: Option<u64>, memory_mib: Option<u64>) -> sqlx::Result<()> {
356
    sqlx::query("UPDATE flow_jobs SET peak_disk_mib = $1, peak_memory_mib = $2 WHERE id = $3")
357
        .bind(disk_mib.map(|v| v.min(i64::MAX as u64) as i64))
358
        .bind(memory_mib.map(|v| v.min(i64::MAX as u64) as i64))
359
        .bind(job_id)
360
        .execute(pool)
361
        .await?;
362
    Ok(())
363
}
364
365
/// Where a finished job's time went, as its runner reported (oxygenflow#35).
366
pub async fn set_phases(pool: &Pool, job_id: i64, phases: &std::collections::BTreeMap<String, u64>) -> sqlx::Result<()> {
367
    let json = if phases.is_empty() { String::new() } else { serde_json::to_string(phases).unwrap_or_default() };
368
    sqlx::query("UPDATE flow_jobs SET phases = $1 WHERE id = $2").bind(json).bind(job_id).execute(pool).await?;
369
    Ok(())
370
}
371
372
pub struct NewRun<'a> {
373
    pub repo_id: i64,
374
    pub bookmark: &'a str,
375
    pub state: &'a str,
376
    pub heads: &'a str,
377
    pub pipeline_hash: &'a str,
378
    pub actor: &'a str,
379
    /// `push`, `proposal`, `tag:NAME`, `manual`, `schedule` or
380
    /// `rerun:N:EVENT`.
381
    pub trigger: &'a str,
382
    /// Problems when the pipeline is invalid: the run is recorded in error.
383
    pub error: Option<&'a str>,
384
}
385
386
/// A push that asked for no run (#284): recorded, finished, as skipped,
387
/// with `why` (which change asked, and who pushed it) as its note.
388
pub async fn create_skipped_run(pool: &Pool, r: NewRun<'_>, why: &str) -> sqlx::Result<i64> {
389
    let mut tx = super::begin_write(pool).await?;
390
    let now = now_ms();
391
    let id: i64 = sqlx::query_scalar(
392
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
393
         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",
394
    )
395
    .bind(r.repo_id)
396
    .bind(r.repo_id)
397
    .bind(r.bookmark)
398
    .bind(r.state)
399
    .bind(r.heads)
400
    .bind(r.pipeline_hash)
401
    .bind(why)
402
    .bind(r.actor)
403
    .bind(r.trigger)
404
    .bind(now)
405
    .bind(now)
406
    .fetch_one(&mut *tx)
407
    .await?;
408
    tx.commit().await?;
409
    Ok(id)
410
}
411
412
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
413
    let mut tx = super::begin_write(pool).await?;
414
    let now = now_ms();
415
    let status = if r.error.is_some() { "error" } else { "queued" };
416
    let id: i64 = sqlx::query_scalar(
417
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
418
         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",
419
    )
420
    .bind(r.repo_id)
421
    .bind(r.repo_id)
422
    .bind(r.bookmark)
423
    .bind(r.state)
424
    .bind(r.heads)
425
    .bind(r.pipeline_hash)
426
    .bind(status)
427
    .bind(r.error.unwrap_or(""))
428
    .bind(r.actor)
429
    .bind(r.trigger)
430
    .bind(now)
431
    .bind(r.error.map(|_| now))
432
    .fetch_one(&mut *tx)
433
    .await?;
434
    for j in jobs {
435
        let job_id: i64 = sqlx::query_scalar(
436
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status, need_disk_mib, approval, environment, priority, queued_ms) \
437
             VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, $10, $11, $12) RETURNING id",
438
        )
439
        .bind(id)
440
        .bind(&j.name)
441
        .bind(j.depth)
442
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
443
        .bind(&j.spec)
444
        .bind(&j.sandbox)
445
        .bind(&j.runtime)
446
        .bind(j.need_disk_mib)
447
        .bind(if needs_approval(&j.spec) { "waiting" } else { "" })
448
        .bind(environment_of(&j.spec))
449
        .bind(priority_of(&j.spec))
450
        .bind(now)
451
        .fetch_one(&mut *tx)
452
        .await?;
453
        // A pass reused (#265): done before any runner can claim it.
454
        if let Some(r) = &j.reused {
455
            sqlx::query(
456
                "UPDATE flow_jobs SET status = 'passed', exit_code = 0, error = $1, receipt = $2, receipt_hash = $3, receipt_attest = $4, \
457
                 receipt_signer = $5, receipt_note = $6, started_ms = $7, finished_ms = $7 WHERE id = $8",
458
            )
459
            .bind(r.note())
460
            .bind(&r.receipt)
461
            .bind(&r.receipt_hash)
462
            .bind(&r.receipt_attest)
463
            .bind(&r.receipt_signer)
464
            .bind(&r.receipt_note)
465
            .bind(now)
466
            .bind(job_id)
467
            .execute(&mut *tx)
468
            .await?;
469
        }
470
    }
471
    // Every job reused: the run has passed already.
472
    if !jobs.is_empty() && jobs.iter().all(|j| j.reused.is_some()) {
473
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = $1 WHERE id = $2").bind(now).bind(id).execute(&mut *tx).await?;
474
    }
475
    tx.commit().await?;
476
    Ok(id)
477
}
478
479
/// The environment a compiled job deploys to, or empty (oxygenflow#59).
480
fn environment_of(spec: &str) -> String {
481
    serde_json::from_str::<serde_json::Value>(spec).ok().and_then(|v| v["environment"].as_str().map(String::from)).unwrap_or_default()
482
}
483
484
/// A compiled job's own priority (`low`, `normal`), or empty; anything
485
/// else is not one a pipeline may give (oxygenhub#244).
486
fn priority_of(spec: &str) -> String {
487
    serde_json::from_str::<serde_json::Value>(spec)
488
        .ok()
489
        .and_then(|v| v["priority"].as_str().map(String::from))
490
        .filter(|p| p == "low" || p == "normal")
491
        .unwrap_or_default()
492
}
493
494
/// Whether a compiled job asks for approval (oxygenflow#57).
495
fn needs_approval(spec: &str) -> bool {
496
    serde_json::from_str::<serde_json::Value>(spec).is_ok_and(|v| !v["approval"].is_null())
497
}
498
499
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
500
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
501
    let mut out: Vec<String> = [spec, sandbox]
502
        .iter()
503
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
504
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
505
        .filter_map(|l| l.as_str().map(String::from))
506
        .collect();
507
    out.sort();
508
    out.dedup();
509
    out
510
}
511
512
impl Job {
513
    /// The runner labels this job needs.
514
    pub fn needs(&self) -> Vec<String> {
515
        labels_in(&self.spec, &self.sandbox)
516
    }
517
518
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
519
    pub fn arch(&self) -> Option<String> {
520
        arch_in(&self.sandbox)
521
    }
522
}
523
524
/// The architecture a sandbox's JSON asks for, if any.
525
fn arch_in(sandbox: &str) -> Option<String> {
526
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
527
}
528
529
/// A job waiting for or held by a runner, with where it comes from.
530
#[derive(Clone, Debug, FromRow)]
531
pub struct QueueEntry {
532
    pub job_id: i64,
533
    pub run_id: i64,
534
    pub repo_id: i64,
535
    pub owner: String,
536
    pub name: String,
537
    pub visibility: String,
538
    pub run_number: i64,
539
    pub job: String,
540
    pub status: String,
541
    /// The runner holding it, when running.
542
    pub runner: String,
543
    pub spec: String,
544
    pub sandbox: String,
545
    /// When it started running.
546
    pub started_ms: Option<i64>,
547
    /// Its level (0 urgent … 3 low, oxygenhub#244) and, when expedited, who
548
    /// did it and why.
549
    pub priority_rank: i64,
550
    pub priority_note: String,
551
}
552
553
impl QueueEntry {
554
    pub fn priority(&self) -> &'static str {
555
        PRIORITIES.get(self.priority_rank as usize).copied().unwrap_or("normal")
556
    }
557
}
558
559
impl QueueEntry {
560
    /// The runner labels the job needs.
561
    pub fn needs(&self) -> Vec<String> {
562
        labels_in(&self.spec, &self.sandbox)
563
    }
564
565
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
566
    pub fn arch(&self) -> Option<String> {
567
        arch_in(&self.sandbox)
568
    }
569
}
570
571
/// Every job of a live run that is running or queued: running ones first,
572
/// then queued ones in the order runners claim them (hub spec §13.2).
573
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
574
    sqlx::query_as(&format!(
575
        "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, \
576
           CAST({PRIORITY_RANK} AS BIGINT) AS priority_rank, {PRIORITY_NOTE} AS priority_note \
577
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
578
         WHERE j.status IN ('queued', 'running') AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
579
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, \
580
           CASE j.status WHEN 'running' THEN 0 ELSE {PRIORITY_RANK} END, \
581
           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) \
582
           + (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, \
583
           j.run_id, j.depth, j.id"
584
    ))
585
    .fetch_all(pool)
586
    .await
587
}
588
589
/// A repository's runs, newest first, numbered below `before`.
590
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
591
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number < $2 ORDER BY number DESC LIMIT $3")
592
        .bind(repo_id)
593
        .bind(before.unwrap_or(i64::MAX))
594
        .bind(limit)
595
        .fetch_all(pool)
596
        .await
597
}
598
599
/// The latest run on this bookmark of this repository, for what a push
600
/// changed since (a job's scope).
601
/// The run a push to `bookmark` is scoped against: the newest that was not
602
/// cancelled, nor a push run still going (a new push supersedes it), so
603
/// that what a cancelled run would have checked is checked by the next.
604
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
605
    sqlx::query_as(
606
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND heads != '' AND status NOT IN ('cancelled', 'skipped')
607
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
608
    )
609
    .bind(repo_id)
610
    .bind(bookmark)
611
    .fetch_optional(pool)
612
    .await
613
}
614
615
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
616
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3")
617
        .bind(repo_id)
618
        .bind(before.unwrap_or(i64::MAX))
619
        .bind(limit)
620
        .fetch_all(pool)
621
        .await
622
}
623
624
/// A repository's run by its number there.
625
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
626
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND number = $2").bind(repo_id).bind(number).fetch_optional(pool).await
627
}
628
629
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
630
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = $1").bind(id).fetch_optional(pool).await
631
}
632
633
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
634
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1 ORDER BY depth, name").bind(run_id).fetch_all(pool).await
635
}
636
637
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
638
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(id).fetch_optional(pool).await
639
}
640
641
/// The running job a job token belongs to, while it may still be used.
642
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
643
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = $1 AND status = 'running' AND started_ms >= $2")
644
        .bind(token_hash)
645
        .bind(now_ms() - max_age_ms)
646
        .fetch_optional(pool)
647
        .await
648
}
649
650
/// Take the oldest queued job whose dependencies all passed and whose tier
651
/// the runner offers, and mark it running for `runner` with a token.
652
/// Let a job's token also read these repositories (its pinned subrepos).
653
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
654
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
655
    sqlx::query("UPDATE flow_jobs SET also_read = $1 WHERE id = $2").bind(list.join(",")).bind(job_id).execute(pool).await?;
656
    Ok(())
657
}
658
659
impl Job {
660
    pub fn also_read_ids(&self) -> Vec<i64> {
661
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
662
    }
663
}
664
665
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
666
/// limit, and the rootfs images it holds, `None` when it does not say.
667
#[derive(Clone, Debug, Default)]
668
pub struct Room {
669
    pub memory_mib: Option<u32>,
670
    pub cpus: Option<u32>,
671
    pub images: Option<std::collections::HashSet<String>>,
672
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
673
    pub arch: String,
674
    /// Each image's architecture as runners have reported it (`flow_images`).
675
    pub image_archs: std::collections::HashMap<String, String>,
676
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
677
    pub declined: std::collections::HashSet<i64>,
678
    /// Images the hub holds that this runner would fetch when it lacks
679
    /// them (oxygenflow#39); empty for a runner that does not fetch.
680
    pub fetchable: std::collections::HashSet<String>,
681
    /// Its free disk now, from its claim's facts (oxygenflow#40); `None`
682
    /// when it does not say.
683
    pub free_disk_mib: Option<u64>,
684
}
685
686
impl Room {
687
    /// Whether a job needing `need` MiB of disk fits in its free disk.
688
    pub fn disk_fits(&self, need: Option<i64>) -> bool {
689
        match (need, self.free_disk_mib) {
690
            (Some(n), Some(free)) => n.max(0) as u64 <= free,
691
            _ => true,
692
        }
693
    }
694
}
695
696
impl Room {
697
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
698
    /// and its rootfs image among the runner's (oxygenhub#73).
699
    pub fn fits(&self, sandbox_json: &str) -> bool {
700
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
701
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
702
        let rootfs = v["rootfs"].as_str().unwrap_or("");
703
        // The architecture: the sandbox's own ask, else the image's as read
704
        // or learned from its passes (oxygenhub#173); one nobody has read
705
        // or run yet matches (OxygenFlow spec §11.3).
706
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
707
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
708
        arch_ok
709
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
710
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
711
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
712
    }
713
}
714
715
/// Remember which architecture each image is for, as a runner reports it.
716
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
717
    for (hash, arch) in archs.iter().take(500) {
718
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
719
            continue;
720
        }
721
        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")
722
        .bind(hash.to_ascii_lowercase())
723
        .bind(arch)
724
        .bind(now_ms())
725
        .execute(pool)
726
        .await?;
727
    }
728
    Ok(())
729
}
730
731
/// Give every image nobody has read the architecture of the runners its
732
/// jobs passed on (oxygenhub#173), for the jobs before the hub learned at
733
/// each pass. Never overrides a known architecture.
734
pub async fn learn_archs_from_runs(pool: &Pool) -> sqlx::Result<u64> {
735
    let rootfs = crate::db::json_text("j.sandbox", "rootfs");
736
    let r = sqlx::query(&format!(
737
        "INSERT INTO flow_images (hash, arch, seen_ms)
738
         SELECT lower({rootfs}), MIN(r.arch), $1 FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id
739
         WHERE j.status = 'passed' AND r.arch != '' AND length({rootfs}) = 64
740
         GROUP BY lower({rootfs})
741
         ON CONFLICT (hash) DO NOTHING"
742
    ))
743
    .bind(now_ms())
744
    .execute(pool)
745
    .await?;
746
    Ok(r.rows_affected())
747
}
748
749
/// Every image's architecture the hub knows.
750
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
751
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
752
    Ok(rows.into_iter().collect())
753
}
754
755
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
756
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
757
}
758
759
/// The first queued job a runner with these tiers, this room and this
760
/// scope may take, now running under `runner`. Repositories take turns
761
/// (fair share, oxygenhub#244): a job's turn is its place in its own
762
/// repository's queue plus that repository's running jobs, lowest first,
763
/// oldest first among equals, so one repository's burst can't hold up the
764
/// rest. A scoped runner never sees
765
/// another scope's jobs (oxygenhub#41).
766
pub async fn claim_within(
767
    pool: &Pool,
768
    runtimes: &[String],
769
    runner: &str,
770
    token_hash: &str,
771
    room: Room,
772
    scope: &super::runners::Scope,
773
    labels: &[String],
774
) -> sqlx::Result<Option<Job>> {
775
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
776
}
777
778
/// [`claim_within`], passing over a job `elsewhere` says a better runner
779
/// should take (oxygenflow#42).
780
#[allow(clippy::too_many_arguments)]
781
pub async fn claim_ranked(
782
    pool: &Pool,
783
    runtimes: &[String],
784
    runner: &str,
785
    token_hash: &str,
786
    room: Room,
787
    scope: &super::runners::Scope,
788
    labels: &[String],
789
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
790
) -> sqlx::Result<Option<Job>> {
791
    let mut tx = super::begin_write(pool).await?;
792
    let queued: Vec<Job> = sqlx::query_as(&format!(
793
        "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 \
794
         WHERE j.status = 'queued' AND j.approval != 'waiting' AND r.status IN ('queued', 'running') \
795
         AND ($1 = '' OR rep.owner = $2) AND ($3 IS NULL OR r.repo_id = $4) \
796
         AND NOT ($5 = '' AND $6 IS NULL AND rep.flow = 'own') \
797
         ORDER BY CASE WHEN j.handed_back_ms IS NULL THEN 1 ELSE 0 END, {PRIORITY_RANK}, \
798
           ROW_NUMBER() OVER (PARTITION BY r.repo_id ORDER BY j.run_id, j.depth, j.id) \
799
           + (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), \
800
           j.run_id, j.depth, j.id LIMIT 200"
801
    ))
802
    .bind(&scope.owner)
803
    .bind(&scope.owner)
804
    .bind(scope.repo_id)
805
    .bind(scope.repo_id)
806
    // A repository on its own runners only (#225): the site's runners skip it.
807
    .bind(&scope.owner)
808
    .bind(scope.repo_id)
809
    .fetch_all(&mut *tx)
810
    .await?;
811
    for j in queued {
812
        if !runtimes.iter().any(|r| r == &j.runtime)
813
            || !room.fits(&j.sandbox)
814
            || !room.disk_fits(j.need_disk_mib)
815
            || room.declined.contains(&j.id)
816
        {
817
            continue;
818
        }
819
        // Every label the job and its sandbox ask for (`runs-on`).
820
        if !j.needs().iter().all(|l| labels.contains(l)) {
821
            continue;
822
        }
823
        let deps = j.depends_on();
824
        // When it became ready: queued, its dependencies passed, approved.
825
        let mut ready = j.queued_ms.unwrap_or(0).max(j.approved_ms.unwrap_or(0));
826
        if !deps.is_empty() {
827
            let mut passed = 0i64;
828
            for d in &deps {
829
                let st: Option<(String, Option<i64>)> =
830
                    sqlx::query_as("SELECT status, finished_ms FROM flow_jobs WHERE run_id = $1 AND name = $2")
831
                        .bind(j.run_id)
832
                        .bind(d)
833
                        .fetch_optional(&mut *tx)
834
                        .await?;
835
                if let Some((status, finished)) = st {
836
                    if status == "passed" {
837
                        passed += 1;
838
                        ready = ready.max(finished.unwrap_or(0));
839
                    }
840
                }
841
            }
842
            if passed != deps.len() as i64 {
843
                continue;
844
            }
845
        }
846
        if elsewhere(&j) {
847
            continue;
848
        }
849
        let now = now_ms();
850
        let done = sqlx::query(
851
            "UPDATE flow_jobs SET status = 'running', runner = $1, token_hash = $2, started_ms = $3, waiting = '', ready_ms = $5 \
852
             WHERE id = $4 AND status = 'queued'",
853
        )
854
        .bind(runner)
855
        .bind(token_hash)
856
        .bind(now)
857
        .bind(j.id)
858
        .bind(if ready > 0 { ready.min(now) } else { now })
859
        .execute(&mut *tx)
860
        .await?;
861
        if done.rows_affected() == 1 {
862
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = $1 AND status = 'queued'")
863
                .bind(j.run_id)
864
                .execute(&mut *tx)
865
                .await?;
866
            tx.commit().await?;
867
            return job(pool, j.id).await;
868
        }
869
    }
870
    tx.commit().await?;
871
    Ok(None)
872
}
873
874
/// How long a decline keeps a job from its runner when the runner's
875
/// profile stays the same: a reason such as memory in use passes.
876
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
877
878
/// The jobs runner `runner_id` declined with this profile, recently.
879
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
880
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = $1 AND profile = $2 AND ms > $3")
881
        .bind(runner_id)
882
        .bind(profile)
883
        .bind(now_ms() - DECLINE_HOLDS_MS)
884
        .fetch_all(pool)
885
        .await?;
886
    Ok(rows.into_iter().map(|(j,)| j).collect())
887
}
888
889
/// A decline: one runner's reason for handing a job back.
890
#[derive(Clone, Debug, sqlx::FromRow)]
891
pub struct DeclineRow {
892
    pub job_id: i64,
893
    pub runner_id: i64,
894
    pub runner: String,
895
    pub reason: String,
896
    pub ms: i64,
897
}
898
899
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
900
/// is kept (one per job and runner, the latest), and the job is queued
901
/// again. Returns every decline the job has had, or `None` when the job
902
/// was not running on that runner.
903
pub async fn decline(
904
    pool: &Pool,
905
    job_id: i64,
906
    runner_id: i64,
907
    runner: &str,
908
    profile: &str,
909
    reason: &str,
910
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
911
    let mut tx = super::begin_write(pool).await?;
912
    let back = sqlx::query(
913
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
914
         WHERE id = $1 AND status = 'running' AND runner_id = $2",
915
    )
916
    .bind(job_id)
917
    .bind(runner_id)
918
    .execute(&mut *tx)
919
    .await?;
920
    if back.rows_affected() != 1 {
921
        tx.rollback().await?;
922
        return Ok(None);
923
    }
924
    sqlx::query(
925
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES ($1, $2, $3, $4, $5, $6) \
926
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
927
    )
928
    .bind(job_id)
929
    .bind(runner_id)
930
    .bind(runner)
931
    .bind(profile)
932
    .bind(reason)
933
    .bind(now_ms())
934
    .execute(&mut *tx)
935
    .await?;
936
    let all: Vec<DeclineRow> =
937
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
938
            .bind(job_id)
939
            .fetch_all(&mut *tx)
940
            .await?;
941
    tx.commit().await?;
942
    Ok(Some(all))
943
}
944
945
/// Job `job_id`, running on runner `runner_id` (any runner when `None`),
946
/// goes back to the queue ahead of new work (oxygenflow#76): drained, or
947
/// its runner's lease lapsed. Its log is kept and its next attempt's
948
/// follows on. Returns how many times it has now been handed back, or
949
/// `None` when it was not running there.
950
pub async fn hand_back(pool: &Pool, job_id: i64, runner_id: Option<i64>) -> sqlx::Result<Option<i64>> {
951
    let mut tx = super::begin_write(pool).await?;
952
    let now = now_ms();
953
    let back = sqlx::query(
954
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL, \
955
         handed_back_ms = $1, handbacks = handbacks + 1, queued_ms = $2, ready_ms = NULL, placed = '' \
956
         WHERE id = $3 AND status = 'running' AND ($4 IS NULL OR runner_id = $5)",
957
    )
958
    .bind(now)
959
    .bind(now)
960
    .bind(job_id)
961
    .bind(runner_id)
962
    .bind(runner_id)
963
    .execute(&mut *tx)
964
    .await?;
965
    if back.rows_affected() != 1 {
966
        tx.rollback().await?;
967
        return Ok(None);
968
    }
969
    let n: i64 = sqlx::query_scalar("SELECT handbacks FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
970
    tx.commit().await?;
971
    Ok(Some(n))
972
}
973
974
/// How long job `name` of repository `repo_id` is expected to take: the
975
/// median of its last five passing runs (claimed to finished), passes
976
/// reused from another run left out (oxygenflow#76). `None` before it has
977
/// passed: a runner leaving then hands it back rather than guess.
978
pub async fn expected_ms(pool: &Pool, repo_id: i64, name: &str) -> sqlx::Result<Option<i64>> {
979
    let mut times: Vec<i64> = sqlx::query_scalar(
980
        "SELECT j.finished_ms - j.started_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
981
         WHERE r.repo_id = $1 AND j.name = $2 AND j.status = 'passed' AND j.error = '' \
982
         AND j.started_ms IS NOT NULL AND j.finished_ms IS NOT NULL ORDER BY j.id DESC LIMIT 5",
983
    )
984
    .bind(repo_id)
985
    .bind(name)
986
    .fetch_all(pool)
987
    .await?;
988
    times.sort_unstable();
989
    Ok(times.get(times.len() / 2).copied().filter(|ms| *ms > 0))
990
}
991
992
/// Jobs running on a runner the hub has not heard from since `before`
993
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
994
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
995
    let rows: Vec<(i64, String)> = sqlx::query_as(
996
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
997
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
998
    )
999
    .bind(before)
1000
    .fetch_all(pool)
1001
    .await?;
1002
    let mut out = Vec::new();
1003
    for (id, runner) in rows {
1004
        if let Some(j) = job(pool, id).await? {
1005
            out.push((j, runner));
1006
        }
1007
    }
1008
    Ok(out)
1009
}
1010
1011
/// The declines of job `job_id`, oldest first.
1012
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
1013
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
1014
        .bind(job_id)
1015
        .fetch_all(pool)
1016
        .await
1017
}
1018
1019
/// A runner's latest declines, newest first, with where the job is.
1020
#[derive(Clone, Debug, sqlx::FromRow)]
1021
pub struct RunnerDecline {
1022
    pub job_id: i64,
1023
    pub job: String,
1024
    pub run_number: i64,
1025
    pub owner: String,
1026
    pub name: String,
1027
    pub reason: String,
1028
    pub ms: i64,
1029
}
1030
1031
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
1032
    sqlx::query_as(
1033
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
1034
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
1035
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
1036
    )
1037
    .bind(runner_id)
1038
    .bind(limit)
1039
    .fetch_all(pool)
1040
    .await
1041
}
1042
1043
/// Queued jobs whose dependencies have passed, in their live runs, with
1044
/// their repositories (owner, id): the ones a runner could take now.
1045
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
1046
/// (#259: how many ready jobs come first).
1047
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
1048
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
1049
        "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 \
1050
         WHERE j.status = 'queued'"
1051
    ))
1052
    .fetch_all(pool)
1053
    .await?;
1054
    Ok(rows.into_iter().collect())
1055
}
1056
1057
/// How many jobs each runner is running now, by runner id (#259).
1058
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
1059
    let rows: Vec<(i64, i64)> =
1060
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
1061
            .fetch_all(pool)
1062
            .await?;
1063
    Ok(rows.into_iter().collect())
1064
}
1065
1066
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
1067
    let queued: Vec<Job> = sqlx::query_as(
1068
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1069
         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",
1070
    )
1071
    .fetch_all(pool)
1072
    .await?;
1073
    let mut out = Vec::new();
1074
    for j in queued {
1075
        let mut ready = true;
1076
        for d in j.depends_on() {
1077
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
1078
                .bind(j.run_id)
1079
                .bind(&d)
1080
                .fetch_optional(pool)
1081
                .await?;
1082
            if st.as_deref() != Some("passed") {
1083
                ready = false;
1084
                break;
1085
            }
1086
        }
1087
        if !ready {
1088
            continue;
1089
        }
1090
        let repo: Option<(String, i64)> =
1091
            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")
1092
                .bind(j.run_id)
1093
                .fetch_optional(pool)
1094
                .await?;
1095
        if let Some((owner, id)) = repo {
1096
            out.push((j, owner, id));
1097
        }
1098
    }
1099
    Ok(out)
1100
}
1101
1102
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
1103
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
1104
        .bind(waiting)
1105
        .bind(job_id)
1106
        .bind(waiting)
1107
        .execute(pool)
1108
        .await?;
1109
    Ok(())
1110
}
1111
1112
/// Append records; returns how many were kept (the rest exceed the cap).
1113
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
1114
    let mut tx = super::begin_write(pool).await?;
1115
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1116
    let room = (cap - count).max(0) as usize;
1117
    let keep = &records[..records.len().min(room)];
1118
    for (i, r) in keep.iter().enumerate() {
1119
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1120
            .bind(job_id)
1121
            .bind(count + i as i64 + 1)
1122
            .bind(r.t as i64)
1123
            .bind(&r.stream)
1124
            .bind(&r.text)
1125
            .execute(&mut *tx)
1126
            .await?;
1127
    }
1128
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
1129
        .bind(keep.len() as i64)
1130
        .bind(job_id)
1131
        .execute(&mut *tx)
1132
        .await?;
1133
    tx.commit().await?;
1134
    Ok(keep.len())
1135
}
1136
1137
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
1138
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
1139
        .bind(job_id)
1140
        .bind(after)
1141
        .bind(limit)
1142
        .fetch_all(pool)
1143
        .await
1144
}
1145
1146
/// Jobs running since before `ms` (the oldest first).
1147
/// Jobs still running at `now` past their own time limit (`default_s` for
1148
/// one claimed without) plus `grace_ms`.
1149
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
1150
    sqlx::query_as(
1151
        "SELECT * FROM flow_jobs WHERE status = 'running' \
1152
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
1153
    )
1154
    .bind(default_s as i64)
1155
    .bind(grace_ms)
1156
    .bind(now)
1157
    .fetch_all(pool)
1158
    .await
1159
}
1160
1161
/// Record the limit a claimed job runs under.
1162
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1163
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1164
    Ok(())
1165
}
1166
1167
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
1168
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
1169
        .bind(ms)
1170
        .fetch_all(pool)
1171
        .await
1172
}
1173
1174
/// The jobs running on the runner with this id.
1175
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
1176
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
1177
}
1178
1179
pub struct Outcome<'a> {
1180
    pub status: &'a str,
1181
    pub exit_code: Option<i64>,
1182
    pub error: &'a str,
1183
    pub receipt: &'a str,
1184
    pub receipt_hash: &'a str,
1185
}
1186
1187
/// Record a job's end, skip the jobs that can no longer run, and settle the
1188
/// run. Returns the jobs whose status changed (for their checks).
1189
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1190
    let mut tx = super::begin_write(pool).await?;
1191
    let now = now_ms();
1192
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1193
    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")
1194
        .bind(o.status)
1195
        .bind(o.exit_code)
1196
        .bind(o.error)
1197
        .bind(o.receipt)
1198
        .bind(o.receipt_hash)
1199
        .bind(now)
1200
        .bind(job_id)
1201
        .execute(&mut *tx)
1202
        .await?;
1203
    // A pass teaches what its image is for, when nobody has read it
1204
    // (oxygenhub#173): the architecture of the runner it passed on.
1205
    if o.status == "passed" {
1206
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
1207
            .ok()
1208
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
1209
            .unwrap_or_default();
1210
        if rootfs.len() == 64 {
1211
            sqlx::query(
1212
                "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 \
1213
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
1214
            )
1215
            .bind(&rootfs)
1216
            .bind(now)
1217
            .bind(job_id)
1218
            .execute(&mut *tx)
1219
            .await?;
1220
        }
1221
    }
1222
    let mut changed = vec![job_id];
1223
    // Dependents of anything that did not pass are skipped, transitively.
1224
    loop {
1225
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1226
        let blocked: Vec<i64> = all
1227
            .iter()
1228
            .filter(|x| x.status == "queued")
1229
            .filter(|x| {
1230
                x.depends_on()
1231
                    .iter()
1232
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
1233
            })
1234
            .map(|x| x.id)
1235
            .collect();
1236
        if blocked.is_empty() {
1237
            break;
1238
        }
1239
        for id in blocked {
1240
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
1241
                .bind(now)
1242
                .bind(id)
1243
                .execute(&mut *tx)
1244
                .await?;
1245
            changed.push(id);
1246
        }
1247
    }
1248
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1249
    if all.iter().all(Job::done) {
1250
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
1251
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
1252
            .bind(status)
1253
            .bind(now)
1254
            .bind(j.run_id)
1255
            .execute(&mut *tx)
1256
            .await?;
1257
    }
1258
    tx.commit().await?;
1259
    let mut out = Vec::new();
1260
    for id in changed {
1261
        if let Some(x) = job(pool, id).await? {
1262
            out.push(x);
1263
        }
1264
    }
1265
    Ok(out)
1266
}
1267
1268
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1269
/// and so does the run. A runner learns of it when the hub next refuses
1270
/// its log lines, and stops the job. Returns the jobs whose status changed.
1271
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
1272
    let now = now_ms();
1273
    let mut tx = pool.begin().await?;
1274
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
1275
        .bind(run_id)
1276
        .fetch_all(&mut *tx)
1277
        .await?;
1278
    sqlx::query(
1279
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
1280
         WHERE run_id = $3 AND status IN ('queued', 'running')",
1281
    )
1282
    .bind(why)
1283
    .bind(now)
1284
    .bind(run_id)
1285
    .execute(&mut *tx)
1286
    .await?;
1287
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
1288
        .bind(now)
1289
        .bind(run_id)
1290
        .execute(&mut *tx)
1291
        .await?;
1292
    tx.commit().await?;
1293
    let mut out = Vec::new();
1294
    for (id,) in ids {
1295
        if let Some(x) = job(pool, id).await? {
1296
            out.push(x);
1297
        }
1298
    }
1299
    Ok(out)
1300
}
1301
1302
/// Run job `name` of finished run `run_id` again, with every job that
1303
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1304
/// artifacts and reports gone, and the run running again. The jobs they
1305
/// depend on keep their results. The jobs reset; none when there is no
1306
/// such job.
1307
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
1308
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
1309
    if !all.iter().any(|j| j.name == name) {
1310
        return Ok(Vec::new());
1311
    }
1312
    let mut again = vec![name.to_string()];
1313
    loop {
1314
        let more: Vec<String> = all
1315
            .iter()
1316
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
1317
            .map(|j| j.name.clone())
1318
            .collect();
1319
        if more.is_empty() {
1320
            break;
1321
        }
1322
        again.extend(more);
1323
    }
1324
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
1325
    let mut tx = pool.begin().await?;
1326
    for id in &ids {
1327
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
1328
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1329
        }
1330
        sqlx::query(
1331
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
1332
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
1333
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
1334
             peak_memory_mib = NULL, phases = '', approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
1335
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
1336
             handbacks = 0 WHERE id = $1",
1337
        )
1338
        .bind(id)
1339
        .bind(now_ms())
1340
        .execute(&mut *tx)
1341
        .await?;
1342
    }
1343
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
1344
    tx.commit().await?;
1345
    let mut out = Vec::new();
1346
    for id in ids {
1347
        if let Some(x) = job(pool, id).await? {
1348
            out.push(x);
1349
        }
1350
    }
1351
    Ok(out)
1352
}
1353
1354
/// The runs of `bookmark` started by `trigger` still going, older than run
1355
/// `number`: those a newer run supersedes (#267). With `running_too`
1356
/// false, only those still queued.
1357
pub async fn live_runs_before(
1358
    pool: &Pool,
1359
    repo_id: i64,
1360
    bookmark: &str,
1361
    trigger: &str,
1362
    number: i64,
1363
    running_too: bool,
1364
) -> sqlx::Result<Vec<Run>> {
1365
    sqlx::query_as(
1366
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1367
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1368
    )
1369
    .bind(repo_id)
1370
    .bind(bookmark)
1371
    .bind(number)
1372
    .bind(trigger)
1373
    .bind(running_too)
1374
    .fetch_all(pool)
1375
    .await
1376
}
1377
1378
/// The runs on `bookmark` that no runner has started yet: queued, with
1379
/// the given trigger, created before `before_ms` (#263).
1380
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
1381
    sqlx::query_as(
1382
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
1383
    )
1384
    .bind(repo_id)
1385
    .bind(bookmark)
1386
    .bind(trigger)
1387
    .bind(before_ms)
1388
    .fetch_all(pool)
1389
    .await
1390
}
1391
1392
/// The newest run of exactly this state (heads joined with `+`, sorted).
1393
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
1394
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
1395
        .bind(repo_id)
1396
        .bind(heads)
1397
        .fetch_optional(pool)
1398
        .await
1399
}
1400
1401
/// Record what became of job `job_id`'s signed receipt.
1402
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
1403
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
1404
        .bind(attest)
1405
        .bind(signer)
1406
        .bind(note)
1407
        .bind(job_id)
1408
        .execute(pool)
1409
        .await?;
1410
    Ok(())
1411
}
1412
1413
/// A job's artifact, kept as a blob of the run's repository.
1414
#[derive(Clone, Debug, FromRow)]
1415
pub struct Artifact {
1416
    pub job_id: i64,
1417
    pub name: String,
1418
    pub path: String,
1419
    pub blob: String,
1420
    pub size: i64,
1421
    /// BLAKE3 of the bytes.
1422
    pub content: String,
1423
    pub created_ms: i64,
1424
}
1425
1426
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
1427
    sqlx::query(
1428
        "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",
1429
    )
1430
    .bind(a.job_id)
1431
    .bind(&a.name)
1432
    .bind(&a.path)
1433
    .bind(&a.blob)
1434
    .bind(a.size)
1435
    .bind(&a.content)
1436
    .bind(a.created_ms)
1437
    .execute(pool)
1438
    .await?;
1439
    Ok(())
1440
}
1441
1442
/// Every artifact blob a repository's runs keep, for garbage collection to
1443
/// keep too (#126): the database is the only thing that names them.
1444
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
1445
    sqlx::query_scalar(
1446
        "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",
1447
    )
1448
    .bind(repo_id)
1449
    .fetch_all(pool)
1450
    .await
1451
}
1452
1453
/// Job `job_id`'s artifacts, by name; not its [`CHECKPOINT`], which no
1454
/// receipt names.
1455
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1456
    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
1457
}
1458
1459
/// The name a job's checkpoint is kept under (oxygenflow#77), beside its
1460
/// artifacts: no pipeline can declare it.
1461
pub const CHECKPOINT: &str = ".checkpoint";
1462
1463
/// The checkpoint an attempt of job `job_id` saved as its runner handed it
1464
/// back (oxygenflow#77), if one did.
1465
pub async fn checkpoint(pool: &Pool, job_id: i64) -> sqlx::Result<Option<Artifact>> {
1466
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 AND name = $2").bind(job_id).bind(CHECKPOINT).fetch_optional(pool).await
1467
}
1468
1469
/// An artifact with the run and job that made it, for a repository's list
1470
/// of every run's outputs (oxygenhub#254).
1471
#[derive(Clone, Debug, FromRow)]
1472
pub struct RepoArtifact {
1473
    pub run_number: i64,
1474
    pub bookmark: String,
1475
    pub job: String,
1476
    pub name: String,
1477
    pub path: String,
1478
    pub size: i64,
1479
    pub content: String,
1480
    pub created_ms: i64,
1481
}
1482
1483
/// A repository's newest artifacts, at most `limit`.
1484
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
1485
    sqlx::query_as(
1486
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
1487
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
1488
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
1489
    )
1490
    .bind(repo_id)
1491
    .bind(limit)
1492
    .fetch_all(pool)
1493
    .await
1494
}
1495
1496
/// Where an artifact with given content came from: the run and job that
1497
/// built it, and the job's signed receipt when one was kept.
1498
#[derive(Clone, Debug, FromRow)]
1499
pub struct Provenance {
1500
    pub run_number: i64,
1501
    pub job: String,
1502
    pub name: String,
1503
    pub receipt_attest: String,
1504
    pub receipt_signer: String,
1505
}
1506
1507
/// The build of the bytes whose BLAKE3 is `content` in repository
1508
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1509
/// run first.
1510
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
1511
    sqlx::query_as(
1512
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
1513
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
1514
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
1515
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
1516
    )
1517
    .bind(repo_id)
1518
    .bind(content)
1519
    .fetch_optional(pool)
1520
    .await
1521
}
1522
1523
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1524
/// whether it was.
1525
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
1526
    let r = sqlx::query(
1527
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
1528
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
1529
    )
1530
    .bind(who)
1531
    .bind(now_ms())
1532
    .bind(seal)
1533
    .bind(id)
1534
    .bind(via)
1535
    .execute(pool)
1536
    .await?;
1537
    Ok(r.rows_affected() > 0)
1538
}
1539
1540
/// Note who rejected job `id` (it is then finished as cancelled).
1541
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
1542
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
1543
        .bind(who)
1544
        .bind(now_ms())
1545
        .bind(id)
1546
        .bind(via)
1547
        .execute(pool)
1548
        .await?;
1549
    Ok(())
1550
}
1551
1552
/// Jobs waiting for a person, in runs still going.
1553
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
1554
    sqlx::query_as(
1555
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1556
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
1557
    )
1558
    .fetch_all(pool)
1559
    .await
1560
}
1561
1562
/// One deployment: a job for an environment that passed.
1563
#[derive(Clone, Debug, FromRow)]
1564
pub struct Deployment {
1565
    pub environment: String,
1566
    pub job: String,
1567
    pub run_number: i64,
1568
    pub state: String,
1569
    pub bookmark: String,
1570
    pub actor: String,
1571
    pub approved_by: String,
1572
    pub finished_ms: i64,
1573
}
1574
1575
/// A repository's deployments, newest first (oxygenflow#59).
1576
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
1577
    sqlx::query_as(
1578
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
1579
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1580
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
1581
    )
1582
    .bind(repo_id)
1583
    .bind(limit)
1584
    .fetch_all(pool)
1585
    .await
1586
}