OXYGENHUB
# c43e4f631d99 oxygenhub / crates / hub / src / db / flow.rs
56.2 KiB · Rust · last changed Runners hand jobs back, and the queue takes them first (closes #312, 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
/// Jobs running on a runner the hub has not heard from since `before`
910
/// (claims, heartbeats, logs): their leases lapsed (oxygenflow#76).
911
pub async fn running_on_silent_runners(pool: &Pool, before: i64) -> sqlx::Result<Vec<(Job, String)>> {
912
    let rows: Vec<(i64, String)> = sqlx::query_as(
913
        "SELECT j.id, r.name FROM flow_jobs j JOIN flow_runners r ON r.id = j.runner_id \
914
         WHERE j.status = 'running' AND r.last_seen_ms < $1 ORDER BY j.id",
915
    )
916
    .bind(before)
917
    .fetch_all(pool)
918
    .await?;
919
    let mut out = Vec::new();
920
    for (id, runner) in rows {
921
        if let Some(j) = job(pool, id).await? {
922
            out.push((j, runner));
923
        }
924
    }
925
    Ok(out)
926
}
927
928
/// The declines of job `job_id`, oldest first.
929
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
930
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = $1 ORDER BY ms")
931
        .bind(job_id)
932
        .fetch_all(pool)
933
        .await
934
}
935
936
/// A runner's latest declines, newest first, with where the job is.
937
#[derive(Clone, Debug, sqlx::FromRow)]
938
pub struct RunnerDecline {
939
    pub job_id: i64,
940
    pub job: String,
941
    pub run_number: i64,
942
    pub owner: String,
943
    pub name: String,
944
    pub reason: String,
945
    pub ms: i64,
946
}
947
948
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
949
    sqlx::query_as(
950
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
951
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
952
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = $1 ORDER BY d.ms DESC LIMIT $2",
953
    )
954
    .bind(runner_id)
955
    .bind(limit)
956
    .fetch_all(pool)
957
    .await
958
}
959
960
/// Queued jobs whose dependencies have passed, in their live runs, with
961
/// their repositories (owner, id): the ones a runner could take now.
962
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
963
/// (#259: how many ready jobs come first).
964
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
965
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
966
        "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 \
967
         WHERE j.status = 'queued'"
968
    ))
969
    .fetch_all(pool)
970
    .await?;
971
    Ok(rows.into_iter().collect())
972
}
973
974
/// How many jobs each runner is running now, by runner id (#259).
975
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
976
    let rows: Vec<(i64, i64)> =
977
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
978
            .fetch_all(pool)
979
            .await?;
980
    Ok(rows.into_iter().collect())
981
}
982
983
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
984
    let queued: Vec<Job> = sqlx::query_as(
985
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
986
         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",
987
    )
988
    .fetch_all(pool)
989
    .await?;
990
    let mut out = Vec::new();
991
    for j in queued {
992
        let mut ready = true;
993
        for d in j.depends_on() {
994
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = $1 AND name = $2")
995
                .bind(j.run_id)
996
                .bind(&d)
997
                .fetch_optional(pool)
998
                .await?;
999
            if st.as_deref() != Some("passed") {
1000
                ready = false;
1001
                break;
1002
            }
1003
        }
1004
        if !ready {
1005
            continue;
1006
        }
1007
        let repo: Option<(String, i64)> =
1008
            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")
1009
                .bind(j.run_id)
1010
                .fetch_optional(pool)
1011
                .await?;
1012
        if let Some((owner, id)) = repo {
1013
            out.push((j, owner, id));
1014
        }
1015
    }
1016
    Ok(out)
1017
}
1018
1019
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
1020
    sqlx::query("UPDATE flow_jobs SET waiting = $1 WHERE id = $2 AND waiting <> $3")
1021
        .bind(waiting)
1022
        .bind(job_id)
1023
        .bind(waiting)
1024
        .execute(pool)
1025
        .await?;
1026
    Ok(())
1027
}
1028
1029
/// Append records; returns how many were kept (the rest exceed the cap).
1030
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
1031
    let mut tx = super::begin_write(pool).await?;
1032
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1033
    let room = (cap - count).max(0) as usize;
1034
    let keep = &records[..records.len().min(room)];
1035
    for (i, r) in keep.iter().enumerate() {
1036
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES ($1, $2, $3, $4, $5)")
1037
            .bind(job_id)
1038
            .bind(count + i as i64 + 1)
1039
            .bind(r.t as i64)
1040
            .bind(&r.stream)
1041
            .bind(&r.text)
1042
            .execute(&mut *tx)
1043
            .await?;
1044
    }
1045
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + $1 WHERE id = $2")
1046
        .bind(keep.len() as i64)
1047
        .bind(job_id)
1048
        .execute(&mut *tx)
1049
        .await?;
1050
    tx.commit().await?;
1051
    Ok(keep.len())
1052
}
1053
1054
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
1055
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = $1 AND seq > $2 ORDER BY seq LIMIT $3")
1056
        .bind(job_id)
1057
        .bind(after)
1058
        .bind(limit)
1059
        .fetch_all(pool)
1060
        .await
1061
}
1062
1063
/// Jobs running since before `ms` (the oldest first).
1064
/// Jobs still running at `now` past their own time limit (`default_s` for
1065
/// one claimed without) plus `grace_ms`.
1066
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
1067
    sqlx::query_as(
1068
        "SELECT * FROM flow_jobs WHERE status = 'running' \
1069
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE $1 END) * 1000 + $2 < $3 ORDER BY started_ms",
1070
    )
1071
    .bind(default_s as i64)
1072
    .bind(grace_ms)
1073
    .bind(now)
1074
    .fetch_all(pool)
1075
    .await
1076
}
1077
1078
/// Record the limit a claimed job runs under.
1079
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
1080
    sqlx::query("UPDATE flow_jobs SET timeout_s = $1 WHERE id = $2").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
1081
    Ok(())
1082
}
1083
1084
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
1085
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < $1 ORDER BY started_ms")
1086
        .bind(ms)
1087
        .fetch_all(pool)
1088
        .await
1089
}
1090
1091
/// The jobs running on the runner with this id.
1092
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
1093
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = $1 ORDER BY id").bind(runner_id).fetch_all(pool).await
1094
}
1095
1096
pub struct Outcome<'a> {
1097
    pub status: &'a str,
1098
    pub exit_code: Option<i64>,
1099
    pub error: &'a str,
1100
    pub receipt: &'a str,
1101
    pub receipt_hash: &'a str,
1102
}
1103
1104
/// Record a job's end, skip the jobs that can no longer run, and settle the
1105
/// run. Returns the jobs whose status changed (for their checks).
1106
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
1107
    let mut tx = super::begin_write(pool).await?;
1108
    let now = now_ms();
1109
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = $1").bind(job_id).fetch_one(&mut *tx).await?;
1110
    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")
1111
        .bind(o.status)
1112
        .bind(o.exit_code)
1113
        .bind(o.error)
1114
        .bind(o.receipt)
1115
        .bind(o.receipt_hash)
1116
        .bind(now)
1117
        .bind(job_id)
1118
        .execute(&mut *tx)
1119
        .await?;
1120
    // A pass teaches what its image is for, when nobody has read it
1121
    // (oxygenhub#173): the architecture of the runner it passed on.
1122
    if o.status == "passed" {
1123
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
1124
            .ok()
1125
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
1126
            .unwrap_or_default();
1127
        if rootfs.len() == 64 {
1128
            sqlx::query(
1129
                "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 \
1130
                 WHERE j.id = $3 AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
1131
            )
1132
            .bind(&rootfs)
1133
            .bind(now)
1134
            .bind(job_id)
1135
            .execute(&mut *tx)
1136
            .await?;
1137
        }
1138
    }
1139
    let mut changed = vec![job_id];
1140
    // Dependents of anything that did not pass are skipped, transitively.
1141
    loop {
1142
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1143
        let blocked: Vec<i64> = all
1144
            .iter()
1145
            .filter(|x| x.status == "queued")
1146
            .filter(|x| {
1147
                x.depends_on()
1148
                    .iter()
1149
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error" | "cancelled")))
1150
            })
1151
            .map(|x| x.id)
1152
            .collect();
1153
        if blocked.is_empty() {
1154
            break;
1155
        }
1156
        for id in blocked {
1157
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = $1 WHERE id = $2")
1158
                .bind(now)
1159
                .bind(id)
1160
                .execute(&mut *tx)
1161
                .await?;
1162
            changed.push(id);
1163
        }
1164
    }
1165
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(j.run_id).fetch_all(&mut *tx).await?;
1166
    if all.iter().all(Job::done) {
1167
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
1168
        sqlx::query("UPDATE flow_runs SET status = $1, finished_ms = $2 WHERE id = $3")
1169
            .bind(status)
1170
            .bind(now)
1171
            .bind(j.run_id)
1172
            .execute(&mut *tx)
1173
            .await?;
1174
    }
1175
    tx.commit().await?;
1176
    let mut out = Vec::new();
1177
    for id in changed {
1178
        if let Some(x) = job(pool, id).await? {
1179
            out.push(x);
1180
        }
1181
    }
1182
    Ok(out)
1183
}
1184
1185
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
1186
/// and so does the run. A runner learns of it when the hub next refuses
1187
/// its log lines, and stops the job. Returns the jobs whose status changed.
1188
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
1189
    let now = now_ms();
1190
    let mut tx = pool.begin().await?;
1191
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = $1 AND status IN ('queued', 'running')")
1192
        .bind(run_id)
1193
        .fetch_all(&mut *tx)
1194
        .await?;
1195
    sqlx::query(
1196
        "UPDATE flow_jobs SET status = 'cancelled', error = $1, finished_ms = $2, token_hash = ''
1197
         WHERE run_id = $3 AND status IN ('queued', 'running')",
1198
    )
1199
    .bind(why)
1200
    .bind(now)
1201
    .bind(run_id)
1202
    .execute(&mut *tx)
1203
    .await?;
1204
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = $1 WHERE id = $2 AND status IN ('queued', 'running')")
1205
        .bind(now)
1206
        .bind(run_id)
1207
        .execute(&mut *tx)
1208
        .await?;
1209
    tx.commit().await?;
1210
    let mut out = Vec::new();
1211
    for (id,) in ids {
1212
        if let Some(x) = job(pool, id).await? {
1213
            out.push(x);
1214
        }
1215
    }
1216
    Ok(out)
1217
}
1218
1219
/// Run job `name` of finished run `run_id` again, with every job that
1220
/// depends on it (oxygenflow#31): back to the queue as if new, their logs,
1221
/// artifacts and reports gone, and the run running again. The jobs they
1222
/// depend on keep their results. The jobs reset; none when there is no
1223
/// such job.
1224
pub async fn rerun_job(pool: &Pool, run_id: i64, name: &str) -> sqlx::Result<Vec<Job>> {
1225
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = $1").bind(run_id).fetch_all(pool).await?;
1226
    if !all.iter().any(|j| j.name == name) {
1227
        return Ok(Vec::new());
1228
    }
1229
    let mut again = vec![name.to_string()];
1230
    loop {
1231
        let more: Vec<String> = all
1232
            .iter()
1233
            .filter(|j| !again.contains(&j.name) && j.depends_on().iter().any(|d| again.contains(d)))
1234
            .map(|j| j.name.clone())
1235
            .collect();
1236
        if more.is_empty() {
1237
            break;
1238
        }
1239
        again.extend(more);
1240
    }
1241
    let ids: Vec<i64> = all.iter().filter(|j| again.contains(&j.name)).map(|j| j.id).collect();
1242
    let mut tx = pool.begin().await?;
1243
    for id in &ids {
1244
        for table in ["flow_logs", "flow_artifacts", "flow_declines", "test_reports", "coverage_reports", "reports"] {
1245
            sqlx::query(&format!("DELETE FROM {table} WHERE job_id = $1")).bind(id).execute(&mut *tx).await?;
1246
        }
1247
        sqlx::query(
1248
            "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, finished_ms = NULL,
1249
             exit_code = NULL, error = '', receipt = '', receipt_hash = '', log_count = 0, also_read = '', receipt_attest = '',
1250
             receipt_signer = '', receipt_note = '', runner_id = NULL, waiting = '', placed = '', peak_disk_mib = NULL,
1251
             peak_memory_mib = NULL, approval = CASE WHEN approval = '' THEN '' ELSE 'waiting' END, approved_by = '',
1252
             approved_ms = NULL, approval_seal = '', approved_via = '', queued_ms = $2, ready_ms = NULL, handed_back_ms = NULL,
1253
             handbacks = 0 WHERE id = $1",
1254
        )
1255
        .bind(id)
1256
        .bind(now_ms())
1257
        .execute(&mut *tx)
1258
        .await?;
1259
    }
1260
    sqlx::query("UPDATE flow_runs SET status = 'running', finished_ms = NULL WHERE id = $1").bind(run_id).execute(&mut *tx).await?;
1261
    tx.commit().await?;
1262
    let mut out = Vec::new();
1263
    for id in ids {
1264
        if let Some(x) = job(pool, id).await? {
1265
            out.push(x);
1266
        }
1267
    }
1268
    Ok(out)
1269
}
1270
1271
/// The runs of `bookmark` started by `trigger` still going, older than run
1272
/// `number`: those a newer run supersedes (#267). With `running_too`
1273
/// false, only those still queued.
1274
pub async fn live_runs_before(
1275
    pool: &Pool,
1276
    repo_id: i64,
1277
    bookmark: &str,
1278
    trigger: &str,
1279
    number: i64,
1280
    running_too: bool,
1281
) -> sqlx::Result<Vec<Run>> {
1282
    sqlx::query_as(
1283
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND number < $3 AND trigger = $4
1284
         AND (status = 'queued' OR ($5 AND status = 'running')) ORDER BY id",
1285
    )
1286
    .bind(repo_id)
1287
    .bind(bookmark)
1288
    .bind(number)
1289
    .bind(trigger)
1290
    .bind(running_too)
1291
    .fetch_all(pool)
1292
    .await
1293
}
1294
1295
/// The runs on `bookmark` that no runner has started yet: queued, with
1296
/// the given trigger, created before `before_ms` (#263).
1297
pub async fn unstarted_runs_on(pool: &Pool, repo_id: i64, bookmark: &str, trigger: &str, before_ms: i64) -> sqlx::Result<Vec<Run>> {
1298
    sqlx::query_as(
1299
        "SELECT * FROM flow_runs WHERE repo_id = $1 AND bookmark = $2 AND trigger = $3 AND status = 'queued' AND created_ms <= $4 ORDER BY id",
1300
    )
1301
    .bind(repo_id)
1302
    .bind(bookmark)
1303
    .bind(trigger)
1304
    .bind(before_ms)
1305
    .fetch_all(pool)
1306
    .await
1307
}
1308
1309
/// The newest run of exactly this state (heads joined with `+`, sorted).
1310
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
1311
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = $1 AND heads = $2 ORDER BY id DESC LIMIT 1")
1312
        .bind(repo_id)
1313
        .bind(heads)
1314
        .fetch_optional(pool)
1315
        .await
1316
}
1317
1318
/// Record what became of job `job_id`'s signed receipt.
1319
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
1320
    sqlx::query("UPDATE flow_jobs SET receipt_attest = $1, receipt_signer = $2, receipt_note = $3 WHERE id = $4")
1321
        .bind(attest)
1322
        .bind(signer)
1323
        .bind(note)
1324
        .bind(job_id)
1325
        .execute(pool)
1326
        .await?;
1327
    Ok(())
1328
}
1329
1330
/// A job's artifact, kept as a blob of the run's repository.
1331
#[derive(Clone, Debug, FromRow)]
1332
pub struct Artifact {
1333
    pub job_id: i64,
1334
    pub name: String,
1335
    pub path: String,
1336
    pub blob: String,
1337
    pub size: i64,
1338
    /// BLAKE3 of the bytes.
1339
    pub content: String,
1340
    pub created_ms: i64,
1341
}
1342
1343
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
1344
    sqlx::query(
1345
        "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",
1346
    )
1347
    .bind(a.job_id)
1348
    .bind(&a.name)
1349
    .bind(&a.path)
1350
    .bind(&a.blob)
1351
    .bind(a.size)
1352
    .bind(&a.content)
1353
    .bind(a.created_ms)
1354
    .execute(pool)
1355
    .await?;
1356
    Ok(())
1357
}
1358
1359
/// Every artifact blob a repository's runs keep, for garbage collection to
1360
/// keep too (#126): the database is the only thing that names them.
1361
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
1362
    sqlx::query_scalar(
1363
        "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",
1364
    )
1365
    .bind(repo_id)
1366
    .fetch_all(pool)
1367
    .await
1368
}
1369
1370
/// Job `job_id`'s artifacts, by name.
1371
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
1372
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = $1 ORDER BY name").bind(job_id).fetch_all(pool).await
1373
}
1374
1375
/// An artifact with the run and job that made it, for a repository's list
1376
/// of every run's outputs (oxygenhub#254).
1377
#[derive(Clone, Debug, FromRow)]
1378
pub struct RepoArtifact {
1379
    pub run_number: i64,
1380
    pub bookmark: String,
1381
    pub job: String,
1382
    pub name: String,
1383
    pub path: String,
1384
    pub size: i64,
1385
    pub content: String,
1386
    pub created_ms: i64,
1387
}
1388
1389
/// A repository's newest artifacts, at most `limit`.
1390
pub async fn repo_artifacts(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<RepoArtifact>> {
1391
    sqlx::query_as(
1392
        "SELECT r.number AS run_number, r.bookmark, j.name AS job, a.name, a.path, a.size, a.content, a.created_ms
1393
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id
1394
         WHERE r.repo_id = $1 ORDER BY a.created_ms DESC, r.number DESC, j.name, a.name LIMIT $2",
1395
    )
1396
    .bind(repo_id)
1397
    .bind(limit)
1398
    .fetch_all(pool)
1399
    .await
1400
}
1401
1402
/// Where an artifact with given content came from: the run and job that
1403
/// built it, and the job's signed receipt when one was kept.
1404
#[derive(Clone, Debug, FromRow)]
1405
pub struct Provenance {
1406
    pub run_number: i64,
1407
    pub job: String,
1408
    pub name: String,
1409
    pub receipt_attest: String,
1410
    pub receipt_signer: String,
1411
}
1412
1413
/// The build of the bytes whose BLAKE3 is `content` in repository
1414
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1415
/// run first.
1416
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
1417
    sqlx::query_as(
1418
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
1419
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
1420
         WHERE r.repo_id = $1 AND a.content = $2 AND j.status = 'passed' \
1421
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
1422
    )
1423
    .bind(repo_id)
1424
    .bind(content)
1425
    .fetch_optional(pool)
1426
    .await
1427
}
1428
1429
/// Approve job `id` if it is still waiting for a person (oxygenflow#57);
1430
/// whether it was.
1431
pub async fn approve_job(pool: &Pool, id: i64, who: &str, seal: &str, via: &str) -> sqlx::Result<bool> {
1432
    let r = sqlx::query(
1433
        "UPDATE flow_jobs SET approval = 'approved', approved_by = $1, approved_ms = $2, approval_seal = $3, approved_via = $5 \
1434
         WHERE id = $4 AND status = 'queued' AND approval = 'waiting'",
1435
    )
1436
    .bind(who)
1437
    .bind(now_ms())
1438
    .bind(seal)
1439
    .bind(id)
1440
    .bind(via)
1441
    .execute(pool)
1442
    .await?;
1443
    Ok(r.rows_affected() > 0)
1444
}
1445
1446
/// Note who rejected job `id` (it is then finished as cancelled).
1447
pub async fn note_rejection(pool: &Pool, id: i64, who: &str, via: &str) -> sqlx::Result<()> {
1448
    sqlx::query("UPDATE flow_jobs SET approved_by = $1, approved_ms = $2, approved_via = $4 WHERE id = $3")
1449
        .bind(who)
1450
        .bind(now_ms())
1451
        .bind(id)
1452
        .bind(via)
1453
        .execute(pool)
1454
        .await?;
1455
    Ok(())
1456
}
1457
1458
/// Jobs waiting for a person, in runs still going.
1459
pub async fn waiting_for_approval(pool: &Pool) -> sqlx::Result<Vec<Job>> {
1460
    sqlx::query_as(
1461
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1462
         WHERE j.status = 'queued' AND j.approval = 'waiting' AND r.status IN ('queued', 'running')",
1463
    )
1464
    .fetch_all(pool)
1465
    .await
1466
}
1467
1468
/// One deployment: a job for an environment that passed.
1469
#[derive(Clone, Debug, FromRow)]
1470
pub struct Deployment {
1471
    pub environment: String,
1472
    pub job: String,
1473
    pub run_number: i64,
1474
    pub state: String,
1475
    pub bookmark: String,
1476
    pub actor: String,
1477
    pub approved_by: String,
1478
    pub finished_ms: i64,
1479
}
1480
1481
/// A repository's deployments, newest first (oxygenflow#59).
1482
pub async fn deployments(pool: &Pool, repo_id: i64, limit: i64) -> sqlx::Result<Vec<Deployment>> {
1483
    sqlx::query_as(
1484
        "SELECT j.environment, j.name AS job, r.number AS run_number, r.state, r.bookmark, r.actor, j.approved_by, \
1485
         COALESCE(j.finished_ms, 0) AS finished_ms FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
1486
         WHERE r.repo_id = $1 AND j.environment != '' AND j.status = 'passed' ORDER BY j.finished_ms DESC LIMIT $2",
1487
    )
1488
    .bind(repo_id)
1489
    .bind(limit)
1490
    .fetch_all(pool)
1491
    .await
1492
}