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