OXYGENHUB
# ea839b44cfb6 oxygenhub / crates / hub / tests / flow.rs
23.0 KiB · Rust · last changed Claims tell the runner the run's state, bookmark and number 1 month ago source blame history raw
1
//! OxygenFlow on the hub (hub spec §13.2), end to end: a real `oxy` push
2
//! starts a run, a runner claims jobs through the API in dependency order,
3
//! job tokens read only their repository, results become checks and pages.
4
5
use axum::body::Body;
6
use axum::http::{header, Request, StatusCode};
7
use http_body_util::BodyExt;
8
use oxy_core::protocol::{open_remote, RemoteOptions};
9
use oxy_core::repo::Repo;
10
use oxygenhub::config::Config;
11
use oxygenhub::repos::RepoName;
12
use oxygenhub::{db, Shared};
13
use std::path::Path;
14
use tower::ServiceExt;
15
16
const ROOTFS: &str = "36fc4e3238044e424219a2b9002bf61bbe1805fec14d52cf37e17fae77c9ff16";
17
18
fn hermetic() {
19
    static ONCE: std::sync::Once = std::sync::Once::new();
20
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
21
    ONCE.call_once(|| {
22
        let d = tempfile::tempdir().unwrap();
23
        std::env::set_var("OXY_HOME", d.path());
24
        DIR.set(d).ok();
25
    });
26
}
27
28
fn write(root: &Path, rel: &str, content: &str) {
29
    let p = root.join(rel);
30
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
31
    std::fs::write(p, content).unwrap();
32
}
33
34
struct Hub {
35
    app: Shared,
36
    base: String,
37
    _dir: tempfile::TempDir,
38
}
39
40
async fn hub() -> Hub {
41
    hermetic();
42
    let dir = tempfile::tempdir().unwrap();
43
    let mut config = Config::load(dir.path()).unwrap();
44
    config.auth.push_tokens = vec!["site".into()];
45
    config.flow.runner_tokens = vec!["runner-secret".into()];
46
    config.flow.repos = vec!["andy/*".into()];
47
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
48
    let port = listener.local_addr().unwrap().port();
49
    config.server.base_url = format!("http://127.0.0.1:{port}");
50
    let app = oxygenhub::build(config).await.unwrap();
51
    let router = oxygenhub::router(app.clone());
52
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
53
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
54
}
55
56
async fn call(app: &Shared, method: &str, path: &str, bearer: Option<&str>, json: Option<String>) -> (StatusCode, String) {
57
    let mut req = Request::builder().method(method).uri(path);
58
    if let Some(b) = bearer {
59
        req = req.header(header::AUTHORIZATION, format!("Bearer {b}"));
60
    }
61
    let body = match json {
62
        Some(j) => {
63
            req = req.header(header::CONTENT_TYPE, "application/json");
64
            Body::from(j)
65
        }
66
        None => Body::empty(),
67
    };
68
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
69
    let status = res.status();
70
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
71
    (status, String::from_utf8_lossy(&bytes).into_owned())
72
}
73
74
async fn claim(app: &Shared) -> Option<serde_json::Value> {
75
    let (st, body) =
76
        call(app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"test-1","runtimes":["microvm"]}"#.into())).await;
77
    match st {
78
        StatusCode::NO_CONTENT => None,
79
        StatusCode::OK => Some(serde_json::from_str(&body).unwrap()),
80
        other => panic!("claim: {other} {body}"),
81
    }
82
}
83
84
fn receipt(job: &str, pipeline_hash: &str, exit: u32) -> serde_json::Value {
85
    serde_json::json!({
86
        "job_name": job, "pipeline_hash": pipeline_hash, "scope_tree_hash": "11".repeat(32),
87
        "inputs": [], "environment": "22".repeat(32), "outputs": [], "exit_code": exit, "duration_ms": 640
88
    })
89
}
90
91
async fn finish(app: &Shared, id: i64, body: serde_json::Value) -> StatusCode {
92
    call(app, "POST", &format!("/api/v1/flow/jobs/{id}/finish"), Some("runner-secret"), Some(body.to_string())).await.0
93
}
94
95
async fn create(app: &Shared, owner: &str, name: &str) {
96
    app.repos.create(&RepoName::parse(&format!("{owner}/{name}")).unwrap(), None).unwrap();
97
    db::repos::create(&app.db, owner, name, "", hub_api::Visibility::Public).await.unwrap();
98
}
99
100
fn client(url: &str, work: &Path) -> Repo {
101
    let mut c = Repo::init(work).unwrap();
102
    c.config.set("remote.origin.url", url).unwrap();
103
    c.config.set("remote.origin.token", "site").unwrap();
104
    c.save_config().unwrap();
105
    c
106
}
107
108
fn pipeline(extra: &str) -> String {
109
    format!(
110
        "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}"
111
    )
112
}
113
114
async fn runs_of(app: &Shared, owner: &str, name: &str) -> Vec<db::flow::Run> {
115
    let row = db::repos::get(&app.db, owner, name).await.unwrap().unwrap();
116
    for _ in 0..100 {
117
        let r = db::flow::runs(&app.db, row.id, 10, None).await.unwrap();
118
        if !r.is_empty() {
119
            return r;
120
        }
121
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
122
    }
123
    vec![]
124
}
125
126
#[tokio::test(flavor = "multi_thread")]
127
async fn a_push_runs_the_pipeline_through_a_runner() {
128
    let h = hub().await;
129
    create(&h.app, "andy", "demo").await;
130
    create(&h.app, "andy", "secret").await;
131
    create(&h.app, "other", "plain").await;
132
    let url = format!("{}/andy/demo", h.base);
133
    let work = tempfile::tempdir().unwrap();
134
    let mut c = client(&url, work.path());
135
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
136
    write(work.path(), "test.sh", "echo ok\n");
137
    c.snapshot("test").unwrap();
138
    c.commit("Add a pipeline", &[]).unwrap();
139
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
140
141
    // The push started a run with three queued jobs, and checks for them.
142
    let runs = runs_of(&h.app, "andy", "demo").await;
143
    assert_eq!(runs.len(), 1);
144
    let run = &runs[0];
145
    assert_eq!((run.bookmark.as_str(), run.status.as_str(), run.actor.as_str()), ("main", "queued", "site token"));
146
    assert_eq!(run.pipeline_hash.len(), 64);
147
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
148
    assert_eq!(jobs.iter().map(|j| (j.name.as_str(), j.depth)).collect::<Vec<_>>(), [("build", 0), ("lint", 0), ("test", 1)]);
149
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
150
    assert_eq!(
151
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
152
        [("flow/build", "queued"), ("flow/lint", "queued"), ("flow/test", "queued")]
153
    );
154
155
    // Runners need a runner token.
156
    assert_eq!(
157
        call(&h.app, "POST", "/api/v1/flow/claim", Some("site"), Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
158
        StatusCode::UNAUTHORIZED
159
    );
160
    assert_eq!(
161
        call(&h.app, "POST", "/api/v1/flow/claim", None, Some(r#"{"runner":"x","runtimes":["microvm"]}"#.into())).await.0,
162
        StatusCode::UNAUTHORIZED
163
    );
164
    // A runner without the tier gets nothing.
165
    let (st, _) =
166
        call(&h.app, "POST", "/api/v1/flow/claim", Some("runner-secret"), Some(r#"{"runner":"x","runtimes":["wasm"]}"#.into())).await;
167
    assert_eq!(st, StatusCode::NO_CONTENT);
168
169
    // Claims come in dependency order; `test` waits for `build`.
170
    let a = claim(&h.app).await.unwrap();
171
    let b = claim(&h.app).await.unwrap();
172
    assert_eq!((a["job"]["name"].as_str(), b["job"]["name"].as_str()), (Some("build"), Some("lint")));
173
    assert!(claim(&h.app).await.is_none(), "test waits for build");
174
    assert_eq!(a["repo"], "andy/demo");
175
    assert_eq!(a["clone_url"], url.as_str());
176
    assert_eq!(a["sandbox"]["rootfs"], ROOTFS);
177
    assert_eq!(a["job"]["exec"], serde_json::json!(["make"]));
178
    assert_eq!(a["timeout_s"], 3600);
179
    // The job is told what it builds (FLOW_STATE, FLOW_BOOKMARK, FLOW_RUN).
180
    assert_eq!(
181
        (a["state"].as_str(), a["bookmark"].as_str(), a["run_number"].as_i64()),
182
        (Some(run.state.as_str()), Some("main"), Some(run.number))
183
    );
184
    let heads: Vec<String> = a["heads"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
185
    assert_eq!(heads.join("+"), run.heads);
186
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
187
    assert_eq!(checks.iter().find(|c| c.name == "flow/build").unwrap().status, "running");
188
189
    // The job token reads this repository over the wire, and nothing else.
190
    let token = a["token"].as_str().unwrap().to_string();
191
    assert!(token.starts_with("flowjob_"));
192
    let opts = RemoteOptions { token: Some(token.clone()), ca: None, repo_id: None };
193
    open_remote(&url, &opts).unwrap().refs().unwrap();
194
    assert!(open_remote(&format!("{}/andy/secret", h.base), &opts).unwrap().refs().is_err(), "another repository");
195
    let bad = RemoteOptions { token: Some("flowjob_00".into()), ca: None, repo_id: None };
196
    assert!(open_remote(&url, &bad).unwrap().refs().is_err(), "an unknown job token");
197
    // … and cannot push.
198
    c.config.set("remote.origin.token", &token).unwrap();
199
    c.save_config().unwrap();
200
    write(work.path(), "more.txt", "x\n");
201
    c.snapshot("test").unwrap();
202
    c.commit("More", &[]).unwrap();
203
    let pushed = c.push("origin", false);
204
    assert!(pushed.is_err() || pushed.unwrap().iter().all(|r| !r.ok), "a job token cannot push");
205
    c.config.set("remote.origin.token", "site").unwrap();
206
    c.save_config().unwrap();
207
208
    // Logs, then results with receipts.
209
    let a_id = a["job_id"].as_i64().unwrap();
210
    let b_id = b["job_id"].as_i64().unwrap();
211
    let log = serde_json::json!({ "records": [
212
        { "t": 5, "stream": "flow", "text": "booting" },
213
        { "t": 120, "stream": "out", "text": "cc -o demo demo.c" },
214
        { "t": 130, "stream": "weird", "text": "x".repeat(20_000) },
215
    ]});
216
    assert_eq!(
217
        call(&h.app, "POST", &format!("/api/v1/flow/jobs/{a_id}/log"), Some("runner-secret"), Some(log.to_string())).await.0,
218
        StatusCode::NO_CONTENT
219
    );
220
    let lines = db::flow::log(&h.app.db, a_id, 0, 100).await.unwrap();
221
    assert_eq!(lines.len(), 3);
222
    assert_eq!((lines[2].stream.as_str(), lines[2].text.len()), ("console", 16 * 1024), "streams are known ones, text is capped");
223
    let ph = a["pipeline_hash"].as_str().unwrap();
224
    assert_eq!(
225
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("lint", ph, 0) })).await,
226
        StatusCode::BAD_REQUEST,
227
        "a receipt for another job"
228
    );
229
    assert_eq!(
230
        finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700, "receipt": receipt("build", ph, 0) })).await,
231
        StatusCode::NO_CONTENT
232
    );
233
    assert_eq!(finish(&h.app, a_id, serde_json::json!({ "exit_code": 0, "duration_ms": 700 })).await, StatusCode::CONFLICT, "only once");
234
    assert!(open_remote(&url, &opts).unwrap().refs().is_err(), "the token ends with its job");
235
    assert_eq!(
236
        finish(&h.app, b_id, serde_json::json!({ "exit_code": 0, "duration_ms": 300, "receipt": receipt("lint", ph, 0) })).await,
237
        StatusCode::NO_CONTENT
238
    );
239
    let t = claim(&h.app).await.unwrap();
240
    assert_eq!(t["job"]["name"], "test");
241
    let t_id = t["job_id"].as_i64().unwrap();
242
    assert_eq!(
243
        finish(&h.app, t_id, serde_json::json!({ "exit_code": 3, "duration_ms": 500, "receipt": receipt("test", ph, 3) })).await,
244
        StatusCode::NO_CONTENT
245
    );
246
247
    let run = db::flow::run_by_id(&h.app.db, run.id).await.unwrap().unwrap();
248
    assert_eq!(run.status, "failed");
249
    let jobs = db::flow::jobs(&h.app.db, run.id).await.unwrap();
250
    let build = jobs.iter().find(|j| j.name == "build").unwrap();
251
    assert_eq!((build.status.as_str(), build.exit_code, build.receipt_hash.len()), ("passed", Some(0), 64));
252
    assert_eq!(jobs.iter().find(|j| j.name == "test").unwrap().status, "failed");
253
    let checks = db::hooks::checks_for_state(&h.app.db, run.repo_id, &run.state).await.unwrap();
254
    assert_eq!(
255
        checks.iter().map(|c| (c.name.as_str(), c.status.as_str())).collect::<Vec<_>>(),
256
        [("flow/build", "passed"), ("flow/lint", "passed"), ("flow/test", "failed")]
257
    );
258
    assert!(checks[2].summary.contains("exit 3") && checks[2].url.ends_with(&format!("/andy/demo/flow/{}", run.id)));
259
260
    // Pages: the list, the run with its graph and logs, and the live view.
261
    let (st, list) = call(&h.app, "GET", "/andy/demo/flow", None, None).await;
262
    assert_eq!(st, StatusCode::OK);
263
    assert!(list.contains(&format!("/andy/demo/flow/{}", run.id)) && list.contains("st-failed"), "{list}");
264
    let (st, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", run.id), None, None).await;
265
    assert_eq!(st, StatusCode::OK);
266
    assert!(page.contains("<svg class=\"flow-graph\""), "graph");
267
    assert_eq!(page.matches("data-job-node=").count(), 3);
268
    assert_eq!(page.matches("<path class=\"edge").count(), 1, "one dependency edge");
269
    assert!(page.contains("cc -o demo demo.c"), "log shown");
270
    assert!(!page.contains("data-flow-live"), "a finished run does not poll");
271
    let (st, live) = call(&h.app, "GET", &format!("/andy/demo/flow/{}/live?after={a_id}:1", run.id), None, None).await;
272
    assert_eq!(st, StatusCode::OK);
273
    let live: serde_json::Value = serde_json::from_str(&live).unwrap();
274
    assert_eq!(live["status"], "failed");
275
    let build_live = live["jobs"].as_array().unwrap().iter().find(|j| j["name"] == "build").unwrap().clone();
276
    assert_eq!(build_live["lines"].as_array().unwrap().len(), 2, "lines after seq 1");
277
    assert_eq!(call(&h.app, "GET", "/andy/demo/flow/999", None, None).await.0, StatusCode::NOT_FOUND);
278
279
    // A failed dependency skips what follows; an unrun job is an error.
280
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
281
    write(work.path(), "test.sh", "echo changed\n");
282
    c.snapshot("test").unwrap();
283
    c.commit("Change the test", &[]).unwrap();
284
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
285
    let mut second = None;
286
    for _ in 0..100 {
287
        let r = runs_of(&h.app, "andy", "demo").await;
288
        if r.len() == 2 {
289
            second = Some(r[0].clone());
290
            break;
291
        }
292
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
293
    }
294
    let second = second.expect("a second run");
295
    let x = claim(&h.app).await.unwrap();
296
    let y = claim(&h.app).await.unwrap();
297
    let (build_id, lint_id) = if x["job"]["name"] == "build" {
298
        (x["job_id"].as_i64().unwrap(), y["job_id"].as_i64().unwrap())
299
    } else {
300
        (y["job_id"].as_i64().unwrap(), x["job_id"].as_i64().unwrap())
301
    };
302
    assert_eq!(
303
        finish(&h.app, build_id, serde_json::json!({ "exit_code": null, "duration_ms": 10, "error": "rootfs is not on this runner" }))
304
            .await,
305
        StatusCode::NO_CONTENT
306
    );
307
    assert_eq!(finish(&h.app, lint_id, serde_json::json!({ "exit_code": 0, "duration_ms": 10 })).await, StatusCode::NO_CONTENT);
308
    assert!(claim(&h.app).await.is_none(), "test was skipped");
309
    let jobs = db::flow::jobs(&h.app.db, second.id).await.unwrap();
310
    assert_eq!(
311
        jobs.iter().map(|j| (j.name.as_str(), j.status.as_str())).collect::<Vec<_>>(),
312
        [("build", "error"), ("lint", "passed"), ("test", "skipped")]
313
    );
314
    assert_eq!(db::flow::run_by_id(&h.app.db, second.id).await.unwrap().unwrap().status, "failed");
315
316
    // An invalid pipeline is a run in error with the line.
317
    write(work.path(), ".flow/pipeline.kdl", &pipeline("job \"broken\" {\n    sandbox \"missing\"\n    exec \"x\"\n}\n"));
318
    c.snapshot("test").unwrap();
319
    c.commit("Break the pipeline", &[]).unwrap();
320
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
321
    let mut third = None;
322
    for _ in 0..100 {
323
        let r = runs_of(&h.app, "andy", "demo").await;
324
        if r.len() == 3 {
325
            third = Some(r[0].clone());
326
            break;
327
        }
328
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
329
    }
330
    let third = third.expect("a third run");
331
    assert_eq!(third.status, "error");
332
    assert!(third.error.contains("line 18") && third.error.contains("\"missing\""), "{}", third.error);
333
    let (_, page) = call(&h.app, "GET", &format!("/andy/demo/flow/{}", third.id), None, None).await;
334
    assert!(page.contains("The pipeline is not valid"));
335
336
    // A repository outside [flow] repos starts nothing.
337
    let work2 = tempfile::tempdir().unwrap();
338
    let c2 = client(&format!("{}/other/plain", h.base), work2.path());
339
    write(work2.path(), ".flow/pipeline.kdl", &pipeline(""));
340
    c2.snapshot("test").unwrap();
341
    c2.commit("Pipeline", &[]).unwrap();
342
    assert!(c2.push("origin", false).unwrap().iter().all(|r| r.ok));
343
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
344
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
345
    assert!(db::flow::runs(&h.app.db, row.id, 10, None).await.unwrap().is_empty());
346
    let (_, page) = call(&h.app, "GET", "/other/plain/flow", None, None).await;
347
    assert!(page.contains("not enabled for this repository"));
348
}
349
350
#[tokio::test(flavor = "multi_thread")]
351
async fn claims_carry_pinned_subrepos_and_the_job_token_reads_only_those() {
352
    let h = hub().await;
353
    for n in ["base", "lib", "vault", "other", "app"] {
354
        create(&h.app, "andy", n).await;
355
    }
356
    let push = |name: &str, file: &str| {
357
        let work = tempfile::tempdir().unwrap();
358
        let c = client(&format!("{}/andy/{name}", h.base), work.path());
359
        write(work.path(), file, "x\n");
360
        c.snapshot("t").unwrap();
361
        c.commit("first", &[]).unwrap();
362
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
363
        let heads = c.bookmark_heads().unwrap();
364
        (work, heads)
365
    };
366
    let (_b, base_heads) = push("base", "base.rs");
367
    // lib pins base in turn: a subrepo of a subrepo.
368
    let lib_work = tempfile::tempdir().unwrap();
369
    let lib = client(&format!("{}/andy/lib", h.base), lib_work.path());
370
    lib.submodule_add(&format!("{}/andy/base", h.base), "deps/base", Some("main")).unwrap();
371
    write(lib_work.path(), "lib.rs", "x\n");
372
    lib.snapshot("t").unwrap();
373
    lib.commit("lib on base", &[]).unwrap();
374
    assert!(lib.push("origin", false).unwrap().iter().all(|r| r.ok));
375
    let lib_heads = lib.bookmark_heads().unwrap();
376
    let (_v, _) = push("vault", "secret.rs");
377
    let (_o, _) = push("other", "o.rs");
378
379
    // The app pins lib and vault as subrepos and pushes as the site token.
380
    let work = tempfile::tempdir().unwrap();
381
    let app = client(&format!("{}/andy/app", h.base), work.path());
382
    app.submodule_add(&format!("{}/andy/lib", h.base), "deps/lib", Some("main")).unwrap();
383
    // Vault is private: adding it takes the environment's token, as a clone does.
384
    sqlx::query("UPDATE repositories SET visibility = 'private' WHERE name = 'vault'").execute(&h.app.db).await.unwrap();
385
    assert!(app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault2", Some("main")).is_err(), "not without a token");
386
    std::env::set_var("OXY_TOKEN", "site");
387
    app.submodule_add(&format!("{}/andy/vault", h.base), "deps/vault", Some("main")).unwrap();
388
    std::env::remove_var("OXY_TOKEN");
389
    // The pusher below is the site token, which has no account: it cannot read vault.
390
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
391
    write(work.path(), "Makefile", "all:\n");
392
    app.snapshot("t").unwrap();
393
    app.commit("app with deps", &[]).unwrap();
394
    assert!(app.push("origin", false).unwrap().iter().all(|r| r.ok));
395
    assert!(!runs_of(&h.app, "andy", "app").await.is_empty());
396
397
    let job = claim(&h.app).await.unwrap();
398
    let subs = job["subrepos"].as_array().cloned().unwrap_or_default();
399
    assert_eq!(subs.len(), 2, "lib and what lib pins; vault is private and the pusher has no account: {subs:?}");
400
    assert_eq!(subs[1]["path"], "deps/lib/deps/base", "nested under its parent, after it");
401
    assert_eq!(subs[1]["heads"], serde_json::json!(base_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
402
    let _ = std::fs::remove_dir_all(work.path().join("deps/vault2"));
403
    assert_eq!(subs[0]["path"], "deps/lib");
404
    assert_eq!(subs[0]["repo"], "andy/lib");
405
    assert_eq!(subs[0]["heads"], serde_json::json!(lib_heads.iter().map(|h| h.to_hex()).collect::<Vec<_>>()));
406
    assert!(subs[0]["clone_url"].as_str().unwrap().ends_with("/andy/lib"));
407
408
    // The job token reads its repository and the pinned lib, nothing else.
409
    let token = job["token"].as_str().unwrap().to_string();
410
    let read = |name: &str| {
411
        let opts = RemoteOptions { token: Some(token.clone()), ..Default::default() };
412
        open_remote(&format!("{}/andy/{name}", h.base), &opts).and_then(|r| r.refs()).is_ok()
413
    };
414
    assert!(read("app") && read("lib") && read("base"));
415
    assert!(!read("vault"), "not pinned for this pusher");
416
    assert!(!read("other"), "public, but not the job's to read");
417
}
418
419
#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
420
async fn concurrent_log_appends_never_fail_on_a_locked_database() {
421
    let h = hub().await;
422
    create(&h.app, "andy", "demo").await;
423
    let work = tempfile::tempdir().unwrap();
424
    let c = client(&format!("{}/andy/demo", h.base), work.path());
425
    write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
426
    write(work.path(), "Makefile", "all:\n");
427
    c.snapshot("t").unwrap();
428
    c.commit("pipeline", &[]).unwrap();
429
    assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
430
    let run = runs_of(&h.app, "andy", "demo").await.remove(0);
431
    let job = db::flow::jobs(&h.app.db, run.id).await.unwrap().remove(0);
432
    // Many writers at once, each reading the count and then inserting: a
433
    // deferred transaction would fail with "database is locked".
434
    let mut tasks = Vec::new();
435
    for w in 0..16 {
436
        let pool = h.app.db.clone();
437
        tasks.push(tokio::spawn(async move {
438
            let records: Vec<flow_core::api::Record> =
439
                (0..20).map(|i| flow_core::api::Record { t: i, stream: "out".into(), text: format!("writer {w} line {i}") }).collect();
440
            db::flow::append_log(&pool, job.id, &records, 100_000).await
441
        }));
442
    }
443
    for t in tasks {
444
        assert_eq!(t.await.unwrap().unwrap(), 20, "every append succeeds");
445
    }
446
    let lines = db::flow::log(&h.app.db, job.id, 0, 1_000).await.unwrap();
447
    assert_eq!(lines.len(), 320);
448
    let seqs: std::collections::BTreeSet<i64> = lines.iter().map(|l| l.seq).collect();
449
    assert_eq!(seqs.len(), 320, "sequence numbers are unique");
450
}
451
452
/// A repository's own Flow setting overrides hub.toml either way.
453
#[tokio::test(flavor = "multi_thread")]
454
async fn a_repository_setting_turns_flow_on_or_off() {
455
    let h = hub().await;
456
    create(&h.app, "other", "plain").await;
457
    create(&h.app, "andy", "quiet").await;
458
    let row = db::repos::get(&h.app.db, "other", "plain").await.unwrap().unwrap();
459
    db::repos::set_flow(&h.app.db, row.id, "on").await.unwrap();
460
    let quiet = db::repos::get(&h.app.db, "andy", "quiet").await.unwrap().unwrap();
461
    db::repos::set_flow(&h.app.db, quiet.id, "off").await.unwrap();
462
    for (owner, name) in [("other", "plain"), ("andy", "quiet")] {
463
        let work = tempfile::tempdir().unwrap();
464
        let c = client(&format!("{}/{owner}/{name}", h.base), work.path());
465
        write(work.path(), ".flow/pipeline.kdl", &pipeline(""));
466
        write(work.path(), "test.sh", "echo ok\n");
467
        c.commit("Add a pipeline", &[]).unwrap();
468
        assert!(c.push("origin", false).unwrap().iter().all(|r| r.ok));
469
    }
470
    assert_eq!(runs_of(&h.app, "other", "plain").await.len(), 1, "turned on");
471
    assert!(runs_of(&h.app, "andy", "quiet").await.is_empty(), "turned off despite andy/*");
472
}