OXYGENHUB
# dbcb0b813caa oxygenhub / crates / hub / src / db / flow.rs
21.6 KiB · Rust · last changed Runs by event: on decides the jobs; tag pushes run tag jobs 1 month 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, 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
}
91
92
impl Job {
93
    pub fn depends_on(&self) -> Vec<String> {
94
        serde_json::from_str(&self.depends).unwrap_or_default()
95
    }
96
97
    pub fn done(&self) -> bool {
98
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error")
99
    }
100
}
101
102
#[derive(Clone, Debug, FromRow)]
103
pub struct LogLine {
104
    pub seq: i64,
105
    pub t: i64,
106
    pub stream: String,
107
    pub text: String,
108
}
109
110
/// A job as the trigger creates it.
111
pub struct NewJob {
112
    pub name: String,
113
    pub depth: i64,
114
    pub depends: Vec<String>,
115
    pub spec: String,
116
    pub sandbox: String,
117
    pub runtime: String,
118
}
119
120
pub struct NewRun<'a> {
121
    pub repo_id: i64,
122
    pub bookmark: &'a str,
123
    pub state: &'a str,
124
    pub heads: &'a str,
125
    pub pipeline_hash: &'a str,
126
    pub actor: &'a str,
127
    /// `push`, `manual` or `rerun:N`.
128
    pub trigger: &'a str,
129
    /// Problems when the pipeline is invalid: the run is recorded in error.
130
    pub error: Option<&'a str>,
131
}
132
133
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
134
    let mut tx = super::begin_write(pool).await?;
135
    let now = now_ms();
136
    let status = if r.error.is_some() { "error" } else { "queued" };
137
    let id: i64 = sqlx::query_scalar(
138
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
139
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
140
    )
141
    .bind(r.repo_id)
142
    .bind(r.repo_id)
143
    .bind(r.bookmark)
144
    .bind(r.state)
145
    .bind(r.heads)
146
    .bind(r.pipeline_hash)
147
    .bind(status)
148
    .bind(r.error.unwrap_or(""))
149
    .bind(r.actor)
150
    .bind(r.trigger)
151
    .bind(now)
152
    .bind(r.error.map(|_| now))
153
    .fetch_one(&mut *tx)
154
    .await?;
155
    for j in jobs {
156
        sqlx::query(
157
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued')",
158
        )
159
        .bind(id)
160
        .bind(&j.name)
161
        .bind(j.depth)
162
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
163
        .bind(&j.spec)
164
        .bind(&j.sandbox)
165
        .bind(&j.runtime)
166
        .execute(&mut *tx)
167
        .await?;
168
    }
169
    tx.commit().await?;
170
    Ok(id)
171
}
172
173
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
174
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
175
    let mut out: Vec<String> = [spec, sandbox]
176
        .iter()
177
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
178
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
179
        .filter_map(|l| l.as_str().map(String::from))
180
        .collect();
181
    out.sort();
182
    out.dedup();
183
    out
184
}
185
186
impl Job {
187
    /// The runner labels this job needs.
188
    pub fn needs(&self) -> Vec<String> {
189
        labels_in(&self.spec, &self.sandbox)
190
    }
191
}
192
193
/// A job waiting for or held by a runner, with where it comes from.
194
#[derive(Clone, Debug, FromRow)]
195
pub struct QueueEntry {
196
    pub job_id: i64,
197
    pub run_id: i64,
198
    pub repo_id: i64,
199
    pub owner: String,
200
    pub name: String,
201
    pub visibility: String,
202
    pub run_number: i64,
203
    pub job: String,
204
    pub status: String,
205
    /// The runner holding it, when running.
206
    pub runner: String,
207
    pub spec: String,
208
    pub sandbox: String,
209
}
210
211
impl QueueEntry {
212
    /// The runner labels the job needs.
213
    pub fn needs(&self) -> Vec<String> {
214
        labels_in(&self.spec, &self.sandbox)
215
    }
216
}
217
218
/// Every job of a live run that is running or queued: running ones first,
219
/// then queued ones in the order runners claim them (hub spec §13.2).
220
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
221
    sqlx::query_as(
222
        "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 \
223
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
224
         WHERE j.status IN ('queued', 'running') AND r.status IN ('queued', 'running') \
225
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
226
    )
227
    .fetch_all(pool)
228
    .await
229
}
230
231
/// A repository's runs, newest first, numbered below `before`.
232
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
233
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
234
        .bind(repo_id)
235
        .bind(before.unwrap_or(i64::MAX))
236
        .bind(limit)
237
        .fetch_all(pool)
238
        .await
239
}
240
241
/// The latest run on this bookmark of this repository, for what a push
242
/// changed since (a job's scope).
243
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
244
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND heads != '' ORDER BY id DESC LIMIT 1")
245
        .bind(repo_id)
246
        .bind(bookmark)
247
        .fetch_optional(pool)
248
        .await
249
}
250
251
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
252
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
253
        .bind(repo_id)
254
        .bind(before.unwrap_or(i64::MAX))
255
        .bind(limit)
256
        .fetch_all(pool)
257
        .await
258
}
259
260
/// A repository's run by its number there.
261
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
262
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
263
}
264
265
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
266
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
267
}
268
269
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
270
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
271
}
272
273
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
274
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
275
}
276
277
/// The running job a job token belongs to, while it may still be used.
278
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
279
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
280
        .bind(token_hash)
281
        .bind(now_ms() - max_age_ms)
282
        .fetch_optional(pool)
283
        .await
284
}
285
286
/// Take the oldest queued job whose dependencies all passed and whose tier
287
/// the runner offers, and mark it running for `runner` with a token.
288
/// Let a job's token also read these repositories (its pinned subrepos).
289
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
290
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
291
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
292
    Ok(())
293
}
294
295
impl Job {
296
    pub fn also_read_ids(&self) -> Vec<i64> {
297
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
298
    }
299
}
300
301
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
302
/// limit, and the rootfs images it holds, `None` when it does not say.
303
#[derive(Clone, Debug, Default)]
304
pub struct Room {
305
    pub memory_mib: Option<u32>,
306
    pub cpus: Option<u32>,
307
    pub images: Option<std::collections::HashSet<String>>,
308
}
309
310
impl Room {
311
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
312
    /// and its rootfs image among the runner's (oxygenhub#73).
313
    pub fn fits(&self, sandbox_json: &str) -> bool {
314
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
315
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
316
        let rootfs = v["rootfs"].as_str().unwrap_or("");
317
        self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
318
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
319
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)))
320
    }
321
}
322
323
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
324
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
325
}
326
327
/// The oldest runnable job that fits in `room`.
328
/// The first queued job a runner with these tiers, this room and this
329
/// scope may take, now running under `runner`. A scoped runner never sees
330
/// another scope's jobs (oxygenhub#41).
331
pub async fn claim_within(
332
    pool: &Pool,
333
    runtimes: &[String],
334
    runner: &str,
335
    token_hash: &str,
336
    room: Room,
337
    scope: &super::runners::Scope,
338
    labels: &[String],
339
) -> sqlx::Result<Option<Job>> {
340
    let mut tx = super::begin_write(pool).await?;
341
    let queued: Vec<Job> = sqlx::query_as(
342
        "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 \
343
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') \
344
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
345
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
346
    )
347
    .bind(&scope.owner)
348
    .bind(&scope.owner)
349
    .bind(scope.repo_id)
350
    .bind(scope.repo_id)
351
    .fetch_all(&mut *tx)
352
    .await?;
353
    for j in queued {
354
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) {
355
            continue;
356
        }
357
        // Every label the job and its sandbox ask for (`runs-on`).
358
        if !j.needs().iter().all(|l| labels.contains(l)) {
359
            continue;
360
        }
361
        let deps = j.depends_on();
362
        if !deps.is_empty() {
363
            let mut passed = 0i64;
364
            for d in &deps {
365
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
366
                    .bind(j.run_id)
367
                    .bind(d)
368
                    .fetch_optional(&mut *tx)
369
                    .await?;
370
                if st.as_deref() == Some("passed") {
371
                    passed += 1;
372
                }
373
            }
374
            if passed != deps.len() as i64 {
375
                continue;
376
            }
377
        }
378
        let now = now_ms();
379
        let done = sqlx::query(
380
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
381
        )
382
        .bind(runner)
383
        .bind(token_hash)
384
        .bind(now)
385
        .bind(j.id)
386
        .execute(&mut *tx)
387
        .await?;
388
        if done.rows_affected() == 1 {
389
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
390
                .bind(j.run_id)
391
                .execute(&mut *tx)
392
                .await?;
393
            tx.commit().await?;
394
            return job(pool, j.id).await;
395
        }
396
    }
397
    tx.commit().await?;
398
    Ok(None)
399
}
400
401
/// Append records; returns how many were kept (the rest exceed the cap).
402
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
403
    let mut tx = super::begin_write(pool).await?;
404
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
405
    let room = (cap - count).max(0) as usize;
406
    let keep = &records[..records.len().min(room)];
407
    for (i, r) in keep.iter().enumerate() {
408
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
409
            .bind(job_id)
410
            .bind(count + i as i64 + 1)
411
            .bind(r.t as i64)
412
            .bind(&r.stream)
413
            .bind(&r.text)
414
            .execute(&mut *tx)
415
            .await?;
416
    }
417
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
418
        .bind(keep.len() as i64)
419
        .bind(job_id)
420
        .execute(&mut *tx)
421
        .await?;
422
    tx.commit().await?;
423
    Ok(keep.len())
424
}
425
426
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
427
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
428
        .bind(job_id)
429
        .bind(after)
430
        .bind(limit)
431
        .fetch_all(pool)
432
        .await
433
}
434
435
/// Jobs running since before `ms` (the oldest first).
436
/// Jobs still running at `now` past their own time limit (`default_s` for
437
/// one claimed without) plus `grace_ms`.
438
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
439
    sqlx::query_as(
440
        "SELECT * FROM flow_jobs WHERE status = 'running' \
441
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE ? END) * 1000 + ? < ? ORDER BY started_ms",
442
    )
443
    .bind(default_s as i64)
444
    .bind(grace_ms)
445
    .bind(now)
446
    .fetch_all(pool)
447
    .await
448
}
449
450
/// Record the limit a claimed job runs under.
451
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
452
    sqlx::query("UPDATE flow_jobs SET timeout_s = ? WHERE id = ?").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
453
    Ok(())
454
}
455
456
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
457
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
458
        .bind(ms)
459
        .fetch_all(pool)
460
        .await
461
}
462
463
/// The jobs running on the runner with this id.
464
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
465
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = ? ORDER BY id").bind(runner_id).fetch_all(pool).await
466
}
467
468
pub struct Outcome<'a> {
469
    pub status: &'a str,
470
    pub exit_code: Option<i64>,
471
    pub error: &'a str,
472
    pub receipt: &'a str,
473
    pub receipt_hash: &'a str,
474
}
475
476
/// Record a job's end, skip the jobs that can no longer run, and settle the
477
/// run. Returns the jobs whose status changed (for their checks).
478
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
479
    let mut tx = super::begin_write(pool).await?;
480
    let now = now_ms();
481
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
482
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
483
        .bind(o.status)
484
        .bind(o.exit_code)
485
        .bind(o.error)
486
        .bind(o.receipt)
487
        .bind(o.receipt_hash)
488
        .bind(now)
489
        .bind(job_id)
490
        .execute(&mut *tx)
491
        .await?;
492
    let mut changed = vec![job_id];
493
    // Dependents of anything that did not pass are skipped, transitively.
494
    loop {
495
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
496
        let blocked: Vec<i64> = all
497
            .iter()
498
            .filter(|x| x.status == "queued")
499
            .filter(|x| {
500
                x.depends_on()
501
                    .iter()
502
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
503
            })
504
            .map(|x| x.id)
505
            .collect();
506
        if blocked.is_empty() {
507
            break;
508
        }
509
        for id in blocked {
510
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
511
                .bind(now)
512
                .bind(id)
513
                .execute(&mut *tx)
514
                .await?;
515
            changed.push(id);
516
        }
517
    }
518
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
519
    if all.iter().all(Job::done) {
520
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
521
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
522
            .bind(status)
523
            .bind(now)
524
            .bind(j.run_id)
525
            .execute(&mut *tx)
526
            .await?;
527
    }
528
    tx.commit().await?;
529
    let mut out = Vec::new();
530
    for id in changed {
531
        if let Some(x) = job(pool, id).await? {
532
            out.push(x);
533
        }
534
    }
535
    Ok(out)
536
}
537
538
/// The newest run of exactly this state (heads joined with `+`, sorted).
539
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
540
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
541
        .bind(repo_id)
542
        .bind(heads)
543
        .fetch_optional(pool)
544
        .await
545
}
546
547
/// Record what became of job `job_id`'s signed receipt.
548
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
549
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
550
        .bind(attest)
551
        .bind(signer)
552
        .bind(note)
553
        .bind(job_id)
554
        .execute(pool)
555
        .await?;
556
    Ok(())
557
}
558
559
/// A job's artifact, kept as a blob of the run's repository.
560
#[derive(Clone, Debug, FromRow)]
561
pub struct Artifact {
562
    pub job_id: i64,
563
    pub name: String,
564
    pub path: String,
565
    pub blob: String,
566
    pub size: i64,
567
    /// BLAKE3 of the bytes.
568
    pub content: String,
569
    pub created_ms: i64,
570
}
571
572
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
573
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
574
        .bind(a.job_id)
575
        .bind(&a.name)
576
        .bind(&a.path)
577
        .bind(&a.blob)
578
        .bind(a.size)
579
        .bind(&a.content)
580
        .bind(a.created_ms)
581
        .execute(pool)
582
        .await?;
583
    Ok(())
584
}
585
586
/// Job `job_id`'s artifacts, by name.
587
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
588
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
589
}
590
591
/// Where an artifact with given content came from: the run and job that
592
/// built it, and the job's signed receipt when one was kept.
593
#[derive(Clone, Debug, FromRow)]
594
pub struct Provenance {
595
    pub run_number: i64,
596
    pub job: String,
597
    pub name: String,
598
    pub receipt_attest: String,
599
    pub receipt_signer: String,
600
}
601
602
/// The build of the bytes whose BLAKE3 is `content` in repository
603
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
604
/// run first.
605
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
606
    sqlx::query_as(
607
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
608
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
609
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
610
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
611
    )
612
    .bind(repo_id)
613
    .bind(content)
614
    .fetch_optional(pool)
615
    .await
616
}