OXYGENHUB
# d8b86dc23809 oxygenhub / crates / hub / src / db / flow.rs
13.5 KiB · Rust · last changed Flow runs, jobs and logs in the API; checks by heads 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 repository's runs, newest first, numbered below `before`.
152
pub async fn runs_by_number(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
153
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number < ? ORDER BY number DESC LIMIT ?")
154
        .bind(repo_id)
155
        .bind(before.unwrap_or(i64::MAX))
156
        .bind(limit)
157
        .fetch_all(pool)
158
        .await
159
}
160
161
pub async fn runs(pool: &Pool, repo_id: i64, limit: i64, before: Option<i64>) -> sqlx::Result<Vec<Run>> {
162
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND id < ? ORDER BY id DESC LIMIT ?")
163
        .bind(repo_id)
164
        .bind(before.unwrap_or(i64::MAX))
165
        .bind(limit)
166
        .fetch_all(pool)
167
        .await
168
}
169
170
/// A repository's run by its number there.
171
pub async fn run(pool: &Pool, repo_id: i64, number: i64) -> sqlx::Result<Option<Run>> {
172
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND number = ?").bind(repo_id).bind(number).fetch_optional(pool).await
173
}
174
175
pub async fn run_by_id(pool: &Pool, id: i64) -> sqlx::Result<Option<Run>> {
176
    sqlx::query_as("SELECT * FROM flow_runs WHERE id = ?").bind(id).fetch_optional(pool).await
177
}
178
179
pub async fn jobs(pool: &Pool, run_id: i64) -> sqlx::Result<Vec<Job>> {
180
    sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ? ORDER BY depth, name").bind(run_id).fetch_all(pool).await
181
}
182
183
pub async fn job(pool: &Pool, id: i64) -> sqlx::Result<Option<Job>> {
184
    sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(id).fetch_optional(pool).await
185
}
186
187
/// The running job a job token belongs to, while it may still be used.
188
pub async fn job_by_token(pool: &Pool, token_hash: &str, max_age_ms: i64) -> sqlx::Result<Option<Job>> {
189
    sqlx::query_as("SELECT * FROM flow_jobs WHERE token_hash = ? AND status = 'running' AND started_ms >= ?")
190
        .bind(token_hash)
191
        .bind(now_ms() - max_age_ms)
192
        .fetch_optional(pool)
193
        .await
194
}
195
196
/// Take the oldest queued job whose dependencies all passed and whose tier
197
/// the runner offers, and mark it running for `runner` with a token.
198
/// Let a job's token also read these repositories (its pinned subrepos).
199
pub async fn set_also_read(pool: &Pool, job_id: i64, repo_ids: &[i64]) -> sqlx::Result<()> {
200
    let list: Vec<String> = repo_ids.iter().map(|i| i.to_string()).collect();
201
    sqlx::query("UPDATE flow_jobs SET also_read = ? WHERE id = ?").bind(list.join(",")).bind(job_id).execute(pool).await?;
202
    Ok(())
203
}
204
205
impl Job {
206
    pub fn also_read_ids(&self) -> Vec<i64> {
207
        self.also_read.split(',').filter_map(|x| x.trim().parse().ok()).collect()
208
    }
209
}
210
211
/// What a runner can take on: free memory (MiB) and vCPUs, `None` for no limit.
212
#[derive(Clone, Copy, Debug, Default)]
213
pub struct Room {
214
    pub memory_mib: Option<u32>,
215
    pub cpus: Option<u32>,
216
}
217
218
impl Room {
219
    /// Whether a job's sandbox (its stored JSON) fits.
220
    pub fn fits(&self, sandbox_json: &str) -> bool {
221
        let v: serde_json::Value = serde_json::from_str(sandbox_json).unwrap_or_default();
222
        let need = |k: &str| v[k].as_u64().unwrap_or(0);
223
        self.memory_mib.is_none_or(|m| need("memory_mib") <= m as u64) && self.cpus.is_none_or(|c| need("cpus") <= c as u64)
224
    }
225
}
226
227
pub async fn claim(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str) -> sqlx::Result<Option<Job>> {
228
    claim_within(pool, runtimes, runner, token_hash, Room::default()).await
229
}
230
231
/// The oldest runnable job that fits in `room`.
232
pub async fn claim_within(pool: &Pool, runtimes: &[String], runner: &str, token_hash: &str, room: Room) -> sqlx::Result<Option<Job>> {
233
    let mut tx = super::begin_write(pool).await?;
234
    let queued: Vec<Job> = sqlx::query_as(
235
        "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",
236
    )
237
    .fetch_all(&mut *tx)
238
    .await?;
239
    for j in queued {
240
        if !runtimes.iter().any(|r| r == &j.runtime) || !room.fits(&j.sandbox) {
241
            continue;
242
        }
243
        let deps = j.depends_on();
244
        if !deps.is_empty() {
245
            let mut passed = 0i64;
246
            for d in &deps {
247
                let st: Option<String> = sqlx::query_scalar("SELECT status FROM flow_jobs WHERE run_id = ? AND name = ?")
248
                    .bind(j.run_id)
249
                    .bind(d)
250
                    .fetch_optional(&mut *tx)
251
                    .await?;
252
                if st.as_deref() == Some("passed") {
253
                    passed += 1;
254
                }
255
            }
256
            if passed != deps.len() as i64 {
257
                continue;
258
            }
259
        }
260
        let now = now_ms();
261
        let done = sqlx::query(
262
            "UPDATE flow_jobs SET status = 'running', runner = ?, token_hash = ?, started_ms = ? WHERE id = ? AND status = 'queued'",
263
        )
264
        .bind(runner)
265
        .bind(token_hash)
266
        .bind(now)
267
        .bind(j.id)
268
        .execute(&mut *tx)
269
        .await?;
270
        if done.rows_affected() == 1 {
271
            sqlx::query("UPDATE flow_runs SET status = 'running' WHERE id = ? AND status = 'queued'")
272
                .bind(j.run_id)
273
                .execute(&mut *tx)
274
                .await?;
275
            tx.commit().await?;
276
            return job(pool, j.id).await;
277
        }
278
    }
279
    tx.commit().await?;
280
    Ok(None)
281
}
282
283
/// Append records; returns how many were kept (the rest exceed the cap).
284
pub async fn append_log(pool: &Pool, job_id: i64, records: &[flow_core::api::Record], cap: i64) -> sqlx::Result<usize> {
285
    let mut tx = super::begin_write(pool).await?;
286
    let count: i64 = sqlx::query_scalar("SELECT log_count FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
287
    let room = (cap - count).max(0) as usize;
288
    let keep = &records[..records.len().min(room)];
289
    for (i, r) in keep.iter().enumerate() {
290
        sqlx::query("INSERT INTO flow_logs (job_id, seq, t, stream, text) VALUES (?, ?, ?, ?, ?)")
291
            .bind(job_id)
292
            .bind(count + i as i64 + 1)
293
            .bind(r.t as i64)
294
            .bind(&r.stream)
295
            .bind(&r.text)
296
            .execute(&mut *tx)
297
            .await?;
298
    }
299
    sqlx::query("UPDATE flow_jobs SET log_count = log_count + ? WHERE id = ?")
300
        .bind(keep.len() as i64)
301
        .bind(job_id)
302
        .execute(&mut *tx)
303
        .await?;
304
    tx.commit().await?;
305
    Ok(keep.len())
306
}
307
308
pub async fn log(pool: &Pool, job_id: i64, after: i64, limit: i64) -> sqlx::Result<Vec<LogLine>> {
309
    sqlx::query_as("SELECT seq, t, stream, text FROM flow_logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?")
310
        .bind(job_id)
311
        .bind(after)
312
        .bind(limit)
313
        .fetch_all(pool)
314
        .await
315
}
316
317
pub struct Outcome<'a> {
318
    pub status: &'a str,
319
    pub exit_code: Option<i64>,
320
    pub error: &'a str,
321
    pub receipt: &'a str,
322
    pub receipt_hash: &'a str,
323
}
324
325
/// Record a job's end, skip the jobs that can no longer run, and settle the
326
/// run. Returns the jobs whose status changed (for their checks).
327
pub async fn finish(pool: &Pool, job_id: i64, o: Outcome<'_>) -> sqlx::Result<Vec<Job>> {
328
    let mut tx = super::begin_write(pool).await?;
329
    let now = now_ms();
330
    let j: Job = sqlx::query_as("SELECT * FROM flow_jobs WHERE id = ?").bind(job_id).fetch_one(&mut *tx).await?;
331
    sqlx::query("UPDATE flow_jobs SET status = ?, exit_code = ?, error = ?, receipt = ?, receipt_hash = ?, finished_ms = ?, token_hash = '' WHERE id = ?")
332
        .bind(o.status)
333
        .bind(o.exit_code)
334
        .bind(o.error)
335
        .bind(o.receipt)
336
        .bind(o.receipt_hash)
337
        .bind(now)
338
        .bind(job_id)
339
        .execute(&mut *tx)
340
        .await?;
341
    let mut changed = vec![job_id];
342
    // Dependents of anything that did not pass are skipped, transitively.
343
    loop {
344
        let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
345
        let blocked: Vec<i64> = all
346
            .iter()
347
            .filter(|x| x.status == "queued")
348
            .filter(|x| {
349
                x.depends_on()
350
                    .iter()
351
                    .any(|d| all.iter().any(|y| &y.name == d && matches!(y.status.as_str(), "failed" | "skipped" | "error")))
352
            })
353
            .map(|x| x.id)
354
            .collect();
355
        if blocked.is_empty() {
356
            break;
357
        }
358
        for id in blocked {
359
            sqlx::query("UPDATE flow_jobs SET status = 'skipped', finished_ms = ? WHERE id = ?")
360
                .bind(now)
361
                .bind(id)
362
                .execute(&mut *tx)
363
                .await?;
364
            changed.push(id);
365
        }
366
    }
367
    let all: Vec<Job> = sqlx::query_as("SELECT * FROM flow_jobs WHERE run_id = ?").bind(j.run_id).fetch_all(&mut *tx).await?;
368
    if all.iter().all(Job::done) {
369
        let status = if all.iter().all(|x| x.status == "passed") { "passed" } else { "failed" };
370
        sqlx::query("UPDATE flow_runs SET status = ?, finished_ms = ? WHERE id = ?")
371
            .bind(status)
372
            .bind(now)
373
            .bind(j.run_id)
374
            .execute(&mut *tx)
375
            .await?;
376
    }
377
    tx.commit().await?;
378
    let mut out = Vec::new();
379
    for id in changed {
380
        if let Some(x) = job(pool, id).await? {
381
            out.push(x);
382
        }
383
    }
384
    Ok(out)
385
}
386
387
/// The newest run of exactly this state (heads joined with `+`, sorted).
388
pub async fn latest_for_heads(pool: &Pool, repo_id: i64, heads: &str) -> sqlx::Result<Option<Run>> {
389
    sqlx::query_as("SELECT * FROM flow_runs WHERE repo_id = ? AND heads = ? ORDER BY id DESC LIMIT 1")
390
        .bind(repo_id)
391
        .bind(heads)
392
        .fetch_optional(pool)
393
        .await
394
}