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