OXYGENHUB
◆ v0.2.0 oxygenhub / crates / hub / src / db / flow.rs
18.8 KiB · Rust · last changed Flow: jobs that ask for runner labels go to runners with them (refs #41, part 3) 1 month ago source blame history raw
42fa9554 Andy McCall ↶ 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,
a0d4bbfb Andy McCall ↶ 10
    /// The run's number within its repository, from 1 (migration 0019).
11
    #[sqlx(default)]
12
    pub number: i64,
1edac4b6 Andy McCall ↶ 13
    /// `push`, `manual` or `rerun:N` (migration 0020).
14
    #[sqlx(default)]
15
    pub trigger: String,
42fa9554 Andy McCall ↶ 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 {
1edac4b6 Andy McCall ↶ 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
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", &t[6..], self.actor),
33
            _ => format!("pushed by {}", self.actor),
34
        }
35
    }
36
42fa9554 Andy McCall ↶ 37
    pub fn head_list(&self) -> Vec<&str> {
38
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
39
    }
40
41
    pub fn live(&self) -> bool {
42
        matches!(self.status.as_str(), "queued" | "running")
43
    }
44
}
45
46
#[derive(Clone, Debug, FromRow)]
47
pub struct Job {
48
    pub id: i64,
49
    pub run_id: i64,
50
    pub name: String,
51
    pub depth: i64,
52
    pub depends: String,
53
    pub spec: String,
54
    pub sandbox: String,
55
    pub runtime: String,
56
    pub status: String,
57
    pub runner: String,
58
    pub token_hash: String,
59
    pub started_ms: Option<i64>,
60
    pub finished_ms: Option<i64>,
61
    pub exit_code: Option<i64>,
62
    pub error: String,
63
    pub receipt: String,
64
    pub receipt_hash: String,
65
    pub log_count: i64,
fd3db644 Andy McCall ↶ 66
    /// Comma-separated ids of other repositories the job token may read.
67
    pub also_read: String,
cc19697f Andy McCall ↶ 68
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
69
    pub receipt_attest: String,
70
    /// Who signed it: the runner's identity name.
71
    pub receipt_signer: String,
72
    /// Why a signed receipt was not kept.
73
    pub receipt_note: String,
42fa9554 Andy McCall ↶ 74
}
75
76
impl Job {
77
    pub fn depends_on(&self) -> Vec<String> {
78
        serde_json::from_str(&self.depends).unwrap_or_default()
79
    }
80
81
    pub fn done(&self) -> bool {
82
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error")
83
    }
84
}
85
86
#[derive(Clone, Debug, FromRow)]
87
pub struct LogLine {
88
    pub seq: i64,
89
    pub t: i64,
90
    pub stream: String,
91
    pub text: String,
92
}
93
94
/// A job as the trigger creates it.
95
pub struct NewJob {
96
    pub name: String,
97
    pub depth: i64,
98
    pub depends: Vec<String>,
99
    pub spec: String,
100
    pub sandbox: String,
101
    pub runtime: String,
102
}
103
104
pub struct NewRun<'a> {
105
    pub repo_id: i64,
106
    pub bookmark: &'a str,
107
    pub state: &'a str,
108
    pub heads: &'a str,
109
    pub pipeline_hash: &'a str,
110
    pub actor: &'a str,
1edac4b6 Andy McCall ↶ 111
    /// `push`, `manual` or `rerun:N`.
112
    pub trigger: &'a str,
42fa9554 Andy McCall ↶ 113
    /// Problems when the pipeline is invalid: the run is recorded in error.
114
    pub error: Option<&'a str>,
115
}
116
117
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
941abdd6 Andy McCall ↶ 118
    let mut tx = super::begin_write(pool).await?;
42fa9554 Andy McCall ↶ 119
    let now = now_ms();
120
    let status = if r.error.is_some() { "error" } else { "queued" };
121
    let id: i64 = sqlx::query_scalar(
1edac4b6 Andy McCall ↶ 122
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
123
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
42fa9554 Andy McCall ↶ 124
    )
125
    .bind(r.repo_id)
a0d4bbfb Andy McCall ↶ 126
    .bind(r.repo_id)
42fa9554 Andy McCall ↶ 127
    .bind(r.bookmark)
128
    .bind(r.state)
129
    .bind(r.heads)
130
    .bind(r.pipeline_hash)
131
    .bind(status)
132
    .bind(r.error.unwrap_or(""))
133
    .bind(r.actor)
1edac4b6 Andy McCall ↶ 134
    .bind(r.trigger)
42fa9554 Andy McCall ↶ 135
    .bind(now)
136
    .bind(r.error.map(|_| now))
137
    .fetch_one(&mut *tx)
138
    .await?;
139
    for j in jobs {
140
        sqlx::query(
141
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued')",
142
        )
143
        .bind(id)
144
        .bind(&j.name)
145
        .bind(j.depth)
146
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
147
        .bind(&j.spec)
148
        .bind(&j.sandbox)
149
        .bind(&j.runtime)
150
        .execute(&mut *tx)
151
        .await?;
152
    }
153
    tx.commit().await?;
154
    Ok(id)
155
}
156
c4c87f48 Andy McCall ↶ 157
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
158
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
159
    let mut out: Vec<String> = [spec, sandbox]
160
        .iter()
161
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
162
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
163
        .filter_map(|l| l.as_str().map(String::from))
164
        .collect();
165
    out.sort();
166
    out.dedup();
167
    out
168
}
169
170
impl Job {
171
    /// The runner labels this job needs.
172
    pub fn needs(&self) -> Vec<String> {
173
        labels_in(&self.spec, &self.sandbox)
174
    }
175
}
176
bf3d0754 Andy McCall ↶ 177
/// A job waiting for or held by a runner, with where it comes from.
178
#[derive(Clone, Debug, FromRow)]
179
pub struct QueueEntry {
180
    pub job_id: i64,
181
    pub run_id: i64,
182
    pub repo_id: i64,
183
    pub owner: String,
184
    pub name: String,
185
    pub visibility: String,
186
    pub run_number: i64,
187
    pub job: String,
188
    pub status: String,
b66e70b7 Andy McCall ↶ 189
    /// The runner holding it, when running.
190
    pub runner: String,
c4c87f48 Andy McCall ↶ 191
    pub spec: String,
192
    pub sandbox: String,
193
}
194
195
impl QueueEntry {
196
    /// The runner labels the job needs.
197
    pub fn needs(&self) -> Vec<String> {
198
        labels_in(&self.spec, &self.sandbox)
199
    }
bf3d0754 Andy McCall ↶ 200
}
201
202
/// Every job of a live run that is running or queued: running ones first,
203
/// then queued ones in the order runners claim them (hub spec §13.2).
204
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
205
    sqlx::query_as(
c4c87f48 Andy McCall ↶ 206
        "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 \
bf3d0754 Andy McCall ↶ 207
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
208
         WHERE j.status IN ('queued', 'running') AND r.status IN ('queued', 'running') \
209
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
210
    )
211
    .fetch_all(pool)
212
    .await
213
}
214
90326c96 Andy McCall ↶ 215
/// A repository's runs, newest first, numbered below `before`.
216
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
217
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
218
        .bind(repo_id)
219
        .bind(before.unwrap_or(i64::MAX))
220
        .bind(limit)
221
        .fetch_all(pool)
222
        .await
223
}
224
42fa9554 Andy McCall ↶ 225
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
226
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
227
        .bind(repo_id)
228
        .bind(before.unwrap_or(i64::MAX))
229
        .bind(limit)
230
        .fetch_all(pool)
231
        .await
232
}
233
a0d4bbfb Andy McCall ↶ 234
/// A repository's run by its number there.
235
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
236
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
42fa9554 Andy McCall ↶ 237
}
238
239
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
240
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
241
}
242
243
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
244
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
245
}
246
247
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
248
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
249
}
250
251
/// The running job a job token belongs to, while it may still be used.
252
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
253
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
254
        .bind(token_hash)
255
        .bind(now_ms() - max_age_ms)
256
        .fetch_optional(pool)
257
        .await
258
}
259
260
/// Take the oldest queued job whose dependencies all passed and whose tier
261
/// the runner offers, and mark it running for `runner` with a token.
fd3db644 Andy McCall ↶ 262
/// Let a job's token also read these repositories (its pinned subrepos).
263
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
264
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
265
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
266
    Ok(())
267
}
268
269
impl Job {
270
    pub fn also_read_ids(&self) -> Vec<i64> {
271
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
272
    }
273
}
274
76bc5a05 Andy McCall ↶ 275
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no limit.
276
#[derive(Clone, Copy, Debug, Default)]
277
pub struct Room {
278
    pub memory_mib: Option<u32>,
279
    pub cpus: Option<u32>,
280
}
281
282
impl Room {
283
    /// Whether a job's sandbox (its stored JSON) fits.
284
    pub fn fits(&self, sandbox_json: &str) -> bool {
285
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
286
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
287
        self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64) && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
288
    }
289
}
290
42fa9554 Andy McCall ↶ 291
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
c4c87f48 Andy McCall ↶ 292
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
76bc5a05 Andy McCall ↶ 293
}
294
295
/// The oldest runnable job that fits in `room`.
74be9796 Andy McCall ↶ 296
/// The first queued job a runner with these tiers, this room and this
297
/// scope may take, now running under `runner`. A scoped runner never sees
298
/// another scope's jobs (oxygenhub#41).
299
pub async fn claim_within(
300
    pool: &Pool,
301
    runtimes: &[String],
302
    runner: &str,
303
    token_hash: &str,
304
    room: Room,
305
    scope: &super::runners::Scope,
c4c87f48 Andy McCall ↶ 306
    labels: &[String],
74be9796 Andy McCall ↶ 307
) -> sqlx::Result<Option<Job>> {
941abdd6 Andy McCall ↶ 308
    let mut tx = super::begin_write(pool).await?;
42fa9554 Andy McCall ↶ 309
    let queued: Vec<Job> = sqlx::query_as(
74be9796 Andy McCall ↶ 310
        "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 \
311
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') \
312
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
313
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
42fa9554 Andy McCall ↶ 314
    )
74be9796 Andy McCall ↶ 315
    .bind(&scope.owner)
316
    .bind(&scope.owner)
317
    .bind(scope.repo_id)
318
    .bind(scope.repo_id)
42fa9554 Andy McCall ↶ 319
    .fetch_all(&mut *tx)
320
    .await?;
321
    for j in queued {
76bc5a05 Andy McCall ↶ 322
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) {
c4c87f48 Andy McCall ↶ 323
            continue;
324
        }
325
        // Every label the job and its sandbox ask for (`runs-on`).
326
        if !j.needs().iter().all(|l| labels.contains(l)) {
42fa9554 Andy McCall ↶ 327
            continue;
328
        }
329
        let deps = j.depends_on();
330
        if !deps.is_empty() {
331
            let mut passed = 0i64;
332
            for d in &deps {
333
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
334
                    .bind(j.run_id)
335
                    .bind(d)
336
                    .fetch_optional(&mut *tx)
337
                    .await?;
338
                if st.as_deref() == Some("passed") {
339
                    passed += 1;
340
                }
341
            }
342
            if passed != deps.len() as i64 {
343
                continue;
344
            }
345
        }
346
        let now = now_ms();
347
        let done = sqlx::query(
348
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
349
        )
350
        .bind(runner)
351
        .bind(token_hash)
352
        .bind(now)
353
        .bind(j.id)
354
        .execute(&mut *tx)
355
        .await?;
356
        if done.rows_affected() == 1 {
357
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
358
                .bind(j.run_id)
359
                .execute(&mut *tx)
360
                .await?;
361
            tx.commit().await?;
362
            return job(pool, j.id).await;
363
        }
364
    }
365
    tx.commit().await?;
366
    Ok(None)
367
}
368
369
/// Append records; returns how many were kept (the rest exceed the cap).
370
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
941abdd6 Andy McCall ↶ 371
    let mut tx = super::begin_write(pool).await?;
42fa9554 Andy McCall ↶ 372
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
373
    let room = (cap - count).max(0) as usize;
374
    let keep = &records[..records.len().min(room)];
375
    for (i, r) in keep.iter().enumerate() {
376
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
377
            .bind(job_id)
378
            .bind(count + i as i64 + 1)
379
            .bind(r.t as i64)
380
            .bind(&r.stream)
381
            .bind(&r.text)
382
            .execute(&mut *tx)
383
            .await?;
384
    }
385
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
386
        .bind(keep.len() as i64)
387
        .bind(job_id)
388
        .execute(&mut *tx)
389
        .await?;
390
    tx.commit().await?;
391
    Ok(keep.len())
392
}
393
394
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
395
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
396
        .bind(job_id)
397
        .bind(after)
398
        .bind(limit)
399
        .fetch_all(pool)
400
        .await
401
}
402
403
pub struct Outcome<'a> {
404
    pub status: &'a str,
405
    pub exit_code: Option<i64>,
406
    pub error: &'a str,
407
    pub receipt: &'a str,
408
    pub receipt_hash: &'a str,
409
}
410
411
/// Record a job's end, skip the jobs that can no longer run, and settle the
412
/// run. Returns the jobs whose status changed (for their checks).
413
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
941abdd6 Andy McCall ↶ 414
    let mut tx = super::begin_write(pool).await?;
42fa9554 Andy McCall ↶ 415
    let now = now_ms();
416
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
417
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
418
        .bind(o.status)
419
        .bind(o.exit_code)
420
        .bind(o.error)
421
        .bind(o.receipt)
422
        .bind(o.receipt_hash)
423
        .bind(now)
424
        .bind(job_id)
425
        .execute(&mut *tx)
426
        .await?;
427
    let mut changed = vec![job_id];
428
    // Dependents of anything that did not pass are skipped, transitively.
429
    loop {
430
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
431
        let blocked: Vec<i64> = all
432
            .iter()
433
            .filter(|x| x.status == "queued")
434
            .filter(|x| {
435
                x.depends_on()
436
                    .iter()
437
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
438
            })
439
            .map(|x| x.id)
440
            .collect();
441
        if blocked.is_empty() {
442
            break;
443
        }
444
        for id in blocked {
445
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
446
                .bind(now)
447
                .bind(id)
448
                .execute(&mut *tx)
449
                .await?;
450
            changed.push(id);
451
        }
452
    }
453
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
454
    if all.iter().all(Job::done) {
455
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
456
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
457
            .bind(status)
458
            .bind(now)
459
            .bind(j.run_id)
460
            .execute(&mut *tx)
461
            .await?;
462
    }
463
    tx.commit().await?;
464
    let mut out = Vec::new();
465
    for id in changed {
466
        if let Some(x) = job(pool, id).await? {
467
            out.push(x);
468
        }
469
    }
470
    Ok(out)
471
}
736f6813 Andy McCall ↶ 472
473
/// The newest run of exactly this state (heads joined with `+`, sorted).
474
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
475
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
476
        .bind(repo_id)
477
        .bind(heads)
478
        .fetch_optional(pool)
479
        .await
cc19697f Andy McCall ↶ 480
}
481
482
/// Record what became of job `job_id`'s signed receipt.
483
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
484
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
485
        .bind(attest)
486
        .bind(signer)
487
        .bind(note)
488
        .bind(job_id)
489
        .execute(pool)
490
        .await?;
491
    Ok(())
736f6813 Andy McCall ↶ 492
}
a3c8288b Andy McCall ↶ 493
494
/// A job's artifact, kept as a blob of the run's repository.
495
#[derive(Clone, Debug, FromRow)]
496
pub struct Artifact {
497
    pub job_id: i64,
498
    pub name: String,
499
    pub path: String,
500
    pub blob: String,
501
    pub size: i64,
502
    /// BLAKE3 of the bytes.
503
    pub content: String,
504
    pub created_ms: i64,
505
}
506
507
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
508
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
509
        .bind(a.job_id)
510
        .bind(&a.name)
511
        .bind(&a.path)
512
        .bind(&a.blob)
513
        .bind(a.size)
514
        .bind(&a.content)
515
        .bind(a.created_ms)
516
        .execute(pool)
517
        .await?;
518
    Ok(())
519
}
520
521
/// Job `job_id`'s artifacts, by name.
522
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
523
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
524
}
10708ab8 Andy McCall ↶ 525
526
/// Where an artifact with given content came from: the run and job that
527
/// built it, and the job's signed receipt when one was kept.
528
#[derive(Clone, Debug, FromRow)]
529
pub struct Provenance {
530
    pub run_number: i64,
531
    pub job: String,
532
    pub name: String,
533
    pub receipt_attest: String,
534
    pub receipt_signer: String,
535
}
536
537
/// The build of the bytes whose BLAKE3 is `content` in repository
538
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
539
/// run first.
540
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
541
    sqlx::query_as(
542
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
543
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
544
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
545
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
546
    )
547
    .bind(repo_id)
548
    .bind(content)
549
    .fetch_optional(pool)
550
    .await
551
}