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