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