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