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