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