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