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