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