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