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