diff --git a/crates/forge-web/src/pages/ci_badge.rs b/crates/forge-web/src/pages/ci_badge.rs index 4a1bd1d..37c2df2 100644 --- a/crates/forge-web/src/pages/ci_badge.rs +++ b/crates/forge-web/src/pages/ci_badge.rs @@ -262,16 +262,12 @@ mod tests { use super::*; #[test] - fn escapes_markup_and_quotes() { + fn markup_and_quotes_are_escaped_and_never_reach_the_svg_raw() { assert_eq!( escape_xml(r#"'&'"#), "<a href="x">'&'</a>" ); assert_eq!(escape_xml("a\u{1}b"), "a b"); - } - - #[test] - fn hostile_label_never_reaches_the_markup_raw() { let svg = render_badge("\"", BadgeStatus::Passing); assert!(!svg.contains(" CiJob { .expect("a job") } +/// Access follows the repo's role on every route: anonymous and outsider requests are 404, readers see the pages and streams, and only writers see or use the controls. Each scenario makes its own run. #[tokio::test] -async fn private_repo_is_not_found_to_outsiders_and_anonymous() { +async fn access_follows_the_repo_role_on_every_route() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let urls = [ - RUN_BASE.to_owned(), - format!("{RUN_BASE}/runs/{}", run.number), - format!("/tahinli/proj/ci/jobs/{}", job.id), - format!("/tahinli/proj/ci/jobs/{}/log.txt", job.id), - format!("/tahinli/proj/ci/jobs/{}/artifacts/x.bin", job.id), - ]; - for url in &urls { - let anon = get(&fx.app, url, None).await; - assert_eq!(anon.status, 404, "anonymous {url}"); - let outsider = get(&fx.app, url, Some(&cookie_for("carol-token"))).await; - assert_eq!(outsider.status, 404, "outsider {url}"); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let urls = [ + RUN_BASE.to_owned(), + format!("{RUN_BASE}/runs/{}", run.number), + format!("/tahinli/proj/ci/jobs/{}", job.id), + format!("/tahinli/proj/ci/jobs/{}/log.txt", job.id), + format!("/tahinli/proj/ci/jobs/{}/artifacts/x.bin", job.id), + ]; + for url in &urls { + let anon = get(&fx.app, url, None).await; + assert_eq!(anon.status, 404, "anonymous {url}"); + let outsider = get(&fx.app, url, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status, 404, "outsider {url}"); + } + let reader = get(&fx.app, RUN_BASE, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status, 200); } - let reader = get(&fx.app, RUN_BASE, Some(&cookie_for("dave-token"))).await; - assert_eq!(reader.status, 200); -} -#[tokio::test] -async fn buttons_and_manual_form_need_write() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let run_url = format!("{RUN_BASE}/runs/{}", run.number); - let writer = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await; - assert!(writer.text().contains(">Re-run<"), "writer sees re-run"); - assert!(writer.text().contains(">Cancel<"), "writer sees cancel"); - let reader = get(&fx.app, &run_url, Some(&cookie_for("dave-token"))).await; - assert_eq!(reader.status, 200); - assert!(!reader.text().contains(">Re-run<"), "reader sees no re-run"); - assert!(!reader.text().contains(">Cancel<"), "reader sees no cancel"); - let list = get(&fx.app, RUN_BASE, Some(&cookie_for("dave-token"))).await; - assert!( - !list.text().contains("Run workflow"), - "reader has no manual form" - ); - let list = get(&fx.app, RUN_BASE, Some(&cookie_for("bob-token"))).await; - assert!( - list.text().contains("Run workflow"), - "writer has the manual form" - ); - let refused = post( - &fx.app, - &format!("{run_url}/cancel"), - &cookie_for("dave-token"), - &[], - ) - .await; - assert_eq!(refused.status, 403, "reader cannot cancel"); - let still = fx - .store - .run_by_id(&run.id) - .await - .expect("run") - .expect("run"); - assert_eq!(still.state, RunState::Queued); -} + { + let run = run_with(&fx, &["build"], false).await; + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let writer = get(&fx.app, &run_url, Some(&cookie_for("bob-token"))).await; + assert!(writer.text().contains(">Re-run<"), "writer sees re-run"); + assert!(writer.text().contains(">Cancel<"), "writer sees cancel"); + let reader = get(&fx.app, &run_url, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status, 200); + assert!(!reader.text().contains(">Re-run<"), "reader sees no re-run"); + assert!(!reader.text().contains(">Cancel<"), "reader sees no cancel"); + let list = get(&fx.app, RUN_BASE, Some(&cookie_for("dave-token"))).await; + assert!( + !list.text().contains("Run workflow"), + "reader has no manual form" + ); + let list = get(&fx.app, RUN_BASE, Some(&cookie_for("bob-token"))).await; + assert!( + list.text().contains("Run workflow"), + "writer has the manual form" + ); + let refused = post( + &fx.app, + &format!("{run_url}/cancel"), + &cookie_for("dave-token"), + &[], + ) + .await; + assert_eq!(refused.status, 403, "reader cannot cancel"); + let still = fx + .store + .run_by_id(&run.id) + .await + .expect("run") + .expect("run"); + assert_eq!(still.state, RunState::Queued); + } -#[tokio::test] -async fn run_list_pages_25_at_a_time() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - for _ in 0..30 { - run_with(&fx, &[], false).await; + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let urls = [ + format!("{RUN_BASE}/runs/{}/events", run.number), + format!("/tahinli/proj/ci/jobs/{}/events", job.id), + format!("{RUN_BASE}/events"), + ]; + for url in &urls { + let anon = open(&fx.app, url, None).await; + assert_eq!(anon.status().as_u16(), 404, "anonymous {url}"); + let outsider = open(&fx.app, url, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status().as_u16(), 404, "outsider {url}"); + let reader = open(&fx.app, url, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status().as_u16(), 200, "reader {url}"); + } } - let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; - let text = first.text(); - assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 25); - assert!(text.contains("?page=2"), "older link"); - assert!(!text.contains(">Newer<")); - let second = get( - &fx.app, - &format!("{RUN_BASE}?page=2"), - Some(&cookie_for("tahinli-token")), - ) - .await; - let text = second.text(); - assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 5); - assert!(text.contains(">Newer<"), "newer link"); - assert!(!text.contains("?page=3"), "no older link on the last page"); - let bogus = get( - &fx.app, - &format!("{RUN_BASE}?page=abc"), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert_eq!(bogus.status, 200); - assert_eq!( - bogus - .text() - .matches("href=\"/tahinli/proj/ci/runs/") - .count(), - 25 - ); } -/// The pages no longer reload themselves. A page that is not finished carries its live marker, and -/// a finished one carries none. +/// The run list pages 25 at a time and is live on page 1 only. Thirty runs make two pages; page 2 is a fixed slice, so it carries no live marker. #[tokio::test] -async fn pages_are_live_while_not_finished_and_never_meta_refresh() { +async fn run_list_pages_and_its_live_marker() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let url = format!("/tahinli/proj/ci/jobs/{}", job.id); - let run_url = format!("{RUN_BASE}/runs/{}", run.number); - let job_marker = format!("data-live=\"{url}/events\""); - // The split view is live on page 1 through the repo stream, whatever the run's state. - let run_marker = format!("data-live=\"{RUN_BASE}/events\""); + { + for _ in 0..30 { + run_with(&fx, &[], false).await; + } + let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; + let text = first.text(); + assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 25); + assert!(text.contains("?page=2"), "older link"); + assert!(!text.contains(">Newer<")); + let second = get( + &fx.app, + &format!("{RUN_BASE}?page=2"), + Some(&cookie_for("tahinli-token")), + ) + .await; + let text = second.text(); + assert_eq!(text.matches("href=\"/tahinli/proj/ci/runs/").count(), 5); + assert!(text.contains(">Newer<"), "newer link"); + assert!(!text.contains("?page=3"), "no older link on the last page"); + let bogus = get( + &fx.app, + &format!("{RUN_BASE}?page=abc"), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert_eq!(bogus.status, 200); + assert_eq!( + bogus + .text() + .matches("href=\"/tahinli/proj/ci/runs/") + .count(), + 25 + ); + } - let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; - assert!(queued.text().contains(&job_marker), "job live while queued"); - let run_page = get(&fx.app, &run_url, Some(&cookie_for("tahinli-token"))).await; - assert!( - run_page.text().contains(&run_marker), - "run live while queued" - ); - for page in [&queued, &run_page] { + { + let marker = format!("data-live=\"{RUN_BASE}/events\""); + let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; + assert!(first.text().contains(&marker), "page 1 is live"); + let second = get( + &fx.app, + &format!("{RUN_BASE}?page=2"), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert!(!second.text().contains("data-live="), "page 2 is not live"); + let run = get( + &fx.app, + &format!("{RUN_BASE}/runs/30?page=2"), + Some(&cookie_for("tahinli-token")), + ) + .await; assert!( - !page.text().contains("http-equiv=\"refresh\""), - "no meta refresh" + !run.text().contains("data-live="), + "a run on page 2 is not live" ); } - - finish_job(&fx).await; - let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; - assert!( - !done.text().contains("data-live="), - "job not live when finished" - ); - assert!( - !done.text().contains("http-equiv=\"refresh\""), - "no meta refresh" - ); } /// Opens an event stream without reading it. The response head carries the status. @@ -396,126 +400,110 @@ where } } +/// The pages no longer reload themselves, and a job's live streams end with the job. Each scenario finishes its own job first, since `finish_job` claims the oldest queued job. #[tokio::test] -async fn live_events_need_the_same_access_as_the_page() { +async fn live_pages_and_streams_follow_a_job_to_its_end() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let urls = [ - format!("{RUN_BASE}/runs/{}/events", run.number), - format!("/tahinli/proj/ci/jobs/{}/events", job.id), - format!("{RUN_BASE}/events"), - ]; - for url in &urls { - let anon = open(&fx.app, url, None).await; - assert_eq!(anon.status().as_u16(), 404, "anonymous {url}"); - let outsider = open(&fx.app, url, Some(&cookie_for("carol-token"))).await; - assert_eq!(outsider.status().as_u16(), 404, "outsider {url}"); - let reader = open(&fx.app, url, Some(&cookie_for("dave-token"))).await; - assert_eq!(reader.status().as_u16(), 200, "reader {url}"); - } -} - -/// Each stream opens with its status. The run stream follows every bump; the job stream sends only -/// status changes, so a log append is silent, and it ends once the job is terminal. -#[tokio::test] -async fn live_events_open_with_the_status_and_follow_changes() { use futures_util::StreamExt; - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let tahinli = cookie_for("tahinli-token"); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let url = format!("/tahinli/proj/ci/jobs/{}", job.id); + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let job_marker = format!("data-live=\"{url}/events\""); + // The split view is live on page 1 through the repo stream, whatever the run's state. + let run_marker = format!("data-live=\"{RUN_BASE}/events\""); + + let queued = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; + assert!(queued.text().contains(&job_marker), "job live while queued"); + let run_page = get(&fx.app, &run_url, Some(&cookie_for("tahinli-token"))).await; + assert!( + run_page.text().contains(&run_marker), + "run live while queued" + ); + for page in [&queued, &run_page] { + assert!( + !page.text().contains("http-equiv=\"refresh\""), + "no meta refresh" + ); + } - let mut run_frames = open( - &fx.app, - &format!("{RUN_BASE}/runs/{}/events", run.number), - Some(&tahinli), - ) - .await - .into_body() - .into_data_stream(); - let first = next_event(&mut run_frames).await.expect("the run status"); - assert_eq!( - first, - format!("event: changed\ndata: {}\n\n", run.state.as_str()).into_bytes() - ); + finish_job(&fx).await; + let done = get(&fx.app, &url, Some(&cookie_for("tahinli-token"))).await; + assert!( + !done.text().contains("data-live="), + "job not live when finished" + ); + assert!( + !done.text().contains("http-equiv=\"refresh\""), + "no meta refresh" + ); + } - let mut job_frames = open( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}/events", job.id), - Some(&tahinli), - ) - .await - .into_body() - .into_data_stream(); - let first = next_event(&mut job_frames).await.expect("the job status"); - assert_eq!( - first, - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() - ); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let tahinli = cookie_for("tahinli-token"); - // A bump with no new log bytes and no status change sends nothing. - fx.live.bump_job(&job.id); - let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await; - assert!(quiet.is_err(), "a log append sends no status event"); + let mut run_frames = open( + &fx.app, + &format!("{RUN_BASE}/runs/{}/events", run.number), + Some(&tahinli), + ) + .await + .into_body() + .into_data_stream(); + let first = next_event(&mut run_frames).await.expect("the run status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", run.state.as_str()).into_bytes() + ); - // The run stream sends its status on every bump of the run. - fx.live.bump_run(&run.id); - let bumped = next_event(&mut run_frames).await.expect("the run status"); - let now = fx - .store - .run_by_id(&run.id) + let mut job_frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events", job.id), + Some(&tahinli), + ) .await - .expect("run") - .expect("run"); - assert_eq!( - bumped, - format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes() - ); + .into_body() + .into_data_stream(); + let first = next_event(&mut job_frames).await.expect("the job status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + ); - // The job finishes: its final status is sent, then the stream ends. - finish_job(&fx).await; - fx.live.close_job(&job.id); - let last = next_event(&mut job_frames).await.expect("the final status"); - assert_eq!( - last, - format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes() - ); - assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); -} + // A bump with no new log bytes and no status change sends nothing. + fx.live.bump_job(&job.id); + let quiet = tokio::time::timeout(Duration::from_millis(200), job_frames.next()).await; + assert!(quiet.is_err(), "a log append sends no status event"); -/// The run list is live on page 1 only: a new run can appear there at any time. Page 2 is a fixed -/// slice, so it carries no live marker. -#[tokio::test] -async fn run_list_is_live_on_page_one_only() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - for _ in 0..30 { - run_with(&fx, &[], false).await; + // The run stream sends its status on every bump of the run. + fx.live.bump_run(&run.id); + let bumped = next_event(&mut run_frames).await.expect("the run status"); + let now = fx + .store + .run_by_id(&run.id) + .await + .expect("run") + .expect("run"); + assert_eq!( + bumped, + format!("event: changed\ndata: {}\n\n", now.state.as_str()).into_bytes() + ); + + // The job finishes: its final status is sent, then the stream ends. + finish_job(&fx).await; + fx.live.close_job(&job.id); + let last = next_event(&mut job_frames).await.expect("the final status"); + assert_eq!( + last, + format!("event: changed\ndata: {}\n\n", JobState::Success.as_str()).into_bytes() + ); + assert!(next_event(&mut job_frames).await.is_none(), "stream ends"); } - let marker = format!("data-live=\"{RUN_BASE}/events\""); - let first = get(&fx.app, RUN_BASE, Some(&cookie_for("tahinli-token"))).await; - assert!(first.text().contains(&marker), "page 1 is live"); - let second = get( - &fx.app, - &format!("{RUN_BASE}?page=2"), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert!(!second.text().contains("data-live="), "page 2 is not live"); - let run = get( - &fx.app, - &format!("{RUN_BASE}/runs/30?page=2"), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert!( - !run.text().contains("data-live="), - "a run on page 2 is not live" - ); } /// The href of the list row marked as current, from the markup of the runs page. @@ -607,208 +595,199 @@ async fn run_list_events_follow_repo_changes() { assert_eq!(first, b"event: changed\ndata: list\n\n".to_vec()); } -/// The job's log events: each append is sent as a `log` event with its bytes, the id is the offset -/// past them, and the bytes before `?from=` are not sent again. +/// The job's log stream: each append is a `log` event with its bytes, the id is the offset past them, bytes before `?from=` are not sent again, a long append is split into 64 KiB events, and a reconnect resumes after `Last-Event-ID`. #[tokio::test] -async fn job_events_send_each_log_append_as_a_log_event() { +async fn job_log_events() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"one\n").expect("log"); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\n").expect("log"); - let mut frames = open( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}/events?from=4", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await - .into_body() - .into_data_stream(); - let first = next_event(&mut frames).await.expect("the status"); - assert_eq!( - first, - format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() - ); + let mut frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events?from=4", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await + .into_body() + .into_data_stream(); + let first = next_event(&mut frames).await.expect("the status"); + assert_eq!( + first, + format!("event: changed\ndata: {}\n\n", job.state.as_str()).into_bytes() + ); - let mut file = std::fs::OpenOptions::new() - .append(true) - .open(&path) - .expect("log"); - file.write_all(b"two\nthree\n").expect("append"); - fx.live.bump_job(&job.id); - let log = next_event(&mut frames).await.expect("the log event"); - assert_eq!( - log, - b"event: log\ndata: two\ndata: three\ndata: \nid: 14\n\n".to_vec() - ); -} + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(b"two\nthree\n").expect("append"); + fx.live.bump_job(&job.id); + let log = next_event(&mut frames).await.expect("the log event"); + assert_eq!( + log, + b"event: log\ndata: two\ndata: three\ndata: \nid: 14\n\n".to_vec() + ); + } -/// An append longer than 64 KiB is sent in several `log` events, in order. -#[tokio::test] -async fn job_events_split_a_long_append_into_64_kib_events() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"").expect("log"); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"").expect("log"); - let mut frames = open( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}/events", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await - .into_body() - .into_data_stream(); - next_event(&mut frames).await.expect("the status"); - - let long = "a".repeat(150 * 1024); - let mut file = std::fs::OpenOptions::new() - .append(true) - .open(&path) - .expect("log"); - file.write_all(long.as_bytes()).expect("append"); - fx.live.bump_job(&job.id); - - let mut sizes = Vec::new(); - for _ in 0..3 { - let frame = next_event(&mut frames).await.expect("a log event"); - let text = String::from_utf8(frame).expect("text"); - assert!(text.starts_with("event: log\n"), "{text}"); - let data = text - .lines() - .find_map(|line| line.strip_prefix("data: ")) - .expect("data line"); - sizes.push(data.len()); - if sizes.len() == 3 { - assert!( - text.contains("id: 153600\n"), - "the last id is the end offset" - ); + let mut frames = open( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/events", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await + .into_body() + .into_data_stream(); + next_event(&mut frames).await.expect("the status"); + + let long = "a".repeat(150 * 1024); + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(long.as_bytes()).expect("append"); + fx.live.bump_job(&job.id); + + let mut sizes = Vec::new(); + for _ in 0..3 { + let frame = next_event(&mut frames).await.expect("a log event"); + let text = String::from_utf8(frame).expect("text"); + assert!(text.starts_with("event: log\n"), "{text}"); + let data = text + .lines() + .find_map(|line| line.strip_prefix("data: ")) + .expect("data line"); + sizes.push(data.len()); + if sizes.len() == 3 { + assert!( + text.contains("id: 153600\n"), + "the last id is the end offset" + ); + } } + assert_eq!(sizes, vec![64 * 1024, 64 * 1024, 150 * 1024 - 128 * 1024]); } - assert_eq!(sizes, vec![64 * 1024, 64 * 1024, 150 * 1024 - 128 * 1024]); -} -/// A reconnect sends `Last-Event-ID`, and the stream resumes after that offset, not at `?from=`. -#[tokio::test] -async fn job_events_resume_after_the_last_event_id() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"one\ntwo\n").expect("log"); - - let request = Request::builder() - .method("GET") - .uri(format!("/tahinli/proj/ci/jobs/{}/events?from=0", job.id)) - .header("cookie", cookie_for("tahinli-token")) - .header("last-event-id", "4") - .body(Body::from(String::new())) - .expect("request"); - let mut frames = fx.app.handle(request).await.into_body().into_data_stream(); - next_event(&mut frames).await.expect("the status"); - let log = next_event(&mut frames).await.expect("the log event"); - assert_eq!(log, b"event: log\ndata: two\ndata: \nid: 8\n\n".to_vec()); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\ntwo\n").expect("log"); + + let request = Request::builder() + .method("GET") + .uri(format!("/tahinli/proj/ci/jobs/{}/events?from=0", job.id)) + .header("cookie", cookie_for("tahinli-token")) + .header("last-event-id", "4") + .body(Body::from(String::new())) + .expect("request"); + let mut frames = fx.app.handle(request).await.into_body().into_data_stream(); + next_event(&mut frames).await.expect("the status"); + let log = next_event(&mut frames).await.expect("the log event"); + assert_eq!(log, b"event: log\ndata: two\ndata: \nid: 8\n\n".to_vec()); + } } -/// The job page's log tail says where its text ends, so the events stream starts from there. +/// The job page's log tail says where its text ends, tails the last 512 KiB, and a cut log starts at its own line number. #[tokio::test] -async fn job_page_tail_carries_its_offset() { +async fn job_page_log_tail() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"one\ntwo\n").expect("log"); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\ntwo\n").expect("log"); - let page = get( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await; - let text = page.text(); - assert!( - text.contains("data-live-log=\"true\" data-offset=\"8\""), - "tail offset" - ); - assert!( - text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())), - "rendered status" - ); -} + let page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await; + let text = page.text(); + assert!( + text.contains("data-live-log=\"true\" data-offset=\"8\""), + "tail offset" + ); + assert!( + text.contains(&format!("data-live-state=\"{}\"", job.state.as_str())), + "rendered status" + ); + } -#[tokio::test] -async fn job_page_tails_the_log_at_512_kib() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - let mut body = b"HEAD-MARK\n".to_vec(); - let line = format!("{}\n", "x".repeat(99)); - for _ in 0..6_000 { - body.extend_from_slice(line.as_bytes()); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + let mut body = b"HEAD-MARK\n".to_vec(); + let line = format!("{}\n", "x".repeat(99)); + for _ in 0..6_000 { + body.extend_from_slice(line.as_bytes()); + } + body.extend_from_slice(b"TAIL-MARK\n"); + std::fs::write(&path, &body).expect("log"); + let page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await; + let text = page.text(); + assert!(text.contains("TAIL-MARK")); + assert!(!text.contains("HEAD-MARK")); + assert!(text.contains("Showing the last 512 KiB")); + assert!( + page.body.len() < 530 * 1024, + "page is {} bytes", + page.body.len() + ); } - body.extend_from_slice(b"TAIL-MARK\n"); - std::fs::write(&path, &body).expect("log"); - let page = get( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await; - let text = page.text(); - assert!(text.contains("TAIL-MARK")); - assert!(!text.contains("HEAD-MARK")); - assert!(text.contains("Showing the last 512 KiB")); - assert!( - page.body.len() < 530 * 1024, - "page is {} bytes", - page.body.len() - ); -} -#[tokio::test] -async fn log_txt_is_the_full_file_for_a_finished_job() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"line one\nline two\n").expect("log"); - finish_job(&fx).await; - let res = get( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}/log.txt", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert_eq!(res.status, 200); - assert_eq!(res.body, b"line one\nline two\n"); - assert_eq!( - res.headers - .get("content-type") - .and_then(|v| v.to_str().ok()), - Some("text/plain; charset=utf-8") - ); - assert_eq!( - res.headers - .get("x-content-type-options") - .and_then(|v| v.to_str().ok()), - Some("nosniff") - ); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut file = std::fs::File::create(&path).unwrap(); + // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000. + for n in 0..11_000 { + writeln!(file, "{n:0>98}").unwrap(); + } + drop(file); + let page = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}", job.id), + Some(&cookie_for("dave-token")), + ) + .await + .text(); + let marker = "data-first=\""; + let at = page.find(marker).expect("data-first") + marker.len(); + let first: u64 = page[at..].split('"').next().unwrap().parse().unwrap(); + assert!(first > 5000, "first line {first}"); + let after = &page[at..]; + let text = &after[after.find('>').unwrap() + 1..]; + let expected = format!("{:0>98}", first - 1); + assert!( + text.starts_with(&expected), + "the tail starts at its own line number" + ); + } } /// The next chunk a follower sends. Fails the test when none comes within five seconds. @@ -820,101 +799,197 @@ async fn next_chunk( .expect("a chunk within five seconds") } -/// A follower sends each append as soon as the job's signal is bumped. The wait is far longer -/// than the timeouts here, so a chunk that arrives in time was woken by the bump, not by a timer. +/// `log.txt` is the full file of a finished job, and a log follower is woken by bumps and ends once the job is terminal. #[tokio::test] -async fn log_follower_is_woken_by_bumps_and_ends_on_close() { - use futures_util::StreamExt; - +async fn log_txt_and_log_follower() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write(&path, b"one\n").expect("log"); - let live = Arc::new(CiLive::default()); - let mut stream = Box::pin(super::ci_job::follow_log( - fx.store.clone(), - Arc::clone(&live), - job.id.clone(), - path.clone(), - )); - let (tx, mut chunks) = tokio::sync::mpsc::unbounded_channel(); - tokio::spawn(async move { - while let Some(Ok(chunk)) = stream.next().await { - if tx.send(chunk).is_err() { - break; + use futures_util::StreamExt; + + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"line one\nline two\n").expect("log"); + finish_job(&fx).await; + let res = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/log.txt", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert_eq!(res.status, 200); + assert_eq!(res.body, b"line one\nline two\n"); + assert_eq!( + res.headers + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("text/plain; charset=utf-8") + ); + assert_eq!( + res.headers + .get("x-content-type-options") + .and_then(|v| v.to_str().ok()), + Some("nosniff") + ); + } + + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write(&path, b"one\n").expect("log"); + let live = Arc::new(CiLive::default()); + let mut stream = Box::pin(super::ci_job::follow_log( + fx.store.clone(), + Arc::clone(&live), + job.id.clone(), + path.clone(), + )); + let (tx, mut chunks) = tokio::sync::mpsc::unbounded_channel(); + tokio::spawn(async move { + while let Some(Ok(chunk)) = stream.next().await { + if tx.send(chunk).is_err() { + break; + } } - } - }); - assert_eq!( - next_chunk(&mut chunks).await.as_deref(), - Some(&b"one\n"[..]) - ); + }); + assert_eq!( + next_chunk(&mut chunks).await.as_deref(), + Some(&b"one\n"[..]) + ); - let mut file = std::fs::OpenOptions::new() - .append(true) - .open(&path) - .expect("log"); - file.write_all(b"two\n").expect("append"); - live.bump_job(&job.id); - assert_eq!( - next_chunk(&mut chunks).await.as_deref(), - Some(&b"two\n"[..]) - ); + let mut file = std::fs::OpenOptions::new() + .append(true) + .open(&path) + .expect("log"); + file.write_all(b"two\n").expect("append"); + live.bump_job(&job.id); + assert_eq!( + next_chunk(&mut chunks).await.as_deref(), + Some(&b"two\n"[..]) + ); - finish_job(&fx).await; - live.close_job(&job.id); - let end = tokio::time::timeout(Duration::from_secs(5), chunks.recv()) - .await - .expect("the stream ends once the job is terminal"); - assert!(end.is_none()); + finish_job(&fx).await; + live.close_job(&job.id); + let end = tokio::time::timeout(Duration::from_secs(5), chunks.recv()) + .await + .expect("the stream ends once the job is terminal"); + assert!(end.is_none()); + } } +/// Artifact downloads send attachment headers, and a run's artifacts list and zip for readers only. #[tokio::test] -async fn artifact_download_sends_attachment_headers() { +async fn artifact_downloads_and_zip() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let payload = b"artifact bytes"; - let artifact = fx - .store - .add_artifact(&job.id, "report.txt", payload.len() as i64, SHA) - .await - .expect("artifact row"); - let mut writer = fx - .blobs - .begin(&artifact_key(&artifact.id), 1024) - .await - .expect("begin"); - writer.push(payload).await.expect("push"); - writer.finish().await.expect("finish"); - let res = get( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}/artifacts/report.txt", job.id), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert_eq!(res.status, 200); - assert_eq!(res.body, payload); - let header = |name: &str| { - res.headers - .get(name) - .and_then(|v| v.to_str().ok()) - .map(str::to_owned) - }; - assert_eq!( - header("content-disposition").as_deref(), - Some("attachment; filename=\"report.txt\"") - ); - assert_eq!(header("content-length").as_deref(), Some("14")); - assert_eq!(header("x-content-type-options").as_deref(), Some("nosniff")); - assert_eq!( - header("content-type").as_deref(), - Some("application/octet-stream") - ); + { + let run = run_with(&fx, &["build"], false).await; + let job = job_of(&fx, &run).await; + let payload = b"artifact bytes"; + let artifact = fx + .store + .add_artifact(&job.id, "report.txt", payload.len() as i64, SHA) + .await + .expect("artifact row"); + let mut writer = fx + .blobs + .begin(&artifact_key(&artifact.id), 1024) + .await + .expect("begin"); + writer.push(payload).await.expect("push"); + writer.finish().await.expect("finish"); + let res = get( + &fx.app, + &format!("/tahinli/proj/ci/jobs/{}/artifacts/report.txt", job.id), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert_eq!(res.status, 200); + assert_eq!(res.body, payload); + let header = |name: &str| { + res.headers + .get(name) + .and_then(|v| v.to_str().ok()) + .map(str::to_owned) + }; + assert_eq!( + header("content-disposition").as_deref(), + Some("attachment; filename=\"report.txt\"") + ); + assert_eq!(header("content-length").as_deref(), Some("14")); + assert_eq!(header("x-content-type-options").as_deref(), Some("nosniff")); + assert_eq!( + header("content-type").as_deref(), + Some("application/octet-stream") + ); + } + + { + let run = run_with(&fx, &["build", "test"], false).await; + let jobs = fx.store.jobs_for_run(&run.id).await.unwrap(); + for (job, name, payload) in [ + (&jobs[0], "report.txt", &b"alpha"[..]), + (&jobs[1], "out.bin", &b"beta"[..]), + ] { + let artifact = fx + .store + .add_artifact(&job.id, name, payload.len() as i64, SHA) + .await + .expect("artifact row"); + let mut writer = fx + .blobs + .begin(&artifact_key(&artifact.id), 1024) + .await + .expect("begin"); + writer.push(payload).await.expect("push"); + writer.finish().await.expect("finish"); + } + let reader = cookie_for("dave-token"); + let run_url = format!("{RUN_BASE}/runs/{}", run.number); + let page = get(&fx.app, &run_url, Some(&reader)).await.text(); + assert!(page.contains("Download all (.zip)")); + assert!(page.contains("artifacts.zip")); + assert!(page.contains("report.txt") && page.contains("out.bin")); + + let res = get(&fx.app, &format!("{run_url}/artifacts.zip"), Some(&reader)).await; + assert_eq!(res.status, 200); + assert_eq!( + res.headers + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("application/zip") + ); + let mut archive = + zip::ZipArchive::new(std::io::Cursor::new(res.body.clone())).expect("zip"); + assert_eq!(archive.len(), 2); + let mut text = String::new(); + std::io::Read::read_to_string( + &mut archive.by_name("build/report.txt").expect("entry"), + &mut text, + ) + .expect("read"); + assert_eq!(text, "alpha"); + + let outsider = get( + &fx.app, + &format!("{run_url}/artifacts.zip"), + Some(&cookie_for("carol-token")), + ) + .await; + assert_eq!(outsider.status, 404, "a private repo stays private"); + let empty = run_with(&fx, &["lint"], false).await; + let none = get( + &fx.app, + &format!("{RUN_BASE}/runs/{}/artifacts.zip", empty.number), + Some(&reader), + ) + .await; + assert_eq!(none.status, 404); + } } #[tokio::test] @@ -1061,83 +1136,104 @@ async fn manual_run_refuses_an_unknown_branch() { let reader = post( &fx.app, RUN_BASE, - &cookie_for("dave-token"), - &[("branch", "main")], - ) - .await; - assert_eq!(reader.status, 403, "reader cannot start a manual run"); -} - -#[tokio::test] -async fn badge_follows_read_access_and_reports_the_latest_run() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let open = fx - .store - .create_repo(&fx.tahinli, "open", "", Visibility::Public, "main") - .await - .expect("public repo"); - let svg_path = "/tahinli/proj/badge.svg"; - - // The private repo: a run exists, but only readers see its badge. - run_with(&fx, &["build"], false).await; - finish_job(&fx).await; - assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous"); - let outsider = get(&fx.app, svg_path, Some(&cookie_for("carol-token"))).await; - assert_eq!(outsider.status, 404, "outsider"); - let reader = get(&fx.app, svg_path, Some(&cookie_for("dave-token"))).await; - assert_eq!(reader.status, 200, "reader"); - assert!(reader.text().contains("passing")); - assert_eq!( - reader - .headers - .get("content-type") - .and_then(|v| v.to_str().ok()), - Some("image/svg+xml") - ); - assert_eq!( - reader - .headers - .get("cache-control") - .and_then(|v| v.to_str().ok()), - Some("no-cache, max-age=0") - ); - - // The public repo: anyone sees the badge. Unknown branches and jobs have no status. - let needs: &[String] = &[]; - let specs = [NewJob { - name: "build", - spec_json: SPEC, - needs, - }]; - fx.store - .create_run( - &open.id, - "push", - "refs/heads/main", - SHA, - None, - &fx.tahinli, - false, - &specs, - None, + &cookie_for("dave-token"), + &[("branch", "main")], + ) + .await; + assert_eq!(reader.status, 403, "reader cannot start a manual run"); +} + +/// The badge follows read access, and a repo with no run answers 200 with "no status". It runs before any run exists on the private repo. +#[tokio::test] +async fn badge_follows_read_access_and_has_no_run_before_one_exists() { + let dir = tempfile::tempdir().expect("tempdir"); + let fx = fixture(dir.path()).await; + { + let reader = Some(cookie_for("dave-token")); + let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) + .await + .text(); + assert!(plain.contains(">build"), "{plain}"); + assert!(plain.contains(">no status")); + let labelled = get( + &fx.app, + "/tahinli/proj/badge.svg?label=Nightly", + reader.as_deref(), ) .await - .expect("run"); - finish_job(&fx).await; - let anon = get(&fx.app, "/tahinli/open/badge.svg", None).await; - assert_eq!(anon.status, 200); - assert!(anon.text().contains(">passing")); - let unknown = get(&fx.app, "/tahinli/open/badge.svg?branch=nope", None).await; - assert_eq!(unknown.status, 200); - assert!(unknown.text().contains(">no status")); - let job = get(&fx.app, "/tahinli/open/badge.svg?job=build", None).await; - assert!(job.text().contains(">build")); - assert!(job.text().contains(">passing")); - let missing_job = get(&fx.app, "/tahinli/open/badge.svg?job=lint", None).await; - assert!(missing_job.text().contains(">no status")); - let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await; - assert_eq!(unknown_repo.status, 404); + .text(); + assert!(labelled.contains(">Nightly"), "{labelled}"); + assert!(labelled.contains(">no status")); + } + + { + let open = fx + .store + .create_repo(&fx.tahinli, "open", "", Visibility::Public, "main") + .await + .expect("public repo"); + let svg_path = "/tahinli/proj/badge.svg"; + + // The private repo: a run exists, but only readers see its badge. + run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + assert_eq!(get(&fx.app, svg_path, None).await.status, 404, "anonymous"); + let outsider = get(&fx.app, svg_path, Some(&cookie_for("carol-token"))).await; + assert_eq!(outsider.status, 404, "outsider"); + let reader = get(&fx.app, svg_path, Some(&cookie_for("dave-token"))).await; + assert_eq!(reader.status, 200, "reader"); + assert!(reader.text().contains("passing")); + assert_eq!( + reader + .headers + .get("content-type") + .and_then(|v| v.to_str().ok()), + Some("image/svg+xml") + ); + assert_eq!( + reader + .headers + .get("cache-control") + .and_then(|v| v.to_str().ok()), + Some("no-cache, max-age=0") + ); + + // The public repo: anyone sees the badge. Unknown branches and jobs have no status. + let needs: &[String] = &[]; + let specs = [NewJob { + name: "build", + spec_json: SPEC, + needs, + }]; + fx.store + .create_run( + &open.id, + "push", + "refs/heads/main", + SHA, + None, + &fx.tahinli, + false, + &specs, + None, + ) + .await + .expect("run"); + finish_job(&fx).await; + let anon = get(&fx.app, "/tahinli/open/badge.svg", None).await; + assert_eq!(anon.status, 200); + assert!(anon.text().contains(">passing")); + let unknown = get(&fx.app, "/tahinli/open/badge.svg?branch=nope", None).await; + assert_eq!(unknown.status, 200); + assert!(unknown.text().contains(">no status")); + let job = get(&fx.app, "/tahinli/open/badge.svg?job=build", None).await; + assert!(job.text().contains(">build")); + assert!(job.text().contains(">passing")); + let missing_job = get(&fx.app, "/tahinli/open/badge.svg?job=lint", None).await; + assert!(missing_job.text().contains(">no status")); + let unknown_repo = get(&fx.app, "/tahinli/nothere/badge.svg", None).await; + assert_eq!(unknown_repo.status, 404); + } } /// Writes `.forge/ci.toml` with `text` into a new commit of the bare repo and returns its id. @@ -1203,199 +1299,230 @@ async fn run_at(fx: &Fixture, commit: &str) { .expect("run"); } +/// The badge label comes from `?label=`, the job or the workflow name, trimmed and escaped, with "build" as the fallback. Each scenario finishes its own run, so the latest run is the one it made. #[tokio::test] -async fn badge_label_comes_from_the_query_job_or_workflow_name() { +async fn badge_label_comes_from_the_query_job_or_name() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); - let commit = commit_ci_toml( - &bare, - "name = \" release-check \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", - ); - run_at(&fx, &commit).await; - finish_job(&fx).await; - let path = "/tahinli/proj/badge.svg"; - let reader = Some(cookie_for("dave-token")); - let named = get(&fx.app, path, reader.as_deref()).await.text(); - assert!(named.contains(">release-check"), "name: {named}"); - assert!(named.contains(">passing")); + { + let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); + let commit = commit_ci_toml( + &bare, + "name = \" release-check \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", + ); + run_at(&fx, &commit).await; + finish_job(&fx).await; + let path = "/tahinli/proj/badge.svg"; + let reader = Some(cookie_for("dave-token")); + let named = get(&fx.app, path, reader.as_deref()).await.text(); + assert!(named.contains(">release-check"), "name: {named}"); + assert!(named.contains(">passing")); + + let job = get(&fx.app, &format!("{path}?job=build"), reader.as_deref()) + .await + .text(); + assert!(job.contains(">build"), "job beats name: {job}"); - let job = get(&fx.app, &format!("{path}?job=build"), reader.as_deref()) - .await - .text(); - assert!(job.contains(">build"), "job beats name: {job}"); + let label = get(&fx.app, &format!("{path}?label=Ship"), reader.as_deref()) + .await + .text(); + assert!(label.contains(">Ship"), "label beats name: {label}"); - let label = get(&fx.app, &format!("{path}?label=Ship"), reader.as_deref()) + let both = get( + &fx.app, + &format!("{path}?job=build&label=Ship"), + reader.as_deref(), + ) .await .text(); - assert!(label.contains(">Ship"), "label beats name: {label}"); - - let both = get( - &fx.app, - &format!("{path}?job=build&label=Ship"), - reader.as_deref(), - ) - .await - .text(); - assert!(both.contains(">Ship"), "label beats job: {both}"); - assert!(both.contains(">passing"), "status is the job's"); -} + assert!(both.contains(">Ship"), "label beats job: {both}"); + assert!(both.contains(">passing"), "status is the job's"); + } -#[tokio::test] -async fn badge_label_is_trimmed_escaped_and_empty_means_absent() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - run_with(&fx, &["build"], false).await; - finish_job(&fx).await; - let path = "/tahinli/proj/badge.svg"; - let reader = Some(cookie_for("dave-token")); - let padded = get( - &fx.app, - &format!("{path}?label=%20deploy%20"), - reader.as_deref(), - ) - .await - .text(); - assert!(padded.contains(">deploy"), "{padded}"); - let empty = get(&fx.app, &format!("{path}?label="), reader.as_deref()) + { + run_with(&fx, &["build"], false).await; + finish_job(&fx).await; + let path = "/tahinli/proj/badge.svg"; + let reader = Some(cookie_for("dave-token")); + let padded = get( + &fx.app, + &format!("{path}?label=%20deploy%20"), + reader.as_deref(), + ) .await .text(); - assert!( - empty.contains(">build"), - "empty label is absent: {empty}" - ); - let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref()) + assert!(padded.contains(">deploy"), "{padded}"); + let empty = get(&fx.app, &format!("{path}?label="), reader.as_deref()) + .await + .text(); + assert!( + empty.contains(">build"), + "empty label is absent: {empty}" + ); + let blank = get(&fx.app, &format!("{path}?label=%20%20"), reader.as_deref()) + .await + .text(); + assert!( + blank.contains(">build"), + "blank label is absent: {blank}" + ); + let escaped = get( + &fx.app, + "/tahinli/proj/badge.svg?label=%3Cb%3E%20a%20%26%20b%20%3E", + reader.as_deref(), + ) .await .text(); - assert!( - blank.contains(">build"), - "blank label is absent: {blank}" - ); - let escaped = get( - &fx.app, - "/tahinli/proj/badge.svg?label=%3Cb%3E%20a%20%26%20b%20%3E", - reader.as_deref(), - ) - .await - .text(); - assert!(escaped.contains("<b> a & b >"), "{escaped}"); - assert!( - !escaped.contains(""), - "raw markup must not reach the SVG" - ); -} + assert!(escaped.contains("<b> a & b >"), "{escaped}"); + assert!( + !escaped.contains(""), + "raw markup must not reach the SVG" + ); + } -#[tokio::test] -async fn badge_label_defaults_to_build_without_a_usable_workflow_name() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); - // A run whose config has an empty name: the name is ignored. - let commit = commit_ci_toml( - &bare, - "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", - ); - run_at(&fx, &commit).await; - finish_job(&fx).await; - let reader = Some(cookie_for("dave-token")); - let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) - .await - .text(); - assert!(svg.contains(">build"), "{svg}"); + { + let bare = repo_path(&fx.data_dir, &fx.repo.id).expect("repo path"); + // A run whose config has an empty name: the name is ignored. + let commit = commit_ci_toml( + &bare, + "name = \" \"\n[jobs.build]\nimage = \"i\"\nrun = \"r\"\n", + ); + run_at(&fx, &commit).await; + finish_job(&fx).await; + let reader = Some(cookie_for("dave-token")); + let svg = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) + .await + .text(); + assert!(svg.contains(">build"), "{svg}"); + } } +/// The pages say whether a run is counting. A running run carries the start of each counting duration, and the run page previews each job's last log line and opens a failed job. #[tokio::test] -async fn badge_without_any_run_uses_the_label_or_build() { +async fn running_runs_and_run_page_previews() { let dir = tempfile::tempdir().expect("tempdir"); let fx = fixture(dir.path()).await; - let reader = Some(cookie_for("dave-token")); - let plain = get(&fx.app, "/tahinli/proj/badge.svg", reader.as_deref()) - .await - .text(); - assert!(plain.contains(">build"), "{plain}"); - assert!(plain.contains(">no status")); - let labelled = get( - &fx.app, - "/tahinli/proj/badge.svg?label=Nightly", - reader.as_deref(), - ) - .await - .text(); - assert!(labelled.contains(">Nightly"), "{labelled}"); - assert!(labelled.contains(">no status")); -} + { + run_with(&fx, &["test"], false).await; + let token = fx + .store + .create_registration_token(&fx.tahinli, 24) + .await + .expect("token"); + let (runner, _) = fx + .store + .register_runner(&token, "runner-1", &["linux".to_owned()]) + .await + .expect("runner"); + let (job, _, _) = fx + .store + .claim_job(&runner) + .await + .expect("claim") + .expect("a queued job"); + let cookie = cookie_for("tahinli-token"); + let html = get(&fx.app, RUN_BASE, Some(&cookie)) + .await + .text() + .to_owned(); + assert!( + html.contains("data-now=\""), + "the server clock is on the page" + ); + assert!( + html.contains("data-fm=\"{m}m {s}s\""), + "the duration format is on the page" + ); + assert!( + html.contains("class=\"ci-row-dur\" data-since=\""), + "the list duration counts" + ); + assert!(html.contains("data-tick=\"grow\""), "a running bar grows"); + assert!( + html.contains("data-tick=\"rest\""), + "the hatched remainder follows the clock" + ); + assert!( + html.contains("data-live-gantt=\"true\""), + "the timeline is live" + ); + assert!( + html.contains("class=\"ci-job-dur\" data-since=\""), + "the job duration counts" + ); -/// A running run carries what the client's local clock needs: the start of each duration that is -/// still counting, the growing boxes of the list bar and the timeline, and the server's clock. A -/// finished run carries none of it, so the ticker stops. -#[tokio::test] -async fn running_runs_carry_ticker_attributes_and_finished_ones_do_not() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - run_with(&fx, &["test"], false).await; - let token = fx - .store - .create_registration_token(&fx.tahinli, 24) - .await - .expect("token"); - let (runner, _) = fx - .store - .register_runner(&token, "runner-1", &["linux".to_owned()]) - .await - .expect("runner"); - let (job, _, _) = fx - .store - .claim_job(&runner) - .await - .expect("claim") - .expect("a queued job"); - let cookie = cookie_for("tahinli-token"); - let html = get(&fx.app, RUN_BASE, Some(&cookie)) - .await - .text() - .to_owned(); - assert!( - html.contains("data-now=\""), - "the server clock is on the page" - ); - assert!( - html.contains("data-fm=\"{m}m {s}s\""), - "the duration format is on the page" - ); - assert!( - html.contains("class=\"ci-row-dur\" data-since=\""), - "the list duration counts" - ); - assert!(html.contains("data-tick=\"grow\""), "a running bar grows"); - assert!( - html.contains("data-tick=\"rest\""), - "the hatched remainder follows the clock" - ); - assert!( - html.contains("data-live-gantt=\"true\""), - "the timeline is live" - ); - assert!( - html.contains("class=\"ci-job-dur\" data-since=\""), - "the job duration counts" - ); + fx.store + .finish_job(&job.id, JobState::Success, Some(0), None) + .await + .expect("finish"); + let html = get(&fx.app, RUN_BASE, Some(&cookie)) + .await + .text() + .to_owned(); + assert!( + !html.contains("data-since="), + "nothing counts once the run is done" + ); + assert!( + !html.contains("data-tick="), + "nothing grows once the run is done" + ); + } - fx.store - .finish_job(&job.id, JobState::Success, Some(0), None) - .await - .expect("finish"); - let html = get(&fx.app, RUN_BASE, Some(&cookie)) - .await - .text() - .to_owned(); - assert!( - !html.contains("data-since="), - "nothing counts once the run is done" - ); - assert!( - !html.contains("data-tick="), - "nothing grows once the run is done" - ); + { + let run = run_with(&fx, &["build", "test", "lint"], false).await; + let token = fx + .store + .create_registration_token(&fx.tahinli, 24) + .await + .expect("token"); + let (runner, _) = fx + .store + .register_runner(&token, "runner-1", &["linux".to_owned()]) + .await + .expect("runner"); + for _ in 0..3 { + fx.store + .claim_job(&runner) + .await + .expect("claim") + .expect("a queued job"); + } + let jobs = fx.store.jobs_for_run(&run.id).await.expect("jobs"); + for job in &jobs { + let path = log_path(&fx.data_dir, &job.id); + std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); + std::fs::write( + &path, + format!("early\n\u{1b}[32mlast of {}\u{1b}[0m\n\n", job.name), + ) + .expect("log"); + } + let lint = jobs.iter().find(|job| job.name == "lint").expect("lint"); + fx.store + .finish_job(&lint.id, JobState::Failure, Some(1), None) + .await + .expect("fail"); + let page = get( + &fx.app, + &format!("{RUN_BASE}/runs/{}", run.number), + Some(&cookie_for("tahinli-token")), + ) + .await; + assert_eq!(page.status, 200); + let html = page.text(); + for name in ["build", "test", "lint"] { + assert!( + html.contains(&format!("title=\"last of {name}\"")), + "{name}: {html}" + ); + } + assert!(!html.contains('\u{1b}')); + assert_eq!(html.matches("data-job-row=").count(), 3); + assert_eq!(html.matches("data-open=\"true\"").count(), 1); + assert!(html.contains(&format!("data-job-row=\"{}\" data-open=\"true\"", lint.id))); + assert!(html.contains("data-job-all")); + } } #[tokio::test] @@ -1515,71 +1642,6 @@ async fn a_run_with_no_failed_jobs_has_nothing_to_rerun() { ); } -#[tokio::test] -async fn run_artifacts_list_and_zip() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build", "test"], false).await; - let jobs = fx.store.jobs_for_run(&run.id).await.unwrap(); - for (job, name, payload) in [ - (&jobs[0], "report.txt", &b"alpha"[..]), - (&jobs[1], "out.bin", &b"beta"[..]), - ] { - let artifact = fx - .store - .add_artifact(&job.id, name, payload.len() as i64, SHA) - .await - .expect("artifact row"); - let mut writer = fx - .blobs - .begin(&artifact_key(&artifact.id), 1024) - .await - .expect("begin"); - writer.push(payload).await.expect("push"); - writer.finish().await.expect("finish"); - } - let reader = cookie_for("dave-token"); - let run_url = format!("{RUN_BASE}/runs/{}", run.number); - let page = get(&fx.app, &run_url, Some(&reader)).await.text(); - assert!(page.contains("Download all (.zip)")); - assert!(page.contains("artifacts.zip")); - assert!(page.contains("report.txt") && page.contains("out.bin")); - - let res = get(&fx.app, &format!("{run_url}/artifacts.zip"), Some(&reader)).await; - assert_eq!(res.status, 200); - assert_eq!( - res.headers - .get("content-type") - .and_then(|v| v.to_str().ok()), - Some("application/zip") - ); - let mut archive = zip::ZipArchive::new(std::io::Cursor::new(res.body.clone())).expect("zip"); - assert_eq!(archive.len(), 2); - let mut text = String::new(); - std::io::Read::read_to_string( - &mut archive.by_name("build/report.txt").expect("entry"), - &mut text, - ) - .expect("read"); - assert_eq!(text, "alpha"); - - let outsider = get( - &fx.app, - &format!("{run_url}/artifacts.zip"), - Some(&cookie_for("carol-token")), - ) - .await; - assert_eq!(outsider.status, 404, "a private repo stays private"); - let empty = run_with(&fx, &["lint"], false).await; - let none = get( - &fx.app, - &format!("{RUN_BASE}/runs/{}/artifacts.zip", empty.number), - Some(&reader), - ) - .await; - assert_eq!(none.status, 404); -} - #[tokio::test] async fn config_warnings_show_on_the_run_page() { let dir = tempfile::tempdir().expect("tempdir"); @@ -1608,97 +1670,3 @@ async fn config_warnings_show_on_the_run_page() { assert!(page.contains("on.schedule")); assert!(page.contains("Config warnings")); } - -#[tokio::test] -async fn job_page_log_carries_the_first_line_number_of_a_cut_log() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build"], false).await; - let job = job_of(&fx, &run).await; - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - let mut file = std::fs::File::create(&path).unwrap(); - // 11000 lines of 100 bytes cut the 512 KiB tail somewhere past line 5000. - for n in 0..11_000 { - writeln!(file, "{n:0>98}").unwrap(); - } - drop(file); - let page = get( - &fx.app, - &format!("/tahinli/proj/ci/jobs/{}", job.id), - Some(&cookie_for("dave-token")), - ) - .await - .text(); - let marker = "data-first=\""; - let at = page.find(marker).expect("data-first") + marker.len(); - let first: u64 = page[at..].split('"').next().unwrap().parse().unwrap(); - assert!(first > 5000, "first line {first}"); - let after = &page[at..]; - let text = &after[after.find('>').unwrap() + 1..]; - let expected = format!("{:0>98}", first - 1); - assert!( - text.starts_with(&expected), - "the tail starts at its own line number" - ); -} - -/// The run page previews the last log line of every running job in its row, and a failed job's row -/// starts expanded. -#[tokio::test] -async fn run_page_previews_each_job_and_expands_failed_ones() { - let dir = tempfile::tempdir().expect("tempdir"); - let fx = fixture(dir.path()).await; - let run = run_with(&fx, &["build", "test", "lint"], false).await; - let token = fx - .store - .create_registration_token(&fx.tahinli, 24) - .await - .expect("token"); - let (runner, _) = fx - .store - .register_runner(&token, "runner-1", &["linux".to_owned()]) - .await - .expect("runner"); - for _ in 0..3 { - fx.store - .claim_job(&runner) - .await - .expect("claim") - .expect("a queued job"); - } - let jobs = fx.store.jobs_for_run(&run.id).await.expect("jobs"); - for job in &jobs { - let path = log_path(&fx.data_dir, &job.id); - std::fs::create_dir_all(path.parent().expect("log dir")).expect("log dir"); - std::fs::write( - &path, - format!("early\n\u{1b}[32mlast of {}\u{1b}[0m\n\n", job.name), - ) - .expect("log"); - } - let lint = jobs.iter().find(|job| job.name == "lint").expect("lint"); - fx.store - .finish_job(&lint.id, JobState::Failure, Some(1), None) - .await - .expect("fail"); - let page = get( - &fx.app, - &format!("{RUN_BASE}/runs/{}", run.number), - Some(&cookie_for("tahinli-token")), - ) - .await; - assert_eq!(page.status, 200); - let html = page.text(); - for name in ["build", "test", "lint"] { - assert!( - html.contains(&format!("title=\"last of {name}\"")), - "{name}: {html}" - ); - } - assert!(!html.contains('\u{1b}')); - assert_eq!(html.matches("data-job-row=").count(), 3); - assert_eq!(html.matches("data-open=\"true\"").count(), 1); - assert!(html.contains(&format!("data-job-row=\"{}\" data-open=\"true\"", lint.id))); - assert!(html.contains("data-job-all")); -}