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