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