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