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