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