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