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