diff --git a/.forge/ci.toml b/.forge/ci.toml index f68e1e6..8f397dd 100644 --- a/.forge/ci.toml +++ b/.forge/ci.toml @@ -26,14 +26,25 @@ image = "docker.io/library/rust:1" env = { CARGO_PROFILE_DEV_DEBUG = "0", CARGO_PROFILE_TEST_DEBUG = "0", CARGO_HOME = "/workspace/.cargo-home", SOURCE_DATE_EPOCH = "0" } # Unit tests run first, so a failure shows before the release build. The e2e tests then run against # the binary this job ships, so forge is not compiled a third time just for them. +# The groups are the job's steps on the run page, and `exec 2>&1` keeps a marker in order with cargo's +# stderr, which the runner reads from a separate pipe. run = """ +exec 2>&1 +echo "::group::Unit tests" cargo test --workspace --exclude forge-e2e +echo "::endgroup::" +echo "::group::Release build" cargo build --profile dist -p forge-web -p forge-runner +echo "::endgroup::" +echo "::group::E2E tests" FORGE_BIN="$PWD/target/dist/forge" cargo test -p forge-e2e +echo "::endgroup::" +echo "::group::Package" ARCH=$(uname -m) cp target/dist/forge forge-$ARCH-linux cp target/dist/forge-runner forge-runner-$ARCH-linux sha256sum forge-$ARCH-linux forge-runner-$ARCH-linux > SHA256SUMS +echo "::endgroup::" """ artifacts = ["forge-*-linux", "SHA256SUMS"] cache = ["target", ".cargo-home"] diff --git a/crates/forge-ci/src/lib.rs b/crates/forge-ci/src/lib.rs index 4117e00..6d6791b 100644 --- a/crates/forge-ci/src/lib.rs +++ b/crates/forge-ci/src/lib.rs @@ -8,5 +8,6 @@ pub mod error; pub mod mask; pub mod proto; pub mod size; +pub mod steps; pub use error::ConfigError; diff --git a/crates/forge-ci/src/steps.rs b/crates/forge-ci/src/steps.rs new file mode 100644 index 0000000..30e4eef --- /dev/null +++ b/crates/forge-ci/src/steps.rs @@ -0,0 +1,129 @@ +//! Job steps from the log: `::group::Name` opens a step and `::endgroup::` closes it, the way the +//! browser's log viewer reads them. Only top-level groups are steps; nested groups add no marks. + +/// The most steps kept per job. Later top-level groups are not stored. +pub const MAX_STEPS: usize = 32; +/// The longest step name, in characters. Longer names are cut. +pub const MAX_STEP_NAME_CHARS: usize = 80; + +/// A change of step state found in a log line. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StepMark { + /// A top-level group opened. `offset` is the byte position of its line in the log. + Start { name: String, offset: u64 }, + /// The open top-level group closed. + End, +} + +/// The marks found in the complete lines of a chunk, and how many bytes of it they used. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Scan { + pub marks: Vec, + /// Bytes through the last newline. A partial last line is left for the next scan. + pub consumed: usize, +} + +/// Reads the complete lines of `bytes`, which start at log byte `base_offset`. `depth` is the +/// number of open groups and carries over between scans. +pub fn scan(bytes: &[u8], base_offset: u64, depth: &mut u32) -> Scan { + let mut marks = Vec::new(); + let mut start = 0; + for (i, &byte) in bytes.iter().enumerate() { + if byte != b'\n' { + continue; + } + let raw = String::from_utf8_lossy(&bytes[start..i]); + let stripped = strip_ansi(&raw); + let line = stripped.strip_suffix('\r').unwrap_or(&stripped); + if let Some(rest) = line.strip_prefix("::group::") { + if *depth == 0 { + let trimmed = rest.trim(); + let name = if trimmed.is_empty() { "group" } else { trimmed }; + marks.push(StepMark::Start { + name: name.chars().take(MAX_STEP_NAME_CHARS).collect(), + offset: base_offset + start as u64, + }); + } + *depth = depth.saturating_add(1); + } else if line.trim_end() == "::endgroup::" { + if *depth == 1 { + marks.push(StepMark::End); + } + *depth = depth.saturating_sub(1); + } + start = i + 1; + } + Scan { + marks, + consumed: start, + } +} + +/// Removes ANSI CSI sequences: `ESC [`, any parameter bytes, then one final byte. +fn strip_ansi(line: &str) -> String { + let mut out = String::with_capacity(line.len()); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + if c == '\u{1b}' && chars.peek() == Some(&'[') { + chars.next(); + for f in chars.by_ref() { + if ('\u{40}'..='\u{7e}').contains(&f) { + break; + } + } + } else { + out.push(c); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn top_level_groups_become_marks_with_offsets() { + let log = b"hi\n::group::Build\nx\n::endgroup::\npartial"; + let mut depth = 0; + let found = scan(log, 100, &mut depth); + assert_eq!(found.consumed, log.len() - "partial".len()); + assert_eq!( + found.marks, + vec![ + StepMark::Start { + name: "Build".into(), + offset: 103 + }, + StepMark::End, + ] + ); + assert_eq!(depth, 0); + } + + #[test] + fn nested_groups_add_no_marks() { + let mut depth = 0; + let found = scan( + b"::group::A\n::group::B\n::endgroup::\n::endgroup::\n", + 0, + &mut depth, + ); + assert_eq!(found.marks.len(), 2); + assert_eq!(found.marks[1], StepMark::End); + assert_eq!(depth, 0); + } + + #[test] + fn ansi_codes_are_stripped_and_empty_names_default() { + let mut depth = 0; + let found = scan(b"\x1b[1;32m::group::\x1b[0m \r\n", 0, &mut depth); + assert_eq!( + found.marks, + vec![StepMark::Start { + name: "group".into(), + offset: 0 + }] + ); + } +} diff --git a/crates/forge-core/migrations/0071_ci_job_steps.sql b/crates/forge-core/migrations/0071_ci_job_steps.sql new file mode 100644 index 0000000..e6b5fca --- /dev/null +++ b/crates/forge-core/migrations/0071_ci_job_steps.sql @@ -0,0 +1,16 @@ +-- Steps of a CI job: the top-level `::group::` sections of its log, in order. `log_offset` is where the +-- group line starts in the log. `step_scanned` and `step_depth` are how far the log was read and how +-- many groups are open, so the next scan resumes there. Rows go with the job (ON DELETE CASCADE). +-- Applied by store/migrate.rs. + +CREATE TABLE ci_job_steps ( + job_id TEXT NOT NULL REFERENCES ci_jobs(id) ON DELETE CASCADE, + seq INTEGER NOT NULL, + name TEXT NOT NULL, + started_at TEXT NOT NULL, + finished_at TEXT NULL, + log_offset INTEGER NOT NULL, + PRIMARY KEY (job_id, seq) +); +ALTER TABLE ci_jobs ADD COLUMN step_scanned INTEGER NOT NULL DEFAULT 0; +ALTER TABLE ci_jobs ADD COLUMN step_depth INTEGER NOT NULL DEFAULT 0; diff --git a/crates/forge-core/src/ci.rs b/crates/forge-core/src/ci.rs index 2512f77..91b06d7 100644 --- a/crates/forge-core/src/ci.rs +++ b/crates/forge-core/src/ci.rs @@ -571,6 +571,59 @@ pub struct JobSample { pub secs: i64, } +/// A step of a job: a top-level `::group::` section of its log (migration 0071). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct JobStep { + pub job_id: String, + /// The step's place in its job, from 0. + pub seq: i64, + pub name: String, + pub started_at: String, + /// Set when the group closed. Unset while it is open. + pub finished_at: Option, + /// Byte position of the group's line in the job's log. + pub log_offset: i64, +} + +/// What a step shows: its own state, or the job's once the job ended without closing it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StepState { + Running, + Passed, + Failed, + Cancelled, +} + +impl JobStep { + /// A closed step passed. An open one follows its job: a job that succeeded passed it too. + pub fn state(&self, job: JobState) -> StepState { + if self.finished_at.is_some() { + return StepState::Passed; + } + match job { + JobState::Success => StepState::Passed, + JobState::Cancelled => StepState::Cancelled, + JobState::Failure | JobState::Error => StepState::Failed, + _ => StepState::Running, + } + } +} + +/// One step's duration in a recent successful run of a repo, for the CI time estimate. Sampled like +/// `JobSample`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StepSample { + pub git_ref: String, + /// The run's place among the repo's successful runs on its branch, newest first. + pub branch_rank: i64, + /// The run's place among the repo's successful runs on any branch, newest first. + pub repo_rank: i64, + pub job: String, + pub step: String, + /// The step's duration in seconds. + pub secs: i64, +} + /// A job of one runner, with the run and repo it belongs to, for the runner's admin page. The /// run's page is `/{owner}/{repo}/ci/runs/{run_number}`. #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index d552e7d..1a71f3e 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -14,14 +14,16 @@ use super::{ finish, insert_err, missing_row, new_id, }; use crate::ci::{ - CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, MAX_RUNNER_CONCURRENCY, - MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, RunState, RunnerJob, - RunnerReport, RunnerRestart, STARVE_AFTER_SECS, pick_by_memory, validate_runner_field, + CiArtifact, CiJob, CiRun, CiRunner, FieldKind, JobSample, JobState, JobStep, + MAX_RUNNER_CONCURRENCY, MIN_RUNNER_CONCURRENCY, MemoryOffer, NewJob, QueueSkips, RestartMode, + RunState, RunnerJob, RunnerReport, RunnerRestart, STARVE_AFTER_SECS, StepSample, + pick_by_memory, validate_runner_field, }; use crate::error::{Error, Result}; use crate::secret; use crate::time::{now_stamp, stamp_after, stamp_to_unix}; use crate::token::{generate_token, hash_token}; +use forge_ci::steps::{MAX_STEPS, StepMark}; const JOB_COLS: &str = "id, run_id, name, spec, state, runner_id, exit_code, message, queued_at, \ started_at, finished_at, heartbeat_at, cancel_requested, log_bytes, oom_kills"; @@ -1339,7 +1341,8 @@ impl Store { .execute( "UPDATE ci_jobs SET state = 'queued', runner_id = NULL, job_token_hash = NULL, \ started_at = NULL, heartbeat_at = NULL, finished_at = NULL, exit_code = NULL, \ - message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL \ + message = NULL, cancel_requested = 0, log_bytes = 0, oom_kills = NULL, \ + step_scanned = 0, step_depth = 0 \ WHERE id = ?1 AND state = 'running'", (job_id.to_string(),), ) @@ -1348,6 +1351,12 @@ impl Store { if changed != 1 { return Ok(false); } + tx.execute( + "DELETE FROM ci_job_steps WHERE job_id = ?1", + (job_id.to_string(),), + ) + .await + .map_err(db_err)?; recompute_run(&tx, &job.run_id, &now).await?; Ok(true) } @@ -1730,6 +1739,168 @@ impl Store { Ok(rows.into_iter().flatten().collect()) } + /// How far a job's log has been scanned for steps, and how many groups are open there. + /// `NotFound` if the job does not exist. + pub async fn step_scan(&self, job_id: &str) -> Result<(u64, u32)> { + let conn = self.read_conn().await; + let row = fetch_opt( + &conn, + "SELECT step_scanned, step_depth FROM ci_jobs WHERE id = ?1", + (job_id.to_string(),), + |row| Ok((col_int(row, 0)?, col_int(row, 1)?)), + ) + .await? + .ok_or(Error::NotFound)?; + Ok(( + u64::try_from(row.0).unwrap_or(0), + u32::try_from(row.1).unwrap_or(0), + )) + } + + /// Stores the marks of one log scan and the new scan position. A start is kept while the job + /// has fewer than `MAX_STEPS` steps. An end closes the newest open step, if any. + pub async fn apply_step_scan( + &self, + job_id: &str, + scanned: u64, + depth: u32, + marks: &[StepMark], + ) -> Result<()> { + let now = now_stamp(); + let conn = self.inner.conn.lock().await; + let tx = conn.unchecked_transaction().await.map_err(db_err)?; + let outcome: Result<()> = async { + let mut count = fetch_opt( + &tx, + "SELECT COUNT(*) FROM ci_job_steps WHERE job_id = ?1", + (job_id.to_string(),), + |row| col_int(row, 0), + ) + .await? + .unwrap_or(0); + for mark in marks { + match mark { + StepMark::Start { name, offset } => { + if count >= MAX_STEPS as i64 { + continue; + } + tx.execute( + "INSERT INTO ci_job_steps \ + (job_id, seq, name, started_at, finished_at, log_offset) \ + VALUES (?1, ?2, ?3, ?4, NULL, ?5)", + ( + job_id.to_string(), + count, + name.clone(), + now.clone(), + *offset as i64, + ), + ) + .await + .map_err(db_err)?; + count += 1; + } + StepMark::End => { + tx.execute( + "UPDATE ci_job_steps SET finished_at = ?2 \ + WHERE job_id = ?1 AND finished_at IS NULL AND seq = ( \ + SELECT MAX(seq) FROM ci_job_steps \ + WHERE job_id = ?1 AND finished_at IS NULL)", + (job_id.to_string(), now.clone()), + ) + .await + .map_err(db_err)?; + } + } + } + tx.execute( + "UPDATE ci_jobs SET step_scanned = ?2, step_depth = ?3 WHERE id = ?1", + (job_id.to_string(), scanned as i64, i64::from(depth)), + ) + .await + .map_err(db_err)?; + Ok(()) + } + .await; + finish(tx, outcome).await + } + + /// Every step of a run's jobs, ordered by job, then by step. + pub async fn steps_for_run(&self, run_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + "SELECT s.job_id, s.seq, s.name, s.started_at, s.finished_at, s.log_offset \ + FROM ci_job_steps s JOIN ci_jobs j ON j.id = s.job_id \ + WHERE j.run_id = ?1 ORDER BY s.job_id, s.seq", + (run_id.to_string(),), + |row| { + Ok(JobStep { + job_id: col_text(row, 0)?, + seq: col_int(row, 1)?, + name: col_text(row, 2)?, + started_at: col_text(row, 3)?, + finished_at: col_opt_text(row, 4)?, + log_offset: col_int(row, 5)?, + }) + }, + ) + .await + } + + /// One step's duration in the recent successful runs of a repo, sampled as `recent_job_samples` + /// samples jobs. Only finished steps of successful jobs count. + pub async fn recent_step_samples( + &self, + repo_id: &str, + git_refs: &[String], + ) -> Result> { + let mut params: Vec = Vec::with_capacity(git_refs.len() + 1); + params.push(Value::Text(repo_id.to_string())); + params.extend(git_refs.iter().map(|git_ref| Value::Text(git_ref.clone()))); + let scope = if git_refs.is_empty() { + "done.repo_rank <= 5".to_owned() + } else { + let marks: Vec = (2..=git_refs.len() + 1).map(|i| format!("?{i}")).collect(); + format!( + "(done.branch_rank <= 5 AND done.git_ref IN ({})) OR done.repo_rank <= 5", + marks.join(", ") + ) + }; + let sql = format!( + "WITH done AS ( \ + SELECT id, git_ref, \ + ROW_NUMBER() OVER (PARTITION BY git_ref ORDER BY number DESC) AS branch_rank, \ + ROW_NUMBER() OVER (ORDER BY number DESC) AS repo_rank \ + FROM ci_runs WHERE repo_id = ?1 AND state = 'success' \ + ) \ + SELECT done.git_ref, done.branch_rank, done.repo_rank, j.name, s.name, \ + s.started_at, s.finished_at \ + FROM done JOIN ci_jobs j ON j.run_id = done.id \ + JOIN ci_job_steps s ON s.job_id = j.id \ + WHERE ({scope}) \ + AND j.state = 'success' AND s.finished_at IS NOT NULL" + ); + let conn = self.read_conn().await; + let rows = fetch_all(&conn, &sql, params, |row| { + let started = col_opt_text(row, 5)?.as_deref().and_then(stamp_to_unix); + let finished = col_opt_text(row, 6)?.as_deref().and_then(stamp_to_unix); + Ok(match (started, finished) { + (Some(start), Some(end)) => Some(StepSample { + git_ref: col_text(row, 0)?, + branch_rank: col_int(row, 1)?, + repo_rank: col_int(row, 2)?, + job: col_text(row, 3)?, + step: col_text(row, 4)?, + secs: (end - start).max(0), + }), + _ => None, + }) + }) + .await?; + Ok(rows.into_iter().flatten().collect()) + } + /// The jobs a runner holds or held: every running one, then its `recent` newest finished jobs /// (by start time). Each carries its run's number and its repo's owner and name. pub async fn runner_jobs(&self, runner_id: &str, recent: usize) -> Result> { diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index d1ab77e..0edfbdb 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -116,6 +116,7 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ 70, include_str!("../../migrations/0070_pull_viewed_files.sql"), ), + (71, include_str!("../../migrations/0071_ci_job_steps.sql")), ]; /// The highest migration version this binary knows about. diff --git a/crates/forge-e2e/tests/e2e/ci_e2e.rs b/crates/forge-e2e/tests/e2e/ci_e2e.rs index 5c3e99c..fdd8b0c 100644 --- a/crates/forge-e2e/tests/e2e/ci_e2e.rs +++ b/crates/forge-e2e/tests/e2e/ci_e2e.rs @@ -547,6 +547,60 @@ async fn push_run_masks_secrets_keeps_artifacts_and_skips_dependants() { ); } +#[tokio::test] +async fn run_page_lists_a_jobs_steps_and_a_step_opens_its_part_of_the_log() { + let b = boot().await; + let tahinli = login(&b.http, "tahinli", TAHINLI_PW).await; + let token = create_token(&b.http, &tahinli, "ci-token").await; + create_repo(&b.http, &tahinli, "r").await; + let worker = register_runner(&b, &tahinli, "runner-a").await; + + // Each `::group::` line the job prints is one of its steps. + let work = clone( + &remote(b.port, "tahinli", &token, "tahinli", "r"), + &b.dir.join("tahinli-work"), + ); + let sha = push_ci_config( + &work, + "[on]\npush = [\"main\"]\n\n[jobs.build]\nimage = \"docker.io/library/alpine:3\"\nrun = \"echo ::group::Compile; echo built; echo ::endgroup::; echo ::group::Test; echo tested\"\n", + ); + let found = wait_statuses(&b.http, &token, &sha, &["ci/build"]).await; + let job_id = job_id_of(&found["ci/build"]); + assert_eq!(worker.drain().await, 1, "the build job runs"); + + let page = b + .http + .get( + &format!("{REPO_PATH}/ci/runs/1?job={job_id}"), + Some(&tahinli), + ) + .await; + assert_eq!(page.status, 200, "GET run page"); + assert!( + page.body.contains("ci-tl-stepname") && page.body.contains("Compile"), + "the rail lists the step names: {}", + page.body + ); + assert!( + page.body.contains("step=0"), + "a step links to its part of the log" + ); + + let step = b + .http + .get( + &format!("{REPO_PATH}/ci/runs/1?job={job_id}&step=1"), + Some(&tahinli), + ) + .await; + assert_eq!(step.status, 200, "GET the step's run page"); + assert!( + step.body.contains(r#"data-log-start="true""#), + "the log opens at the step: {}", + step.body + ); +} + #[tokio::test] async fn fork_pull_waits_for_approval_and_runs_without_secrets() { let b = boot().await; diff --git a/crates/forge-web/assets/nav.js b/crates/forge-web/assets/nav.js index 93401d4..913db3a 100644 --- a/crates/forge-web/assets/nav.js +++ b/crates/forge-web/assets/nav.js @@ -219,9 +219,11 @@ } // The log tail is a terminal: it opens at its end. A reader who scrolls up keeps their place. + // A step's part of the log (data-log-start) opens at its top: the reader came for its first line. function followTail() { var pre = document.querySelector('[data-live-log]'); - if (pre && !pre.querySelector('.ll-sel')) { pre.scrollTop = pre.scrollHeight; } + if (!pre || pre.querySelector('.ll-sel')) { return; } + pre.scrollTop = pre.hasAttribute('data-log-start') ? 0 : pre.scrollHeight; } // The run page's job rows each have a last-line preview and a tail that opens under the row @@ -326,7 +328,7 @@ var saved = history.state; // A live swap keeps the log tail where the reader had it: at the end it stays at the end. var tail = how === 'live' ? document.querySelector('[data-live-log]') : null; - var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24 } : null; + var tailAt = tail ? { top: tail.scrollTop, end: tail.scrollTop + tail.clientHeight >= tail.scrollHeight - 24, start: tail.hasAttribute('data-log-start') } : null; // A live change must not shut a menu the reader has open (a run's branch picker, say). var dd = how === 'live' ? captureDropdowns() : null; var at = how === 'live' ? captureAnchor() : null; @@ -342,7 +344,7 @@ if (paneTops) { setPaneScrolls(paneTops); } if (tailAt) { var nextTail = document.querySelector('[data-live-log]'); - if (nextTail) { nextTail.scrollTop = tailAt.end ? nextTail.scrollHeight : tailAt.top; } + if (nextTail) { nextTail.scrollTop = tailAt.end && !tailAt.start ? nextTail.scrollHeight : tailAt.top; } } if (how === 'nav') { history.pushState(null, '', dest.href); } else if (how === 'post' || how === 'query') { history.replaceState(null, '', dest.href); } diff --git a/crates/forge-web/src/ci/api.rs b/crates/forge-web/src/ci/api.rs index 069d5a6..d1f98b6 100644 --- a/crates/forge-web/src/ci/api.rs +++ b/crates/forge-web/src/ci/api.rs @@ -43,6 +43,9 @@ const LOG_OFFSET_HEADER: &str = "x-forge-log-offset"; const LOG_SIZE_HEADER: &str = "x-forge-log-size"; /// Largest log chunk, in bytes. const MAX_LOG_CHUNK: usize = 1024 * 1024; +/// Longest line the step scan waits for. A longer line with no newline is passed over, so a log +/// with no newlines is not read again and again. +const MAX_STEP_LINE: usize = 1024 * 1024; /// Largest JSON body on the runner routes, in bytes. const MAX_JSON_BODY: usize = 64 * 1024; /// Largest runner log batch, in bytes. A batch holds at most 1000 lines of up to 4 KiB each. @@ -907,6 +910,10 @@ async fn write_log( .add_log_bytes(&job.id, len as i64) .await .map_err(api::internal)?; + // A failure here must not fail the append: the runner would retry it and read a duplicate. + if let Err(e) = record_steps(state, &job.id, &path).await { + tracing::warn!(error = %e, job = %job.id, "ci: could not record job steps"); + } state.ci_live.bump_job(&job.id); // The run page shows the last log lines, so its streams wake too. The page debounces. state.ci_live.bump_run(&job.run_id); @@ -916,6 +923,39 @@ async fn write_log( Ok(LogWrite::Stored(size + len)) } +/// Scans the file's log from the last scanned byte for step marks and stores them. The file is read, +/// not the chunk: it holds the masked text, and its offsets are the ones the job page seeks to. +async fn record_steps( + state: &AppState, + job_id: &str, + path: &std::path::Path, +) -> Result<(), CoreError> { + use tokio::io::{AsyncReadExt, AsyncSeekExt}; + + let (scanned, mut depth) = state.store.step_scan(job_id).await?; + let mut file = match tokio::fs::File::open(path).await { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(e) => return Err(e.into()), + }; + file.seek(std::io::SeekFrom::Start(scanned)).await?; + let mut bytes = Vec::new(); + file.read_to_end(&mut bytes).await?; + let found = forge_ci::steps::scan(&bytes, scanned, &mut depth); + let used = if found.consumed == 0 && bytes.len() >= MAX_STEP_LINE { + bytes.len() + } else { + found.consumed + }; + if used == 0 { + return Ok(()); + } + state + .store + .apply_step_scan(job_id, scanned + used as u64, depth, &found.marks) + .await +} + /// Masks a chunk with the values of the job's secrets. The chunk is masked on its own, so a /// secret split across two requests is masked by the runner, which holds back the boundary. async fn mask_for_job(state: &AppState, job: &CiJob, chunk: &[u8]) -> Result, Refusal> { diff --git a/crates/forge-web/src/ci/api_tests.rs b/crates/forge-web/src/ci/api_tests.rs index 495ed47..69e83f3 100644 --- a/crates/forge-web/src/ci/api_tests.rs +++ b/crates/forge-web/src/ci/api_tests.rs @@ -398,6 +398,34 @@ async fn logs_append_retry_mismatch_and_mask() { assert_eq!(sent.status, 400); } +#[tokio::test] +async fn a_group_split_across_chunks_is_a_step_and_an_unclosed_one_stays_open() { + let env = bare(|_| {}).await; + let (_, secret) = runner(&env, &[]).await; + let run = make_run(&env, "push", None, COMMIT, &[job("test", spec(&[], &[]))]).await; + let assignment = claim_job(&env.router, &secret).await; + let job_id = assignment["job_id"].as_str().unwrap().to_owned(); + let token = assignment["job_token"].as_str().unwrap().to_owned(); + + // The `::group::Build` line is split between two chunks. Its offset is the start of its line. + let first = b"setup\n::gro"; + let (uri, headers, body) = log_post(&job_id, &token, 0, first); + let sent = send(&env.router, "POST", &uri, &headers, body).await; + assert_eq!(sent.status, 200, "{}", sent.json()); + let rest = b"up::Build\nbuild\n::endgroup::\n::group::Test\nrunning\n"; + let (uri, headers, body) = log_post(&job_id, &token, first.len() as u64, rest); + let sent = send(&env.router, "POST", &uri, &headers, body).await; + assert_eq!(sent.status, 200, "{}", sent.json()); + + let steps = env.store.steps_for_run(&run.id).await.unwrap(); + assert_eq!(steps.len(), 2); + assert_eq!(steps[0].name, "Build"); + assert!(steps[0].finished_at.is_some(), "Build is closed"); + assert_eq!(steps[0].log_offset, 6, "the group line starts after setup"); + assert_eq!(steps[1].name, "Test"); + assert!(steps[1].finished_at.is_none(), "Test is still open"); +} + #[test] fn log_cap_keeps_what_fits_then_one_marker() { // 100 byte cap. The marker is 17 bytes, so 83 bytes of data fit. diff --git a/crates/forge-web/src/pages/ci_estimate.rs b/crates/forge-web/src/pages/ci_estimate.rs index b2e4e75..4ad04fc 100644 --- a/crates/forge-web/src/pages/ci_estimate.rs +++ b/crates/forge-web/src/pages/ci_estimate.rs @@ -2,11 +2,11 @@ //! store hands in the samples, the run's jobs go in as steps, and the answers are unix seconds, //! seconds or the page's words. The estimate of a job is the median of its last five successful runs //! on the branch, or on any branch when the branch has fewer than `MIN_SAMPLES`. Failed and cancelled -//! runs are never sampled. +//! runs are never sampled. A step's estimate follows the same rule, from its own durations. use std::collections::{HashMap, HashSet}; -use forge_core::ci::{JobSample, JobState}; +use forge_core::ci::{JobSample, JobState, StepSample}; use serde::Deserialize; use crate::i18n::Lang; @@ -40,17 +40,57 @@ pub fn needs_of(spec_json: &str) -> Vec { /// five successful runs on that branch, or in the newest five on any branch when the branch has fewer /// than `MIN_SAMPLES`. None when neither has enough. pub fn job_expected(samples: &[JobSample], git_ref: &str, job: &str) -> Option { - let on_branch: Vec = samples + let rows: Vec = samples .iter() - .filter(|s| s.job == job && s.git_ref == git_ref && s.branch_rank <= 5) + .filter(|s| s.job == job) + .map(|s| Sample { + git_ref: &s.git_ref, + branch_rank: s.branch_rank, + repo_rank: s.repo_rank, + secs: s.secs, + }) + .collect(); + expected_of(&rows, git_ref) +} + +/// The expected duration of `step` of `job` on `git_ref`, in seconds, by the same rule as +/// `job_expected`. None when neither the branch nor the repo has enough samples. +pub fn step_expected(samples: &[StepSample], git_ref: &str, job: &str, step: &str) -> Option { + let rows: Vec = samples + .iter() + .filter(|s| s.job == job && s.step == step) + .map(|s| Sample { + git_ref: &s.git_ref, + branch_rank: s.branch_rank, + repo_rank: s.repo_rank, + secs: s.secs, + }) + .collect(); + expected_of(&rows, git_ref) +} + +/// One duration sample of a job or step, with the ranks that place it. +struct Sample<'a> { + git_ref: &'a str, + branch_rank: i64, + repo_rank: i64, + secs: i64, +} + +/// The rule both estimates share: the median of the newest five on `git_ref` when that has +/// `MIN_SAMPLES`, else of the newest five on any branch when that has them. None otherwise. +fn expected_of(rows: &[Sample], git_ref: &str) -> Option { + let on_branch: Vec = rows + .iter() + .filter(|s| s.git_ref == git_ref && s.branch_rank <= 5) .map(|s| s.secs) .collect(); if on_branch.len() >= MIN_SAMPLES { return Some(median(on_branch)); } - let any: Vec = samples + let any: Vec = rows .iter() - .filter(|s| s.job == job && s.repo_rank <= 5) + .filter(|s| s.repo_rank <= 5) .map(|s| s.secs) .collect(); (any.len() >= MIN_SAMPLES).then(|| median(any)) diff --git a/crates/forge-web/src/pages/ci_job.rs b/crates/forge-web/src/pages/ci_job.rs index b0d033f..b99d7cb 100644 --- a/crates/forge-web/src/pages/ci_job.rs +++ b/crates/forge-web/src/pages/ci_job.rs @@ -196,6 +196,54 @@ pub(crate) async fn log_tail_of(path: &Path, max: u64) -> Result { }) } +/// The log from byte `offset`, at most `max` bytes. `offset` should be the start of a line, such as a +/// step's. When the file goes on past the bytes read, the text is cut back to its last newline. A log +/// that does not exist yet is empty. `truncated` is never set: nothing is cut at the start. +pub(crate) async fn log_from(path: &Path, offset: u64, max: u64) -> Result { + let mut file = match tokio::fs::File::open(path).await { + Ok(file) => file, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + return Ok(Tail { + text: String::new(), + truncated: false, + offset: 0, + first_line: 1, + }); + } + Err(e) => return Err(forge_core::Error::Io(e).into()), + }; + let len = file.metadata().await.map_err(forge_core::Error::Io)?.len(); + let start = offset.min(len); + file.seek(SeekFrom::Start(start)) + .await + .map_err(forge_core::Error::Io)?; + let mut buf = Vec::new(); + (&mut file) + .take(max) + .read_to_end(&mut buf) + .await + .map_err(forge_core::Error::Io)?; + if start + (buf.len() as u64) < len { + // A single line longer than `max` stays as it is: an empty page would hide it. + if let Some(end) = buf.iter().rposition(|byte| *byte == b'\n') { + buf.truncate(end + 1); + } + } + buf.truncate(whole_utf8_len(&buf)); + let offset = start + buf.len() as u64; + let first_line = if start > 0 { + newlines_before(path, start).await? + 1 + } else { + 1 + }; + Ok(Tail { + text: String::from_utf8_lossy(&buf).into_owned(), + truncated: false, + offset, + first_line, + }) +} + /// Follows a log: yields what the file holds, then sends new bytes each time the job changes (its /// log grew or its state did). The stream ends when the job is terminal and a read after seeing /// that returns nothing, so every byte the runner wrote is sent. A job that is gone, a read diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index ccb935e..8c47abc 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -13,7 +13,7 @@ use std::future::Future; use std::path::Path; use std::time::Duration; -use forge_core::ci::{CiJob, CiRun, JobSample, JobState, RunState}; +use forge_core::ci::{CiJob, CiRun, JobSample, JobState, JobStep, RunState, StepSample, StepState}; use forge_core::{Action, Denied, Store, User, authorize}; use forge_git::browse::{RefInfo, RefKind, commit_reachable, reachable_commits, read_commit}; use futures_util::{Stream, StreamExt, stream}; @@ -41,7 +41,7 @@ use crate::i18n::{ }; use crate::pages::ci_estimate::{self, Est, Step}; use crate::pages::ci_fail::{self, FailFirst, fail_first_block}; -use crate::pages::ci_job::{Tail, log_tail_of}; +use crate::pages::ci_job::{Tail, log_from, log_tail_of}; use crate::pages::refs::load_refs; use crate::pages::repo::repo_head; use crate::pages::repo_ctx::{RepoCtx, RepoHead, load_repo, still_readable}; @@ -420,6 +420,25 @@ struct JobLine { rerun: Option, /// A running job whose cancel was requested: it shows as stopping until its runner stops it. stopping: bool, + /// The job's steps under its row. Only the selected job has lines; the others have none. + steps: Vec, + /// The job's bar along the bottom of its row: one segment per step. Empty for a job with no steps. + step_bar: Vec, +} + +/// One step of the selected job, drawn as a line under its row in the jobs pane. +struct StepLine { + name: String, + /// The classes of the step's mark, which carry its state's colour. + mark: &'static str, + duration: String, + /// Unix seconds a running step's duration counts from. + since: Option, + /// The expected duration of a running step, as "~2m". + expected: Option, + /// The link that opens the step's part of the log. None when the job's log was pruned. + href: Option, + selected: bool, } /// One artifact of the run: its download link, the job that made it, its name and size. @@ -486,6 +505,8 @@ struct JobLog { truncated: bool, offset: String, first_line: String, + /// Whether the log is one step's part of the job's log: the pre opens at its top, not its end. + at_step: bool, } /// A box in an SVG, with its class and its position and size in the SVG's units. @@ -660,6 +681,19 @@ struct Timing { started: Option, finished: Option, cancel_requested: bool, + /// The job's log size in bytes. 0 means the log was pruned. + log_bytes: i64, + /// The job's steps, in order, for the timeline's lanes under the selected job. + steps: Vec, +} + +/// One step of a job on the timeline: its state as the job state its box takes, its start and its end +/// in unix seconds (None while it runs). +struct StepSpan { + name: String, + state: JobState, + start: i64, + end: Option, } impl Timing { @@ -693,8 +727,13 @@ const TRACK_X: i64 = 100; const TRACK_W: i64 = 530; const AXIS_H: i64 = 24; const ROW_H: i64 = 40; +/// A step's lane under its job's row on the timeline. +const STEP_H: i64 = 20; const BAR_DY: i64 = 9; const BAR_H: i64 = 22; +/// The narrowest segment of a job's step bar, and the gap between segments, in its SVG units. +const STEP_BAR_MIN: i64 = 8; +const STEP_BAR_GAP: i64 = 6; /// The narrowest a box is drawn, so a short lead-in or job still shows. const MIN_BOX_W: i64 = 3; /// The most intervals an axis has, so its ticks stay readable. @@ -849,7 +888,14 @@ fn row_sub(job: &Timing, lang: Lang) -> Option { /// its box at its real start and end, a hatched lead-in from its queueing, and an elbow connector with /// an arrowhead from each needed job's end to the start of the job that needs it. A blocked job is an /// outline from its needs' end, and a skipped or cancelled one is an outline across the track. -fn gantt(jobs: &[Timing], origin: i64, run_end: Option, now: i64, lang: Lang) -> Gantt { +fn gantt( + jobs: &[Timing], + origin: i64, + run_end: Option, + now: i64, + lang: Lang, + selected: Option, +) -> Gantt { let last = jobs .iter() .filter_map(|job| job.end(now)) @@ -858,9 +904,26 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option, now: i64, lang: Lan .unwrap_or(now); let (step, len) = axis((last - origin).max(1)); let x = |at: i64| TRACK_X + place(at - origin, len, TRACK_W); - let row_mid = |i: usize| AXIS_H + i as i64 * ROW_H + ROW_H / 2; + // The selected job's steps take a lane each under its row, so every row below it moves down. + let row_height = |i: usize| { + ROW_H + + if selected == Some(i) { + jobs[i].steps.len() as i64 * STEP_H + } else { + 0 + } + }; + let tops: Vec = (0..jobs.len()) + .scan(AXIS_H, |top, i| { + let at = *top; + *top += row_height(i); + Some(at) + }) + .collect(); + let row_top = |i: usize| tops[i]; + let row_mid = |i: usize| row_top(i) + ROW_H / 2; let track_end = TRACK_X + TRACK_W; - let height = AXIS_H + jobs.len() as i64 * ROW_H; + let height = AXIS_H + (0..jobs.len()).map(&row_height).sum::(); let mut g = Gantt { view_box: format!("0 0 {GANTT_W} {height}"), origin: origin.to_string(), @@ -926,8 +989,7 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option, now: i64, lang: Lan let mut targets: Vec> = Vec::with_capacity(jobs.len()); for (i, job) in jobs.iter().enumerate() { let row = &rows[i]; - let top = AXIS_H + i as i64 * ROW_H; - let bar_y = top + BAR_DY; + let bar_y = row_top(i) + BAR_DY; let label_y = (bar_y + BAR_H / 2 + 4).to_string(); g.labels.push(Label { class: "ci-gname", @@ -1076,6 +1138,36 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option, now: i64, lang: Lan }, } } + // The selected job's steps: a lane each under its row, with a box at the step's times. + if let Some(i) = selected.filter(|i| *i < jobs.len()) { + for (k, step) in jobs[i].steps.iter().enumerate() { + let lane = row_top(i) + ROW_H + k as i64 * STEP_H; + let end = step.end.unwrap_or(now); + let left = x(step.start); + let width = (x(end) - left).max(MIN_BOX_W); + let mut bar = Rect::new( + format!("ci-gstep {}", tone(step.state)), + left, + lane + (STEP_H - 10) / 2, + width, + 10, + ); + bar.title = Some(format!( + "{} \u{b7} {}", + step.name, + span_text((end - step.start).max(0)) + )); + g.rects.push(bar); + g.labels.push(Label { + class: "ci-gsub", + x: "12".to_owned(), + y: (lane + STEP_H / 2 + 4).to_string(), + anchor: "start", + text: gantt_name(&step.name), + ..Default::default() + }); + } + } let xn = x(now); for (i, job) in jobs.iter().enumerate() { let Some((tx, child_moves, spans)) = targets[i] else { @@ -1199,7 +1291,126 @@ fn timing_of(job: &CiJob, runner: String, lang: Lang) -> Timing { started: job.started_at.as_deref().and_then(unix_of), finished: job.finished_at.as_deref().and_then(unix_of), cancel_requested: job.cancel_requested, + log_bytes: job.log_bytes, + steps: Vec::new(), + } +} + +/// The job state a step's box takes on the timeline: a passed step is a success, a failed one a failure. +fn step_job_state(state: StepState) -> JobState { + match state { + StepState::Passed => JobState::Success, + StepState::Failed => JobState::Failure, + StepState::Cancelled => JobState::Cancelled, + StepState::Running => JobState::Running, + } +} + +/// The steps of a job as the timeline draws them. A step whose start does not read is left out. +fn step_spans(steps: &[JobStep], job: JobState) -> Vec { + steps + .iter() + .filter_map(|step| { + Some(StepSpan { + name: step.name.clone(), + state: step_job_state(step.state(job)), + start: unix_of(&step.started_at)?, + end: step.finished_at.as_deref().and_then(unix_of), + }) + }) + .collect() +} + +/// A step's share of its job's bar: its state, its elapsed seconds and, while it runs, its expected ones. +struct BarStep { + state: StepState, + elapsed: i64, + expected: Option, +} + +/// The bar along a job's row: one segment per step, as wide as its seconds (a running step counts the +/// larger of its elapsed and expected seconds), with a gap between segments. A running step with an +/// estimate is a track of its full width with its elapsed share filled in the accent. +fn step_bar(steps: &[BarStep]) -> Vec { + let weight = |step: &BarStep| step.expected.unwrap_or(0).max(step.elapsed).max(1); + let total: i64 = steps.iter().map(weight).sum(); + let gaps = STEP_BAR_GAP * (steps.len() as i64 - 1).max(0); + // Every segment gets its least first, so 32 short steps beside a long one still all fit. + let room = (LIST_BAR_W - gaps - STEP_BAR_MIN * steps.len() as i64).max(0); + let mut rects = Vec::with_capacity(steps.len() + 1); + let mut x = 0; + for step in steps { + let weight = weight(step); + let w = STEP_BAR_MIN + weight * room / total; + match (step.state, step.expected) { + (StepState::Running, Some(expected)) => { + rects.push(Rect::new("ci-sbar-track", x, 0, w, 3)); + let done = step.elapsed.min(expected) * w / weight; + rects.push(Rect::new("ci-sbar-run", x, 0, done, 3)); + } + (StepState::Running, None) => rects.push(Rect::new("ci-sbar-run", x, 0, w, 3)), + (StepState::Passed, _) => rects.push(Rect::new("ci-sbar-pass", x, 0, w, 3)), + (StepState::Failed, _) => rects.push(Rect::new("ci-sbar-fail", x, 0, w, 3)), + (StepState::Cancelled, _) => rects.push(Rect::new("ci-sbar-off", x, 0, w, 3)), + } + x += w + STEP_BAR_GAP; + } + rects +} + +/// The rail's step lines of a job and the bar under its row. The lines are kept for the selected job +/// only, and `wanted` marks the step the log shows. A running step's expected time comes from the +/// repo's step samples. +fn job_steps( + job: &Timing, + steps: &[JobStep], + samples: &[StepSample], + run: &CiRun, + pick: &str, + wanted: Option, + now: i64, + lang: Lang, +) -> (Vec, Vec) { + let mut lines = Vec::with_capacity(steps.len()); + let mut bar = Vec::with_capacity(steps.len()); + for step in steps { + let state = step.state(job.state); + let running = state == StepState::Running; + let started = unix_of(&step.started_at); + let elapsed = started.map_or(0, |at| { + let end = step.finished_at.as_deref().and_then(unix_of).unwrap_or(now); + (end - at).max(0) + }); + let expected = running + .then(|| ci_estimate::step_expected(samples, &run.git_ref, &job.name, &step.name)) + .flatten(); + bar.push(BarStep { + state, + elapsed, + expected, + }); + // A step of a job whose log was pruned has no part of the log to open. + let href = (job.log_bytes != 0).then(|| format!("{pick}&step={}", step.seq)); + lines.push(StepLine { + name: step.name.clone(), + mark: match state { + StepState::Passed => "ci-st-pass", + StepState::Running => "ci-st-run", + StepState::Failed => "ci-st-fail", + StepState::Cancelled => "ci-st-off", + }, + duration: duration_text( + lang, + Some(step.started_at.as_str()), + step.finished_at.as_deref(), + ), + since: started.filter(|_| running).map(|at| at.to_string()), + expected: expected.map(|secs| format!("~{}", span_text(secs))), + selected: href.is_some() && wanted == Some(step.seq), + href, + }); } + (lines, step_bar(&bar)) } /// "test OOM" for a failed run: the first failed job's message, or its name and state. @@ -1275,7 +1486,12 @@ fn last_line(tail: &[String]) -> Option<&str> { tail.iter() .rev() .map(|line| line.trim()) - .find(|line| !line.is_empty()) + .find(|line| !line.is_empty() && !is_group_marker(line)) +} + +/// Whether a log line only opens or closes a group: it says nothing about what the job did. +fn is_group_marker(line: &str) -> bool { + line.starts_with("::group::") || line.starts_with("::endgroup::") } /// The last lines of a log, read from its tail only, without ANSI codes and trailing blank lines. @@ -1354,7 +1570,12 @@ struct SplitPage { /// The split view of the runs: the list (left) and the selected run (right). Both routes render it. /// `number` is the run the URL names. Without one, the newest run of the list page is selected. /// The list is live on every page: a run's state, its hint and its age change on any page of it. -async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result { +async fn runs_split( + cx: &Cx, + number: Option<&str>, + job: Option<&str>, + step: Option, +) -> Result { let owner = path_param::(cx); let name = path_param::(cx); let ctx = load_repo(cx, owner, name).await?; @@ -1549,6 +1770,7 @@ async fn runs_split(cx: &Cx, number: Option<&str>, job: Option<&str>) -> Result< lang, now, job, + step, ) .await?, ) @@ -1623,9 +1845,29 @@ async fn run_detail( lang: Lang, now: i64, wanted: Option<&str>, + wanted_step: Option, ) -> Result { - let jobs = timings_of(state, &run.id, runners, lang).await?; + let mut jobs = timings_of(state, &run.id, runners, lang).await?; let picked = pick_job(&jobs, wanted); + let mut steps_of: HashMap> = HashMap::new(); + for step in state.store.steps_for_run(&run.id).await? { + steps_of.entry(step.job_id.clone()).or_default().push(step); + } + for job in jobs.iter_mut() { + let spans = steps_of + .get(&job.id) + .map_or_else(Vec::new, |steps| step_spans(steps, job.state)); + job.steps = spans; + } + // A running step's expected time is judged from the samples of the run's branch. + let step_samples = if run.state == RunState::Running { + state + .store + .recent_step_samples(&run.repo_id, std::slice::from_ref(&run.git_ref)) + .await? + } else { + Vec::new() + }; let est = if run.state == RunState::Running { let samples = state .store @@ -1635,8 +1877,8 @@ async fn run_detail( } else { None }; - let gantt = - (!jobs.is_empty()).then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang)); + let gantt = (!jobs.is_empty()) + .then(|| gantt(&jobs, origin_of(run, now), run_end(run, now), now, lang, picked)); let writer = header.writer_csrf.is_some(); let rerunnable = writer && header.reachable; let mut lines = Vec::with_capacity(jobs.len()); @@ -1655,6 +1897,17 @@ async fn run_detail( }); } let tail = log_last_lines(&log_path(&state.config.data_dir, &job.id)).await; + let pick = format!("{}?job={}", run_href(title, run.number), job.id); + let (steps, step_bar) = job_steps( + job, + steps_of.get(&job.id).map(Vec::as_slice).unwrap_or_default(), + &step_samples, + run, + &pick, + wanted_step, + now, + lang, + ); let preview = match last_line(&tail) { Some(line) => line.to_owned(), None if job.state == JobState::Queued && !job.message.is_empty() => job.message.clone(), @@ -1672,7 +1925,13 @@ async fn run_detail( lines.push(JobLine { id: job.id.clone(), selected: picked == Some(index), - pick: format!("{}?job={}", run_href(title, run.number), job.id), + steps: if picked == Some(index) { + steps + } else { + Vec::new() + }, + step_bar, + pick, expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()), preview, tail: tail.join("\n"), @@ -1697,12 +1956,26 @@ async fn run_detail( let log = match picked { Some(index) => { let job = &jobs[index]; - let Tail { - text, - truncated, - offset, - first_line, - } = log_tail_of(&log_path(&state.config.data_dir, &job.id), RUN_LOG_BYTES).await?; + let path = log_path(&state.config.data_dir, &job.id); + // A step the URL names opens at its own line in the log, not at the job's end. + let step = wanted_step + .and_then(|seq| steps_of.get(&job.id)?.iter().find(|step| step.seq == seq)) + .filter(|_| job.log_bytes != 0); + let ( + Tail { + text, + truncated, + offset, + first_line, + }, + at_step, + ) = match step { + Some(step) => { + let from = u64::try_from(step.log_offset).unwrap_or(0); + (log_from(&path, from, RUN_LOG_BYTES).await?, true) + } + None => (log_tail_of(&path, RUN_LOG_BYTES).await?, false), + }; let href = job_href(title, &job.id); Some(JobLog { log_href: format!("{href}/log.txt"), @@ -1718,6 +1991,7 @@ async fn run_detail( truncated, offset: offset.to_string(), first_line: first_line.to_string(), + at_step, }) } None => None, @@ -1807,6 +2081,11 @@ fn job_from_query(cx: &Cx) -> Option { query_value(cx, "job") } +/// The step number `?step=` names, if the URL has a valid one. +fn step_from_query(cx: &Cx) -> Option { + query_value(cx, "step")?.parse().ok() +} + /// The value of one query parameter, if the URL has it. fn query_value(cx: &Cx, key: &str) -> Option { let query = uri(cx).query()?; @@ -2159,8 +2438,38 @@ async fn run_jobs(lang: Lang, run: &RunDetail) -> Result { } else { (job.duration.as_str()) } + if !job.step_bar.is_empty() { + + } + for step in job.steps.iter() { +
  • + if let Some(href) = step.href.as_ref() { + + + (step.name.as_str()) + (step.duration.as_str()) + if let Some(expected) = step.expected.as_ref() { + (expected.as_str()) + } + + } else { +
    + + (step.name.as_str()) + (step.duration.as_str()) + if let Some(expected) = step.expected.as_ref() { + (expected.as_str()) + } +
    + } +
  • + } } } @@ -2234,7 +2543,8 @@ async fn run_log(lang: Lang, run: &RunDetail, timeline: bool) -> Result } - if let Some(fail) = run.failing.clone() { + // A reader who picked a step came for that step: the failure's box would leave it no room. + if let Some(fail) = run.failing.clone().filter(|_| !run.log.as_ref().is_some_and(|log| log.at_step)) { fail_first_block(lang: lang, fail: fail) } if let Some(log) = run.log.as_ref() { @@ -2244,7 +2554,7 @@ async fn run_log(lang: Lang, run: &RunDetail, timeline: bool) -> Result(crate::pages::passkeys::s(lang, "Full log", "Tam günlük"))

    } -
    (log.text.as_str())
    +
    (log.text.as_str())
    } else {

    (g::t(lang, K::NoJobs))

    } @@ -2321,7 +2631,7 @@ async fn runs_list_page(cx: &Cx) -> Result { page_title, list, detail, - } = runs_split(cx, None, None).await?; + } = runs_split(cx, None, None, None).await?; Ok(view! { shell(title: page_title.as_str(), viewer: ctx.viewer.as_ref(), runs_body(head: head, lang: lang, notice: notice, live: live, list: list, detail: detail)) @@ -2334,6 +2644,7 @@ async fn runs_list_page(cx: &Cx) -> Result { async fn run_page(cx: &Cx) -> Result { let number = path_param::(cx).to_owned(); let wanted = job_from_query(cx); + let wanted_step = step_from_query(cx); let SplitPage { ctx, head, @@ -2343,7 +2654,7 @@ async fn run_page(cx: &Cx) -> Result { page_title, list, detail, - } = runs_split(cx, Some(&number), wanted.as_deref()).await?; + } = runs_split(cx, Some(&number), wanted.as_deref(), wanted_step).await?; let Some(run) = detail else { return Err(not_found().into()); }; @@ -2933,6 +3244,8 @@ mod tests { started, finished, cancel_requested: false, + log_bytes: 1, + steps: Vec::new(), } } @@ -3082,7 +3395,7 @@ mod tests { Some(4692), ); build.needs = vec!["test".to_owned()]; - let g = gantt(&[test, build], 0, Some(4692), 4692, Lang::En); + let g = gantt(&[test, build], 0, Some(4692), 4692, Lang::En, None); assert_eq!(g.view_box, "0 0 640 104"); let bars: Vec<&Rect> = g .rects @@ -3121,7 +3434,7 @@ mod tests { let mut build = timing("build", JobState::Success, Some(900), Some(900), Some(1200)); build.needs = vec!["test".to_owned()]; let test = timing("test", JobState::Failure, Some(0), Some(0), Some(600)); - let g = gantt(&[build, test], 0, Some(1200), 1200, Lang::En); + let g = gantt(&[build, test], 0, Some(1200), 1200, Lang::En, None); let link = &g.links[0]; assert!(link.hot, "a failed need lights its connector"); assert_eq!(link.rel, "j1 j0"); @@ -3137,7 +3450,7 @@ mod tests { build.needs = vec!["test".to_owned()]; let mut lint = timing("lint", JobState::Skipped, None, None, None); lint.needs = vec!["build".to_owned()]; - let g = gantt(&[test, build, lint], 0, Some(30), 30, Lang::En); + let g = gantt(&[test, build, lint], 0, Some(30), 30, Lang::En, None); // Only build has a need with an end; the connector rides the moving edge. assert_eq!(g.links.len(), 1); let link = &g.links[0]; @@ -3151,7 +3464,7 @@ mod tests { let broken = timing("broken", JobState::Failure, Some(0), Some(0), Some(30)); let mut skipme = timing("skipme", JobState::Skipped, None, None, None); skipme.needs = vec!["broken".to_owned()]; - let g = gantt(&[broken, skipme], 0, Some(30), 30, Lang::En); + let g = gantt(&[broken, skipme], 0, Some(30), 30, Lang::En, None); let part = &g.links[0].parts[0]; // Out of broken's end (365), down onto the top edge of skipme's outline. assert_eq!(part.x, 365); @@ -3162,7 +3475,7 @@ mod tests { #[test] fn a_queued_job_shows_its_lead_in_before_it_starts() { let test = timing("test", JobState::Success, Some(0), Some(4), Some(10)); - let g = gantt(&[test], 0, Some(10), 10, Lang::En); + let g = gantt(&[test], 0, Some(10), 10, Lang::En, None); let lead = g .rects .iter() diff --git a/docs/ci.md b/docs/ci.md index 0077a85..af61cbe 100644 --- a/docs/ci.md +++ b/docs/ci.md @@ -290,6 +290,28 @@ A line that is exactly `::group::name` starts a collapsible section and `::endgr themselves are not shown. Streaming keeps working while the job runs. The page shows the last 512 KiB; the full log is at `log.txt`. +A top-level group is a step of the job. Forge stores its name, when it started and ended, and where it +begins in the log. It estimates the step's duration the way it estimates the job's. Nested groups stay +plain sections. + +A step is closed by `::endgroup::`. A step still open when the job ends takes the job's result, so a +failing command under `sh -e` leaves its step failed. + +A job has at most 32 steps, and names are cut to 80 characters. Any program in the job can print these +lines, so a stray `::endgroup::` closes a step early. + +Print `exec 2>&1` first. The runner reads stdout and stderr separately, so without it a marker on stdout +can overtake the last stderr lines. For example: + +```sh +exec 2>&1 +echo "::group::Unit tests" +cargo test --workspace +echo "::endgroup::" +``` + +Step times come from when the log arrives, so they are good to about a second. + ### Releases A `[release]` table publishes a release from a tag run. It needs at least one glob in `[on] tags`. diff --git a/style/_lang_ci.scss b/style/_lang_ci.scss index 8dfbd86..1badb2c 100644 --- a/style/_lang_ci.scss +++ b/style/_lang_ci.scss @@ -86,6 +86,23 @@ grid-template-columns: minmax(0, 1fr); } + // The page scrolls here. A pane share of a fixed height left a run with a long title no room at all. + .ci-split.fit-pane { + height: auto; + overflow: visible; + } + + .ci-split > .ci-detail, + .ci-split > .ci-run { + height: auto; + overflow: visible; + } + + .ci-split > .ci-detail > .ci-tl-main, + .ci-split > .ci-run > .ci-tl-main { + flex: none; + } + .ci-split:has(> .ci-run) > .ci-side { display: none; } diff --git a/style/_shell.scss b/style/_shell.scss index c6dfd68..a7decd8 100644 --- a/style/_shell.scss +++ b/style/_shell.scss @@ -253,10 +253,12 @@ } } +// The shortcut sits right after the hint: at the far end of the bar it read as the key for the link +// beside it. .pathbar-edit { display: flex; align-items: center; - justify-content: space-between; + justify-content: flex-start; gap: 8px; flex: 1 1 0; height: 100%; diff --git a/style/_timeline_ci.scss b/style/_timeline_ci.scss index cfbe9cc..1bc8697 100644 --- a/style/_timeline_ci.scss +++ b/style/_timeline_ci.scss @@ -225,6 +225,7 @@ } .ci-tl-job { + position: relative; display: flex; align-items: center; gap: 10px; @@ -257,6 +258,115 @@ padding-left: 28px; } +// The job's bar: a 3 px band along the bottom of its row, one segment per step. It sits over the row's +// hairline and takes no room, so the row keeps its height. +.ci-tl-stepbar { + position: absolute; + left: 0; + bottom: 0; + display: block; + width: 100%; + height: 3px; + pointer-events: none; + + .ci-sbar-pass { + fill: var(--border-strong); + } + + .ci-sbar-fail { + fill: var(--bad); + } + + .ci-sbar-off, + .ci-sbar-track { + fill: var(--border); + } + + .ci-sbar-run { + fill: var(--accent); + } +} + +// A step under the selected job: a 30 px line with a 6 px mark, its name and its duration at the right. +// Indented past the job's dot, one level more for a matrix combination. The selected step has an +// accent edge on the left, and a failed step's name reads in --text. +.ci-tl-step { + display: flex; + align-items: center; + gap: 8px; + height: 30px; + min-width: 0; + padding: 0 14px 0 34px; + box-shadow: inset 0 -1px var(--border); + color: var(--text-2); + text-decoration: none; + font-size: 12px; + + &.ci-tl-step-sub { + padding-left: 48px; + } + + &:hover { + background: var(--surface-2); + text-decoration: none; + } + + &[aria-current="true"] { + color: var(--text); + background: var(--surface-2); + box-shadow: inset 2px 0 var(--accent), inset 0 -1px var(--border); + } + + .ci-tl-dur { + margin-left: auto; + flex: none; + font-family: var(--mono); + font-size: 11px; + color: var(--text-2); + } +} + +.ci-tl-stepmark { + flex: none; + width: 6px; + height: 6px; + border-radius: 50%; + background: var(--muted); + + &.ci-st-run { + background: var(--accent); + } + + &.ci-st-fail { + background: var(--bad); + } + + &.ci-st-off { + background: transparent; + border: 1px solid var(--muted); + box-sizing: border-box; + } +} + +.ci-tl-stepname { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ci-st-fail ~ .ci-tl-stepname { + color: var(--text); +} + +.ci-tl-stepexp { + flex: none; + font-family: var(--mono); + font-size: 11px; + color: var(--muted); +} + .ci-tl-name { flex: 1 1 auto; min-width: 0; @@ -406,6 +516,11 @@ } // The code area: --bg, mono 12.5 px on a 1.7 line, numbers right aligned in their own column. +// A group's name sticks to the pane's edge, not inside its padding, or lines show above it. +.ci-tl-code details.lg > summary { + top: -14px; +} + .ci-tl-code { flex: 1 1 0; min-height: 0; @@ -526,7 +641,13 @@ overflow: visible; } - .ci-tl-code { + // These panels share out a fixed height on a wide window; here there is none to share. + .ci-tl-panel { + flex: none; + } + + .ci-tl-panel-log > .ci-log.ci-tl-code { + flex: none; max-height: 60vh; } diff --git a/style/main.scss b/style/main.scss index 7971c2d..e0fc088 100644 --- a/style/main.scss +++ b/style/main.scss @@ -5060,7 +5060,13 @@ button.ci-mini { } } + // The group's name stays at the top of the log while its lines are read. It is opaque, so the lines + // scroll under it, and the code area's scroll is the one that sticks it. details.lg > summary { + position: sticky; + top: 0; + z-index: 1; + background: var(--bg); cursor: pointer; font-weight: 600; color: var(--text); @@ -6013,6 +6019,30 @@ html.js form.runner-load[data-dirty-form][data-dirty] .runner-save { } } +// A step's box under the selected job: the job colours, at a lower opacity so the job's own bar leads. +.ci-gstep { + rx: 3px; + opacity: 0.7; + + &.ci-ok { + fill: var(--ok); + } + + &.ci-bad { + fill: var(--bad); + } + + &.ci-run { + fill: var(--heat-3); + } + + &.ci-muted { + fill: var(--surface-2); + stroke: var(--border-strong); + stroke-width: 1; + } +} + .ci-glead { fill: url(#ci-hatch); }