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