OXYGENHUB
# 9aee52d392a6 oxygenhub / crates / hub / tests / flow.rs
246.3 KiB · Rust · last changed A new hub gives administrator only to whoever brings its setup code 20 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
    // The first account's setup code (oxygenhub#245).
45
    config.registration.setup_code = "test-setup".into();
46
    config.auth.push_tokens = vec!["site".into()];
47
    config.flow.runner_tokens = vec!["runner-secret".into(), "runner-two".into(), "runner-three".into()];
48
    config.flow.repos = vec!["andy/*".into()];
49
    config.registration.mode = "open".into();
50
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
51
    let port = listener.local_addr().unwrap().port();
52
    config.server.base_url = format!("http://127.0.0.1:{port}");
53
    let app = oxygenhub::build(config).await.unwrap();
54
    let router = oxygenhub::router(app.clone());
55
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
56
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
57
}
58
59
async fn call(app: &Shared, method: &str, path: &str, bearer: Option<&str>, json: Option<String>) -> (StatusCode, String) {
60
    let mut req = Request::builder().method(method).uri(path);
61
    if let Some(b) = bearer {
62
        req = req.header(header::AUTHORIZATION, format!("Bearer {b}"));
63
    }
64
    let body = match json {
65
        Some(j) => {
66
            req = req.header(header::CONTENT_TYPE, "application/json");
67
            Body::from(j)
68
        }
69
        None => Body::empty(),
70
    };
71
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
72
    let status = res.status();
73
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
74
    (status, String::from_utf8_lossy(&bytes).into_owned())
75
}
76
77
/// A GET's status, `Location` and `Content-Type`.
78
async fn head(app: &Shared, path: &str) -> (StatusCode, String, String) {
79
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
80
    let h = |k: header::HeaderName| res.headers().get(k).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
81
    (res.status(), h(header::LOCATION), h(header::CONTENT_TYPE))
82
}
83
84
async fn claim(app: &Shared) -> Option<serde_json::Value> {
85
    let (st, body) =
86
        call(app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["microvm"]}"#.into())).await;
87
    match st {
88
        StatusCode::NO_CONTENT => None,
89
        StatusCode::OK => Some(serde_json::from_str(&body).unwrap()),
90
        other => panic!("claim: {other} {body}"),
91
    }
92
}
93
94
fn receipt(job: &str, pipeline_hash: &str, exit: u32) -> serde_json::Value {
95
    serde_json::json!({
96
        "job_name": job, "pipeline_hash": pipeline_hash, "scope_tree_hash": "11".repeat(32),
97
        "inputs": [], "environment": "22".repeat(32), "outputs": [], "exit_code": exit, "duration_ms": 640
98
    })
99
}
100
101
async fn finish(app: &Shared, id: i64, body: serde_json::Value) -> StatusCode {
102
    call(app, "POST", &format!("/api/v1/flow/jobs/{id}/finish"), Some("runner-secret"), Some(body.to_string())).await.0
103
}
104
105
async fn create(app: &Shared, owner: &str, name: &str) {
106
    app.repos.create(&RepoName::parse(&format!("{owner}/{name}")).unwrap(), None).unwrap();
107
    db::repos::create(&app.db, owner, name, "", hub_api::Visibility::Public).await.unwrap();
108
}
109
110
fn client(url: &str, work: &Path) -> Repo {
111
    let mut c = Repo::init(work).unwrap();
112
    c.config.set("remote.origin.url", url).unwrap();
113
    c.config.set("remote.origin.token", "site").unwrap();
114
    c.save_config().unwrap();
115
    c
116
}
117
118
fn pipeline(extra: &str) -> String {
119
    format!(
120
        "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}"
121
    )
122
}
123
124
async fn runs_of(app: &Shared, owner: &str, name: &str) -> Vec<db::flow::Run> {
125
    let row = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
126
    for _ in 0..100 {
127
        let r = db::flow::runs(&app.db, row.id, 10, None).await.unwrap();
128
        if !r.is_empty() {
129
            return r;
130
        }
131
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
132
    }
133
    vec![]
134
}
135
136
/// The checks on a state once there are `n` of them (they follow the run).
137
async fn checks_when(app: &Shared, repo_id: i64, state: &str, n: usize) -> Vec<db::hooks::Check> {
138
    for _ in 0..100 {
139
        let c = db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap();
140
        if c.len() >= n {
141
            return c;
142
        }
143
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
144
    }
145
    db::hooks::checks_for_state(&app.db, repo_id, state).await.unwrap()
146
}
147
148
#[tokio::test(flavor = "multi_thread")]
149
async fn a_push_runs_the_pipeline_through_a_runner() {
150
    let h = hub().await;
151
    create(&h.app, "andy", "demo").await;
152
    create(&h.app, "andy", "secret").await;
153
    create(&h.app, "other", "plain").await;
154
    let url = format!("{}/andy/demo", h.base);
155
    let work = tempfile::tempdir().unwrap();
156
    let mut c = client(&url, work.path());
157
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
158
    write(work.path(), "test.sh", "echo ok\n");
159
    c.snapshot("test").unwrap();
160
    c.commit("Add a pipeline", &[]).unwrap();
161
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
162
163
    // The push started a run with three queued jobs, and checks for them.
164
    let runs = runs_of(&h.app, "andy", "demo").await;
165
    assert_eq!(runs.len(), 1);
166
    let run = &runs[0];
167
    assert_eq!((run.bookmark.as_str(), run.status.as_str(), run.actor.as_str()), ("main", "queued", "site token"));
168
    assert_eq!(run.pipeline_hash.len(), 64);
169
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
170
    assert_eq!(jobs.iter().map(|j| (j.name.as_str(), j.depth)).collect::<Vec<_>>(), [("build", 0), ("lint", 0), ("test", 1)]);
171
    // The checks are reported just after the run is recorded.
172
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
173
    assert_eq!(
174
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
175
        [("flow/build", "queued"), ("flow/lint", "queued"), ("flow/test", "queued")]
176
    );
177
178
    // Runners need a runner token.
179
    assert_eq!(
180
        call(&h.app, "POST", "/api/v1/flow/claim", Some("site"), Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
181
        StatusCode::UNAUTHORIZED
182
    );
183
    assert_eq!(
184
        call(&h.app, "POST", "/api/v1/flow/claim", None, Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
185
        StatusCode::UNAUTHORIZED
186
    );
187
    // A runner without the tier gets nothing.
188
    let (st, _) =
189
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"x","runtimes":["wasm"]}"#.into())).await;
190
    assert_eq!(st, StatusCode::NO_CONTENT);
191
192
    // Claims come in dependency order; `test` waits for `build`.
193
    let a = claim(&h.app).await.unwrap();
194
    let b = claim(&h.app).await.unwrap();
195
    assert_eq!((a["job"]["name"].as_str(), b["job"]["name"].as_str()), (Some("build"), Some("lint")));
196
    assert!(claim(&h.app).await.is_none(), "test waits for build");
197
    assert_eq!(a["repo"], "andy/demo");
198
    assert_eq!(a["clone_url"], url.as_str());
199
    assert_eq!(a["sandbox"]["rootfs"], ROOTFS);
200
    assert_eq!(a["job"]["exec"], serde_json::json!(["make"]));
201
    assert_eq!(a["timeout_s"], 3600);
202
    // The job is told what it builds (FLOW_STATE, FLOW_BOOKMARK, FLOW_RUN).
203
    assert_eq!(
204
        (a["state"].as_str(), a["bookmark"].as_str(), a["run_number"].as_i64()),
205
        (Some(run.state.as_str()), Some("main"), Some(run.number))
206
    );
207
    let heads: Vec<String> = a["heads"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
208
    assert_eq!(heads.join("+"), run.heads);
209
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
210
    assert_eq!(checks.iter().find(|c| c.name == "flow/build").unwrap().status, "running");
211
212
    // The job token reads this repository over the wire, and nothing else.
213
    let token = a["token"].as_str().unwrap().to_string();
214
    assert!(token.starts_with("flowjob_"));
215
    let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
216
    open_remote(&url, &opts).unwrap().refs().unwrap();
217
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
218
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ..Default::default() };
219
    assert!(open_remote(&url, &bad).unwrap().refs().is_err(), "an unknown job token");
220
    // … and cannot push.
221
    c.config.set("remote.origin.token", &token).unwrap();
222
    c.save_config().unwrap();
223
    write(work.path(), "more.txt", "x\n");
224
    c.snapshot("test").unwrap();
225
    c.commit("More", &[]).unwrap();
226
    let pushed = c.push("origin", false);
227
    assert!(pushed.is_err() || pushed.unwrap().iter().all(|r| !r.ok), "a job token cannot push");
228
    c.config.set("remote.origin.token", "site").unwrap();
229
    c.save_config().unwrap();
230
231
    // Logs, then results with receipts.
232
    let a_id = a["job_id"].as_i64().unwrap();
233
    let b_id = b["job_id"].as_i64().unwrap();
234
    let log = serde_json::json!({ "records": [
235
        { "t": 5, "stream": "flow", "text": "booting" },
236
        { "t": 120, "stream": "out", "text": "cc -o demo demo.c" },
237
        { "t": 130, "stream": "weird", "text": "x".repeat(20_000) },
238
    ]});
239
    assert_eq!(
240
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{a_id}/log"), Some("runner-secret"), Some(log.to_string())).await.0,
241
        StatusCode::NO_CONTENT
242
    );
243
    let lines = db::flow::log(&h.app.db, a_id, 0, 100).await.unwrap();
244
    assert_eq!(lines.len(), 3);
245
    assert_eq!((lines[2].stream.as_str(), lines[2].text.len()), ("console", 16 * 1024), "streams are known ones, text is capped");
246
    let ph = a["pipeline_hash"].as_str().unwrap();
247
    assert_eq!(
248
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("lint", ph, 0) })).await,
249
        StatusCode::BAD_REQUEST,
250
        "a receipt for another job"
251
    );
252
    assert_eq!(
253
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("build", ph, 0) })).await,
254
        StatusCode::NO_CONTENT
255
    );
256
    assert_eq!(finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::CONFLICT, "only once");
257
    assert!(open_remote(&url, &opts).unwrap().refs().is_err(), "the token ends with its job");
258
    assert_eq!(
259
        finish(&h.app, b_id, serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": receipt("lint", ph, 0) })).await,
260
        StatusCode::NO_CONTENT
261
    );
262
    let t = claim(&h.app).await.unwrap();
263
    assert_eq!(t["job"]["name"], "test");
264
    let t_id = t["job_id"].as_i64().unwrap();
265
    assert_eq!(
266
        finish(&h.app, t_id, serde_json::json!({ "exit_code": 3, "duration_ms": 500, "receipt": receipt("test", ph, 3) })).await,
267
        StatusCode::NO_CONTENT
268
    );
269
270
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
271
    assert_eq!(run.status, "failed");
272
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
273
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
274
    assert_eq!((build.status.as_str(), build.exit_code, build.receipt_hash.len()), ("passed", Some(0), 64));
275
    assert_eq!(jobs.iter().find(|j| j.name == "test").unwrap().status, "failed");
276
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
277
    assert_eq!(
278
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
279
        [("flow/build", "passed"), ("flow/lint", "passed"), ("flow/test", "failed")]
280
    );
281
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.number)));
282
283
    // Pages: the list, the run with its graph and logs, and the live view.
284
    let (st, list) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
285
    assert_eq!(st, StatusCode::OK);
286
    assert!(list.contains(&format!("/andy/demo/flow/{}", run.number)) && list.contains("st-failed"), "{list}");
287
    let (st, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
288
    assert_eq!(st, StatusCode::OK);
289
    assert!(page.contains("<svg class=\"flow-graph\""), "graph");
290
    assert_eq!(page.matches("data-job-node=").count(), 3);
291
    assert_eq!(page.matches("<path class=\"edge").count(), 1, "one dependency edge");
292
    assert!(page.contains("cc -o demo demo.c"), "log shown");
293
    assert!(!page.contains("data-flow-live"), "a finished run does not poll");
294
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.number), None, None).await;
295
    assert_eq!(st, StatusCode::OK);
296
    let live: serde_json::Value = serde_json::from_str(&live).unwrap();
297
    assert_eq!(live["status"], "failed");
298
    let build_live = live["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
299
    assert_eq!(build_live["lines"].as_array().unwrap().len(), 2, "lines after seq 1");
300
    assert_eq!(call(&h.app, "GET", "/andy/demo/flow/999", None, None).await.0, StatusCode::NOT_FOUND);
301
302
    // A failed dependency skips what follows; an unrun job is an error.
303
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
304
    write(work.path(), "test.sh", "echo changed\n");
305
    c.snapshot("test").unwrap();
306
    c.commit("Change the test", &[]).unwrap();
307
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
308
    let mut second = None;
309
    for _ in 0..100 {
310
        let r = runs_of(&h.app, "andy", "demo").await;
311
        if r.len() == 2 {
312
            second = Some(r[0].clone());
313
            break;
314
        }
315
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
316
    }
317
    let second = second.expect("a second run");
318
    let x = claim(&h.app).await.unwrap();
319
    let y = claim(&h.app).await.unwrap();
320
    let (build_id, lint_id) = if x["job"]["name"] == "build" {
321
        (x["job_id"].as_i64().unwrap(), y["job_id"].as_i64().unwrap())
322
    } else {
323
        (y["job_id"].as_i64().unwrap(), x["job_id"].as_i64().unwrap())
324
    };
325
    assert_eq!(
326
        finish(&h.app, build_id, serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "rootfs is not on this runner" }))
327
            .await,
328
        StatusCode::NO_CONTENT
329
    );
330
    assert_eq!(finish(&h.app, lint_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10 })).await, StatusCode::NO_CONTENT);
331
    assert!(claim(&h.app).await.is_none(), "test was skipped");
332
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
333
    assert_eq!(
334
        jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect::<Vec<_>>(),
335
        [("build", "error"), ("lint", "passed"), ("test", "skipped")]
336
    );
337
    assert_eq!(db::flow::run_by_id(&h.app.db, second.id).await.unwrap().unwrap().status, "failed");
338
339
    // An invalid pipeline is a run in error with the line.
340
    write(work.path(), ".flow/pipeline.kdl", &pipeline("job \"broken\" {\n    sandbox \"missing\"\n    exec \"x\"\n}\n"));
341
    c.snapshot("test").unwrap();
342
    c.commit("Break the pipeline", &[]).unwrap();
343
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
344
    let mut third = None;
345
    for _ in 0..100 {
346
        let r = runs_of(&h.app, "andy", "demo").await;
347
        if r.len() == 3 {
348
            third = Some(r[0].clone());
349
            break;
350
        }
351
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
352
    }
353
    let third = third.expect("a third run");
354
    assert_eq!(third.status, "error");
355
    assert!(third.error.contains("line 18") && third.error.contains("\"missing\""), "{}", third.error);
356
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.number), None, None).await;
357
    assert!(page.contains("The pipeline is not valid"));
358
359
    // State stamps (hub spec §13.2) and images in READMEs.
360
    write(work.path(), "README.md", "# Demo\n\n[![flow](.flow/stamp)](.flow/run)\n\n![logo](img/logo.png)\n");
361
    std::fs::create_dir_all(work.path().join("img")).unwrap();
362
    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")
363
        .unwrap();
364
    c.snapshot("test").unwrap();
365
    c.commit("A README with a stamp", &[]).unwrap();
366
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
367
    let mut fourth = None;
368
    for _ in 0..100 {
369
        let r = runs_of(&h.app, "andy", "demo").await;
370
        if r.len() == 4 {
371
            fourth = Some(r[0].clone());
372
            break;
373
        }
374
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
375
    }
376
    let fourth = fourth.expect("a fourth run");
377
    let (_, overview) = call(&h.app, "GET", "/andy/demo", None, None).await;
378
    assert!(overview.contains("src=\"/andy/demo/raw/main/.flow/stamp\""), "{overview}");
379
    assert!(overview.contains("href=\"/andy/demo/file/main/.flow/run\""));
380
    assert!(overview.contains("src=\"/andy/demo/raw/main/img/logo.png\""), "images use the raw route");
381
    let (st, _, ct) = head(&h.app, "/andy/demo/raw/main/img/logo.png").await;
382
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/png"));
383
    let (st, loc, _) = head(&h.app, "/andy/demo/raw/main/.flow/stamp").await;
384
    assert!(st.is_redirection() && loc == "/andy/demo/flow/stamp/main", "{st} {loc}");
385
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/stamp/main").await;
386
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/stamp/{}", fourth.heads), "a bookmark's stamp names its state: {loc}");
387
    let (st, _, ct) = head(&h.app, &loc).await;
388
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/svg+xml; charset=utf-8"));
389
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
390
    assert!(svg.starts_with("<svg") && svg.contains("error ·") && svg.contains(&fourth.heads[..12]), "{svg}");
391
    let (_, svg1) = call(&h.app, "GET", &format!("/andy/demo/flow/stamp/{}", run.heads), None, None).await;
392
    assert!(svg1.contains("failed ·") && svg1.contains(&format!("run #{} failed", run.id)), "an older state keeps its own result: {svg1}");
393
    assert!(svg1.contains(&build.receipt_hash), "receipt hashes in the metadata");
394
    assert_eq!(svg1.matches("text-anchor=\"middle\"").count(), 3, "one glyph per job");
395
    let (st, loc, _) = head(&h.app, "/andy/demo/file/main/.flow/run").await;
396
    assert!(st.is_redirection() && loc == "/andy/demo/flow/at/main", "{loc}");
397
    let (st, loc, _) = head(&h.app, "/andy/demo/flow/at/main").await;
398
    assert!(st.is_redirection() && loc == format!("/andy/demo/flow/{}", fourth.id), "{loc}");
399
400
    // A repository outside [flow] repos starts nothing.
401
    let work2 = tempfile::tempdir().unwrap();
402
    let c2 = client(&format!("{}/other/plain", h.base), work2.path());
403
    write(work2.path(), ".flow/pipeline.kdl", &pipeline(""));
404
    c2.snapshot("test").unwrap();
405
    c2.commit("Pipeline", &[]).unwrap();
406
    assert!(c2.push("origin", false).unwrap().iter().all(|r| r.ok));
407
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
408
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
409
    assert!(db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap().is_empty());
410
    let (_, page) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
411
    assert!(page.contains("not enabled for this repository"));
412
    let (_, loc, _) = head(&h.app, "/other/plain/flow/stamp/main").await;
413
    let (_, svg) = call(&h.app, "GET", &loc, None, None).await;
414
    assert!(svg.contains("no run ·"), "{svg}");
415
    let (_, loc, _) = head(&h.app, "/other/plain/flow/at/main").await;
416
    assert_eq!(loc, "/other/plain/flow");
417
}
418
419
#[tokio::test(flavor = "multi_thread")]
420
async fn claims_carry_pinned_subrepos_and_the_job_token_reads_only_those() {
421
    let h = hub().await;
422
    for n in ["base", "lib", "vault", "other", "app"] {
423
        create(&h.app, "andy", n).await;
424
    }
425
    let push = |name: &str, file: &str| {
426
        let work = tempfile::tempdir().unwrap();
427
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
428
        write(work.path(), file, "x\n");
429
        c.snapshot("t").unwrap();
430
        c.commit("first", &[]).unwrap();
431
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
432
        let heads = c.bookmark_heads().unwrap();
433
        (work, heads)
434
    };
435
    let (_b, base_heads) = push("base", "base.rs");
436
    // lib pins base in turn: a subrepo of a subrepo.
437
    let lib_work = tempfile::tempdir().unwrap();
438
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
439
    lib.submodule_add(&format!("{}/andy/base", h.base), "deps/base", Some("main")).unwrap();
440
    write(lib_work.path(), "lib.rs", "x\n");
441
    lib.snapshot("t").unwrap();
442
    lib.commit("lib on base", &[]).unwrap();
443
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
444
    let lib_heads = lib.bookmark_heads().unwrap();
445
    let (_v, _) = push("vault", "secret.rs");
446
    let (_o, _) = push("other", "o.rs");
447
448
    // The app pins lib and vault as subrepos and pushes as the site token.
449
    let work = tempfile::tempdir().unwrap();
450
    let app = client(&format!("{}/andy/app", h.base), work.path());
451
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
452
    // Vault is private: a checkout with no token for this hub cannot add
453
    // it, but the app's remote on the same hub lends its token (oxygen#32).
454
    // The subrepo keeps no copy: its own fetches find the parent's (oxygen#47).
455
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
456
    let bare_work = tempfile::tempdir().unwrap();
457
    let mut bare = Repo::init(bare_work.path()).unwrap();
458
    bare.config.set("remote.origin.url", &format!("{}/andy/bare", h.base)).unwrap();
459
    bare.save_config().unwrap();
460
    assert!(bare.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).is_err(), "not without a token");
461
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
462
    let nested = Repo::open(&work.path().join("deps/vault")).unwrap();
463
    assert!(nested.config.remote_tokens.is_empty(), "no token is copied into a subrepo");
464
    nested.fetch("origin").unwrap();
465
    // The pusher below is the site token, which has no account: it cannot read vault.
466
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
467
    write(work.path(), "Makefile", "all:\n");
468
    app.snapshot("t").unwrap();
469
    app.commit("app with deps", &[]).unwrap();
470
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
471
    assert!(!runs_of(&h.app, "andy", "app").await.is_empty());
472
473
    let job = claim(&h.app).await.unwrap();
474
    let subs = job["subrepos"].as_array().cloned().unwrap_or_default();
475
    assert_eq!(subs.len(), 2, "lib and what lib pins; vault is private and the pusher has no account: {subs:?}");
476
    assert_eq!(subs[1]["path"], "deps/lib/deps/base", "nested under its parent, after it");
477
    assert_eq!(subs[1]["heads"], serde_json::json!(base_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
478
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
479
    assert_eq!(subs[0]["path"], "deps/lib");
480
    assert_eq!(subs[0]["repo"], "andy/lib");
481
    assert_eq!(subs[0]["heads"], serde_json::json!(lib_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
482
    assert!(subs[0]["clone_url"].as_str().unwrap().ends_with("/andy/lib"));
483
    // The job's log says vault was left out, and why (oxygenhub#56).
484
    let job_id = job["job_id"].as_i64().unwrap();
485
    let lines = db::flow::log(&h.app.db, job_id, 0, 100).await.unwrap();
486
    assert!(
487
        lines.iter().any(|l| l.stream == "flow" && l.text.contains("subrepo deps/vault (andy/vault) is left out")),
488
        "{:?}",
489
        lines.iter().map(|l| &l.text).collect::<Vec<_>>()
490
    );
491
492
    // The job token reads its repository and the pinned lib, nothing else.
493
    let token = job["token"].as_str().unwrap().to_string();
494
    let read = |name: &str| {
495
        let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
496
        open_remote(&format!("{}/andy/{name}", h.base), &opts).and_then(|r| r.refs()).is_ok()
497
    };
498
    assert!(read("app") && read("lib") && read("base"));
499
    assert!(!read("vault"), "not pinned for this pusher");
500
    assert!(!read("other"), "public, but not the job's to read");
501
}
502
503
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
504
async fn concurrent_log_appends_never_fail_on_a_locked_database() {
505
    let h = hub().await;
506
    create(&h.app, "andy", "demo").await;
507
    let work = tempfile::tempdir().unwrap();
508
    let c = client(&format!("{}/andy/demo", h.base), work.path());
509
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
510
    write(work.path(), "Makefile", "all:\n");
511
    c.snapshot("t").unwrap();
512
    c.commit("pipeline", &[]).unwrap();
513
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
514
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
515
    let job = db::flow::jobs(&h.app.db, run.id).await.unwrap().remove(0);
516
    // Many writers at once, each reading the count and then inserting: a
517
    // deferred transaction would fail with "database is locked".
518
    let mut tasks = Vec::new();
519
    for w in 0..16 {
520
        let pool = h.app.db.clone();
521
        tasks.push(tokio::spawn(async move {
522
            let records: Vec<flow_core::api::Record> =
523
                (0..20).map(|i| flow_core::api::Record { t: i, stream: "out".into(), text: format!("writer {w} line {i}") }).collect();
524
            db::flow::append_log(&pool, job.id, &records, 100_000).await
525
        }));
526
    }
527
    for t in tasks {
528
        assert_eq!(t.await.unwrap().unwrap(), 20, "every append succeeds");
529
    }
530
    let lines = db::flow::log(&h.app.db, job.id, 0, 1_000).await.unwrap();
531
    assert_eq!(lines.len(), 320);
532
    let seqs: std::collections::BTreeSet<i64> = lines.iter().map(|l| l.seq).collect();
533
    assert_eq!(seqs.len(), 320, "sequence numbers are unique");
534
}
535
536
/// A repository's own Flow setting overrides hub.toml either way.
537
#[tokio::test(flavor = "multi_thread")]
538
async fn a_repository_setting_turns_flow_on_or_off() {
539
    let h = hub().await;
540
    create(&h.app, "other", "plain").await;
541
    create(&h.app, "andy", "quiet").await;
542
    // A run elsewhere first, so hub-wide ids and per-repository numbers differ.
543
    create(&h.app, "andy", "first").await;
544
    {
545
        let work = tempfile::tempdir().unwrap();
546
        let c = client(&format!("{}/andy/first", h.base), work.path());
547
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
548
        write(work.path(), "test.sh", "echo ok\n");
549
        c.commit("Add a pipeline", &[]).unwrap();
550
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
551
        assert_eq!(runs_of(&h.app, "andy", "first").await.len(), 1);
552
    }
553
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
554
    db::repos::set_flow(&h.app.db, row.id, "on").await.unwrap();
555
    let quiet = db::repos::get(&h.app.db, "andy", "quiet").await.unwrap().unwrap();
556
    db::repos::set_flow(&h.app.db, quiet.id, "off").await.unwrap();
557
    for (owner, name) in [("other", "plain"), ("andy", "quiet")] {
558
        let work = tempfile::tempdir().unwrap();
559
        let c = client(&format!("{}/{owner}/{name}", h.base), work.path());
560
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
561
        write(work.path(), "test.sh", "echo ok\n");
562
        c.commit("Add a pipeline", &[]).unwrap();
563
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
564
    }
565
    let plain = runs_of(&h.app, "other", "plain").await;
566
    assert_eq!(plain.len(), 1, "turned on");
567
    // With andy/first's jobs ahead, plain's run says where it stands.
568
    let a = claim(&h.app).await.unwrap();
569
    assert_eq!(a["repo"], "andy/first");
570
    let (_, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
571
    assert!(page.contains("Waiting for a runner: 3rd in line") && page.contains("Running now: andy/first #1"), "{page}");
572
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/other/plain/flow/runs/1", None, None).await;
573
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["queue_position"], 3);
574
    let (_, list) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
575
    assert!(list.contains("queued, 3rd in line"), "{list}");
576
    // Runs are numbered per repository: this is plain's first, whatever
577
    // other repositories ran before.
578
    assert_eq!(plain[0].number, 1);
579
    let checks = checks_when(&h.app, row.id, &plain[0].state, 3).await;
580
    assert!(checks.iter().all(|c| c.url.ends_with("/other/plain/flow/1")), "{checks:?}");
581
    let (st, page) = call(&h.app, "GET", "/other/plain/flow/1", None, None).await;
582
    assert!(st == StatusCode::OK && page.contains("Run #1"), "{st}");
583
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
584
}
585
586
/// "Run pipeline" and "Re-run" (hub spec §13.2): runs that move no
587
/// bookmark, through the API and the pages.
588
#[tokio::test(flavor = "multi_thread")]
589
async fn runs_start_without_a_push_and_finished_runs_re_run() {
590
    let h = hub().await;
591
    // The site token acts as the first site administrator.
592
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
593
    create(&h.app, "andy", "demo").await;
594
    let url = format!("{}/andy/demo", h.base);
595
    let work = tempfile::tempdir().unwrap();
596
    let c = client(&url, work.path());
597
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
598
    write(work.path(), "test.sh", "echo ok\n");
599
    c.commit("Add a pipeline", &[]).unwrap();
600
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
601
    let first = runs_of(&h.app, "andy", "demo").await;
602
    assert_eq!((first.len(), first[0].trigger.as_str()), (1, "push"));
603
604
    // Run pipeline on the default bookmark: a new run of the same state.
605
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
606
    assert_eq!(st, StatusCode::CREATED, "{body}");
607
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
608
    assert_eq!(v["number"], 2);
609
    assert!(v["url"].as_str().unwrap().ends_with("/andy/demo/flow/2"));
610
    let second = db::flow::run(&h.app.db, first[0].repo_id, 2).await.unwrap().unwrap();
611
    assert_eq!((second.trigger.as_str(), second.actor.as_str(), second.state.as_str()), ("manual", "andy", first[0].state.as_str()));
612
    assert_eq!(db::flow::jobs(&h.app.db, second.id).await.unwrap().len(), 3);
613
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/2", None, None).await;
614
    assert!(page.contains("started by andy"), "the run page says what started it");
615
616
    // Run pipeline on one change: its state, with no bookmark.
617
    let head = first[0].head_list()[0].to_string();
618
    let (st, body) =
619
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{head}"}}"#))).await;
620
    assert_eq!(st, StatusCode::CREATED, "{body}");
621
    let on_change = db::flow::run(&h.app.db, first[0].repo_id, 3).await.unwrap().unwrap();
622
    assert_eq!(
623
        (on_change.bookmark.as_str(), on_change.heads.as_str(), on_change.state.as_str()),
624
        ("", head.as_str(), first[0].state.as_str())
625
    );
626
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/3", None, None).await;
627
    assert!(page.contains("title=\"Run on one change, not a bookmark\">change</span>"), "run page");
628
    let (st, body) =
629
        call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(format!(r#"{{"change":"{}"}}"#, "ab".repeat(32))))
630
            .await;
631
    assert!(st == StatusCode::CONFLICT && body.contains("no change"), "{st} {body}");
632
    // Viewers who cannot start runs are told why, and get no button.
633
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
634
    assert!(page.contains("Sign in with write access to run the pipeline.") && !page.contains("primary-btn"));
635
    let (_, page) = call(&h.app, "GET", "/andy/demo/bookmarks", None, None).await;
636
    assert!(!page.contains("/flow/start"), "no run buttons for anonymous viewers");
637
638
    // A live run is not re-run; unknown bookmarks and runs are refused.
639
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
640
    assert!(st == StatusCode::CONFLICT && body.contains("still queued"), "{st} {body}");
641
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"bookmark":"nope"}"#.into())).await;
642
    assert_eq!(st, StatusCode::CONFLICT);
643
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/99/rerun", Some("site"), None).await;
644
    assert_eq!(st, StatusCode::NOT_FOUND);
645
    // Anonymous callers cannot start runs.
646
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", None, Some("{}".into())).await;
647
    assert_ne!(st, StatusCode::CREATED);
648
649
    // A finished run re-runs as a new run of the same state.
650
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
651
    for r in [&first[0], &second] {
652
        for j in db::flow::jobs(&h.app.db, r.id).await.unwrap() {
653
            sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE id = ?").bind(j.id).execute(&h.app.db).await.unwrap();
654
        }
655
        sqlx::query("UPDATE flow_runs SET status = 'passed', finished_ms = 1 WHERE id = ?").bind(r.id).execute(&h.app.db).await.unwrap();
656
    }
657
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs/1/rerun", Some("site"), None).await;
658
    assert_eq!(st, StatusCode::CREATED, "{body}");
659
    let third = db::flow::run(&h.app.db, row.id, 4).await.unwrap().unwrap();
660
    assert_eq!(
661
        (third.trigger_label().as_str(), third.status.as_str(), third.state.as_str()),
662
        ("rerun:1", "queued", first[0].state.as_str())
663
    );
664
    assert_eq!(third.trigger, "rerun:1:push", "a rerun keeps the event it repeats");
665
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, &third.state).await.unwrap();
666
    assert!(
667
        checks.iter().all(|c| c.status == "queued" && c.url.ends_with("/flow/4")),
668
        "the re-run's checks replace the old ones: {checks:?}"
669
    );
670
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/4", None, None).await;
671
    assert!(page.contains("re-run of #1 by andy"));
672
    assert!(!page.contains("RE-RUN"), "anonymous viewers get no button");
673
674
    // oxygenhub#130: one job, with what it depends on; an unknown one is
675
    // refused, naming the jobs a manual run can start.
676
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["test"]}"#.into())).await;
677
    assert_eq!(st, StatusCode::CREATED, "{body}");
678
    let n = serde_json::from_str::<serde_json::Value>(&body).unwrap()["number"].as_i64().unwrap();
679
    let only = db::flow::run(&h.app.db, first[0].repo_id, n).await.unwrap().unwrap();
680
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, only.id).await.unwrap().into_iter().map(|j| j.name).collect();
681
    names.sort();
682
    assert_eq!(names, ["build", "test"], "test and the job it depends on, not lint");
683
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some(r#"{"jobs":["deploy"]}"#.into())).await;
684
    assert!(st == StatusCode::CONFLICT && body.contains("not in the pipeline") && body.contains("build, lint, test"), "{st} {body}");
685
686
    // With Flow off, nothing starts.
687
    db::repos::set_flow(&h.app.db, row.id, "off").await.unwrap();
688
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
689
    assert!(st == StatusCode::CONFLICT && body.contains("not enabled"), "{body}");
690
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
691
    assert!(page.contains("Flow is off for this repository"), "and the Flow tab says so");
692
}
693
694
/// The Flow API (hub spec §13.2): runs, a run with its jobs, a job's log,
695
/// checks by the heads a client has, and JSON for unknown API routes.
696
#[tokio::test(flavor = "multi_thread")]
697
async fn runs_jobs_and_logs_are_in_the_api() {
698
    let h = hub().await;
699
    create(&h.app, "andy", "demo").await;
700
    let url = format!("{}/andy/demo", h.base);
701
    let work = tempfile::tempdir().unwrap();
702
    let c = client(&url, work.path());
703
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
704
    write(work.path(), "test.sh", "echo ok\n");
705
    let head = c.commit("Add a pipeline", &[]).unwrap();
706
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
707
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
708
709
    // A job runs and logs.
710
    let a = claim(&h.app).await.unwrap();
711
    let id = a["job_id"].as_i64().unwrap();
712
    let recs =
713
        serde_json::json!({ "records": [{ "t": 1, "stream": "stdout", "text": "one" }, { "t": 3, "stream": "stderr", "text": "three" }] });
714
    let (st, _) = call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(recs.to_string())).await;
715
    assert!(st.is_success(), "{st}");
716
717
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs", None, None).await;
718
    assert_eq!(st, StatusCode::OK, "{body}");
719
    let runs: Vec<hub_api::FlowRun> = serde_json::from_str(&body).unwrap();
720
    assert_eq!(runs.len(), 1);
721
    assert_eq!((runs[0].number, runs[0].state.as_str(), runs[0].trigger.as_str()), (1, run.state.as_str(), "push"));
722
    assert!(runs[0].url.ends_with("/andy/demo/flow/1") && runs[0].jobs.is_empty());
723
724
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", None, None).await;
725
    let one: hub_api::FlowRun = serde_json::from_str(&body).unwrap();
726
    let names: Vec<(&str, &str)> = one.jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect();
727
    assert_eq!(names.len(), 3);
728
    let running = one.jobs.iter().find(|j| j.status == "running").unwrap();
729
    assert_eq!(running.name, a["job"]["name"].as_str().unwrap());
730
    assert!(one.jobs.iter().any(|j| j.name == "test" && j.depends_on == ["build"]));
731
732
    let job = running.name.clone();
733
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log"), None, None).await;
734
    assert_eq!(st, StatusCode::OK, "{body}");
735
    let lines: Vec<hub_api::FlowLogLine> = serde_json::from_str(&body).unwrap();
736
    assert!(lines.iter().any(|l| l.text == "three"), "{body}");
737
    let last = lines.last().unwrap().seq;
738
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/repos/andy/demo/flow/runs/1/jobs/{job}/log?after={last}"), None, None).await;
739
    assert_eq!(body, "[]", "nothing after the last line");
740
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/9", None, None).await.0, StatusCode::NOT_FOUND);
741
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1/jobs/nope/log", None, None).await.0, StatusCode::NOT_FOUND);
742
743
    // Checks by the state hash, by the head `oxy log` shows, and by bookmark.
744
    let by = |key: String| {
745
        let app = h.app.clone();
746
        async move {
747
            let (st, body) = call(&app, "GET", &format!("/api/v1/repos/andy/demo/checks/{key}"), None, None).await;
748
            assert_eq!(st, StatusCode::OK, "{key}: {body}");
749
            serde_json::from_str::<Vec<hub_api::Check>>(&body).unwrap().len()
750
        }
751
    };
752
    checks_when(&h.app, run.repo_id, &run.state, 3).await;
753
    assert_eq!(by(run.state.clone()).await, 3);
754
    assert_eq!(by(head.to_hex()).await, 3, "a single head names its state");
755
    assert_eq!(by("main".into()).await, 3);
756
    let (st, _) = call(&h.app, "GET", "/api/v1/repos/andy/demo/checks/no-such-bookmark", None, None).await;
757
    assert_eq!(st, StatusCode::NOT_FOUND);
758
759
    // An unknown API route answers with a problem document.
760
    let (st, body) = call(&h.app, "GET", "/api/v1/users/andy/repos", None, None).await;
761
    assert_eq!(st, StatusCode::NOT_FOUND);
762
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
763
    assert_eq!(v["status"], 404, "{body}");
764
}
765
766
async fn get_bytes(app: &Shared, path: &str) -> (StatusCode, Vec<u8>) {
767
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(path).body(Body::empty()).unwrap()).await.unwrap();
768
    let status = res.status();
769
    (status, res.into_body().collect().await.unwrap().to_bytes().to_vec())
770
}
771
772
#[tokio::test(flavor = "multi_thread")]
773
async fn signed_receipts_are_checked_kept_and_shown() {
774
    use oxy_core::hash::{hash_object, ChangeHash, ObjectRef, ObjectType};
775
    use oxy_core::identity::SecretKey;
776
    use oxy_core::objects::StateObject;
777
    use oxy_core::receipt::SignedReceipt;
778
    let h = hub().await;
779
    create(&h.app, "andy", "demo").await;
780
    let url = format!("{}/andy/demo", h.base);
781
    let work = tempfile::tempdir().unwrap();
782
    let c = client(&url, work.path());
783
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
784
    c.snapshot("test").unwrap();
785
    c.commit("Add a pipeline", &[]).unwrap();
786
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
787
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
788
    let heads: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
789
    let state = hash_object(ObjectType::State, &StateObject::new(heads.clone()).encode());
790
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
791
    let sk = SecretKey::generate();
792
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
793
    let sign = |r: &serde_json::Value, state: ObjectRef, sk: &SecretKey, id: &oxy_core::identity::Identity| {
794
        let r: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
795
        let run_url = format!("{url}/flow/{}", run.number);
796
        hex::encode(SignedReceipt::sign(r.to_oxy(), repo_id, state, &run_url, id, sk).encode())
797
    };
798
799
    let a = claim(&h.app).await.unwrap();
800
    let b = claim(&h.app).await.unwrap();
801
    let ph = a["pipeline_hash"].as_str().unwrap().to_string();
802
    let (a_id, b_id) = (a["job_id"].as_i64().unwrap(), b["job_id"].as_i64().unwrap());
803
    // The first signed receipt binds the runner token to its key, and is kept.
804
    let rb = receipt("build", &ph, 0);
805
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": rb, "signed_receipt": sign(&rb, state, &sk, &runner) });
806
    assert_eq!(finish(&h.app, a_id, body).await, StatusCode::NO_CONTENT);
807
    // Another key under the same token: the result counts, the receipt is not kept.
808
    let other = SecretKey::generate();
809
    let rl = receipt("lint", &ph, 0);
810
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": rl,
811
        "signed_receipt": sign(&rl, state, &other, &other.identity("mallory", "", 1)) });
812
    assert_eq!(finish(&h.app, b_id, body).await, StatusCode::NO_CONTENT);
813
    // The right key, but for another state.
814
    let t = claim(&h.app).await.unwrap();
815
    let rt = receipt("test", &ph, 0);
816
    let body = serde_json::json!({ "exit_code": 0, "duration_ms": 500, "receipt": rt,
817
        "signed_receipt": sign(&rt, ObjectRef([9; 32]), &sk, &runner) });
818
    assert_eq!(finish(&h.app, t["job_id"].as_i64().unwrap(), body).await, StatusCode::NO_CONTENT);
819
820
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
821
    let job = |n: &str| jobs.iter().find(|j| j.name == n).unwrap().clone();
822
    assert_eq!(job("build").status, "passed");
823
    assert_eq!((job("build").receipt_attest.len(), job("build").receipt_signer.as_str()), (64, "test-1 (OxygenFlow runner)"));
824
    assert_eq!(job("lint").status, "passed", "the job's result stands");
825
    assert!(job("lint").receipt_attest.is_empty());
826
    assert!(job("lint").receipt_note.contains("not the key this runner signs with"), "{}", job("lint").receipt_note);
827
    assert!(job("test").receipt_note.contains("another state"), "{}", job("test").receipt_note);
828
829
    // The repository keeps it, and anyone who can read the repository can
830
    // download it and check it on their own.
831
    let kept = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().receipts(&heads).unwrap();
832
    assert_eq!(kept.len(), 1);
833
    let attest = job("build").receipt_attest;
834
    let (st, bytes) = get_bytes(&h.app, &format!("/andy/demo/receipts/{attest}")).await;
835
    assert_eq!(st, StatusCode::OK);
836
    let sr = SignedReceipt::decode(&bytes).unwrap();
837
    sr.verify().unwrap();
838
    assert_eq!((sr.state(), sr.receipt.job_name.as_str()), (state, "build"));
839
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/receipts/{}", "0".repeat(64))).await.0, StatusCode::NOT_FOUND);
840
841
    // Pages: the run names the signer or why a receipt was not kept; the
842
    // change whose state it is lists it.
843
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
844
    assert!(page.contains("signed receipt</a> by test-1"), "run page");
845
    assert!(page.contains("receipt not kept"), "run page");
846
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/change/{}", heads[0].to_hex()), None, None).await;
847
    assert!(page.contains("<dt>Receipts</dt>") && page.contains(&format!("/andy/demo/receipts/{attest}")), "change page");
848
}
849
850
async fn upload(app: &Shared, job: i64, name: &str, bytes: &[u8]) -> (StatusCode, String) {
851
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/artifacts/{name}"))
852
        .header(header::AUTHORIZATION, "Bearer runner-secret")
853
        .header(header::CONTENT_TYPE, "application/octet-stream")
854
        .body(Body::from(bytes.to_vec()))
855
        .unwrap();
856
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
857
    let status = res.status();
858
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
859
}
860
861
#[tokio::test(flavor = "multi_thread")]
862
async fn artifacts_are_kept_named_by_the_receipt_and_served() {
863
    let h = hub().await;
864
    create(&h.app, "andy", "demo").await;
865
    let url = format!("{}/andy/demo", h.base);
866
    let work = tempfile::tempdir().unwrap();
867
    let c = client(&url, work.path());
868
    write(
869
        work.path(),
870
        ".flow/pipeline.kdl",
871
        &format!(
872
            "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"
873
        ),
874
    );
875
    c.snapshot("test").unwrap();
876
    c.commit("Build a tool", &[]).unwrap();
877
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
878
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
879
    let a = claim(&h.app).await.unwrap();
880
    assert_eq!(a["job"]["outputs"], serde_json::json!([{ "name": "tool", "path": "/src/out/tool" }]), "the runner is told");
881
    let id = a["job_id"].as_i64().unwrap();
882
883
    let body: Vec<u8> = (0..300_000u32).map(|i| (i % 253) as u8).collect();
884
    let (st, text) = upload(&h.app, id, "other", &body).await;
885
    assert_eq!(st, StatusCode::BAD_REQUEST, "an undeclared artifact: {text}");
886
    let (st, text) = upload(&h.app, id, "tool", &body).await;
887
    assert_eq!(st, StatusCode::OK, "{text}");
888
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
889
    assert_eq!(blob, oxy_core::repo::Repo::blob_ref(&body).to_hex(), "the same blob the runner computes");
890
891
    // The receipt must name exactly the uploaded artifacts.
892
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
893
    assert_eq!(
894
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r.clone() })).await,
895
        StatusCode::BAD_REQUEST
896
    );
897
    r["outputs"] = serde_json::json!([blob]);
898
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
899
900
    // The run page lists it; anyone who can read the repository downloads it.
901
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
902
    let link = format!("/andy/demo/flow/{}/artifacts/build/tool", run.number);
903
    assert!(page.contains(&link), "run page lists the artifact");
904
    let (st, got) = get_bytes(&h.app, &link).await;
905
    assert_eq!((st, got == body), (StatusCode::OK, true));
906
    assert_eq!(get_bytes(&h.app, &format!("/andy/demo/flow/{}/artifacts/build/none", run.number)).await.0, StatusCode::NOT_FOUND);
907
908
    // The nightly gc keeps it (#126): only the database names it, so with
909
    // no grace period a gc that did not root it would prune it at once.
910
    {
911
        let name = RepoName::parse("andy/demo").unwrap();
912
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
913
        hosted.config.set("core.gc-grace", "0").unwrap();
914
        hosted.save_config().unwrap();
915
    }
916
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
917
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
918
    let (st, got) = get_bytes(&h.app, &link).await;
919
    assert_eq!((st, got == body), (StatusCode::OK, true), "the artifact survives gc");
920
921
    // A writer attaches the artifact to a release from the run page; the
922
    // release then names the run and job that built it, as does the API.
923
    let form = |f: String| {
924
        Request::post("/register").header(header::CONTENT_TYPE, "application/x-www-form-urlencoded").body(Body::from(f)).unwrap()
925
    };
926
    let res = oxygenhub::router(h.app.clone())
927
        .oneshot(form("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup".into()))
928
        .await
929
        .unwrap();
930
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
931
    let with_cookie = |method: &str, path: &str, body: Option<String>| {
932
        let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie.clone());
933
        if body.is_some() {
934
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
935
        }
936
        req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()
937
    };
938
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
939
    db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
940
    let res = oxygenhub::router(h.app.clone()).oneshot(with_cookie("GET", &format!("/andy/demo/flow/{}", run.number), None)).await.unwrap();
941
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
942
    let attach = format!("/andy/demo/flow/{}/artifacts/build/tool/attach", run.number);
943
    assert!(page.contains(&attach), "a writer is offered the release");
944
    let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
945
    let csrf = page[i..].split('"').next().unwrap().to_string();
946
    let release_id = db::releases::list(&h.app.db, row.id).await.unwrap()[0].id;
947
    let res = oxygenhub::router(h.app.clone())
948
        .oneshot(with_cookie("POST", &attach, Some(format!("_csrf={csrf}&release={release_id}"))))
949
        .await
950
        .unwrap();
951
    assert_eq!(res.status(), StatusCode::SEE_OTHER);
952
    let (_, page) = call(&h.app, "GET", "/andy/demo/releases/tag/v1", None, None).await;
953
    assert!(
954
        page.contains(">tool</a>") && page.contains(&format!("built by <a href=\"/andy/demo/flow/{0}\">run #{0}</a> build", run.number)),
955
        "{page}"
956
    );
957
    let (_, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases", None, None).await;
958
    let api: serde_json::Value = serde_json::from_str(&api).unwrap();
959
    let asset = &api[0]["assets"][0];
960
    assert_eq!(
961
        (asset["name"].as_str(), asset["built_by"]["run"].as_i64(), asset["built_by"]["job"].as_str()),
962
        (Some("tool"), Some(run.number), Some("build"))
963
    );
964
    assert!(asset["built_by"]["receipt"].is_null(), "that receipt was not signed");
965
}
966
967
/// oxygenflow#37: a failing job keeps a `when "always"` artifact; its
968
/// receipt names none, and the run page says the file is outside it.
969
async fn upload_report_file(app: &Shared, job: i64, name: &str, path: &str, bytes: &[u8]) -> (StatusCode, String) {
970
    let req = Request::post(format!("/api/v1/flow/jobs/{job}/reports/{name}/files"))
971
        .header(header::AUTHORIZATION, "Bearer runner-secret")
972
        .header(header::CONTENT_TYPE, "application/octet-stream")
973
        .header("X-Flow-Report-Path", path)
974
        .body(Body::from(bytes.to_vec()))
975
        .unwrap();
976
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
977
    let status = res.status();
978
    (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
979
}
980
981
/// #127: a report's files arrive one by one, then its manifest as the
982
/// report's artifact; the hub indexes the declaration, metrics and files,
983
/// and gc keeps every file.
984
#[tokio::test(flavor = "multi_thread")]
985
async fn reports_are_kept_file_by_file_and_indexed() {
986
    let h = hub().await;
987
    create(&h.app, "andy", "demo").await;
988
    let url = format!("{}/andy/demo", h.base);
989
    let work = tempfile::tempdir().unwrap();
990
    let c = client(&url, work.path());
991
    write(
992
        work.path(),
993
        ".flow/pipeline.kdl",
994
        &format!(
995
            "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"
996
        ),
997
    );
998
    c.snapshot("test").unwrap();
999
    c.commit("Measure frames", &[]).unwrap();
1000
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1001
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1002
    let a = claim(&h.app).await.unwrap();
1003
    let id = a["job_id"].as_i64().unwrap();
1004
1005
    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";
1006
    let page = b"<p>frames</p>".to_vec();
1007
    let data: Vec<u8> = (0..100_000u32).map(|i| (i % 241) as u8).collect();
1008
    let (page_bytes, data_bytes) = (page.clone(), data.clone());
1009
    let files: [(&str, &[u8]); 3] = [("data/frames.csv", &data), ("index.html", &page), ("report.toml", toml)];
1010
1011
    assert_eq!(upload_report_file(&h.app, id, "tool", "report.toml", toml).await.0, StatusCode::BAD_REQUEST, "not a report");
1012
    assert_eq!(upload_report_file(&h.app, id, "frame-timing", "../x", toml).await.0, StatusCode::BAD_REQUEST, "not a clean path");
1013
    let mut listed = vec![];
1014
    for (path, bytes) in files {
1015
        let (st, text) = upload_report_file(&h.app, id, "frame-timing", path, bytes).await;
1016
        assert_eq!(st, StatusCode::OK, "{text}");
1017
        let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1018
        assert_eq!(blob, oxy_core::repo::Repo::blob_ref(bytes).to_hex());
1019
        listed.push(serde_json::json!({ "path": path, "blob": blob, "size": bytes.len() }));
1020
    }
1021
    let mut missing = listed.clone();
1022
    missing.push(serde_json::json!({ "path": "assets/x.js", "blob": "ab".repeat(32), "size": 1 }));
1023
    let (st, text) =
1024
        upload(&h.app, id, "frame-timing", &serde_json::to_vec(&serde_json::json!({ "version": 1, "files": missing })).unwrap()).await;
1025
    assert_eq!(st, StatusCode::BAD_REQUEST, "a file never uploaded: {text}");
1026
    assert!(text.contains("assets/x.js"), "{text}");
1027
    let manifest = serde_json::to_vec(&serde_json::json!({ "version": 1, "files": listed })).unwrap();
1028
    let (st, text) = upload(&h.app, id, "frame-timing", &manifest).await;
1029
    assert_eq!(st, StatusCode::OK, "{text}");
1030
1031
    let (kind, title, summary, files_n, bytes): (String, String, String, i64, i64) =
1032
        sqlx::query_as("SELECT kind, title, summary, files, bytes FROM reports WHERE job_id = ? AND name = 'frame-timing'")
1033
            .bind(id)
1034
            .fetch_one(&h.app.db)
1035
            .await
1036
            .unwrap();
1037
    assert_eq!((kind.as_str(), title.as_str(), summary.as_str()), ("performance", "Frame timing", "Median 16.4 ms"));
1038
    assert_eq!((files_n, bytes), (3, (data.len() + page.len() + toml.len()) as i64));
1039
    let rid: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE job_id = ?").bind(id).fetch_one(&h.app.db).await.unwrap();
1040
    let m = oxygenhub::reports::metrics(&h.app.db, rid).await.unwrap();
1041
    assert_eq!((m[0].key.as_str(), m[0].value, m[0].fail_above), ("median_ms", 16.4, Some(20.0)));
1042
    let log = db::flow::log(&h.app.db, id, 0, 1000).await.unwrap();
1043
    assert!(log.iter().any(|r| r.text.contains("report frame-timing: performance \"Frame timing\", 1 metric")), "{log:?}");
1044
1045
    // The threshold is a check on the run's state, passing at 16.4.
1046
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
1047
    let c = checks.iter().find(|c| c.name == "report/frame-timing/median_ms").expect("a check per threshold");
1048
    assert_eq!(c.status, "passed", "{c:?}");
1049
    assert!(c.summary.contains("16.4 ms") && c.url.contains("/reports/frame-timing?id="), "{c:?}");
1050
1051
    // The Reports tab, the report's page, and its own page in a sandbox.
1052
    let (_, page) = call(&h.app, "GET", "/andy/demo", None, None).await;
1053
    assert!(page.contains(">Reports</a>"), "the tab");
1054
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports", None, None).await;
1055
    assert!(st == StatusCode::OK && page.contains("Frame timing") && page.contains("median_ms"), "{st}");
1056
    let (st, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1057
    assert!(st == StatusCode::OK && page.contains("fails above 20") && page.contains("sandbox=\"allow-scripts\""), "{st}");
1058
    let src = page.split("class=\"rep-frame\" src=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
1059
    assert!(src.ends_with("/index.html"), "{src}");
1060
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get(&src).body(Body::empty()).unwrap()).await.unwrap();
1061
    assert_eq!(res.status(), StatusCode::OK);
1062
    let csp = res.headers()[header::CONTENT_SECURITY_POLICY].to_str().unwrap().to_string();
1063
    assert!(csp.starts_with("sandbox allow-scripts;") && csp.contains("default-src 'none'"), "{csp}");
1064
    // The site's own policy and frame refusal stay off it: report frames are framed (#222).
1065
    assert!(
1066
        res.headers().get(header::X_FRAME_OPTIONS).is_none() && res.headers().get(header::CONTENT_SECURITY_POLICY_REPORT_ONLY).is_none()
1067
    );
1068
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1069
    assert_eq!(res.headers()[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
1070
    // The page as kept, with the frame script that sizes the frame added.
1071
    let served = res.into_body().collect().await.unwrap().to_bytes().to_vec();
1072
    assert!(served.starts_with(&page_bytes), "the report's page");
1073
    assert!(String::from_utf8_lossy(&served).contains("/static/report-frame.js"), "with the frame script");
1074
    let (st, _) = get_bytes(&h.app, "/static/report.css").await;
1075
    assert_eq!(st, StatusCode::OK, "the stylesheet a report may link");
1076
    let data = src.replace("/index.html", "/data/frames.csv");
1077
    assert_eq!(get_bytes(&h.app, &data).await, (StatusCode::OK, data_bytes.clone()));
1078
    // A link with another report's MAC, or a file it lacks, finds nothing.
1079
    // A second run of the report: the timeline has two stops, and the
1080
    // first can be compared with it (RP4).
1081
    let first: i64 = sqlx::query_scalar("SELECT id FROM reports WHERE name = 'frame-timing'").fetch_one(&h.app.db).await.unwrap();
1082
    let second: i64 = sqlx::query_scalar(
1083
        "INSERT INTO reports (repo_id, name, kind, title, summary, context, run_id, job_id, run_number, job, bookmark, state, manifest, files, bytes, created_ms) \
1084
         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",
1085
    )
1086
    .bind(first)
1087
    .fetch_one(&h.app.db)
1088
    .await
1089
    .unwrap();
1090
    sqlx::query(
1091
        "INSERT INTO report_metrics (report_id, key, value, unit, better, fail_above) VALUES (?, 'median_ms', 18.0, 'ms', 'lower', 20)",
1092
    )
1093
    .bind(second)
1094
    .execute(&h.app.db)
1095
    .await
1096
    .unwrap();
1097
    let (_, page) = call(&h.app, "GET", "/andy/demo/reports/frame-timing", None, None).await;
1098
    assert_eq!(page.matches("data-tl-stop").count(), 2, "a stop per run");
1099
    assert!(page.contains("Median 18.0 ms"), "the newest run is shown");
1100
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/frame-timing?id={first}&compare={second}&play=3"), None, None).await;
1101
    assert!(page.contains("This run against run #2") && page.contains("-1.6"), "every metric against the other run");
1102
    let stop = page.split("data-tl-stop").next().unwrap_or("").rsplit("href=").next().unwrap_or("").to_string();
1103
    assert!(page.contains("data-play=\"3\""), "playing");
1104
    assert!(stop.contains("play") && stop.contains('3'), "playing carries on from stop to stop: {stop}");
1105
    assert!(page.contains("data-report-runs="), "the frame interface knows the runs");
1106
    let forged = src.replacen("/files/", "/files/9", 1);
1107
    assert_eq!(get_bytes(&h.app, &forged).await.0, StatusCode::NOT_FOUND);
1108
    assert_eq!(get_bytes(&h.app, &src.replace("/index.html", "/secret.txt")).await.0, StatusCode::NOT_FOUND);
1109
    let _ = run;
1110
1111
    // gc keeps every file: only the database names them.
1112
    {
1113
        let name = RepoName::parse("andy/demo").unwrap();
1114
        let mut hosted = oxy_core::repo::Repo::open(&h.app.repos.dir(&name)).unwrap();
1115
        hosted.config.set("core.gc-grace", "0").unwrap();
1116
        hosted.save_config().unwrap();
1117
    }
1118
    let done = oxygenhub::maintenance::gc_all(&h.app).await;
1119
    assert!(done.iter().all(|d| !d.failed), "{done:?}");
1120
    let hosted = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap();
1121
    for (path, bytes) in files {
1122
        assert_eq!(hosted.read_blob(&oxy_core::repo::Repo::blob_ref(bytes)).unwrap(), bytes, "{path} survives gc");
1123
    }
1124
}
1125
1126
#[tokio::test(flavor = "multi_thread")]
1127
async fn a_failing_job_keeps_an_artifact_outside_its_receipt() {
1128
    let h = hub().await;
1129
    create(&h.app, "andy", "demo").await;
1130
    let url = format!("{}/andy/demo", h.base);
1131
    let work = tempfile::tempdir().unwrap();
1132
    let c = client(&url, work.path());
1133
    write(
1134
        work.path(),
1135
        ".flow/pipeline.kdl",
1136
        &format!(
1137
            "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"
1138
        ),
1139
    );
1140
    c.snapshot("test").unwrap();
1141
    c.commit("Test", &[]).unwrap();
1142
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1143
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1144
    let a = claim(&h.app).await.unwrap();
1145
    assert_eq!(a["job"]["outputs"][0]["always"], true, "the runner is told to keep it from a failing job");
1146
    let id = a["job_id"].as_i64().unwrap();
1147
    // A JUnit report (#114): parsed on upload, counted, failures listed.
1148
    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>"#;
1149
    let (st, text) = upload(&h.app, id, "junit", xml).await;
1150
    assert_eq!(st, StatusCode::OK, "{text}");
1151
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1152
    let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), 1);
1153
    r["outputs"] = serde_json::json!([blob]);
1154
    assert_eq!(
1155
        finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r.clone() })).await,
1156
        StatusCode::BAD_REQUEST,
1157
        "a failing receipt names no outputs"
1158
    );
1159
    r["outputs"] = serde_json::json!([]);
1160
    assert_eq!(finish(&h.app, id, serde_json::json!({ "exit_code": 1, "duration_ms": 700, "receipt": r })).await, StatusCode::NO_CONTENT);
1161
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.number), None, None).await;
1162
    assert!(page.contains(&format!("/andy/demo/flow/{}/artifacts/test/junit", run.number)), "listed");
1163
    assert!(page.contains("not in its receipt"), "marked");
1164
    assert!(page.contains("2 tests: 1 failed"), "counts beside the job");
1165
    assert!(page.contains("tests.test_io::test_write") && page.contains("disk full") && page.contains("OSError"), "the failure");
1166
    assert!(page.contains("tests: 2 tests: 1 failed in 2.0 s"), "said in the job's log");
1167
}
1168
1169
/// A release's trust report (hub spec §9.1): a signed tag, an asset built
1170
/// by a job with a signed receipt from the tagged state, and one uploaded
1171
/// by hand; the page, its JSON export and the API.
1172
#[tokio::test(flavor = "multi_thread")]
1173
async fn a_release_is_audited_from_authors_to_receipts() {
1174
    use oxy_core::hash::{hash_object, ChangeHash, ObjectType};
1175
    use oxy_core::identity::SecretKey;
1176
    use oxy_core::objects::StateObject;
1177
    use oxy_core::receipt::SignedReceipt;
1178
    let h = hub().await;
1179
    create(&h.app, "andy", "demo").await;
1180
    let url = format!("{}/andy/demo", h.base);
1181
    let work = tempfile::tempdir().unwrap();
1182
    let mut c = client(&url, work.path());
1183
    c.create_identity("Andy", "[email protected]", oxy_core::repo::IdentityScope::Repo).unwrap();
1184
    write(
1185
        work.path(),
1186
        ".flow/pipeline.kdl",
1187
        &format!(
1188
            "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"
1189
        ),
1190
    );
1191
    c.snapshot("test").unwrap();
1192
    c.commit("Build a tool", &[]).unwrap();
1193
    let heads = c.bookmark_heads().unwrap();
1194
    c.tag_create("v1", &heads, "first").unwrap();
1195
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1196
1197
    // The runner builds, uploads the artifact and signs its receipt.
1198
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
1199
    let a = claim(&h.app).await.unwrap();
1200
    let id = a["job_id"].as_i64().unwrap();
1201
    let body: Vec<u8> = b"#!/bin/sh\necho tool\n".to_vec();
1202
    let (_, text) = upload(&h.app, id, "tool", &body).await;
1203
    let blob = serde_json::from_str::<serde_json::Value>(&text).unwrap()["blob"].as_str().unwrap().to_string();
1204
    let mut r = receipt("build", a["pipeline_hash"].as_str().unwrap(), 0);
1205
    r["outputs"] = serde_json::json!([blob]);
1206
    let heads_run: Vec<ChangeHash> = run.head_list().into_iter().filter_map(ChangeHash::from_hex).collect();
1207
    let state = hash_object(ObjectType::State, &StateObject::new(heads_run).encode());
1208
    let repo_id = h.app.repos.open(&RepoName::parse("andy/demo").unwrap()).unwrap().id().unwrap();
1209
    let sk = SecretKey::generate();
1210
    let runner = sk.identity("test-1 (OxygenFlow runner)", "", 1);
1211
    let fr: flow_core::Receipt = serde_json::from_value(r.clone()).unwrap();
1212
    let signed = hex::encode(SignedReceipt::sign(fr.to_oxy(), repo_id, state, &format!("{url}/flow/1"), &runner, &sk).encode());
1213
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 900, "receipt": r, "signed_receipt": signed });
1214
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
1215
1216
    // A release with the built asset and a file uploaded by hand.
1217
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1218
    let rel = db::releases::create(&h.app.db, row.id, "v1", "One", "", false, None).await.unwrap();
1219
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "tool", "", &body).await.unwrap();
1220
    oxygenhub::web::releases::store_asset(&h.app, rel.id, "notes.txt", "", b"by hand\n").await.unwrap();
1221
1222
    let (st, page) = call(&h.app, "GET", "/andy/demo/releases/trust/v1", None, None).await;
1223
    assert_eq!(st, StatusCode::OK);
1224
    for want in [
1225
        "Tag v1 is signed",
1226
        "The one change in the release is authenticated",
1227
        "tool: signed receipt from run #1 build",
1228
        "a runner key of this hub",
1229
        "tool: built from the tagged state",
1230
        "tool: pinned environment",
1231
        "notes.txt: no build found",
1232
        "<svg class=\"trust-graph\"",
1233
        // oxygenhub#79: a summary of badges, badges in the graph, and the
1234
        // graph drawn at its own size rather than stretched to the page.
1235
        "Tag signed by",
1236
        "1 of 1 changes signed or sealed",
1237
        "1 of 2 assets built and attested by OxygenFlow",
1238
        "attested build",
1239
        "uploaded by hand",
1240
        "receipt verified",
1241
        "class=\"shackle\"",
1242
        "<title>notes.txt:",
1243
    ] {
1244
        assert!(page.contains(want), "missing {want:?}");
1245
    }
1246
    let svg = &page[page.find("<svg class=\"trust-graph\"").unwrap()..];
1247
    assert!(svg[..200].contains(" width=\"") && svg[..200].contains(" height=\""), "the graph has its own size: {}", &svg[..200]);
1248
    let (_, releases) = call(&h.app, "GET", "/andy/demo/releases", None, None).await;
1249
    assert!(releases.contains("/andy/demo/releases/trust/v1"), "the release links its audit");
1250
1251
    // The export carries the signed receipt, which checks on its own.
1252
    let (st, json) = call(&h.app, "GET", "/andy/demo/releases/trust/v1?format=json", None, None).await;
1253
    assert_eq!(st, StatusCode::OK);
1254
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
1255
    assert_eq!((t["tag"].as_str(), t["tag_signature"].as_str(), t["changes"].as_i64()), (Some("v1"), Some("valid"), Some(1)));
1256
    assert_eq!(t["authors"][0]["who"]["name"], "Andy");
1257
    let tool = t["assets"].as_array().unwrap().iter().find(|a| a["name"] == "tool").unwrap();
1258
    let hex_receipt = tool["build"]["signed_receipt"].as_str().unwrap();
1259
    let sr = SignedReceipt::decode(&hex::decode(hex_receipt).unwrap()).unwrap();
1260
    sr.verify().unwrap();
1261
    assert_eq!(sr.receipt.outputs[0].to_hex(), blob);
1262
    let audit = t["audit"].as_array().unwrap();
1263
    assert!(audit.iter().any(|c| c["verdict"] == "warn" && c["title"].as_str().unwrap().starts_with("notes.txt")));
1264
    assert!(!audit.iter().any(|c| c["verdict"] == "fail"), "{audit:?}");
1265
    // The API gives the same report; an unknown release is a 404.
1266
    let (st, api) = call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v1", None, None).await;
1267
    assert_eq!(st, StatusCode::OK);
1268
    assert_eq!(serde_json::from_str::<serde_json::Value>(&api).unwrap()["assets"].as_array().unwrap().len(), 2);
1269
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1270
    assert_eq!(call(&h.app, "GET", "/andy/demo/releases/trust/v9", None, None).await.0, StatusCode::NOT_FOUND);
1271
}
1272
1273
/// Runners (hub spec §13.2): an administrator makes a registration token,
1274
/// a runner registers with it (binding its key), claims, shows on Admin →
1275
/// Runners with its history, and is drained, disabled and removed.
1276
#[tokio::test(flavor = "multi_thread")]
1277
async fn runners_register_show_their_history_and_are_drained_and_removed() {
1278
    use oxy_core::identity::SecretKey;
1279
    let h = hub().await;
1280
    create(&h.app, "andy", "demo").await;
1281
    // A signed-in site administrator.
1282
    let res = oxygenhub::router(h.app.clone())
1283
        .oneshot(
1284
            Request::post("/register")
1285
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1286
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
1287
                .unwrap(),
1288
        )
1289
        .await
1290
        .unwrap();
1291
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1292
    let admin = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
1293
    db::accounts::set_admin(&h.app.db, admin.id, true).await.unwrap();
1294
    let web = |method: &'static str, path: String, body: Option<String>| {
1295
        let (app, cookie) = (h.app.clone(), cookie.clone());
1296
        async move {
1297
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1298
            if body.is_some() {
1299
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1300
            }
1301
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1302
            let st = res.status();
1303
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1304
        }
1305
    };
1306
    let csrf_of = |page: &str| {
1307
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1308
        page[i..].split('"').next().unwrap().to_string()
1309
    };
1310
    let (st, page) = web("GET", "/admin/runners".into(), None).await;
1311
    assert_eq!(st, StatusCode::OK);
1312
    assert!(page.contains("No runners yet"));
1313
    assert_eq!(call(&h.app, "GET", "/admin/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1314
1315
    // A one-time registration token, shown once with the command.
1316
    let (_, page) = web("POST", "/admin/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1317
    let i = page.find("--token ").unwrap() + "--token ".len();
1318
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1319
    assert!(token.starts_with("flowreg_"), "{token}");
1320
1321
    // The runner registers, binding its key; the token then is spent.
1322
    let sk = SecretKey::generate();
1323
    let identity = sk.identity("plex (OxygenFlow runner)", "", 1);
1324
    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 });
1325
    let reg = serde_json::json!({ "token": token, "name": "plex", "identity": hex::encode(identity.encode()), "info": info });
1326
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1327
    assert_eq!(st, StatusCode::OK, "{body}");
1328
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1329
    assert!(credential.starts_with("flowrunner_"));
1330
    assert_eq!(
1331
        call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0,
1332
        StatusCode::FORBIDDEN,
1333
        "used once"
1334
    );
1335
1336
    // It claims with its credential; the hub.toml runner shows too.
1337
    let claim_as = |who: String| {
1338
        let app = h.app.clone();
1339
        let info = info.clone();
1340
        async move {
1341
            let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
1342
            call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await
1343
        }
1344
    };
1345
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "nothing queued");
1346
    assert_eq!(claim(&h.app).await, None);
1347
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1348
    assert!(
1349
        page.contains(">plex</strong>") && page.contains("st-online") && page.contains("x86_64 · linux") && page.contains("big-disk"),
1350
        "{page}"
1351
    );
1352
    assert!(page.contains(">test-1</strong>") && page.contains("hub.toml"), "the configured runner, by its claimed name");
1353
    let plex = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex").unwrap();
1354
    assert_eq!(plex.key, identity.hash().to_hex(), "bound at registration");
1355
1356
    // A run: plex takes a job, and its history shows it.
1357
    let url = format!("{}/andy/demo", h.base);
1358
    let work = tempfile::tempdir().unwrap();
1359
    let c = client(&url, work.path());
1360
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1361
    c.snapshot("test").unwrap();
1362
    c.commit("Add a pipeline", &[]).unwrap();
1363
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1364
    runs_of(&h.app, "andy", "demo").await;
1365
    let (st, body) = claim_as(credential.clone()).await;
1366
    assert_eq!(st, StatusCode::OK, "{body}");
1367
    let job: serde_json::Value = serde_json::from_str(&body).unwrap();
1368
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1369
    assert!(
1370
        page.contains("andy/demo") && page.contains(job["job"]["name"].as_str().unwrap()) && page.contains("Running now</dt><dd>1 job"),
1371
        "{page}"
1372
    );
1373
    // The queue on Admin → Runners and through the API (#41, part 4).
1374
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1375
    assert!(page.contains("<h2>Queue</h2>") && page.contains("<td>plex</td>"), "{page}");
1376
    let (_, tokens) = web("GET", "/settings/tokens".into(), None).await;
1377
    let (_, made) = web("POST", "/settings/tokens".into(), Some(format!("_csrf={}&name=admin&scopes=user%3Aread", csrf_of(&tokens)))).await;
1378
    let i = made.find("oxyhub_").unwrap();
1379
    let admin_token: String = made[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
1380
    let (st, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1381
    assert_eq!(st, StatusCode::OK, "{body}");
1382
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1383
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1384
    assert_eq!((plex_row["running"].as_i64(), plex_row["arch"].as_str()), (Some(1), Some("x86_64")));
1385
    // A runner's own labels and time limit from its page (#98).
1386
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1387
    let (st, _) = web(
1388
        "POST",
1389
        format!("/admin/runners/{}/limits", plex.id),
1390
        Some(format!("_csrf={}&labels=gpu%2C+plex&timeout_minutes=5", csrf_of(&page))),
1391
    )
1392
    .await;
1393
    assert_eq!(st, StatusCode::SEE_OTHER);
1394
    let (_, page) = web("GET", format!("/admin/runners/{}", plex.id), None).await;
1395
    assert!(page.contains(">gpu<") && page.contains("5 min for its jobs"), "{page}");
1396
    let (_, body) = call(&h.app, "GET", "/api/v1/runners", Some(&admin_token), None).await;
1397
    let listed: serde_json::Value = serde_json::from_str(&body).unwrap();
1398
    let plex_row = listed.as_array().unwrap().iter().find(|r| r["name"] == "plex").unwrap();
1399
    assert!(plex_row["labels"].as_array().unwrap().iter().any(|l| l == "gpu"), "{plex_row}");
1400
    let (st, _) = web(
1401
        "POST",
1402
        format!("/admin/runners/{}/limits", plex.id),
1403
        Some(format!("_csrf={}&labels=bad%20label%21&timeout_minutes=", csrf_of(&page))),
1404
    )
1405
    .await;
1406
    assert_eq!(st, StatusCode::BAD_REQUEST, "a label with a space or punctuation is refused");
1407
    let (_, body) = call(&h.app, "GET", "/api/v1/runners/queue", Some(&admin_token), None).await;
1408
    let queue: serde_json::Value = serde_json::from_str(&body).unwrap();
1409
    assert!(queue.as_array().unwrap().iter().any(|q| q["status"] == "running" && q["runner"] == "plex"), "{queue}");
1410
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/runners/{}/jobs", plex.id), Some(&admin_token), None).await;
1411
    let jobs: serde_json::Value = serde_json::from_str(&body).unwrap();
1412
    assert_eq!(jobs[0]["repo"], "andy/demo", "{jobs}");
1413
    assert_eq!(call(&h.app, "GET", "/api/v1/runners", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
1414
1415
    // Draining: no new work; removing while busy is refused.
1416
    let (_, page) = web("GET", "/admin/runners".into(), None).await;
1417
    let csrf = csrf_of(&page);
1418
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=draining"))).await;
1419
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::NO_CONTENT, "a draining runner takes nothing");
1420
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1421
    assert!(page.contains("is running jobs: drain it first"), "{page}");
1422
    // Its job finishes; disabled, it is refused; removed, its credential is dead.
1423
    let id = job["job_id"].as_i64().unwrap();
1424
    let done = call(
1425
        &h.app,
1426
        "POST",
1427
        &format!("/api/v1/flow/jobs/{id}/finish"),
1428
        Some(&credential),
1429
        Some(r#"{"exit_code":0,"duration_ms":5}"#.into()),
1430
    )
1431
    .await;
1432
    assert_eq!(done.0, StatusCode::NO_CONTENT);
1433
    web("POST", format!("/admin/runners/{}/state", plex.id), Some(format!("_csrf={csrf}&state=disabled"))).await;
1434
    assert_eq!(claim_as(credential.clone()).await.0, StatusCode::FORBIDDEN);
1435
    let (_, page) = web("POST", format!("/admin/runners/{}/remove", plex.id), Some(format!("_csrf={csrf}"))).await;
1436
    assert!(page.contains("Removed plex."), "{page}");
1437
    assert_eq!(claim_as(credential).await.0, StatusCode::UNAUTHORIZED);
1438
}
1439
1440
/// Runner scopes (oxygenhub#41): a runner registered for one repository, or
1441
/// one owner, takes only those jobs; a site runner takes any.
1442
#[tokio::test(flavor = "multi_thread")]
1443
async fn scoped_runners_take_only_their_scope() {
1444
    use oxy_core::identity::SecretKey;
1445
    let h = hub().await;
1446
    create(&h.app, "andy", "demo").await;
1447
    create(&h.app, "andy", "other").await;
1448
    let register = |scope: db::runners::Scope, name: &'static str| {
1449
        let app = h.app.clone();
1450
        async move {
1451
            let token = format!("flowreg_{name}");
1452
            db::runners::add_registration(&app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &scope).await.unwrap();
1453
            let identity = SecretKey::generate().identity(name, "", 1);
1454
            let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1455
            let reg = serde_json::json!({ "token": token, "name": name, "identity": hex::encode(identity.encode()), "info": info });
1456
            let (st, body) = call(&app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1457
            assert_eq!(st, StatusCode::OK, "{body}");
1458
            serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string()
1459
        }
1460
    };
1461
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1462
    let only_demo = register(db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) }, "demo-runner").await;
1463
    let carols = register(db::runners::Scope { owner: "carol".into(), repo_id: None }, "carol-runner").await;
1464
    let andys = register(db::runners::Scope { owner: "andy".into(), repo_id: None }, "andy-runner").await;
1465
    let claim_as = |who: String| {
1466
        let app = h.app.clone();
1467
        async move {
1468
            let body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"] }).to_string();
1469
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(&who), Some(body)).await;
1470
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["repo"].as_str().unwrap().to_string())
1471
        }
1472
    };
1473
    // Jobs queued in andy/other only.
1474
    let work = tempfile::tempdir().unwrap();
1475
    let c = client(&format!("{}/andy/other", h.base), work.path());
1476
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1477
    c.snapshot("t").unwrap();
1478
    c.commit("pipeline", &[]).unwrap();
1479
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1480
    assert!(!runs_of(&h.app, "andy", "other").await.is_empty());
1481
    assert_eq!(claim_as(only_demo.clone()).await, None, "nothing of andy/demo is queued");
1482
    assert_eq!(claim_as(carols).await, None, "nothing of carol's");
1483
    assert_eq!(claim_as(andys).await.as_deref(), Some("andy/other"), "the owner's runner takes its repositories' jobs");
1484
    // The site runner (hub.toml) takes any.
1485
    assert_eq!(claim(&h.app).await.unwrap()["repo"], "andy/other");
1486
    assert_eq!(claim_as(only_demo).await, None, "still nothing of its own");
1487
}
1488
1489
/// Settings → Runners (oxygenhub#41, part 2b): a repository's admin adds a
1490
/// runner for that repository alone, sees which runners serve it, and
1491
/// removes only its own.
1492
#[tokio::test(flavor = "multi_thread")]
1493
async fn repository_admins_add_and_remove_their_own_runners() {
1494
    use oxy_core::identity::SecretKey;
1495
    let h = hub().await;
1496
    let res = oxygenhub::router(h.app.clone())
1497
        .oneshot(
1498
            Request::post("/register")
1499
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1500
                .body(Body::from("username=andy&email=andy%40example.com&password=correct-horse-battery&setup=test-setup"))
1501
                .unwrap(),
1502
        )
1503
        .await
1504
        .unwrap();
1505
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1506
    create(&h.app, "andy", "demo").await;
1507
    let demo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
1508
    let web = |method: &'static str, path: String, body: Option<String>| {
1509
        let (app, cookie) = (h.app.clone(), cookie.clone());
1510
        async move {
1511
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
1512
            if body.is_some() {
1513
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1514
            }
1515
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
1516
            let st = res.status();
1517
            (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1518
        }
1519
    };
1520
    let csrf_of = |page: &str| {
1521
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
1522
        page[i..].split('"').next().unwrap().to_string()
1523
    };
1524
    let (st, page) = web("GET", "/andy/demo/settings".into(), None).await;
1525
    assert_eq!(st, StatusCode::OK);
1526
    assert!(page.contains("<h2>Runners</h2>"), "the owner sees the section");
1527
    let (_, page) = web("POST", "/andy/demo/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1528
    let i = page.find("--token ").unwrap() + "--token ".len();
1529
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1530
    let identity = SecretKey::generate().identity("mine", "", 1);
1531
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
1532
    let reg = serde_json::json!({ "token": token, "name": "mine", "identity": hex::encode(identity.encode()), "info": info });
1533
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1534
    assert_eq!(st, StatusCode::OK, "{body}");
1535
    let mine = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "mine").unwrap();
1536
    assert_eq!(mine.scope(), db::runners::Scope { owner: "andy".into(), repo_id: Some(demo.id) });
1537
    // The site's runner (hub.toml, from its first claim) serves it too, but is not the owner's to remove.
1538
    claim(&h.app).await;
1539
    let site = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "test-1").unwrap();
1540
    let (_, page) = web("GET", "/andy/demo/settings".into(), None).await;
1541
    assert!(page.contains("<strong>mine</strong>") && page.contains("this repository"), "{page}");
1542
    assert!(page.contains("<strong>test-1</strong>") && page.contains("the whole site"), "{page}");
1543
    let csrf = csrf_of(&page);
1544
    let (st, _) = web("POST", format!("/andy/demo/settings/runners/{}/remove", site.id), Some(format!("_csrf={csrf}"))).await;
1545
    assert_eq!(st, StatusCode::NOT_FOUND, "not the repository's own");
1546
    let (_, page) = web("POST", format!("/andy/demo/settings/runners/{}/remove", mine.id), Some(format!("_csrf={csrf}"))).await;
1547
    assert!(page.contains("mine removed"), "{page}");
1548
    assert!(db::runners::get(&h.app.db, mine.id).await.unwrap().is_none());
1549
1550
    // The same for an organisation's owner.
1551
    let (_, page) = web("GET", "/orgs/new".into(), None).await;
1552
    web("POST", "/orgs/new".into(), Some(format!("_csrf={}&name=acme&display_name=Acme", csrf_of(&page)))).await;
1553
    let (st, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1554
    assert_eq!(st, StatusCode::OK);
1555
    let (_, page) = web("POST", "/orgs/acme/settings/runners/token".into(), Some(format!("_csrf={}", csrf_of(&page)))).await;
1556
    let i = page.find("--token ").unwrap() + "--token ".len();
1557
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
1558
    let identity = SecretKey::generate().identity("acme-runner", "", 1);
1559
    let reg = serde_json::json!({ "token": token, "name": "acme-runner", "identity": hex::encode(identity.encode()), "info": info });
1560
    assert_eq!(call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await.0, StatusCode::OK);
1561
    let acme = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "acme-runner").unwrap();
1562
    assert_eq!(acme.scope(), db::runners::Scope { owner: "acme".into(), repo_id: None });
1563
    let (_, page) = web("GET", "/orgs/acme/settings".into(), None).await;
1564
    assert!(page.contains("<strong>acme-runner</strong>") && page.contains("the organisation's repositories"), "{page}");
1565
    let (_, page) = web("POST", format!("/orgs/acme/settings/runners/{}/remove", acme.id), Some(format!("_csrf={}", csrf_of(&page)))).await;
1566
    assert!(page.contains("acme-runner removed"), "{page}");
1567
}
1568
1569
/// runs-on (oxygenhub#41, part 3): a job that asks for a label goes only to
1570
/// a runner that has it, and waits for one otherwise.
1571
#[tokio::test(flavor = "multi_thread")]
1572
async fn jobs_that_ask_for_labels_wait_for_a_runner_with_them() {
1573
    use oxy_core::identity::SecretKey;
1574
    let h = hub().await;
1575
    create(&h.app, "andy", "demo").await;
1576
    let work = tempfile::tempdir().unwrap();
1577
    let c = client(&format!("{}/andy/demo", h.base), work.path());
1578
    let cross = "job \"cross\" {\n    sandbox \"alpine\"\n    runs-on \"riscv64\"\n    exec \"true\"\n}\n";
1579
    write(work.path(), ".flow/pipeline.kdl", &pipeline(cross));
1580
    c.snapshot("t").unwrap();
1581
    c.commit("pipeline", &[]).unwrap();
1582
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1583
    assert!(!runs_of(&h.app, "andy", "demo").await.is_empty());
1584
    // The site runner has no labels: it takes the others, never cross.
1585
    let mut taken = Vec::new();
1586
    while let Some(j) = claim(&h.app).await {
1587
        taken.push(j["job"]["name"].as_str().unwrap().to_string());
1588
    }
1589
    assert!(!taken.contains(&"cross".to_string()) && taken.contains(&"lint".to_string()), "{taken:?}");
1590
    let queue = db::flow::queue(&h.app.db).await.unwrap();
1591
    let waiting = queue.iter().find(|q| q.job == "cross").unwrap();
1592
    assert_eq!((waiting.status.as_str(), waiting.needs()), ("queued", vec!["riscv64".to_string()]));
1593
    // A runner registered with the label takes it.
1594
    let token = "flowreg_riscv";
1595
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
1596
    let identity = SecretKey::generate().identity("visionfive", "", 1);
1597
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": ["riscv64"], "max_jobs": 1 });
1598
    let reg = serde_json::json!({ "token": token, "name": "visionfive", "identity": hex::encode(identity.encode()), "info": info });
1599
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
1600
    assert_eq!(st, StatusCode::OK, "{body}");
1601
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
1602
    let claim_body = serde_json::json!({ "runner": "x", "runtimes": ["microvm"], "info": info }).to_string();
1603
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(claim_body)).await;
1604
    assert_eq!(st, StatusCode::OK, "{body}");
1605
    assert_eq!(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"], "cross");
1606
}
1607
1608
/// oxygenhub#71: a job its runner stopped reporting (restarted, or lost
1609
/// the hub as the job ended) is ended once it has run past the time limit
1610
/// and a grace: an error with the reason, its dependents skipped and its
1611
/// run settled, as if the runner had reported the error.
1612
#[tokio::test(flavor = "multi_thread")]
1613
async fn a_job_no_runner_reports_is_ended_after_the_time_limit() {
1614
    let h = hub().await;
1615
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1616
    create(&h.app, "andy", "lost").await;
1617
    let url = format!("{}/andy/lost", h.base);
1618
    let work = tempfile::tempdir().unwrap();
1619
    let c = client(&url, work.path());
1620
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1621
    write(work.path(), "test.sh", "echo ok\n");
1622
    c.commit("Add a pipeline", &[]).unwrap();
1623
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1624
    assert_eq!(runs_of(&h.app, "andy", "lost").await.len(), 1);
1625
    let job = claim(&h.app).await.expect("a job to claim");
1626
    let id = job["job_id"].as_i64().unwrap();
1627
1628
    // Running, but well within the limit: left alone.
1629
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 0);
1630
    // Started long ago and never reported: ended.
1631
    let old = db::now_ms() - 24 * 3600 * 1000;
1632
    sqlx::query("UPDATE flow_jobs SET started_ms = ? WHERE id = ?").bind(old).bind(id).execute(&h.app.db).await.unwrap();
1633
    assert_eq!(oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap(), 1);
1634
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1635
    assert_eq!(j.status, "error");
1636
    assert!(j.error.starts_with("lost:"), "{}", j.error);
1637
    let run = &runs_of(&h.app, "andy", "lost").await[0];
1638
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
1639
    assert!(jobs.iter().all(|j| j.status != "running"), "nothing left running");
1640
    // A late report, should one come, does not overwrite the ending.
1641
    assert_ne!(finish(&h.app, id, serde_json::json!({ "exit_code": 0 })).await, StatusCode::NO_CONTENT);
1642
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "error");
1643
}
1644
1645
/// oxygenhub#73: a runner that lists the images it holds is offered only
1646
/// the jobs whose rootfs is among them; one that does not say gets any.
1647
#[tokio::test(flavor = "multi_thread")]
1648
async fn a_runner_is_offered_only_jobs_whose_image_it_holds() {
1649
    let h = hub().await;
1650
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1651
    create(&h.app, "andy", "images").await;
1652
    let url = format!("{}/andy/images", h.base);
1653
    let work = tempfile::tempdir().unwrap();
1654
    let c = client(&url, work.path());
1655
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1656
    write(work.path(), "test.sh", "echo ok\n");
1657
    c.commit("Add a pipeline", &[]).unwrap();
1658
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1659
    assert_eq!(runs_of(&h.app, "andy", "images").await.len(), 1);
1660
    let claim_with = |images: Vec<String>| {
1661
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "images": images }).to_string();
1662
        let app = h.app.clone();
1663
        async move {
1664
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await;
1665
            (st, body)
1666
        }
1667
    };
1668
    let (st, _) = claim_with(vec!["ab".repeat(32)]).await;
1669
    assert_eq!(st, StatusCode::NO_CONTENT, "no job for a runner without the image");
1670
    let jobs = db::flow::jobs(&h.app.db, runs_of(&h.app, "andy", "images").await[0].id).await.unwrap();
1671
    let rootfs: serde_json::Value = serde_json::from_str(&jobs[0].sandbox).unwrap();
1672
    let rootfs = rootfs["rootfs"].as_str().unwrap().to_string();
1673
    let (st, body) = claim_with(vec!["ab".repeat(32), rootfs]).await;
1674
    assert_eq!(st, StatusCode::OK, "{body}");
1675
}
1676
1677
/// oxygenhub#71: a runner that lists the jobs it holds has the others it
1678
/// was given ended at once (it restarted, or never received them), not at
1679
/// the time limit; a held job is left alone.
1680
#[tokio::test(flavor = "multi_thread")]
1681
async fn a_job_its_runner_no_longer_holds_is_ended_at_its_next_claim() {
1682
    let h = hub().await;
1683
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1684
    create(&h.app, "andy", "held").await;
1685
    let url = format!("{}/andy/held", h.base);
1686
    let work = tempfile::tempdir().unwrap();
1687
    let c = client(&url, work.path());
1688
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
1689
    write(work.path(), "test.sh", "echo ok\n");
1690
    c.commit("Add a pipeline", &[]).unwrap();
1691
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1692
    assert_eq!(runs_of(&h.app, "andy", "held").await.len(), 1);
1693
    let id = claim(&h.app).await.expect("a job to claim")["job_id"].as_i64().unwrap();
1694
    let claim_holding = |holding: Vec<i64>| {
1695
        let body = serde_json::json!({ "runner": "test-1", "runtimes": ["microvm"], "holding": holding }).to_string();
1696
        let app = h.app.clone();
1697
        async move { call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body)).await.0 }
1698
    };
1699
    claim_holding(vec![id]).await;
1700
    assert_eq!(db::flow::job(&h.app.db, id).await.unwrap().unwrap().status, "running", "a held job stays");
1701
    claim_holding(vec![]).await;
1702
    let j = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
1703
    assert_eq!(j.status, "error");
1704
    assert!(j.error.starts_with("lost:") && j.error.contains("no longer holds"), "{}", j.error);
1705
    let run = &runs_of(&h.app, "andy", "held").await[0];
1706
    assert!(db::flow::jobs(&h.app.db, run.id).await.unwrap().iter().all(|j| j.status != "running"), "the run settles");
1707
}
1708
1709
/// oxygen#59: a job with a `scope` runs on a push only when the push's
1710
/// changes touch a path it names (a release job, when Cargo.toml's version
1711
/// moves); a bookmark's first run and manual runs have every job.
1712
#[tokio::test(flavor = "multi_thread")]
1713
async fn a_scoped_job_runs_only_when_a_push_touches_its_paths() {
1714
    let h = hub().await;
1715
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1716
    create(&h.app, "andy", "scoped").await;
1717
    let url = format!("{}/andy/scoped", h.base);
1718
    let work = tempfile::tempdir().unwrap();
1719
    let c = client(&url, work.path());
1720
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\" \"packaging/**\"\n    exec \"true\"\n}\n";
1721
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1722
    write(work.path(), "test.sh", "echo ok\n");
1723
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1724
    c.commit("Start", &[]).unwrap();
1725
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1726
    let names = |app: Shared, n: usize| async move {
1727
        let mut runs = Vec::new();
1728
        for _ in 0..100 {
1729
            runs = runs_of(&app, "andy", "scoped").await;
1730
            if runs.len() >= n {
1731
                break;
1732
            }
1733
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1734
        }
1735
        assert_eq!(runs.len(), n, "runs");
1736
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1737
        j.sort();
1738
        // Passed, so the next push is scoped against it, not superseding it.
1739
        sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = ?").bind(runs[0].id).execute(&app.db).await.unwrap();
1740
        j
1741
    };
1742
    assert_eq!(names(h.app.clone(), 1).await, ["build", "dist", "lint", "test"], "the first run has every job");
1743
    write(work.path(), "test.sh", "echo still ok\n");
1744
    c.commit("Edit the test", &[]).unwrap();
1745
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1746
    assert_eq!(names(h.app.clone(), 2).await, ["build", "lint", "test"], "dist is out of scope");
1747
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1748
    c.commit("Release 0.1.1", &[]).unwrap();
1749
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1750
    assert_eq!(names(h.app.clone(), 3).await, ["build", "dist", "lint", "test"], "a version bump runs dist");
1751
}
1752
1753
/// oxygenflow#32: a run still going is cancelled from the API, the web or
1754
/// by a newer push to its bookmark; its runner is refused from then on,
1755
/// and the next push is scoped past the cancelled run.
1756
#[tokio::test(flavor = "multi_thread")]
1757
async fn runs_are_cancelled_by_hand_or_by_a_newer_push() {
1758
    let h = hub().await;
1759
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1760
    create(&h.app, "andy", "stop").await;
1761
    let url = format!("{}/andy/stop", h.base);
1762
    let work = tempfile::tempdir().unwrap();
1763
    let c = client(&url, work.path());
1764
    let extra = "job \"dist\" {\n    sandbox \"alpine\"\n    scope \"Cargo.toml\"\n    exec \"true\"\n}\n";
1765
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1766
    write(work.path(), "test.sh", "echo ok\n");
1767
    write(work.path(), "Cargo.toml", "version = \"0.1.0\"\n");
1768
    c.commit("Start", &[]).unwrap();
1769
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1770
    let wait_runs = |app: Shared, n: usize| async move {
1771
        for _ in 0..100 {
1772
            let runs = runs_of(&app, "andy", "stop").await;
1773
            if runs.len() >= n {
1774
                return runs;
1775
            }
1776
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1777
        }
1778
        panic!("no run {n}");
1779
    };
1780
    let first = wait_runs(h.app.clone(), 1).await;
1781
    sqlx::query("UPDATE flow_runs SET status = 'passed' WHERE id = ?").bind(first[0].id).execute(&h.app.db).await.unwrap();
1782
    sqlx::query("UPDATE flow_jobs SET status = 'passed' WHERE run_id = ?").bind(first[0].id).execute(&h.app.db).await.unwrap();
1783
1784
    // Run 2 (a version bump) has a job running when run 3 is pushed.
1785
    write(work.path(), "Cargo.toml", "version = \"0.1.1\"\n");
1786
    c.commit("Release 0.1.1", &[]).unwrap();
1787
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1788
    wait_runs(h.app.clone(), 2).await;
1789
    let job = claim(&h.app).await.expect("a job of run 2");
1790
    let id = job["job_id"].as_i64().unwrap();
1791
    write(work.path(), "test.sh", "echo still ok\n");
1792
    c.commit("Edit the test", &[]).unwrap();
1793
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1794
    let runs = wait_runs(h.app.clone(), 3).await;
1795
    let third = &runs[0];
1796
    let mut second = runs[1].clone();
1797
    for _ in 0..100 {
1798
        second = db::flow::run_by_id(&h.app.db, runs[1].id).await.unwrap().unwrap();
1799
        if !second.live() {
1800
            break;
1801
        }
1802
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1803
    }
1804
    assert_eq!(second.status, "cancelled", "a newer push supersedes a run still going");
1805
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
1806
    assert!(jobs.iter().all(|j| j.status == "cancelled" && j.error == "superseded by run #3"), "{jobs:?}");
1807
    let mut names: Vec<String> = db::flow::jobs(&h.app.db, third.id).await.unwrap().into_iter().map(|j| j.name).collect();
1808
    names.sort();
1809
    assert_eq!(names, ["build", "dist", "lint", "test"], "run 3 also checks what run 2 would have: the version bump");
1810
    let mut checks = vec![];
1811
    for _ in 0..100 {
1812
        checks = db::hooks::checks_for_state(&h.app.db, second.repo_id, &second.state).await.unwrap();
1813
        if checks.iter().all(|c| c.status == "cancelled") {
1814
            break;
1815
        }
1816
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1817
    }
1818
    assert!(checks.iter().all(|c| c.status == "cancelled"), "{checks:?}");
1819
    // The runner of the cancelled job is refused, so it stops the job.
1820
    let (st, _) =
1821
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(r#"{"records":[]}"#.into())).await;
1822
    assert_eq!(st, StatusCode::CONFLICT);
1823
1824
    // By hand: the API, then a run already ended is refused.
1825
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1826
    assert_eq!(st, StatusCode::OK, "{body}");
1827
    let third = db::flow::run_by_id(&h.app.db, third.id).await.unwrap().unwrap();
1828
    assert_eq!(third.status, "cancelled");
1829
    assert!(db::flow::jobs(&h.app.db, third.id).await.unwrap().iter().all(|j| j.error == "cancelled by andy"));
1830
    let (st, body) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", Some("site"), None).await;
1831
    assert!(st == StatusCode::CONFLICT && body.contains("already cancelled"), "{st} {body}");
1832
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/stop/flow/runs/3/cancel", None, None).await;
1833
    assert_ne!(st, StatusCode::OK, "anonymous callers cannot cancel");
1834
    let (_, page) = call(&h.app, "GET", "/andy/stop/flow/3", None, None).await;
1835
    assert!(page.contains("⊘") && !page.contains("CANCEL</button>"), "a cancelled run shows so, with no button");
1836
}
1837
1838
/// oxygenflow#23 and oxygenhub#89: a job runs under its pipeline's
1839
/// timeout, capped at the site's maximum, else the site's default; and the
1840
/// hub gives a job up only past its own limit.
1841
#[tokio::test(flavor = "multi_thread")]
1842
async fn a_job_runs_under_its_own_time_limit_within_the_sites() {
1843
    let h = hub().await;
1844
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1845
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_DEFAULT, "30").await.unwrap();
1846
    db::accounts::set_setting(&h.app.db, oxygenhub::flow::SETTING_MAX, "120").await.unwrap();
1847
    create(&h.app, "andy", "limits").await;
1848
    let url = format!("{}/andy/limits", h.base);
1849
    let work = tempfile::tempdir().unwrap();
1850
    let c = client(&url, work.path());
1851
    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";
1852
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1853
    write(work.path(), "test.sh", "echo ok\n");
1854
    c.commit("Add a pipeline", &[]).unwrap();
1855
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1856
    assert_eq!(runs_of(&h.app, "andy", "limits").await.len(), 1);
1857
    let mut limits = std::collections::HashMap::new();
1858
    let mut ids = std::collections::HashMap::new();
1859
    while let Some(j) = claim(&h.app).await {
1860
        let name = j["job"]["name"].as_str().unwrap().to_string();
1861
        limits.insert(name.clone(), j["timeout_s"].as_u64().unwrap());
1862
        ids.insert(name, j["job_id"].as_i64().unwrap());
1863
    }
1864
    assert_eq!(limits["slow"], 5400, "its own");
1865
    assert_eq!(limits["huge"], 7200, "cut to the site's maximum");
1866
    assert_eq!(limits["build"], 1800, "the site's default");
1867
    // 40 minutes in: past the default and its grace, within slow's limit.
1868
    let started = db::now_ms() - 40 * 60 * 1000;
1869
    sqlx::query("UPDATE flow_jobs SET started_ms = ?").bind(started).execute(&h.app.db).await.unwrap();
1870
    oxygenhub::flow::reap_lost_jobs(&h.app).await.unwrap();
1871
    let status = |id: i64| {
1872
        let app = h.app.clone();
1873
        async move { db::flow::job(&app.db, id).await.unwrap().unwrap().status }
1874
    };
1875
    assert_eq!(status(ids["build"]).await, "error", "past its 30 minutes");
1876
    assert_eq!(status(ids["slow"]).await, "running", "within its 90");
1877
    assert_eq!(status(ids["huge"]).await, "running", "within its 120");
1878
}
1879
1880
/// oxygenflow#24: a job's `on` decides which events start it: a pushed
1881
/// tag runs only the jobs that name it; a push to a bookmark the pipeline
1882
/// does not name starts no run; a rerun repeats its run's event.
1883
#[tokio::test(flavor = "multi_thread")]
1884
async fn on_decides_which_events_start_a_job() {
1885
    let h = hub().await;
1886
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1887
    create(&h.app, "andy", "events").await;
1888
    let url = format!("{}/andy/events", h.base);
1889
    let work = tempfile::tempdir().unwrap();
1890
    let c = client(&url, work.path());
1891
    let text = format!(
1892
        "on {{\n    push \"main\"\n    manual\n}}\n{}job \"dist\" {{\n    sandbox \"alpine\"\n    on {{\n        tag \"v*\"\n    }}\n    exec \"true\"\n}}\n",
1893
        pipeline("")
1894
    );
1895
    // `on` must come after schema-version; pipeline() starts with it.
1896
    let text = text.replacen(
1897
        "on {\n    push \"main\"\n    manual\n}\nschema-version 1\n",
1898
        "schema-version 1\non {\n    push \"main\"\n    manual\n}\n",
1899
        1,
1900
    );
1901
    write(work.path(), ".flow/pipeline.kdl", &text);
1902
    write(work.path(), "test.sh", "echo ok\n");
1903
    c.commit("Start", &[]).unwrap();
1904
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1905
    let jobs_of_latest = |app: Shared, n: usize| async move {
1906
        let mut runs = Vec::new();
1907
        for _ in 0..100 {
1908
            runs = runs_of(&app, "andy", "events").await;
1909
            if runs.len() >= n {
1910
                break;
1911
            }
1912
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1913
        }
1914
        assert_eq!(runs.len(), n, "runs");
1915
        let mut j: Vec<String> = db::flow::jobs(&app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1916
        j.sort();
1917
        (runs[0].clone(), j)
1918
    };
1919
    let (_, j) = jobs_of_latest(h.app.clone(), 1).await;
1920
    assert_eq!(j, ["build", "lint", "test"], "a push to main: no dist");
1921
    // A tag: only dist.
1922
    let heads = c.bookmark_heads().unwrap();
1923
    c.tag_create("v1.0.0", &heads, "first").unwrap();
1924
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1925
    let (run, j) = jobs_of_latest(h.app.clone(), 2).await;
1926
    assert_eq!(j, ["dist"], "a tag runs only what names it");
1927
    assert_eq!(run.trigger, "tag:v1.0.0");
1928
    // A rerun repeats the tag's event.
1929
    let row = db::repos::get(&h.app.db, "andy", "events").await.unwrap().unwrap();
1930
    db::flow::finish(
1931
        &h.app.db,
1932
        db::flow::jobs(&h.app.db, run.id).await.unwrap()[0].id,
1933
        db::flow::Outcome { status: "passed", exit_code: Some(0), error: "", receipt: "", receipt_hash: "" },
1934
    )
1935
    .await
1936
    .unwrap();
1937
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
1938
    oxygenhub::flow::rerun(&h.app, &row, &run, "andy").await.unwrap();
1939
    let (_, j) = jobs_of_latest(h.app.clone(), 3).await;
1940
    assert_eq!(j, ["dist"], "the rerun is the tag's run again");
1941
    // A bookmark the pipeline does not name starts nothing.
1942
    c.bookmark_create("develop", None).unwrap();
1943
    assert!(c.push_bookmark("origin", "develop", false).unwrap().iter().all(|r| r.ok));
1944
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
1945
    assert_eq!(runs_of(&h.app, "andy", "events").await.len(), 3, "no run for develop");
1946
}
1947
1948
/// oxygenflow#24: a job with a `schedule` line runs on the default
1949
/// bookmark when the line comes due, and only then; other jobs stay out.
1950
#[tokio::test(flavor = "multi_thread")]
1951
async fn scheduled_jobs_run_when_due() {
1952
    let h = hub().await;
1953
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
1954
    create(&h.app, "andy", "nightly").await;
1955
    let url = format!("{}/andy/nightly", h.base);
1956
    let work = tempfile::tempdir().unwrap();
1957
    let c = client(&url, work.path());
1958
    // An odd minute, so the hub's own ticker cannot fire it during the test.
1959
    let extra = "job \"nightly\" {\n    sandbox \"alpine\"\n    on {\n        schedule \"17 4 29 2 *\"\n    }\n    exec \"true\"\n}\n";
1960
    write(work.path(), ".flow/pipeline.kdl", &pipeline(extra));
1961
    write(work.path(), "test.sh", "echo ok\n");
1962
    c.commit("Start", &[]).unwrap();
1963
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
1964
    assert_eq!(runs_of(&h.app, "andy", "nightly").await.len(), 1);
1965
    let first = runs_of(&h.app, "andy", "nightly").await;
1966
    let names: Vec<String> = db::flow::jobs(&h.app.db, first[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1967
    assert!(!names.contains(&"nightly".to_string()), "a push does not run a scheduled job");
1968
    use flow_core::pipeline::When;
1969
    let not_yet = When { minute: 16, hour: 4, day: 29, month: 2, weekday: 4 };
1970
    assert_eq!(oxygenhub::flow::run_due(&h.app, not_yet).await, 0);
1971
    let due = When { minute: 17, ..not_yet };
1972
    assert_eq!(oxygenhub::flow::run_due(&h.app, due).await, 1);
1973
    let runs = runs_of(&h.app, "andy", "nightly").await;
1974
    assert_eq!(runs.len(), 2);
1975
    assert_eq!(runs[0].trigger, "schedule");
1976
    let names: Vec<String> = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap().into_iter().map(|j| j.name).collect();
1977
    assert_eq!(names, ["nightly"]);
1978
    assert_eq!(runs[0].bookmark, "main", "on the default bookmark");
1979
}
1980
1981
#[tokio::test(flavor = "multi_thread")]
1982
async fn variables_from_three_levels_reach_a_job_inner_overriding_outer() {
1983
    use oxygenhub::levels::Scope;
1984
    use oxygenhub::variables;
1985
    let h = hub().await;
1986
    let app = &h.app;
1987
    // Andy, the site's administrator, owns the acme organisation.
1988
    let res = oxygenhub::router(app.clone())
1989
        .oneshot(
1990
            Request::post("/register")
1991
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
1992
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
1993
                .unwrap(),
1994
        )
1995
        .await
1996
        .unwrap();
1997
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
1998
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
1999
    db::accounts::create_org(&app.db, "acme", "Acme", andy.id).await.unwrap();
2000
    create(app, "acme", "app").await;
2001
    let page = |path: &str, form: Option<String>| {
2002
        let mut req =
2003
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2004
        if form.is_some() {
2005
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2006
        }
2007
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2008
        let app = app.clone();
2009
        async move {
2010
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2011
            let status = res.status();
2012
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2013
            (status, body)
2014
        }
2015
    };
2016
    let csrf_of = |page: &str| {
2017
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2018
        page[i..].split('"').next().unwrap().to_string()
2019
    };
2020
2021
    // The site sets CC and LANG, the organisation its own CC, the
2022
    // repository RUST_LOG from its settings page.
2023
    variables::set(&app.db, Scope::Site, "CC", "gcc").await.unwrap();
2024
    variables::set(&app.db, Scope::Site, "LANG", "C").await.unwrap();
2025
    let org = db::accounts::org_by_name(&app.db, "acme").await.unwrap().unwrap();
2026
    variables::set(&app.db, Scope::Org(org.id), "CC", "clang").await.unwrap();
2027
    let (st, settings) = page("/acme/app/settings", None).await;
2028
    assert_eq!(st, StatusCode::OK, "{settings}");
2029
    assert!(settings.contains("Inherited") && settings.contains("the acme organisation") && settings.contains("overridden"), "{settings}");
2030
    let csrf = csrf_of(&settings);
2031
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=RUST_LOG&value=debug"))).await;
2032
    assert!(body.contains("RUST_LOG set.") && body.contains("<code>debug</code>"), "{body}");
2033
    let (_, body) = page("/acme/app/settings/variables", Some(format!("_csrf={csrf}&action=set&name=FLOW_REPO&value=x"))).await;
2034
    assert!(body.contains("not FLOW_"), "{body}");
2035
    let repo = db::repos::get(&app.db, "acme", "app").await.unwrap().unwrap();
2036
    db::repos::set_flow(&app.db, repo.id, "on").await.unwrap();
2037
    let env = variables::env_for_repo(&app.db, &repo).await.unwrap();
2038
    assert_eq!(
2039
        env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect::<Vec<_>>(),
2040
        [("CC", "clang"), ("LANG", "C"), ("RUST_LOG", "debug")],
2041
        "the organisation's CC wins over the site's"
2042
    );
2043
2044
    // A claim carries them.
2045
    let url = format!("{}/acme/app", h.base);
2046
    let work = tempfile::tempdir().unwrap();
2047
    let c = client(&url, work.path());
2048
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2049
    write(work.path(), "test.sh", "echo ok\n");
2050
    c.snapshot("test").unwrap();
2051
    c.commit("Add a pipeline", &[]).unwrap();
2052
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2053
    let runs = runs_of(app, "acme", "app").await;
2054
    assert_eq!(runs.len(), 1, "{runs:?}");
2055
    let got = claim(app).await.unwrap_or_else(|| panic!("a job: {:?}", runs[0]));
2056
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "LANG": "C", "RUST_LOG": "debug" }), "{got}");
2057
2058
    // Removing a site variable from the admin page takes effect at the next claim.
2059
    let (_, admin) = page("/admin", None).await;
2060
    assert!(admin.contains("Variables") && admin.contains("<code>gcc</code>"), "{admin}");
2061
    let (_, body) = page("/admin/variables", Some(format!("_csrf={}&action=delete&name=LANG", csrf_of(&admin)))).await;
2062
    assert!(body.contains("LANG removed."), "{body}");
2063
    let got = claim(app).await.expect("another job");
2064
    assert_eq!(got["env"], serde_json::json!({ "CC": "clang", "RUST_LOG": "debug" }), "{got}");
2065
}
2066
2067
#[tokio::test(flavor = "multi_thread")]
2068
async fn secrets_a_job_declares_come_with_the_claim_and_never_reach_the_log() {
2069
    let h = hub().await;
2070
    let app = &h.app;
2071
    let res = oxygenhub::router(app.clone())
2072
        .oneshot(
2073
            Request::post("/register")
2074
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
2075
                .body(Body::from("username=andy&email=a%40example.com&password=correct-horse-battery&setup=test-setup"))
2076
                .unwrap(),
2077
        )
2078
        .await
2079
        .unwrap();
2080
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
2081
    let page = |path: &str, form: Option<String>| {
2082
        let mut req =
2083
            Request::builder().method(if form.is_some() { "POST" } else { "GET" }).uri(path).header(header::COOKIE, cookie.clone());
2084
        if form.is_some() {
2085
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
2086
        }
2087
        let req = req.body(Body::from(form.unwrap_or_default())).unwrap();
2088
        let app = app.clone();
2089
        async move {
2090
            let res = oxygenhub::router(app).oneshot(req).await.unwrap();
2091
            let status = res.status();
2092
            let body = String::from_utf8(res.into_body().collect().await.unwrap().to_bytes().to_vec()).unwrap();
2093
            (status, body)
2094
        }
2095
    };
2096
    let csrf_of = |page: &str| {
2097
        let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
2098
        page[i..].split('"').next().unwrap().to_string()
2099
    };
2100
    create(app, "andy", "demo").await;
2101
    // The site sets deploy-token; the repository overrides it. Neither
2102
    // page shows a value, only that it is set.
2103
    let (_, admin) = page("/admin", None).await;
2104
    let csrf = csrf_of(&admin);
2105
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=deploy-token&value=site-level-value"))).await;
2106
    assert!(body.contains("deploy-token set.") && !body.contains("site-level-value"), "{body}");
2107
    let (_, body) = page("/admin/secrets", Some(format!("_csrf={csrf}&action=set&name=bad+name&value=x"))).await;
2108
    assert!(body.contains("name is 1 to 64 of"), "{body}");
2109
    let (_, settings) = page("/andy/demo/settings", None).await;
2110
    assert!(
2111
        settings.contains("Secrets") && settings.contains("<code>deploy-token</code>") && settings.contains("the site</td>"),
2112
        "{settings}"
2113
    );
2114
    let csrf_r = csrf_of(&settings);
2115
    let (_, body) =
2116
        page("/andy/demo/settings/secrets", Some(format!("_csrf={csrf_r}&action=set&name=deploy-token&value=hunter22-repo-value"))).await;
2117
    assert!(body.contains("deploy-token set.") && body.contains("overridden") && !body.contains("hunter22"), "{body}");
2118
    let repo = db::repos::get(&app.db, "andy", "demo").await.unwrap().unwrap();
2119
    assert!(
2120
        !String::from_utf8_lossy(&oxygenhub::secrets::list(&app.db, oxygenhub::levels::Scope::Repo(repo.id)).await.unwrap()[0].value)
2121
            .contains("hunter22"),
2122
        "sealed at rest"
2123
    );
2124
2125
    // A job that declares the secret, and one the levels do not hold.
2126
    let url = format!("{}/andy/demo", h.base);
2127
    let work = tempfile::tempdir().unwrap();
2128
    let c = client(&url, work.path());
2129
    write(
2130
        work.path(),
2131
        ".flow/pipeline.kdl",
2132
        &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"),
2133
    );
2134
    write(work.path(), "test.sh", "echo ok\n");
2135
    c.snapshot("test").unwrap();
2136
    c.commit("Add a pipeline", &[]).unwrap();
2137
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2138
    let runs = runs_of(app, "andy", "demo").await;
2139
    let jobs = match runs.first() {
2140
        Some(r) => db::flow::jobs(&app.db, r.id).await.unwrap().iter().map(|j| format!("{}:{}", j.name, j.status)).collect::<Vec<_>>(),
2141
        None => vec![],
2142
    };
2143
    let mut deploy = None;
2144
    for _ in 0..50 {
2145
        let Some(got) = claim(app).await else {
2146
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2147
            continue;
2148
        };
2149
        if got["job"]["name"] == "deploy" {
2150
            deploy = Some(got);
2151
            break;
2152
        }
2153
        assert_eq!(got["secrets"], serde_json::Value::Null, "{got}");
2154
    }
2155
    let got = deploy.unwrap_or_else(|| panic!("the deploy job: runs {runs:?} jobs {jobs:?}"));
2156
    assert_eq!(
2157
        got["secrets"],
2158
        serde_json::json!([{ "name": "deploy-token", "path": "/run/secrets/token", "value": "hunter22-repo-value" }]),
2159
        "the repository's value, the missing one left out: {got}"
2160
    );
2161
    let id = got["job_id"].as_i64().unwrap();
2162
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2163
    assert!(log.iter().any(|l| l.stream == "flow" && l.text.contains("secret \"missing\" is not set")), "{log:?}");
2164
2165
    // The value never reaches the stored log, plain or base64.
2166
    let records = serde_json::json!({ "records": [
2167
        { "t": 1, "stream": "out", "text": "token=hunter22-repo-value" },
2168
        { "t": 2, "stream": "err", "text": "b64 aHVudGVyMjItcmVwby12YWx1ZQ== end" },
2169
    ] });
2170
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2171
    assert_eq!(st, StatusCode::NO_CONTENT);
2172
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2173
    let texts: Vec<&str> = log.iter().map(|l| l.text.as_str()).collect();
2174
    assert!(texts.contains(&"token=***") && texts.contains(&"b64 *** end"), "{texts:?}");
2175
    assert!(!texts.iter().any(|t| t.contains("hunter22")), "{texts:?}");
2176
}
2177
2178
#[tokio::test(flavor = "multi_thread")]
2179
async fn a_job_s_identity_is_a_signed_token_the_discovery_document_lets_anyone_verify() {
2180
    let h = hub().await;
2181
    let app = &h.app;
2182
    let (st, disc) = call(app, "GET", "/.well-known/openid-configuration", None, None).await;
2183
    assert_eq!(st, StatusCode::OK, "{disc}");
2184
    let disc: serde_json::Value = serde_json::from_str(&disc).unwrap();
2185
    assert_eq!(disc["issuer"], h.base.as_str());
2186
    assert_eq!(disc["jwks_uri"], format!("{}/.well-known/jwks.json", h.base));
2187
    let (st, jwks) = call(app, "GET", "/.well-known/jwks.json", None, None).await;
2188
    assert_eq!(st, StatusCode::OK, "{jwks}");
2189
    let jwks: serde_json::Value = serde_json::from_str(&jwks).unwrap();
2190
    assert_eq!(jwks["keys"][0]["alg"], "RS256");
2191
    let kid = jwks["keys"][0]["kid"].as_str().unwrap().to_string();
2192
2193
    create(app, "andy", "demo").await;
2194
    let url = format!("{}/andy/demo", h.base);
2195
    let work = tempfile::tempdir().unwrap();
2196
    let c = client(&url, work.path());
2197
    write(
2198
        work.path(),
2199
        ".flow/pipeline.kdl",
2200
        &pipeline("job \"deploy\" {\n    sandbox \"alpine\"\n    identity \"sts.amazonaws.com\" {\n        mount-path \"/run/secrets/aws-token\"\n    }\n    exec \"deploy\"\n}\n"),
2201
    );
2202
    write(work.path(), "test.sh", "echo ok\n");
2203
    c.snapshot("test").unwrap();
2204
    c.commit("Add a pipeline", &[]).unwrap();
2205
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2206
    let mut deploy = None;
2207
    for _ in 0..50 {
2208
        let Some(got) = claim(app).await else {
2209
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2210
            continue;
2211
        };
2212
        if got["job"]["name"] == "deploy" {
2213
            deploy = Some(got);
2214
            break;
2215
        }
2216
    }
2217
    let got = deploy.expect("the deploy job");
2218
    let secrets = got["secrets"].as_array().expect("secrets");
2219
    assert_eq!(secrets.len(), 1);
2220
    assert_eq!(
2221
        (secrets[0]["name"].as_str(), secrets[0]["path"].as_str()),
2222
        (Some("identity:sts.amazonaws.com"), Some("/run/secrets/aws-token"))
2223
    );
2224
    let token = secrets[0]["value"].as_str().unwrap().to_string();
2225
    let issuer = app.oidc().await.unwrap();
2226
    assert_eq!(issuer.kid, kid, "the key the JWKS publishes signed it");
2227
    let claims = issuer.verify(&token, "sts.amazonaws.com", db::now_ms()).expect("verifies");
2228
    assert_eq!(claims["sub"], "repo:andy/demo:bookmark:main");
2229
    assert_eq!(claims["repository"], "andy/demo");
2230
    assert_eq!(claims["job"], "deploy");
2231
    assert_eq!(claims["run_number"], 1);
2232
    assert_eq!(claims["runner"], "test-1");
2233
    assert_eq!(claims["iss"], h.base.as_str());
2234
    assert!(claims["state"].as_str().unwrap().len() == 64);
2235
    // A job that prints its token leaves *** in the log.
2236
    let id = got["job_id"].as_i64().unwrap();
2237
    let records = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("TOKEN={token} end") }] });
2238
    let (st, _) = call(app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(records.to_string())).await;
2239
    assert_eq!(st, StatusCode::NO_CONTENT);
2240
    let log = db::flow::log(&app.db, id, 0, 100).await.unwrap();
2241
    assert!(log.iter().any(|l| l.text == "TOKEN=*** end"), "{log:?}");
2242
}
2243
2244
#[tokio::test(flavor = "multi_thread")]
2245
async fn jobs_are_offered_only_to_runners_of_their_architecture() {
2246
    let h = hub().await;
2247
    let app = &h.app;
2248
    create(app, "andy", "demo").await;
2249
    let url = format!("{}/andy/demo", h.base);
2250
    let work = tempfile::tempdir().unwrap();
2251
    let c = client(&url, work.path());
2252
    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)));
2253
    write(work.path(), "test.sh", "echo ok\n");
2254
    c.snapshot("test").unwrap();
2255
    c.commit("Add a pipeline", &[]).unwrap();
2256
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2257
    let claim_as = |arch: &'static str, archs: serde_json::Value| {
2258
        let app = app.clone();
2259
        async move {
2260
            let body = serde_json::json!({
2261
                "runner": format!("{arch}-1"), "runtimes": ["microvm"],
2262
                "info": { "arch": arch, "os": "linux", "version": "t", "labels": [], "max_jobs": 1 },
2263
                "image_archs": archs,
2264
            });
2265
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
2266
            match st {
2267
                StatusCode::NO_CONTENT => None,
2268
                StatusCode::OK => {
2269
                    Some(serde_json::from_str::<serde_json::Value>(&body).unwrap()["job"]["name"].as_str().unwrap().to_string())
2270
                }
2271
                other => panic!("claim: {other} {body}"),
2272
            }
2273
        }
2274
    };
2275
    // An x86_64 runner that says the alpine image is x86_64: it takes the
2276
    // alpine jobs, never the one that asks for riscv64.
2277
    let rootfs = pipeline("").split("cas://blob/").nth(1).unwrap()[..64].to_string();
2278
    for _ in 0..50 {
2279
        if !runs_of(app, "andy", "demo").await.is_empty() {
2280
            break;
2281
        }
2282
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
2283
    }
2284
    let runs = runs_of(app, "andy", "demo").await;
2285
    assert_eq!(runs.len(), 1, "{runs:?}");
2286
    let mut taken = vec![];
2287
    while let Some(j) = claim_as("x86_64", serde_json::json!({ rootfs.clone(): "x86_64" })).await {
2288
        taken.push(j);
2289
    }
2290
    assert_eq!(taken, ["build", "lint"], "test waits for build; flash is for riscv64");
2291
    // A riscv64 runner: the alpine image is known to be x86_64, so only flash.
2292
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await.as_deref(), Some("flash"));
2293
    assert_eq!(claim_as("riscv64", serde_json::json!({})).await, None);
2294
    let (_, queue) = call(app, "GET", "/admin/runners", None, None).await;
2295
    let _ = queue;
2296
}
2297
2298
/// OxygenFlow spec §11.5: a runner hands back a job it cannot run. The
2299
/// job is queued again and not offered to that runner again, the decline
2300
/// shows on the run's page and is kept for the runner's, and once three
2301
/// runners have declined it the job ends as unplaceable with their reasons.
2302
#[tokio::test(flavor = "multi_thread")]
2303
async fn a_declined_job_goes_to_another_runner_or_ends_unplaceable() {
2304
    let h = hub().await;
2305
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2306
    create(&h.app, "andy", "declines").await;
2307
    let url = format!("{}/andy/declines", h.base);
2308
    let work = tempfile::tempdir().unwrap();
2309
    let c = client(&url, work.path());
2310
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2311
    write(work.path(), "test.sh", "echo ok\n");
2312
    c.commit("Add a pipeline", &[]).unwrap();
2313
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2314
    let run = runs_of(&h.app, "andy", "declines").await[0].clone();
2315
    let claim_as = |token: &'static str, name: &'static str| {
2316
        let app = h.app.clone();
2317
        async move {
2318
            let body = serde_json::json!({ "runner": name, "runtimes": ["microvm"] }).to_string();
2319
            let (st, body) = call(&app, "POST", "/api/v1/flow/claim", Some(token), Some(body)).await;
2320
            (st == StatusCode::OK).then(|| serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap())
2321
        }
2322
    };
2323
    let decline = |token: &'static str, id: i64, reason: &'static str| {
2324
        let app = h.app.clone();
2325
        async move {
2326
            let body = serde_json::json!({ "reason": reason }).to_string();
2327
            call(&app, "POST", &format!("/api/v1/flow/jobs/{id}/decline"), Some(token), Some(body)).await.0
2328
        }
2329
    };
2330
    let job = claim_as("runner-secret", "earth-1").await.expect("a job");
2331
    // The other runners are known to the hub before they decline anything.
2332
    assert_eq!(decline("runner-two", job, "not mine").await, StatusCode::CONFLICT, "only the runner it runs on may decline it");
2333
    assert_eq!(decline("runner-secret", job, "the MicroVM tier needs /dev/kvm").await, StatusCode::NO_CONTENT);
2334
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2335
    assert_eq!((j.status.as_str(), j.runner.as_str()), ("queued", ""));
2336
    assert_eq!(j.waiting, "declined by earth-1: the MicroVM tier needs /dev/kvm; waiting for another runner");
2337
    // earth-1 is offered the other ready job, not this one, while it stays the same.
2338
    let next = claim_as("runner-secret", "earth-1").await.expect("the other ready job");
2339
    assert_ne!(next, job);
2340
    let page = call(&h.app, "GET", &format!("/andy/declines/flow/{}", run.number), None, None).await.1;
2341
    assert!(page.contains("Waiting: declined by earth-1: the MicroVM tier needs /dev/kvm"), "{page}");
2342
    assert_eq!(claim_as("runner-two", "plex-1").await, Some(job), "another runner takes it");
2343
    assert_eq!(decline("runner-two", job, "rootfs 36fc4e323804 is not on this runner").await, StatusCode::NO_CONTENT);
2344
    assert_eq!(claim_as("runner-three", "narvi").await, Some(job));
2345
    assert_eq!(decline("runner-three", job, "rootfs 36fc4e323804 is for x86_64; this runner is riscv64").await, StatusCode::NO_CONTENT);
2346
    let j = db::flow::job(&h.app.db, job).await.unwrap().unwrap();
2347
    assert_eq!(j.status, "error");
2348
    assert_eq!(
2349
        j.error,
2350
        "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"
2351
    );
2352
    let r = db::runners::list(&h.app.db).await.unwrap().into_iter().find(|r| r.name == "plex-1").unwrap();
2353
    let declined = db::flow::declines_of_runner(&h.app.db, r.id, 10).await.unwrap();
2354
    assert_eq!(declined.len(), 1);
2355
    assert_eq!((declined[0].job_id, declined[0].reason.as_str()), (job, "rootfs 36fc4e323804 is not on this runner"));
2356
    assert_eq!(r.tier_list(), vec!["microvm"]);
2357
}
2358
2359
/// oxygenhub#113: a job's artifact named `coverage` (LCOV) is read when
2360
/// it is uploaded. The job's log says what it found; the Coverage tab,
2361
/// the file view, the badge and the run page show it.
2362
#[tokio::test(flavor = "multi_thread")]
2363
async fn a_coverage_artifact_becomes_a_coverage_report() {
2364
    let h = hub().await;
2365
    create(&h.app, "andy", "cov").await;
2366
    let url = format!("{}/andy/cov", h.base);
2367
    let work = tempfile::tempdir().unwrap();
2368
    let c = client(&url, work.path());
2369
    write(
2370
        work.path(),
2371
        ".flow/pipeline.kdl",
2372
        &format!(
2373
            "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"
2374
        ),
2375
    );
2376
    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");
2377
    c.snapshot("test").unwrap();
2378
    c.commit("Code and coverage", &[]).unwrap();
2379
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2380
    let run = runs_of(&h.app, "andy", "cov").await.remove(0);
2381
    assert!(!call(&h.app, "GET", "/andy/cov", None, None).await.1.contains(">Reports</a>"), "no tab before a report");
2382
    let id = claim(&h.app).await.unwrap()["job_id"].as_i64().unwrap();
2383
2384
    let (st, text) = upload(&h.app, id, "coverage", b"this is not a report").await;
2385
    assert_eq!(st, StatusCode::OK, "a bad report never fails the upload: {text}");
2386
    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\
2387
SF:/src/src/gone.rs\nDA:1,1\nend_of_record\nSF:/usr/lib/rustlib/x.rs\nDA:1,1\nend_of_record\n";
2388
    let (st, text) = upload(&h.app, id, "coverage", lcov.as_bytes()).await;
2389
    assert_eq!(st, StatusCode::OK, "{text}");
2390
    let log: Vec<String> = db::flow::log(&h.app.db, id, 0, 50).await.unwrap().into_iter().map(|l| l.text).collect();
2391
    assert!(log.iter().any(|l| l.contains("coverage: this is not an LCOV report")), "{log:?}");
2392
    assert!(
2393
        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)"),
2394
        "{log:?}"
2395
    );
2396
2397
    let (st, page) = call(&h.app, "GET", "/andy/cov/coverage", None, None).await;
2398
    assert_eq!(st, StatusCode::OK);
2399
    assert!(
2400
        page.contains(">Reports</a>")
2401
            && page.contains("50.0%")
2402
            && page.contains("<strong>2</strong> of <strong>4</strong> relevant lines covered"),
2403
        "{page}"
2404
    );
2405
    assert!(page.contains("1 of 2") && page.contains("/andy/cov/coverage/") && page.contains("/file/src/lib.rs"), "{page}");
2406
    let report = crate_report(&h.app, run.id).await;
2407
    let (st, file) = call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/lib.rs"), None, None).await;
2408
    assert_eq!(st, StatusCode::OK, "{file}");
2409
    assert_eq!(file.matches("class=\"cov-hit\"").count(), 2, "{file}");
2410
    assert_eq!(file.matches("class=\"cov-miss\"").count(), 2, "{file}");
2411
    assert!(file.contains("3×"), "{file}");
2412
    assert_eq!(call(&h.app, "GET", &format!("/andy/cov/coverage/{report}/file/src/gone.rs"), None, None).await.0, StatusCode::NOT_FOUND);
2413
    let (_, badge) = call(&h.app, "GET", "/andy/cov/coverage/badge.svg", None, None).await;
2414
    assert!(badge.contains("coverage: 50.0%"), "{badge}");
2415
    let (_, run_page) = call(&h.app, "GET", &format!("/andy/cov/flow/{}", run.number), None, None).await;
2416
    assert!(run_page.contains("coverage 50.0%"), "{run_page}");
2417
    // The API (#113).
2418
    let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/cov/coverage", None, None).await;
2419
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2420
    assert_eq!((list[0]["percent"].as_f64(), list[0]["format"].as_str()), (Some(50.0), Some("lcov")), "{list}");
2421
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/cov/coverage/{report}"), None, None).await;
2422
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2423
    assert_eq!((one["files"][0]["path"].as_str(), one["files"][0]["lines_hit"].as_i64()), (Some("src/lib.rs"), Some(2)), "{one}");
2424
2425
    // The `coverage` check on the run's state: it reports, and with a
2426
    // minimum the repository sets, it fails below it.
2427
    let row = db::repos::get(&h.app.db, "andy", "cov").await.unwrap().unwrap();
2428
    let check = |checks: Vec<db::hooks::Check>| checks.into_iter().find(|c| c.name == "coverage").expect("a coverage check");
2429
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2430
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "50.0%"));
2431
    assert!(c.url.ends_with(&format!("/andy/cov/coverage?report={report}")), "{}", c.url);
2432
    oxygenhub::coverage::set_rules(&h.app.db, row.id, oxygenhub::coverage::Rules { min: Some(60.0), max_drop: None }).await.unwrap();
2433
    assert_eq!(upload(&h.app, id, "coverage", lcov.as_bytes()).await.0, StatusCode::OK);
2434
    let c = check(db::hooks::checks_for_state(&h.app.db, row.id, &run.state).await.unwrap());
2435
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "50.0%: below the minimum of 60%"));
2436
}
2437
2438
async fn crate_report(app: &Shared, run_id: i64) -> i64 {
2439
    oxygenhub::coverage::for_run(&app.db, run_id).await.unwrap()[0].id
2440
}
2441
2442
/// The Tests tab (#114): three runs' JUnit reports on a bookmark; a test
2443
/// breaks in the second and is fixed in the third.
2444
#[tokio::test(flavor = "multi_thread")]
2445
async fn junit_reports_make_a_tests_tab() {
2446
    let h = hub().await;
2447
    create(&h.app, "andy", "t").await;
2448
    let url = format!("{}/andy/t", h.base);
2449
    let work = tempfile::tempdir().unwrap();
2450
    let c = client(&url, work.path());
2451
    write(
2452
        work.path(),
2453
        ".flow/pipeline.kdl",
2454
        &format!(
2455
            "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"
2456
        ),
2457
    );
2458
    assert!(!call(&h.app, "GET", "/andy/t", None, None).await.1.contains(">Reports</a>"));
2459
    let case = |name: &str, ok: bool, secs: &str| {
2460
        if ok {
2461
            format!(r#"<testcase classname="t.suite" name="{name}" time="{secs}"/>"#)
2462
        } else {
2463
            format!(
2464
                r#"<testcase classname="t.suite" name="{name}" time="{secs}"><failure message="{name} broke">AssertionError</failure></testcase>"#
2465
            )
2466
        }
2467
    };
2468
    let runs = [
2469
        vec![case("a", true, "0.1"), case("b", true, "2.5"), case("c", true, "0.2")],
2470
        vec![case("a", true, "0.1"), case("b", false, "2.6"), case("c", true, "0.2"), case("d", true, "0.3")],
2471
        vec![case("a", true, "0.1"), case("b", true, "2.4"), case("c", true, "0.2"), case("d", true, "0.3")],
2472
    ];
2473
    for (i, cases) in runs.iter().enumerate() {
2474
        write(work.path(), "n.txt", &i.to_string());
2475
        c.snapshot("test").unwrap();
2476
        c.commit(&format!("Run {i}"), &[]).unwrap();
2477
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2478
        // The run is made after the push answers.
2479
        let mut a = None;
2480
        for _ in 0..100 {
2481
            a = claim(&h.app).await;
2482
            if a.is_some() {
2483
                break;
2484
            }
2485
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
2486
        }
2487
        let a = a.expect("a job to claim");
2488
        let id = a["job_id"].as_i64().unwrap();
2489
        let xml = format!("<testsuites><testsuite name=\"t\">{}</testsuite></testsuites>", cases.concat());
2490
        assert_eq!(upload(&h.app, id, "junit", xml.as_bytes()).await.0, StatusCode::OK);
2491
        let failed = cases.iter().any(|c| c.contains("<failure"));
2492
        let mut r = receipt("test", a["pipeline_hash"].as_str().unwrap(), failed as u32);
2493
        if !failed {
2494
            r["outputs"] = serde_json::json!([oxy_core::repo::Repo::blob_ref(xml.as_bytes()).to_hex()]);
2495
        }
2496
        let code = failed as i32;
2497
        assert_eq!(
2498
            finish(&h.app, id, serde_json::json!({ "exit_code": code, "duration_ms": 700, "receipt": r })).await,
2499
            StatusCode::NO_CONTENT
2500
        );
2501
    }
2502
    let (st, page) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2503
    assert_eq!(st, StatusCode::OK, "{page}");
2504
    if let Some(out) = std::env::var_os("OXYHUB_DUMP_TESTS_PAGE") {
2505
        std::fs::write(out, &page).unwrap();
2506
    }
2507
    assert!(page.contains(">Reports</a>"), "the tab");
2508
    assert!(page.contains("100%") && page.contains("of 4 tests passed"), "the latest run passes");
2509
    assert!(page.contains("1 fixed") && page.contains("t.suite::b"), "b fixed against the run before");
2510
    assert!(page.contains("1 ✕") && page.contains("2 ✓"), "b is flaky: {page}");
2511
    assert!(page.contains("<svg class=\"cov-chart\""), "charts");
2512
    // The slowest first.
2513
    let slow = page.find("Slowest tests").unwrap();
2514
    assert!(page[slow..].find("t.suite::b").unwrap() < page[slow..].find("t.suite::d").unwrap());
2515
    // The second run, picked: b newly failing, its failure listed.
2516
    let row = db::repos::get(&h.app.db, "andy", "t").await.unwrap().unwrap();
2517
    let second = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap()[1].id;
2518
    let (_, page) = call(&h.app, "GET", &format!("/andy/t/tests?report={second}"), None, None).await;
2519
    assert!(page.contains("1 failing") && page.contains("Newly failing") && page.contains("b broke"), "{page}");
2520
    assert!(page.contains("1 new tests"), "d is new");
2521
2522
    // The API (#114): the bookmark's reports newest first, and one with
2523
    // its failed cases.
2524
    let (st, list) = call(&h.app, "GET", "/api/v1/repos/andy/t/tests", None, None).await;
2525
    assert_eq!(st, StatusCode::OK, "{list}");
2526
    let list: serde_json::Value = serde_json::from_str(&list).unwrap();
2527
    assert_eq!(list.as_array().unwrap().len(), 3);
2528
    assert_eq!((list[0]["tests"].as_i64(), list[1]["failed"].as_i64()), (Some(4), Some(1)));
2529
    let (_, one) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}?status=failed"), None, None).await;
2530
    let one: serde_json::Value = serde_json::from_str(&one).unwrap();
2531
    assert_eq!(one["cases"].as_array().unwrap().len(), 1);
2532
    assert_eq!((one["cases"][0]["name"].as_str(), one["cases"][0]["message"].as_str()), (Some("b"), Some("b broke")));
2533
    let (_, all) = call(&h.app, "GET", &format!("/api/v1/repos/andy/t/tests/{second}"), None, None).await;
2534
    assert_eq!(serde_json::from_str::<serde_json::Value>(&all).unwrap()["cases"].as_array().unwrap().len(), 4);
2535
    assert_eq!(call(&h.app, "GET", "/api/v1/repos/andy/t/tests/99999", None, None).await.0, StatusCode::NOT_FOUND);
2536
2537
    // The `tests` check names what broke against main.
2538
    let reports = oxygenhub::junit::on_bookmark(&h.app.db, row.id, "main", 10).await.unwrap();
2539
    let check = |state: String| {
2540
        let app = h.app.clone();
2541
        async move { db::hooks::checks_for_state(&app.db, row.id, &state).await.unwrap().into_iter().find(|c| c.name == "tests").unwrap() }
2542
    };
2543
    let c = check(reports[1].state.clone()).await;
2544
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("failed", "1 failing; 1 new against main: t.suite::b"));
2545
    let c = check(reports[0].state.clone()).await;
2546
    assert_eq!((c.status.as_str(), c.summary.as_str()), ("passed", "4 passed"));
2547
2548
    // One test's history: b passed, failed, passed.
2549
    let (_, tab) = call(&h.app, "GET", "/andy/t/tests", None, None).await;
2550
    assert!(
2551
        tab.contains("/andy/t/tests/case?classname=t.suite&amp;name=b") || tab.contains("/andy/t/tests/case?classname=t.suite&name=b"),
2552
        "linked"
2553
    );
2554
    let (st, hist) = call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=b", None, None).await;
2555
    assert_eq!(st, StatusCode::OK, "{hist}");
2556
    assert!(hist.contains("2 passed") && hist.contains("1 failed") && hist.contains("b broke"), "{hist}");
2557
    assert_eq!(call(&h.app, "GET", "/andy/t/tests/case?classname=t.suite&name=nope", None, None).await.0, StatusCode::NOT_FOUND);
2558
}
2559
2560
/// oxygenhub#28: a queued job no runner can take says why, in the API, on
2561
/// the run page (its panel open) and in its check.
2562
#[tokio::test(flavor = "multi_thread")]
2563
async fn a_job_no_runner_can_take_says_why() {
2564
    let h = hub().await;
2565
    create(&h.app, "andy", "demo").await;
2566
    let url = format!("{}/andy/demo", h.base);
2567
    let work = tempfile::tempdir().unwrap();
2568
    let c = client(&url, work.path());
2569
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
2570
    write(work.path(), "test.sh", "echo ok\n");
2571
    c.commit("Add a pipeline", &[]).unwrap();
2572
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2573
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
2574
2575
    // One runner, online, holding another image only.
2576
    let r = db::runners::configured(&h.app.db, &blake3::hash(b"elsewhere").to_hex(), "earth-9").await.unwrap();
2577
    db::runners::seen(&h.app.db, r.id, None, None).await.unwrap();
2578
    let other = "ab".repeat(32);
2579
    db::runners::set_offer(&h.app.db, r.id, &["microvm".to_string()], Some(&[other]), false, "p").await.unwrap();
2580
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2581
2582
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2583
    let v: serde_json::Value = serde_json::from_str(&body).unwrap();
2584
    let build = v["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
2585
    let why = build["waiting"].as_str().unwrap_or_default().to_string();
2586
    assert!(why.contains("earth-9 does not hold image") && why.contains(&ROOTFS[..12]), "{body}");
2587
    let (_, page) = call(&h.app, "GET", "/andy/demo/flow/1", None, None).await;
2588
    assert!(page.contains("data-waiting") && page.contains("does not hold image"), "the run page says it");
2589
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
2590
    let check = checks.iter().find(|c| c.name == "flow/build").unwrap();
2591
    assert!(check.summary.contains("does not hold image"), "{check:?}");
2592
}
2593
2594
async fn put_bytes(app: &Shared, path: &str, bearer: &str, bytes: Vec<u8>) -> (StatusCode, String) {
2595
    let req = Request::put(path)
2596
        .header(header::AUTHORIZATION, format!("Bearer {bearer}"))
2597
        .header(header::CONTENT_TYPE, "application/octet-stream")
2598
        .body(Body::from(bytes))
2599
        .unwrap();
2600
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
2601
    let st = res.status();
2602
    (st, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
2603
}
2604
2605
/// oxygenflow#39: an image is sent as the chunks the hub lacks and then its
2606
/// manifest, checked against its hash; runners fetch it; and a job whose
2607
/// image only the hub holds is offered to a runner that fetches, not to one
2608
/// that does not.
2609
#[tokio::test(flavor = "multi_thread")]
2610
async fn images_are_sent_by_chunk_and_offered_to_runners_that_fetch() {
2611
    let h = hub().await;
2612
    // The site token acts as the first site administrator.
2613
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2614
    // An image: bytes, a run of zeros, more bytes.
2615
    let mut image: Vec<u8> = (0..400_000u32).map(|i| (i % 251) as u8).collect();
2616
    image.extend(std::iter::repeat_n(0u8, 2 << 20));
2617
    image.extend((0..100_000u32).map(|i| (i % 239) as u8));
2618
    let mut chunks = std::collections::HashMap::new();
2619
    let m = jet::images::scan(&image[..], Some("x86_64".into()), |c, b| {
2620
        chunks.insert(c.hash().to_string(), b.to_vec());
2621
        Ok(())
2622
    })
2623
    .unwrap();
2624
    let hash = m.hash.clone();
2625
2626
    // Which chunks the hub lacks: every one but zeros; a manifest before them is refused.
2627
    let ask = serde_json::json!({ "chunks": m.needed() }).to_string();
2628
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask.clone())).await;
2629
    assert_eq!(st, StatusCode::OK, "{body}");
2630
    let missing: Vec<String> = serde_json::from_str::<serde_json::Value>(&body).unwrap()["missing"]
2631
        .as_array()
2632
        .unwrap()
2633
        .iter()
2634
        .map(|v| v.as_str().unwrap().to_string())
2635
        .collect();
2636
    assert_eq!(missing.len(), m.needed().len());
2637
    let manifest = serde_json::to_string(&m).unwrap();
2638
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest.clone())).await;
2639
    assert!(st == StatusCode::CONFLICT && body.contains("was not sent"), "{st} {body}");
2640
    // A chunk is checked against its name; a runner token may not send.
2641
    let first = &missing[0];
2642
    assert_eq!(put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "site", vec![1, 2, 3]).await.0, StatusCode::BAD_REQUEST);
2643
    assert_ne!(
2644
        put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{first}"), "runner-secret", chunks[first].clone()).await.0,
2645
        StatusCode::NO_CONTENT
2646
    );
2647
    for c in &missing {
2648
        let (st, body) = put_bytes(&h.app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
2649
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
2650
    }
2651
    let (_, body) = call(&h.app, "POST", "/api/v1/flow/images/missing", Some("site"), Some(ask)).await;
2652
    assert!(body.contains("\"missing\":[]"), "{body}");
2653
    // A manifest naming another hash is refused; the right one is kept.
2654
    let mut wrong = m.clone();
2655
    wrong.hash = "ab".repeat(32);
2656
    let (st, _) =
2657
        call(&h.app, "PUT", &format!("/api/v1/flow/images/{}", wrong.hash), Some("site"), Some(serde_json::to_string(&wrong).unwrap()))
2658
            .await;
2659
    assert_eq!(st, StatusCode::CONFLICT, "chunks that make another image");
2660
    let (st, body) = call(&h.app, "PUT", &format!("/api/v1/flow/images/{hash}"), Some("site"), Some(manifest)).await;
2661
    assert_eq!(st, StatusCode::CREATED, "{body}");
2662
2663
    // A runner fetches the manifest and the chunks, and the image comes back whole.
2664
    let (st, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), Some("runner-secret"), None).await;
2665
    assert_eq!(st, StatusCode::OK, "{body}");
2666
    let got: jet::images::Manifest = serde_json::from_str(&body).unwrap();
2667
    assert_eq!(got, m);
2668
    let dir = tempfile::tempdir().unwrap();
2669
    let out = dir.path().join("img.ext4");
2670
    let mut fetched = Vec::new();
2671
    for c in got.needed() {
2672
        let req = Request::get(format!("/api/v1/flow/images/chunks/{c}"))
2673
            .header(header::AUTHORIZATION, "Bearer runner-secret")
2674
            .body(Body::empty())
2675
            .unwrap();
2676
        let res = oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap();
2677
        assert_eq!(res.status(), StatusCode::OK);
2678
        let bytes = res.into_body().collect().await.unwrap().to_bytes().to_vec();
2679
        fetched.push((c.to_string(), bytes));
2680
    }
2681
    jet::images::assemble(&got, &out, |c| Ok(fetched.iter().find(|(h, _)| h == c.hash()).unwrap().1.clone())).unwrap();
2682
    assert_eq!(std::fs::read(&out).unwrap(), image);
2683
    assert_eq!(
2684
        call(&h.app, "GET", &format!("/api/v1/flow/images/{}", "cd".repeat(32)), Some("runner-secret"), None).await.0,
2685
        StatusCode::NOT_FOUND
2686
    );
2687
    assert_ne!(call(&h.app, "GET", &format!("/api/v1/flow/images/{hash}"), None, None).await.0, StatusCode::OK, "not anonymous");
2688
2689
    // A job on that image: a runner holding no images and not fetching
2690
    // is offered nothing; one that fetches is offered it.
2691
    create(&h.app, "andy", "demo").await;
2692
    let url = format!("{}/andy/demo", h.base);
2693
    let work = tempfile::tempdir().unwrap();
2694
    let c = client(&url, work.path());
2695
    write(
2696
        work.path(),
2697
        ".flow/pipeline.kdl",
2698
        &format!("schema-version 1\nsandbox \"img\" {{\n    rootfs \"cas://blob/{hash}\"\n}}\njob \"build\" {{\n    sandbox \"img\"\n    exec \"make\"\n}}\n"),
2699
    );
2700
    c.commit("Build on the image", &[]).unwrap();
2701
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2702
    runs_of(&h.app, "andy", "demo").await;
2703
    // #137: the run's images are held (by the hub), so no images check.
2704
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2705
    let run1 = db::flow::run(&h.app.db, row.id, 1).await.unwrap().unwrap();
2706
    let checks = checks_when(&h.app, row.id, &run1.state, 1).await;
2707
    assert!(checks.iter().all(|c| c.name != "pipeline/images"), "{checks:?}");
2708
    let ask = |fetches: bool| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":[],"fetches_images":{fetches}}}"#);
2709
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(false))).await;
2710
    assert_eq!(st, StatusCode::NO_CONTENT, "it lacks the image and does not fetch");
2711
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2712
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2713
    assert!(body.contains("does not hold image"), "{body}");
2714
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(true))).await;
2715
    assert_eq!(st, StatusCode::OK, "it fetches, and the hub holds the image: {body}");
2716
}
2717
2718
/// oxygenhub#136: coverage measured on a workstation is uploaded for a
2719
/// bookmark's state, kept as uploaded by its account, shown so, and sets
2720
/// no check.
2721
#[tokio::test(flavor = "multi_thread")]
2722
async fn coverage_uploaded_from_a_workstation_says_so() {
2723
    let h = hub().await;
2724
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2725
    create(&h.app, "andy", "vk").await;
2726
    let url = format!("{}/andy/vk", h.base);
2727
    let work = tempfile::tempdir().unwrap();
2728
    let c = client(&url, work.path());
2729
    write(work.path(), "src/game.c", "int a;\nint b;\nint c;\nint d;\n");
2730
    c.commit("Game", &[]).unwrap();
2731
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2732
2733
    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";
2734
    let body = serde_json::json!({ "bookmark": "main", "content": lcov }).to_string();
2735
    let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", Some("site"), Some(body)).await;
2736
    assert_eq!(st, StatusCode::CREATED, "{out}");
2737
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2738
    assert_eq!((v["uploaded_by"].as_str(), v["lines_hit"].as_i64(), v["lines_found"].as_i64()), (Some("andy"), Some(3), Some(4)));
2739
    assert_eq!(v["dropped"], 1, "a file outside the state is left out");
2740
    assert_eq!(v["bookmark"], "main");
2741
2742
    let (_, page) = call(&h.app, "GET", "/andy/vk/coverage", None, None).await;
2743
    assert!(page.contains("uploaded by andy") && page.contains("75.0%"), "the Coverage page says where it came from");
2744
    let (_, page) = call(&h.app, "GET", "/andy/vk/reports", None, None).await;
2745
    assert!(page.contains("uploaded by andy"), "and the Reports card");
2746
    let row = db::repos::get(&h.app.db, "andy", "vk").await.unwrap().unwrap();
2747
    let state = v["state"].as_str().unwrap();
2748
    let checks = db::hooks::checks_for_state(&h.app.db, row.id, state).await.unwrap();
2749
    assert!(checks.iter().all(|c| c.name != "coverage"), "an upload sets no check: {checks:?}");
2750
2751
    // Readers cannot upload; bad reports and bookmarks are refused.
2752
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/vk/coverage", None, Some(r#"{"content":"x"}"#.into())).await;
2753
    assert_ne!(st, StatusCode::CREATED);
2754
    let (st, _) = call(
2755
        &h.app,
2756
        "POST",
2757
        "/api/v1/repos/andy/vk/coverage",
2758
        Some("site"),
2759
        Some(r#"{"bookmark":"nope","content":"SF:a\nend_of_record\n"}"#.into()),
2760
    )
2761
    .await;
2762
    assert_eq!(st, StatusCode::BAD_REQUEST);
2763
}
2764
2765
/// oxygenflow#40: what a runner measured at its claim is kept and shown.
2766
#[tokio::test(flavor = "multi_thread")]
2767
async fn a_runners_facts_are_kept_from_its_claim() {
2768
    let h = hub().await;
2769
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2770
    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"}}"#;
2771
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.into())).await;
2772
    assert_eq!(st, StatusCode::NO_CONTENT, "nothing to run, but the facts are kept");
2773
    let (st, out) = call(&h.app, "GET", "/api/v1/runners", Some("site"), None).await;
2774
    assert_eq!(st, StatusCode::OK, "{out}");
2775
    let v: serde_json::Value = serde_json::from_str(&out).unwrap();
2776
    let r = &v[0];
2777
    assert_eq!(
2778
        (r["speed"].as_i64(), r["speed_class"].as_i64(), r["free_disk_mib"].as_i64(), r["load_x100"].as_i64()),
2779
        (Some(100), Some(3), Some(42000), Some(112))
2780
    );
2781
    let row = db::runners::list(&h.app.db).await.unwrap().remove(0);
2782
    assert_eq!(row.facts_line(), "speed 100 (class 3) · load 1.12 · 41 GiB free");
2783
}
2784
2785
/// oxygenflow#41: a job's peaks set what its next run needs; a runner
2786
/// without that much free disk is not offered it, and the reason says so.
2787
#[tokio::test(flavor = "multi_thread")]
2788
async fn a_jobs_next_run_needs_the_disk_its_last_took() {
2789
    let h = hub().await;
2790
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2791
    create(&h.app, "andy", "demo").await;
2792
    let url = format!("{}/andy/demo", h.base);
2793
    let work = tempfile::tempdir().unwrap();
2794
    let c = client(&url, work.path());
2795
    write(
2796
        work.path(),
2797
        ".flow/pipeline.kdl",
2798
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2799
    );
2800
    c.commit("Build", &[]).unwrap();
2801
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2802
    runs_of(&h.app, "andy", "demo").await;
2803
    let claim_with = |free: u64| format!(r#"{{"runner":"test-1","runtimes":["microvm"],"facts":{{"free_disk_mib":{free}}}}}"#);
2804
2805
    // The first run has nothing to learn from: any runner takes it.
2806
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(500))).await;
2807
    assert_eq!(st, StatusCode::OK, "{body}");
2808
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2809
    let done = serde_json::json!({ "exit_code": 0, "duration_ms": 10, "peak_disk_mib": 8000, "peak_memory_mib": 900 });
2810
    assert_eq!(finish(&h.app, id, done).await, StatusCode::NO_CONTENT);
2811
    let job = db::flow::job(&h.app.db, id).await.unwrap().unwrap();
2812
    assert_eq!((job.peak_disk_mib, job.peak_memory_mib), (Some(8000), Some(900)));
2813
2814
    // The next run needs 8000 MiB and a quarter more.
2815
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
2816
    assert_eq!(st, StatusCode::CREATED);
2817
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2818
    let run2 = db::flow::run(&h.app.db, repo.id, 2).await.unwrap().unwrap();
2819
    let next = db::flow::jobs(&h.app.db, run2.id).await.unwrap().remove(0);
2820
    assert_eq!(next.need_disk_mib, Some(8000 + 2000 + 64));
2821
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(9000))).await;
2822
    assert_eq!(st, StatusCode::NO_CONTENT, "9000 MiB free is not enough");
2823
    oxygenhub::flow::explain_waits(&h.app).await.unwrap();
2824
    let waiting = db::flow::job(&h.app.db, next.id).await.unwrap().unwrap().waiting;
2825
    assert!(waiting.contains("8.8 GiB free; the job needs ~9.8 GiB"), "{waiting}");
2826
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(claim_with(20_000))).await;
2827
    assert_eq!(st, StatusCode::OK, "a roomier runner takes it: {body}");
2828
}
2829
2830
/// oxygenflow#42: a job another free runner would do better (it holds the
2831
/// image) is held from a runner that would fetch it, the better runner
2832
/// takes it, and the job says why it ran there.
2833
#[tokio::test(flavor = "multi_thread")]
2834
async fn a_job_waits_briefly_for_a_runner_that_holds_its_image() {
2835
    let h = hub().await;
2836
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2837
    // A second runner, with a token of its own.
2838
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2839
    let ask = |images: &str| {
2840
        format!(
2841
            r#"{{"runner":"r","runtimes":["microvm"],"images":[{images}],"fetches_images":true,"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2842
        )
2843
    };
2844
    let holder = ask(&format!("\"{ROOTFS}\""));
2845
    // earth-9 holds the image and is polling; nothing is queued yet.
2846
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2847
    assert_eq!(st, StatusCode::NO_CONTENT);
2848
    // The hub holds the image too, so test-1 could fetch it.
2849
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES (?, 1, 'x86_64', 1, 'andy', 0)")
2850
        .bind(ROOTFS)
2851
        .execute(&h.app.db)
2852
        .await
2853
        .unwrap();
2854
2855
    create(&h.app, "andy", "demo").await;
2856
    let url = format!("{}/andy/demo", h.base);
2857
    let work = tempfile::tempdir().unwrap();
2858
    let c = client(&url, work.path());
2859
    write(
2860
        work.path(),
2861
        ".flow/pipeline.kdl",
2862
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2863
    );
2864
    c.commit("Build", &[]).unwrap();
2865
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2866
    runs_of(&h.app, "andy", "demo").await;
2867
2868
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2869
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner that holds the image");
2870
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2871
    assert_eq!(st, StatusCode::OK, "{body}");
2872
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2873
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2874
    assert!(placed.starts_with("holds the image, idle, speed 100 (class 3)"), "{placed}");
2875
    assert!(placed.contains("held for a better runner"), "{placed}");
2876
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/demo/flow/runs/1", Some("site"), None).await;
2877
    assert!(body.contains("\"placed\":\"holds the image"), "{body}");
2878
}
2879
2880
/// oxygenflow#51: a job waits briefly for the runner holding its build
2881
/// cache, even when the other one holds its image too.
2882
#[tokio::test(flavor = "multi_thread")]
2883
async fn a_job_waits_briefly_for_the_runner_holding_its_build_cache() {
2884
    let h = hub().await;
2885
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2886
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2887
    let slot = flow_core::api::cache_slot("andy/demo", "build");
2888
    let ask = |caches: &str| {
2889
        format!(
2890
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":[{caches}],"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2891
        )
2892
    };
2893
    let holder = ask(&format!("\"{slot}\""));
2894
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder.clone())).await;
2895
    assert_eq!(st, StatusCode::NO_CONTENT);
2896
2897
    create(&h.app, "andy", "demo").await;
2898
    let url = format!("{}/andy/demo", h.base);
2899
    let work = tempfile::tempdir().unwrap();
2900
    let c = client(&url, work.path());
2901
    write(
2902
        work.path(),
2903
        ".flow/pipeline.kdl",
2904
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2905
    );
2906
    c.commit("Build", &[]).unwrap();
2907
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2908
    runs_of(&h.app, "andy", "demo").await;
2909
2910
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(""))).await;
2911
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the runner holding the build cache");
2912
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(holder)).await;
2913
    assert_eq!(st, StatusCode::OK, "{body}");
2914
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2915
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2916
    assert!(placed.starts_with("holds its build cache, holds the image"), "{placed}");
2917
}
2918
2919
/// oxygenflow#54: when both runners hold a job's build cache, the job waits
2920
/// briefly for the one whose copy is fresher.
2921
#[tokio::test(flavor = "multi_thread")]
2922
async fn a_job_waits_briefly_for_the_fresher_build_cache() {
2923
    let h = hub().await;
2924
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
2925
    db::runners::configured(&h.app.db, &blake3::hash(b"other-secret").to_hex(), "earth-9").await.unwrap();
2926
    let slot = flow_core::api::cache_slot("andy/demo", "build");
2927
    let now = db::now_ms();
2928
    let ask = |kept: i64| {
2929
        format!(
2930
            r#"{{"runner":"r","runtimes":["microvm"],"images":["{ROOTFS}"],"fetches_images":true,"caches":["{slot}"],"cache_times":{{"{slot}":{kept}}},"facts":{{"speed":100,"speed_class":3,"free_disk_mib":50000}}}}"#
2931
        )
2932
    };
2933
    // earth-9 kept its copy a minute ago; the other runner's is a day old.
2934
    let fresh = ask(now - 60_000);
2935
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh.clone())).await;
2936
    assert_eq!(st, StatusCode::NO_CONTENT);
2937
2938
    create(&h.app, "andy", "demo").await;
2939
    let url = format!("{}/andy/demo", h.base);
2940
    let work = tempfile::tempdir().unwrap();
2941
    let c = client(&url, work.path());
2942
    write(
2943
        work.path(),
2944
        ".flow/pipeline.kdl",
2945
        &format!("schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"build\" {{\n    sandbox \"alpine\"\n    exec \"make\"\n}}\n"),
2946
    );
2947
    c.commit("Build", &[]).unwrap();
2948
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
2949
    runs_of(&h.app, "andy", "demo").await;
2950
2951
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(ask(now - 86_400_000))).await;
2952
    assert_eq!(st, StatusCode::NO_CONTENT, "held for the fresher copy");
2953
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("other-secret"), Some(fresh)).await;
2954
    assert_eq!(st, StatusCode::OK, "{body}");
2955
    let id = serde_json::from_str::<serde_json::Value>(&body).unwrap()["job_id"].as_i64().unwrap();
2956
    let placed = db::flow::job(&h.app.db, id).await.unwrap().unwrap().placed;
2957
    assert!(placed.starts_with("holds its build cache (kept 1 min ago), holds the image"), "{placed}");
2958
}
2959
2960
/// oxygenhub#127 §3.3: report files expire beyond the newest 50 runs of a
2961
/// report on a bookmark other than the default; the default keeps all,
2962
/// and an expired report keeps its metrics.
2963
#[tokio::test(flavor = "multi_thread")]
2964
async fn report_files_expire_under_retention() {
2965
    let h = hub().await;
2966
    create(&h.app, "andy", "demo").await;
2967
    let repo = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
2968
    let add = |bookmark: &'static str, at: i64| {
2969
        let db = h.app.db.clone();
2970
        async move {
2971
            let id: i64 = sqlx::query_scalar(
2972
                "INSERT INTO reports (repo_id, name, kind, title, summary, context, job, bookmark, state, files, bytes, created_ms) \
2973
                 VALUES (?, 'perf', 'performance', 'Perf', '', '{}', 'perf', ?, 's', 1, 1, ?) RETURNING id",
2974
            )
2975
            .bind(repo.id)
2976
            .bind(bookmark)
2977
            .bind(at)
2978
            .fetch_one(&db)
2979
            .await
2980
            .unwrap();
2981
            sqlx::query("INSERT INTO report_files (report_id, path, blob, size) VALUES (?, 'report.toml', ?, 1)")
2982
                .bind(id)
2983
                .bind(format!("{:064x}", id))
2984
                .execute(&db)
2985
                .await
2986
                .unwrap();
2987
            sqlx::query("INSERT INTO report_metrics (report_id, key, value, unit, better) VALUES (?, 'ms', 1, '', '')")
2988
                .bind(id)
2989
                .execute(&db)
2990
                .await
2991
                .unwrap();
2992
            id
2993
        }
2994
    };
2995
    let main_old = add("main", 1).await;
2996
    add("main", 2).await;
2997
    let mut feature = Vec::new();
2998
    for at in 0..52 {
2999
        feature.push(add("feature", 10 + at).await);
3000
    }
3001
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 2, "the two oldest feature runs");
3002
    let files = |id: i64| {
3003
        let db = h.app.db.clone();
3004
        async move {
3005
            sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM report_files WHERE report_id = ?").bind(id).fetch_one(&db).await.unwrap()
3006
        }
3007
    };
3008
    assert_eq!((files(feature[0]).await, files(feature[1]).await, files(feature[2]).await), (0, 0, 1));
3009
    assert_eq!(files(main_old).await, 1, "the default bookmark keeps every run");
3010
    assert_eq!(oxygenhub::reports::metrics(&h.app.db, feature[0]).await.unwrap().len(), 1, "metrics are kept");
3011
    assert_eq!(oxygenhub::reports::expire(&h.app.db).await.unwrap(), 0, "once");
3012
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/reports/perf?id={}", feature[0]), None, None).await;
3013
    assert!(page.contains("files have expired"), "the page says so");
3014
}
3015
3016
/// #137: a run pinning an image neither the hub nor any runner holds sets a
3017
/// failing `pipeline/images` check saying how to send it; once it is held,
3018
/// a run of the same state turns the check to passed.
3019
#[tokio::test(flavor = "multi_thread")]
3020
async fn a_pipeline_pinning_an_image_nobody_holds_fails_a_check() {
3021
    let h = hub().await;
3022
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3023
    // The one runner reports holding no images.
3024
    let none = r#"{"runner":"test-1","runtimes":["microvm"],"images":[]}"#;
3025
    let (st, _) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(none.into())).await;
3026
    assert_eq!(st, StatusCode::NO_CONTENT);
3027
    create(&h.app, "andy", "demo").await;
3028
    let url = format!("{}/andy/demo", h.base);
3029
    let work = tempfile::tempdir().unwrap();
3030
    let c = client(&url, work.path());
3031
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3032
    write(work.path(), "test.sh", "echo ok\n");
3033
    c.commit("Add a pipeline", &[]).unwrap();
3034
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3035
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
3036
    let checks = checks_when(&h.app, run.repo_id, &run.state, 4).await;
3037
    let check = checks.iter().find(|c| c.name == "pipeline/images").expect("an images check");
3038
    assert!(check.status == "failed" && check.summary.contains(&ROOTFS[..12]) && check.summary.contains("flow rootfs push"), "{check:?}");
3039
    // Once a runner holds it, a run of the state passes the check.
3040
    let holds = format!(r#"{{"runner":"test-1","runtimes":["microvm"],"images":["{ROOTFS}"]}}"#);
3041
    call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(holds)).await;
3042
    let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/demo/flow/runs", Some("site"), Some("{}".into())).await;
3043
    assert_eq!(st, StatusCode::CREATED);
3044
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
3045
    let check = checks.iter().find(|c| c.name == "pipeline/images").unwrap();
3046
    assert_eq!(check.status, "passed", "{check:?}");
3047
}
3048
3049
/// The swarm's tracker (#144): a fetching runner is given the peers in its
3050
/// site that hold the image or are fetching it, and a ticket signed with
3051
/// the hub key; a runner not in a swarm is told how to join one.
3052
#[tokio::test(flavor = "multi_thread")]
3053
async fn the_tracker_names_peers_in_the_same_site_and_signs_a_ticket() {
3054
    let h = hub().await;
3055
    let app = &h.app;
3056
    let image = "ab".repeat(32);
3057
    let claim_as = |token: &'static str, name: &'static str, body: serde_json::Value| async move {
3058
        let mut b = serde_json::json!({ "runner": name, "runtimes": ["microvm"] });
3059
        b.as_object_mut().unwrap().extend(body.as_object().unwrap().clone());
3060
        let (st, out) = call(app, "POST", "/api/v1/flow/claim", Some(token), Some(b.to_string())).await;
3061
        assert_eq!(st, StatusCode::NO_CONTENT, "{out}");
3062
    };
3063
    let announce = |token: &'static str, state: &'static str| {
3064
        let body = serde_json::json!({ "image": image, "state": state }).to_string();
3065
        async move { call(app, "POST", "/api/v1/flow/swarm/announce", Some(token), Some(body)).await }
3066
    };
3067
    // A holds the image; B and C hold nothing; all three are in site "lab".
3068
    claim_as(
3069
        "runner-secret",
3070
        "a",
3071
        serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "lab", "cert": "11".repeat(32) } }),
3072
    )
3073
    .await;
3074
    claim_as(
3075
        "runner-two",
3076
        "b",
3077
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.2:7401", "site": "lab", "cert": "22".repeat(32) } }),
3078
    )
3079
    .await;
3080
    claim_as(
3081
        "runner-three",
3082
        "c",
3083
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "lab", "cert": "33".repeat(32) } }),
3084
    )
3085
    .await;
3086
3087
    let (st, body) = announce("runner-two", "fetching").await;
3088
    assert_eq!(st, StatusCode::OK, "{body}");
3089
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3090
    let names: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3091
    assert_eq!(names, vec![("10.0.0.1:7401", true)], "only A holds it so far");
3092
    assert_eq!(a.peers[0].cert, "11".repeat(32), "with the fingerprint peers check it by");
3093
    let t = jet::swarm::Ticket::open(&a.ticket, &app.hub_key.identity, oxygenhub::db::now_ms() as u64).unwrap();
3094
    assert_eq!((t.name.as_str(), t.site.as_str()), ("b", "lab"));
3095
3096
    // C, fetching too, is told of A (whole) and B (fetching).
3097
    let (_, body) = announce("runner-three", "fetching").await;
3098
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3099
    let mut peers: Vec<(&str, bool)> = a.peers.iter().map(|p| (p.addr.as_str(), p.complete)).collect();
3100
    peers.sort();
3101
    assert_eq!(peers, vec![("10.0.0.1:7401", true), ("10.0.0.2:7401", false)]);
3102
3103
    // B is done: no longer offered as fetching. C moves site: no peers.
3104
    announce("runner-two", "done").await;
3105
    claim_as(
3106
        "runner-three",
3107
        "c",
3108
        serde_json::json!({ "images": [], "swarm": { "addr": "10.0.0.3:7401", "site": "elsewhere", "cert": "33".repeat(32) } }),
3109
    )
3110
    .await;
3111
    let (_, body) = announce("runner-three", "fetching").await;
3112
    let a: flow_core::api::Announced = serde_json::from_str(&body).unwrap();
3113
    assert!(a.peers.is_empty(), "{:?}", a.peers);
3114
3115
    // A runner without a certificate (an older flow) is not in the swarm.
3116
    claim_as("runner-secret", "a", serde_json::json!({ "images": [image], "swarm": { "addr": "10.0.0.1:7401", "site": "elsewhere" } }))
3117
        .await;
3118
    let (st, _) = announce("runner-secret", "fetching").await;
3119
    assert_eq!(st, StatusCode::CONFLICT);
3120
3121
    // A runner that left the swarm is told how to join; nonsense is refused.
3122
    claim_as("runner-two", "b", serde_json::json!({ "images": [] })).await;
3123
    let (st, body) = announce("runner-two", "fetching").await;
3124
    assert_eq!(st, StatusCode::CONFLICT);
3125
    assert!(body.contains("[runner.swarm]"), "{body}");
3126
    let (st, _) =
3127
        call(app, "POST", "/api/v1/flow/swarm/announce", Some("runner-secret"), Some(r#"{"image":"nope","state":"fetching"}"#.into()))
3128
            .await;
3129
    assert_eq!(st, StatusCode::BAD_REQUEST);
3130
    let (st, _) = call(
3131
        app,
3132
        "POST",
3133
        "/api/v1/flow/swarm/announce",
3134
        None,
3135
        Some(serde_json::json!({ "image": image, "state": "fetching" }).to_string()),
3136
    )
3137
    .await;
3138
    assert_eq!(st, StatusCode::UNAUTHORIZED);
3139
}
3140
3141
/// Admin › Runners › Images (C0): each image, where it is and what uses it.
3142
#[tokio::test(flavor = "multi_thread")]
3143
async fn the_images_page_says_where_each_image_is_and_what_uses_it() {
3144
    let h = hub().await;
3145
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3146
    create(&h.app, "andy", "demo").await;
3147
    let work = tempfile::tempdir().unwrap();
3148
    let c = client(&format!("{}/andy/demo", h.base), work.path());
3149
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3150
    write(work.path(), "test.sh", "echo ok\n");
3151
    c.commit("Add a pipeline", &[]).unwrap();
3152
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3153
    // A runner holds another image and shares it; the hub keeps a third.
3154
    let held = "cd".repeat(32);
3155
    let kept = "ef".repeat(32);
3156
    let body = serde_json::json!({ "runner": "earth-1", "runtimes": ["wasm"], "images": [held], "swarm": { "addr": "10.0.0.1:7401", "site": "home", "cert": "11".repeat(32) } });
3157
    let (st, out) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(body.to_string())).await;
3158
    assert!(st == StatusCode::NO_CONTENT || st == StatusCode::OK, "{st} {out}");
3159
    sqlx::query("INSERT INTO jet_images (hash, size, arch, chunks, uploader, created_ms) VALUES (?, 1048576, 'x86_64', 9, 'andy', 1)")
3160
        .bind(&kept)
3161
        .execute(&h.app.db)
3162
        .await
3163
        .unwrap();
3164
3165
    let res = oxygenhub::router(h.app.clone())
3166
        .oneshot(
3167
            Request::post("/register")
3168
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
3169
                .body(Body::from("username=carol&email=carol%40example.com&password=correct-horse-battery&setup=test-setup"))
3170
                .unwrap(),
3171
        )
3172
        .await
3173
        .unwrap();
3174
    let cookie = res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string();
3175
    let carol = db::accounts::account_by_name(&h.app.db, "carol").await.unwrap().unwrap();
3176
    db::accounts::set_admin(&h.app.db, carol.id, true).await.unwrap();
3177
    let res = oxygenhub::router(h.app.clone())
3178
        .oneshot(Request::get("/admin/runners/images").header(header::COOKIE, cookie).body(Body::empty()).unwrap())
3179
        .await
3180
        .unwrap();
3181
    assert_eq!(res.status(), StatusCode::OK);
3182
    let page = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
3183
    let row = |hash: &str| {
3184
        let at = page.find(&format!("title=\"{hash}\"")).unwrap_or_else(|| panic!("{hash} is not on the page"));
3185
        let end = page[at..].find("</tr>").unwrap();
3186
        page[at..at + end].to_string()
3187
    };
3188
    let pinned = row(ROOTFS);
3189
    assert!(pinned.contains("nowhere") && pinned.contains("andy/demo") && pinned.contains("3 jobs"), "{pinned}");
3190
    let on_runner = row(&held);
3191
    assert!(on_runner.contains("img-holds") && on_runner.contains("earth-1") && !on_runner.contains("nowhere"), "{on_runner}");
3192
    let on_hub = row(&kept);
3193
    assert!(on_hub.contains("img-hub") && on_hub.contains("1.0 MiB") && on_hub.contains("x86_64"), "{on_hub}");
3194
    assert!(page.contains("earth-1 (home)"), "the swarm is named");
3195
    // The swarm backdrop (docs/backgrounds.md §2): the hub and the runners.
3196
    assert!(page.contains(r#"{"images":"#) && page.contains(r#""scene":"swarm""#) && page.contains(r#""earth-1""#), "the swarm's data");
3197
    assert_eq!(call(&h.app, "GET", "/admin/runners/images", None, None).await.0, StatusCode::NOT_FOUND, "administrators only");
3198
}
3199
3200
/// Diffusion D1 (#148): the reverse pin index. A repository that pins
3201
/// another as a subrepo is a consumer of it; the upstream's API and page
3202
/// say who, at which state, and how far behind its default bookmark.
3203
#[tokio::test(flavor = "multi_thread")]
3204
async fn consumers_of_a_subrepo_are_indexed_with_how_far_behind_they_are() {
3205
    let h = hub().await;
3206
    // The site token acts as the first site administrator.
3207
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3208
    create(&h.app, "andy", "api").await;
3209
    create(&h.app, "andy", "game").await;
3210
    let api_work = tempfile::tempdir().unwrap();
3211
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3212
    write(api_work.path(), "api.h", "v1\n");
3213
    api.snapshot("t").unwrap();
3214
    api.commit("api v1", &[]).unwrap();
3215
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3216
3217
    let game_work = tempfile::tempdir().unwrap();
3218
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3219
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3220
    write(game_work.path(), "game.c", "int main;\n");
3221
    game.snapshot("t").unwrap();
3222
    game.commit("game on api v1", &[]).unwrap();
3223
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3224
3225
    let consumers = || async {
3226
        let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3227
        assert_eq!(st, StatusCode::OK, "{body}");
3228
        serde_json::from_str::<Vec<serde_json::Value>>(&body).unwrap()
3229
    };
3230
    // The index is written by the push's after-work, a moment after the
3231
    // client hears the push succeeded.
3232
    let settle = |want: &'static (dyn Fn(&[serde_json::Value]) -> bool + Sync)| {
3233
        let consumers = &consumers;
3234
        async move {
3235
            for _ in 0..100 {
3236
                let list = consumers().await;
3237
                if want(&list) {
3238
                    return list;
3239
                }
3240
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3241
            }
3242
            consumers().await
3243
        }
3244
    };
3245
    let list = settle(&|l| !l.is_empty()).await;
3246
    assert_eq!(list.len(), 1, "{list:?}");
3247
    assert_eq!(
3248
        (list[0]["name"].as_str(), list[0]["path"].as_str(), list[0]["bookmark"].as_str()),
3249
        (Some("game"), Some("deps/api"), Some("main"))
3250
    );
3251
    assert_eq!(list[0]["behind"], 0);
3252
3253
    // The upstream moves on: the consumer is one change behind.
3254
    write(api_work.path(), "api.c", "v2\n");
3255
    api.snapshot("t").unwrap();
3256
    api.commit("api v2", &[]).unwrap();
3257
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3258
    assert_eq!(settle(&|l| l.first().is_some_and(|c| c["behind"] == 1)).await[0]["behind"], 1);
3259
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3260
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains("1 behind"), "the page shows it");
3261
3262
    // A private consumer is not shown to someone who cannot read it.
3263
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3264
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", None, None).await;
3265
    assert_eq!(body.trim(), "[]");
3266
    let (_, page) = call(&h.app, "GET", "/andy/api", None, None).await;
3267
    assert!(!page.contains("andy/game"));
3268
    sqlx::query("UPDATE repositories SET visibility = 'public' WHERE name = 'game'").execute(&h.app.db).await.unwrap();
3269
3270
    // A bump (DF3): one signed change on the target moving only the pin, on
3271
    // `diffusion/deps/api`; again with the same state, nothing new.
3272
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3273
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3274
    let api_heads = api.bookmark_heads().unwrap();
3275
    let bumped = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap();
3276
    let oxygenhub::diffusion::Bumped::Moved { bookmark, heads, .. } = bumped else { panic!("{bumped:?}") };
3277
    assert_eq!(bookmark, "diffusion/deps/api");
3278
    game.fetch("origin").unwrap();
3279
    let bump_state = game.load_state(&heads).unwrap().materialize();
3280
    let pin = match &bump_state.files["deps/api"].content {
3281
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3282
        other => panic!("{other:?}"),
3283
    };
3284
    assert!(
3285
        matches!(&pin, oxy_core::subrepo::Pin::Oxy { heads, .. } if { let mut a = heads.clone(); a.sort(); let mut b = api_heads.clone(); b.sort(); a == b }),
3286
        "{pin:?}"
3287
    );
3288
    assert!(bump_state.files.contains_key("game.c"), "the rest of the game is as it was");
3289
    assert!(matches!(
3290
        oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, api_heads.clone()).await.unwrap(),
3291
        oxygenhub::diffusion::Bumped::Already { .. }
3292
    ));
3293
    // A state lacking changes the pin has (as when the consumer pinned an
3294
    // upstream proposal not landed yet) is combined with the pin, never
3295
    // dropping what it relies on.
3296
    write(api_work.path(), "other.c", "v3\n");
3297
    api.snapshot("t").unwrap();
3298
    let v3 = api.commit("api v3, on its own", &[]).unwrap();
3299
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3300
    let only_v3 = api.load_state(&[v3]).unwrap().heads().to_vec();
3301
    let combined = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, only_v3).await.unwrap();
3302
    let oxygenhub::diffusion::Bumped::Moved { heads: ch, .. } = combined else { panic!("{combined:?}") };
3303
    game.fetch("origin").unwrap();
3304
    let st = game.load_state(&ch).unwrap().materialize();
3305
    let pin = match &st.files["deps/api"].content {
3306
        oxy_core::state::FileContent::Opaque { blobs } => oxy_core::subrepo::Pin::decode(&game.read_blob(&blobs[0]).unwrap()).unwrap(),
3307
        other => panic!("{other:?}"),
3308
    };
3309
    let oxy_core::subrepo::Pin::Oxy { heads: pinned, .. } = pin else { panic!() };
3310
    let all = api.load_state(&pinned).unwrap();
3311
    // The game's main still pins v1 alone; combined with v3, it is both.
3312
    assert!(all.contains(&v3) && all.len() == 2, "v1 and v3, {} changes", all.len());
3313
    // The upstream moves again: the same bookmark moves.
3314
    let newer = api.bookmark_heads().unwrap();
3315
    let again = oxygenhub::diffusion::bump(&h.app, &game_row, "main", "deps/api", &api_row, newer).await.unwrap();
3316
    assert!(matches!(again, oxygenhub::diffusion::Bumped::Moved { ref bookmark, .. } if bookmark == "diffusion/deps/api"), "{again:?}");
3317
3318
    // Following is off by default; owners turn it on (DF2).
3319
    let put =
3320
        |body: &'static str, who: Option<&'static str>| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", who, Some(body.into()));
3321
    let (st, body) = put(r#"{"follow":"green"}"#, Some("site")).await;
3322
    assert_eq!(st, StatusCode::OK, "{body}");
3323
    assert!(body.contains("\"follow\":\"green\"") && body.contains("\"from\":\"setting\""), "{body}");
3324
    assert_eq!(put(r#"{"follow":"sometimes"}"#, Some("site")).await.0, StatusCode::BAD_REQUEST);
3325
    assert_ne!(put(r#"{"follow":"any"}"#, None).await.0, StatusCode::OK, "not without a token");
3326
    let (_, body) = put(r#"{"follow":"default"}"#, Some("site")).await;
3327
    assert!(body.contains("\"follow\":\"off\"") && body.contains("\"from\":\"site\""), "{body}");
3328
3329
    // Dropping the subrepo drops the consumer.
3330
    game.submodule_remove("deps/api").unwrap();
3331
    std::fs::remove_dir_all(game_work.path().join("deps/api")).unwrap();
3332
    game.snapshot("t").unwrap();
3333
    game.commit("game without api", &[]).unwrap();
3334
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3335
    let left = settle(&|l| l.is_empty()).await;
3336
    assert!(left.is_empty(), "{left:?}");
3337
}
3338
3339
/// Diffusion D1 end to end (#148): a consumer that follows every move gets
3340
/// a bump proposal on a push; one that follows green gets it when the
3341
/// upstream's run passes. One proposal, kept up to date.
3342
#[tokio::test(flavor = "multi_thread")]
3343
async fn diffusion_proposes_a_bump_when_the_upstream_moves() {
3344
    let h = hub().await;
3345
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3346
    create(&h.app, "andy", "api").await;
3347
    create(&h.app, "andy", "game").await;
3348
    // Run every job of the upstream's newest run to a pass, keeping each claim.
3349
    let seen: std::sync::Mutex<Vec<serde_json::Value>> = std::sync::Mutex::new(Vec::new());
3350
    let seen = &seen;
3351
    let hub_app = &h.app;
3352
    let pass_all = move || async move {
3353
        let h_app = hub_app;
3354
        for _ in 0..20 {
3355
            let Some(a) = claim(h_app).await else {
3356
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3357
                if !jobs_left(h_app).await {
3358
                    break;
3359
                }
3360
                continue;
3361
            };
3362
            seen.lock().unwrap().push(a.clone());
3363
            let id = a["job_id"].as_i64().unwrap();
3364
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3365
            assert_eq!(
3366
                finish(h_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3367
                StatusCode::NO_CONTENT
3368
            );
3369
        }
3370
    };
3371
    let api_work = tempfile::tempdir().unwrap();
3372
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3373
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3374
    write(api_work.path(), "test.sh", "echo ok\n");
3375
    write(api_work.path(), "api.h", "v1\n");
3376
    api.snapshot("t").unwrap();
3377
    api.commit("api v1", &[]).unwrap();
3378
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3379
    pass_all().await;
3380
3381
    let game_work = tempfile::tempdir().unwrap();
3382
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3383
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3384
    write(game_work.path(), "game.c", "int main;\n");
3385
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3386
    write(game_work.path(), "test.sh", "echo ok\n");
3387
    game.snapshot("t").unwrap();
3388
    game.commit("game on api v1", &[]).unwrap();
3389
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3390
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3391
    let bump = || async {
3392
        for _ in 0..100 {
3393
            let open = db::proposals::list(&h.app.db, game_row.id, &["open"]).await.unwrap();
3394
            if let Some(p) = open.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api") {
3395
                return Some(p);
3396
            }
3397
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3398
        }
3399
        None
3400
    };
3401
3402
    // Off by default: an upstream move proposes nothing.
3403
    write(api_work.path(), "a2.c", "v2\n");
3404
    api.snapshot("t").unwrap();
3405
    api.commit("api v2: faster sprites", &[]).unwrap();
3406
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3407
    pass_all().await;
3408
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3409
    assert!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().is_empty(), "off proposes nothing");
3410
3411
    // Turned on to follow every move: bumped at once to where the upstream
3412
    // is (v2), by the diffusion account; the next push updates it.
3413
    let put = |body: &'static str| call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(body.into()));
3414
    assert_eq!(put(r#"{"follow":"any"}"#).await.0, StatusCode::OK);
3415
    let first = bump().await.expect("caught up when turned on");
3416
    assert!(first.title.contains("1 change") && first.body.contains("api v2: faster sprites"), "{:?}", first.title);
3417
    // The bump's pipeline runs, as a push of it would, so the proposal is tested.
3418
    let mut ran = false;
3419
    for _ in 0..100 {
3420
        if runs_of(&h.app, "andy", "game").await.iter().any(|r| r.bookmark == "diffusion/deps/api") {
3421
            ran = true;
3422
            break;
3423
        }
3424
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3425
    }
3426
    assert!(ran, "a run of the bump");
3427
    pass_all().await;
3428
    write(api_work.path(), "a3.c", "v3\n");
3429
    api.snapshot("t").unwrap();
3430
    api.commit("api v3: save slots past ten", &[]).unwrap();
3431
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3432
    let mut p = first.clone();
3433
    for _ in 0..100 {
3434
        p = bump().await.unwrap();
3435
        if p.body.contains("api v3") {
3436
            break;
3437
        }
3438
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3439
    }
3440
    assert_eq!(p.number, first.number, "the same proposal");
3441
    assert_eq!((p.author.as_str(), p.target.as_str()), ("diffusion", "main"));
3442
    assert!(p.title.contains("deps/api") && p.title.contains("andy/api") && p.title.contains("2 changes"), "{}", p.title);
3443
    assert!(p.body.contains("api v2: faster sprites") && p.body.contains("api v3: save slots past ten"), "{}", p.body);
3444
    let labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap();
3445
    assert!(labels.iter().any(|l| l.name == "dependencies"));
3446
    pass_all().await;
3447
3448
    // Following green: a push alone does not move it; the passing run does,
3449
    // and the same proposal is brought up to date.
3450
    assert_eq!(put(r#"{"follow":"green"}"#).await.0, StatusCode::OK);
3451
    write(api_work.path(), "a4.c", "v4\n");
3452
    api.snapshot("t").unwrap();
3453
    api.commit("api v4: rsm_set cheaper", &[]).unwrap();
3454
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3455
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;
3456
    assert!(!bump().await.unwrap().body.contains("api v4"), "not before its run passes");
3457
    pass_all().await;
3458
    let mut updated = None;
3459
    for _ in 0..100 {
3460
        let p2 = bump().await.unwrap();
3461
        if p2.body.contains("api v4") {
3462
            updated = Some(p2);
3463
            break;
3464
        }
3465
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3466
    }
3467
    let p2 = updated.expect("brought up to date once the run passed");
3468
    assert_eq!(p2.number, p.number, "the same proposal");
3469
    assert!(p2.title.contains("3 changes"), "{}", p2.title);
3470
    assert_eq!(db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap().len(), 1, "never a pile of bumps");
3471
3472
    // The views (#150): the upstream's Diffusion tab lists the game with its
3473
    // status; the game's tab and overview say what it follows.
3474
    pass_all().await;
3475
    let (st, page) = call(&h.app, "GET", "/andy/api/diffusion", None, None).await;
3476
    assert_eq!(st, StatusCode::OK);
3477
    assert!(page.contains("Diffuses to") && page.contains("andy/game") && page.contains(&format!("#{}", p2.number)), "the bump is listed");
3478
    assert!(page.contains("df-green"), "a passing run of a checked upstream is green");
3479
    // The ripples backdrop: the page's own repositories and tones.
3480
    assert!(
3481
        page.contains(r#""scene":"ripples""#) && page.contains(r#"["andy/game","#) && page.contains(r#""repo":"andy/api""#),
3482
        "the ripples' data"
3483
    );
3484
    let (_, page) = call(&h.app, "GET", "/andy/game/diffusion", None, None).await;
3485
    assert!(page.contains("Takes from") && page.contains("andy/api"));
3486
    let (_, overview) = call(&h.app, "GET", "/andy/game", None, None).await;
3487
    assert!(overview.contains("Takes from") && overview.contains(">Diffusion</a>"), "the tab and the panel");
3488
    // Both directions through the API (#153), as the extension reads them.
3489
    let (st, body) = call(&h.app, "GET", "/api/v1/repos/andy/game/diffusion", Some("site"), None).await;
3490
    assert_eq!(st, StatusCode::OK, "{body}");
3491
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3492
    assert!(d.diffuses_to.is_empty(), "nothing pins the game");
3493
    let pin = d.takes_from.first().expect("the game takes from the api");
3494
    assert_eq!((pin.upstream.as_str(), pin.consumer.as_str()), ("andy/api", "andy/game"));
3495
    assert_eq!(pin.bump, Some(p2.number));
3496
    assert_eq!(pin.upstream_state.tone, "green", "{body}");
3497
    let (_, body) = call(&h.app, "GET", "/api/v1/repos/andy/api/diffusion", Some("site"), None).await;
3498
    let d: hub_api::Diffusion = serde_json::from_str(&body).unwrap();
3499
    assert!(d.takes_from.is_empty() && d.diffuses_to.iter().any(|p| p.consumer == "andy/game"), "{body}");
3500
    let (st, _) = call(&h.app, "GET", "/admin/diffusion", None, None).await;
3501
    assert_eq!(st, StatusCode::NOT_FOUND, "administrators only");
3502
3503
    // Landing the bump on the hub moves the game's pin as a push would:
3504
    // the index follows, so it is no longer behind.
3505
    let (st, body) =
3506
        call(&h.app, "POST", &format!("/api/v1/repos/andy/game/proposals/{}/land", p2.number), Some("site"), Some("{}".into())).await;
3507
    assert_eq!(st, StatusCode::OK, "{body}");
3508
    let mut behind = serde_json::Value::Null;
3509
    for _ in 0..100 {
3510
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3511
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3512
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3513
        if behind == 0 {
3514
            break;
3515
        }
3516
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3517
    }
3518
    assert_eq!(behind, 0, "the index followed the landing");
3519
3520
    // A private upstream: the bump's run (started by the diffusion account,
3521
    // which cannot read it) still gets the subrepo it bumps.
3522
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'api'").execute(&h.app.db).await.unwrap();
3523
    seen.lock().unwrap().clear();
3524
    write(api_work.path(), "a6.c", "v6\n");
3525
    api.snapshot("t").unwrap();
3526
    api.commit("api v6", &[]).unwrap();
3527
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3528
    // The bump's run starts in the background: wait for its job, under a
3529
    // loaded test run as well as alone.
3530
    let mut bump_job = None;
3531
    for _ in 0..100 {
3532
        pass_all().await;
3533
        bump_job = seen.lock().unwrap().iter().find(|c| c["repo"] == "andy/game" && c["bookmark"] == "diffusion/deps/api").cloned();
3534
        if bump_job.is_some() {
3535
            break;
3536
        }
3537
        tokio::time::sleep(std::time::Duration::from_millis(100)).await;
3538
    }
3539
    let bump_job = bump_job.expect("the bump's job ran");
3540
    let subs: Vec<&str> = bump_job["subrepos"].as_array().unwrap().iter().filter_map(|s| s["path"].as_str()).collect();
3541
    assert_eq!(subs, vec!["deps/api"], "{bump_job}");
3542
3543
    // A consumer turning Diffusion on is bumped at once to the upstream's
3544
    // newest passing state, without waiting for it to move again.
3545
    create(&h.app, "andy", "game2").await;
3546
    let g2_work = tempfile::tempdir().unwrap();
3547
    let g2 = client(&format!("{}/andy/game2", h.base), g2_work.path());
3548
    g2.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3549
    g2.snapshot("t").unwrap();
3550
    g2.commit("game2 on api", &[]).unwrap();
3551
    assert!(g2.push("origin", false).unwrap().iter().all(|r| r.ok));
3552
    // Its pin is api's newest state already: move api on, pass the run.
3553
    write(api_work.path(), "a5.c", "v5\n");
3554
    api.snapshot("t").unwrap();
3555
    api.commit("api v5", &[]).unwrap();
3556
    let api_row = db::repos::get(&h.app.db, "andy", "api").await.unwrap().unwrap();
3557
    let runs_before = db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len();
3558
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3559
    // The push's run is made in the background: wait for it, or pass_all
3560
    // can finish before it exists and v5 never passes (a flake under load).
3561
    for _ in 0..300 {
3562
        if db::flow::runs(&h.app.db, api_row.id, 100, None).await.unwrap().len() > runs_before {
3563
            break;
3564
        }
3565
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
3566
    }
3567
    pass_all().await;
3568
    let g2_row = db::repos::get(&h.app.db, "andy", "game2").await.unwrap().unwrap();
3569
    for _ in 0..100 {
3570
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = ?")
3571
            .bind(g2_row.id)
3572
            .fetch_one(&h.app.db)
3573
            .await
3574
            .unwrap()
3575
            > 0
3576
        {
3577
            break;
3578
        }
3579
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3580
    }
3581
    assert!(db::proposals::list(&h.app.db, g2_row.id, &[]).await.unwrap().is_empty(), "off until turned on");
3582
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/game2/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3583
    assert_eq!(st, StatusCode::OK);
3584
    let mut caught = None;
3585
    for _ in 0..100 {
3586
        if let Some(p) = db::proposals::list(&h.app.db, g2_row.id, &["open"]).await.unwrap().into_iter().next() {
3587
            caught = Some(p);
3588
            break;
3589
        }
3590
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3591
    }
3592
    let caught = caught.expect("bumped as soon as it was turned on");
3593
    assert!(caught.body.contains("api v5") && caught.title.contains("1 change"), "{:?} {:?}", caught.title, caught.body);
3594
}
3595
3596
/// Whether any job is queued or running.
3597
async fn jobs_left(app: &Shared) -> bool {
3598
    sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM flow_jobs WHERE status IN ('queued', 'running')")
3599
        .fetch_one(&app.db)
3600
        .await
3601
        .unwrap_or(0)
3602
        > 0
3603
}
3604
3605
/// An upstream with no checks never turns green: a consumer following green
3606
/// still gets its bumps, marked amber, `upstream unverified` (#148).
3607
#[tokio::test(flavor = "multi_thread")]
3608
async fn bumps_from_an_upstream_without_checks_are_marked_unverified() {
3609
    let h = hub().await;
3610
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3611
    create(&h.app, "andy", "lib").await;
3612
    create(&h.app, "andy", "app").await;
3613
    let lib_work = tempfile::tempdir().unwrap();
3614
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3615
    write(lib_work.path(), "lib.h", "v1\n");
3616
    lib.snapshot("t").unwrap();
3617
    lib.commit("lib v1", &[]).unwrap();
3618
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3619
    let app_work = tempfile::tempdir().unwrap();
3620
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3621
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
3622
    // It watches lib.c: upstream changes touching it are flagged.
3623
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3624
    write(app_work.path(), ".oxymodules", &format!("{modules}watch = lib.c\n"));
3625
    app.snapshot("t").unwrap();
3626
    app.commit("app on lib", &[]).unwrap();
3627
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
3628
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
3629
    for _ in 0..100 {
3630
        if sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = ?")
3631
            .bind(app_row.id)
3632
            .fetch_one(&h.app.db)
3633
            .await
3634
            .unwrap()
3635
            > 0
3636
        {
3637
            break;
3638
        }
3639
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3640
    }
3641
    let (st, _) = call(&h.app, "PUT", "/api/v1/repos/andy/app/diffusion", Some("site"), Some(r#"{"follow":"green"}"#.into())).await;
3642
    assert_eq!(st, StatusCode::OK);
3643
    write(lib_work.path(), "lib.c", "v2\n");
3644
    lib.snapshot("t").unwrap();
3645
    lib.commit("lib v2", &[]).unwrap();
3646
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3647
    let mut found = None;
3648
    for _ in 0..100 {
3649
        if let Some(p) = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap().into_iter().next() {
3650
            found = Some(p);
3651
            break;
3652
        }
3653
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3654
    }
3655
    let p = found.expect("a bump although the upstream never goes green");
3656
    assert!(p.body.contains("Upstream unverified"), "{}", p.body);
3657
    assert!(p.body.contains("Touches what you watch") && p.body.contains("touches `lib.c`") && p.body.contains("⚑"), "{}", p.body);
3658
    let mut labels = Vec::new();
3659
    for _ in 0..100 {
3660
        labels = db::issues::proposal_labels(&h.app.db, p.id).await.unwrap().into_iter().map(|l| l.name).collect::<Vec<String>>();
3661
        if labels.len() == 2 {
3662
            break;
3663
        }
3664
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3665
    }
3666
    assert!(labels.contains(&"upstream unverified".to_string()) && labels.contains(&"dependencies".to_string()), "{labels:?}");
3667
}
3668
3669
/// #134: when a proposal's target moves, its projected state is new; the
3670
/// hub runs the pipeline on it, so its checks are never for an older one.
3671
#[tokio::test(flavor = "multi_thread")]
3672
async fn a_moved_target_runs_its_open_proposals_again() {
3673
    let h = hub().await;
3674
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3675
    create(&h.app, "andy", "demo").await;
3676
    let work = tempfile::tempdir().unwrap();
3677
    let mut c = client(&format!("{}/andy/demo", h.base), work.path());
3678
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3679
    write(work.path(), "test.sh", "echo ok\n");
3680
    c.snapshot("t").unwrap();
3681
    let base = c.commit("base", &[]).unwrap();
3682
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3683
    // Two proposals, each main plus one change.
3684
    for (b, file) in [("fix-a", "a.txt"), ("fix-b", "b.txt")] {
3685
        c.bookmark_create(b, Some(&[base])).unwrap();
3686
        c.bookmark_switch(b, true).unwrap();
3687
        write(work.path(), file, "x\n");
3688
        c.snapshot("t").unwrap();
3689
        c.commit(&format!("add {file}"), &[]).unwrap();
3690
        assert!(c.push_bookmark("origin", b, false).unwrap().iter().all(|r| r.ok));
3691
        let body = serde_json::json!({ "title": b, "target": "main", "source": b }).to_string();
3692
        let (st, out) = call(&h.app, "POST", "/api/v1/repos/andy/demo/proposals", Some("site"), Some(body)).await;
3693
        assert_eq!(st, StatusCode::CREATED, "{out}");
3694
    }
3695
    let row = db::repos::get(&h.app.db, "andy", "demo").await.unwrap().unwrap();
3696
    let props = db::proposals::list(&h.app.db, row.id, &["open"]).await.unwrap();
3697
    let a = props.iter().find(|p| p.source_bookmark == "fix-a").unwrap().number;
3698
    let b = props.iter().find(|p| p.source_bookmark == "fix-b").unwrap().number;
3699
    // Landing fix-a moves main: fix-b's projected state gets a run.
3700
    let (st, out) = call(&h.app, "POST", &format!("/api/v1/repos/andy/demo/proposals/{a}/land"), Some("site"), Some("{}".into())).await;
3701
    assert_eq!(st, StatusCode::OK, "{out}");
3702
    let label = format!("proposal/{b}");
3703
    let mut found = None;
3704
    for _ in 0..100 {
3705
        if let Some(r) = runs_of(&h.app, "andy", "demo").await.into_iter().find(|r| r.bookmark == label) {
3706
            found = Some(r);
3707
            break;
3708
        }
3709
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3710
    }
3711
    let run = found.expect("a run of fix-b's new projected state");
3712
    let projected = db::proposals::get(&h.app.db, row.id, b).await.unwrap().unwrap();
3713
    assert_eq!((run.trigger.as_str(), run.state.as_str()), ("proposal", projected.projected_state.as_str()), "on its projected state");
3714
    // Moving main again by a push does it once more; the same state is not run twice.
3715
    let before = runs_of(&h.app, "andy", "demo").await.len();
3716
    oxygenhub::web::proposals::settle_after_push(&h.app, &row, "main", "andy").await;
3717
    assert_eq!(runs_of(&h.app, "andy", "demo").await.len(), before, "not again for the same state");
3718
}
3719
3720
/// Send image bytes to the hub as their chunks and then a manifest that
3721
/// names no architecture; the manifest as the hub answers it.
3722
async fn send_image(app: &Shared, image: &[u8]) -> (String, serde_json::Value) {
3723
    let mut chunks = std::collections::HashMap::new();
3724
    let m = jet::images::scan(image, None, |c, b| {
3725
        chunks.insert(c.hash().to_string(), b.to_vec());
3726
        Ok(())
3727
    })
3728
    .unwrap();
3729
    for c in m.needed() {
3730
        let (st, body) = put_bytes(app, &format!("/api/v1/flow/images/chunks/{c}"), "site", chunks[c].clone()).await;
3731
        assert_eq!(st, StatusCode::NO_CONTENT, "{body}");
3732
    }
3733
    let (st, body) =
3734
        call(app, "PUT", &format!("/api/v1/flow/images/{}", m.hash), Some("site"), Some(serde_json::to_string(&m).unwrap())).await;
3735
    assert_eq!(st, StatusCode::CREATED, "{body}");
3736
    (m.hash.clone(), serde_json::from_str(&body).unwrap())
3737
}
3738
3739
/// oxygenhub#173 (OxygenFlow spec §11.2, Andy's "detect and learn"): an
3740
/// image sent with no architecture is read from its own files, so a
3741
/// riscv64 runner is never offered an x86_64 image's jobs; an image
3742
/// nobody can read takes the architecture its first pass ran on.
3743
#[tokio::test(flavor = "multi_thread")]
3744
async fn an_image_names_its_own_architecture_and_a_pass_teaches_the_rest() {
3745
    use oxy_core::identity::SecretKey;
3746
    let h = hub().await;
3747
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3748
    // An ext4 image whose shell is x86_64, as `flow rootfs import` makes one.
3749
    let dir = tempfile::tempdir().unwrap();
3750
    let tree = dir.path().join("tree");
3751
    std::fs::create_dir_all(tree.join("bin")).unwrap();
3752
    let mut elf = vec![0u8; 64];
3753
    elf[..7].copy_from_slice(b"\x7fELF\x02\x01\x01");
3754
    elf[18..20].copy_from_slice(&0x3Eu16.to_le_bytes());
3755
    std::fs::write(tree.join("bin/sh"), &elf).unwrap();
3756
    let img = dir.path().join("rootfs.ext4");
3757
    let made = std::process::Command::new("mkfs.ext4").args(["-q", "-F", "-d"]).arg(&tree).arg(&img).arg("8M").status();
3758
    if !made.is_ok_and(|s| s.success()) {
3759
        eprintln!("mkfs.ext4 not found: skipped");
3760
        return;
3761
    }
3762
    let (x86, answer) = send_image(&h.app, &std::fs::read(&img).unwrap()).await;
3763
    assert_eq!(answer["arch"], "x86_64", "read from its shell: {answer}");
3764
    let (_, body) = call(&h.app, "GET", &format!("/api/v1/flow/images/{x86}"), Some("runner-secret"), None).await;
3765
    assert_eq!(serde_json::from_str::<jet::images::Manifest>(&body).unwrap().arch.as_deref(), Some("x86_64"), "runners fetch it named");
3766
    // One nobody can read: no ext4, no shell.
3767
    let blob: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
3768
    let (unread, answer) = send_image(&h.app, &blob).await;
3769
    assert!(answer["arch"].is_null(), "{answer}");
3770
    let archs = db::flow::image_archs(&h.app.db).await.unwrap();
3771
    assert_eq!((archs.get(&x86).map(String::as_str), archs.get(&unread)), (Some("x86_64"), None));
3772
    // Kept images with none are read once at start.
3773
    sqlx::query("UPDATE jet_images SET arch = ''").execute(&h.app.db).await.unwrap();
3774
    sqlx::query("DELETE FROM flow_images").execute(&h.app.db).await.unwrap();
3775
    assert_eq!(oxygenhub::images::learn_archs(&h.app).await.unwrap(), 1);
3776
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&x86).map(String::as_str), Some("x86_64"));
3777
3778
    // A job on each image.
3779
    create(&h.app, "andy", "arch").await;
3780
    let work = tempfile::tempdir().unwrap();
3781
    let c = client(&format!("{}/andy/arch", h.base), work.path());
3782
    let kdl = format!(
3783
        "schema-version 1\nsandbox \"unread\" {{\n    rootfs \"cas://blob/{unread}\"\n}}\nsandbox \"x86\" {{\n    rootfs \"cas://blob/{x86}\"\n}}\n\
3784
         job \"first\" {{\n    sandbox \"unread\"\n    exec \"make\"\n}}\njob \"second\" {{\n    sandbox \"x86\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n\
3785
         job \"third\" {{\n    sandbox \"unread\"\n    exec \"make\"\n    depends-on \"first\"\n}}\n"
3786
    );
3787
    write(work.path(), ".flow/pipeline.kdl", &kdl);
3788
    c.commit("Jobs on two images", &[]).unwrap();
3789
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
3790
    runs_of(&h.app, "andy", "arch").await;
3791
3792
    // The x86_64 runner passes the first job: its image is x86_64 now.
3793
    let x86_info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3794
    let x86_claim =
3795
        serde_json::json!({ "runner": "earth", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": x86_info });
3796
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3797
    assert_eq!(st, StatusCode::OK, "{body}");
3798
    let first: serde_json::Value = serde_json::from_str(&body).unwrap();
3799
    assert_eq!(first["job"]["name"], "first");
3800
    let ph = first["pipeline_hash"].as_str().unwrap();
3801
    let id = first["job_id"].as_i64().unwrap();
3802
    assert_eq!(
3803
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("first", ph, 0) })).await,
3804
        StatusCode::NO_CONTENT
3805
    );
3806
    assert_eq!(db::flow::image_archs(&h.app.db).await.unwrap().get(&unread).map(String::as_str), Some("x86_64"), "learned");
3807
3808
    // A riscv64 runner is offered neither: one read, one learned.
3809
    let token = "flowreg_narvi";
3810
    db::runners::add_registration(&h.app.db, &blake3::hash(token.as_bytes()).to_hex(), "admin", &Default::default()).await.unwrap();
3811
    let identity = SecretKey::generate().identity("narvi", "", 1);
3812
    let info = serde_json::json!({ "arch": "riscv64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
3813
    let reg = serde_json::json!({ "token": token, "name": "narvi", "identity": hex::encode(identity.encode()), "info": info });
3814
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
3815
    assert_eq!(st, StatusCode::OK, "{body}");
3816
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
3817
    let narvi =
3818
        serde_json::json!({ "runner": "narvi", "runtimes": ["microvm"], "images": [], "fetches_images": true, "info": info }).to_string();
3819
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(narvi)).await;
3820
    assert_eq!(st, StatusCode::NO_CONTENT, "the second job's image is x86_64 and the third's learned so: {body}");
3821
    for _ in 0..2 {
3822
        let (st, body) = call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(x86_claim.to_string())).await;
3823
        assert_eq!(st, StatusCode::OK, "both go to x86_64: {body}");
3824
    }
3825
}
3826
3827
/// Diffusion auto-land (docs/diffusion.md §4.2; Andy chose "opt-in, per
3828
/// repository", 2026-10-13): a consumer that chose `land = auto` has a bump
3829
/// landed by itself, as the diffusion account, once both halves are green;
3830
/// a bump from an upstream with no checks (amber) always waits.
3831
#[tokio::test(flavor = "multi_thread")]
3832
async fn a_consumer_that_chose_auto_lands_green_bumps_itself() {
3833
    let h = hub().await;
3834
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3835
    create(&h.app, "andy", "api").await;
3836
    create(&h.app, "andy", "game").await;
3837
    let hub_app = &h.app;
3838
    // Run every queued job to a pass.
3839
    let pass_all = move || async move {
3840
        for _ in 0..20 {
3841
            let Some(a) = claim(hub_app).await else {
3842
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3843
                if !jobs_left(hub_app).await {
3844
                    break;
3845
                }
3846
                continue;
3847
            };
3848
            let id = a["job_id"].as_i64().unwrap();
3849
            let (name, ph) = (a["job"]["name"].as_str().unwrap().to_string(), a["pipeline_hash"].as_str().unwrap().to_string());
3850
            assert_eq!(
3851
                finish(hub_app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt(&name, &ph, 0) })).await,
3852
                StatusCode::NO_CONTENT
3853
            );
3854
        }
3855
    };
3856
    let api_work = tempfile::tempdir().unwrap();
3857
    let api = client(&format!("{}/andy/api", h.base), api_work.path());
3858
    write(api_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3859
    write(api_work.path(), "test.sh", "echo ok\n");
3860
    api.snapshot("t").unwrap();
3861
    api.commit("api v1", &[]).unwrap();
3862
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3863
    pass_all().await;
3864
    let game_work = tempfile::tempdir().unwrap();
3865
    let game = client(&format!("{}/andy/game", h.base), game_work.path());
3866
    game.submodule_add(&format!("{}/andy/api", h.base), "deps/api", Some("main")).unwrap();
3867
    write(game_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3868
    write(game_work.path(), "test.sh", "echo ok\n");
3869
    game.snapshot("t").unwrap();
3870
    game.commit("game on api v1", &[]).unwrap();
3871
    assert!(game.push("origin", false).unwrap().iter().all(|r| r.ok));
3872
    pass_all().await;
3873
    let game_row = db::repos::get(&h.app.db, "andy", "game").await.unwrap().unwrap();
3874
    for _ in 0..100 {
3875
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = ?")
3876
            .bind(game_row.id)
3877
            .fetch_one(&h.app.db)
3878
            .await
3879
            .unwrap();
3880
        if n > 0 {
3881
            break;
3882
        }
3883
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3884
    }
3885
    let (st, body) =
3886
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"auto"}"#.into())).await;
3887
    assert_eq!(st, StatusCode::OK, "{body}");
3888
    assert!(body.contains(r#""land":"auto""#), "{body}");
3889
    let (st, _) =
3890
        call(&h.app, "PUT", "/api/v1/repos/andy/game/diffusion", Some("site"), Some(r#"{"follow":"green","land":"soon"}"#.into())).await;
3891
    assert_eq!(st, StatusCode::BAD_REQUEST);
3892
3893
    // The upstream moves and passes: the bump is proposed, its run passes,
3894
    // and it lands by itself.
3895
    write(api_work.path(), "a2.c", "v2\n");
3896
    api.snapshot("t").unwrap();
3897
    api.commit("api v2: faster sprites", &[]).unwrap();
3898
    assert!(api.push("origin", false).unwrap().iter().all(|r| r.ok));
3899
    let mut landed = None;
3900
    for _ in 0..100 {
3901
        pass_all().await;
3902
        let all = db::proposals::list(&h.app.db, game_row.id, &[]).await.unwrap();
3903
        if let Some(p) = all.into_iter().find(|p| p.source_bookmark == "diffusion/deps/api" && p.state == "landed") {
3904
            landed = Some(p);
3905
            break;
3906
        }
3907
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3908
    }
3909
    let p = landed.expect("landed by itself once both halves were green");
3910
    assert!(p.body.contains("lands its bumps itself"), "{}", p.body);
3911
    let events = db::proposals::events(&h.app.db, p.id).await.unwrap();
3912
    let landing = events.iter().find(|e| e.event == "landed").expect("a landing on the timeline");
3913
    assert_eq!(landing.actor, "diffusion");
3914
    assert!(landing.detail.contains("Diffusion, both halves green"), "{}", landing.detail);
3915
    // The game's main now pins api v2.
3916
    let mut behind = serde_json::Value::Null;
3917
    for _ in 0..100 {
3918
        let (_, list) = call(&h.app, "GET", "/api/v1/repos/andy/api/consumers", Some("site"), None).await;
3919
        let list: Vec<serde_json::Value> = serde_json::from_str(&list).unwrap();
3920
        behind = list.iter().find(|c| c["name"] == "game").map(|c| c["behind"].clone()).unwrap_or_default();
3921
        if behind == 0 {
3922
            break;
3923
        }
3924
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3925
    }
3926
    assert_eq!(behind, 0, "main moved to the bump");
3927
3928
    // An upstream with no checks: its bump passes in the consumer, but
3929
    // amber never lands by itself, whatever the setting.
3930
    create(&h.app, "andy", "lib").await;
3931
    create(&h.app, "andy", "app").await;
3932
    let lib_work = tempfile::tempdir().unwrap();
3933
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
3934
    write(lib_work.path(), "lib.h", "v1\n");
3935
    lib.snapshot("t").unwrap();
3936
    lib.commit("lib v1", &[]).unwrap();
3937
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3938
    let app_work = tempfile::tempdir().unwrap();
3939
    let app = client(&format!("{}/andy/app", h.base), app_work.path());
3940
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
3941
    let modules = std::fs::read_to_string(app_work.path().join(".oxymodules")).unwrap();
3942
    write(app_work.path(), ".oxymodules", &format!("{modules}follow = green\nland = auto\n"));
3943
    write(app_work.path(), ".flow/pipeline.kdl", &pipeline(""));
3944
    write(app_work.path(), "test.sh", "echo ok\n");
3945
    app.snapshot("t").unwrap();
3946
    app.commit("app on lib", &[]).unwrap();
3947
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
3948
    pass_all().await;
3949
    let app_row = db::repos::get(&h.app.db, "andy", "app").await.unwrap().unwrap();
3950
    for _ in 0..100 {
3951
        let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM diffusion_pins WHERE consumer_id = ?")
3952
            .bind(app_row.id)
3953
            .fetch_one(&h.app.db)
3954
            .await
3955
            .unwrap();
3956
        if n > 0 {
3957
            break;
3958
        }
3959
        tokio::time::sleep(std::time::Duration::from_millis(30)).await;
3960
    }
3961
    write(lib_work.path(), "lib.c", "v2\n");
3962
    lib.snapshot("t").unwrap();
3963
    lib.commit("lib v2", &[]).unwrap();
3964
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
3965
    let mut passed = false;
3966
    for _ in 0..100 {
3967
        pass_all().await;
3968
        let s: Option<String> = sqlx::query_scalar(
3969
            "SELECT status FROM flow_runs WHERE repo_id = ? AND bookmark = 'diffusion/deps/lib' ORDER BY id DESC LIMIT 1",
3970
        )
3971
        .bind(app_row.id)
3972
        .fetch_optional(&h.app.db)
3973
        .await
3974
        .unwrap();
3975
        if s.as_deref() == Some("passed") {
3976
            passed = true;
3977
            break;
3978
        }
3979
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
3980
    }
3981
    assert!(passed, "the app's run on the bump passed");
3982
    assert_eq!(oxygenhub::diffusion::auto_land(&h.app, &app_row, "deps/lib").await, Err(oxygenhub::diffusion::Held::Unverified));
3983
    let open = db::proposals::list(&h.app.db, app_row.id, &["open"]).await.unwrap();
3984
    assert!(open.iter().any(|p| p.source_bookmark == "diffusion/deps/lib"), "amber waits for a person");
3985
}
3986
3987
/// oxygenflow#31: one finished job runs again in the same run, with the
3988
/// jobs that depend on it; what it depends on keeps its result, so a flaky
3989
/// test reruns without its build. Not while the run is live, and only a
3990
/// job the run has.
3991
#[tokio::test(flavor = "multi_thread")]
3992
async fn one_job_reruns_with_what_depends_on_it() {
3993
    let h = hub().await;
3994
    db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
3995
    create(&h.app, "andy", "flaky").await;
3996
    let work = tempfile::tempdir().unwrap();
3997
    let c = client(&format!("{}/andy/flaky", h.base), work.path());
3998
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
3999
    write(work.path(), "test.sh", "echo ok\n");
4000
    c.commit("Add a pipeline", &[]).unwrap();
4001
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4002
    let run = runs_of(&h.app, "andy", "flaky").await[0].clone();
4003
    // build and lint pass; test fails, as a flaky one does.
4004
    let (st, _) =
4005
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4006
    assert_eq!(st, StatusCode::CONFLICT, "not while the run is live");
4007
    while let Some(j) = claim(&h.app).await {
4008
        let id = j["job_id"].as_i64().unwrap();
4009
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4010
        let exit = if name == "test" { 1 } else { 0 };
4011
        let log = serde_json::json!({ "records": [{ "t": 1, "stream": "out", "text": format!("{name} ran") }] });
4012
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{id}/log"), Some("runner-secret"), Some(log.to_string())).await;
4013
        assert_eq!(
4014
            finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) }))
4015
                .await,
4016
            StatusCode::NO_CONTENT
4017
        );
4018
    }
4019
    let status = |n: &'static str| {
4020
        let (app, run_id) = (h.app.clone(), run.id);
4021
        async move { db::flow::jobs(&app.db, run_id).await.unwrap().into_iter().find(|j| j.name == n).unwrap() }
4022
    };
4023
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "failed");
4024
    let failed_test = status("test").await;
4025
4026
    // The test again: build and lint keep their results.
4027
    let (st, body) =
4028
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/test/rerun", run.number), Some("site"), None).await;
4029
    assert_eq!(st, StatusCode::OK, "{body}");
4030
    assert!(body.contains(r#""queued":1"#), "{body}");
4031
    assert_eq!(
4032
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4033
        ("passed".into(), "passed".into(), "queued".into())
4034
    );
4035
    assert!(db::flow::log(&h.app.db, failed_test.id, 0, 100).await.unwrap().is_empty(), "its old log is gone");
4036
    assert!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().live());
4037
    let checks = checks_when(&h.app, run.repo_id, &run.state, 3).await;
4038
    assert_eq!(checks.iter().find(|c| c.name == "flow/test").map(|c| c.status.as_str()), Some("queued"));
4039
    let j = claim(&h.app).await.expect("the test, queued again");
4040
    assert_eq!(j["job"]["name"], "test");
4041
    let ph = j["pipeline_hash"].as_str().unwrap().to_string();
4042
    let id = j["job_id"].as_i64().unwrap();
4043
    assert_eq!(
4044
        finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("test", &ph, 0) })).await,
4045
        StatusCode::NO_CONTENT
4046
    );
4047
    assert_eq!(db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap().status, "passed", "the run is whole again");
4048
    // Andy owns it: told it failed, then that it is fixed (#183).
4049
    let andy_id = db::accounts::account_by_name(&h.app.db, "andy").await.unwrap().unwrap().id;
4050
    let kinds: Vec<String> = db::notify::inbox(&h.app.db, andy_id, 20).await.unwrap().into_iter().map(|n| n.kind).collect();
4051
    assert!(kinds.contains(&"flow.failed".to_string()) && kinds.contains(&"flow.fixed".to_string()), "{kinds:?}");
4052
4053
    // The build again brings the test that depends on it; lint stays.
4054
    let (_, body) =
4055
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/build/rerun", run.number), Some("site"), None).await;
4056
    assert!(body.contains(r#""queued":2"#), "{body}");
4057
    assert_eq!(
4058
        (status("build").await.status, status("lint").await.status, status("test").await.status),
4059
        ("queued".into(), "passed".into(), "queued".into())
4060
    );
4061
    let (st, _) =
4062
        call(&h.app, "POST", &format!("/api/v1/repos/andy/flaky/flow/runs/{}/jobs/deploy/rerun", run.number), Some("site"), None).await;
4063
    assert_eq!(st, StatusCode::CONFLICT, "live again, and no such job either way");
4064
}
4065
4066
/// oxygenflow#30: a failed run tells its pusher and the repository's
4067
/// watchers; a runner whose last five jobs ended in infrastructure errors
4068
/// is drained and the administrators told, counting only since an
4069
/// administrator last made it active.
4070
#[tokio::test(flavor = "multi_thread")]
4071
async fn failed_runs_are_told_and_an_erroring_runner_is_drained() {
4072
    let h = hub().await;
4073
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4074
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4075
    create(&h.app, "andy", "alerts").await;
4076
    let row = db::repos::get(&h.app.db, "andy", "alerts").await.unwrap().unwrap();
4077
    db::notify::set_watch(&h.app.db, bob.id, row.id, true).await.unwrap();
4078
    let work = tempfile::tempdir().unwrap();
4079
    let c = client(&format!("{}/andy/alerts", h.base), work.path());
4080
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4081
    write(work.path(), "test.sh", "exit 1\n");
4082
    c.commit("Add a pipeline", &[]).unwrap();
4083
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4084
    let run = runs_of(&h.app, "andy", "alerts").await[0].clone();
4085
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = ?").bind(run.id).execute(&h.app.db).await.unwrap();
4086
    while let Some(j) = claim(&h.app).await {
4087
        let id = j["job_id"].as_i64().unwrap();
4088
        let (name, ph) = (j["job"]["name"].as_str().unwrap().to_string(), j["pipeline_hash"].as_str().unwrap().to_string());
4089
        let exit = if name == "test" { 1 } else { 0 };
4090
        finish(&h.app, id, serde_json::json!({ "exit_code": exit, "duration_ms": 10, "receipt": receipt(&name, &ph, exit as u32) })).await;
4091
    }
4092
    let told = |id: i64| {
4093
        let db = h.app.db.clone();
4094
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.failed").collect::<Vec<_>>() }
4095
    };
4096
    let (for_andy, for_bob) = (told(andy.id).await, told(bob.id).await);
4097
    assert_eq!((for_andy.len(), for_bob.len()), (1, 1), "the pusher and a watcher");
4098
    assert!(for_andy[0].title.contains(&format!("run #{} on main failed (test)", run.number)), "{}", for_andy[0].title);
4099
    assert_eq!(for_andy[0].url, format!("/andy/alerts/flow/{}", run.number));
4100
4101
    // Five infrastructure errors in a row drain the runner.
4102
    let runner_id = || {
4103
        let db = h.app.db.clone();
4104
        async move { sqlx::query_scalar::<_, i64>("SELECT id FROM flow_runners WHERE name = 'test-1'").fetch_one(&db).await.unwrap() }
4105
    };
4106
    let mut errors = 0;
4107
    while errors < 5 {
4108
        let (st, _) = call(&h.app, "POST", "/api/v1/repos/andy/alerts/flow/runs", Some("site"), Some("{}".into())).await;
4109
        assert_eq!(st, StatusCode::CREATED);
4110
        while let Some(j) = claim(&h.app).await {
4111
            let id = j["job_id"].as_i64().unwrap();
4112
            let st = finish(
4113
                &h.app,
4114
                id,
4115
                serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "the microVM did not start: /dev/kvm busy" }),
4116
            )
4117
            .await;
4118
            assert_eq!(st, StatusCode::NO_CONTENT);
4119
            errors += 1;
4120
            if errors == 5 {
4121
                break;
4122
            }
4123
        }
4124
    }
4125
    let state = |id: i64| {
4126
        let db = h.app.db.clone();
4127
        async move { db::runners::get(&db, id).await.unwrap().unwrap().state }
4128
    };
4129
    let id = runner_id().await;
4130
    assert_eq!(state(id).await, "draining");
4131
    let drained: Vec<_> =
4132
        db::notify::inbox(&h.app.db, andy.id, 50).await.unwrap().into_iter().filter(|n| n.kind == "flow.runner_drained").collect();
4133
    assert_eq!(drained.len(), 1, "the administrator is told");
4134
    assert!(drained[0].title.contains("/dev/kvm busy"), "{}", drained[0].title);
4135
    assert!(
4136
        !told(bob.id).await.is_empty()
4137
            && db::notify::inbox(&h.app.db, bob.id, 50).await.unwrap().iter().all(|n| n.kind != "flow.runner_drained")
4138
    );
4139
    // Made active again, past errors no longer count.
4140
    db::runners::set_state(&h.app.db, id, "active").await.unwrap();
4141
    assert_eq!(db::runners::erroring(&h.app.db, id, 5).await.unwrap(), None);
4142
}
4143
4144
/// #225: an ordinary user turns Flow on for their repository on their own
4145
/// runner, and the site's runners never take its jobs.
4146
#[tokio::test(flavor = "multi_thread")]
4147
async fn owners_run_flow_on_their_own_runners_only() {
4148
    use oxy_core::identity::SecretKey;
4149
    let h = hub().await;
4150
    let register = |name: &'static str| {
4151
        let app = h.app.clone();
4152
        async move {
4153
            let body = format!("username={name}&email={name}%40example.com&password=correct-horse-battery&setup=test-setup");
4154
            let res = oxygenhub::router(app)
4155
                .oneshot(
4156
                    Request::post("/register")
4157
                        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
4158
                        .body(Body::from(body))
4159
                        .unwrap(),
4160
                )
4161
                .await
4162
                .unwrap();
4163
            res.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap().split(';').next().unwrap().to_string()
4164
        }
4165
    };
4166
    register("andy").await; // the first account: the site's administrator
4167
    let bob = register("bob").await;
4168
    create(&h.app, "bob", "game").await;
4169
    let web = |method: &'static str, path: &str, body: Option<String>| {
4170
        let (app, cookie, path) = (h.app.clone(), bob.clone(), path.to_string());
4171
        async move {
4172
            let mut req = Request::builder().method(method).uri(path).header(header::COOKIE, cookie);
4173
            if body.is_some() {
4174
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
4175
            }
4176
            let res = oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap();
4177
            String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()
4178
        }
4179
    };
4180
    let csrf_of = |page: &str| {
4181
        let i = page.find("name=\"_csrf\" value=\"").unwrap() + "name=\"_csrf\" value=\"".len();
4182
        page[i..].split('"').next().unwrap().to_string()
4183
    };
4184
    // No runner of his own yet: he is told how, and cannot switch it on.
4185
    let page = web("GET", "/bob/game/settings", None).await;
4186
    assert!(page.contains("register a runner for this repository") && !page.contains("value=\"own\""), "{page}");
4187
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4188
    assert!(page.contains("Register a runner for this repository"), "{page}");
4189
    // He registers one.
4190
    let page = web("GET", "/bob/game/settings", None).await;
4191
    let page = web("POST", "/bob/game/settings/runners/token", Some(format!("_csrf={}", csrf_of(&page)))).await;
4192
    let i = page.find("--token ").unwrap() + "--token ".len();
4193
    let token: String = page[i..].chars().take_while(|c| !c.is_whitespace()).collect();
4194
    let info = serde_json::json!({ "arch": "x86_64", "os": "linux", "version": "0.1.0", "labels": [], "max_jobs": 1 });
4195
    let identity = SecretKey::generate().identity("bobs", "", 1);
4196
    let reg = serde_json::json!({ "token": token, "name": "bobs", "identity": hex::encode(identity.encode()), "info": info });
4197
    let (st, body) = call(&h.app, "POST", "/api/v1/flow/runners/register", None, Some(reg.to_string())).await;
4198
    assert_eq!(st, StatusCode::OK, "{body}");
4199
    let credential = serde_json::from_str::<serde_json::Value>(&body).unwrap()["credential"].as_str().unwrap().to_string();
4200
    // The site's runners stay a site administrator's to grant; his own he may choose.
4201
    let page = web("GET", "/bob/game/settings", None).await;
4202
    assert!(page.contains("value=\"own\"") && !page.contains("value=\"on\""), "{page}");
4203
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=on", csrf_of(&page)))).await;
4204
    assert!(page.contains("Only site administrators let the site's runners"), "{page}");
4205
    let page = web("POST", "/bob/game/settings/flow", Some(format!("_csrf={}&flow=own", csrf_of(&page)))).await;
4206
    assert!(page.contains("value=\"own\" checked") && page.contains("start runs"), "{page}");
4207
    assert_eq!(db::repos::get(&h.app.db, "bob", "game").await.unwrap().unwrap().flow, "own");
4208
    // A push starts a run; the site's runner is not offered it, his is.
4209
    let work = tempfile::tempdir().unwrap();
4210
    let c = client(&format!("{}/bob/game", h.base), work.path());
4211
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
4212
    write(work.path(), "test.sh", "echo ok\n");
4213
    c.snapshot("t").unwrap();
4214
    c.commit("A pipeline", &[]).unwrap();
4215
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4216
    assert_eq!(runs_of(&h.app, "bob", "game").await.len(), 1, "a run started");
4217
    assert!(claim(&h.app).await.is_none(), "the site's runner is not offered it");
4218
    let body = serde_json::json!({ "runner": "ignored", "runtimes": ["microvm"], "info": info }).to_string();
4219
    let (st, job) = call(&h.app, "POST", "/api/v1/flow/claim", Some(&credential), Some(body)).await;
4220
    assert_eq!(st, StatusCode::OK, "{job}");
4221
    assert_eq!(serde_json::from_str::<serde_json::Value>(&job).unwrap()["repo"], "bob/game");
4222
}
4223
4224
#[tokio::test(flavor = "multi_thread")]
4225
async fn a_job_takes_the_artifact_its_producer_kept() {
4226
    let h = hub().await;
4227
    create(&h.app, "andy", "demo").await;
4228
    let url = format!("{}/andy/demo", h.base);
4229
    let work = tempfile::tempdir().unwrap();
4230
    let c = client(&url, work.path());
4231
    write(
4232
        work.path(),
4233
        ".flow/pipeline.kdl",
4234
        &format!(
4235
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"plan\" {{\n    sandbox \"alpine\"\n    exec \"plan\"\n    output {{\n        artifact \"tfplan\" {{\n            path \"/src/out/tfplan\"\n        }}\n    }}\n}}\njob \"apply\" {{\n    sandbox \"alpine\"\n    depends-on \"plan\"\n    input {{\n        artifact \"tfplan\" from \"plan\"\n        path \"/src/tfplan\"\n    }}\n    exec \"apply\"\n}}\n"
4236
        ),
4237
    );
4238
    c.snapshot("test").unwrap();
4239
    c.commit("Plan, then apply that plan", &[]).unwrap();
4240
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4241
4242
    // The plan job runs and keeps its plan, named by its receipt.
4243
    let runs = runs_of(&h.app, "andy", "demo").await;
4244
    assert_eq!(runs.len(), 1, "a run");
4245
    let jobs = db::flow::jobs(&h.app.db, runs[0].id).await.unwrap();
4246
    assert!(!jobs.is_empty(), "jobs: {:?}", runs[0]);
4247
    let p = claim(&h.app)
4248
        .await
4249
        .unwrap_or_else(|| panic!("nothing to claim: {:?}", jobs.iter().map(|j| (&j.name, &j.status, &j.error)).collect::<Vec<_>>()));
4250
    assert_eq!(p["job"]["name"], "plan");
4251
    let plan_id = p["job_id"].as_i64().unwrap();
4252
    let plan = b"the reviewed plan".to_vec();
4253
    let (st, text) = upload(&h.app, plan_id, "tfplan", &plan).await;
4254
    assert_eq!(st, StatusCode::OK, "{text}");
4255
    let blob = oxy_core::repo::Repo::blob_ref(&plan).to_hex();
4256
    let mut r = receipt("plan", p["pipeline_hash"].as_str().unwrap(), 0);
4257
    r["outputs"] = serde_json::json!([blob]);
4258
    assert_eq!(
4259
        finish(&h.app, plan_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": r })).await,
4260
        StatusCode::NO_CONTENT
4261
    );
4262
4263
    // The apply job is told what to take and the blob to expect, and the
4264
    // runner fetches exactly those bytes.
4265
    let a = claim(&h.app).await.unwrap();
4266
    assert_eq!(a["job"]["name"], "apply");
4267
    let apply_id = a["job_id"].as_i64().unwrap();
4268
    assert_eq!(
4269
        a["inputs"],
4270
        serde_json::json!([{ "artifact": "tfplan", "from": "plan", "path": "/src/tfplan", "blob": blob }]),
4271
        "the claim names the producer's blob"
4272
    );
4273
    let req = Request::get(format!("/api/v1/flow/jobs/{apply_id}/inputs/0")).header(header::AUTHORIZATION, "Bearer runner-secret");
4274
    let res = oxygenhub::router(h.app.clone()).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4275
    assert_eq!(res.status(), StatusCode::OK);
4276
    assert_eq!(res.into_body().collect().await.unwrap().to_bytes().to_vec(), plan);
4277
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/1"), Some("runner-secret"), None).await;
4278
    assert_eq!(st, StatusCode::NOT_FOUND, "no second input");
4279
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{apply_id}/inputs/0"), None, None).await;
4280
    assert_eq!(st, StatusCode::UNAUTHORIZED, "runners only");
4281
    let (st, _) = call(&h.app, "GET", &format!("/api/v1/flow/jobs/{plan_id}/inputs/0"), Some("runner-secret"), None).await;
4282
    assert_eq!(st, StatusCode::CONFLICT, "only a running job's");
4283
}
4284
4285
#[tokio::test(flavor = "multi_thread")]
4286
async fn a_job_waits_for_approval_and_is_approved_rejected_or_expires() {
4287
    let h = hub().await;
4288
    let andy = db::accounts::create_account(&h.app.db, "andy", "[email protected]", "x", "salt", true).await.unwrap();
4289
    let bob = db::accounts::create_account(&h.app.db, "bob", "[email protected]", "x", "salt", false).await.unwrap();
4290
    let carol = db::accounts::create_account(&h.app.db, "carol", "[email protected]", "x", "salt", true).await.unwrap();
4291
    create(&h.app, "andy", "gated").await;
4292
    let row = db::repos::get(&h.app.db, "andy", "gated").await.unwrap().unwrap();
4293
    let work = tempfile::tempdir().unwrap();
4294
    let c = client(&format!("{}/andy/gated", h.base), work.path());
4295
    write(
4296
        work.path(),
4297
        ".flow/pipeline.kdl",
4298
        &format!(
4299
            "schema-version 1\nsandbox \"alpine\" {{\n    rootfs \"cas://blob/{ROOTFS}\"\n}}\njob \"plan\" {{\n    sandbox \"alpine\"\n    exec \"plan\"\n}}\njob \"apply\" {{\n    sandbox \"alpine\"\n    depends-on \"plan\"\n    approval {{\n        by \"maintain\"\n        others-only #true\n    }}\n    exec \"apply\"\n}}\n"
4300
        ),
4301
    );
4302
    let mut n = 0;
4303
    let mut push = || {
4304
        n += 1;
4305
        write(work.path(), "n.txt", &format!("{n}\n"));
4306
        c.snapshot("test").unwrap();
4307
        c.commit(&format!("Push {n}"), &[]).unwrap();
4308
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
4309
    };
4310
    // Runs `plan` to a pass; returns the run, its actor set to andy.
4311
    let plan_passes = |number: i64| {
4312
        let app = h.app.clone();
4313
        let row = row.clone();
4314
        async move {
4315
            let mut run = None;
4316
            for _ in 0..100 {
4317
                if let Some(r) = db::flow::run(&app.db, row.id, number).await.unwrap() {
4318
                    run = Some(r);
4319
                    break;
4320
                }
4321
                tokio::time::sleep(std::time::Duration::from_millis(30)).await;
4322
            }
4323
            let run = run.expect("the run");
4324
            sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = ?").bind(run.id).execute(&app.db).await.unwrap();
4325
            let j = claim(&app).await.expect("plan is claimed");
4326
            assert_eq!(j["job"]["name"], "plan");
4327
            let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4328
            finish(&app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("plan", &ph, 0) })).await;
4329
            db::flow::run(&app.db, row.id, number).await.unwrap().unwrap()
4330
        }
4331
    };
4332
4333
    // Run 1: apply waits; only someone with the role, other than the pusher, approves it.
4334
    push();
4335
    let run = runs_of(&h.app, "andy", "gated").await[0].clone();
4336
    // Live pages hear of the push (oxygenhub#203).
4337
    let heard = |topic: String| match h.app.events.live.since(0, &[topic]) {
4338
        oxygenhub::events::Replay::Events(e) => e.into_iter().map(|e| e.kind).collect::<Vec<_>>(),
4339
        oxygenhub::events::Replay::Reload => vec!["reload".into()],
4340
    };
4341
    assert!(heard(oxygenhub::events::topic::repo(row.id)).contains(&"push".to_string()), "the push is on the repository's topic");
4342
    sqlx::query("UPDATE flow_runs SET actor = 'andy' WHERE id = ?").bind(run.id).execute(&h.app.db).await.unwrap();
4343
    let early = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true).await.unwrap_err();
4344
    assert!(early.contains("waits for plan first"), "{early}");
4345
    let run = plan_passes(run.number).await;
4346
    assert!(claim(&h.app).await.is_none(), "apply waits for a person, so no runner gets it");
4347
    assert!(heard(oxygenhub::events::topic::run(run.id)).contains(&"jobs".to_string()), "the run's topic hears its jobs");
4348
    // Those who may approve are told, once; the pusher (others-only) and
4349
    // someone without the role are not.
4350
    let told = |id: i64| {
4351
        let db = h.app.db.clone();
4352
        async move { db::notify::inbox(&db, id, 20).await.unwrap().into_iter().filter(|n| n.kind == "flow.approval").count() }
4353
    };
4354
    assert_eq!((told(carol.id).await, told(andy.id).await, told(bob.id).await), (1, 0, 0));
4355
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4356
    assert!(page.contains("waits for approval by someone with the <em>maintain</em> role, other than andy"), "the run page says so");
4357
    let own = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &andy, true).await.unwrap_err();
4358
    assert!(own.contains("someone other than andy"), "{own}");
4359
    let no_role = oxygenhub::flow::decide(&h.app, &row, &run, "apply", &bob, true).await.unwrap_err();
4360
    assert!(no_role.contains("takes the maintain role"), "{no_role}");
4361
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, true).await.unwrap(), "apply: approved by carol");
4362
    assert_eq!(told(carol.id).await, 1, "told once");
4363
    let j = claim(&h.app).await.expect("approved, it runs");
4364
    assert_eq!(j["job"]["name"], "apply");
4365
    let (id, ph) = (j["job_id"].as_i64().unwrap(), j["pipeline_hash"].as_str().unwrap().to_string());
4366
    finish(&h.app, id, serde_json::json!({ "exit_code": 0, "duration_ms": 10, "receipt": receipt("apply", &ph, 0) })).await;
4367
    let audit = db::accounts::audit_rows(&h.app.db, 50).await.unwrap();
4368
    assert!(audit.iter().any(|r| r.action == "flow.approved" && r.actor == "carol" && r.target.ends_with("#1 apply")), "audited");
4369
    let (_, page) = call(&h.app, "GET", &format!("/andy/gated/flow/{}", run.number), None, None).await;
4370
    assert!(page.contains("approved by carol"), "the run says who");
4371
4372
    // Run 2: rejected through the API's rules: the job ends cancelled, the run ends.
4373
    push();
4374
    let run = plan_passes(2).await;
4375
    assert_eq!(oxygenhub::flow::decide(&h.app, &row, &run, "apply", &carol, false).await.unwrap(), "apply: rejected by carol");
4376
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4377
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4378
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "rejected by carol"));
4379
    assert!(claim(&h.app).await.is_none());
4380
4381
    // Run 3: nobody decides in time.
4382
    push();
4383
    let run = plan_passes(3).await;
4384
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 3_600_000).await.unwrap(), 0, "not yet");
4385
    assert_eq!(oxygenhub::flow::expire_approvals(&h.app, db::now_ms() + 25 * 3_600_000).await.unwrap(), 1);
4386
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
4387
    let apply = jobs.iter().find(|j| j.name == "apply").unwrap();
4388
    assert_eq!((apply.status.as_str(), apply.error.as_str()), ("cancelled", "no approval within 24h"));
4389
}
4390
4391
#[tokio::test(flavor = "multi_thread")]
4392
async fn live_streams_only_topics_the_viewer_may_hear_and_replays() {
4393
    let h = hub().await;
4394
    create(&h.app, "andy", "open").await;
4395
    h.app.repos.create(&RepoName::parse("andy/shut").unwrap(), None).unwrap();
4396
    db::repos::create(&h.app.db, "andy", "shut", "", hub_api::Visibility::Private).await.unwrap();
4397
    let open = db::repos::get(&h.app.db, "andy", "open").await.unwrap().unwrap();
4398
    let shut = db::repos::get(&h.app.db, "andy", "shut").await.unwrap().unwrap();
4399
    let live = &h.app.events.live;
4400
    let first = live.publish(&oxygenhub::events::topic::repo(open.id), "push");
4401
    live.publish(&oxygenhub::events::topic::repo(shut.id), "push");
4402
    live.publish(&oxygenhub::events::topic::proposal(open.id, 3), "review");
4403
4404
    // The first bytes of a stream, within a moment.
4405
    let read = |path: String, last: Option<u64>| {
4406
        let app = h.app.clone();
4407
        async move {
4408
            let mut req = Request::get(&path);
4409
            if let Some(l) = last {
4410
                req = req.header("last-event-id", l.to_string());
4411
            }
4412
            let res = oxygenhub::router(app).oneshot(req.body(Body::empty()).unwrap()).await.unwrap();
4413
            let status = res.status();
4414
            let mut body = res.into_body();
4415
            let mut text = String::new();
4416
            while let Ok(Some(Ok(frame))) = tokio::time::timeout(std::time::Duration::from_millis(300), body.frame()).await {
4417
                if let Some(d) = frame.data_ref() {
4418
                    text.push_str(&String::from_utf8_lossy(d));
4419
                }
4420
            }
4421
            (status, text)
4422
        }
4423
    };
4424
    let topics = format!("/live?topics=repo:{},repo:{}/proposal:3", open.id, open.id);
4425
    // From the first event on: what came after it on these topics only.
4426
    let (st, text) = read(topics.clone(), Some(first.id)).await;
4427
    assert_eq!(st, StatusCode::OK);
4428
    assert!(text.contains("event: change") && text.contains(&format!("\"topic\":\"repo:{}/proposal:3\"", open.id)), "{text}");
4429
    assert!(!text.contains(&format!("\"topic\":\"repo:{}\"", shut.id)), "never another topic: {text}");
4430
    assert!(!text.contains(&format!("id: {}\n", first.id)), "not what was already seen: {text}");
4431
    // A private repository's topic, or someone else's, is refused whole.
4432
    let (st, _) = read(format!("/live?topics=repo:{},repo:{}", open.id, shut.id), None).await;
4433
    assert_eq!(st, StatusCode::FORBIDDEN);
4434
    assert_eq!(read("/live?topics=user:1".into(), None).await.0, StatusCode::FORBIDDEN);
4435
    assert_eq!(read("/live?topics=nonsense".into(), None).await.0, StatusCode::BAD_REQUEST);
4436
    assert_eq!(read("/live?topics=".into(), None).await.0, StatusCode::BAD_REQUEST);
4437
    // Too far behind: told to reload.
4438
    for _ in 0..oxygenhub::events::REPLAY {
4439
        live.publish("repo:999999", "push");
4440
    }
4441
    let (_, text) = read(topics, Some(first.id)).await;
4442
    assert!(text.contains("event: reload"), "{text}");
4443
}