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