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