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