OXYGENHUB
◆ v0.3.0 oxygenhub / crates / hub / tests / flow.rs
80.7 KiB · Rust · last changed End the jobs a runner no longer holds at its next claim 1 month ago source blame history raw
42fa9554 Andy McCall ↶ 1
//! OxygenFlow on the hub (hub spec §13.2), end to end: a real `oxy` push
2
//! starts a run, a runner claims jobs through the API in dependency order,
3
//! job tokens read only their repository, results become checks and pages.
4
5
use axum::body::Body;
6
use axum::http::{header, Request, StatusCode};
7
use http_body_util::BodyExt;
8
use oxy_core::protocol::{open_remote, RemoteOptions};
9
use oxy_core::repo::Repo;
10
use oxygenhub::config::Config;
11
use oxygenhub::repos::RepoName;
12
use oxygenhub::{db, Shared};
13
use std::path::Path;
14
use tower::ServiceExt;
15
16
const ROOTFS: &str = "36fc4e3238044e424219a2b9002bf61bbe1805fec14d52cf37e17fae77c9ff16";
17
18
fn hermetic() {
19
    static ONCE: std::sync::Once = std::sync::Once::new();
20
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
21
    ONCE.call_once(|| {
22
        let d = tempfile::tempdir().unwrap();
23
        std::env::set_var("OXY_HOME", d.path());
24
        DIR.set(d).ok();
25
    });
26
}
27
28
fn write(root: &Path, rel: &str, content: &str) {
29
    let p = root.join(rel);
30
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
31
    std::fs::write(p, content).unwrap();
32
}
33
34
struct Hub {
35
    app: Shared,
36
    base: String,
37
    _dir: tempfile::TempDir,
38
}
39
40
async fn hub() -> Hub {
41
    hermetic();
42
    let dir = tempfile::tempdir().unwrap();
43
    let mut config = Config::load(dir.path()).unwrap();
44
    config.auth.push_tokens = vec!["site".into()];
45
    config.flow.runner_tokens = vec!["runner-secret".into()];
46
    config.flow.repos = vec!["andy/*".into()];
10708ab8 Andy McCall ↶ 47
    config.registration.mode = "open".into();
42fa9554 Andy McCall ↶ 48
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
49
    let port = listener.local_addr().unwrap().port();
50
    config.server.base_url = format!("http://127.0.0.1:{port}");
51
    let app = oxygenhub::build(config).await.unwrap();
52
    let router = oxygenhub::router(app.clone());
53
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
54
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
55
}
56
57
async fn call(app: &Shared, method: &str, path: &str, bearer: Option<&str>, json: Option<String>) -> (StatusCode, String) {
58
    let mut req = Request::builder().method(method).uri(path);
59
    if let Some(b) = bearer {
60
        req = req.header(header::AUTHORIZATION, format!("Bearer {b}"));
61
    }
62
    let body = match json {
63
        Some(j) => {
64
            req = req.header(header::CONTENT_TYPE, "application/json");
65
            Body::from(j)
66
        }
67
        None => Body::empty(),
68
    };
69
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
70
    let status = res.status();
71
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
72
    (status, String::from_utf8_lossy(&bytes).into_owned())
73
}
74
736f6813 Andy McCall ↶ 75
/// A GET's status, `Location` and `Content-Type`.
76
async fn head(app: &Shared, path: &str) -> (StatusCode, String, String) {
77
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
78
    let h = |k: header::HeaderName| res.headers().get(k).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
79
    (res.status(), h(header::LOCATION), h(header::CONTENT_TYPE))
80
}
81
42fa9554 Andy McCall ↶ 82
async fn claim(app: &Shared) -> Option<serde_json::Value> {
83
    let (st, body) =
84
        call(app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["microvm"]}"#.into())).await;
85
    match st {
86
        StatusCode::NO_CONTENT => None,
87
        StatusCode::OK => Some(serde_json::from_str(&body).unwrap()),
88
        other => panic!("claim: {other} {body}"),
89
    }
90
}
91
92
fn receipt(job: &str, pipeline_hash: &str, exit: u32) -> serde_json::Value {
93
    serde_json::json!({
94
        "job_name": job, "pipeline_hash": pipeline_hash, "scope_tree_hash": "11".repeat(32),
95
        "inputs": [], "environment": "22".repeat(32), "outputs": [], "exit_code": exit, "duration_ms": 640
96
    })
97
}
98
99
async fn finish(app: &Shared, id: i64, body: serde_json::Value) -> StatusCode {
100
    call(app, "POST", &format!("/api/v1/flow/jobs/{id}/finish"), Some("runner-secret"), Some(body.to_string())).await.0
101
}
102
103
async fn create(app: &Shared, owner: &str, name: &str) {
104
    app.repos.create(&RepoName::parse(&format!("{owner}/{name}")).unwrap(), None).unwrap();
105
    db::repos::create(&app.db, owner, name, "", hub_api::Visibility::Public).await.unwrap();
106
}
107
108
fn client(url: &str, work: &Path) -> Repo {
109
    let mut c = Repo::init(work).unwrap();
110
    c.config.set("remote.origin.url", url).unwrap();
111
    c.config.set("remote.origin.token", "site").unwrap();
112
    c.save_config().unwrap();
113
    c
114
}
115
116
fn pipeline(extra: &str) -> String {
117
    format!(
118
        "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    depends-on \"build\"\n    exec \"sh\" \"-eu\" \"test.sh\"\n}}\njob \"lint\" {{\n    sandbox \"alpine\"\n    exec \"true\"\n}}\n{extra}"
119
    )
120
}
121
122
async fn runs_of(app: &Shared, owner: &str, name: &str) -> Vec<db::flow::Run> {
123
    let row = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
124
    for _ in 0..100 {
125
        let r = db::flow::runs(&app.db, row.id, 10, None).await.unwrap();
126
        if !r.is_empty() {
127
            return r;
128
        }
129
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
130
    }
131
    vec![]
132
}
133
90326c96 Andy McCall ↶ 134
/// The checks on a state once there are `n` of them (they follow the run).
135
async fn checks_when(app: &Shared, repo_id: i64, state: &str, n: usize) -> Vec<db::hooks::Check> {
136
    for _ in 0..100 {
137
        let c = db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap();
138
        if c.len() >= n {
139
            return c;
140
        }
141
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
142
    }
143
    db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap()
144
}
145
42fa9554 Andy McCall ↶ 146
#[tokio::test(flavor = "multi_thread")]
147
async fn a_push_runs_the_pipeline_through_a_runner() {
148
    let h = hub().await;
149
    create(&h.app, "andy", "demo").await;
150
    create(&h.app, "andy", "secret").await;
151
    create(&h.app, "other", "plain").await;
152
    let url = format!("{}/andy/demo", h.base);
153
    let work = tempfile::tempdir().unwrap();
154
    let mut c = client(&url, work.path());
155
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
156
    write(work.path(), "test.sh", "echo ok\n");
157
    c.snapshot("test").unwrap();
158
    c.commit("Add a pipeline", &[]).unwrap();
159
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
160
161
    // The push started a run with three queued jobs, and checks for them.
162
    let runs = runs_of(&h.app, "andy", "demo").await;
163
    assert_eq!(runs.len(), 1);
164
    let run = &runs[0];
165
    assert_eq!((run.bookmark.as_str(), run.status.as_str(), run.actor.as_str()), ("main", "queued", "site token"));
166
    assert_eq!(run.pipeline_hash.len(), 64);
167
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
168
    assert_eq!(jobs.iter().map(|j| (j.name.as_str(), j.depth)).collect::<Vec<_>>(), [("build", 0), ("lint", 0), ("test", 1)]);
90326c96 Andy McCall ↶ 169
    // The checks are reported just after the run is recorded.
170
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
42fa9554 Andy McCall ↶ 171
    assert_eq!(
172
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
173
        [("flow/build", "queued"), ("flow/lint", "queued"), ("flow/test", "queued")]
174
    );
175
176
    // Runners need a runner token.
177
    assert_eq!(
178
        call(&h.app, "POST", "/api/v1/flow/claim", Some("site"), Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
179
        StatusCode::UNAUTHORIZED
180
    );
181
    assert_eq!(
182
        call(&h.app, "POST", "/api/v1/flow/claim", None, Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
183
        StatusCode::UNAUTHORIZED
184
    );
185
    // A runner without the tier gets nothing.
186
    let (st, _) =
187
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"x","runtimes":["wasm"]}"#.into())).await;
188
    assert_eq!(st, StatusCode::NO_CONTENT);
189
190
    // Claims come in dependency order; `test` waits for `build`.
191
    let a = claim(&h.app).await.unwrap();
192
    let b = claim(&h.app).await.unwrap();
193
    assert_eq!((a["job"]["name"].as_str(), b["job"]["name"].as_str()), (Some("build"), Some("lint")));
194
    assert!(claim(&h.app).await.is_none(), "test waits for build");
195
    assert_eq!(a["repo"], "andy/demo");
196
    assert_eq!(a["clone_url"], url.as_str());
197
    assert_eq!(a["sandbox"]["rootfs"], ROOTFS);
198
    assert_eq!(a["job"]["exec"], serde_json::json!(["make"]));
199
    assert_eq!(a["timeout_s"], 3600);
9a065bc0 Andy McCall ↶ 200
    // The job is told what it builds (FLOW_STATE, FLOW_BOOKMARK, FLOW_RUN).
201
    assert_eq!(
202
        (a["state"].as_str(), a["bookmark"].as_str(), a["run_number"].as_i64()),
203
        (Some(run.state.as_str()), Some("main"), Some(run.number))
204
    );
42fa9554 Andy McCall ↶ 205
    let heads: Vec<String> = a["heads"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
206
    assert_eq!(heads.join("+"), run.heads);
207
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
208
    assert_eq!(checks.iter().find(|c| c.name == "flow/build").unwrap().status, "running");
209
210
    // The job token reads this repository over the wire, and nothing else.
211
    let token = a["token"].as_str().unwrap().to_string();
212
    assert!(token.starts_with("flowjob_"));
213
    let opts = RemoteOptions { token: Some(token.clone()), ca: None, repo_id: None };
214
    open_remote(&url, &opts).unwrap().refs().unwrap();
215
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
216
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ca: None, repo_id: None };
217
    assert!(open_remote(&url, &bad).unwrap().refs().is_err(), "an unknown job token");
218
    // … and cannot push.
219
    c.config.set("remote.origin.token", &token).unwrap();
220
    c.save_config().unwrap();
221
    write(work.path(), "more.txt", "x\n");
222
    c.snapshot("test").unwrap();
223
    c.commit("More", &[]).unwrap();
224
    let pushed = c.push("origin", false);
225
    assert!(pushed.is_err() || pushed.unwrap().iter().all(|r| !r.ok), "a job token cannot push");
226
    c.config.set("remote.origin.token", "site").unwrap();
227
    c.save_config().unwrap();
228
229
    // Logs, then results with receipts.
230
    let a_id = a["job_id"].as_i64().unwrap();
231
    let b_id = b["job_id"].as_i64().unwrap();
232
    let log = serde_json::json!({ "records": [
233
        { "t": 5, "stream": "flow", "text": "booting" },
234
        { "t": 120, "stream": "out", "text": "cc -o demo demo.c" },
235
        { "t": 130, "stream": "weird", "text": "x".repeat(20_000) },
236
    ]});
237
    assert_eq!(
238
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{a_id}/log"), Some("runner-secret"), Some(log.to_string())).await.0,
239
        StatusCode::NO_CONTENT
240
    );
241
    let lines = db::flow::log(&h.app.db, a_id, 0, 100).await.unwrap();
242
    assert_eq!(lines.len(), 3);
243
    assert_eq!((lines[2].stream.as_str(), lines[2].text.len()), ("console", 16 * 1024), "streams are known ones, text is capped");
244
    let ph = a["pipeline_hash"].as_str().unwrap();
245
    assert_eq!(
246
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("lint", ph, 0) })).await,
247
        StatusCode::BAD_REQUEST,
248
        "a receipt for another job"
249
    );
250
    assert_eq!(
251
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("build", ph, 0) })).await,
252
        StatusCode::NO_CONTENT
253
    );
254
    assert_eq!(finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::CONFLICT, "only once");
255
    assert!(open_remote(&url, &opts).unwrap().refs().is_err(), "the token ends with its job");
256
    assert_eq!(
257
        finish(&h.app, b_id, serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": receipt("lint", ph, 0) })).await,
258
        StatusCode::NO_CONTENT
259
    );
260
    let t = claim(&h.app).await.unwrap();
261
    assert_eq!(t["job"]["name"], "test");
262
    let t_id = t["job_id"].as_i64().unwrap();
263
    assert_eq!(
264
        finish(&h.app, t_id, serde_json::json!({ "exit_code": 3, "duration_ms": 500, "receipt": receipt("test", ph, 3) })).await,
265
        StatusCode::NO_CONTENT
266
    );
267
268
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
269
    assert_eq!(run.status, "failed");
270
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
271
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
272
    assert_eq!((build.status.as_str(), build.exit_code, build.receipt_hash.len()), ("passed", Some(0), 64));
273
    assert_eq!(jobs.iter().find(|j| j.name == "test").unwrap().status, "failed");
274
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
275
    assert_eq!(
276
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
277
        [("flow/build", "passed"), ("flow/lint", "passed"), ("flow/test", "failed")]
278
    );
a0d4bbfb Andy McCall ↶ 279
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
42fa9554 Andy McCall ↶ 280
281
    // Pages: the list, the run with its graph and logs, and the live view.
282
    let (st, list) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
283
    assert_eq!(st, StatusCode::OK);
a0d4bbfb Andy McCall ↶ 284
    assert!(list.contains(&format!("/andy/demo/flow/{}", run.number)) && list.contains("st-failed"), "{list}");
285
    let (st, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
42fa9554 Andy McCall ↶ 286
    assert_eq!(st, StatusCode::OK);
287
    assert!(page.contains("<svg class=\"flow-graph\""), "graph");
288
    assert_eq!(page.matches("data-job-node=").count(), 3);
289
    assert_eq!(page.matches("<path class=\"edge").count(), 1, "one dependency edge");
290
    assert!(page.contains("cc -o demo demo.c"), "log shown");
291
    assert!(!page.contains("data-flow-live"), "a finished run does not poll");
a0d4bbfb Andy McCall ↶ 292
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
42fa9554 Andy McCall ↶ 293
    assert_eq!(st, StatusCode::OK);
294
    let live: serde_json::Value = serde_json::from_str(&live).unwrap();
295
    assert_eq!(live["status"], "failed");
296
    let build_live = live["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
297
    assert_eq!(build_live["lines"].as_array().unwrap().len(), 2, "lines after seq 1");
298
    assert_eq!(call(&h.app, "GET", "/andy/demo/flow/999", None, None).await.0, StatusCode::NOT_FOUND);
299
300
    // A failed dependency skips what follows; an unrun job is an error.
301
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
302
    write(work.path(), "test.sh", "echo changed\n");
303
    c.snapshot("test").unwrap();
304
    c.commit("Change the test", &[]).unwrap();
305
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
306
    let mut second = None;
307
    for _ in 0..100 {
308
        let r = runs_of(&h.app, "andy", "demo").await;
309
        if r.len() == 2 {
310
            second = Some(r[0].clone());
311
            break;
312
        }
313
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
314
    }
315
    let second = second.expect("a second run");
316
    let x = claim(&h.app).await.unwrap();
317
    let y = claim(&h.app).await.unwrap();
318
    let (build_id, lint_id) = if x["job"]["name"] == "build" {
319
        (x["job_id"].as_i64().unwrap(), y["job_id"].as_i64().unwrap())
320
    } else {
321
        (y["job_id"].as_i64().unwrap(), x["job_id"].as_i64().unwrap())
322
    };
323
    assert_eq!(
324
        finish(&h.app, build_id, serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "rootfs is not on this runner" }))
325
            .await,
326
        StatusCode::NO_CONTENT
327
    );
328
    assert_eq!(finish(&h.app, lint_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10 })).await, StatusCode::NO_CONTENT);
329
    assert!(claim(&h.app).await.is_none(), "test was skipped");
330
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
331
    assert_eq!(
332
        jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect::<Vec<_>>(),
333
        [("build", "error"), ("lint", "passed"), ("test", "skipped")]
334
    );
335
    assert_eq!(db::flow::run_by_id(&h.app.db, second.id).await.unwrap().unwrap().status, "failed");
336
337
    // An invalid pipeline is a run in error with the line.
338
    write(work.path(), ".flow/pipeline.kdl", &pipeline("job \"broken\" {\n    sandbox \"missing\"\n    exec \"x\"\n}\n"));
339
    c.snapshot("test").unwrap();
340
    c.commit("Break the pipeline", &[]).unwrap();
341
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
342
    let mut third = None;
343
    for _ in 0..100 {
344
        let r = runs_of(&h.app, "andy", "demo").await;
345
        if r.len() == 3 {
346
            third = Some(r[0].clone());
347
            break;
348
        }
349
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
350
    }
351
    let third = third.expect("a third run");
352
    assert_eq!(third.status, "error");
353
    assert!(third.error.contains("line 18") && third.error.contains("\"missing\""), "{}", third.error);
a0d4bbfb Andy McCall ↶ 354
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
42fa9554 Andy McCall ↶ 355
    assert!(page.contains("The pipeline is not valid"));
356
736f6813 Andy McCall ↶ 357
    // State stamps (hub spec §13.2) and images in READMEs.
358
    write(work.path(), "README.md", "# Demo\n\n[![flow](.flow/stamp)](.flow/run)\n\n![logo](img/logo.png)\n");
359
    std::fs::create_dir_all(work.path().join("img")).unwrap();
360
    std::fs::write(work.path().join("img/logo.png"), b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\0\x01\0\0\0\x01\x08\x06\0\0\0\x1f\x15\xc4\x89")
361
        .unwrap();
362
    c.snapshot("test").unwrap();
363
    c.commit("A README with a stamp", &[]).unwrap();
364
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
365
    let mut fourth = None;
366
    for _ in 0..100 {
367
        let r = runs_of(&h.app, "andy", "demo").await;
368
        if r.len() == 4 {
369
            fourth = Some(r[0].clone());
370
            break;
371
        }
372
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
373
    }
374
    let fourth = fourth.expect("a fourth run");
375
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
376
    assert!(overview.contains("src=\"/andy/demo/raw/main/.flow/stamp\""), "{overview}");
377
    assert!(overview.contains("href=\"/andy/demo/file/main/.flow/run\""));
378
    assert!(overview.contains("src=\"/andy/demo/raw/main/img/logo.png\""), "images use the raw route");
379
    let (st, _, ct) = head(&h.app, "/andy/demo/raw/main/img/logo.png").await;
380
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/png"));
381
    let (st, loc, _) = head(&h.app, "/andy/demo/raw/main/.flow/stamp").await;
382
    assert!(st.is_redirection() && loc == "/andy/demo/flow/stamp/main", "{st} {loc}");
383
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/stamp/main").await;
384
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/stamp/{}", fourth.heads), "a bookmark's stamp names its state: {loc}");
385
    let (st, _, ct) = head(&h.app, &loc).await;
386
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/svg+xml; charset=utf-8"));
387
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
388
    assert!(svg.starts_with("<svg") && svg.contains("error ·") && svg.contains(&fourth.heads[..12]), "{svg}");
389
    let (_, svg1) = call(&h.app, "GET", &format!("/andy/demo/flow/stamp/{}", run.heads), None, None).await;
390
    assert!(svg1.contains("failed ·") && svg1.contains(&format!("run #{} failed", run.id)), "an older state keeps its own result: {svg1}");
391
    assert!(svg1.contains(&build.receipt_hash), "receipt hashes in the metadata");
392
    assert_eq!(svg1.matches("text-anchor=\"middle\"").count(), 3, "one glyph per job");
393
    let (st, loc, _) = head(&h.app, "/andy/demo/file/main/.flow/run").await;
394
    assert!(st.is_redirection() && loc == "/andy/demo/flow/at/main", "{loc}");
395
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/at/main").await;
396
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/{}", fourth.id), "{loc}");
397
42fa9554 Andy McCall ↶ 398
    // A repository outside [flow] repos starts nothing.
399
    let work2 = tempfile::tempdir().unwrap();
400
    let c2 = client(&format!("{}/other/plain", h.base), work2.path());
401
    write(work2.path(), ".flow/pipeline.kdl", &pipeline(""));
402
    c2.snapshot("test").unwrap();
403
    c2.commit("Pipeline", &[]).unwrap();
404
    assert!(c2.push("origin", false).unwrap().iter().all(|r| r.ok));
405
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
406
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
407
    assert!(db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap().is_empty());
408
    let (_, page) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
409
    assert!(page.contains("not enabled for this repository"));
736f6813 Andy McCall ↶ 410
    let (_, loc, _) = head(&h.app, "/other/plain/flow/stamp/main").await;
411
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
412
    assert!(svg.contains("no run ·"), "{svg}");
413
    let (_, loc, _) = head(&h.app, "/other/plain/flow/at/main").await;
414
    assert_eq!(loc, "/other/plain/flow");
42fa9554 Andy McCall ↶ 415
}
fd3db644 Andy McCall ↶ 416
417
#[tokio::test(flavor = "multi_thread")]
418
async fn claims_carry_pinned_subrepos_and_the_job_token_reads_only_those() {
419
    let h = hub().await;
25091e5c Andy McCall ↶ 420
    for n in ["base", "lib", "vault", "other", "app"] {
fd3db644 Andy McCall ↶ 421
        create(&h.app, "andy", n).await;
422
    }
423
    let push = |name: &str, file: &str| {
424
        let work = tempfile::tempdir().unwrap();
425
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
426
        write(work.path(), file, "x\n");
427
        c.snapshot("t").unwrap();
428
        c.commit("first", &[]).unwrap();
429
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
430
        let heads = c.bookmark_heads().unwrap();
431
        (work, heads)
432
    };
25091e5c Andy McCall ↶ 433
    let (_b, base_heads) = push("base", "base.rs");
434
    // lib pins base in turn: a subrepo of a subrepo.
435
    let lib_work = tempfile::tempdir().unwrap();
436
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
437
    lib.submodule_add(&format!("{}/andy/base", h.base), "deps/base", Some("main")).unwrap();
438
    write(lib_work.path(), "lib.rs", "x\n");
439
    lib.snapshot("t").unwrap();
440
    lib.commit("lib on base", &[]).unwrap();
441
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
442
    let lib_heads = lib.bookmark_heads().unwrap();
fd3db644 Andy McCall ↶ 443
    let (_v, _) = push("vault", "secret.rs");
444
    let (_o, _) = push("other", "o.rs");
445
446
    // The app pins lib and vault as subrepos and pushes as the site token.
447
    let work = tempfile::tempdir().unwrap();
448
    let app = client(&format!("{}/andy/app", h.base), work.path());
449
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
a4f01d51 Andy McCall ↶ 450
    // Vault is private: a checkout with no token for this hub cannot add
2bbe88a8 Andy McCall ↶ 451
    // it, but the app's remote on the same hub lends its token (oxygen#32).
452
    // The subrepo keeps no copy: its own fetches find the parent's (oxygen#47).
fd3db644 Andy McCall ↶ 453
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
a4f01d51 Andy McCall ↶ 454
    let bare_work = tempfile::tempdir().unwrap();
455
    let mut bare = Repo::init(bare_work.path()).unwrap();
456
    bare.config.set("remote.origin.url", &format!("{}/andy/bare", h.base)).unwrap();
457
    bare.save_config().unwrap();
458
    assert!(bare.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).is_err(), "not without a token");
370035a4 Andy McCall ↶ 459
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
a4f01d51 Andy McCall ↶ 460
    let nested = Repo::open(&work.path().join("deps/vault")).unwrap();
2bbe88a8 Andy McCall ↶ 461
    assert!(nested.config.remote_tokens.is_empty(), "no token is copied into a subrepo");
462
    nested.fetch("origin").unwrap();
370035a4 Andy McCall ↶ 463
    // The pusher below is the site token, which has no account: it cannot read vault.
fd3db644 Andy McCall ↶ 464
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
465
    write(work.path(), "Makefile", "all:\n");
466
    app.snapshot("t").unwrap();
467
    app.commit("app with deps", &[]).unwrap();
468
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
469
    assert!(!runs_of(&h.app, "andy", "app").await.is_empty());
470
471
    let job = claim(&h.app).await.unwrap();
472
    let subs = job["subrepos"].as_array().cloned().unwrap_or_default();
25091e5c Andy McCall ↶ 473
    assert_eq!(subs.len(), 2, "lib and what lib pins; vault is private and the pusher has no account: {subs:?}");
474
    assert_eq!(subs[1]["path"], "deps/lib/deps/base", "nested under its parent, after it");
475
    assert_eq!(subs[1]["heads"], serde_json::json!(base_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
370035a4 Andy McCall ↶ 476
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
fd3db644 Andy McCall ↶ 477
    assert_eq!(subs[0]["path"], "deps/lib");
478
    assert_eq!(subs[0]["repo"], "andy/lib");
479
    assert_eq!(subs[0]["heads"], serde_json::json!(lib_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
480
    assert!(subs[0]["clone_url"].as_str().unwrap().ends_with("/andy/lib"));
afd0be38 Andy McCall ↶ 481
    // The job's log says vault was left out, and why (oxygenhub#56).
482
    let job_id = job["job_id"].as_i64().unwrap();
483
    let lines = db::flow::log(&h.app.db, job_id, 0, 100).await.unwrap();
484
    assert!(
485
        lines.iter().any(|l| l.stream == "flow" && l.text.contains("subrepo deps/vault (andy/vault) is left out")),
486
        "{:?}",
487
        lines.iter().map(|l| &l.text).collect::<Vec<_>>()
488
    );
fd3db644 Andy McCall ↶ 489
490
    // The job token reads its repository and the pinned lib, nothing else.
491
    let token = job["token"].as_str().unwrap().to_string();
492
    let read = |name: &str| {
493
        let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
494
        open_remote(&format!("{}/andy/{name}", h.base), &opts).and_then(|r| r.refs()).is_ok()
495
    };
25091e5c Andy McCall ↶ 496
    assert!(read("app") && read("lib") && read("base"));
fd3db644 Andy McCall ↶ 497
    assert!(!read("vault"), "not pinned for this pusher");
498
    assert!(!read("other"), "public, but not the job's to read");
499
}
941abdd6 Andy McCall ↶ 500
501
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
502
async fn concurrent_log_appends_never_fail_on_a_locked_database() {
503
    let h = hub().await;
504
    create(&h.app, "andy", "demo").await;
505
    let work = tempfile::tempdir().unwrap();
506
    let c = client(&format!("{}/andy/demo", h.base), work.path());
507
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
508
    write(work.path(), "Makefile", "all:\n");
509
    c.snapshot("t").unwrap();
510
    c.commit("pipeline", &[]).unwrap();
511
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
512
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
513
    let job = db::flow::jobs(&h.app.db, run.id).await.unwrap().remove(0);
514
    // Many writers at once, each reading the count and then inserting: a
515
    // deferred transaction would fail with "database is locked".
516
    let mut tasks = Vec::new();
517
    for w in 0..16 {
518
        let pool = h.app.db.clone();
519
        tasks.push(tokio::spawn(async move {
520
            let records: Vec<flow_core::api::Record> =
521
                (0..20).map(|i| flow_core::api::Record { t: i, stream: "out".into(), text: format!("writer {w} line {i}") }).collect();
522
            db::flow::append_log(&pool, job.id, &records, 100_000).await
523
        }));
524
    }
525
    for t in tasks {
526
        assert_eq!(t.await.unwrap().unwrap(), 20, "every append succeeds");
527
    }
528
    let lines = db::flow::log(&h.app.db, job.id, 0, 1_000).await.unwrap();
529
    assert_eq!(lines.len(), 320);
530
    let seqs: std::collections::BTreeSet<i64> = lines.iter().map(|l| l.seq).collect();
531
    assert_eq!(seqs.len(), 320, "sequence numbers are unique");
532
}
9008bf6c Andy McCall ↶ 533
534
/// A repository's own Flow setting overrides hub.toml either way.
535
#[tokio::test(flavor = "multi_thread")]
536
async fn a_repository_setting_turns_flow_on_or_off() {
537
    let h = hub().await;
538
    create(&h.app, "other", "plain").await;
539
    create(&h.app, "andy", "quiet").await;
a0d4bbfb Andy McCall ↶ 540
    // A run elsewhere first, so hub-wide ids and per-repository numbers differ.
541
    create(&h.app, "andy", "first").await;
542
    {
543
        let work = tempfile::tempdir().unwrap();
544
        let c = client(&format!("{}/andy/first", h.base), work.path());
545
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
546
        write(work.path(), "test.sh", "echo ok\n");
547
        c.commit("Add a pipeline", &[]).unwrap();
548
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
549
        assert_eq!(runs_of(&h.app, "andy", "first").await.len(), 1);
550
    }
9008bf6c Andy McCall ↶ 551
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
552
    db::repos::set_flow(&h.app.db, row.id, "on").await.unwrap();
553
    let quiet = db::repos::get(&h.app.db, "andy", "quiet").await.unwrap().unwrap();
554
    db::repos::set_flow(&h.app.db, quiet.id, "off").await.unwrap();
555
    for (owner, name) in [("other", "plain"), ("andy", "quiet")] {
556
        let work = tempfile::tempdir().unwrap();
557
        let c = client(&format!("{}/{owner}/{name}", h.base), work.path());
558
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
559
        write(work.path(), "test.sh", "echo ok\n");
560
        c.commit("Add a pipeline", &[]).unwrap();
561
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
562
    }
a0d4bbfb Andy McCall ↶ 563
    let plain = runs_of(&h.app, "other", "plain").await;
564
    assert_eq!(plain.len(), 1, "turned on");
bf3d0754 Andy McCall ↶ 565
    // With andy/first's jobs ahead, plain's run says where it stands.
566
    let a = claim(&h.app).await.unwrap();
567
    assert_eq!(a["repo"], "andy/first");
568
    let (_, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
569
    assert!(page.contains("Waiting for a runner: 3rd in line") && page.contains("Running now: andy/first #1"), "{page}");
570
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/other/plain/flow/runs/1", None, None).await;
571
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["queue_position"], 3);
572
    let (_, list) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
573
    assert!(list.contains("queued, 3rd in line"), "{list}");
a0d4bbfb Andy McCall ↶ 574
    // Runs are numbered per repository: this is plain's first, whatever
575
    // other repositories ran before.
576
    assert_eq!(plain[0].number, 1);
90326c96 Andy McCall ↶ 577
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
a0d4bbfb Andy McCall ↶ 578
    assert!(checks.iter().all(|c| c.url.ends_with("/other/plain/flow/1")), "{checks:?}");
579
    let (st, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
580
    assert!(st == StatusCode::OK && page.contains("Run #1"), "{st}");
9008bf6c Andy McCall ↶ 581
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
582
}
1edac4b6 Andy McCall ↶ 583
584
/// "Run pipeline" and "Re-run" (hub spec §13.2): runs that move no
585
/// bookmark, through the API and the pages.
586
#[tokio::test(flavor = "multi_thread")]
587
async fn runs_start_without_a_push_and_finished_runs_re_run() {
588
    let h = hub().await;
589
    // The site token acts as the first site administrator.
590
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
591
    create(&h.app, "andy", "demo").await;
592
    let url = format!("{}/andy/demo", h.base);
593
    let work = tempfile::tempdir().unwrap();
594
    let c = client(&url, work.path());
595
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
596
    write(work.path(), "test.sh", "echo ok\n");
597
    c.commit("Add a pipeline", &[]).unwrap();
598
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
599
    let first = runs_of(&h.app, "andy", "demo").await;
600
    assert_eq!((first.len(), first[0].trigger.as_str()), (1, "push"));
601
602
    // Run pipeline on the default bookmark: a new run of the same state.
603
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
604
    assert_eq!(st, StatusCode::CREATED, "{body}");
605
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
606
    assert_eq!(v["number"], 2);
607
    assert!(v["url"].as_str().unwrap().ends_with("/andy/demo/flow/2"));
608
    let second = db::flow::run(&h.app.db, first[0].repo_id, 2).await.unwrap().unwrap();
609
    assert_eq!((second.trigger.as_str(), second.actor.as_str(), second.state.as_str()), ("manual", "andy", first[0].state.as_str()));
610
    assert_eq!(db::flow::jobs(&h.app.db, second.id).await.unwrap().len(), 3);
611
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/2", None, None).await;
612
    assert!(page.contains("started by andy"), "the run page says what started it");
613
4f692533 Andy McCall ↶ 614
    // Run pipeline on one change: its state, with no bookmark.
615
    let head = first[0].head_list()[0].to_string();
616
    let (st, body) =
617
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{head}"}}"#))).await;
618
    assert_eq!(st, StatusCode::CREATED, "{body}");
619
    let on_change = db::flow::run(&h.app.db, first[0].repo_id, 3).await.unwrap().unwrap();
620
    assert_eq!(
621
        (on_change.bookmark.as_str(), on_change.heads.as_str(), on_change.state.as_str()),
622
        ("", head.as_str(), first[0].state.as_str())
623
    );
624
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/3", None, None).await;
625
    assert!(page.contains("title=\"Run on one change, not a bookmark\">change</span>"), "run page");
626
    let (st, body) =
627
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{}"}}"#, "ab".repeat(32))))
628
            .await;
629
    assert!(st == StatusCode::CONFLICT && body.contains("no change"), "{st} {body}");
630
    // Viewers who cannot start runs are told why, and get no button.
631
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
632
    assert!(page.contains("Sign in with write access to run the pipeline.") && !page.contains("primary-btn"));
633
    let (_, page) = call(&h.app, "GET", "/andy/demo/bookmarks", None, None).await;
634
    assert!(!page.contains("/flow/start"), "no run buttons for anonymous viewers");
635
1edac4b6 Andy McCall ↶ 636
    // A live run is not re-run; unknown bookmarks and runs are refused.
637
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
638
    assert!(st == StatusCode::CONFLICT && body.contains("still queued"), "{st} {body}");
639
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"bookmark":"nope"}"#.into())).await;
640
    assert_eq!(st, StatusCode::CONFLICT);
641
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/99/rerun", Some("site"), None).await;
642
    assert_eq!(st, StatusCode::NOT_FOUND);
643
    // Anonymous callers cannot start runs.
644
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", None, Some("{}".into())).await;
645
    assert_ne!(st, StatusCode::CREATED);
646
647
    // A finished run re-runs as a new run of the same state.
648
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
649
    for r in [&first[0], &second] {
650
        for j in db::flow::jobs(&h.app.db, r.id).await.unwrap() {
651
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = ?").bind(j.id).execute(&h.app.db).await.unwrap();
652
        }
653
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = 1 WHERE id = ?").bind(r.id).execute(&h.app.db).await.unwrap();
654
    }
655
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
656
    assert_eq!(st, StatusCode::CREATED, "{body}");
4f692533 Andy McCall ↶ 657
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
1edac4b6 Andy McCall ↶ 658
    assert_eq!((third.trigger.as_str(), third.status.as_str(), third.state.as_str()), ("rerun:1", "queued", first[0].state.as_str()));
659
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
660
    assert!(
4f692533 Andy McCall ↶ 661
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
1edac4b6 Andy McCall ↶ 662
        "the re-run's checks replace the old ones: {checks:?}"
663
    );
4f692533 Andy McCall ↶ 664
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
1edac4b6 Andy McCall ↶ 665
    assert!(page.contains("re-run of #1 by andy"));
666
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
667
668
    // With Flow off, nothing starts.
669
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
670
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
671
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
4f692533 Andy McCall ↶ 672
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
673
    assert!(page.contains("Flow is off for this repository"), "and the Flow tab says so");
90326c96 Andy McCall ↶ 674
}
675
676
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
677
/// checks by the heads a client has, and JSON for unknown API routes.
678
#[tokio::test(flavor = "multi_thread")]
679
async fn runs_jobs_and_logs_are_in_the_api() {
680
    let h = hub().await;
681
    create(&h.app, "andy", "demo").await;
682
    let url = format!("{}/andy/demo", h.base);
683
    let work = tempfile::tempdir().unwrap();
684
    let c = client(&url, work.path());
685
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
686
    write(work.path(), "test.sh", "echo ok\n");
687
    let head = c.commit("Add a pipeline", &[]).unwrap();
688
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
689
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
690
691
    // A job runs and logs.
692
    let a = claim(&h.app).await.unwrap();
693
    let id = a["job_id"].as_i64().unwrap();
694
    let recs =
695
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
696
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
697
    assert!(st.is_success(), "{st}");
698
699
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
700
    assert_eq!(st, StatusCode::OK, "{body}");
701
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
702
    assert_eq!(runs.len(), 1);
703
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
704
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
705
706
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
707
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
708
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
709
    assert_eq!(names.len(), 3);
710
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
711
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
712
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
713
714
    let job = running.name.clone();
715
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
716
    assert_eq!(st, StatusCode::OK, "{body}");
717
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
718
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
719
    let last = lines.last().unwrap().seq;
720
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
721
    assert_eq!(body, "[]", "nothing after the last line");
722
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
723
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
724
725
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
726
    let by = |key: String| {
727
        let app = h.app.clone();
728
        async move {
729
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
730
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
731
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
732
        }
733
    };
734
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
735
    assert_eq!(by(run.state.clone()).await, 3);
736
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
737
    assert_eq!(by("main".into()).await, 3);
738
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
739
    assert_eq!(st, StatusCode::NOT_FOUND);
740
741
    // An unknown API route answers with a problem document.
742
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
743
    assert_eq!(st, StatusCode::NOT_FOUND);
744
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
745
    assert_eq!(v["status"], 404, "{body}");
1edac4b6 Andy McCall ↶ 746
}
cc19697f Andy McCall ↶ 747
748
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
749
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
750
    let status = res.status();
751
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
752
}
753
754
#[tokio::test(flavor = "multi_thread")]
755
async fn signed_receipts_are_checked_kept_and_shown() {
756
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
757
    use oxy_core::identity::SecretKey;
758
    use oxy_core::objects::StateObject;
759
    use oxy_core::receipt::SignedReceipt;
760
    let h = hub().await;
761
    create(&h.app, "andy", "demo").await;
762
    let url = format!("{}/andy/demo", h.base);
763
    let work = tempfile::tempdir().unwrap();
764
    let c = client(&url, work.path());
765
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
766
    c.snapshot("test").unwrap();
767
    c.commit("Add a pipeline", &[]).unwrap();
768
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
769
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
770
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
771
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
772
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
773
    let sk = SecretKey::generate();
774
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
775
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
776
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
777
        let run_url = format!("{url}/flow/{}", run.number);
778
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
779
    };
780
781
    let a = claim(&h.app).await.unwrap();
782
    let b = claim(&h.app).await.unwrap();
783
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
784
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
785
    // The first signed receipt binds the runner token to its key, and is kept.
786
    let rb = receipt("build", &ph, 0);
787
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
788
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
789
    // Another key under the same token: the result counts, the receipt is not kept.
790
    let other = SecretKey::generate();
791
    let rl = receipt("lint", &ph, 0);
792
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
793
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
794
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
795
    // The right key, but for another state.
796
    let t = claim(&h.app).await.unwrap();
797
    let rt = receipt("test", &ph, 0);
798
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
799
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
800
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
801
802
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
803
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
804
    assert_eq!(job("build").status, "passed");
805
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
806
    assert_eq!(job("lint").status, "passed", "the job's result stands");
807
    assert!(job("lint").receipt_attest.is_empty());
808
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
809
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
810
811
    // The repository keeps it, and anyone who can read the repository can
812
    // download it and check it on their own.
813
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
814
    assert_eq!(kept.len(), 1);
815
    let attest = job("build").receipt_attest;
816
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
817
    assert_eq!(st, StatusCode::OK);
818
    let sr = SignedReceipt::decode(&bytes).unwrap();
819
    sr.verify().unwrap();
820
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
821
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
822
823
    // Pages: the run names the signer or why a receipt was not kept; the
824
    // change whose state it is lists it.
825
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
826
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
827
    assert!(page.contains("receipt not kept"), "run page");
828
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
829
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
830
}
a3c8288b Andy McCall ↶ 831
832
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
833
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
834
        .header(header::AUTHORIZATION, "Bearer runner-secret")
835
        .header(header::CONTENT_TYPE, "application/octet-stream")
836
        .body(Body::from(bytes.to_vec()))
837
        .unwrap();
838
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
839
    let status = res.status();
840
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
841
}
842
843
#[tokio::test(flavor = "multi_thread")]
844
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
845
    let h = hub().await;
846
    create(&h.app, "andy", "demo").await;
847
    let url = format!("{}/andy/demo", h.base);
848
    let work = tempfile::tempdir().unwrap();
849
    let c = client(&url, work.path());
850
    write(
851
        work.path(),
852
        ".flow/pipeline.kdl",
853
        &format!(
854
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n    }}\n}}\n"
855
        ),
856
    );
857
    c.snapshot("test").unwrap();
858
    c.commit("Build a tool", &[]).unwrap();
859
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
860
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
861
    let a = claim(&h.app).await.unwrap();
862
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
863
    let id = a["job_id"].as_i64().unwrap();
864
865
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
866
    let (st, text) = upload(&h.app, id, "other", &body).await;
867
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
868
    let (st, text) = upload(&h.app, id, "tool", &body).await;
869
    assert_eq!(st, StatusCode::OK, "{text}");
870
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
871
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
872
873
    // The receipt must name exactly the uploaded artifacts.
874
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
875
    assert_eq!(
876
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
877
        StatusCode::BAD_REQUEST
878
    );
879
    r["outputs"] = serde_json::json!([blob]);
880
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
881
882
    // The run page lists it; anyone who can read the repository downloads it.
883
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
884
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
885
    assert!(page.contains(&link), "run page lists the artifact");
886
    let (st, got) = get_bytes(&h.app, &link).await;
887
    assert_eq!((st, got == body), (StatusCode::OK, true));
888
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
10708ab8 Andy McCall ↶ 889
890
    // A writer attaches the artifact to a release from the run page; the
891
    // release then names the run and job that built it, as does the API.
892
    let form = |f: String| {
893
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
894
    };
895
    let res = oxygenhub::router(h.app.clone())
896
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery".into()))
897
        .await
898
        .unwrap();
899
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
900
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
901
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
902
        if body.is_some() {
903
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
904
        }
905
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
906
    };
907
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
908
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
909
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
910
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
911
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
912
    assert!(page.contains(&attach), "a writer is offered the release");
913
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
914
    let csrf = page[i..].split('"').next().unwrap().to_string();
915
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
916
    let res = oxygenhub::router(h.app.clone())
917
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
918
        .await
919
        .unwrap();
920
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
921
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
922
    assert!(
923
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
924
        "{page}"
925
    );
926
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
927
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
928
    let asset = &api[0]["assets"][0];
929
    assert_eq!(
930
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
931
        (Some("tool"), Some(run.number), Some("build"))
932
    );
933
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
a3c8288b Andy McCall ↶ 934
}
df940d75 Andy McCall ↶ 935
936
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
937
/// by a job with a signed receipt from the tagged state, and one uploaded
938
/// by hand; the page, its JSON export and the API.
939
#[tokio::test(flavor = "multi_thread")]
940
async fn a_release_is_audited_from_authors_to_receipts() {
941
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
942
    use oxy_core::identity::SecretKey;
943
    use oxy_core::objects::StateObject;
944
    use oxy_core::receipt::SignedReceipt;
945
    let h = hub().await;
946
    create(&h.app, "andy", "demo").await;
947
    let url = format!("{}/andy/demo", h.base);
948
    let work = tempfile::tempdir().unwrap();
949
    let mut c = client(&url, work.path());
950
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
951
    write(
952
        work.path(),
953
        ".flow/pipeline.kdl",
954
        &format!(
955
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n    }}\n}}\n"
956
        ),
957
    );
958
    c.snapshot("test").unwrap();
959
    c.commit("Build a tool", &[]).unwrap();
960
    let heads = c.bookmark_heads().unwrap();
961
    c.tag_create("v1", &heads, "first").unwrap();
962
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
963
964
    // The runner builds, uploads the artifact and signs its receipt.
965
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
966
    let a = claim(&h.app).await.unwrap();
967
    let id = a["job_id"].as_i64().unwrap();
968
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
969
    let (_, text) = upload(&h.app, id, "tool", &body).await;
970
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
971
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
972
    r["outputs"] = serde_json::json!([blob]);
973
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
974
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
975
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
976
    let sk = SecretKey::generate();
977
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
978
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
979
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
980
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
981
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
982
983
    // A release with the built asset and a file uploaded by hand.
984
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
985
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
986
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
987
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
988
989
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
990
    assert_eq!(st, StatusCode::OK);
991
    for want in [
992
        "Tag v1 is signed",
993
        "The one change in the release is authenticated",
994
        "tool: signed receipt from run #1 build",
995
        "a runner key of this hub",
996
        "tool: built from the tagged state",
997
        "tool: pinned environment",
998
        "notes.txt: no build found",
999
        "<svg class=\"trust-graph\"",
1000
    ] {
1001
        assert!(page.contains(want), "missing {want:?}");
1002
    }
1003
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1004
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1005
1006
    // The export carries the signed receipt, which checks on its own.
1007
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1008
    assert_eq!(st, StatusCode::OK);
1009
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1010
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1011
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1012
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1013
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1014
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1015
    sr.verify().unwrap();
1016
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1017
    let audit = t["audit"].as_array().unwrap();
1018
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1019
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1020
    // The API gives the same report; an unknown release is a 404.
1021
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1022
    assert_eq!(st, StatusCode::OK);
1023
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1024
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1025
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1026
}
b6b7e4cf Andy McCall ↶ 1027
1028
/// Runners (hub spec §13.2): an administrator makes a registration token,
1029
/// a runner registers with it (binding its key), claims, shows on Admin →
1030
/// Runners with its history, and is drained, disabled and removed.
1031
#[tokio::test(flavor = "multi_thread")]
1032
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1033
    use oxy_core::identity::SecretKey;
1034
    let h = hub().await;
1035
    create(&h.app, "andy", "demo").await;
1036
    // A signed-in site administrator.
1037
    let res = oxygenhub::router(h.app.clone())
1038
        .oneshot(
1039
            Request::post("/register")
1040
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1041
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery"))
1042
                .unwrap(),
1043
        )
1044
        .await
1045
        .unwrap();
1046
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1047
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1048
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1049
    let web = |method: &'static str, path: String, body: Option<String>| {
1050
        let (app, cookie) = (h.app.clone(), cookie.clone());
1051
        async move {
1052
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1053
            if body.is_some() {
1054
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1055
            }
1056
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1057
            let st = res.status();
1058
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1059
        }
1060
    };
1061
    let csrf_of = |page: &str| {
1062
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1063
        page[i..].split('"').next().unwrap().to_string()
1064
    };
1065
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1066
    assert_eq!(st, StatusCode::OK);
1067
    assert!(page.contains("No runners yet"));
1068
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1069
1070
    // A one-time registration token, shown once with the command.
1071
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1072
    let i = page.find("--token ").unwrap() + "--token ".len();
1073
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1074
    assert!(token.starts_with("flowreg_"), "{token}");
1075
1076
    // The runner registers, binding its key; the token then is spent.
1077
    let sk = SecretKey::generate();
1078
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1079
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": ["big-disk"], "max_jobs": 2, "memory_mib": 16384, "cpus": 4 });
1080
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1081
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1082
    assert_eq!(st, StatusCode::OK, "{body}");
1083
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1084
    assert!(credential.starts_with("flowrunner_"));
1085
    assert_eq!(
1086
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1087
        StatusCode::FORBIDDEN,
1088
        "used once"
1089
    );
1090
1091
    // It claims with its credential; the hub.toml runner shows too.
1092
    let claim_as = |who: String| {
1093
        let app = h.app.clone();
1094
        let info = info.clone();
1095
        async move {
1096
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1097
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1098
        }
1099
    };
1100
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1101
    assert_eq!(claim(&h.app).await, None);
1102
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1103
    assert!(
1104
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1105
        "{page}"
1106
    );
1107
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1108
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1109
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1110
1111
    // A run: plex takes a job, and its history shows it.
1112
    let url = format!("{}/andy/demo", h.base);
1113
    let work = tempfile::tempdir().unwrap();
1114
    let c = client(&url, work.path());
1115
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1116
    c.snapshot("test").unwrap();
1117
    c.commit("Add a pipeline", &[]).unwrap();
1118
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1119
    runs_of(&h.app, "andy", "demo").await;
1120
    let (st, body) = claim_as(credential.clone()).await;
1121
    assert_eq!(st, StatusCode::OK, "{body}");
1122
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1123
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1124
    assert!(
1125
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1126
        "{page}"
1127
    );
b66e70b7 Andy McCall ↶ 1128
    // The queue on Admin → Runners and through the API (#41, part 4).
1129
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1130
    assert!(page.contains("<h2>Queue</h2>") && page.contains("<td>plex</td>"), "{page}");
1131
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1132
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1133
    let i = made.find("oxyhub_").unwrap();
1134
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1135
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1136
    assert_eq!(st, StatusCode::OK, "{body}");
1137
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1138
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1139
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1140
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1141
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1142
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1143
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1144
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1145
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1146
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
b6b7e4cf Andy McCall ↶ 1147
1148
    // Draining: no new work; removing while busy is refused.
1149
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1150
    let csrf = csrf_of(&page);
1151
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1152
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1153
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1154
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1155
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1156
    let id = job["job_id"].as_i64().unwrap();
1157
    let done = call(
1158
        &h.app,
1159
        "POST",
1160
        &format!("/api/v1/flow/jobs/{id}/finish"),
1161
        Some(&credential),
1162
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1163
    )
1164
    .await;
1165
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1166
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1167
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1168
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1169
    assert!(page.contains("Removed plex."), "{page}");
1170
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1171
}
74be9796 Andy McCall ↶ 1172
1173
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1174
/// one owner, takes only those jobs; a site runner takes any.
1175
#[tokio::test(flavor = "multi_thread")]
1176
async fn scoped_runners_take_only_their_scope() {
1177
    use oxy_core::identity::SecretKey;
1178
    let h = hub().await;
1179
    create(&h.app, "andy", "demo").await;
1180
    create(&h.app, "andy", "other").await;
1181
    let register = |scope: db::runners::Scope, name: &'static str| {
1182
        let app = h.app.clone();
1183
        async move {
1184
            let token = format!("flowreg_{name}");
1185
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1186
            let identity = SecretKey::generate().identity(name, "", 1);
1187
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1188
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1189
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1190
            assert_eq!(st, StatusCode::OK, "{body}");
1191
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1192
        }
1193
    };
1194
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1195
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1196
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1197
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1198
    let claim_as = |who: String| {
1199
        let app = h.app.clone();
1200
        async move {
1201
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1202
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1203
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1204
        }
1205
    };
1206
    // Jobs queued in andy/other only.
1207
    let work = tempfile::tempdir().unwrap();
1208
    let c = client(&format!("{}/andy/other", h.base), work.path());
1209
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1210
    c.snapshot("t").unwrap();
1211
    c.commit("pipeline", &[]).unwrap();
1212
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1213
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1214
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1215
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1216
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1217
    // The site runner (hub.toml) takes any.
1218
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1219
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1220
}
7974adb0 Andy McCall ↶ 1221
1222
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1223
/// runner for that repository alone, sees which runners serve it, and
1224
/// removes only its own.
1225
#[tokio::test(flavor = "multi_thread")]
1226
async fn repository_admins_add_and_remove_their_own_runners() {
1227
    use oxy_core::identity::SecretKey;
1228
    let h = hub().await;
1229
    let res = oxygenhub::router(h.app.clone())
1230
        .oneshot(
1231
            Request::post("/register")
1232
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1233
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery"))
1234
                .unwrap(),
1235
        )
1236
        .await
1237
        .unwrap();
1238
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1239
    create(&h.app, "andy", "demo").await;
1240
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1241
    let web = |method: &'static str, path: String, body: Option<String>| {
1242
        let (app, cookie) = (h.app.clone(), cookie.clone());
1243
        async move {
1244
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1245
            if body.is_some() {
1246
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1247
            }
1248
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1249
            let st = res.status();
1250
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1251
        }
1252
    };
1253
    let csrf_of = |page: &str| {
1254
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1255
        page[i..].split('"').next().unwrap().to_string()
1256
    };
1257
    let (st, page) = web("GET", "/andy/demo/settings".into(), None).await;
1258
    assert_eq!(st, StatusCode::OK);
1259
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the section");
1260
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1261
    let i = page.find("--token ").unwrap() + "--token ".len();
1262
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1263
    let identity = SecretKey::generate().identity("mine", "", 1);
1264
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1265
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1266
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1267
    assert_eq!(st, StatusCode::OK, "{body}");
1268
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1269
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1270
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1271
    claim(&h.app).await;
1272
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1273
    let (_, page) = web("GET", "/andy/demo/settings".into(), None).await;
1274
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1275
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1276
    let csrf = csrf_of(&page);
1277
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1278
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1279
    let (_, page) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1280
    assert!(page.contains("mine removed"), "{page}");
1281
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1282
1283
    // The same for an organisation's owner.
1284
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1285
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1286
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1287
    assert_eq!(st, StatusCode::OK);
1288
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1289
    let i = page.find("--token ").unwrap() + "--token ".len();
1290
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1291
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1292
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1293
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1294
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1295
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1296
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1297
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1298
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1299
    assert!(page.contains("acme-runner removed"), "{page}");
1300
}
c4c87f48 Andy McCall ↶ 1301
1302
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1303
/// a runner that has it, and waits for one otherwise.
1304
#[tokio::test(flavor = "multi_thread")]
1305
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1306
    use oxy_core::identity::SecretKey;
1307
    let h = hub().await;
1308
    create(&h.app, "andy", "demo").await;
1309
    let work = tempfile::tempdir().unwrap();
1310
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1311
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1312
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1313
    c.snapshot("t").unwrap();
1314
    c.commit("pipeline", &[]).unwrap();
1315
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1316
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1317
    // The site runner has no labels: it takes the others, never cross.
1318
    let mut taken = Vec::new();
1319
    while let Some(j) = claim(&h.app).await {
1320
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1321
    }
1322
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1323
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1324
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1325
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1326
    // A runner registered with the label takes it.
1327
    let token = "flowreg_riscv";
1328
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1329
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1330
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1331
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1332
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1333
    assert_eq!(st, StatusCode::OK, "{body}");
1334
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1335
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1336
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1337
    assert_eq!(st, StatusCode::OK, "{body}");
1338
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1339
}
070a7b64 Andy McCall ↶ 1340
1341
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1342
/// the hub as the job ended) is ended once it has run past the time limit
1343
/// and a grace: an error with the reason, its dependents skipped and its
1344
/// run settled, as if the runner had reported the error.
1345
#[tokio::test(flavor = "multi_thread")]
1346
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1347
    let h = hub().await;
1348
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1349
    create(&h.app, "andy", "lost").await;
1350
    let url = format!("{}/andy/lost", h.base);
1351
    let work = tempfile::tempdir().unwrap();
1352
    let c = client(&url, work.path());
1353
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1354
    write(work.path(), "test.sh", "echo ok\n");
1355
    c.commit("Add a pipeline", &[]).unwrap();
1356
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1357
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1358
    let job = claim(&h.app).await.expect("a job to claim");
1359
    let id = job["job_id"].as_i64().unwrap();
1360
1361
    // Running, but well within the limit: left alone.
1362
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1363
    // Started long ago and never reported: ended.
1364
    let old = db::now_ms() - 24 * 3600 * 1000;
1365
    sqlx::query("UPDATE flow_jobs SET started_ms = ? WHERE id = ?").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1366
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1367
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1368
    assert_eq!(j.status, "error");
1369
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1370
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1371
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1372
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1373
    // A late report, should one come, does not overwrite the ending.
1374
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1375
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1376
}
b0612e7d Andy McCall ↶ 1377
1378
/// oxygenhub#73: a runner that lists the images it holds is offered only
1379
/// the jobs whose rootfs is among them; one that does not say gets any.
1380
#[tokio::test(flavor = "multi_thread")]
1381
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1382
    let h = hub().await;
1383
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1384
    create(&h.app, "andy", "images").await;
1385
    let url = format!("{}/andy/images", h.base);
1386
    let work = tempfile::tempdir().unwrap();
1387
    let c = client(&url, work.path());
1388
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1389
    write(work.path(), "test.sh", "echo ok\n");
1390
    c.commit("Add a pipeline", &[]).unwrap();
1391
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1392
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1393
    let claim_with = |images: Vec<String>| {
1394
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1395
        let app = h.app.clone();
1396
        async move {
1397
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1398
            (st, body)
1399
        }
1400
    };
1401
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1402
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1403
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1404
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1405
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1406
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1407
    assert_eq!(st, StatusCode::OK, "{body}");
1408
}
eef677c4 Andy McCall ↶ 1409
1410
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1411
/// was given ended at once (it restarted, or never received them), not at
1412
/// the time limit; a held job is left alone.
1413
#[tokio::test(flavor = "multi_thread")]
1414
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1415
    let h = hub().await;
1416
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1417
    create(&h.app, "andy", "held").await;
1418
    let url = format!("{}/andy/held", h.base);
1419
    let work = tempfile::tempdir().unwrap();
1420
    let c = client(&url, work.path());
1421
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1422
    write(work.path(), "test.sh", "echo ok\n");
1423
    c.commit("Add a pipeline", &[]).unwrap();
1424
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1425
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1426
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1427
    let claim_holding = |holding: Vec<i64>| {
1428
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1429
        let app = h.app.clone();
1430
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1431
    };
1432
    claim_holding(vec![id]).await;
1433
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1434
    claim_holding(vec![]).await;
1435
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1436
    assert_eq!(j.status, "error");
1437
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1438
    let run = &runs_of(&h.app, "andy", "held").await[0];
1439
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1440
}