OXYGENHUB
# 58cbf42447bc oxygenhub / crates / hub / src / db / flow.rs
37.3 KiB · Rust · last changed Say why a job waits when the runners that could take it are full 18 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
/// Every queued job's priority rank, 0 (urgent) to 3 (low), by job id
667
/// (#259: how many ready jobs come first).
668
pub async fn queued_ranks(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
669
    let rows: Vec<(i64, i64)> = sqlx::query_as(&format!(
670
        "SELECT j.id, CAST({PRIORITY_RANK} AS BIGINT) FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories rep ON rep.id = r.repo_id \
671
         WHERE j.status = 'queued'"
672
    ))
673
    .fetch_all(pool)
674
    .await?;
675
    Ok(rows.into_iter().collect())
676
}
677
678
/// How many jobs each runner is running now, by runner id (#259).
679
pub async fn running_by_runner(pool: &Pool) -> sqlx::Result<std::collections::HashMap<i64, i64>> {
680
    let rows: Vec<(i64, i64)> =
681
        sqlx::query_as("SELECT runner_id, COUNT(*) FROM flow_jobs WHERE status = 'running' AND runner_id IS NOT NULL GROUP BY runner_id")
682
            .fetch_all(pool)
683
            .await?;
684
    Ok(rows.into_iter().collect())
685
}
686
687
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
688
    let queued: Vec<Job> = sqlx::query_as(
689
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
690
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') ORDER BY j.run_id, j.depth, j.id LIMIT 500",
691
    )
692
    .fetch_all(pool)
693
    .await?;
694
    let mut out = Vec::new();
695
    for j in queued {
696
        let mut ready = true;
697
        for d in j.depends_on() {
698
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
699
                .bind(j.run_id)
700
                .bind(&d)
701
                .fetch_optional(pool)
702
                .await?;
703
            if st.as_deref() != Some("passed") {
704
                ready = false;
705
                break;
706
            }
707
        }
708
        if !ready {
709
            continue;
710
        }
711
        let repo: Option<(String, i64)> =
712
            sqlx::query_as("SELECT rep.owner, rep.id FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id WHERE r.id = ?")
713
                .bind(j.run_id)
714
                .fetch_optional(pool)
715
                .await?;
716
        if let Some((owner, id)) = repo {
717
            out.push((j, owner, id));
718
        }
719
    }
720
    Ok(out)
721
}
722
723
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
724
    sqlx::query("UPDATE flow_jobs SET waiting = ? WHERE id = ? AND waiting <> ?")
725
        .bind(waiting)
726
        .bind(job_id)
727
        .bind(waiting)
728
        .execute(pool)
729
        .await?;
730
    Ok(())
731
}
732
733
/// Append records; returns how many were kept (the rest exceed the cap).
734
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
735
    let mut tx = super::begin_write(pool).await?;
736
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
737
    let room = (cap - count).max(0) as usize;
738
    let keep = &records[..records.len().min(room)];
739
    for (i, r) in keep.iter().enumerate() {
740
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
741
            .bind(job_id)
742
            .bind(count + i as i64 + 1)
743
            .bind(r.t as i64)
744
            .bind(&r.stream)
745
            .bind(&r.text)
746
            .execute(&mut *tx)
747
            .await?;
748
    }
749
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
750
        .bind(keep.len() as i64)
751
        .bind(job_id)
752
        .execute(&mut *tx)
753
        .await?;
754
    tx.commit().await?;
755
    Ok(keep.len())
756
}
757
758
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
759
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
760
        .bind(job_id)
761
        .bind(after)
762
        .bind(limit)
763
        .fetch_all(pool)
764
        .await
765
}
766
767
/// Jobs running since before `ms` (the oldest first).
768
/// Jobs still running at `now` past their own time limit (`default_s` for
769
/// one claimed without) plus `grace_ms`.
770
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
771
    sqlx::query_as(
772
        "SELECT * FROM flow_jobs WHERE status = 'running' \
773
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE ? END) * 1000 + ? < ? ORDER BY started_ms",
774
    )
775
    .bind(default_s as i64)
776
    .bind(grace_ms)
777
    .bind(now)
778
    .fetch_all(pool)
779
    .await
780
}
781
782
/// Record the limit a claimed job runs under.
783
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
784
    sqlx::query("UPDATE flow_jobs SET timeout_s = ? WHERE id = ?").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
785
    Ok(())
786
}
787
788
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
789
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
790
        .bind(ms)
791
        .fetch_all(pool)
792
        .await
793
}
794
795
/// The jobs running on the runner with this id.
796
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
797
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = ? ORDER BY id").bind(runner_id).fetch_all(pool).await
798
}
799
800
pub struct Outcome<'a> {
801
    pub status: &'a str,
802
    pub exit_code: Option<i64>,
803
    pub error: &'a str,
804
    pub receipt: &'a str,
805
    pub receipt_hash: &'a str,
806
}
807
808
/// Record a job's end, skip the jobs that can no longer run, and settle the
809
/// run. Returns the jobs whose status changed (for their checks).
810
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
811
    let mut tx = super::begin_write(pool).await?;
812
    let now = now_ms();
813
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
814
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
815
        .bind(o.status)
816
        .bind(o.exit_code)
817
        .bind(o.error)
818
        .bind(o.receipt)
819
        .bind(o.receipt_hash)
820
        .bind(now)
821
        .bind(job_id)
822
        .execute(&mut *tx)
823
        .await?;
824
    // A pass teaches what its image is for, when nobody has read it
825
    // (oxygenhub#173): the architecture of the runner it passed on.
826
    if o.status == "passed" {
827
        let rootfs = serde_json::from_str::<serde_json::Value>(&j.sandbox)
828
            .ok()
829
            .and_then(|v| v["rootfs"].as_str().map(str::to_ascii_lowercase))
830
            .unwrap_or_default();
831
        if rootfs.len() == 64 {
832
            sqlx::query(
833
                "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 \
834
                 WHERE j.id = ? AND r.arch != '' ON CONFLICT (hash) DO NOTHING",
835
            )
836
            .bind(&rootfs)
837
            .bind(now)
838
            .bind(job_id)
839
            .execute(&mut *tx)
840
            .await?;
841
        }
842
    }
843
    let mut changed = vec![job_id];
844
    // Dependents of anything that did not pass are skipped, transitively.
845
    loop {
846
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
847
        let blocked: Vec<i64> = all
848
            .iter()
849
            .filter(|x| x.status == "queued")
850
            .filter(|x| {
851
                x.depends_on()
852
                    .iter()
853
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
854
            })
855
            .map(|x| x.id)
856
            .collect();
857
        if blocked.is_empty() {
858
            break;
859
        }
860
        for id in blocked {
861
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
862
                .bind(now)
863
                .bind(id)
864
                .execute(&mut *tx)
865
                .await?;
866
            changed.push(id);
867
        }
868
    }
869
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
870
    if all.iter().all(Job::done) {
871
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
872
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
873
            .bind(status)
874
            .bind(now)
875
            .bind(j.run_id)
876
            .execute(&mut *tx)
877
            .await?;
878
    }
879
    tx.commit().await?;
880
    let mut out = Vec::new();
881
    for id in changed {
882
        if let Some(x) = job(pool, id).await? {
883
            out.push(x);
884
        }
885
    }
886
    Ok(out)
887
}
888
889
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
890
/// and so does the run. A runner learns of it when the hub next refuses
891
/// its log lines, and stops the job. Returns the jobs whose status changed.
892
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
893
    let now = now_ms();
894
    let mut tx = pool.begin().await?;
895
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = ? AND status IN ('queued', 'running')")
896
        .bind(run_id)
897
        .fetch_all(&mut *tx)
898
        .await?;
899
    sqlx::query(
900
        "UPDATE flow_jobs SET status = 'cancelled', error = ?, finished_ms = ?, token_hash = ''
901
         WHERE run_id = ? AND status IN ('queued', 'running')",
902
    )
903
    .bind(why)
904
    .bind(now)
905
    .bind(run_id)
906
    .execute(&mut *tx)
907
    .await?;
908
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = ? WHERE id = ? AND status IN ('queued', 'running')")
909
        .bind(now)
910
        .bind(run_id)
911
        .execute(&mut *tx)
912
        .await?;
913
    tx.commit().await?;
914
    let mut out = Vec::new();
915
    for (id,) in ids {
916
        if let Some(x) = job(pool, id).await? {
917
            out.push(x);
918
        }
919
    }
920
    Ok(out)
921
}
922
923
/// The push runs of `bookmark` still going, older than run `number`.
924
pub async fn live_push_runs_before(pool: &Pool, repo_id: i64, bookmark: &str, number: i64) -> sqlx::Result<Vec<Run>> {
925
    sqlx::query_as(
926
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND number < ? AND trigger = 'push'
927
         AND status IN ('queued', 'running') ORDER BY id",
928
    )
929
    .bind(repo_id)
930
    .bind(bookmark)
931
    .bind(number)
932
    .fetch_all(pool)
933
    .await
934
}
935
936
/// The newest run of exactly this state (heads joined with `+`, sorted).
937
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
938
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
939
        .bind(repo_id)
940
        .bind(heads)
941
        .fetch_optional(pool)
942
        .await
943
}
944
945
/// Record what became of job `job_id`'s signed receipt.
946
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
947
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
948
        .bind(attest)
949
        .bind(signer)
950
        .bind(note)
951
        .bind(job_id)
952
        .execute(pool)
953
        .await?;
954
    Ok(())
955
}
956
957
/// A job's artifact, kept as a blob of the run's repository.
958
#[derive(Clone, Debug, FromRow)]
959
pub struct Artifact {
960
    pub job_id: i64,
961
    pub name: String,
962
    pub path: String,
963
    pub blob: String,
964
    pub size: i64,
965
    /// BLAKE3 of the bytes.
966
    pub content: String,
967
    pub created_ms: i64,
968
}
969
970
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
971
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
972
        .bind(a.job_id)
973
        .bind(&a.name)
974
        .bind(&a.path)
975
        .bind(&a.blob)
976
        .bind(a.size)
977
        .bind(&a.content)
978
        .bind(a.created_ms)
979
        .execute(pool)
980
        .await?;
981
    Ok(())
982
}
983
984
/// Every artifact blob a repository's runs keep, for garbage collection to
985
/// keep too (#126): the database is the only thing that names them.
986
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
987
    sqlx::query_scalar(
988
        "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 = ?",
989
    )
990
    .bind(repo_id)
991
    .fetch_all(pool)
992
    .await
993
}
994
995
/// Job `job_id`'s artifacts, by name.
996
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
997
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
998
}
999
1000
/// Where an artifact with given content came from: the run and job that
1001
/// built it, and the job's signed receipt when one was kept.
1002
#[derive(Clone, Debug, FromRow)]
1003
pub struct Provenance {
1004
    pub run_number: i64,
1005
    pub job: String,
1006
    pub name: String,
1007
    pub receipt_attest: String,
1008
    pub receipt_signer: String,
1009
}
1010
1011
/// The build of the bytes whose BLAKE3 is `content` in repository
1012
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
1013
/// run first.
1014
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
1015
    sqlx::query_as(
1016
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
1017
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
1018
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
1019
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
1020
    )
1021
    .bind(repo_id)
1022
    .bind(content)
1023
    .fetch_optional(pool)
1024
    .await
1025
}