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