diff --git a/Cargo.lock b/Cargo.lock index 33db61e..42dcb31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1039,6 +1039,17 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "croner" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b5b023fc2978536bbb2a3b71237964fc4630bec1eb31077b4977127f4cdb9c0" +dependencies = [ + "chrono", + "derive_builder", + "strum 0.27.2", +] + [[package]] name = "crossbeam-channel" version = "0.5.17" @@ -1850,6 +1861,8 @@ name = "forge-ci" version = "0.1.0" dependencies = [ "base64 0.23.1", + "chrono", + "croner", "globset", "serde", "serde_ignored", @@ -6677,6 +6690,9 @@ name = "strum" version = "0.27.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" +dependencies = [ + "strum_macros 0.27.2", +] [[package]] name = "strum_macros" diff --git a/crates/forge-ci/Cargo.toml b/crates/forge-ci/Cargo.toml index 9f40e4c..7df20c8 100644 --- a/crates/forge-ci/Cargo.toml +++ b/crates/forge-ci/Cargo.toml @@ -8,6 +8,8 @@ publish = false [dependencies] base64 = { workspace = true } +chrono = { version = "0.4.45", default-features = false } +croner = "4.0.1" globset = { workspace = true } serde = { workspace = true } serde_ignored = "0.1.14" diff --git a/crates/forge-ci/src/config.rs b/crates/forge-ci/src/config.rs index d03956d..d960852 100644 --- a/crates/forge-ci/src/config.rs +++ b/crates/forge-ci/src/config.rs @@ -38,6 +38,11 @@ pub const MAX_RELEASE_ASSETS: usize = 32; /// Longest `[release] title` template, in characters, after trimming. pub const MAX_RELEASE_TITLE_CHARS: usize = 200; +/// Most `[on] schedule` entries. +pub const MAX_SCHEDULES: usize = 8; +/// Longest matrix axis value, in characters. +pub const MAX_MATRIX_VALUE_CHARS: usize = 64; + /// A parsed and validated workflow. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct CiConfig { @@ -148,6 +153,9 @@ pub struct Triggers { /// Defaults to `false`. When set, a push to a branch cancels the queued and running runs of /// older commits on that branch. pub cancel_superseded: bool, + /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default + /// branch head at each match. + pub schedule: Vec, } impl Default for Triggers { @@ -158,6 +166,7 @@ impl Default for Triggers { pull_request: false, manual: true, cancel_superseded: false, + schedule: Vec::new(), } } } @@ -187,6 +196,51 @@ pub struct JobSpec { pub timeout_minutes: u32, #[serde(default = "default_network")] pub network: bool, + /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job + /// with one job per combination, and those have no matrix. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub matrix: Option, +} + +/// A matrix axis value. TOML strings, integers and booleans are all read as text. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] +pub struct MatrixValue(pub String); + +impl Serialize for MatrixValue { + fn serialize(&self, serializer: S) -> Result { + serializer.serialize_str(&self.0) + } +} + +impl<'de> Deserialize<'de> for MatrixValue { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Raw { + Text(String), + Int(i64), + Flag(bool), + } + Ok(MatrixValue(match Raw::deserialize(deserializer)? { + Raw::Text(text) => text, + Raw::Int(n) => n.to_string(), + Raw::Flag(b) => b.to_string(), + })) + } +} + +/// A job's `matrix` table: every key but `exclude` and `include` is an axis with its values. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct MatrixSpec { + /// Combinations to drop. An entry matches a combination that agrees on every key it names. + #[serde(default)] + pub exclude: Vec>, + /// Extra combinations. Each names a value for every axis, and may add more keys, which are + /// exposed like the axes but are not part of the job name. + #[serde(default)] + pub include: Vec>, + #[serde(flatten)] + pub axes: BTreeMap>, } fn default_timeout_minutes() -> u32 { @@ -200,10 +254,16 @@ fn default_network() -> bool { /// Something that can start a workflow run. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Event<'a> { - Push { branch: &'a str }, - Tag { tag: &'a str }, + Push { + branch: &'a str, + }, + Tag { + tag: &'a str, + }, PullRequest, Manual, + /// A `[on] schedule` tick. + Schedule, } /// Parses and validates a `ci.toml` document. @@ -224,6 +284,7 @@ pub fn parse_config(text: &str) -> Result { )); }) .map_err(|e| ConfigError::Toml(e.to_string()))?; + config.expand_matrices()?; config.validate()?; config.warnings = warnings; Ok(config) @@ -237,6 +298,7 @@ impl CiConfig { Event::Tag { tag } => matches_any(&self.on.tags, tag), Event::PullRequest => self.on.pull_request, Event::Manual => self.on.manual, + Event::Schedule => !self.on.schedule.is_empty(), } } @@ -274,6 +336,57 @@ impl CiConfig { order } + /// Checks every job key, then replaces each matrix job with one job per combination, named + /// `base (v1, v2)` with the axis values in axis-name order. Expanded jobs get `MATRIX_` + /// env entries and `${{ matrix.key }}` (or `${matrix.key}`) filled in `image`, `runs_on` and + /// `run`. A `needs` on a matrix job becomes a `needs` on all its combinations. + fn expand_matrices(&mut self) -> Result<(), ConfigError> { + for name in self.jobs.keys() { + if !is_job_name(name) { + return Err(ConfigError::InvalidJobName(name.clone())); + } + } + let mut groups: BTreeMap> = BTreeMap::new(); + let mut expanded: BTreeMap = BTreeMap::new(); + for (name, mut job) in std::mem::take(&mut self.jobs) { + let Some(matrix) = job.matrix.take() else { + expanded.insert(name, job); + continue; + }; + let mut names = Vec::new(); + for (suffix, vars) in combinations(&name, &matrix)? { + let mut copy = job.clone(); + copy.image = interpolate(&name, ©.image, &vars)?; + copy.run = interpolate(&name, ©.run, &vars)?; + for label in &mut copy.runs_on { + *label = interpolate(&name, label, &vars)?; + } + for (key, value) in &vars { + copy.env.insert( + format!("MATRIX_{}", key.to_ascii_uppercase()), + value.clone(), + ); + } + let full = format!("{name} ({suffix})"); + names.push(full.clone()); + expanded.insert(full, copy); + } + groups.insert(name, names); + } + for job in expanded.values_mut() { + job.needs = job + .needs + .iter() + .flat_map(|need| match groups.get(need) { + Some(all) => all.clone(), + None => vec![need.clone()], + }) + .collect(); + } + self.jobs = expanded; + Ok(()) + } + fn validate(&self) -> Result<(), ConfigError> { if let Some(name) = &self.name { validate_workflow_name(name)?; @@ -293,6 +406,18 @@ impl CiConfig { for pattern in &self.on.tags { validate_trigger_glob("tag", pattern)?; } + if self.on.schedule.len() > MAX_SCHEDULES { + return Err(ConfigError::InvalidSchedule { + expr: String::new(), + reason: format!("at most {MAX_SCHEDULES} schedules are allowed"), + }); + } + for expr in &self.on.schedule { + crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { + expr: expr.clone(), + reason, + })?; + } for (name, job) in &self.jobs { validate_job(name, job, &self.jobs)?; } @@ -333,7 +458,7 @@ impl ReleaseSpec { pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { self.assets.iter().any(|asset| { asset_selector(asset).is_some_and(|(selected_job, glob)| { - selected_job == job && matches_any(&[glob.to_string()], artifact_name) + names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) }) }) } @@ -542,7 +667,7 @@ fn validate_release_asset( let Some((job, glob)) = asset_selector(asset) else { return Err(invalid("must be \"job:glob\"".into())); }; - let Some(spec) = jobs.get(job) else { + let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { return Err(invalid(format!("job {job:?} is not defined"))); }; if spec.artifacts.is_empty() { @@ -579,14 +704,203 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> { Ok(()) } +/// The job name without its matrix suffix: `test (stable, x86_64)` gives `test`. +pub fn base_job_name(name: &str) -> &str { + name.split_once(" (").map_or(name, |(base, _)| base) +} + +/// Whether `selected` (a job name from the config) names `job`: the job itself, or any +/// combination of the matrix job `selected`. +fn names_job(selected: &str, job: &str) -> bool { + selected == job + || job + .strip_prefix(selected) + .is_some_and(|rest| rest.starts_with(" (")) +} + +fn is_matrix_key(key: &str) -> bool { + let Some((first, rest)) = key.as_bytes().split_first() else { + return false; + }; + rest.len() <= 31 + && first.is_ascii_lowercase() + && rest + .iter() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') +} + +/// One matrix combination: the job name suffix and its variables. +type Combination = (String, BTreeMap); + +/// The combinations of a matrix as `(name suffix, variables)`, in a stable order. +fn combinations(job: &str, matrix: &MatrixSpec) -> Result, ConfigError> { + let bad = |reason: String| ConfigError::InvalidMatrix { + job: job.to_string(), + reason, + }; + if matrix.axes.is_empty() { + return Err(bad( + "needs at least one axis, e.g. rust = [\"stable\"]".into() + )); + } + let mut total: usize = 1; + for (key, values) in &matrix.axes { + if !is_matrix_key(key) { + return Err(bad(format!( + "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" + ))); + } + if values.is_empty() { + return Err(bad(format!("axis {key:?} has no values"))); + } + for (i, value) in values.iter().enumerate() { + validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; + if values[..i].contains(value) { + return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); + } + } + total = total.saturating_mul(values.len()); + if total > MAX_JOBS { + return Err(ConfigError::MatrixTooLarge { + job: job.to_string(), + count: total, + max: MAX_JOBS, + }); + } + } + let mut combos: Vec> = vec![BTreeMap::new()]; + for (key, values) in &matrix.axes { + combos = combos + .into_iter() + .flat_map(|base| { + values.iter().map(move |value| { + let mut next = base.clone(); + next.insert(key.clone(), value.0.clone()); + next + }) + }) + .collect(); + } + for entry in &matrix.exclude { + for key in entry.keys() { + if !matrix.axes.contains_key(key) { + return Err(bad(format!("exclude names {key:?}, which is not an axis"))); + } + } + combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); + } + for entry in &matrix.include { + let mut combo = BTreeMap::new(); + for (key, value) in entry { + if !is_matrix_key(key) { + return Err(bad(format!( + "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" + ))); + } + validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; + combo.insert(key.clone(), value.0.clone()); + } + if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { + return Err(bad(format!("an include entry must set axis {missing:?}"))); + } + let same_axes = |other: &BTreeMap| { + matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) + }; + if !combos.iter().any(same_axes) { + combos.push(combo); + } + } + if combos.is_empty() { + return Err(bad("exclude removes every combination".into())); + } + if combos.len() > MAX_JOBS { + return Err(ConfigError::MatrixTooLarge { + job: job.to_string(), + count: combos.len(), + max: MAX_JOBS, + }); + } + Ok(combos + .into_iter() + .map(|combo| { + let suffix = matrix + .axes + .keys() + .filter_map(|k| combo.get(k).map(String::as_str)) + .collect::>() + .join(", "); + (suffix, combo) + }) + .collect()) +} + +/// A matrix value: non-empty, at most [`MAX_MATRIX_VALUE_CHARS`] characters, no control +/// characters, and none of `,`, `(` and `)`, which would make job names ambiguous. +fn validate_matrix_value(value: &str) -> Result<(), String> { + if value.is_empty() { + return Err("values must not be empty".into()); + } + if value.chars().count() > MAX_MATRIX_VALUE_CHARS { + return Err(format!( + "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" + )); + } + if value + .chars() + .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) + { + return Err(format!( + "{value:?} must not contain control characters, commas or parentheses" + )); + } + Ok(()) +} + +/// Replaces `${{ matrix.key }}` and `${matrix.key}` in `text`. A key that is not in `vars` is an +/// error, so a typo fails at parse time instead of reaching the shell. Anything else that starts +/// with `${` is left alone. +fn interpolate( + job: &str, + text: &str, + vars: &BTreeMap, +) -> Result { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + while let Some(at) = rest.find("${") { + out.push_str(&rest[..at]); + let after = &rest[at + 2..]; + let found = if let Some(body) = after.strip_prefix('{') { + body.find("}}") + .map(|end| (body[..end].trim(), &body[end + 2..])) + } else { + after + .find('}') + .map(|end| (after[..end].trim(), &after[end + 1..])) + }; + match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { + Some((key, tail)) => { + let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { + job: job.to_string(), + reason: format!("`matrix.{key}` is not an axis or include key"), + })?; + out.push_str(value); + rest = tail; + } + None => { + out.push_str("${"); + rest = after; + } + } + } + out.push_str(rest); + Ok(out) +} + fn validate_job( name: &str, job: &JobSpec, all: &BTreeMap, ) -> Result<(), ConfigError> { - if !is_job_name(name) { - return Err(ConfigError::InvalidJobName(name.to_string())); - } if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { return Err(ConfigError::InvalidImage { job: name.to_string(), @@ -722,9 +1036,9 @@ artifacts = ["target/release/forge"] #[test] fn unknown_keys_are_ignored_with_a_warning() { - let cfg = parse_config(&format!("[on]\nschedule = true\n{}", job_toml(""))).unwrap(); + let cfg = parse_config(&format!("[on]\nwebhook = true\n{}", job_toml(""))).unwrap(); assert_eq!(cfg.warnings.len(), 1); - assert!(cfg.warnings[0].starts_with("unknown key `on.schedule` ignored")); + assert!(cfg.warnings[0].starts_with("unknown key `on.webhook` ignored")); assert!(cfg.on.manual, "known keys still apply"); let cfg = parse_config(&job_toml("bogus = 1")).unwrap(); @@ -1340,4 +1654,163 @@ artifacts = ["target/release/forge"] assert!(without.release.is_none()); assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); } + + fn matrix_toml(matrix: &str, extra: &str) -> String { + format!( + "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" + ) + } + + const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; + + #[test] + fn schedule_is_parsed_and_validated() { + let cfg = parse_config(&format!( + "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", + job_toml("") + )) + .unwrap(); + assert_eq!(cfg.on.schedule.len(), 2); + assert!(cfg.warnings.is_empty()); + assert!(cfg.triggered_by(&Event::Schedule)); + let none = parse_config(&job_toml("")).unwrap(); + assert!(!none.triggered_by(&Event::Schedule)); + for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { + let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); + assert!( + matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), + "{bad}" + ); + } + let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); + let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); + assert!(matches!(err_of(&text), ConfigError::InvalidSchedule { .. })); + } + + #[test] + fn a_matrix_expands_into_named_jobs() { + let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); + let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); + assert_eq!( + names, + [ + "test (1.85, aarch64)", + "test (1.85, x86_64)", + "test (stable, aarch64)", + "test (stable, x86_64)" + ] + ); + let job = &cfg.jobs["test (stable, x86_64)"]; + assert_eq!(job.image, "rust:stable"); + assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); + assert_eq!(job.runs_on, vec!["x86_64".to_string()]); + assert_eq!(job.env["MATRIX_RUST"], "stable"); + assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); + assert!(job.matrix.is_none()); + } + + #[test] + fn matrix_exclude_and_include() { + let m = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Z" }] }"#; + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); + assert_eq!(cfg.jobs.len(), 4); + assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); + let extra = &cfg.jobs["test (nightly, x86_64)"]; + assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); + // A partial exclude drops every combination that agrees on the named keys. + let m = + r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); + assert_eq!( + cfg.jobs.keys().collect::>(), + ["test (stable, x86_64)"] + ); + // An include that repeats an existing combination adds nothing. + let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; + assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); + } + + #[test] + fn needs_on_a_matrix_job_waits_for_every_combination() { + let text = format!( + "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", + matrix_toml(GRID, "") + ); + let cfg = parse_config(&text).unwrap(); + assert_eq!(cfg.jobs["ship"].needs.len(), 4); + let order = cfg.job_order(); + assert_eq!(order.last(), Some(&"ship")); + // The matrix job's own needs apply to each combination. + let text = format!( + "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", + matrix_toml(GRID, "needs = [\"setup\"]") + ); + let cfg = parse_config(&text).unwrap(); + assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); + } + + #[test] + fn matrix_errors_are_clear() { + let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); + let e = err_of(&text); + assert_eq!( + e, + ConfigError::MatrixTooLarge { + job: "t".into(), + count: 25, + max: MAX_JOBS + } + ); + assert!(e.to_string().contains("limit is 20")); + // Expansion that fits one job but not the workflow hits the job cap. + let mut text = String::new(); + for i in 0..MAX_JOBS - 1 { + text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); + } + text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); + assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); + for bad in [ + "{}", + "{ a = [] }", + "{ a = [\"x\", \"x\"] }", + "{ A = [\"x\"] }", + "{ a = [\"x,y\"] }", + "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", + "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", + "{ a = [\"x\"], include = [{ b = \"1\" }] }", + ] { + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); + assert!( + matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), + "{bad}" + ); + } + // A typo in an interpolation fails at parse time. + let text = + "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; + assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); + // Plain job keys cannot smuggle a suffix. + let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; + assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); + } + + #[test] + fn shell_variables_are_left_alone() { + let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; + let cfg = parse_config(text).unwrap(); + assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); + } + + #[test] + fn release_assets_can_name_a_matrix_job() { + let text = format!( + "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", + matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") + ); + let cfg = parse_config(&text).unwrap(); + let release = cfg.release.unwrap(); + assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); + assert!(!release.asset_matches("testing", "a.tar")); + } } diff --git a/crates/forge-ci/src/cron.rs b/crates/forge-ci/src/cron.rs new file mode 100644 index 0000000..d376e85 --- /dev/null +++ b/crates/forge-ci/src/cron.rs @@ -0,0 +1,81 @@ +//! Standard 5-field cron expressions in UTC, for `[on] schedule`. +//! +//! Times are Unix seconds. The functions are pure, so the scheduler's tick logic can be tested +//! with a fake clock. + +use chrono::DateTime; +use croner::Cron; + +/// Parses a 5-field cron expression (`minute hour day-of-month month day-of-week`). +pub fn parse(expr: &str) -> Result { + let trimmed = expr.trim(); + if trimmed.split_whitespace().count() != 5 { + return Err( + "must have exactly 5 fields: minute hour day-of-month month day-of-week".into(), + ); + } + trimmed.parse::().map_err(|e| e.to_string()) +} + +/// The first time strictly after `after` that `cron` matches. +fn next_one(cron: &Cron, after: i64) -> Option { + let start = DateTime::from_timestamp(after, 0)?.naive_utc(); + let next = cron.find_next_occurrence(&start, false).ok()?; + Some(next.and_utc().timestamp()) +} + +/// The first time strictly after `after` that any of `exprs` matches. Expressions that do not +/// parse are ignored. +pub fn next_after>(exprs: &[S], after: i64) -> Option { + exprs + .iter() + .filter_map(|e| parse(e.as_ref()).ok()) + .filter_map(|c| next_one(&c, after)) + .min() +} + +/// Whether any of `exprs` matched a time `t` with `last < t <= now`. However many ticks fell in +/// that window, the answer is one yes: a scheduler that was down catches up once. +pub fn fired_between>(exprs: &[S], last: i64, now: i64) -> bool { + next_after(exprs, last).is_some_and(|t| t <= now) +} + +#[cfg(test)] +mod tests { + use super::*; + + // 2026-10-15 12:00:00 UTC + const NOON: i64 = 1_791_979_200; + + #[test] + fn requires_five_fields() { + assert!(parse("0 3 * * *").is_ok()); + assert!(parse("0 0 3 * * *").is_err()); + assert!(parse("0 3 * *").is_err()); + assert!(parse("61 3 * * *").is_err()); + assert!(parse("nope").is_err()); + } + + #[test] + fn next_is_strictly_after() { + let day = 86_400; + let three = NOON - 9 * 3600 + day; + assert_eq!(next_after(&["0 3 * * *"], NOON), Some(three)); + assert_eq!(next_after(&["0 3 * * *"], three), Some(three + day)); + assert_eq!( + next_after(&["0 3 * * *", "30 12 * * *"], NOON), + Some(NOON + 1800) + ); + assert_eq!(next_after::<&str>(&[], NOON), None); + } + + #[test] + fn fires_inside_the_window_only() { + assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800)); + assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799)); + // The window is open at `last`: a tick already handled does not fire again. + assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60)); + // A week of downtime is still one yes. + assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400)); + } +} diff --git a/crates/forge-ci/src/error.rs b/crates/forge-ci/src/error.rs index 0a1109f..04d4a27 100644 --- a/crates/forge-ci/src/error.rs +++ b/crates/forge-ci/src/error.rs @@ -14,9 +14,24 @@ pub enum ConfigError { #[error("no jobs are defined")] NoJobs, - #[error("{count} jobs are defined, the limit is {max}")] + #[error( + "{count} jobs are defined (a matrix job counts once per combination), the limit is {max}" + )] TooManyJobs { count: usize, max: usize }, + #[error("job {job:?}: matrix expands to {count} jobs, the limit is {max} jobs per workflow")] + MatrixTooLarge { + job: String, + count: usize, + max: usize, + }, + + #[error("job {job:?}: invalid matrix: {reason}")] + InvalidMatrix { job: String, reason: String }, + + #[error("invalid schedule {expr:?}: {reason}")] + InvalidSchedule { expr: String, reason: String }, + #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] InvalidJobName(String), diff --git a/crates/forge-ci/src/lib.rs b/crates/forge-ci/src/lib.rs index 829bd66..b02eaf5 100644 --- a/crates/forge-ci/src/lib.rs +++ b/crates/forge-ci/src/lib.rs @@ -2,6 +2,7 @@ //! forge-web and forge-runner. pub mod config; +pub mod cron; pub mod error; pub mod mask; pub mod proto; diff --git a/crates/forge-core/migrations/0055_attachments.sql b/crates/forge-core/migrations/0052_attachments.sql similarity index 100% rename from crates/forge-core/migrations/0055_attachments.sql rename to crates/forge-core/migrations/0052_attachments.sql diff --git a/crates/forge-core/migrations/0056_review_requests.sql b/crates/forge-core/migrations/0053_review_requests.sql similarity index 100% rename from crates/forge-core/migrations/0056_review_requests.sql rename to crates/forge-core/migrations/0053_review_requests.sql diff --git a/crates/forge-core/migrations/0054_ci_schedule_state.sql b/crates/forge-core/migrations/0054_ci_schedule_state.sql new file mode 100644 index 0000000..2de775f --- /dev/null +++ b/crates/forge-core/migrations/0054_ci_schedule_state.sql @@ -0,0 +1,9 @@ +-- Where the CI scheduler left off, per repo: the last time (Unix seconds, UTC) it checked the +-- repo's `[on] schedule`. A cron match in (last_tick, now] queues one run, however many ticks that +-- spans, so a server that was down catches up once. A repo with no schedule has no row. Applied by +-- store/migrate.rs. + +CREATE TABLE ci_schedule_state ( + repo_id TEXT PRIMARY KEY REFERENCES repos(id) ON DELETE CASCADE, + last_tick INTEGER NOT NULL +); diff --git a/crates/forge-core/src/store/ci.rs b/crates/forge-core/src/store/ci.rs index 1d93d48..363ea7b 100644 --- a/crates/forge-core/src/store/ci.rs +++ b/crates/forge-core/src/store/ci.rs @@ -487,6 +487,60 @@ impl Store { .await } + /// Repos the CI scheduler looks at: everything that is not archived. + pub async fn repos_for_ci_schedule(&self) -> Result> { + let conn = self.read_conn().await; + fetch_all( + &conn, + &format!( + "SELECT {} FROM repos r JOIN users u ON u.id = r.owner_id \ + WHERE r.archived = 0 ORDER BY r.id", + super::REPO_COLS + ), + (), + super::map_repo, + ) + .await + } + + /// When (Unix seconds) the scheduler last checked `repo_id`, if it has. + pub async fn ci_schedule_last_tick(&self, repo_id: &str) -> Result> { + let conn = self.read_conn().await; + fetch_opt( + &conn, + "SELECT last_tick FROM ci_schedule_state WHERE repo_id = ?1", + (repo_id.to_string(),), + |row| col_int(row, 0), + ) + .await + } + + /// Records that the scheduler checked `repo_id` at `tick` (Unix seconds). + pub async fn set_ci_schedule_last_tick(&self, repo_id: &str, tick: i64) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "INSERT INTO ci_schedule_state (repo_id, last_tick) VALUES (?1, ?2) \ + ON CONFLICT(repo_id) DO UPDATE SET last_tick = excluded.last_tick", + (repo_id.to_string(), tick), + ) + .await + .map_err(db_err)?; + Ok(()) + } + + /// Forgets `repo_id`, for a repo whose workflow no longer has a schedule. Turning a schedule + /// back on later then starts from that moment instead of catching up. + pub async fn clear_ci_schedule(&self, repo_id: &str) -> Result<()> { + let conn = self.inner.conn.lock().await; + conn.execute( + "DELETE FROM ci_schedule_state WHERE repo_id = ?1", + (repo_id.to_string(),), + ) + .await + .map_err(db_err)?; + Ok(()) + } + /// Disabled runners get no jobs. `NotFound` if the runner does not exist. pub async fn set_runner_disabled(&self, id: &str, disabled: bool) -> Result<()> { let conn = self.inner.conn.lock().await; diff --git a/crates/forge-core/src/store/migrate.rs b/crates/forge-core/src/store/migrate.rs index 6b10137..6767394 100644 --- a/crates/forge-core/src/store/migrate.rs +++ b/crates/forge-core/src/store/migrate.rs @@ -82,10 +82,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ ), (50, include_str!("../../migrations/0050_imports.sql")), (51, include_str!("../../migrations/0051_data_exports.sql")), - (55, include_str!("../../migrations/0055_attachments.sql")), + (52, include_str!("../../migrations/0052_attachments.sql")), ( - 56, - include_str!("../../migrations/0056_review_requests.sql"), + 53, + include_str!("../../migrations/0053_review_requests.sql"), + ), + ( + 54, + include_str!("../../migrations/0054_ci_schedule_state.sql"), ), ]; diff --git a/crates/forge-web/src/boot.rs b/crates/forge-web/src/boot.rs index 9646d18..138cf4b 100644 --- a/crates/forge-web/src/boot.rs +++ b/crates/forge-web/src/boot.rs @@ -154,6 +154,7 @@ pub async fn serve( crate::replication::worker::spawn(state.clone()); } crate::ci::reaper::spawn(state.clone()); + crate::ci::scheduled::spawn(state.clone()); // Topcoat's builder-wide compression is off because it cannot filter by content type or path. // `ResponseCompression` compresses text responses only and skips git, LFS, raw and archive paths. diff --git a/crates/forge-web/src/ci/mod.rs b/crates/forge-web/src/ci/mod.rs index f6a7aa1..7e5611e 100644 --- a/crates/forge-web/src/ci/mod.rs +++ b/crates/forge-web/src/ci/mod.rs @@ -15,6 +15,7 @@ pub mod live; pub mod reaper; pub mod release; pub mod schedule; +pub mod scheduled; pub use live::CiLive; pub use schedule::{manual_run, on_pull_event, on_ref_update}; diff --git a/crates/forge-web/src/ci/schedule.rs b/crates/forge-web/src/ci/schedule.rs index 685a382..a113f38 100644 --- a/crates/forge-web/src/ci/schedule.rs +++ b/crates/forge-web/src/ci/schedule.rs @@ -29,7 +29,7 @@ const MIB: u64 = 1024 * 1024; type PlannedJob = (String, String, Vec); /// What `.forge/ci.toml` held at one commit. -enum Loaded { +pub(super) enum Loaded { Missing, Invalid(String), Valid(CiConfig), @@ -225,6 +225,68 @@ pub async fn manual_run( } } +/// The head commit of the repo's default branch and the workflow at it. `None` when the branch +/// has no commits (or cannot be read, which is logged). +pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option<(String, Loaded)> { + let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).ok()?; + let short = repo.default_branch.clone(); + let commit = match blocking(move || resolve_commit(&repo_dir, &short)).await { + Ok(commit) => commit?, + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "ci: resolving the default branch failed"); + return None; + } + }; + let loaded = load(state, &repo.id, &commit).await; + Some((commit, loaded)) +} + +/// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is +/// no valid workflow. +pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec { + match default_head_config(state, repo).await { + Some((_, Loaded::Valid(cfg))) => cfg.on.schedule, + _ => Vec::new(), + } +} + +/// Queues a `schedule` run of `commit` on the default branch. A config that does not parse gives +/// an Error run, as a push does. Nothing happens when the workflow has no schedule. +pub(super) async fn scheduled_run( + state: &AppState, + repo: &Repo, + commit: &str, + loaded: Loaded, +) -> forge_core::Result> { + let Plan::Run { + jobs, + config_error, + warnings, + } = plan_for(loaded, &Event::Schedule)? + else { + return Ok(None); + }; + let git_ref = format!("refs/heads/{}", repo.default_branch); + let run = create( + state, + Request { + repo, + trigger: "schedule", + git_ref: &git_ref, + commit, + pull_number: None, + // The column needs a user; the repo owner stands in. The pages show no actor for these. + actor_id: &repo.owner_id, + needs_approval: false, + }, + jobs, + config_error.as_deref(), + &warnings, + ) + .await?; + Ok(Some(run)) +} + /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes /// the runner claims when a job is queued. async fn create( diff --git a/crates/forge-web/src/ci/scheduled.rs b/crates/forge-web/src/ci/scheduled.rs new file mode 100644 index 0000000..31b4a5b --- /dev/null +++ b/crates/forge-web/src/ci/scheduled.rs @@ -0,0 +1,283 @@ +//! The CI scheduler: queues a `schedule` run for each repo whose `[on] schedule` matched since the +//! last check. It reads `.forge/ci.toml` from the head of the default branch, so a schedule +//! change takes effect without a push. +//! +//! A tick checks the window `(last_tick, now]` per repo. However many cron matches fall inside it, +//! one run is queued: a server that was down for a day catches up once, not once per missed +//! match. A repo seen for the first time starts from now. Archived repos are not looked at, and +//! nothing happens while CI is disabled on the instance. + +use std::time::Duration; + +use forge_ci::cron; +use forge_core::Repo; + +use super::schedule::{Loaded, default_head_config, scheduled_run}; +use crate::state::AppState; + +/// What a tick does for one repo. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + /// No schedule and nothing remembered. + Idle, + /// The schedule is gone: forget the repo, so a later schedule starts fresh. + Forget, + /// A match fell in the window: queue one run, then move the window. + Fire, + /// Nothing is due: move the window. + Advance, +} + +/// What to do for a repo with these `schedules`, last checked at `last` (Unix seconds), at `now`. +pub fn decide(schedules: &[String], last: Option, now: i64) -> Decision { + if schedules.is_empty() { + return if last.is_some() { + Decision::Forget + } else { + Decision::Idle + }; + } + match last { + Some(last) if cron::fired_between(schedules, last, now) => Decision::Fire, + _ => Decision::Advance, + } +} + +/// Seconds to sleep so the next tick lands just after the next minute starts. +pub fn nap_secs(now: i64) -> u64 { + u64::try_from(61 - now.rem_euclid(60)).unwrap_or(60) +} + +/// Starts the scheduler task. It runs until the process exits. +pub fn spawn(state: AppState) { + tokio::spawn(run(state)); +} + +async fn run(state: AppState) { + loop { + tick(&state, crate::raw::now_unix()).await; + tokio::time::sleep(Duration::from_secs(nap_secs(crate::raw::now_unix()))).await; + } +} + +/// One pass over every repo at `now` (Unix seconds). Returns how many runs it queued. +pub async fn tick(state: &AppState, now: i64) -> usize { + if !state.live().ci.enabled { + return 0; + } + let repos = match state.store.repos_for_ci_schedule().await { + Ok(repos) => repos, + Err(e) => { + tracing::error!(error = %e, "ci: listing repos for the scheduler failed"); + return 0; + } + }; + let mut queued = 0; + for repo in &repos { + match tick_repo(state, repo, now).await { + Ok(true) => queued += 1, + Ok(false) => {} + Err(e) => { + tracing::error!(error = %e, repo_id = %repo.id, "ci: scheduled run failed"); + } + } + } + queued +} + +async fn tick_repo(state: &AppState, repo: &Repo, now: i64) -> forge_core::Result { + let last = state.store.ci_schedule_last_tick(&repo.id).await?; + let head = default_head_config(state, repo).await; + let schedules = match &head { + Some((_, Loaded::Valid(cfg))) => cfg.on.schedule.clone(), + _ => Vec::new(), + }; + match decide(&schedules, last, now) { + Decision::Idle => Ok(false), + Decision::Forget => { + state.store.clear_ci_schedule(&repo.id).await?; + Ok(false) + } + Decision::Advance => { + state.store.set_ci_schedule_last_tick(&repo.id, now).await?; + Ok(false) + } + Decision::Fire => { + // A failure leaves the window where it was, so the next tick tries again. + let Some((commit, loaded)) = head else { + return Ok(false); + }; + let run = scheduled_run(state, repo, &commit, loaded).await?; + state.store.set_ci_schedule_last_tick(&repo.id, now).await?; + Ok(run.is_some()) + } + } +} + +#[cfg(test)] +mod tests { + use std::io::Write; + use std::path::Path; + + use forge_core::Visibility; + use forge_git::repo::{init_bare, repo_path}; + + use super::*; + use crate::test_support::test_state; + + // 2026-10-15 12:00:00 UTC. + const NOON: i64 = 1_791_979_200; + const DAILY_3: [&str; 1] = ["0 3 * * *"]; + + fn schedules(list: &[&str]) -> Vec { + list.iter().map(|s| (*s).to_owned()).collect() + } + + #[test] + fn a_repo_seen_first_starts_from_now() { + assert_eq!( + decide(&schedules(&DAILY_3), None, NOON), + Decision::Advance, + "no catch-up for a schedule nobody has seen" + ); + } + + #[test] + fn fires_once_when_a_tick_falls_in_the_window() { + let s = schedules(&DAILY_3); + // 03:00 the next day. + let fire_at = NOON + 15 * 3600; + assert_eq!(decide(&s, Some(NOON), fire_at - 1), Decision::Advance); + assert_eq!(decide(&s, Some(NOON), fire_at), Decision::Fire); + // Having moved the window to the fire time, the same tick does not fire again. + assert_eq!(decide(&s, Some(fire_at), fire_at + 60), Decision::Advance); + } + + #[test] + fn downtime_catches_up_at_most_once() { + let s = schedules(&["* * * * *"]); + // A week of missed minutes is one Fire, and the window then restarts at now. + let back = NOON + 7 * 86_400; + assert_eq!(decide(&s, Some(NOON), back), Decision::Fire); + assert_eq!(decide(&s, Some(back), back + 30), Decision::Advance); + assert_eq!(decide(&s, Some(back), back + 60), Decision::Fire); + } + + #[test] + fn a_removed_schedule_is_forgotten() { + assert_eq!(decide(&[], Some(NOON), NOON), Decision::Forget); + assert_eq!(decide(&[], None, NOON), Decision::Idle); + } + + #[test] + fn naps_land_just_after_the_minute() { + assert_eq!(nap_secs(NOON), 61); + assert_eq!(nap_secs(NOON + 59), 2); + assert_eq!(nap_secs(NOON + 1), 60); + } + + fn git(bare: &Path, args: &[&str], stdin: &str) -> String { + let mut child = std::process::Command::new("git") + .arg("--git-dir") + .arg(bare) + .args(args) + .env("GIT_AUTHOR_NAME", "tahinli") + .env("GIT_AUTHOR_EMAIL", "tahinli@example.com") + .env("GIT_COMMITTER_NAME", "tahinli") + .env("GIT_COMMITTER_EMAIL", "tahinli@example.com") + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn git"); + child + .stdin + .take() + .expect("stdin") + .write_all(stdin.as_bytes()) + .expect("write stdin"); + let out = child.wait_with_output().expect("git output"); + assert!(out.status.success(), "git {args:?}"); + String::from_utf8(out.stdout) + .expect("utf8") + .trim() + .to_owned() + } + + /// Commits `.forge/ci.toml` with `text` and points `main` at it. + fn commit_config(bare: &Path, text: &str) { + let blob = git(bare, &["hash-object", "-w", "--stdin"], text); + let forge = git(bare, &["mktree"], &format!("100644 blob {blob}\tci.toml\n")); + let root = git(bare, &["mktree"], &format!("040000 tree {forge}\t.forge\n")); + let commit = git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], ""); + git( + bare, + &["update-ref", "refs/heads/main", commit.as_str()], + "", + ); + } + + const WORKFLOW: &str = + "[on]\nschedule = [\"0 3 * * *\"]\n[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n"; + + #[tokio::test] + async fn ticks_queue_one_schedule_run_and_skip_archived_repos() { + let dir = tempfile::tempdir().expect("tempdir"); + let state = test_state(dir.path()).await; + let store = state.store.clone(); + let tahinli = store + .create_user("tahinli", None, "unused", false) + .await + .expect("user"); + let mut repos = Vec::new(); + for name in ["live", "old"] { + let repo = store + .create_repo(&tahinli.id, name, "", Visibility::Private, "main") + .await + .expect("repo"); + let bare = repo_path(&state.git.data_dir, &repo.id).expect("path"); + init_bare(&state.git, &bare, "main").await.expect("init"); + commit_config(&bare, WORKFLOW); + repos.push(repo); + } + store + .set_repo_archived(&repos[1].id, true) + .await + .expect("archive"); + + // First sight only records where the window starts. + assert_eq!(tick(&state, NOON).await, 0); + assert_eq!( + store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), + Some(NOON) + ); + assert_eq!( + store.ci_schedule_last_tick(&repos[1].id).await.unwrap(), + None, + "archived repos are skipped" + ); + // Before 03:00 nothing is due. + assert_eq!(tick(&state, NOON + 3600).await, 0); + // Three days of downtime later: one run, not three. + let later = NOON + 3 * 86_400; + assert_eq!(tick(&state, later).await, 1); + assert_eq!(tick(&state, later + 60).await, 0); + let (runs, total) = store.list_runs(&repos[0].id, 1, 25).await.unwrap(); + assert_eq!(total, 1); + assert_eq!(runs[0].trigger, "schedule"); + assert_eq!(runs[0].git_ref, "refs/heads/main"); + let (_, archived_total) = store.list_runs(&repos[1].id, 1, 25).await.unwrap(); + assert_eq!(archived_total, 0); + + // Dropping the schedule forgets the repo. + commit_config( + &repo_path(&state.git.data_dir, &repos[0].id).unwrap(), + "[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n", + ); + assert_eq!(tick(&state, later + 120).await, 0); + assert_eq!( + store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), + None + ); + } +} diff --git a/crates/forge-web/src/i18n/mod.rs b/crates/forge-web/src/i18n/mod.rs index 725bd0d..cf437fa 100644 --- a/crates/forge-web/src/i18n/mod.rs +++ b/crates/forge-web/src/i18n/mod.rs @@ -19,8 +19,8 @@ use forge_core::User; pub mod accents; pub mod admin; -pub mod browse; pub mod authoring; +pub mod browse; pub mod code; pub mod community; pub mod integrations; diff --git a/crates/forge-web/src/i18n/releases_ci.rs b/crates/forge-web/src/i18n/releases_ci.rs index cfc92fa..079066f 100644 --- a/crates/forge-web/src/i18n/releases_ci.rs +++ b/crates/forge-web/src/i18n/releases_ci.rs @@ -45,6 +45,8 @@ pub enum K { Runs, NoRunsYet, NoRunsHint, + TriggerScheduled, + NextScheduledRun, NoJobs, Newer, Older, @@ -231,6 +233,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { (NoRunsHint, Tr) => { ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." } + (TriggerScheduled, En) => "scheduled", + (TriggerScheduled, Tr) => "zamanlanmış", + (NextScheduledRun, En) => "Next scheduled run", + (NextScheduledRun, Tr) => "Sonraki zamanlanmış çalıştırma", (NoJobs, En) => "No jobs.", (NoJobs, Tr) => "İş yok.", (Newer, En) => "Newer", @@ -565,6 +571,8 @@ mod tests { K::Runs, K::NoRunsYet, K::NoRunsHint, + K::TriggerScheduled, + K::NextScheduledRun, K::NoJobs, K::Newer, K::Older, diff --git a/crates/forge-web/src/pages/ci_runs.rs b/crates/forge-web/src/pages/ci_runs.rs index cdfefc6..96c8b24 100644 --- a/crates/forge-web/src/pages/ci_runs.rs +++ b/crates/forge-web/src/pages/ci_runs.rs @@ -298,6 +298,36 @@ pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob Ok(()) } +/// A job name as the timeline's label column can hold it: a matrix combination shows its values +/// without the base name (the job list below groups them), and a long name is cut with an ellipsis. +fn gantt_name(name: &str) -> String { + const MAX_CHARS: usize = 14; + let shown = name + .split_once(" (") + .map_or(name, |(_, rest)| rest.trim_end_matches(')')); + if shown.chars().count() <= MAX_CHARS { + return shown.to_owned(); + } + let head: String = shown.chars().take(MAX_CHARS - 1).collect(); + format!("{head}\u{2026}") +} + +/// How the run header names what started it. Scheduled runs read "scheduled"; the rest keep the +/// stored word. +fn trigger_text(lang: Lang, trigger: &str) -> String { + match trigger { + "schedule" => g::t(lang, K::TriggerScheduled).to_owned(), + other => other.to_owned(), + } +} + +/// The next scheduled run as `2026-10-21 03:00 UTC`. +fn next_run_text(at: i64) -> Option { + let when = time::OffsetDateTime::from_unix_timestamp(at).ok()?; + let format = time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]"); + Some(format!("{} UTC", when.format(&format).ok()?)) +} + /// One run in the list. `bar` is its duration bar on the page's shared scale. struct RunRow { href: String, @@ -336,10 +366,18 @@ struct ListView { newer_href: Option, older_href: Option, page_label: String, + /// The next `[on] schedule` match of the default branch's workflow, as text. + next_scheduled: Option, } /// One job line under the timeline. Its link goes to the job page. struct JobLine { + /// A heading drawn above this line: the base name of a matrix job, on its first combination. + group: Option, + /// The matrix job this line belongs to, to tell when a new group starts. + group_of: Option, + /// The line is one combination of a matrix job, drawn under its heading. + sub: bool, href: String, name: String, dot: String, @@ -833,7 +871,7 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option, now: i64, lang: Lan x: "0".to_owned(), y: (row_mid(i) - 3).to_string(), anchor: "start", - text: job.name.clone(), + text: gantt_name(&job.name), ..Default::default() }); if let Some(sub) = row_sub(job, lang) { @@ -1281,7 +1319,11 @@ async fn runs_split(cx: &Cx, number: Option<&str>) -> Result { .iter() .zip(&timings) .map(|(run, jobs)| { - let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); + let actor = if run.trigger == "schedule" { + String::new() + } else { + names.get(&run.actor_id).cloned().unwrap_or_default() + }; RunRow { href: row_href(run.number), current: if selected.as_ref().is_some_and(|sel| sel.id == run.id) { @@ -1338,7 +1380,11 @@ async fn runs_split(cx: &Cx, number: Option<&str>) -> Result { }; let detail = match selected.as_ref() { Some(run) => { - let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); + let actor = if run.trigger == "schedule" { + String::new() + } else { + names.get(&run.actor_id).cloned().unwrap_or_default() + }; let subject = subjects .get(&run.commit_oid) .cloned() @@ -1374,6 +1420,10 @@ async fn runs_split(cx: &Cx, number: Option<&str>) -> Result { newer_href, older_href, page_label: g::page_label(lang, page), + next_scheduled: { + let schedules = crate::ci::schedule::schedules_of(state, &ctx.repo).await; + forge_ci::cron::next_after(&schedules, now).and_then(next_run_text) + }, }; let live = (page == 1).then(|| format!("{base}/events")); let notice = notice_from_query(cx, lang); @@ -1443,13 +1493,24 @@ async fn run_detail( None if job.state == JobState::Queued => state_text(lang, job.state.as_str()), None => String::new(), }; + let (base, variant) = match job.name.split_once(" (") { + Some((base, rest)) => (base, Some(rest.trim_end_matches(')'))), + None => (job.name.as_str(), None), + }; + let first = variant.is_some() + && lines + .last() + .is_none_or(|prev: &JobLine| prev.group_of.as_deref() != Some(base)); lines.push(JobLine { id: job.id.clone(), expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()), preview, tail: tail.join("\n"), + group: first.then(|| base.to_owned()), + group_of: variant.map(|_| base.to_owned()), + sub: variant.is_some(), href: job_href(title, &job.id), - name: job.name.clone(), + name: variant.unwrap_or(job.name.as_str()).to_owned(), dot: format!("ci-dot ci-{}", job.state.as_str()), detail: job.image.clone(), rerun: (writer && job.state.is_terminal()) @@ -1477,7 +1538,7 @@ async fn run_detail( title: header.title, state: state_text(lang, run.state.as_str()), state_class: format!("ci-state ci-{}", run.state.as_str()), - trigger: run.trigger.clone(), + trigger: trigger_text(lang, &run.trigger), branch: short_ref(&run.git_ref).to_owned(), commit_href: format!("/{title}/commit/{}", run.commit_oid), commit: short_oid(&run.commit_oid).to_owned(), @@ -1525,6 +1586,7 @@ async fn runs_body( newer_href, older_href, page_label, + next_scheduled, } = list; let (fm, fs) = duration_templates(lang); Ok(view! { @@ -1581,6 +1643,9 @@ async fn runs_body( + if let Some(next) = next_scheduled.as_ref() { +

(g::t(lang, K::NextScheduledRun)) ": "

+ } if rows.is_empty() {

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

@@ -1707,7 +1772,10 @@ async fn runs_body( }