OXYGENHUB
◆ image-check oxygenhub / crates / hub / tests / flow.rs
166.2 KiB · Rust · last changed Flow: a pipeline pinning an image nobody holds fails a check 24 days ago source blame history raw
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(), "runner-two".into(), "runner-three".into()];
46
    config.flow.repos = vec!["andy/*".into()];
47
    config.registration.mode = "open".into();
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
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
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
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
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)]);
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;
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);
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
    );
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, cache_dir: 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, cache_dir: 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
    );
279
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
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);
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;
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");
292
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
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);
354
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
355
    assert!(page.contains("The pipeline is not valid"));
356
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
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"));
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");
415
}
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;
420
    for n in ["base", "lib", "vault", "other", "app"] {
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
    };
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();
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();
450
    // Vault is private: a checkout with no token for this hub cannot add
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).
453
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
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");
459
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
460
    let nested = Repo::open(&work.path().join("deps/vault")).unwrap();
461
    assert!(nested.config.remote_tokens.is_empty(), "no token is copied into a subrepo");
462
    nested.fetch("origin").unwrap();
463
    // The pusher below is the site token, which has no account: it cannot read vault.
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();
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<_>>()));
476
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
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"));
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
    );
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
    };
496
    assert!(read("app") && read("lib") && read("base"));
497
    assert!(!read("vault"), "not pinned for this pusher");
498
    assert!(!read("other"), "public, but not the job's to read");
499
}
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
}
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;
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
    }
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
    }
563
    let plain = runs_of(&h.app, "other", "plain").await;
564
    assert_eq!(plain.len(), 1, "turned on");
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}");
574
    // Runs are numbered per repository: this is plain's first, whatever
575
    // other repositories ran before.
576
    assert_eq!(plain[0].number, 1);
577
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
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}");
581
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
582
}
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
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
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}");
657
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
658
    assert_eq!(
659
        (third.trigger_label().as_str(), third.status.as_str(), third.state.as_str()),
660
        ("rerun:1", "queued", first[0].state.as_str())
661
    );
662
    assert_eq!(third.trigger, "rerun:1:push", "a rerun keeps the event it repeats");
663
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
664
    assert!(
665
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
666
        "the re-run's checks replace the old ones: {checks:?}"
667
    );
668
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
669
    assert!(page.contains("re-run of #1 by andy"));
670
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
671
672
    // oxygenhub#130: one job, with what it depends on; an unknown one is
673
    // refused, naming the jobs a manual run can start.
674
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["test"]}"#.into())).await;
675
    assert_eq!(st, StatusCode::CREATED, "{body}");
676
    let n = serde_json::from_str::<serde_json::Value>(&body).unwrap()["number"].as_i64().unwrap();
677
    let only = db::flow::run(&h.app.db, first[0].repo_id, n).await.unwrap().unwrap();
678
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, only.id).await.unwrap().into_iter().map(|j| j.name).collect();
679
    names.sort();
680
    assert_eq!(names, ["build", "test"], "test and the job it depends on, not lint");
681
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["deploy"]}"#.into())).await;
682
    assert!(st == StatusCode::CONFLICT && body.contains("not in the pipeline") && body.contains("build, lint, test"), "{st} {body}");
683
684
    // With Flow off, nothing starts.
685
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
686
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
687
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
688
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
689
    assert!(page.contains("Flow is off for this repository"), "and the Flow tab says so");
690
}
691
692
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
693
/// checks by the heads a client has, and JSON for unknown API routes.
694
#[tokio::test(flavor = "multi_thread")]
695
async fn runs_jobs_and_logs_are_in_the_api() {
696
    let h = hub().await;
697
    create(&h.app, "andy", "demo").await;
698
    let url = format!("{}/andy/demo", h.base);
699
    let work = tempfile::tempdir().unwrap();
700
    let c = client(&url, work.path());
701
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
702
    write(work.path(), "test.sh", "echo ok\n");
703
    let head = c.commit("Add a pipeline", &[]).unwrap();
704
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
705
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
706
707
    // A job runs and logs.
708
    let a = claim(&h.app).await.unwrap();
709
    let id = a["job_id"].as_i64().unwrap();
710
    let recs =
711
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
712
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
713
    assert!(st.is_success(), "{st}");
714
715
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
716
    assert_eq!(st, StatusCode::OK, "{body}");
717
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
718
    assert_eq!(runs.len(), 1);
719
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
720
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
721
722
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
723
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
724
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
725
    assert_eq!(names.len(), 3);
726
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
727
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
728
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
729
730
    let job = running.name.clone();
731
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
732
    assert_eq!(st, StatusCode::OK, "{body}");
733
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
734
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
735
    let last = lines.last().unwrap().seq;
736
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
737
    assert_eq!(body, "[]", "nothing after the last line");
738
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
739
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
740
741
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
742
    let by = |key: String| {
743
        let app = h.app.clone();
744
        async move {
745
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
746
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
747
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
748
        }
749
    };
750
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
751
    assert_eq!(by(run.state.clone()).await, 3);
752
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
753
    assert_eq!(by("main".into()).await, 3);
754
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
755
    assert_eq!(st, StatusCode::NOT_FOUND);
756
757
    // An unknown API route answers with a problem document.
758
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
759
    assert_eq!(st, StatusCode::NOT_FOUND);
760
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
761
    assert_eq!(v["status"], 404, "{body}");
762
}
763
764
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
765
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
766
    let status = res.status();
767
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
768
}
769
770
#[tokio::test(flavor = "multi_thread")]
771
async fn signed_receipts_are_checked_kept_and_shown() {
772
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
773
    use oxy_core::identity::SecretKey;
774
    use oxy_core::objects::StateObject;
775
    use oxy_core::receipt::SignedReceipt;
776
    let h = hub().await;
777
    create(&h.app, "andy", "demo").await;
778
    let url = format!("{}/andy/demo", h.base);
779
    let work = tempfile::tempdir().unwrap();
780
    let c = client(&url, work.path());
781
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
782
    c.snapshot("test").unwrap();
783
    c.commit("Add a pipeline", &[]).unwrap();
784
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
785
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
786
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
787
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
788
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
789
    let sk = SecretKey::generate();
790
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
791
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
792
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
793
        let run_url = format!("{url}/flow/{}", run.number);
794
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
795
    };
796
797
    let a = claim(&h.app).await.unwrap();
798
    let b = claim(&h.app).await.unwrap();
799
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
800
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
801
    // The first signed receipt binds the runner token to its key, and is kept.
802
    let rb = receipt("build", &ph, 0);
803
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
804
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
805
    // Another key under the same token: the result counts, the receipt is not kept.
806
    let other = SecretKey::generate();
807
    let rl = receipt("lint", &ph, 0);
808
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
809
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
810
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
811
    // The right key, but for another state.
812
    let t = claim(&h.app).await.unwrap();
813
    let rt = receipt("test", &ph, 0);
814
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
815
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
816
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
817
818
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
819
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
820
    assert_eq!(job("build").status, "passed");
821
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
822
    assert_eq!(job("lint").status, "passed", "the job's result stands");
823
    assert!(job("lint").receipt_attest.is_empty());
824
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
825
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
826
827
    // The repository keeps it, and anyone who can read the repository can
828
    // download it and check it on their own.
829
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
830
    assert_eq!(kept.len(), 1);
831
    let attest = job("build").receipt_attest;
832
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
833
    assert_eq!(st, StatusCode::OK);
834
    let sr = SignedReceipt::decode(&bytes).unwrap();
835
    sr.verify().unwrap();
836
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
837
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
838
839
    // Pages: the run names the signer or why a receipt was not kept; the
840
    // change whose state it is lists it.
841
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
842
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
843
    assert!(page.contains("receipt not kept"), "run page");
844
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
845
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
846
}
847
848
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
849
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
850
        .header(header::AUTHORIZATION, "Bearer runner-secret")
851
        .header(header::CONTENT_TYPE, "application/octet-stream")
852
        .body(Body::from(bytes.to_vec()))
853
        .unwrap();
854
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
855
    let status = res.status();
856
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
857
}
858
859
#[tokio::test(flavor = "multi_thread")]
860
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
861
    let h = hub().await;
862
    create(&h.app, "andy", "demo").await;
863
    let url = format!("{}/andy/demo", h.base);
864
    let work = tempfile::tempdir().unwrap();
865
    let c = client(&url, work.path());
866
    write(
867
        work.path(),
868
        ".flow/pipeline.kdl",
869
        &format!(
870
            "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"
871
        ),
872
    );
873
    c.snapshot("test").unwrap();
874
    c.commit("Build a tool", &[]).unwrap();
875
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
876
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
877
    let a = claim(&h.app).await.unwrap();
878
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
879
    let id = a["job_id"].as_i64().unwrap();
880
881
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
882
    let (st, text) = upload(&h.app, id, "other", &body).await;
883
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
884
    let (st, text) = upload(&h.app, id, "tool", &body).await;
885
    assert_eq!(st, StatusCode::OK, "{text}");
886
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
887
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
888
889
    // The receipt must name exactly the uploaded artifacts.
890
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
891
    assert_eq!(
892
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
893
        StatusCode::BAD_REQUEST
894
    );
895
    r["outputs"] = serde_json::json!([blob]);
896
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
897
898
    // The run page lists it; anyone who can read the repository downloads it.
899
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
900
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
901
    assert!(page.contains(&link), "run page lists the artifact");
902
    let (st, got) = get_bytes(&h.app, &link).await;
903
    assert_eq!((st, got == body), (StatusCode::OK, true));
904
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
905
906
    // The nightly gc keeps it (#126): only the database names it, so with
907
    // no grace period a gc that did not root it would prune it at once.
908
    {
909
        let name = RepoName::parse("andy/demo").unwrap();
910
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
911
        hosted.config.set("core.gc-grace", "0").unwrap();
912
        hosted.save_config().unwrap();
913
    }
914
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
915
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
916
    let (st, got) = get_bytes(&h.app, &link).await;
917
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
918
919
    // A writer attaches the artifact to a release from the run page; the
920
    // release then names the run and job that built it, as does the API.
921
    let form = |f: String| {
922
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
923
    };
924
    let res = oxygenhub::router(h.app.clone())
925
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery".into()))
926
        .await
927
        .unwrap();
928
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
929
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
930
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
931
        if body.is_some() {
932
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
933
        }
934
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
935
    };
936
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
937
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
938
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
939
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
940
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
941
    assert!(page.contains(&attach), "a writer is offered the release");
942
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
943
    let csrf = page[i..].split('"').next().unwrap().to_string();
944
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
945
    let res = oxygenhub::router(h.app.clone())
946
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
947
        .await
948
        .unwrap();
949
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
950
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
951
    assert!(
952
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
953
        "{page}"
954
    );
955
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
956
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
957
    let asset = &api[0]["assets"][0];
958
    assert_eq!(
959
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
960
        (Some("tool"), Some(run.number), Some("build"))
961
    );
962
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
963
}
964
965
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
966
/// receipt names none, and the run page says the file is outside it.
967
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
968
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
969
        .header(header::AUTHORIZATION, "Bearer runner-secret")
970
        .header(header::CONTENT_TYPE, "application/octet-stream")
971
        .header("X-Flow-Report-Path", path)
972
        .body(Body::from(bytes.to_vec()))
973
        .unwrap();
974
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
975
    let status = res.status();
976
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
977
}
978
979
/// #127: a report's files arrive one by one, then its manifest as the
980
/// report's artifact; the hub indexes the declaration, metrics and files,
981
/// and gc keeps every file.
982
#[tokio::test(flavor = "multi_thread")]
983
async fn reports_are_kept_file_by_file_and_indexed() {
984
    let h = hub().await;
985
    create(&h.app, "andy", "demo").await;
986
    let url = format!("{}/andy/demo", h.base);
987
    let work = tempfile::tempdir().unwrap();
988
    let c = client(&url, work.path());
989
    write(
990
        work.path(),
991
        ".flow/pipeline.kdl",
992
        &format!(
993
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"perf\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n    output {{\n        artifact \"tool\" {{\n            path \"/src/out/tool\"\n        }}\n        report \"frame-timing\" {{\n            path \"/src/out/report\"\n            when \"always\"\n        }}\n    }}\n}}\n"
994
        ),
995
    );
996
    c.snapshot("test").unwrap();
997
    c.commit("Measure frames", &[]).unwrap();
998
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
999
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1000
    let a = claim(&h.app).await.unwrap();
1001
    let id = a["job_id"].as_i64().unwrap();
1002
1003
    let toml = b"kind = \"performance\"\ntitle = \"Frame timing\"\nsummary = \"Median 16.4 ms\"\n\n[metrics]\nmedian_ms = { value = 16.4, unit = \"ms\", better = \"lower\", fail_above = 20 }\n\n[context]\ntarget_fps = 30\n";
1004
    let page = b"<p>frames</p>".to_vec();
1005
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
1006
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
1007
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1008
1009
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1010
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1011
    let mut listed = vec![];
1012
    for (path, bytes) in files {
1013
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1014
        assert_eq!(st, StatusCode::OK, "{text}");
1015
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1016
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1017
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1018
    }
1019
    let mut missing = listed.clone();
1020
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1021
    let (st, text) =
1022
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1023
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1024
    assert!(text.contains("assets/x.js"), "{text}");
1025
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1026
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1027
    assert_eq!(st, StatusCode::OK, "{text}");
1028
1029
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
1030
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = ? AND name = 'frame-timing'")
1031
            .bind(id)
1032
            .fetch_one(&h.app.db)
1033
            .await
1034
            .unwrap();
1035
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1036
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
1037
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = ?").bind(id).fetch_one(&h.app.db).await.unwrap();
1038
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1039
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1040
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1041
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
1042
1043
    // The threshold is a check on the run's state, passing at 16.4.
1044
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1045
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1046
    assert_eq!(c.status, "passed", "{c:?}");
1047
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1048
1049
    // The Reports tab, the report's page, and its own page in a sandbox.
1050
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1051
    assert!(page.contains(">Reports</a>"), "the tab");
1052
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1053
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1054
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1055
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1056
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1057
    assert!(src.ends_with("/index.html"), "{src}");
1058
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1059
    assert_eq!(res.status(), StatusCode::OK);
1060
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1061
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
1062
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
1063
    // The page as kept, with the frame script that sizes the frame added.
1064
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1065
    assert!(served.starts_with(&page_bytes), "the report's page");
1066
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1067
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1068
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
1069
    let data = src.replace("/index.html", "/data/frames.csv");
1070
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1071
    // A link with another report's MAC, or a file it lacks, finds nothing.
1072
    // A second run of the report: the timeline has two stops, and the
1073
    // first can be compared with it (RP4).
1074
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1075
    let second: i64 = sqlx::query_scalar(
1076
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
1077
         SELECT repo_id, name, kind, title, 'Median 18.0 ms', context, run_id, NULL, 2, job, bookmark, state, manifest, files, bytes, created_ms + 1000 FROM reports WHERE id = ? RETURNING id",
1078
    )
1079
    .bind(first)
1080
    .fetch_one(&h.app.db)
1081
    .await
1082
    .unwrap();
1083
    sqlx::query(
1084
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES (?, 'median_ms', 18.0, 'ms', 'lower', 20)",
1085
    )
1086
    .bind(second)
1087
    .execute(&h.app.db)
1088
    .await
1089
    .unwrap();
1090
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1091
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1092
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1093
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1094
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1095
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1096
    assert!(page.contains("data-play=\"3\""), "playing");
1097
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1098
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
1099
    let forged = src.replacen("/files/", "/files/9", 1);
1100
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1101
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
1102
    let _ = run;
1103
1104
    // gc keeps every file: only the database names them.
1105
    {
1106
        let name = RepoName::parse("andy/demo").unwrap();
1107
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1108
        hosted.config.set("core.gc-grace", "0").unwrap();
1109
        hosted.save_config().unwrap();
1110
    }
1111
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1112
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1113
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1114
    for (path, bytes) in files {
1115
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1116
    }
1117
}
1118
1119
#[tokio::test(flavor = "multi_thread")]
1120
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1121
    let h = hub().await;
1122
    create(&h.app, "andy", "demo").await;
1123
    let url = format!("{}/andy/demo", h.base);
1124
    let work = tempfile::tempdir().unwrap();
1125
    let c = client(&url, work.path());
1126
    write(
1127
        work.path(),
1128
        ".flow/pipeline.kdl",
1129
        &format!(
1130
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"test\"\n    output {{\n        artifact \"junit\" {{\n            path \"/src/out/junit.xml\"\n            when \"always\"\n        }}\n    }}\n}}\n"
1131
        ),
1132
    );
1133
    c.snapshot("test").unwrap();
1134
    c.commit("Test", &[]).unwrap();
1135
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1136
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1137
    let a = claim(&h.app).await.unwrap();
1138
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
1139
    let id = a["job_id"].as_i64().unwrap();
1140
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1141
    let xml = br#"<testsuites><testsuite name="pytest"><testcase classname="tests.test_io" name="test_read" time="0.5"/><testcase classname="tests.test_io" name="test_write" time="1.5"><failure message="disk full">E   OSError: disk full</failure></testcase></testsuite></testsuites>"#;
1142
    let (st, text) = upload(&h.app, id, "junit", xml).await;
1143
    assert_eq!(st, StatusCode::OK, "{text}");
1144
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1145
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1146
    r["outputs"] = serde_json::json!([blob]);
1147
    assert_eq!(
1148
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1149
        StatusCode::BAD_REQUEST,
1150
        "a failing receipt names no outputs"
1151
    );
1152
    r["outputs"] = serde_json::json!([]);
1153
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
1154
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1155
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1156
    assert!(page.contains("not in its receipt"), "marked");
1157
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1158
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1159
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
1160
}
1161
1162
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1163
/// by a job with a signed receipt from the tagged state, and one uploaded
1164
/// by hand; the page, its JSON export and the API.
1165
#[tokio::test(flavor = "multi_thread")]
1166
async fn a_release_is_audited_from_authors_to_receipts() {
1167
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1168
    use oxy_core::identity::SecretKey;
1169
    use oxy_core::objects::StateObject;
1170
    use oxy_core::receipt::SignedReceipt;
1171
    let h = hub().await;
1172
    create(&h.app, "andy", "demo").await;
1173
    let url = format!("{}/andy/demo", h.base);
1174
    let work = tempfile::tempdir().unwrap();
1175
    let mut c = client(&url, work.path());
1176
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1177
    write(
1178
        work.path(),
1179
        ".flow/pipeline.kdl",
1180
        &format!(
1181
            "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"
1182
        ),
1183
    );
1184
    c.snapshot("test").unwrap();
1185
    c.commit("Build a tool", &[]).unwrap();
1186
    let heads = c.bookmark_heads().unwrap();
1187
    c.tag_create("v1", &heads, "first").unwrap();
1188
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1189
1190
    // The runner builds, uploads the artifact and signs its receipt.
1191
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1192
    let a = claim(&h.app).await.unwrap();
1193
    let id = a["job_id"].as_i64().unwrap();
1194
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1195
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1196
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1197
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1198
    r["outputs"] = serde_json::json!([blob]);
1199
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1200
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1201
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1202
    let sk = SecretKey::generate();
1203
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1204
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1205
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1206
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1207
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1208
1209
    // A release with the built asset and a file uploaded by hand.
1210
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1211
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1212
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1213
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1214
1215
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1216
    assert_eq!(st, StatusCode::OK);
1217
    for want in [
1218
        "Tag v1 is signed",
1219
        "The one change in the release is authenticated",
1220
        "tool: signed receipt from run #1 build",
1221
        "a runner key of this hub",
1222
        "The tagged state is one change",
1223
        "tool: built from the tagged state",
1224
        "tool: pinned environment",
1225
        "notes.txt: no build found",
1226
        "<svg class=\"trust-graph\"",
1227
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1228
        // graph drawn at its own size rather than stretched to the page.
1229
        "Tag signed by",
1230
        "1 of 1 changes signed or sealed",
1231
        "1 of 2 assets built and attested by OxygenFlow",
1232
        "attested build",
1233
        "uploaded by hand",
1234
        "receipt verified",
1235
        "class=\"shackle\"",
1236
        "<title>notes.txt:",
1237
    ] {
1238
        assert!(page.contains(want), "missing {want:?}");
1239
    }
1240
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1241
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
1242
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1243
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1244
1245
    // The export carries the signed receipt, which checks on its own.
1246
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1247
    assert_eq!(st, StatusCode::OK);
1248
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1249
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1250
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1251
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1252
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1253
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1254
    sr.verify().unwrap();
1255
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1256
    let audit = t["audit"].as_array().unwrap();
1257
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1258
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1259
    // The API gives the same report; an unknown release is a 404.
1260
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1261
    assert_eq!(st, StatusCode::OK);
1262
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1263
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1264
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1265
}
1266
1267
/// Runners (hub spec §13.2): an administrator makes a registration token,
1268
/// a runner registers with it (binding its key), claims, shows on Admin →
1269
/// Runners with its history, and is drained, disabled and removed.
1270
#[tokio::test(flavor = "multi_thread")]
1271
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1272
    use oxy_core::identity::SecretKey;
1273
    let h = hub().await;
1274
    create(&h.app, "andy", "demo").await;
1275
    // A signed-in site administrator.
1276
    let res = oxygenhub::router(h.app.clone())
1277
        .oneshot(
1278
            Request::post("/register")
1279
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1280
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery"))
1281
                .unwrap(),
1282
        )
1283
        .await
1284
        .unwrap();
1285
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1286
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1287
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1288
    let web = |method: &'static str, path: String, body: Option<String>| {
1289
        let (app, cookie) = (h.app.clone(), cookie.clone());
1290
        async move {
1291
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1292
            if body.is_some() {
1293
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1294
            }
1295
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1296
            let st = res.status();
1297
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1298
        }
1299
    };
1300
    let csrf_of = |page: &str| {
1301
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1302
        page[i..].split('"').next().unwrap().to_string()
1303
    };
1304
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1305
    assert_eq!(st, StatusCode::OK);
1306
    assert!(page.contains("No runners yet"));
1307
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1308
1309
    // A one-time registration token, shown once with the command.
1310
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1311
    let i = page.find("--token ").unwrap() + "--token ".len();
1312
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1313
    assert!(token.starts_with("flowreg_"), "{token}");
1314
1315
    // The runner registers, binding its key; the token then is spent.
1316
    let sk = SecretKey::generate();
1317
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1318
    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 });
1319
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1320
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1321
    assert_eq!(st, StatusCode::OK, "{body}");
1322
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1323
    assert!(credential.starts_with("flowrunner_"));
1324
    assert_eq!(
1325
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1326
        StatusCode::FORBIDDEN,
1327
        "used once"
1328
    );
1329
1330
    // It claims with its credential; the hub.toml runner shows too.
1331
    let claim_as = |who: String| {
1332
        let app = h.app.clone();
1333
        let info = info.clone();
1334
        async move {
1335
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1336
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1337
        }
1338
    };
1339
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1340
    assert_eq!(claim(&h.app).await, None);
1341
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1342
    assert!(
1343
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1344
        "{page}"
1345
    );
1346
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1347
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1348
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1349
1350
    // A run: plex takes a job, and its history shows it.
1351
    let url = format!("{}/andy/demo", h.base);
1352
    let work = tempfile::tempdir().unwrap();
1353
    let c = client(&url, work.path());
1354
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1355
    c.snapshot("test").unwrap();
1356
    c.commit("Add a pipeline", &[]).unwrap();
1357
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1358
    runs_of(&h.app, "andy", "demo").await;
1359
    let (st, body) = claim_as(credential.clone()).await;
1360
    assert_eq!(st, StatusCode::OK, "{body}");
1361
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1362
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1363
    assert!(
1364
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1365
        "{page}"
1366
    );
1367
    // The queue on Admin → Runners and through the API (#41, part 4).
1368
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1369
    assert!(page.contains("<h2>Queue</h2>") && page.contains("<td>plex</td>"), "{page}");
1370
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1371
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1372
    let i = made.find("oxyhub_").unwrap();
1373
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1374
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1375
    assert_eq!(st, StatusCode::OK, "{body}");
1376
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1377
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1378
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1379
    // A runner's own labels and time limit from its page (#98).
1380
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1381
    let (st, _) = web(
1382
        "POST",
1383
        format!("/admin/runners/{}/limits", plex.id),
1384
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1385
    )
1386
    .await;
1387
    assert_eq!(st, StatusCode::SEE_OTHER);
1388
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1389
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1390
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1391
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1392
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1393
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1394
    let (st, _) = web(
1395
        "POST",
1396
        format!("/admin/runners/{}/limits", plex.id),
1397
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1398
    )
1399
    .await;
1400
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
1401
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1402
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1403
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1404
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1405
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1406
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1407
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1408
1409
    // Draining: no new work; removing while busy is refused.
1410
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1411
    let csrf = csrf_of(&page);
1412
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1413
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1414
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1415
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1416
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1417
    let id = job["job_id"].as_i64().unwrap();
1418
    let done = call(
1419
        &h.app,
1420
        "POST",
1421
        &format!("/api/v1/flow/jobs/{id}/finish"),
1422
        Some(&credential),
1423
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1424
    )
1425
    .await;
1426
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1427
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1428
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1429
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1430
    assert!(page.contains("Removed plex."), "{page}");
1431
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1432
}
1433
1434
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1435
/// one owner, takes only those jobs; a site runner takes any.
1436
#[tokio::test(flavor = "multi_thread")]
1437
async fn scoped_runners_take_only_their_scope() {
1438
    use oxy_core::identity::SecretKey;
1439
    let h = hub().await;
1440
    create(&h.app, "andy", "demo").await;
1441
    create(&h.app, "andy", "other").await;
1442
    let register = |scope: db::runners::Scope, name: &'static str| {
1443
        let app = h.app.clone();
1444
        async move {
1445
            let token = format!("flowreg_{name}");
1446
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1447
            let identity = SecretKey::generate().identity(name, "", 1);
1448
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1449
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1450
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1451
            assert_eq!(st, StatusCode::OK, "{body}");
1452
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1453
        }
1454
    };
1455
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1456
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1457
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1458
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1459
    let claim_as = |who: String| {
1460
        let app = h.app.clone();
1461
        async move {
1462
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1463
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1464
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1465
        }
1466
    };
1467
    // Jobs queued in andy/other only.
1468
    let work = tempfile::tempdir().unwrap();
1469
    let c = client(&format!("{}/andy/other", h.base), work.path());
1470
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1471
    c.snapshot("t").unwrap();
1472
    c.commit("pipeline", &[]).unwrap();
1473
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1474
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1475
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1476
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1477
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1478
    // The site runner (hub.toml) takes any.
1479
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1480
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1481
}
1482
1483
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1484
/// runner for that repository alone, sees which runners serve it, and
1485
/// removes only its own.
1486
#[tokio::test(flavor = "multi_thread")]
1487
async fn repository_admins_add_and_remove_their_own_runners() {
1488
    use oxy_core::identity::SecretKey;
1489
    let h = hub().await;
1490
    let res = oxygenhub::router(h.app.clone())
1491
        .oneshot(
1492
            Request::post("/register")
1493
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1494
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery"))
1495
                .unwrap(),
1496
        )
1497
        .await
1498
        .unwrap();
1499
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1500
    create(&h.app, "andy", "demo").await;
1501
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1502
    let web = |method: &'static str, path: String, body: Option<String>| {
1503
        let (app, cookie) = (h.app.clone(), cookie.clone());
1504
        async move {
1505
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1506
            if body.is_some() {
1507
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1508
            }
1509
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1510
            let st = res.status();
1511
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1512
        }
1513
    };
1514
    let csrf_of = |page: &str| {
1515
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1516
        page[i..].split('"').next().unwrap().to_string()
1517
    };
1518
    let (st, page) = web("GET", "/andy/demo/settings".into(), None).await;
1519
    assert_eq!(st, StatusCode::OK);
1520
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the section");
1521
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1522
    let i = page.find("--token ").unwrap() + "--token ".len();
1523
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1524
    let identity = SecretKey::generate().identity("mine", "", 1);
1525
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1526
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1527
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1528
    assert_eq!(st, StatusCode::OK, "{body}");
1529
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1530
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1531
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1532
    claim(&h.app).await;
1533
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1534
    let (_, page) = web("GET", "/andy/demo/settings".into(), None).await;
1535
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1536
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1537
    let csrf = csrf_of(&page);
1538
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1539
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1540
    let (_, page) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1541
    assert!(page.contains("mine removed"), "{page}");
1542
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1543
1544
    // The same for an organisation's owner.
1545
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1546
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1547
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1548
    assert_eq!(st, StatusCode::OK);
1549
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1550
    let i = page.find("--token ").unwrap() + "--token ".len();
1551
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1552
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1553
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1554
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1555
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1556
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1557
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1558
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1559
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1560
    assert!(page.contains("acme-runner removed"), "{page}");
1561
}
1562
1563
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1564
/// a runner that has it, and waits for one otherwise.
1565
#[tokio::test(flavor = "multi_thread")]
1566
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1567
    use oxy_core::identity::SecretKey;
1568
    let h = hub().await;
1569
    create(&h.app, "andy", "demo").await;
1570
    let work = tempfile::tempdir().unwrap();
1571
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1572
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1573
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1574
    c.snapshot("t").unwrap();
1575
    c.commit("pipeline", &[]).unwrap();
1576
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1577
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1578
    // The site runner has no labels: it takes the others, never cross.
1579
    let mut taken = Vec::new();
1580
    while let Some(j) = claim(&h.app).await {
1581
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1582
    }
1583
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1584
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1585
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1586
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1587
    // A runner registered with the label takes it.
1588
    let token = "flowreg_riscv";
1589
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1590
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1591
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1592
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1593
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1594
    assert_eq!(st, StatusCode::OK, "{body}");
1595
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1596
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1597
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1598
    assert_eq!(st, StatusCode::OK, "{body}");
1599
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1600
}
1601
1602
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1603
/// the hub as the job ended) is ended once it has run past the time limit
1604
/// and a grace: an error with the reason, its dependents skipped and its
1605
/// run settled, as if the runner had reported the error.
1606
#[tokio::test(flavor = "multi_thread")]
1607
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1608
    let h = hub().await;
1609
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1610
    create(&h.app, "andy", "lost").await;
1611
    let url = format!("{}/andy/lost", h.base);
1612
    let work = tempfile::tempdir().unwrap();
1613
    let c = client(&url, work.path());
1614
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1615
    write(work.path(), "test.sh", "echo ok\n");
1616
    c.commit("Add a pipeline", &[]).unwrap();
1617
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1618
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1619
    let job = claim(&h.app).await.expect("a job to claim");
1620
    let id = job["job_id"].as_i64().unwrap();
1621
1622
    // Running, but well within the limit: left alone.
1623
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1624
    // Started long ago and never reported: ended.
1625
    let old = db::now_ms() - 24 * 3600 * 1000;
1626
    sqlx::query("UPDATE flow_jobs SET started_ms = ? WHERE id = ?").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1627
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1628
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1629
    assert_eq!(j.status, "error");
1630
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1631
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1632
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1633
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1634
    // A late report, should one come, does not overwrite the ending.
1635
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1636
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1637
}
1638
1639
/// oxygenhub#73: a runner that lists the images it holds is offered only
1640
/// the jobs whose rootfs is among them; one that does not say gets any.
1641
#[tokio::test(flavor = "multi_thread")]
1642
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1643
    let h = hub().await;
1644
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1645
    create(&h.app, "andy", "images").await;
1646
    let url = format!("{}/andy/images", h.base);
1647
    let work = tempfile::tempdir().unwrap();
1648
    let c = client(&url, work.path());
1649
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1650
    write(work.path(), "test.sh", "echo ok\n");
1651
    c.commit("Add a pipeline", &[]).unwrap();
1652
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1653
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1654
    let claim_with = |images: Vec<String>| {
1655
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1656
        let app = h.app.clone();
1657
        async move {
1658
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1659
            (st, body)
1660
        }
1661
    };
1662
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1663
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1664
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1665
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1666
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1667
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1668
    assert_eq!(st, StatusCode::OK, "{body}");
1669
}
1670
1671
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1672
/// was given ended at once (it restarted, or never received them), not at
1673
/// the time limit; a held job is left alone.
1674
#[tokio::test(flavor = "multi_thread")]
1675
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1676
    let h = hub().await;
1677
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1678
    create(&h.app, "andy", "held").await;
1679
    let url = format!("{}/andy/held", h.base);
1680
    let work = tempfile::tempdir().unwrap();
1681
    let c = client(&url, work.path());
1682
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1683
    write(work.path(), "test.sh", "echo ok\n");
1684
    c.commit("Add a pipeline", &[]).unwrap();
1685
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1686
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1687
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1688
    let claim_holding = |holding: Vec<i64>| {
1689
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1690
        let app = h.app.clone();
1691
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1692
    };
1693
    claim_holding(vec![id]).await;
1694
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1695
    claim_holding(vec![]).await;
1696
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1697
    assert_eq!(j.status, "error");
1698
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1699
    let run = &runs_of(&h.app, "andy", "held").await[0];
1700
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1701
}
1702
1703
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1704
/// changes touch a path it names (a release job, when Cargo.toml's version
1705
/// moves); a bookmark's first run and manual runs have every job.
1706
#[tokio::test(flavor = "multi_thread")]
1707
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1708
    let h = hub().await;
1709
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1710
    create(&h.app, "andy", "scoped").await;
1711
    let url = format!("{}/andy/scoped", h.base);
1712
    let work = tempfile::tempdir().unwrap();
1713
    let c = client(&url, work.path());
1714
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1715
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1716
    write(work.path(), "test.sh", "echo ok\n");
1717
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1718
    c.commit("Start", &[]).unwrap();
1719
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1720
    let names = |app: Shared, n: usize| async move {
1721
        let mut runs = Vec::new();
1722
        for _ in 0..100 {
1723
            runs = runs_of(&app, "andy", "scoped").await;
1724
            if runs.len() >= n {
1725
                break;
1726
            }
1727
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1728
        }
1729
        assert_eq!(runs.len(), n, "runs");
1730
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1731
        j.sort();
1732
        // Passed, so the next push is scoped against it, not superseding it.
1733
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = ?").bind(runs[0].id).execute(&app.db).await.unwrap();
1734
        j
1735
    };
1736
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1737
    write(work.path(), "test.sh", "echo still ok\n");
1738
    c.commit("Edit the test", &[]).unwrap();
1739
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1740
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1741
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1742
    c.commit("Release 0.1.1", &[]).unwrap();
1743
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1744
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1745
}
1746
1747
/// oxygenflow#32: a run still going is cancelled from the API, the web or
1748
/// by a newer push to its bookmark; its runner is refused from then on,
1749
/// and the next push is scoped past the cancelled run.
1750
#[tokio::test(flavor = "multi_thread")]
1751
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
1752
    let h = hub().await;
1753
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1754
    create(&h.app, "andy", "stop").await;
1755
    let url = format!("{}/andy/stop", h.base);
1756
    let work = tempfile::tempdir().unwrap();
1757
    let c = client(&url, work.path());
1758
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1759
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1760
    write(work.path(), "test.sh", "echo ok\n");
1761
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1762
    c.commit("Start", &[]).unwrap();
1763
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1764
    let wait_runs = |app: Shared, n: usize| async move {
1765
        for _ in 0..100 {
1766
            let runs = runs_of(&app, "andy", "stop").await;
1767
            if runs.len() >= n {
1768
                return runs;
1769
            }
1770
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1771
        }
1772
        panic!("no run {n}");
1773
    };
1774
    let first = wait_runs(h.app.clone(), 1).await;
1775
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = ?").bind(first[0].id).execute(&h.app.db).await.unwrap();
1776
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = ?").bind(first[0].id).execute(&h.app.db).await.unwrap();
1777
1778
    // Run 2 (a version bump) has a job running when run 3 is pushed.
1779
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1780
    c.commit("Release 0.1.1", &[]).unwrap();
1781
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1782
    wait_runs(h.app.clone(), 2).await;
1783
    let job = claim(&h.app).await.expect("a job of run 2");
1784
    let id = job["job_id"].as_i64().unwrap();
1785
    write(work.path(), "test.sh", "echo still ok\n");
1786
    c.commit("Edit the test", &[]).unwrap();
1787
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1788
    let runs = wait_runs(h.app.clone(), 3).await;
1789
    let third = &runs[0];
1790
    let mut second = runs[1].clone();
1791
    for _ in 0..100 {
1792
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
1793
        if !second.live() {
1794
            break;
1795
        }
1796
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1797
    }
1798
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
1799
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
1800
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
1801
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
1802
    names.sort();
1803
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
1804
    let mut checks = vec![];
1805
    for _ in 0..100 {
1806
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
1807
        if checks.iter().all(|c| c.status == "cancelled") {
1808
            break;
1809
        }
1810
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1811
    }
1812
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
1813
    // The runner of the cancelled job is refused, so it stops the job.
1814
    let (st, _) =
1815
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
1816
    assert_eq!(st, StatusCode::CONFLICT);
1817
1818
    // By hand: the API, then a run already ended is refused.
1819
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1820
    assert_eq!(st, StatusCode::OK, "{body}");
1821
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
1822
    assert_eq!(third.status, "cancelled");
1823
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
1824
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1825
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
1826
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
1827
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
1828
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
1829
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
1830
}
1831
1832
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
1833
/// timeout, capped at the site's maximum, else the site's default; and the
1834
/// hub gives a job up only past its own limit.
1835
#[tokio::test(flavor = "multi_thread")]
1836
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
1837
    let h = hub().await;
1838
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1839
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
1840
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
1841
    create(&h.app, "andy", "limits").await;
1842
    let url = format!("{}/andy/limits", h.base);
1843
    let work = tempfile::tempdir().unwrap();
1844
    let c = client(&url, work.path());
1845
    let extra = "job \"slow\" {\n    sandbox \"alpine\"\n    timeout \"90m\"\n    exec \"true\"\n}\njob \"huge\" {\n    sandbox \"alpine\"\n    timeout \"5h\"\n    exec \"true\"\n}\n";
1846
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1847
    write(work.path(), "test.sh", "echo ok\n");
1848
    c.commit("Add a pipeline", &[]).unwrap();
1849
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1850
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
1851
    let mut limits = std::collections::HashMap::new();
1852
    let mut ids = std::collections::HashMap::new();
1853
    while let Some(j) = claim(&h.app).await {
1854
        let name = j["job"]["name"].as_str().unwrap().to_string();
1855
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
1856
        ids.insert(name, j["job_id"].as_i64().unwrap());
1857
    }
1858
    assert_eq!(limits["slow"], 5400, "its own");
1859
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
1860
    assert_eq!(limits["build"], 1800, "the site's default");
1861
    // 40 minutes in: past the default and its grace, within slow's limit.
1862
    let started = db::now_ms() - 40 * 60 * 1000;
1863
    sqlx::query("UPDATE flow_jobs SET started_ms = ?").bind(started).execute(&h.app.db).await.unwrap();
1864
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
1865
    let status = |id: i64| {
1866
        let app = h.app.clone();
1867
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
1868
    };
1869
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
1870
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
1871
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
1872
}
1873
1874
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
1875
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
1876
/// does not name starts no run; a rerun repeats its run's event.
1877
#[tokio::test(flavor = "multi_thread")]
1878
async fn on_decides_which_events_start_a_job() {
1879
    let h = hub().await;
1880
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1881
    create(&h.app, "andy", "events").await;
1882
    let url = format!("{}/andy/events", h.base);
1883
    let work = tempfile::tempdir().unwrap();
1884
    let c = client(&url, work.path());
1885
    let text = format!(
1886
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
1887
        pipeline("")
1888
    );
1889
    // `on` must come after schema-version; pipeline() starts with it.
1890
    let text = text.replacen(
1891
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
1892
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
1893
        1,
1894
    );
1895
    write(work.path(), ".flow/pipeline.kdl", &text);
1896
    write(work.path(), "test.sh", "echo ok\n");
1897
    c.commit("Start", &[]).unwrap();
1898
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1899
    let jobs_of_latest = |app: Shared, n: usize| async move {
1900
        let mut runs = Vec::new();
1901
        for _ in 0..100 {
1902
            runs = runs_of(&app, "andy", "events").await;
1903
            if runs.len() >= n {
1904
                break;
1905
            }
1906
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1907
        }
1908
        assert_eq!(runs.len(), n, "runs");
1909
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1910
        j.sort();
1911
        (runs[0].clone(), j)
1912
    };
1913
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
1914
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
1915
    // A tag: only dist.
1916
    let heads = c.bookmark_heads().unwrap();
1917
    c.tag_create("v1.0.0", &heads, "first").unwrap();
1918
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1919
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
1920
    assert_eq!(j, ["dist"], "a tag runs only what names it");
1921
    assert_eq!(run.trigger, "tag:v1.0.0");
1922
    // A rerun repeats the tag's event.
1923
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
1924
    db::flow::finish(
1925
        &h.app.db,
1926
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
1927
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
1928
    )
1929
    .await
1930
    .unwrap();
1931
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
1932
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
1933
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
1934
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
1935
    // A bookmark the pipeline does not name starts nothing.
1936
    c.bookmark_create("develop", None).unwrap();
1937
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
1938
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1939
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
1940
}
1941
1942
/// oxygenflow#24: a job with a `schedule` line runs on the default
1943
/// bookmark when the line comes due, and only then; other jobs stay out.
1944
#[tokio::test(flavor = "multi_thread")]
1945
async fn scheduled_jobs_run_when_due() {
1946
    let h = hub().await;
1947
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1948
    create(&h.app, "andy", "nightly").await;
1949
    let url = format!("{}/andy/nightly", h.base);
1950
    let work = tempfile::tempdir().unwrap();
1951
    let c = client(&url, work.path());
1952
    // An odd minute, so the hub's own ticker cannot fire it during the test.
1953
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
1954
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1955
    write(work.path(), "test.sh", "echo ok\n");
1956
    c.commit("Start", &[]).unwrap();
1957
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1958
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
1959
    let first = runs_of(&h.app, "andy", "nightly").await;
1960
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1961
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
1962
    use flow_core::pipeline::When;
1963
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
1964
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
1965
    let due = When { minute: 17, ..not_yet };
1966
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
1967
    let runs = runs_of(&h.app, "andy", "nightly").await;
1968
    assert_eq!(runs.len(), 2);
1969
    assert_eq!(runs[0].trigger, "schedule");
1970
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1971
    assert_eq!(names, ["nightly"]);
1972
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
1973
}
1974
1975
#[tokio::test(flavor = "multi_thread")]
1976
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
1977
    use oxygenhub::levels::Scope;
1978
    use oxygenhub::variables;
1979
    let h = hub().await;
1980
    let app = &h.app;
1981
    // Andy, the site's administrator, owns the acme organisation.
1982
    let res = oxygenhub::router(app.clone())
1983
        .oneshot(
1984
            Request::post("/register")
1985
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1986
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery"))
1987
                .unwrap(),
1988
        )
1989
        .await
1990
        .unwrap();
1991
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1992
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
1993
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
1994
    create(app, "acme", "app").await;
1995
    let page = |path: &str, form: Option<String>| {
1996
        let mut req =
1997
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
1998
        if form.is_some() {
1999
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2000
        }
2001
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2002
        let app = app.clone();
2003
        async move {
2004
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2005
            let status = res.status();
2006
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2007
            (status, body)
2008
        }
2009
    };
2010
    let csrf_of = |page: &str| {
2011
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2012
        page[i..].split('"').next().unwrap().to_string()
2013
    };
2014
2015
    // The site sets CC and LANG, the organisation its own CC, the
2016
    // repository RUST_LOG from its settings page.
2017
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2018
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2019
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2020
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
2021
    let (st, settings) = page("/acme/app/settings", None).await;
2022
    assert_eq!(st, StatusCode::OK, "{settings}");
2023
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2024
    let csrf = csrf_of(&settings);
2025
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2026
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2027
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2028
    assert!(body.contains("not FLOW_"), "{body}");
2029
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2030
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2031
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2032
    assert_eq!(
2033
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2034
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2035
        "the organisation's CC wins over the site's"
2036
    );
2037
2038
    // A claim carries them.
2039
    let url = format!("{}/acme/app", h.base);
2040
    let work = tempfile::tempdir().unwrap();
2041
    let c = client(&url, work.path());
2042
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2043
    write(work.path(), "test.sh", "echo ok\n");
2044
    c.snapshot("test").unwrap();
2045
    c.commit("Add a pipeline", &[]).unwrap();
2046
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2047
    let runs = runs_of(app, "acme", "app").await;
2048
    assert_eq!(runs.len(), 1, "{runs:?}");
2049
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2050
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2051
2052
    // Removing a site variable from the admin page takes effect at the next claim.
2053
    let (_, admin) = page("/admin", None).await;
2054
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2055
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2056
    assert!(body.contains("LANG removed."), "{body}");
2057
    let got = claim(app).await.expect("another job");
2058
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2059
}
2060
2061
#[tokio::test(flavor = "multi_thread")]
2062
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2063
    let h = hub().await;
2064
    let app = &h.app;
2065
    let res = oxygenhub::router(app.clone())
2066
        .oneshot(
2067
            Request::post("/register")
2068
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2069
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery"))
2070
                .unwrap(),
2071
        )
2072
        .await
2073
        .unwrap();
2074
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2075
    let page = |path: &str, form: Option<String>| {
2076
        let mut req =
2077
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2078
        if form.is_some() {
2079
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2080
        }
2081
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2082
        let app = app.clone();
2083
        async move {
2084
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2085
            let status = res.status();
2086
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2087
            (status, body)
2088
        }
2089
    };
2090
    let csrf_of = |page: &str| {
2091
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2092
        page[i..].split('"').next().unwrap().to_string()
2093
    };
2094
    create(app, "andy", "demo").await;
2095
    // The site sets deploy-token; the repository overrides it. Neither
2096
    // page shows a value, only that it is set.
2097
    let (_, admin) = page("/admin", None).await;
2098
    let csrf = csrf_of(&admin);
2099
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2100
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2101
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2102
    assert!(body.contains("name is 1 to 64 of"), "{body}");
2103
    let (_, settings) = page("/andy/demo/settings", None).await;
2104
    assert!(
2105
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2106
        "{settings}"
2107
    );
2108
    let csrf_r = csrf_of(&settings);
2109
    let (_, body) =
2110
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2111
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2112
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2113
    assert!(
2114
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2115
            .contains("hunter22"),
2116
        "sealed at rest"
2117
    );
2118
2119
    // A job that declares the secret, and one the levels do not hold.
2120
    let url = format!("{}/andy/demo", h.base);
2121
    let work = tempfile::tempdir().unwrap();
2122
    let c = client(&url, work.path());
2123
    write(
2124
        work.path(),
2125
        ".flow/pipeline.kdl",
2126
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    secret \"deploy-token\" {\n        mount-path \"/run/secrets/token\"\n    }\n    secret \"missing\" {\n        mount-path \"/run/secrets/missing\"\n    }\n    exec \"deploy\"\n}\n"),
2127
    );
2128
    write(work.path(), "test.sh", "echo ok\n");
2129
    c.snapshot("test").unwrap();
2130
    c.commit("Add a pipeline", &[]).unwrap();
2131
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2132
    let runs = runs_of(app, "andy", "demo").await;
2133
    let jobs = match runs.first() {
2134
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2135
        None => vec![],
2136
    };
2137
    let mut deploy = None;
2138
    for _ in 0..50 {
2139
        let Some(got) = claim(app).await else {
2140
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2141
            continue;
2142
        };
2143
        if got["job"]["name"] == "deploy" {
2144
            deploy = Some(got);
2145
            break;
2146
        }
2147
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2148
    }
2149
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2150
    assert_eq!(
2151
        got["secrets"],
2152
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2153
        "the repository's value, the missing one left out: {got}"
2154
    );
2155
    let id = got["job_id"].as_i64().unwrap();
2156
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2157
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2158
2159
    // The value never reaches the stored log, plain or base64.
2160
    let records = serde_json::json!({ "records": [
2161
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2162
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2163
    ] });
2164
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2165
    assert_eq!(st, StatusCode::NO_CONTENT);
2166
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2167
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2168
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2169
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2170
}
2171
2172
#[tokio::test(flavor = "multi_thread")]
2173
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2174
    let h = hub().await;
2175
    let app = &h.app;
2176
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2177
    assert_eq!(st, StatusCode::OK, "{disc}");
2178
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2179
    assert_eq!(disc["issuer"], h.base.as_str());
2180
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2181
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2182
    assert_eq!(st, StatusCode::OK, "{jwks}");
2183
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2184
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2185
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2186
2187
    create(app, "andy", "demo").await;
2188
    let url = format!("{}/andy/demo", h.base);
2189
    let work = tempfile::tempdir().unwrap();
2190
    let c = client(&url, work.path());
2191
    write(
2192
        work.path(),
2193
        ".flow/pipeline.kdl",
2194
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2195
    );
2196
    write(work.path(), "test.sh", "echo ok\n");
2197
    c.snapshot("test").unwrap();
2198
    c.commit("Add a pipeline", &[]).unwrap();
2199
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2200
    let mut deploy = None;
2201
    for _ in 0..50 {
2202
        let Some(got) = claim(app).await else {
2203
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2204
            continue;
2205
        };
2206
        if got["job"]["name"] == "deploy" {
2207
            deploy = Some(got);
2208
            break;
2209
        }
2210
    }
2211
    let got = deploy.expect("the deploy job");
2212
    let secrets = got["secrets"].as_array().expect("secrets");
2213
    assert_eq!(secrets.len(), 1);
2214
    assert_eq!(
2215
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2216
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2217
    );
2218
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2219
    let issuer = app.oidc().await.unwrap();
2220
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2221
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2222
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2223
    assert_eq!(claims["repository"], "andy/demo");
2224
    assert_eq!(claims["job"], "deploy");
2225
    assert_eq!(claims["run_number"], 1);
2226
    assert_eq!(claims["runner"], "test-1");
2227
    assert_eq!(claims["iss"], h.base.as_str());
2228
    assert!(claims["state"].as_str().unwrap().len() == 64);
2229
    // A job that prints its token leaves *** in the log.
2230
    let id = got["job_id"].as_i64().unwrap();
2231
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2232
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2233
    assert_eq!(st, StatusCode::NO_CONTENT);
2234
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2235
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2236
}
2237
2238
#[tokio::test(flavor = "multi_thread")]
2239
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2240
    let h = hub().await;
2241
    let app = &h.app;
2242
    create(app, "andy", "demo").await;
2243
    let url = format!("{}/andy/demo", h.base);
2244
    let work = tempfile::tempdir().unwrap();
2245
    let c = client(&url, work.path());
2246
    write(work.path(), ".flow/pipeline.kdl", &pipeline("sandbox \"board\" {\n    rootfs \"cas://blob/{ROOTFS}\"\n    arch \"riscv64\"\n}\njob \"flash\" {\n    sandbox \"board\"\n    exec \"flash\"\n}\n").replace("{ROOTFS}", &"ab".repeat(32)));
2247
    write(work.path(), "test.sh", "echo ok\n");
2248
    c.snapshot("test").unwrap();
2249
    c.commit("Add a pipeline", &[]).unwrap();
2250
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2251
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2252
        let app = app.clone();
2253
        async move {
2254
            let body = serde_json::json!({
2255
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2256
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2257
                "image_archs": archs,
2258
            });
2259
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2260
            match st {
2261
                StatusCode::NO_CONTENT => None,
2262
                StatusCode::OK => {
2263
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2264
                }
2265
                other => panic!("claim: {other} {body}"),
2266
            }
2267
        }
2268
    };
2269
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2270
    // alpine jobs, never the one that asks for riscv64.
2271
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2272
    for _ in 0..50 {
2273
        if !runs_of(app, "andy", "demo").await.is_empty() {
2274
            break;
2275
        }
2276
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2277
    }
2278
    let runs = runs_of(app, "andy", "demo").await;
2279
    assert_eq!(runs.len(), 1, "{runs:?}");
2280
    let mut taken = vec![];
2281
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2282
        taken.push(j);
2283
    }
2284
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2285
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2286
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2287
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2288
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2289
    let _ = queue;
2290
}
2291
2292
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2293
/// job is queued again and not offered to that runner again, the decline
2294
/// shows on the run's page and is kept for the runner's, and once three
2295
/// runners have declined it the job ends as unplaceable with their reasons.
2296
#[tokio::test(flavor = "multi_thread")]
2297
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2298
    let h = hub().await;
2299
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2300
    create(&h.app, "andy", "declines").await;
2301
    let url = format!("{}/andy/declines", h.base);
2302
    let work = tempfile::tempdir().unwrap();
2303
    let c = client(&url, work.path());
2304
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2305
    write(work.path(), "test.sh", "echo ok\n");
2306
    c.commit("Add a pipeline", &[]).unwrap();
2307
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2308
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2309
    let claim_as = |token: &'static str, name: &'static str| {
2310
        let app = h.app.clone();
2311
        async move {
2312
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2313
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2314
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2315
        }
2316
    };
2317
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2318
        let app = h.app.clone();
2319
        async move {
2320
            let body = serde_json::json!({ "reason": reason }).to_string();
2321
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2322
        }
2323
    };
2324
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2325
    // The other runners are known to the hub before they decline anything.
2326
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2327
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2328
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2329
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2330
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2331
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2332
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2333
    assert_ne!(next, job);
2334
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2335
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2336
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2337
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2338
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2339
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2340
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2341
    assert_eq!(j.status, "error");
2342
    assert_eq!(
2343
        j.error,
2344
        "unplaceable: declined by 3 runners: earth-1: the MicroVM tier needs /dev/kvm; plex-1: rootfs 36fc4e323804 is not on this runner; narvi: rootfs 36fc4e323804 is for x86_64; this runner is riscv64"
2345
    );
2346
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2347
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2348
    assert_eq!(declined.len(), 1);
2349
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2350
    assert_eq!(r.tier_list(), vec!["microvm"]);
2351
}
2352
2353
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2354
/// it is uploaded. The job's log says what it found; the Coverage tab,
2355
/// the file view, the badge and the run page show it.
2356
#[tokio::test(flavor = "multi_thread")]
2357
async fn a_coverage_artifact_becomes_a_coverage_report() {
2358
    let h = hub().await;
2359
    create(&h.app, "andy", "cov").await;
2360
    let url = format!("{}/andy/cov", h.base);
2361
    let work = tempfile::tempdir().unwrap();
2362
    let c = client(&url, work.path());
2363
    write(
2364
        work.path(),
2365
        ".flow/pipeline.kdl",
2366
        &format!(
2367
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"coverage\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"coverage\"\n    output {{\n        artifact \"coverage\" {{\n            path \"/src/lcov.info\"\n        }}\n    }}\n}}\n"
2368
        ),
2369
    );
2370
    write(work.path(), "src/lib.rs", "pub fn add(a: u32, b: u32) -> u32 {\n    a + b\n}\n\npub fn unused() {\n    todo!()\n}\n");
2371
    c.snapshot("test").unwrap();
2372
    c.commit("Code and coverage", &[]).unwrap();
2373
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2374
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
2375
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
2376
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2377
2378
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2379
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2380
    let lcov = "TN:\nSF:/src/src/lib.rs\nFN:1,add\nFN:5,unused\nFNDA:3,add\nFNDA:0,unused\nDA:1,3\nDA:2,3\nDA:5,0\nDA:6,0\nend_of_record\n\
2381
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2382
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2383
    assert_eq!(st, StatusCode::OK, "{text}");
2384
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2385
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2386
    assert!(
2387
        log.iter().any(|l| l == "coverage: 50.0% of lines (2 of 4) in 1 files (2 named files are not in this state and were left out)"),
2388
        "{log:?}"
2389
    );
2390
2391
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2392
    assert_eq!(st, StatusCode::OK);
2393
    assert!(
2394
        page.contains(">Reports</a>")
2395
            && page.contains("50.0%")
2396
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2397
        "{page}"
2398
    );
2399
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2400
    let report = crate_report(&h.app, run.id).await;
2401
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2402
    assert_eq!(st, StatusCode::OK, "{file}");
2403
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2404
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2405
    assert!(file.contains("3×"), "{file}");
2406
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2407
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2408
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2409
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2410
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
2411
    // The API (#113).
2412
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2413
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2414
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2415
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2416
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2417
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
2418
2419
    // The `coverage` check on the run's state: it reports, and with a
2420
    // minimum the repository sets, it fails below it.
2421
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2422
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2423
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2424
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2425
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2426
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2427
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2428
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2429
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
2430
}
2431
2432
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2433
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2434
}
2435
2436
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2437
/// breaks in the second and is fixed in the third.
2438
#[tokio::test(flavor = "multi_thread")]
2439
async fn junit_reports_make_a_tests_tab() {
2440
    let h = hub().await;
2441
    create(&h.app, "andy", "t").await;
2442
    let url = format!("{}/andy/t", h.base);
2443
    let work = tempfile::tempdir().unwrap();
2444
    let c = client(&url, work.path());
2445
    write(
2446
        work.path(),
2447
        ".flow/pipeline.kdl",
2448
        &format!(
2449
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"test\" {{\n    sandbox \"alpine\"\n    exec \"make\" \"test\"\n    output {{\n        artifact \"junit\" {{\n            path \"/src/junit.xml\"\n        }}\n    }}\n}}\n"
2450
        ),
2451
    );
2452
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
2453
    let case = |name: &str, ok: bool, secs: &str| {
2454
        if ok {
2455
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2456
        } else {
2457
            format!(
2458
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2459
            )
2460
        }
2461
    };
2462
    let runs = [
2463
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2464
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2465
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2466
    ];
2467
    for (i, cases) in runs.iter().enumerate() {
2468
        write(work.path(), "n.txt", &i.to_string());
2469
        c.snapshot("test").unwrap();
2470
        c.commit(&format!("Run {i}"), &[]).unwrap();
2471
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2472
        // The run is made after the push answers.
2473
        let mut a = None;
2474
        for _ in 0..100 {
2475
            a = claim(&h.app).await;
2476
            if a.is_some() {
2477
                break;
2478
            }
2479
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2480
        }
2481
        let a = a.expect("a job to claim");
2482
        let id = a["job_id"].as_i64().unwrap();
2483
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2484
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2485
        let failed = cases.iter().any(|c| c.contains("<failure"));
2486
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2487
        if !failed {
2488
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2489
        }
2490
        let code = failed as i32;
2491
        assert_eq!(
2492
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2493
            StatusCode::NO_CONTENT
2494
        );
2495
    }
2496
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2497
    assert_eq!(st, StatusCode::OK, "{page}");
2498
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2499
        std::fs::write(out, &page).unwrap();
2500
    }
2501
    assert!(page.contains(">Reports</a>"), "the tab");
2502
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2503
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2504
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2505
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2506
    // The slowest first.
2507
    let slow = page.find("Slowest tests").unwrap();
2508
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2509
    // The second run, picked: b newly failing, its failure listed.
2510
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2511
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2512
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2513
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2514
    assert!(page.contains("1 new tests"), "d is new");
2515
2516
    // The API (#114): the bookmark's reports newest first, and one with
2517
    // its failed cases.
2518
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2519
    assert_eq!(st, StatusCode::OK, "{list}");
2520
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2521
    assert_eq!(list.as_array().unwrap().len(), 3);
2522
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2523
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2524
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2525
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2526
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
2527
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
2528
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
2529
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
2530
2531
    // The `tests` check names what broke against main.
2532
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
2533
    let check = |state: String| {
2534
        let app = h.app.clone();
2535
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
2536
    };
2537
    let c = check(reports[1].state.clone()).await;
2538
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
2539
    let c = check(reports[0].state.clone()).await;
2540
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
2541
2542
    // One test's history: b passed, failed, passed.
2543
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2544
    assert!(
2545
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
2546
        "linked"
2547
    );
2548
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
2549
    assert_eq!(st, StatusCode::OK, "{hist}");
2550
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
2551
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
2552
}
2553
2554
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
2555
/// the run page (its panel open) and in its check.
2556
#[tokio::test(flavor = "multi_thread")]
2557
async fn a_job_no_runner_can_take_says_why() {
2558
    let h = hub().await;
2559
    create(&h.app, "andy", "demo").await;
2560
    let url = format!("{}/andy/demo", h.base);
2561
    let work = tempfile::tempdir().unwrap();
2562
    let c = client(&url, work.path());
2563
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2564
    write(work.path(), "test.sh", "echo ok\n");
2565
    c.commit("Add a pipeline", &[]).unwrap();
2566
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2567
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2568
2569
    // One runner, online, holding another image only.
2570
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
2571
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2572
    let other = "ab".repeat(32);
2573
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
2574
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2575
2576
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2577
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
2578
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
2579
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
2580
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
2581
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
2582
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
2583
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2584
    let check = checks.iter().find(|c| c.name == "flow/build").unwrap();
2585
    assert!(check.summary.contains("does not hold image"), "{check:?}");
2586
}
2587
2588
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
2589
    let req = Request::put(path)
2590
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
2591
        .header(header::CONTENT_TYPE, "application/octet-stream")
2592
        .body(Body::from(bytes))
2593
        .unwrap();
2594
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2595
    let st = res.status();
2596
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
2597
}
2598
2599
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
2600
/// manifest, checked against its hash; runners fetch it; and a job whose
2601
/// image only the hub holds is offered to a runner that fetches, not to one
2602
/// that does not.
2603
#[tokio::test(flavor = "multi_thread")]
2604
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
2605
    let h = hub().await;
2606
    // The site token acts as the first site administrator.
2607
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2608
    // An image: bytes, a run of zeros, more bytes.
2609
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
2610
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
2611
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
2612
    let mut chunks = std::collections::HashMap::new();
2613
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
2614
        chunks.insert(c.hash().to_string(), b.to_vec());
2615
        Ok(())
2616
    })
2617
    .unwrap();
2618
    let hash = m.hash.clone();
2619
2620
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
2621
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
2622
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
2623
    assert_eq!(st, StatusCode::OK, "{body}");
2624
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
2625
        .as_array()
2626
        .unwrap()
2627
        .iter()
2628
        .map(|v| v.as_str().unwrap().to_string())
2629
        .collect();
2630
    assert_eq!(missing.len(), m.needed().len());
2631
    let manifest = serde_json::to_string(&m).unwrap();
2632
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
2633
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
2634
    // A chunk is checked against its name; a runner token may not send.
2635
    let first = &missing[0];
2636
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
2637
    assert_ne!(
2638
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
2639
        StatusCode::NO_CONTENT
2640
    );
2641
    for c in &missing {
2642
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
2643
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
2644
    }
2645
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
2646
    assert!(body.contains("\"missing\":[]"), "{body}");
2647
    // A manifest naming another hash is refused; the right one is kept.
2648
    let mut wrong = m.clone();
2649
    wrong.hash = "ab".repeat(32);
2650
    let (st, _) =
2651
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
2652
            .await;
2653
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
2654
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
2655
    assert_eq!(st, StatusCode::CREATED, "{body}");
2656
2657
    // A runner fetches the manifest and the chunks, and the image comes back whole.
2658
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
2659
    assert_eq!(st, StatusCode::OK, "{body}");
2660
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
2661
    assert_eq!(got, m);
2662
    let dir = tempfile::tempdir().unwrap();
2663
    let out = dir.path().join("img.ext4");
2664
    let mut fetched = Vec::new();
2665
    for c in got.needed() {
2666
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
2667
            .header(header::AUTHORIZATION, "Bearer runner-secret")
2668
            .body(Body::empty())
2669
            .unwrap();
2670
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
2671
        assert_eq!(res.status(), StatusCode::OK);
2672
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
2673
        fetched.push((c.to_string(), bytes));
2674
    }
2675
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
2676
    assert_eq!(std::fs::read(&out).unwrap(), image);
2677
    assert_eq!(
2678
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
2679
        StatusCode::NOT_FOUND
2680
    );
2681
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
2682
2683
    // A job on that image: a runner holding no images and not fetching
2684
    // is offered nothing; one that fetches is offered it.
2685
    create(&h.app, "andy", "demo").await;
2686
    let url = format!("{}/andy/demo", h.base);
2687
    let work = tempfile::tempdir().unwrap();
2688
    let c = client(&url, work.path());
2689
    write(
2690
        work.path(),
2691
        ".flow/pipeline.kdl",
2692
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
2693
    );
2694
    c.commit("Build on the image", &[]).unwrap();
2695
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2696
    runs_of(&h.app, "andy", "demo").await;
2697
    // #137: the run's images are held (by the hub), so no images check.
2698
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2699
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
2700
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
2701
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
2702
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
2703
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
2704
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
2705
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2706
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2707
    assert!(body.contains("does not hold image"), "{body}");
2708
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
2709
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
2710
    // oxygenhub#135: once claimed, the old waiting reason is gone.
2711
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2712
    assert!(!body.contains("waiting"), "a running job keeps no waiting reason: {body}");
2713
}
2714
2715
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
2716
/// bookmark's state, kept as uploaded by its account, shown so, and sets
2717
/// no check.
2718
#[tokio::test(flavor = "multi_thread")]
2719
async fn coverage_uploaded_from_a_workstation_says_so() {
2720
    let h = hub().await;
2721
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2722
    create(&h.app, "andy", "vk").await;
2723
    let url = format!("{}/andy/vk", h.base);
2724
    let work = tempfile::tempdir().unwrap();
2725
    let c = client(&url, work.path());
2726
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
2727
    c.commit("Game", &[]).unwrap();
2728
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2729
2730
    let lcov = "SF:src/game.c\nDA:1,3\nDA:2,1\nDA:3,0\nDA:4,5\nend_of_record\nSF:reference/rom.asm\nDA:1,1\nend_of_record\n";
2731
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
2732
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
2733
    assert_eq!(st, StatusCode::CREATED, "{out}");
2734
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2735
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
2736
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
2737
    assert_eq!(v["bookmark"], "main");
2738
2739
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
2740
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
2741
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
2742
    assert!(page.contains("uploaded by andy"), "and the Reports card");
2743
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
2744
    let state = v["state"].as_str().unwrap();
2745
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
2746
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
2747
2748
    // Readers cannot upload; bad reports and bookmarks are refused.
2749
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
2750
    assert_ne!(st, StatusCode::CREATED);
2751
    let (st, _) = call(
2752
        &h.app,
2753
        "POST",
2754
        "/api/v1/repos/andy/vk/coverage",
2755
        Some("site"),
2756
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
2757
    )
2758
    .await;
2759
    assert_eq!(st, StatusCode::BAD_REQUEST);
2760
}
2761
2762
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
2763
#[tokio::test(flavor = "multi_thread")]
2764
async fn a_runners_facts_are_kept_from_its_claim() {
2765
    let h = hub().await;
2766
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2767
    let body = r#"{"runner":"test-1","runtimes":["microvm"],"facts":{"free_disk_mib":42000,"load_x100":112,"speed":100,"speed_class":3,"kernel":"7.0.0"}}"#;
2768
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
2769
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
2770
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
2771
    assert_eq!(st, StatusCode::OK, "{out}");
2772
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2773
    let r = &v[0];
2774
    assert_eq!(
2775
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
2776
        (Some(100), Some(3), Some(42000), Some(112))
2777
    );
2778
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
2779
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
2780
}
2781
2782
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
2783
/// without that much free disk is not offered it, and the reason says so.
2784
#[tokio::test(flavor = "multi_thread")]
2785
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
2786
    let h = hub().await;
2787
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2788
    create(&h.app, "andy", "demo").await;
2789
    let url = format!("{}/andy/demo", h.base);
2790
    let work = tempfile::tempdir().unwrap();
2791
    let c = client(&url, work.path());
2792
    write(
2793
        work.path(),
2794
        ".flow/pipeline.kdl",
2795
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2796
    );
2797
    c.commit("Build", &[]).unwrap();
2798
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2799
    runs_of(&h.app, "andy", "demo").await;
2800
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
2801
2802
    // The first run has nothing to learn from: any runner takes it.
2803
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
2804
    assert_eq!(st, StatusCode::OK, "{body}");
2805
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2806
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
2807
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
2808
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
2809
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
2810
2811
    // The next run needs 8000 MiB and a quarter more.
2812
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2813
    assert_eq!(st, StatusCode::CREATED);
2814
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2815
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
2816
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
2817
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
2818
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
2819
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
2820
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2821
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
2822
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
2823
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
2824
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
2825
}
2826
2827
/// oxygenflow#42: a job another free runner would do better (it holds the
2828
/// image) is held from a runner that would fetch it, the better runner
2829
/// takes it, and the job says why it ran there.
2830
#[tokio::test(flavor = "multi_thread")]
2831
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
2832
    let h = hub().await;
2833
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2834
    // A second runner, with a token of its own.
2835
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2836
    let ask = |images: &str| {
2837
        format!(
2838
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2839
        )
2840
    };
2841
    let holder = ask(&format!("\"{ROOTFS}\""));
2842
    // earth-9 holds the image and is polling; nothing is queued yet.
2843
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2844
    assert_eq!(st, StatusCode::NO_CONTENT);
2845
    // The hub holds the image too, so test-1 could fetch it.
2846
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES (?, 1, 'x86_64', 1, 'andy', 0)")
2847
        .bind(ROOTFS)
2848
        .execute(&h.app.db)
2849
        .await
2850
        .unwrap();
2851
2852
    create(&h.app, "andy", "demo").await;
2853
    let url = format!("{}/andy/demo", h.base);
2854
    let work = tempfile::tempdir().unwrap();
2855
    let c = client(&url, work.path());
2856
    write(
2857
        work.path(),
2858
        ".flow/pipeline.kdl",
2859
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2860
    );
2861
    c.commit("Build", &[]).unwrap();
2862
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2863
    runs_of(&h.app, "andy", "demo").await;
2864
2865
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2866
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
2867
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2868
    assert_eq!(st, StatusCode::OK, "{body}");
2869
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2870
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2871
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
2872
    assert!(placed.contains("held for a better runner"), "{placed}");
2873
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2874
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
2875
}
2876
2877
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
2878
/// report on a bookmark other than the default; the default keeps all,
2879
/// and an expired report keeps its metrics.
2880
#[tokio::test(flavor = "multi_thread")]
2881
async fn report_files_expire_under_retention() {
2882
    let h = hub().await;
2883
    create(&h.app, "andy", "demo").await;
2884
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2885
    let add = |bookmark: &'static str, at: i64| {
2886
        let db = h.app.db.clone();
2887
        async move {
2888
            let id: i64 = sqlx::query_scalar(
2889
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
2890
                 VALUES (?, 'perf', 'performance', 'Perf', '', '{}', 'perf', ?, 's', 1, 1, ?) RETURNING id",
2891
            )
2892
            .bind(repo.id)
2893
            .bind(bookmark)
2894
            .bind(at)
2895
            .fetch_one(&db)
2896
            .await
2897
            .unwrap();
2898
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES (?, 'report.toml', ?, 1)")
2899
                .bind(id)
2900
                .bind(format!("{:064x}", id))
2901
                .execute(&db)
2902
                .await
2903
                .unwrap();
2904
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES (?, 'ms', 1, '', '')")
2905
                .bind(id)
2906
                .execute(&db)
2907
                .await
2908
                .unwrap();
2909
            id
2910
        }
2911
    };
2912
    let main_old = add("main", 1).await;
2913
    add("main", 2).await;
2914
    let mut feature = Vec::new();
2915
    for at in 0..52 {
2916
        feature.push(add("feature", 10 + at).await);
2917
    }
2918
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
2919
    let files = |id: i64| {
2920
        let db = h.app.db.clone();
2921
        async move {
2922
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = ?").bind(id).fetch_one(&db).await.unwrap()
2923
        }
2924
    };
2925
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
2926
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
2927
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
2928
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
2929
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
2930
    assert!(page.contains("files have expired"), "the page says so");
2931
}
2932
2933
/// #137: a run pinning an image neither the hub nor any runner holds sets a
2934
/// failing `pipeline/images` check saying how to send it; once it is held,
2935
/// a run of the same state turns the check to passed.
2936
#[tokio::test(flavor = "multi_thread")]
2937
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
2938
    let h = hub().await;
2939
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2940
    // The one runner reports holding no images.
2941
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
2942
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
2943
    assert_eq!(st, StatusCode::NO_CONTENT);
2944
    create(&h.app, "andy", "demo").await;
2945
    let url = format!("{}/andy/demo", h.base);
2946
    let work = tempfile::tempdir().unwrap();
2947
    let c = client(&url, work.path());
2948
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2949
    write(work.path(), "test.sh", "echo ok\n");
2950
    c.commit("Add a pipeline", &[]).unwrap();
2951
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2952
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2953
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
2954
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
2955
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
2956
    // Once a runner holds it, a run of the state passes the check.
2957
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
2958
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
2959
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2960
    assert_eq!(st, StatusCode::CREATED);
2961
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2962
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
2963
    assert_eq!(check.status, "passed", "{check:?}");
2964
}