OXYGENHUB
# f8cf54e99879 oxygenhub / crates / hub / src / db / flow.rs
34.8 KiB · Rust · last changed Placement ranks runners and says why a job ran where it did 24 days ago source blame history raw
1
//! OxygenFlow runs, jobs and logs (hub spec §13.2).
2
3
use super::{now_ms, Pool};
4
use sqlx::FromRow;
5
6
#[derive(Clone, Debug, FromRow)]
7
pub struct Run {
8
    pub id: i64,
9
    pub repo_id: i64,
10
    /// The run's number within its repository, from 1 (migration 0019).
11
    #[sqlx(default)]
12
    pub number: i64,
13
    /// `push`, `manual` or `rerun:N` (migration 0020).
14
    #[sqlx(default)]
15
    pub trigger: String,
16
    pub bookmark: String,
17
    pub state: String,
18
    pub heads: String,
19
    pub pipeline_hash: String,
20
    pub status: String,
21
    pub error: String,
22
    pub actor: String,
23
    pub created_ms: i64,
24
    pub finished_ms: Option<i64>,
25
}
26
27
impl Run {
28
    /// How the run page says what started it.
29
    pub fn started_by(&self) -> String {
30
        match self.trigger.as_str() {
31
            "manual" => format!("started by {}", self.actor),
32
            "schedule" => "started on schedule".to_string(),
33
            t if t.starts_with("tag:") => format!("tag {} pushed by {}", &t[4..], self.actor),
34
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", self.rerun_of().unwrap_or(""), self.actor),
35
            _ => format!("pushed by {}", self.actor),
36
        }
37
    }
38
39
    /// The run a rerun repeats: `N` of `rerun:N` or `rerun:N:EVENT`.
40
    pub fn rerun_of(&self) -> Option<&str> {
41
        let rest = self.trigger.strip_prefix("rerun:")?;
42
        Some(rest.split(':').next().unwrap_or(rest))
43
    }
44
45
    /// The trigger as people read it: `rerun:N`, without the event it repeats.
46
    pub fn trigger_label(&self) -> String {
47
        match self.rerun_of() {
48
            Some(n) => format!("rerun:{n}"),
49
            None => self.trigger.clone(),
50
        }
51
    }
52
53
    pub fn head_list(&self) -> Vec<&str> {
54
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
55
    }
56
57
    pub fn live(&self) -> bool {
58
        matches!(self.status.as_str(), "queued" | "running")
59
    }
60
}
61
62
#[derive(Clone, Debug, Default, FromRow)]
63
pub struct Job {
64
    pub id: i64,
65
    pub run_id: i64,
66
    pub name: String,
67
    pub depth: i64,
68
    pub depends: String,
69
    pub spec: String,
70
    pub sandbox: String,
71
    pub runtime: String,
72
    pub status: String,
73
    pub runner: String,
74
    pub token_hash: String,
75
    pub started_ms: Option<i64>,
76
    pub finished_ms: Option<i64>,
77
    pub exit_code: Option<i64>,
78
    pub error: String,
79
    pub receipt: String,
80
    pub receipt_hash: String,
81
    pub log_count: i64,
82
    /// Comma-separated ids of other repositories the job token may read.
83
    pub also_read: String,
84
    /// The receipt attestation kept in the repository (Oxygen spec §14.6).
85
    pub receipt_attest: String,
86
    /// Who signed it: the runner's identity name.
87
    pub receipt_signer: String,
88
    /// Why a signed receipt was not kept.
89
    pub receipt_note: String,
90
    /// Why a queued job no runner can take waits (spec §11.4), from the
91
    /// last placement pass; empty when it is only waiting its turn.
92
    pub waiting: String,
93
    /// What it took, as its runner reported (oxygenflow#41), in MiB.
94
    pub peak_disk_mib: Option<i64>,
95
    pub peak_memory_mib: Option<i64>,
96
    /// The free disk it needs, learned from past runs of the same job.
97
    pub need_disk_mib: Option<i64>,
98
    /// 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 known;
410
        // an unknown one matches, as before (OxygenFlow spec §11.3).
411
        let wanted = v["arch"].as_str().map(String::from).or_else(|| self.image_archs.get(rootfs).cloned());
412
        let arch_ok = self.arch.is_empty() || wanted.as_deref().is_none_or(|w| w == self.arch);
413
        arch_ok
414
            && self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64)
415
            && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
416
            && (rootfs.is_empty() || self.images.as_ref().is_none_or(|have| have.contains(rootfs)) || self.fetchable.contains(rootfs))
417
    }
418
}
419
420
/// Remember which architecture each image is for, as a runner reports it.
421
pub async fn record_image_archs(pool: &Pool, archs: &std::collections::BTreeMap<String, String>) -> sqlx::Result<()> {
422
    for (hash, arch) in archs.iter().take(500) {
423
        if hash.len() != 64 || !flow_core::arch_ok(arch) {
424
            continue;
425
        }
426
        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")
427
        .bind(hash.to_ascii_lowercase())
428
        .bind(arch)
429
        .bind(now_ms())
430
        .execute(pool)
431
        .await?;
432
    }
433
    Ok(())
434
}
435
436
/// Every image's architecture the hub knows.
437
pub async fn image_archs(pool: &Pool) -> sqlx::Result<std::collections::HashMap<String, String>> {
438
    let rows: Vec<(String, String)> = sqlx::query_as("SELECT hash, arch FROM flow_images").fetch_all(pool).await?;
439
    Ok(rows.into_iter().collect())
440
}
441
442
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
443
    claim_within(pool, runtimes, runner, token_hash, Room::default(), &Default::default(), &[]).await
444
}
445
446
/// The oldest runnable job that fits in `room`.
447
/// The first queued job a runner with these tiers, this room and this
448
/// scope may take, now running under `runner`. A scoped runner never sees
449
/// another scope's jobs (oxygenhub#41).
450
pub async fn claim_within(
451
    pool: &Pool,
452
    runtimes: &[String],
453
    runner: &str,
454
    token_hash: &str,
455
    room: Room,
456
    scope: &super::runners::Scope,
457
    labels: &[String],
458
) -> sqlx::Result<Option<Job>> {
459
    claim_ranked(pool, runtimes, runner, token_hash, room, scope, labels, &|_| false).await
460
}
461
462
/// [`claim_within`], passing over a job `elsewhere` says a better runner
463
/// should take (oxygenflow#42).
464
#[allow(clippy::too_many_arguments)]
465
pub async fn claim_ranked(
466
    pool: &Pool,
467
    runtimes: &[String],
468
    runner: &str,
469
    token_hash: &str,
470
    room: Room,
471
    scope: &super::runners::Scope,
472
    labels: &[String],
473
    elsewhere: &(dyn Fn(&Job) -> bool + Sync),
474
) -> sqlx::Result<Option<Job>> {
475
    let mut tx = super::begin_write(pool).await?;
476
    let queued: Vec<Job> = sqlx::query_as(
477
        "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 \
478
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') \
479
         AND (? = '' OR rep.owner = ?) AND (? IS NULL OR r.repo_id = ?) \
480
         ORDER BY j.run_id, j.depth, j.id LIMIT 200",
481
    )
482
    .bind(&scope.owner)
483
    .bind(&scope.owner)
484
    .bind(scope.repo_id)
485
    .bind(scope.repo_id)
486
    .fetch_all(&mut *tx)
487
    .await?;
488
    for j in queued {
489
        if !runtimes.iter().any(|r| r == &j.runtime)
490
            || !room.fits(&j.sandbox)
491
            || !room.disk_fits(j.need_disk_mib)
492
            || room.declined.contains(&j.id)
493
        {
494
            continue;
495
        }
496
        // Every label the job and its sandbox ask for (`runs-on`).
497
        if !j.needs().iter().all(|l| labels.contains(l)) {
498
            continue;
499
        }
500
        let deps = j.depends_on();
501
        if !deps.is_empty() {
502
            let mut passed = 0i64;
503
            for d in &deps {
504
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
505
                    .bind(j.run_id)
506
                    .bind(d)
507
                    .fetch_optional(&mut *tx)
508
                    .await?;
509
                if st.as_deref() == Some("passed") {
510
                    passed += 1;
511
                }
512
            }
513
            if passed != deps.len() as i64 {
514
                continue;
515
            }
516
        }
517
        if elsewhere(&j) {
518
            continue;
519
        }
520
        let now = now_ms();
521
        let done = sqlx::query(
522
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
523
        )
524
        .bind(runner)
525
        .bind(token_hash)
526
        .bind(now)
527
        .bind(j.id)
528
        .execute(&mut *tx)
529
        .await?;
530
        if done.rows_affected() == 1 {
531
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
532
                .bind(j.run_id)
533
                .execute(&mut *tx)
534
                .await?;
535
            tx.commit().await?;
536
            return job(pool, j.id).await;
537
        }
538
    }
539
    tx.commit().await?;
540
    Ok(None)
541
}
542
543
/// How long a decline keeps a job from its runner when the runner's
544
/// profile stays the same: a reason such as memory in use passes.
545
pub const DECLINE_HOLDS_MS: i64 = 10 * 60_000;
546
547
/// The jobs runner `runner_id` declined with this profile, recently.
548
pub async fn declined_by(pool: &Pool, runner_id: i64, profile: &str) -> sqlx::Result<std::collections::HashSet<i64>> {
549
    let rows: Vec<(i64,)> = sqlx::query_as("SELECT job_id FROM flow_declines WHERE runner_id = ? AND profile = ? AND ms > ?")
550
        .bind(runner_id)
551
        .bind(profile)
552
        .bind(now_ms() - DECLINE_HOLDS_MS)
553
        .fetch_all(pool)
554
        .await?;
555
    Ok(rows.into_iter().map(|(j,)| j).collect())
556
}
557
558
/// A decline: one runner's reason for handing a job back.
559
#[derive(Clone, Debug, sqlx::FromRow)]
560
pub struct DeclineRow {
561
    pub job_id: i64,
562
    pub runner_id: i64,
563
    pub runner: String,
564
    pub reason: String,
565
    pub ms: i64,
566
}
567
568
/// Runner `runner_id` hands back job `job_id`, running on it: the decline
569
/// is kept (one per job and runner, the latest), and the job is queued
570
/// again. Returns every decline the job has had, or `None` when the job
571
/// was not running on that runner.
572
pub async fn decline(
573
    pool: &Pool,
574
    job_id: i64,
575
    runner_id: i64,
576
    runner: &str,
577
    profile: &str,
578
    reason: &str,
579
) -> sqlx::Result<Option<Vec<DeclineRow>>> {
580
    let mut tx = super::begin_write(pool).await?;
581
    let back = sqlx::query(
582
        "UPDATE flow_jobs SET status = 'queued', runner = '', token_hash = '', started_ms = NULL, runner_id = NULL \
583
         WHERE id = ? AND status = 'running' AND runner_id = ?",
584
    )
585
    .bind(job_id)
586
    .bind(runner_id)
587
    .execute(&mut *tx)
588
    .await?;
589
    if back.rows_affected() != 1 {
590
        tx.rollback().await?;
591
        return Ok(None);
592
    }
593
    sqlx::query(
594
        "INSERT INTO flow_declines (job_id, runner_id, runner, profile, reason, ms) VALUES (?, ?, ?, ?, ?, ?) \
595
         ON CONFLICT (job_id, runner_id) DO UPDATE SET runner = excluded.runner, profile = excluded.profile, reason = excluded.reason, ms = excluded.ms",
596
    )
597
    .bind(job_id)
598
    .bind(runner_id)
599
    .bind(runner)
600
    .bind(profile)
601
    .bind(reason)
602
    .bind(now_ms())
603
    .execute(&mut *tx)
604
    .await?;
605
    let all: Vec<DeclineRow> =
606
        sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
607
            .bind(job_id)
608
            .fetch_all(&mut *tx)
609
            .await?;
610
    tx.commit().await?;
611
    Ok(Some(all))
612
}
613
614
/// The declines of job `job_id`, oldest first.
615
pub async fn declines_of_job(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<DeclineRow>> {
616
    sqlx::query_as("SELECT job_id, runner_id, runner, reason, ms FROM flow_declines WHERE job_id = ? ORDER BY ms")
617
        .bind(job_id)
618
        .fetch_all(pool)
619
        .await
620
}
621
622
/// A runner's latest declines, newest first, with where the job is.
623
#[derive(Clone, Debug, sqlx::FromRow)]
624
pub struct RunnerDecline {
625
    pub job_id: i64,
626
    pub job: String,
627
    pub run_number: i64,
628
    pub owner: String,
629
    pub name: String,
630
    pub reason: String,
631
    pub ms: i64,
632
}
633
634
pub async fn declines_of_runner(pool: &Pool, runner_id: i64, limit: i64) -> sqlx::Result<Vec<RunnerDecline>> {
635
    sqlx::query_as(
636
        "SELECT d.job_id, j.name AS job, r.number AS run_number, rep.owner, rep.name, d.reason, d.ms \
637
         FROM flow_declines d JOIN flow_jobs j ON j.id = d.job_id JOIN flow_runs r ON r.id = j.run_id \
638
         JOIN repositories rep ON rep.id = r.repo_id WHERE d.runner_id = ? ORDER BY d.ms DESC LIMIT ?",
639
    )
640
    .bind(runner_id)
641
    .bind(limit)
642
    .fetch_all(pool)
643
    .await
644
}
645
646
/// Queued jobs whose dependencies have passed, in their live runs, with
647
/// their repositories (owner, id): the ones a runner could take now.
648
pub async fn ready_queued(pool: &Pool) -> sqlx::Result<Vec<(Job, String, i64)>> {
649
    let queued: Vec<Job> = sqlx::query_as(
650
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id \
651
         WHERE j.status = 'queued' AND r.status IN ('queued', 'running') ORDER BY j.run_id, j.depth, j.id LIMIT 500",
652
    )
653
    .fetch_all(pool)
654
    .await?;
655
    let mut out = Vec::new();
656
    for j in queued {
657
        let mut ready = true;
658
        for d in j.depends_on() {
659
            let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
660
                .bind(j.run_id)
661
                .bind(&d)
662
                .fetch_optional(pool)
663
                .await?;
664
            if st.as_deref() != Some("passed") {
665
                ready = false;
666
                break;
667
            }
668
        }
669
        if !ready {
670
            continue;
671
        }
672
        let repo: Option<(String, i64)> =
673
            sqlx::query_as("SELECT rep.owner, rep.id FROM flow_runs r JOIN repositories rep ON rep.id = r.repo_id WHERE r.id = ?")
674
                .bind(j.run_id)
675
                .fetch_optional(pool)
676
                .await?;
677
        if let Some((owner, id)) = repo {
678
            out.push((j, owner, id));
679
        }
680
    }
681
    Ok(out)
682
}
683
684
pub async fn set_waiting(pool: &Pool, job_id: i64, waiting: &str) -> sqlx::Result<()> {
685
    sqlx::query("UPDATE flow_jobs SET waiting = ? WHERE id = ? AND waiting <> ?")
686
        .bind(waiting)
687
        .bind(job_id)
688
        .bind(waiting)
689
        .execute(pool)
690
        .await?;
691
    Ok(())
692
}
693
694
/// Append records; returns how many were kept (the rest exceed the cap).
695
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
696
    let mut tx = super::begin_write(pool).await?;
697
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
698
    let room = (cap - count).max(0) as usize;
699
    let keep = &records[..records.len().min(room)];
700
    for (i, r) in keep.iter().enumerate() {
701
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
702
            .bind(job_id)
703
            .bind(count + i as i64 + 1)
704
            .bind(r.t as i64)
705
            .bind(&r.stream)
706
            .bind(&r.text)
707
            .execute(&mut *tx)
708
            .await?;
709
    }
710
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
711
        .bind(keep.len() as i64)
712
        .bind(job_id)
713
        .execute(&mut *tx)
714
        .await?;
715
    tx.commit().await?;
716
    Ok(keep.len())
717
}
718
719
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
720
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
721
        .bind(job_id)
722
        .bind(after)
723
        .bind(limit)
724
        .fetch_all(pool)
725
        .await
726
}
727
728
/// Jobs running since before `ms` (the oldest first).
729
/// Jobs still running at `now` past their own time limit (`default_s` for
730
/// one claimed without) plus `grace_ms`.
731
pub async fn running_past_limit(pool: &Pool, now: i64, default_s: u64, grace_ms: i64) -> sqlx::Result<Vec<Job>> {
732
    sqlx::query_as(
733
        "SELECT * FROM flow_jobs WHERE status = 'running' \
734
         AND COALESCE(started_ms, 0) + (CASE WHEN timeout_s > 0 THEN timeout_s ELSE ? END) * 1000 + ? < ? ORDER BY started_ms",
735
    )
736
    .bind(default_s as i64)
737
    .bind(grace_ms)
738
    .bind(now)
739
    .fetch_all(pool)
740
    .await
741
}
742
743
/// Record the limit a claimed job runs under.
744
pub async fn set_job_timeout(pool: &Pool, job_id: i64, timeout_s: u64) -> sqlx::Result<()> {
745
    sqlx::query("UPDATE flow_jobs SET timeout_s = ? WHERE id = ?").bind(timeout_s as i64).bind(job_id).execute(pool).await?;
746
    Ok(())
747
}
748
749
pub async fn running_since_before(pool: &Pool, ms: i64) -> sqlx::Result<Vec<Job>> {
750
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND COALESCE(started_ms, 0) < ? ORDER BY started_ms")
751
        .bind(ms)
752
        .fetch_all(pool)
753
        .await
754
}
755
756
/// The jobs running on the runner with this id.
757
pub async fn running_on(pool: &Pool, runner_id: i64) -> sqlx::Result<Vec<Job>> {
758
    sqlx::query_as("SELECT * FROM flow_jobs WHERE status = 'running' AND runner_id = ? ORDER BY id").bind(runner_id).fetch_all(pool).await
759
}
760
761
pub struct Outcome<'a> {
762
    pub status: &'a str,
763
    pub exit_code: Option<i64>,
764
    pub error: &'a str,
765
    pub receipt: &'a str,
766
    pub receipt_hash: &'a str,
767
}
768
769
/// Record a job's end, skip the jobs that can no longer run, and settle the
770
/// run. Returns the jobs whose status changed (for their checks).
771
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
772
    let mut tx = super::begin_write(pool).await?;
773
    let now = now_ms();
774
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
775
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
776
        .bind(o.status)
777
        .bind(o.exit_code)
778
        .bind(o.error)
779
        .bind(o.receipt)
780
        .bind(o.receipt_hash)
781
        .bind(now)
782
        .bind(job_id)
783
        .execute(&mut *tx)
784
        .await?;
785
    let mut changed = vec![job_id];
786
    // Dependents of anything that did not pass are skipped, transitively.
787
    loop {
788
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
789
        let blocked: Vec<i64> = all
790
            .iter()
791
            .filter(|x| x.status == "queued")
792
            .filter(|x| {
793
                x.depends_on()
794
                    .iter()
795
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
796
            })
797
            .map(|x| x.id)
798
            .collect();
799
        if blocked.is_empty() {
800
            break;
801
        }
802
        for id in blocked {
803
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
804
                .bind(now)
805
                .bind(id)
806
                .execute(&mut *tx)
807
                .await?;
808
            changed.push(id);
809
        }
810
    }
811
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
812
    if all.iter().all(Job::done) {
813
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
814
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
815
            .bind(status)
816
            .bind(now)
817
            .bind(j.run_id)
818
            .execute(&mut *tx)
819
            .await?;
820
    }
821
    tx.commit().await?;
822
    let mut out = Vec::new();
823
    for id in changed {
824
        if let Some(x) = job(pool, id).await? {
825
            out.push(x);
826
        }
827
    }
828
    Ok(out)
829
}
830
831
/// Cancel a run (oxygenflow#32): its jobs not yet done end as cancelled,
832
/// and so does the run. A runner learns of it when the hub next refuses
833
/// its log lines, and stops the job. Returns the jobs whose status changed.
834
pub async fn cancel_run(pool: &Pool, run_id: i64, why: &str) -> sqlx::Result<Vec<Job>> {
835
    let now = now_ms();
836
    let mut tx = pool.begin().await?;
837
    let ids: Vec<(i64,)> = sqlx::query_as("SELECT id FROM flow_jobs WHERE run_id = ? AND status IN ('queued', 'running')")
838
        .bind(run_id)
839
        .fetch_all(&mut *tx)
840
        .await?;
841
    sqlx::query(
842
        "UPDATE flow_jobs SET status = 'cancelled', error = ?, finished_ms = ?, token_hash = ''
843
         WHERE run_id = ? AND status IN ('queued', 'running')",
844
    )
845
    .bind(why)
846
    .bind(now)
847
    .bind(run_id)
848
    .execute(&mut *tx)
849
    .await?;
850
    sqlx::query("UPDATE flow_runs SET status = 'cancelled', finished_ms = ? WHERE id = ? AND status IN ('queued', 'running')")
851
        .bind(now)
852
        .bind(run_id)
853
        .execute(&mut *tx)
854
        .await?;
855
    tx.commit().await?;
856
    let mut out = Vec::new();
857
    for (id,) in ids {
858
        if let Some(x) = job(pool, id).await? {
859
            out.push(x);
860
        }
861
    }
862
    Ok(out)
863
}
864
865
/// The push runs of `bookmark` still going, older than run `number`.
866
pub async fn live_push_runs_before(pool: &Pool, repo_id: i64, bookmark: &str, number: i64) -> sqlx::Result<Vec<Run>> {
867
    sqlx::query_as(
868
        "SELECT * FROM flow_runs WHERE repo_id = ? AND bookmark = ? AND number < ? AND trigger = 'push'
869
         AND status IN ('queued', 'running') ORDER BY id",
870
    )
871
    .bind(repo_id)
872
    .bind(bookmark)
873
    .bind(number)
874
    .fetch_all(pool)
875
    .await
876
}
877
878
/// The newest run of exactly this state (heads joined with `+`, sorted).
879
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
880
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
881
        .bind(repo_id)
882
        .bind(heads)
883
        .fetch_optional(pool)
884
        .await
885
}
886
887
/// Record what became of job `job_id`'s signed receipt.
888
pub async fn set_receipt(pool: &Pool, job_id: i64, attest: &str, signer: &str, note: &str) -> sqlx::Result<()> {
889
    sqlx::query("UPDATE flow_jobs SET receipt_attest = ?, receipt_signer = ?, receipt_note = ? WHERE id = ?")
890
        .bind(attest)
891
        .bind(signer)
892
        .bind(note)
893
        .bind(job_id)
894
        .execute(pool)
895
        .await?;
896
    Ok(())
897
}
898
899
/// A job's artifact, kept as a blob of the run's repository.
900
#[derive(Clone, Debug, FromRow)]
901
pub struct Artifact {
902
    pub job_id: i64,
903
    pub name: String,
904
    pub path: String,
905
    pub blob: String,
906
    pub size: i64,
907
    /// BLAKE3 of the bytes.
908
    pub content: String,
909
    pub created_ms: i64,
910
}
911
912
pub async fn add_artifact(pool: &Pool, a: &Artifact) -> sqlx::Result<()> {
913
    sqlx::query("INSERT OR REPLACE INTO flow_artifacts (job_id, name, path, blob, size, content, created_ms) VALUES (?, ?, ?, ?, ?, ?, ?)")
914
        .bind(a.job_id)
915
        .bind(&a.name)
916
        .bind(&a.path)
917
        .bind(&a.blob)
918
        .bind(a.size)
919
        .bind(&a.content)
920
        .bind(a.created_ms)
921
        .execute(pool)
922
        .await?;
923
    Ok(())
924
}
925
926
/// Every artifact blob a repository's runs keep, for garbage collection to
927
/// keep too (#126): the database is the only thing that names them.
928
pub async fn artifact_blobs(pool: &Pool, repo_id: i64) -> sqlx::Result<Vec<String>> {
929
    sqlx::query_scalar(
930
        "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 = ?",
931
    )
932
    .bind(repo_id)
933
    .fetch_all(pool)
934
    .await
935
}
936
937
/// Job `job_id`'s artifacts, by name.
938
pub async fn artifacts(pool: &Pool, job_id: i64) -> sqlx::Result<Vec<Artifact>> {
939
    sqlx::query_as("SELECT * FROM flow_artifacts WHERE job_id = ? ORDER BY name").bind(job_id).fetch_all(pool).await
940
}
941
942
/// Where an artifact with given content came from: the run and job that
943
/// built it, and the job's signed receipt when one was kept.
944
#[derive(Clone, Debug, FromRow)]
945
pub struct Provenance {
946
    pub run_number: i64,
947
    pub job: String,
948
    pub name: String,
949
    pub receipt_attest: String,
950
    pub receipt_signer: String,
951
}
952
953
/// The build of the bytes whose BLAKE3 is `content` in repository
954
/// `repo_id`: a passed job, one with a kept signed receipt first, newest
955
/// run first.
956
pub async fn provenance(pool: &Pool, repo_id: i64, content: &str) -> sqlx::Result<Option<Provenance>> {
957
    sqlx::query_as(
958
        "SELECT r.number AS run_number, j.name AS job, a.name AS name, j.receipt_attest, j.receipt_signer \
959
         FROM flow_artifacts a JOIN flow_jobs j ON j.id = a.job_id JOIN flow_runs r ON r.id = j.run_id \
960
         WHERE r.repo_id = ? AND a.content = ? AND j.status = 'passed' \
961
         ORDER BY (j.receipt_attest != '') DESC, r.number DESC LIMIT 1",
962
    )
963
    .bind(repo_id)
964
    .bind(content)
965
    .fetch_optional(pool)
966
    .await
967
}