OXYGENHUB
# bf3d07541368 oxygenhub / crates / hub / src / db / flow.rs
14.5 KiB · Rust · last changed A queued run says where it stands 1 month ago source blame history raw
1
//! OxygenFlow runs, jobs and logs (hub spec §13.2).
2
3
use super::{now_ms, Pool};
4
use sqlx::FromRow;
5
6
#[derive(Clone, Debug, FromRow)]
7
pub struct Run {
8
    pub id: i64,
9
    pub repo_id: i64,
10
    /// The run's number within its repository, from 1 (migration 0019).
11
    #[sqlx(default)]
12
    pub number: i64,
13
    /// `push`, `manual` or `rerun:N` (migration 0020).
14
    #[sqlx(default)]
15
    pub trigger: String,
16
    pub bookmark: String,
17
    pub state: String,
18
    pub heads: String,
19
    pub pipeline_hash: String,
20
    pub status: String,
21
    pub error: String,
22
    pub actor: String,
23
    pub created_ms: i64,
24
    pub finished_ms: Option<i64>,
25
}
26
27
impl Run {
28
    /// How the run page says what started it.
29
    pub fn started_by(&self) -> String {
30
        match self.trigger.as_str() {
31
            "manual" => format!("started by {}", self.actor),
32
            t if t.starts_with("rerun:") => format!("re-run of #{} by {}", &t[6..], self.actor),
33
            _ => format!("pushed by {}", self.actor),
34
        }
35
    }
36
37
    pub fn head_list(&self) -> Vec<&str> {
38
        self.heads.split('+').filter(|h| !h.is_empty()).collect()
39
    }
40
41
    pub fn live(&self) -> bool {
42
        matches!(self.status.as_str(), "queued" | "running")
43
    }
44
}
45
46
#[derive(Clone, Debug, FromRow)]
47
pub struct Job {
48
    pub id: i64,
49
    pub run_id: i64,
50
    pub name: String,
51
    pub depth: i64,
52
    pub depends: String,
53
    pub spec: String,
54
    pub sandbox: String,
55
    pub runtime: String,
56
    pub status: String,
57
    pub runner: String,
58
    pub token_hash: String,
59
    pub started_ms: Option<i64>,
60
    pub finished_ms: Option<i64>,
61
    pub exit_code: Option<i64>,
62
    pub error: String,
63
    pub receipt: String,
64
    pub receipt_hash: String,
65
    pub log_count: i64,
66
    /// Comma-separated ids of other repositories the job token may read.
67
    pub also_read: String,
68
}
69
70
impl Job {
71
    pub fn depends_on(&self) -> Vec<String> {
72
        serde_json::from_str(&self.depends).unwrap_or_default()
73
    }
74
75
    pub fn done(&self) -> bool {
76
        matches!(self.status.as_str(), "passed" | "failed" | "skipped" | "error")
77
    }
78
}
79
80
#[derive(Clone, Debug, FromRow)]
81
pub struct LogLine {
82
    pub seq: i64,
83
    pub t: i64,
84
    pub stream: String,
85
    pub text: String,
86
}
87
88
/// A job as the trigger creates it.
89
pub struct NewJob {
90
    pub name: String,
91
    pub depth: i64,
92
    pub depends: Vec<String>,
93
    pub spec: String,
94
    pub sandbox: String,
95
    pub runtime: String,
96
}
97
98
pub struct NewRun<'a> {
99
    pub repo_id: i64,
100
    pub bookmark: &'a str,
101
    pub state: &'a str,
102
    pub heads: &'a str,
103
    pub pipeline_hash: &'a str,
104
    pub actor: &'a str,
105
    /// `push`, `manual` or `rerun:N`.
106
    pub trigger: &'a str,
107
    /// Problems when the pipeline is invalid: the run is recorded in error.
108
    pub error: Option<&'a str>,
109
}
110
111
pub async fn create_run(pool: &Pool, r: NewRun<'_>, jobs: &[NewJob]) -> sqlx::Result<i64> {
112
    let mut tx = super::begin_write(pool).await?;
113
    let now = now_ms();
114
    let status = if r.error.is_some() { "error" } else { "queued" };
115
    let id: i64 = sqlx::query_scalar(
116
        "INSERT INTO flow_runs (repo_id, number, bookmark, state, heads, pipeline_hash, status, error, actor, trigger, created_ms, finished_ms) \
117
         VALUES (?, (SELECT COALESCE(MAX(number), 0) + 1 FROM flow_runs WHERE repo_id = ?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
118
    )
119
    .bind(r.repo_id)
120
    .bind(r.repo_id)
121
    .bind(r.bookmark)
122
    .bind(r.state)
123
    .bind(r.heads)
124
    .bind(r.pipeline_hash)
125
    .bind(status)
126
    .bind(r.error.unwrap_or(""))
127
    .bind(r.actor)
128
    .bind(r.trigger)
129
    .bind(now)
130
    .bind(r.error.map(|_| now))
131
    .fetch_one(&mut *tx)
132
    .await?;
133
    for j in jobs {
134
        sqlx::query(
135
            "INSERT INTO flow_jobs (run_id, name, depth, depends, spec, sandbox, runtime, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'queued')",
136
        )
137
        .bind(id)
138
        .bind(&j.name)
139
        .bind(j.depth)
140
        .bind(serde_json::to_string(&j.depends).unwrap_or_else(|_| "[]".into()))
141
        .bind(&j.spec)
142
        .bind(&j.sandbox)
143
        .bind(&j.runtime)
144
        .execute(&mut *tx)
145
        .await?;
146
    }
147
    tx.commit().await?;
148
    Ok(id)
149
}
150
151
/// A job waiting for or held by a runner, with where it comes from.
152
#[derive(Clone, Debug, FromRow)]
153
pub struct QueueEntry {
154
    pub job_id: i64,
155
    pub run_id: i64,
156
    pub repo_id: i64,
157
    pub owner: String,
158
    pub name: String,
159
    pub visibility: String,
160
    pub run_number: i64,
161
    pub job: String,
162
    pub status: String,
163
}
164
165
/// Every job of a live run that is running or queued: running ones first,
166
/// then queued ones in the order runners claim them (hub spec §13.2).
167
pub async fn queue(pool: &Pool) -> sqlx::Result<Vec<QueueEntry>> {
168
    sqlx::query_as(
169
        "SELECT j.id AS job_id, j.run_id, r.repo_id, p.owner, p.name, p.visibility, r.number AS run_number, j.name AS job, j.status \
170
         FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id JOIN repositories p ON p.id = r.repo_id \
171
         WHERE j.status IN ('queued', 'running') AND r.status IN ('queued', 'running') \
172
         ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.run_id, j.depth, j.id",
173
    )
174
    .fetch_all(pool)
175
    .await
176
}
177
178
/// A repository's runs, newest first, numbered below `before`.
179
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
180
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
181
        .bind(repo_id)
182
        .bind(before.unwrap_or(i64::MAX))
183
        .bind(limit)
184
        .fetch_all(pool)
185
        .await
186
}
187
188
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
189
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
190
        .bind(repo_id)
191
        .bind(before.unwrap_or(i64::MAX))
192
        .bind(limit)
193
        .fetch_all(pool)
194
        .await
195
}
196
197
/// A repository's run by its number there.
198
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
199
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
200
}
201
202
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
203
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
204
}
205
206
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
207
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
208
}
209
210
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
211
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
212
}
213
214
/// The running job a job token belongs to, while it may still be used.
215
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
216
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
217
        .bind(token_hash)
218
        .bind(now_ms() - max_age_ms)
219
        .fetch_optional(pool)
220
        .await
221
}
222
223
/// Take the oldest queued job whose dependencies all passed and whose tier
224
/// the runner offers, and mark it running for `runner` with a token.
225
/// Let a job's token also read these repositories (its pinned subrepos).
226
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
227
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
228
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
229
    Ok(())
230
}
231
232
impl Job {
233
    pub fn also_read_ids(&self) -> Vec<i64> {
234
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
235
    }
236
}
237
238
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no limit.
239
#[derive(Clone, Copy, Debug, Default)]
240
pub struct Room {
241
    pub memory_mib: Option<u32>,
242
    pub cpus: Option<u32>,
243
}
244
245
impl Room {
246
    /// Whether a job's sandbox (its stored JSON) fits.
247
    pub fn fits(&self, sandbox_json: &str) -> bool {
248
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
249
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
250
        self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64) && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
251
    }
252
}
253
254
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
255
    claim_within(pool, runtimes, runner, token_hash, Room::default()).await
256
}
257
258
/// The oldest runnable job that fits in `room`.
259
pub async fn claim_within(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str, room: Room) -> sqlx::Result<Option<Job>> {
260
    let mut tx = super::begin_write(pool).await?;
261
    let queued: Vec<Job> = sqlx::query_as(
262
        "SELECT j.* FROM flow_jobs j JOIN flow_runs r ON r.id = j.run_id WHERE j.status = 'queued' AND r.status IN ('queued', 'running') ORDER BY j.run_id, j.depth, j.id LIMIT 200",
263
    )
264
    .fetch_all(&mut *tx)
265
    .await?;
266
    for j in queued {
267
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) {
268
            continue;
269
        }
270
        let deps = j.depends_on();
271
        if !deps.is_empty() {
272
            let mut passed = 0i64;
273
            for d in &deps {
274
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
275
                    .bind(j.run_id)
276
                    .bind(d)
277
                    .fetch_optional(&mut *tx)
278
                    .await?;
279
                if st.as_deref() == Some("passed") {
280
                    passed += 1;
281
                }
282
            }
283
            if passed != deps.len() as i64 {
284
                continue;
285
            }
286
        }
287
        let now = now_ms();
288
        let done = sqlx::query(
289
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
290
        )
291
        .bind(runner)
292
        .bind(token_hash)
293
        .bind(now)
294
        .bind(j.id)
295
        .execute(&mut *tx)
296
        .await?;
297
        if done.rows_affected() == 1 {
298
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
299
                .bind(j.run_id)
300
                .execute(&mut *tx)
301
                .await?;
302
            tx.commit().await?;
303
            return job(pool, j.id).await;
304
        }
305
    }
306
    tx.commit().await?;
307
    Ok(None)
308
}
309
310
/// Append records; returns how many were kept (the rest exceed the cap).
311
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
312
    let mut tx = super::begin_write(pool).await?;
313
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
314
    let room = (cap - count).max(0) as usize;
315
    let keep = &records[..records.len().min(room)];
316
    for (i, r) in keep.iter().enumerate() {
317
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
318
            .bind(job_id)
319
            .bind(count + i as i64 + 1)
320
            .bind(r.t as i64)
321
            .bind(&r.stream)
322
            .bind(&r.text)
323
            .execute(&mut *tx)
324
            .await?;
325
    }
326
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
327
        .bind(keep.len() as i64)
328
        .bind(job_id)
329
        .execute(&mut *tx)
330
        .await?;
331
    tx.commit().await?;
332
    Ok(keep.len())
333
}
334
335
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
336
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
337
        .bind(job_id)
338
        .bind(after)
339
        .bind(limit)
340
        .fetch_all(pool)
341
        .await
342
}
343
344
pub struct Outcome<'a> {
345
    pub status: &'a str,
346
    pub exit_code: Option<i64>,
347
    pub error: &'a str,
348
    pub receipt: &'a str,
349
    pub receipt_hash: &'a str,
350
}
351
352
/// Record a job's end, skip the jobs that can no longer run, and settle the
353
/// run. Returns the jobs whose status changed (for their checks).
354
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
355
    let mut tx = super::begin_write(pool).await?;
356
    let now = now_ms();
357
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
358
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
359
        .bind(o.status)
360
        .bind(o.exit_code)
361
        .bind(o.error)
362
        .bind(o.receipt)
363
        .bind(o.receipt_hash)
364
        .bind(now)
365
        .bind(job_id)
366
        .execute(&mut *tx)
367
        .await?;
368
    let mut changed = vec![job_id];
369
    // Dependents of anything that did not pass are skipped, transitively.
370
    loop {
371
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
372
        let blocked: Vec<i64> = all
373
            .iter()
374
            .filter(|x| x.status == "queued")
375
            .filter(|x| {
376
                x.depends_on()
377
                    .iter()
378
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
379
            })
380
            .map(|x| x.id)
381
            .collect();
382
        if blocked.is_empty() {
383
            break;
384
        }
385
        for id in blocked {
386
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
387
                .bind(now)
388
                .bind(id)
389
                .execute(&mut *tx)
390
                .await?;
391
            changed.push(id);
392
        }
393
    }
394
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
395
    if all.iter().all(Job::done) {
396
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
397
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
398
            .bind(status)
399
            .bind(now)
400
            .bind(j.run_id)
401
            .execute(&mut *tx)
402
            .await?;
403
    }
404
    tx.commit().await?;
405
    let mut out = Vec::new();
406
    for id in changed {
407
        if let Some(x) = job(pool, id).await? {
408
            out.push(x);
409
        }
410
    }
411
    Ok(out)
412
}
413
414
/// The newest run of exactly this state (heads joined with `+`, sorted).
415
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
416
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
417
        .bind(repo_id)
418
        .bind(heads)
419
        .fetch_optional(pool)
420
        .await
421
}