OXYGENHUB
# 36e5a9c15a84 oxygenhub / crates / hub / src / db / flow.rs
31.1 KiB · Rust · last changed Runners decline, and the queue says why a job waits 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, 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
}
94
95
impl Job {
96
    pub fn depends_on(&self) -> Vec<String> {
97
        serde_json::from_str(&self.depends).unwrap_or_default()
98
    }
99
100
    pub fn done(&self) -> bool {
101
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error" | "cancelled")
102
    }
103
}
104
105
#[derive(Clone, Debug, FromRow)]
106
pub struct LogLine {
107
    pub seq: i64,
108
    pub t: i64,
109
    pub stream: String,
110
    pub text: String,
111
}
112
113
/// A job as the trigger creates it.
114
pub struct NewJob {
115
    pub name: String,
116
    pub depth: i64,
117
    pub depends: Vec<String>,
118
    pub spec: String,
119
    pub sandbox: String,
120
    pub runtime: String,
121
}
122
123
pub struct NewRun<'a> {
124
    pub repo_id: i64,
125
    pub bookmark: &'a str,
126
    pub state: &'a str,
127
    pub heads: &'a str,
128
    pub pipeline_hash: &'a str,
129
    pub actor: &'a str,
130
    /// `push`, `manual` or `rerun:N`.
131
    pub trigger: &'a str,
132
    /// Problems when the pipeline is invalid: the run is recorded in error.
133
    pub error: Option<&'a str>,
134
}
135
136
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
137
    let mut tx = super::begin_write(pool).await?;
138
    let now = now_ms();
139
    let status = if r.error.is_some() { "error" } else { "queued" };
140
    let id: i64 = sqlx::query_scalar(
141
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
142
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
143
    )
144
    .bind(r.repo_id)
145
    .bind(r.repo_id)
146
    .bind(r.bookmark)
147
    .bind(r.state)
148
    .bind(r.heads)
149
    .bind(r.pipeline_hash)
150
    .bind(status)
151
    .bind(r.error.unwrap_or(""))
152
    .bind(r.actor)
153
    .bind(r.trigger)
154
    .bind(now)
155
    .bind(r.error.map(|_| now))
156
    .fetch_one(&mut *tx)
157
    .await?;
158
    for j in jobs {
159
        sqlx::query(
160
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued')",
161
        )
162
        .bind(id)
163
        .bind(&j.name)
164
        .bind(j.depth)
165
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
166
        .bind(&j.spec)
167
        .bind(&j.sandbox)
168
        .bind(&j.runtime)
169
        .execute(&mut *tx)
170
        .await?;
171
    }
172
    tx.commit().await?;
173
    Ok(id)
174
}
175
176
/// The labels a compiled job and its sandbox ask a runner for (`runs-on`).
177
fn labels_in(spec: &str, sandbox: &str) -> Vec<String> {
178
    let mut out: Vec<String> = [spec, sandbox]
179
        .iter()
180
        .filter_map(|j| serde_json::from_str::<serde_json::Value>(j).ok())
181
        .flat_map(|v| v["runs_on"].as_array().cloned().unwrap_or_default())
182
        .filter_map(|l| l.as_str().map(String::from))
183
        .collect();
184
    out.sort();
185
    out.dedup();
186
    out
187
}
188
189
impl Job {
190
    /// The runner labels this job needs.
191
    pub fn needs(&self) -> Vec<String> {
192
        labels_in(&self.spec, &self.sandbox)
193
    }
194
195
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
196
    pub fn arch(&self) -> Option<String> {
197
        arch_in(&self.sandbox)
198
    }
199
}
200
201
/// The architecture a sandbox's JSON asks for, if any.
202
fn arch_in(sandbox: &str) -> Option<String> {
203
    serde_json::from_str::<serde_json::Value>(sandbox).ok()?["arch"].as_str().map(String::from)
204
}
205
206
/// A job waiting for or held by a runner, with where it comes from.
207
#[derive(Clone, Debug, FromRow)]
208
pub struct QueueEntry {
209
    pub job_id: i64,
210
    pub run_id: i64,
211
    pub repo_id: i64,
212
    pub owner: String,
213
    pub name: String,
214
    pub visibility: String,
215
    pub run_number: i64,
216
    pub job: String,
217
    pub status: String,
218
    /// The runner holding it, when running.
219
    pub runner: String,
220
    pub spec: String,
221
    pub sandbox: String,
222
}
223
224
impl QueueEntry {
225
    /// The runner labels the job needs.
226
    pub fn needs(&self) -> Vec<String> {
227
        labels_in(&self.spec, &self.sandbox)
228
    }
229
230
    /// The architecture the job's sandbox asks for (OxygenFlow spec §11.3).
231
    pub fn arch(&self) -> Option<String> {
232
        arch_in(&self.sandbox)
233
    }
234
}
235
236
/// Every job of a live run that is running or queued: running ones first,
237
/// then queued ones in the order runners claim them (hub spec §13.2).
238
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
239
    sqlx::query_as(
240
        "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 \
241
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
242
         WHERE j.status IN ('queued', 'running') AND r.status IN ('queued', 'running') \
243
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
244
    )
245
    .fetch_all(pool)
246
    .await
247
}
248
249
/// A repository's runs, newest first, numbered below `before`.
250
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
251
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
252
        .bind(repo_id)
253
        .bind(before.unwrap_or(i64::MAX))
254
        .bind(limit)
255
        .fetch_all(pool)
256
        .await
257
}
258
259
/// The latest run on this bookmark of this repository, for what a push
260
/// changed since (a job's scope).
261
/// The run a push to `bookmark` is scoped against: the newest that was not
262
/// cancelled, nor a push run still going (a new push supersedes it), so
263
/// that what a cancelled run would have checked is checked by the next.
264
pub async fn latest_on(pool: &Pool, repo_id: i64, bookmark: &str) -> sqlx::Result<Option<Run>> {
265
    sqlx::query_as(
266
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND heads != '' AND status != 'cancelled'
267
         AND NOT (trigger = 'push' AND status IN ('queued', 'running')) ORDER BY id DESC LIMIT 1",
268
    )
269
    .bind(repo_id)
270
    .bind(bookmark)
271
    .fetch_optional(pool)
272
    .await
273
}
274
275
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
276
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
277
        .bind(repo_id)
278
        .bind(before.unwrap_or(i64::MAX))
279
        .bind(limit)
280
        .fetch_all(pool)
281
        .await
282
}
283
284
/// A repository's run by its number there.
285
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
286
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
287
}
288
289
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
290
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
291
}
292
293
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
294
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
295
}
296
297
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
298
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
299
}
300
301
/// The running job a job token belongs to, while it may still be used.
302
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
303
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
304
        .bind(token_hash)
305
        .bind(now_ms() - max_age_ms)
306
        .fetch_optional(pool)
307
        .await
308
}
309
310
/// Take the oldest queued job whose dependencies all passed and whose tier
311
/// the runner offers, and mark it running for `runner` with a token.
312
/// Let a job's token also read these repositories (its pinned subrepos).
313
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
314
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
315
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
316
    Ok(())
317
}
318
319
impl Job {
320
    pub fn also_read_ids(&self) -> Vec<i64> {
321
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
322
    }
323
}
324
325
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no
326
/// limit, and the rootfs images it holds, `None` when it does not say.
327
#[derive(Clone, Debug, Default)]
328
pub struct Room {
329
    pub memory_mib: Option<u32>,
330
    pub cpus: Option<u32>,
331
    pub images: Option<std::collections::HashSet<String>>,
332
    /// The runner's architecture (`x86_64`, `riscv64`, …), empty when unknown.
333
    pub arch: String,
334
    /// Each image's architecture as runners have reported it (`flow_images`).
335
    pub image_archs: std::collections::HashMap<String, String>,
336
    /// Jobs this runner declined, not to be offered to it again (spec §11.5).
337
    pub declined: std::collections::HashSet<i64>,
338
}
339
340
impl Room {
341
    /// Whether a job's sandbox (its stored JSON) fits: its memory and vCPUs,
342
    /// and its rootfs image among the runner's (oxygenhub#73).
343
    pub fn fits(&self, sandbox_json: &str) -> bool {
344
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
345
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
346
        let rootfs = v["rootfs"].as_str().unwrap_or("");
347
        // The architecture: the sandbox's own ask, else the image's as known;
348
        // an unknown one matches, as before (OxygenFlow spec §11.3).
349
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
350
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
351
        arch_ok
352
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
353
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
354
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)))
355
    }
356
}
357
358
/// Remember which architecture each image is for, as a runner reports it.
359
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
360
    for (hash, arch) in archs.iter().take(500) {
361
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
362
            continue;
363
        }
364
        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")
365
        .bind(hash.to_ascii_lowercase())
366
        .bind(arch)
367
        .bind(now_ms())
368
        .execute(pool)
369
        .await?;
370
    }
371
    Ok(())
372
}
373
374
/// Every image's architecture the hub knows.
375
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
376
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
377
    Ok(rows.into_iter().collect())
378
}
379
380
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
381
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
382
}
383
384
/// The oldest runnable job that fits in `room`.
385
/// The first queued job a runner with these tiers, this room and this
386
/// scope may take, now running under `runner`. A scoped runner never sees
387
/// another scope's jobs (oxygenhub#41).
388
pub async fn claim_within(
389
    pool: &Pool,
390
    runtimes: &[String],
391
    runner: &str,
392
    token_hash: &str,
393
    room: Room,
394
    scope: &super::runners::Scope,
395
    labels: &[String],
396
) -> sqlx::Result<Option<Job>> {
397
    let mut tx = super::begin_write(pool).await?;
398
    let queued: Vec<Job> = sqlx::query_as(
399
        "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 \
400
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') \
401
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
402
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
403
    )
404
    .bind(&scope.owner)
405
    .bind(&scope.owner)
406
    .bind(scope.repo_id)
407
    .bind(scope.repo_id)
408
    .fetch_all(&mut *tx)
409
    .await?;
410
    for j in queued {
411
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) || room.declined.contains(&j.id) {
412
            continue;
413
        }
414
        // Every label the job and its sandbox ask for (`runs-on`).
415
        if !j.needs().iter().all(|l| labels.contains(l)) {
416
            continue;
417
        }
418
        let deps = j.depends_on();
419
        if !deps.is_empty() {
420
            let mut passed = 0i64;
421
            for d in &deps {
422
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
423
                    .bind(j.run_id)
424
                    .bind(d)
425
                    .fetch_optional(&mut *tx)
426
                    .await?;
427
                if st.as_deref() == Some("passed") {
428
                    passed += 1;
429
                }
430
            }
431
            if passed != deps.len() as i64 {
432
                continue;
433
            }
434
        }
435
        let now = now_ms();
436
        let done = sqlx::query(
437
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
438
        )
439
        .bind(runner)
440
        .bind(token_hash)
441
        .bind(now)
442
        .bind(j.id)
443
        .execute(&mut *tx)
444
        .await?;
445
        if done.rows_affected() == 1 {
446
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
447
                .bind(j.run_id)
448
                .execute(&mut *tx)
449
                .await?;
450
            tx.commit().await?;
451
            return job(pool, j.id).await;
452
        }
453
    }
454
    tx.commit().await?;
455
    Ok(None)
456
}
457
458
/// How long a decline keeps a job from its runner when the runner's
459
/// profile stays the same: a reason such as memory in use passes.
460
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
461
462
/// The jobs runner `runner_id` declined with this profile, recently.
463
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
464
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = ? AND profile = ? AND ms > ?")
465
        .bind(runner_id)
466
        .bind(profile)
467
        .bind(now_ms() - DECLINE_HOLDS_MS)
468
        .fetch_all(pool)
469
        .await?;
470
    Ok(rows.into_iter().map(|(j,)| j).collect())
471
}
472
473
/// A decline: one runner's reason for handing a job back.
474
#[derive(Clone, Debug, sqlx::FromRow)]
475
pub struct DeclineRow {
476
    pub job_id: i64,
477
    pub runner_id: i64,
478
    pub runner: String,
479
    pub reason: String,
480
    pub ms: i64,
481
}
482
483
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
484
/// is kept (one per job and runner, the latest), and the job is queued
485
/// again. Returns every decline the job has had, or `None` when the job
486
/// was not running on that runner.
487
pub async fn decline(
488
    pool: &Pool,
489
    job_id: i64,
490
    runner_id: i64,
491
    runner: &str,
492
    profile: &str,
493
    reason: &str,
494
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
495
    let mut tx = super::begin_write(pool).await?;
496
    let back = sqlx::query(
497
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
498
         WHERE id = ? AND status = 'running' AND runner_id = ?",
499
    )
500
    .bind(job_id)
501
    .bind(runner_id)
502
    .execute(&mut *tx)
503
    .await?;
504
    if back.rows_affected() != 1 {
505
        tx.rollback().await?;
506
        return Ok(None);
507
    }
508
    sqlx::query(
509
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES (?, ?, ?, ?, ?, ?) \
510
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
511
    )
512
    .bind(job_id)
513
    .bind(runner_id)
514
    .bind(runner)
515
    .bind(profile)
516
    .bind(reason)
517
    .bind(now_ms())
518
    .execute(&mut *tx)
519
    .await?;
520
    let all: Vec<DeclineRow> =
521
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
522
            .bind(job_id)
523
            .fetch_all(&mut *tx)
524
            .await?;
525
    tx.commit().await?;
526
    Ok(Some(all))
527
}
528
529
/// The declines of job `job_id`, oldest first.
530
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
531
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
532
        .bind(job_id)
533
        .fetch_all(pool)
534
        .await
535
}
536
537
/// A runner's latest declines, newest first, with where the job is.
538
#[derive(Clone, Debug, sqlx::FromRow)]
539
pub struct RunnerDecline {
540
    pub job_id: i64,
541
    pub job: String,
542
    pub run_number: i64,
543
    pub owner: String,
544
    pub name: String,
545
    pub reason: String,
546
    pub ms: i64,
547
}
548
549
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
550
    sqlx::query_as(
551
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
552
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
553
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = ? ORDER BY d.ms DESC LIMIT ?",
554
    )
555
    .bind(runner_id)
556
    .bind(limit)
557
    .fetch_all(pool)
558
    .await
559
}
560
561
/// Queued jobs whose dependencies have passed, in their live runs, with
562
/// their repositories (owner, id): the ones a runner could take now.
563
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
564
    let queued: Vec<Job> = sqlx::query_as(
565
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
566
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') ORDER BY j.run_id, j.depth, j.id LIMIT 500",
567
    )
568
    .fetch_all(pool)
569
    .await?;
570
    let mut out = Vec::new();
571
    for j in queued {
572
        let mut ready = true;
573
        for d in j.depends_on() {
574
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
575
                .bind(j.run_id)
576
                .bind(&d)
577
                .fetch_optional(pool)
578
                .await?;
579
            if st.as_deref() != Some("passed") {
580
                ready = false;
581
                break;
582
            }
583
        }
584
        if !ready {
585
            continue;
586
        }
587
        let repo: Option<(String, i64)> =
588
            sqlx::query_as("SELECT rep.owner, rep.id FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id WHERE r.id = ?")
589
                .bind(j.run_id)
590
                .fetch_optional(pool)
591
                .await?;
592
        if let Some((owner, id)) = repo {
593
            out.push((j, owner, id));
594
        }
595
    }
596
    Ok(out)
597
}
598
599
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
600
    sqlx::query("UPDATE flow_jobs SET waiting = ? WHERE id = ? AND waiting <> ?")
601
        .bind(waiting)
602
        .bind(job_id)
603
        .bind(waiting)
604
        .execute(pool)
605
        .await?;
606
    Ok(())
607
}
608
609
/// Append records; returns how many were kept (the rest exceed the cap).
610
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
611
    let mut tx = super::begin_write(pool).await?;
612
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
613
    let room = (cap - count).max(0) as usize;
614
    let keep = &records[..records.len().min(room)];
615
    for (i, r) in keep.iter().enumerate() {
616
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
617
            .bind(job_id)
618
            .bind(count + i as i64 + 1)
619
            .bind(r.t as i64)
620
            .bind(&r.stream)
621
            .bind(&r.text)
622
            .execute(&mut *tx)
623
            .await?;
624
    }
625
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
626
        .bind(keep.len() as i64)
627
        .bind(job_id)
628
        .execute(&mut *tx)
629
        .await?;
630
    tx.commit().await?;
631
    Ok(keep.len())
632
}
633
634
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
635
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
636
        .bind(job_id)
637
        .bind(after)
638
        .bind(limit)
639
        .fetch_all(pool)
640
        .await
641
}
642
643
/// Jobs running since before `ms` (the oldest first).
644
/// Jobs still running at `now` past their own time limit (`default_s` for
645
/// one claimed without) plus `grace_ms`.
646
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
647
    sqlx::query_as(
648
        "SELECT * FROM flow_jobs WHERE status = 'running' \
649
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE ? END) * 1000 + ? < ? ORDER BY started_ms",
650
    )
651
    .bind(default_s as i64)
652
    .bind(grace_ms)
653
    .bind(now)
654
    .fetch_all(pool)
655
    .await
656
}
657
658
/// Record the limit a claimed job runs under.
659
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
660
    sqlx::query("UPDATE flow_jobs SET timeout_s = ? WHERE id = ?").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
661
    Ok(())
662
}
663
664
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
665
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
666
        .bind(ms)
667
        .fetch_all(pool)
668
        .await
669
}
670
671
/// The jobs running on the runner with this id.
672
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
673
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = ? ORDER BY id").bind(runner_id).fetch_all(pool).await
674
}
675
676
pub struct Outcome<'a> {
677
    pub status: &'a str,
678
    pub exit_code: Option<i64>,
679
    pub error: &'a str,
680
    pub receipt: &'a str,
681
    pub receipt_hash: &'a str,
682
}
683
684
/// Record a job's end, skip the jobs that can no longer run, and settle the
685
/// run. Returns the jobs whose status changed (for their checks).
686
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
687
    let mut tx = super::begin_write(pool).await?;
688
    let now = now_ms();
689
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
690
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
691
        .bind(o.status)
692
        .bind(o.exit_code)
693
        .bind(o.error)
694
        .bind(o.receipt)
695
        .bind(o.receipt_hash)
696
        .bind(now)
697
        .bind(job_id)
698
        .execute(&mut *tx)
699
        .await?;
700
    let mut changed = vec![job_id];
701
    // Dependents of anything that did not pass are skipped, transitively.
702
    loop {
703
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
704
        let blocked: Vec<i64> = all
705
            .iter()
706
            .filter(|x| x.status == "queued")
707
            .filter(|x| {
708
                x.depends_on()
709
                    .iter()
710
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
711
            })
712
            .map(|x| x.id)
713
            .collect();
714
        if blocked.is_empty() {
715
            break;
716
        }
717
        for id in blocked {
718
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
719
                .bind(now)
720
                .bind(id)
721
                .execute(&mut *tx)
722
                .await?;
723
            changed.push(id);
724
        }
725
    }
726
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
727
    if all.iter().all(Job::done) {
728
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
729
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
730
            .bind(status)
731
            .bind(now)
732
            .bind(j.run_id)
733
            .execute(&mut *tx)
734
            .await?;
735
    }
736
    tx.commit().await?;
737
    let mut out = Vec::new();
738
    for id in changed {
739
        if let Some(x) = job(pool, id).await? {
740
            out.push(x);
741
        }
742
    }
743
    Ok(out)
744
}
745
746
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
747
/// and so does the run. A runner learns of it when the hub next refuses
748
/// its log lines, and stops the job. Returns the jobs whose status changed.
749
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
750
    let now = now_ms();
751
    let mut tx = pool.begin().await?;
752
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = ? AND status IN ('queued', 'running')")
753
        .bind(run_id)
754
        .fetch_all(&mut *tx)
755
        .await?;
756
    sqlx::query(
757
        "UPDATE flow_jobs SET status = 'cancelled', error = ?, finished_ms = ?, token_hash = ''
758
         WHERE run_id = ? AND status IN ('queued', 'running')",
759
    )
760
    .bind(why)
761
    .bind(now)
762
    .bind(run_id)
763
    .execute(&mut *tx)
764
    .await?;
765
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = ? WHERE id = ? AND status IN ('queued', 'running')")
766
        .bind(now)
767
        .bind(run_id)
768
        .execute(&mut *tx)
769
        .await?;
770
    tx.commit().await?;
771
    let mut out = Vec::new();
772
    for (id,) in ids {
773
        if let Some(x) = job(pool, id).await? {
774
            out.push(x);
775
        }
776
    }
777
    Ok(out)
778
}
779
780
/// The push runs of `bookmark` still going, older than run `number`.
781
pub async fn live_push_runs_before(pool: &Pool, repo_id: i64, bookmark: &str, number: i64) -> sqlx::Result<Vec<Run>> {
782
    sqlx::query_as(
783
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND number < ? AND trigger = 'push'
784
         AND status IN ('queued', 'running') ORDER BY id",
785
    )
786
    .bind(repo_id)
787
    .bind(bookmark)
788
    .bind(number)
789
    .fetch_all(pool)
790
    .await
791
}
792
793
/// The newest run of exactly this state (heads joined with `+`, sorted).
794
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
795
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
796
        .bind(repo_id)
797
        .bind(heads)
798
        .fetch_optional(pool)
799
        .await
800
}
801
802
/// Record what became of job `job_id`'s signed receipt.
803
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
804
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
805
        .bind(attest)
806
        .bind(signer)
807
        .bind(note)
808
        .bind(job_id)
809
        .execute(pool)
810
        .await?;
811
    Ok(())
812
}
813
814
/// A job's artifact, kept as a blob of the run's repository.
815
#[derive(Clone, Debug, FromRow)]
816
pub struct Artifact {
817
    pub job_id: i64,
818
    pub name: String,
819
    pub path: String,
820
    pub blob: String,
821
    pub size: i64,
822
    /// BLAKE3 of the bytes.
823
    pub content: String,
824
    pub created_ms: i64,
825
}
826
827
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
828
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
829
        .bind(a.job_id)
830
        .bind(&a.name)
831
        .bind(&a.path)
832
        .bind(&a.blob)
833
        .bind(a.size)
834
        .bind(&a.content)
835
        .bind(a.created_ms)
836
        .execute(pool)
837
        .await?;
838
    Ok(())
839
}
840
841
/// Job `job_id`'s artifacts, by name.
842
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
843
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
844
}
845
846
/// Where an artifact with given content came from: the run and job that
847
/// built it, and the job's signed receipt when one was kept.
848
#[derive(Clone, Debug, FromRow)]
849
pub struct Provenance {
850
    pub run_number: i64,
851
    pub job: String,
852
    pub name: String,
853
    pub receipt_attest: String,
854
    pub receipt_signer: String,
855
}
856
857
/// The build of the bytes whose BLAKE3 is `content` in repository
858
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
859
/// run first.
860
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
861
    sqlx::query_as(
862
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
863
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
864
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
865
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
866
    )
867
    .bind(repo_id)
868
    .bind(content)
869
    .fetch_optional(pool)
870
    .await
871
}