Scheduler loop, scheduled trigger, next-run hint, grouped matrix jobs, docs
Browse files at this commit1277e9940c7e560af63c668a53372e781a127990Parent: e674439- feat
- scheduler loop, scheduled trigger, next-run hint, grouped matrix jobs, docs
20 changed files +1183 -21
- Cargo.lock +16 -0
- crates/forge-ci/Cargo.toml +2 -0
- crates/forge-ci/src/config.rs +482 -9
- crates/forge-ci/src/cron.rs +81 -0
- crates/forge-ci/src/error.rs +16 -1
- crates/forge-ci/src/lib.rs +1 -0
- crates/forge-core/migrations/0055_attachments.sql → crates/forge-core/migrations/0052_attachments.sql +0 -0
- crates/forge-core/migrations/0056_review_requests.sql → crates/forge-core/migrations/0053_review_requests.sql +0 -0
- crates/forge-core/migrations/0054_ci_schedule_state.sql +9 -0
- crates/forge-core/src/store/ci.rs +54 -0
- crates/forge-core/src/store/migrate.rs +7 -3
- crates/forge-web/src/boot.rs +1 -0
- crates/forge-web/src/ci/mod.rs +1 -0
- crates/forge-web/src/ci/schedule.rs +63 -1
- crates/forge-web/src/ci/scheduled.rs +283 -0
- crates/forge-web/src/i18n/mod.rs +1 -1
- crates/forge-web/src/i18n/releases_ci.rs +8 -0
- crates/forge-web/src/pages/ci_runs.rs +74 -6
- docs/ci.md +65 -0
- style/main.scss +19 -0
Cargo.lockmodified+16 -0
| @@ -1039,6 +1039,17 @@ dependencies = [ | |||
| 1039 | "cfg-if", | 1039 | "cfg-if", |
| 1040 | ] | 1040 | ] |
| 1041 | 1041 | ||
| 1042 | +[[package]] | ||
| 1043 | +name = "croner" | ||
| 1044 | +version = "4.0.1" | ||
| 1045 | +source = "registry+https://github.com/rust-lang/crates.io-index" | ||
| 1046 | +checksum = "4b5b023fc2978536bbb2a3b71237964fc4630bec1eb31077b4977127f4cdb9c0" | ||
| 1047 | +dependencies = [ | ||
| 1048 | + "chrono", | ||
| 1049 | + "derive_builder", | ||
| 1050 | + "strum 0.27.2", | ||
| 1051 | +] | ||
| 1052 | + | ||
| 1042 | [[package]] | 1053 | [[package]] |
| 1043 | name = "crossbeam-channel" | 1054 | name = "crossbeam-channel" |
| 1044 | version = "0.5.17" | 1055 | version = "0.5.17" |
| @@ -1850,6 +1861,8 @@ name = "forge-ci" | |||
| 1850 | version = "0.1.0" | 1861 | version = "0.1.0" |
| 1851 | dependencies = [ | 1862 | dependencies = [ |
| 1852 | "base64 0.23.1", | 1863 | "base64 0.23.1", |
| 1864 | + "chrono", | ||
| 1865 | + "croner", | ||
| 1853 | "globset", | 1866 | "globset", |
| 1854 | "serde", | 1867 | "serde", |
| 1855 | "serde_ignored", | 1868 | "serde_ignored", |
| @@ -6677,6 +6690,9 @@ name = "strum" | |||
| 6677 | version = "0.27.2" | 6690 | version = "0.27.2" |
| 6678 | source = "registry+https://github.com/rust-lang/crates.io-index" | 6691 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 6679 | checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" | 6692 | checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf" |
| 6693 | +dependencies = [ | ||
| 6694 | + "strum_macros 0.27.2", | ||
| 6695 | +] | ||
| 6680 | 6696 | ||
| 6681 | [[package]] | 6697 | [[package]] |
| 6682 | name = "strum_macros" | 6698 | name = "strum_macros" |
crates/forge-ci/Cargo.tomlmodified+2 -0
| @@ -8,6 +8,8 @@ publish = false | |||
| 8 | 8 | ||
| 9 | [dependencies] | 9 | [dependencies] |
| 10 | base64 = { workspace = true } | 10 | base64 = { workspace = true } |
| 11 | +chrono = { version = "0.4.45", default-features = false } | ||
| 12 | +croner = "4.0.1" | ||
| 11 | globset = { workspace = true } | 13 | globset = { workspace = true } |
| 12 | serde = { workspace = true } | 14 | serde = { workspace = true } |
| 13 | serde_ignored = "0.1.14" | 15 | serde_ignored = "0.1.14" |
crates/forge-ci/src/config.rsmodified+482 -9
| @@ -38,6 +38,11 @@ pub const MAX_RELEASE_ASSETS: usize = 32; | |||
| 38 | /// Longest `[release] title` template, in characters, after trimming. | 38 | /// Longest `[release] title` template, in characters, after trimming. |
| 39 | pub const MAX_RELEASE_TITLE_CHARS: usize = 200; | 39 | pub const MAX_RELEASE_TITLE_CHARS: usize = 200; |
| 40 | 40 | ||
| 41 | +/// Most `[on] schedule` entries. | ||
| 42 | +pub const MAX_SCHEDULES: usize = 8; | ||
| 43 | +/// Longest matrix axis value, in characters. | ||
| 44 | +pub const MAX_MATRIX_VALUE_CHARS: usize = 64; | ||
| 45 | + | ||
| 41 | /// A parsed and validated workflow. | 46 | /// A parsed and validated workflow. |
| 42 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] | 47 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 43 | pub struct CiConfig { | 48 | pub struct CiConfig { |
| @@ -148,6 +153,9 @@ pub struct Triggers { | |||
| 148 | /// Defaults to `false`. When set, a push to a branch cancels the queued and running runs of | 153 | /// Defaults to `false`. When set, a push to a branch cancels the queued and running runs of |
| 149 | /// older commits on that branch. | 154 | /// older commits on that branch. |
| 150 | pub cancel_superseded: bool, | 155 | pub cancel_superseded: bool, |
| 156 | + /// 5-field cron expressions in UTC, e.g. `"0 3 * * *"`. The server queues a run of the default | ||
| 157 | + /// branch head at each match. | ||
| 158 | + pub schedule: Vec<String>, | ||
| 151 | } | 159 | } |
| 152 | 160 | ||
| 153 | impl Default for Triggers { | 161 | impl Default for Triggers { |
| @@ -158,6 +166,7 @@ impl Default for Triggers { | |||
| 158 | pull_request: false, | 166 | pull_request: false, |
| 159 | manual: true, | 167 | manual: true, |
| 160 | cancel_superseded: false, | 168 | cancel_superseded: false, |
| 169 | + schedule: Vec::new(), | ||
| 161 | } | 170 | } |
| 162 | } | 171 | } |
| 163 | } | 172 | } |
| @@ -187,6 +196,51 @@ pub struct JobSpec { | |||
| 187 | pub timeout_minutes: u32, | 196 | pub timeout_minutes: u32, |
| 188 | #[serde(default = "default_network")] | 197 | #[serde(default = "default_network")] |
| 189 | pub network: bool, | 198 | pub network: bool, |
| 199 | + /// The `matrix` table. Only present before expansion: [`parse_config`] replaces a matrix job | ||
| 200 | + /// with one job per combination, and those have no matrix. | ||
| 201 | + #[serde(default, skip_serializing_if = "Option::is_none")] | ||
| 202 | + pub matrix: Option<MatrixSpec>, | ||
| 203 | +} | ||
| 204 | + | ||
| 205 | +/// A matrix axis value. TOML strings, integers and booleans are all read as text. | ||
| 206 | +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] | ||
| 207 | +pub struct MatrixValue(pub String); | ||
| 208 | + | ||
| 209 | +impl Serialize for MatrixValue { | ||
| 210 | + fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { | ||
| 211 | + serializer.serialize_str(&self.0) | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +impl<'de> Deserialize<'de> for MatrixValue { | ||
| 216 | + fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { | ||
| 217 | + #[derive(Deserialize)] | ||
| 218 | + #[serde(untagged)] | ||
| 219 | + enum Raw { | ||
| 220 | + Text(String), | ||
| 221 | + Int(i64), | ||
| 222 | + Flag(bool), | ||
| 223 | + } | ||
| 224 | + Ok(MatrixValue(match Raw::deserialize(deserializer)? { | ||
| 225 | + Raw::Text(text) => text, | ||
| 226 | + Raw::Int(n) => n.to_string(), | ||
| 227 | + Raw::Flag(b) => b.to_string(), | ||
| 228 | + })) | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +/// A job's `matrix` table: every key but `exclude` and `include` is an axis with its values. | ||
| 233 | +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] | ||
| 234 | +pub struct MatrixSpec { | ||
| 235 | + /// Combinations to drop. An entry matches a combination that agrees on every key it names. | ||
| 236 | + #[serde(default)] | ||
| 237 | + pub exclude: Vec<BTreeMap<String, MatrixValue>>, | ||
| 238 | + /// Extra combinations. Each names a value for every axis, and may add more keys, which are | ||
| 239 | + /// exposed like the axes but are not part of the job name. | ||
| 240 | + #[serde(default)] | ||
| 241 | + pub include: Vec<BTreeMap<String, MatrixValue>>, | ||
| 242 | + #[serde(flatten)] | ||
| 243 | + pub axes: BTreeMap<String, Vec<MatrixValue>>, | ||
| 190 | } | 244 | } |
| 191 | 245 | ||
| 192 | fn default_timeout_minutes() -> u32 { | 246 | fn default_timeout_minutes() -> u32 { |
| @@ -200,10 +254,16 @@ fn default_network() -> bool { | |||
| 200 | /// Something that can start a workflow run. | 254 | /// Something that can start a workflow run. |
| 201 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 255 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 202 | pub enum Event<'a> { | 256 | pub enum Event<'a> { |
| 203 | - Push { branch: &'a str }, | 257 | + Push { |
| 204 | - Tag { tag: &'a str }, | 258 | + branch: &'a str, |
| 259 | + }, | ||
| 260 | + Tag { | ||
| 261 | + tag: &'a str, | ||
| 262 | + }, | ||
| 205 | PullRequest, | 263 | PullRequest, |
| 206 | Manual, | 264 | Manual, |
| 265 | + /// A `[on] schedule` tick. | ||
| 266 | + Schedule, | ||
| 207 | } | 267 | } |
| 208 | 268 | ||
| 209 | /// Parses and validates a `ci.toml` document. | 269 | /// Parses and validates a `ci.toml` document. |
| @@ -224,6 +284,7 @@ pub fn parse_config(text: &str) -> Result<CiConfig, ConfigError> { | |||
| 224 | )); | 284 | )); |
| 225 | }) | 285 | }) |
| 226 | .map_err(|e| ConfigError::Toml(e.to_string()))?; | 286 | .map_err(|e| ConfigError::Toml(e.to_string()))?; |
| 287 | + config.expand_matrices()?; | ||
| 227 | config.validate()?; | 288 | config.validate()?; |
| 228 | config.warnings = warnings; | 289 | config.warnings = warnings; |
| 229 | Ok(config) | 290 | Ok(config) |
| @@ -237,6 +298,7 @@ impl CiConfig { | |||
| 237 | Event::Tag { tag } => matches_any(&self.on.tags, tag), | 298 | Event::Tag { tag } => matches_any(&self.on.tags, tag), |
| 238 | Event::PullRequest => self.on.pull_request, | 299 | Event::PullRequest => self.on.pull_request, |
| 239 | Event::Manual => self.on.manual, | 300 | Event::Manual => self.on.manual, |
| 301 | + Event::Schedule => !self.on.schedule.is_empty(), | ||
| 240 | } | 302 | } |
| 241 | } | 303 | } |
| 242 | 304 | ||
| @@ -274,6 +336,57 @@ impl CiConfig { | |||
| 274 | order | 336 | order |
| 275 | } | 337 | } |
| 276 | 338 | ||
| 339 | + /// Checks every job key, then replaces each matrix job with one job per combination, named | ||
| 340 | + /// `base (v1, v2)` with the axis values in axis-name order. Expanded jobs get `MATRIX_<KEY>` | ||
| 341 | + /// env entries and `${{ matrix.key }}` (or `${matrix.key}`) filled in `image`, `runs_on` and | ||
| 342 | + /// `run`. A `needs` on a matrix job becomes a `needs` on all its combinations. | ||
| 343 | + fn expand_matrices(&mut self) -> Result<(), ConfigError> { | ||
| 344 | + for name in self.jobs.keys() { | ||
| 345 | + if !is_job_name(name) { | ||
| 346 | + return Err(ConfigError::InvalidJobName(name.clone())); | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + let mut groups: BTreeMap<String, Vec<String>> = BTreeMap::new(); | ||
| 350 | + let mut expanded: BTreeMap<String, JobSpec> = BTreeMap::new(); | ||
| 351 | + for (name, mut job) in std::mem::take(&mut self.jobs) { | ||
| 352 | + let Some(matrix) = job.matrix.take() else { | ||
| 353 | + expanded.insert(name, job); | ||
| 354 | + continue; | ||
| 355 | + }; | ||
| 356 | + let mut names = Vec::new(); | ||
| 357 | + for (suffix, vars) in combinations(&name, &matrix)? { | ||
| 358 | + let mut copy = job.clone(); | ||
| 359 | + copy.image = interpolate(&name, ©.image, &vars)?; | ||
| 360 | + copy.run = interpolate(&name, ©.run, &vars)?; | ||
| 361 | + for label in &mut copy.runs_on { | ||
| 362 | + *label = interpolate(&name, label, &vars)?; | ||
| 363 | + } | ||
| 364 | + for (key, value) in &vars { | ||
| 365 | + copy.env.insert( | ||
| 366 | + format!("MATRIX_{}", key.to_ascii_uppercase()), | ||
| 367 | + value.clone(), | ||
| 368 | + ); | ||
| 369 | + } | ||
| 370 | + let full = format!("{name} ({suffix})"); | ||
| 371 | + names.push(full.clone()); | ||
| 372 | + expanded.insert(full, copy); | ||
| 373 | + } | ||
| 374 | + groups.insert(name, names); | ||
| 375 | + } | ||
| 376 | + for job in expanded.values_mut() { | ||
| 377 | + job.needs = job | ||
| 378 | + .needs | ||
| 379 | + .iter() | ||
| 380 | + .flat_map(|need| match groups.get(need) { | ||
| 381 | + Some(all) => all.clone(), | ||
| 382 | + None => vec![need.clone()], | ||
| 383 | + }) | ||
| 384 | + .collect(); | ||
| 385 | + } | ||
| 386 | + self.jobs = expanded; | ||
| 387 | + Ok(()) | ||
| 388 | + } | ||
| 389 | + | ||
| 277 | fn validate(&self) -> Result<(), ConfigError> { | 390 | fn validate(&self) -> Result<(), ConfigError> { |
| 278 | if let Some(name) = &self.name { | 391 | if let Some(name) = &self.name { |
| 279 | validate_workflow_name(name)?; | 392 | validate_workflow_name(name)?; |
| @@ -293,6 +406,18 @@ impl CiConfig { | |||
| 293 | for pattern in &self.on.tags { | 406 | for pattern in &self.on.tags { |
| 294 | validate_trigger_glob("tag", pattern)?; | 407 | validate_trigger_glob("tag", pattern)?; |
| 295 | } | 408 | } |
| 409 | + if self.on.schedule.len() > MAX_SCHEDULES { | ||
| 410 | + return Err(ConfigError::InvalidSchedule { | ||
| 411 | + expr: String::new(), | ||
| 412 | + reason: format!("at most {MAX_SCHEDULES} schedules are allowed"), | ||
| 413 | + }); | ||
| 414 | + } | ||
| 415 | + for expr in &self.on.schedule { | ||
| 416 | + crate::cron::parse(expr).map_err(|reason| ConfigError::InvalidSchedule { | ||
| 417 | + expr: expr.clone(), | ||
| 418 | + reason, | ||
| 419 | + })?; | ||
| 420 | + } | ||
| 296 | for (name, job) in &self.jobs { | 421 | for (name, job) in &self.jobs { |
| 297 | validate_job(name, job, &self.jobs)?; | 422 | validate_job(name, job, &self.jobs)?; |
| 298 | } | 423 | } |
| @@ -333,7 +458,7 @@ impl ReleaseSpec { | |||
| 333 | pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { | 458 | pub fn asset_matches(&self, job: &str, artifact_name: &str) -> bool { |
| 334 | self.assets.iter().any(|asset| { | 459 | self.assets.iter().any(|asset| { |
| 335 | asset_selector(asset).is_some_and(|(selected_job, glob)| { | 460 | asset_selector(asset).is_some_and(|(selected_job, glob)| { |
| 336 | - selected_job == job && matches_any(&[glob.to_string()], artifact_name) | 461 | + names_job(selected_job, job) && matches_any(&[glob.to_string()], artifact_name) |
| 337 | }) | 462 | }) |
| 338 | }) | 463 | }) |
| 339 | } | 464 | } |
| @@ -542,7 +667,7 @@ fn validate_release_asset( | |||
| 542 | let Some((job, glob)) = asset_selector(asset) else { | 667 | let Some((job, glob)) = asset_selector(asset) else { |
| 543 | return Err(invalid("must be \"job:glob\"".into())); | 668 | return Err(invalid("must be \"job:glob\"".into())); |
| 544 | }; | 669 | }; |
| 545 | - let Some(spec) = jobs.get(job) else { | 670 | + let Some((_, spec)) = jobs.iter().find(|(name, _)| names_job(job, name)) else { |
| 546 | return Err(invalid(format!("job {job:?} is not defined"))); | 671 | return Err(invalid(format!("job {job:?} is not defined"))); |
| 547 | }; | 672 | }; |
| 548 | if spec.artifacts.is_empty() { | 673 | if spec.artifacts.is_empty() { |
| @@ -579,14 +704,203 @@ fn validate_release_title(title: &str) -> Result<(), ConfigError> { | |||
| 579 | Ok(()) | 704 | Ok(()) |
| 580 | } | 705 | } |
| 581 | 706 | ||
| 707 | +/// The job name without its matrix suffix: `test (stable, x86_64)` gives `test`. | ||
| 708 | +pub fn base_job_name(name: &str) -> &str { | ||
| 709 | + name.split_once(" (").map_or(name, |(base, _)| base) | ||
| 710 | +} | ||
| 711 | + | ||
| 712 | +/// Whether `selected` (a job name from the config) names `job`: the job itself, or any | ||
| 713 | +/// combination of the matrix job `selected`. | ||
| 714 | +fn names_job(selected: &str, job: &str) -> bool { | ||
| 715 | + selected == job | ||
| 716 | + || job | ||
| 717 | + .strip_prefix(selected) | ||
| 718 | + .is_some_and(|rest| rest.starts_with(" (")) | ||
| 719 | +} | ||
| 720 | + | ||
| 721 | +fn is_matrix_key(key: &str) -> bool { | ||
| 722 | + let Some((first, rest)) = key.as_bytes().split_first() else { | ||
| 723 | + return false; | ||
| 724 | + }; | ||
| 725 | + rest.len() <= 31 | ||
| 726 | + && first.is_ascii_lowercase() | ||
| 727 | + && rest | ||
| 728 | + .iter() | ||
| 729 | + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_') | ||
| 730 | +} | ||
| 731 | + | ||
| 732 | +/// One matrix combination: the job name suffix and its variables. | ||
| 733 | +type Combination = (String, BTreeMap<String, String>); | ||
| 734 | + | ||
| 735 | +/// The combinations of a matrix as `(name suffix, variables)`, in a stable order. | ||
| 736 | +fn combinations(job: &str, matrix: &MatrixSpec) -> Result<Vec<Combination>, ConfigError> { | ||
| 737 | + let bad = |reason: String| ConfigError::InvalidMatrix { | ||
| 738 | + job: job.to_string(), | ||
| 739 | + reason, | ||
| 740 | + }; | ||
| 741 | + if matrix.axes.is_empty() { | ||
| 742 | + return Err(bad( | ||
| 743 | + "needs at least one axis, e.g. rust = [\"stable\"]".into() | ||
| 744 | + )); | ||
| 745 | + } | ||
| 746 | + let mut total: usize = 1; | ||
| 747 | + for (key, values) in &matrix.axes { | ||
| 748 | + if !is_matrix_key(key) { | ||
| 749 | + return Err(bad(format!( | ||
| 750 | + "axis name {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" | ||
| 751 | + ))); | ||
| 752 | + } | ||
| 753 | + if values.is_empty() { | ||
| 754 | + return Err(bad(format!("axis {key:?} has no values"))); | ||
| 755 | + } | ||
| 756 | + for (i, value) in values.iter().enumerate() { | ||
| 757 | + validate_matrix_value(&value.0).map_err(|r| bad(format!("axis {key:?}: {r}")))?; | ||
| 758 | + if values[..i].contains(value) { | ||
| 759 | + return Err(bad(format!("axis {key:?} lists {:?} twice", value.0))); | ||
| 760 | + } | ||
| 761 | + } | ||
| 762 | + total = total.saturating_mul(values.len()); | ||
| 763 | + if total > MAX_JOBS { | ||
| 764 | + return Err(ConfigError::MatrixTooLarge { | ||
| 765 | + job: job.to_string(), | ||
| 766 | + count: total, | ||
| 767 | + max: MAX_JOBS, | ||
| 768 | + }); | ||
| 769 | + } | ||
| 770 | + } | ||
| 771 | + let mut combos: Vec<BTreeMap<String, String>> = vec![BTreeMap::new()]; | ||
| 772 | + for (key, values) in &matrix.axes { | ||
| 773 | + combos = combos | ||
| 774 | + .into_iter() | ||
| 775 | + .flat_map(|base| { | ||
| 776 | + values.iter().map(move |value| { | ||
| 777 | + let mut next = base.clone(); | ||
| 778 | + next.insert(key.clone(), value.0.clone()); | ||
| 779 | + next | ||
| 780 | + }) | ||
| 781 | + }) | ||
| 782 | + .collect(); | ||
| 783 | + } | ||
| 784 | + for entry in &matrix.exclude { | ||
| 785 | + for key in entry.keys() { | ||
| 786 | + if !matrix.axes.contains_key(key) { | ||
| 787 | + return Err(bad(format!("exclude names {key:?}, which is not an axis"))); | ||
| 788 | + } | ||
| 789 | + } | ||
| 790 | + combos.retain(|combo| !entry.iter().all(|(k, v)| combo.get(k) == Some(&v.0))); | ||
| 791 | + } | ||
| 792 | + for entry in &matrix.include { | ||
| 793 | + let mut combo = BTreeMap::new(); | ||
| 794 | + for (key, value) in entry { | ||
| 795 | + if !is_matrix_key(key) { | ||
| 796 | + return Err(bad(format!( | ||
| 797 | + "include key {key:?} must match ^[a-z][a-z0-9_]{{0,31}}$" | ||
| 798 | + ))); | ||
| 799 | + } | ||
| 800 | + validate_matrix_value(&value.0).map_err(|r| bad(format!("include {key:?}: {r}")))?; | ||
| 801 | + combo.insert(key.clone(), value.0.clone()); | ||
| 802 | + } | ||
| 803 | + if let Some(missing) = matrix.axes.keys().find(|k| !combo.contains_key(*k)) { | ||
| 804 | + return Err(bad(format!("an include entry must set axis {missing:?}"))); | ||
| 805 | + } | ||
| 806 | + let same_axes = |other: &BTreeMap<String, String>| { | ||
| 807 | + matrix.axes.keys().all(|k| other.get(k) == combo.get(k)) | ||
| 808 | + }; | ||
| 809 | + if !combos.iter().any(same_axes) { | ||
| 810 | + combos.push(combo); | ||
| 811 | + } | ||
| 812 | + } | ||
| 813 | + if combos.is_empty() { | ||
| 814 | + return Err(bad("exclude removes every combination".into())); | ||
| 815 | + } | ||
| 816 | + if combos.len() > MAX_JOBS { | ||
| 817 | + return Err(ConfigError::MatrixTooLarge { | ||
| 818 | + job: job.to_string(), | ||
| 819 | + count: combos.len(), | ||
| 820 | + max: MAX_JOBS, | ||
| 821 | + }); | ||
| 822 | + } | ||
| 823 | + Ok(combos | ||
| 824 | + .into_iter() | ||
| 825 | + .map(|combo| { | ||
| 826 | + let suffix = matrix | ||
| 827 | + .axes | ||
| 828 | + .keys() | ||
| 829 | + .filter_map(|k| combo.get(k).map(String::as_str)) | ||
| 830 | + .collect::<Vec<_>>() | ||
| 831 | + .join(", "); | ||
| 832 | + (suffix, combo) | ||
| 833 | + }) | ||
| 834 | + .collect()) | ||
| 835 | +} | ||
| 836 | + | ||
| 837 | +/// A matrix value: non-empty, at most [`MAX_MATRIX_VALUE_CHARS`] characters, no control | ||
| 838 | +/// characters, and none of `,`, `(` and `)`, which would make job names ambiguous. | ||
| 839 | +fn validate_matrix_value(value: &str) -> Result<(), String> { | ||
| 840 | + if value.is_empty() { | ||
| 841 | + return Err("values must not be empty".into()); | ||
| 842 | + } | ||
| 843 | + if value.chars().count() > MAX_MATRIX_VALUE_CHARS { | ||
| 844 | + return Err(format!( | ||
| 845 | + "values must be at most {MAX_MATRIX_VALUE_CHARS} characters" | ||
| 846 | + )); | ||
| 847 | + } | ||
| 848 | + if value | ||
| 849 | + .chars() | ||
| 850 | + .any(|c| c.is_control() || matches!(c, ',' | '(' | ')')) | ||
| 851 | + { | ||
| 852 | + return Err(format!( | ||
| 853 | + "{value:?} must not contain control characters, commas or parentheses" | ||
| 854 | + )); | ||
| 855 | + } | ||
| 856 | + Ok(()) | ||
| 857 | +} | ||
| 858 | + | ||
| 859 | +/// Replaces `${{ matrix.key }}` and `${matrix.key}` in `text`. A key that is not in `vars` is an | ||
| 860 | +/// error, so a typo fails at parse time instead of reaching the shell. Anything else that starts | ||
| 861 | +/// with `${` is left alone. | ||
| 862 | +fn interpolate( | ||
| 863 | + job: &str, | ||
| 864 | + text: &str, | ||
| 865 | + vars: &BTreeMap<String, String>, | ||
| 866 | +) -> Result<String, ConfigError> { | ||
| 867 | + let mut out = String::with_capacity(text.len()); | ||
| 868 | + let mut rest = text; | ||
| 869 | + while let Some(at) = rest.find("${") { | ||
| 870 | + out.push_str(&rest[..at]); | ||
| 871 | + let after = &rest[at + 2..]; | ||
| 872 | + let found = if let Some(body) = after.strip_prefix('{') { | ||
| 873 | + body.find("}}") | ||
| 874 | + .map(|end| (body[..end].trim(), &body[end + 2..])) | ||
| 875 | + } else { | ||
| 876 | + after | ||
| 877 | + .find('}') | ||
| 878 | + .map(|end| (after[..end].trim(), &after[end + 1..])) | ||
| 879 | + }; | ||
| 880 | + match found.and_then(|(inner, tail)| Some((inner.strip_prefix("matrix.")?, tail))) { | ||
| 881 | + Some((key, tail)) => { | ||
| 882 | + let value = vars.get(key).ok_or_else(|| ConfigError::InvalidMatrix { | ||
| 883 | + job: job.to_string(), | ||
| 884 | + reason: format!("`matrix.{key}` is not an axis or include key"), | ||
| 885 | + })?; | ||
| 886 | + out.push_str(value); | ||
| 887 | + rest = tail; | ||
| 888 | + } | ||
| 889 | + None => { | ||
| 890 | + out.push_str("${"); | ||
| 891 | + rest = after; | ||
| 892 | + } | ||
| 893 | + } | ||
| 894 | + } | ||
| 895 | + out.push_str(rest); | ||
| 896 | + Ok(out) | ||
| 897 | +} | ||
| 898 | + | ||
| 582 | fn validate_job( | 899 | fn validate_job( |
| 583 | name: &str, | 900 | name: &str, |
| 584 | job: &JobSpec, | 901 | job: &JobSpec, |
| 585 | all: &BTreeMap<String, JobSpec>, | 902 | all: &BTreeMap<String, JobSpec>, |
| 586 | ) -> Result<(), ConfigError> { | 903 | ) -> Result<(), ConfigError> { |
| 587 | - if !is_job_name(name) { | ||
| 588 | - return Err(ConfigError::InvalidJobName(name.to_string())); | ||
| 589 | - } | ||
| 590 | if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { | 904 | if job.image.is_empty() || job.image.chars().any(char::is_whitespace) { |
| 591 | return Err(ConfigError::InvalidImage { | 905 | return Err(ConfigError::InvalidImage { |
| 592 | job: name.to_string(), | 906 | job: name.to_string(), |
| @@ -722,9 +1036,9 @@ artifacts = ["target/release/forge"] | |||
| 722 | 1036 | ||
| 723 | #[test] | 1037 | #[test] |
| 724 | fn unknown_keys_are_ignored_with_a_warning() { | 1038 | fn unknown_keys_are_ignored_with_a_warning() { |
| 725 | - let cfg = parse_config(&format!("[on]\nschedule = true\n{}", job_toml(""))).unwrap(); | 1039 | + let cfg = parse_config(&format!("[on]\nwebhook = true\n{}", job_toml(""))).unwrap(); |
| 726 | assert_eq!(cfg.warnings.len(), 1); | 1040 | assert_eq!(cfg.warnings.len(), 1); |
| 727 | - assert!(cfg.warnings[0].starts_with("unknown key `on.schedule` ignored")); | 1041 | + assert!(cfg.warnings[0].starts_with("unknown key `on.webhook` ignored")); |
| 728 | assert!(cfg.on.manual, "known keys still apply"); | 1042 | assert!(cfg.on.manual, "known keys still apply"); |
| 729 | 1043 | ||
| 730 | let cfg = parse_config(&job_toml("bogus = 1")).unwrap(); | 1044 | let cfg = parse_config(&job_toml("bogus = 1")).unwrap(); |
| @@ -1340,4 +1654,163 @@ artifacts = ["target/release/forge"] | |||
| 1340 | assert!(without.release.is_none()); | 1654 | assert!(without.release.is_none()); |
| 1341 | assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); | 1655 | assert!(!without.wants_release(&Event::Tag { tag: "v1.2.0" })); |
| 1342 | } | 1656 | } |
| 1657 | + | ||
| 1658 | + fn matrix_toml(matrix: &str, extra: &str) -> String { | ||
| 1659 | + format!( | ||
| 1660 | + "[jobs.test]\nimage = \"rust:${{{{ matrix.rust }}}}\"\nrun = \"cargo +${{matrix.rust}} test --target $MATRIX_TARGET\"\nruns_on = [\"${{{{ matrix.target }}}}\"]\nmatrix = {matrix}\n{extra}\n" | ||
| 1661 | + ) | ||
| 1662 | + } | ||
| 1663 | + | ||
| 1664 | + const GRID: &str = r#"{ rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] }"#; | ||
| 1665 | + | ||
| 1666 | + #[test] | ||
| 1667 | + fn schedule_is_parsed_and_validated() { | ||
| 1668 | + let cfg = parse_config(&format!( | ||
| 1669 | + "[on]\nschedule = [\"0 3 * * *\", \"*/15 * * * 1\"]\n{}", | ||
| 1670 | + job_toml("") | ||
| 1671 | + )) | ||
| 1672 | + .unwrap(); | ||
| 1673 | + assert_eq!(cfg.on.schedule.len(), 2); | ||
| 1674 | + assert!(cfg.warnings.is_empty()); | ||
| 1675 | + assert!(cfg.triggered_by(&Event::Schedule)); | ||
| 1676 | + let none = parse_config(&job_toml("")).unwrap(); | ||
| 1677 | + assert!(!none.triggered_by(&Event::Schedule)); | ||
| 1678 | + for bad in ["0 0 3 * * *", "nope", "70 3 * * *", ""] { | ||
| 1679 | + let text = format!("[on]\nschedule = [\"{bad}\"]\n{}", job_toml("")); | ||
| 1680 | + assert!( | ||
| 1681 | + matches!(err_of(&text), ConfigError::InvalidSchedule { .. }), | ||
| 1682 | + "{bad}" | ||
| 1683 | + ); | ||
| 1684 | + } | ||
| 1685 | + let many = ["\"0 3 * * *\""; MAX_SCHEDULES + 1].join(", "); | ||
| 1686 | + let text = format!("[on]\nschedule = [{many}]\n{}", job_toml("")); | ||
| 1687 | + assert!(matches!(err_of(&text), ConfigError::InvalidSchedule { .. })); | ||
| 1688 | + } | ||
| 1689 | + | ||
| 1690 | + #[test] | ||
| 1691 | + fn a_matrix_expands_into_named_jobs() { | ||
| 1692 | + let cfg = parse_config(&matrix_toml(GRID, "")).unwrap(); | ||
| 1693 | + let names: Vec<&str> = cfg.jobs.keys().map(String::as_str).collect(); | ||
| 1694 | + assert_eq!( | ||
| 1695 | + names, | ||
| 1696 | + [ | ||
| 1697 | + "test (1.85, aarch64)", | ||
| 1698 | + "test (1.85, x86_64)", | ||
| 1699 | + "test (stable, aarch64)", | ||
| 1700 | + "test (stable, x86_64)" | ||
| 1701 | + ] | ||
| 1702 | + ); | ||
| 1703 | + let job = &cfg.jobs["test (stable, x86_64)"]; | ||
| 1704 | + assert_eq!(job.image, "rust:stable"); | ||
| 1705 | + assert_eq!(job.run, "cargo +stable test --target $MATRIX_TARGET"); | ||
| 1706 | + assert_eq!(job.runs_on, vec!["x86_64".to_string()]); | ||
| 1707 | + assert_eq!(job.env["MATRIX_RUST"], "stable"); | ||
| 1708 | + assert_eq!(job.env["MATRIX_TARGET"], "x86_64"); | ||
| 1709 | + assert!(job.matrix.is_none()); | ||
| 1710 | + } | ||
| 1711 | + | ||
| 1712 | + #[test] | ||
| 1713 | + fn matrix_exclude_and_include() { | ||
| 1714 | + 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" }] }"#; | ||
| 1715 | + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); | ||
| 1716 | + assert_eq!(cfg.jobs.len(), 4); | ||
| 1717 | + assert!(!cfg.jobs.contains_key("test (1.85, aarch64)")); | ||
| 1718 | + let extra = &cfg.jobs["test (nightly, x86_64)"]; | ||
| 1719 | + assert_eq!(extra.env["MATRIX_FLAG"], "-Z"); | ||
| 1720 | + // A partial exclude drops every combination that agrees on the named keys. | ||
| 1721 | + let m = | ||
| 1722 | + r#"{ rust = ["stable", "1.85"], target = ["x86_64"], exclude = [{ rust = "1.85" }] }"#; | ||
| 1723 | + let cfg = parse_config(&matrix_toml(m, "")).unwrap(); | ||
| 1724 | + assert_eq!( | ||
| 1725 | + cfg.jobs.keys().collect::<Vec<_>>(), | ||
| 1726 | + ["test (stable, x86_64)"] | ||
| 1727 | + ); | ||
| 1728 | + // An include that repeats an existing combination adds nothing. | ||
| 1729 | + let m = r#"{ rust = ["stable"], target = ["x86_64"], include = [{ rust = "stable", target = "x86_64" }] }"#; | ||
| 1730 | + assert_eq!(parse_config(&matrix_toml(m, "")).unwrap().jobs.len(), 1); | ||
| 1731 | + } | ||
| 1732 | + | ||
| 1733 | + #[test] | ||
| 1734 | + fn needs_on_a_matrix_job_waits_for_every_combination() { | ||
| 1735 | + let text = format!( | ||
| 1736 | + "{}\n[jobs.ship]\nimage = \"img\"\nrun = \"true\"\nneeds = [\"test\"]\n", | ||
| 1737 | + matrix_toml(GRID, "") | ||
| 1738 | + ); | ||
| 1739 | + let cfg = parse_config(&text).unwrap(); | ||
| 1740 | + assert_eq!(cfg.jobs["ship"].needs.len(), 4); | ||
| 1741 | + let order = cfg.job_order(); | ||
| 1742 | + assert_eq!(order.last(), Some(&"ship")); | ||
| 1743 | + // The matrix job's own needs apply to each combination. | ||
| 1744 | + let text = format!( | ||
| 1745 | + "[jobs.setup]\nimage = \"img\"\nrun = \"true\"\n{}", | ||
| 1746 | + matrix_toml(GRID, "needs = [\"setup\"]") | ||
| 1747 | + ); | ||
| 1748 | + let cfg = parse_config(&text).unwrap(); | ||
| 1749 | + assert_eq!(cfg.jobs["test (stable, x86_64)"].needs, ["setup"]); | ||
| 1750 | + } | ||
| 1751 | + | ||
| 1752 | + #[test] | ||
| 1753 | + fn matrix_errors_are_clear() { | ||
| 1754 | + let big = r#"{ a = [1,2,3,4,5], b = [1,2,3,4,5] }"#; | ||
| 1755 | + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {big}\n"); | ||
| 1756 | + let e = err_of(&text); | ||
| 1757 | + assert_eq!( | ||
| 1758 | + e, | ||
| 1759 | + ConfigError::MatrixTooLarge { | ||
| 1760 | + job: "t".into(), | ||
| 1761 | + count: 25, | ||
| 1762 | + max: MAX_JOBS | ||
| 1763 | + } | ||
| 1764 | + ); | ||
| 1765 | + assert!(e.to_string().contains("limit is 20")); | ||
| 1766 | + // Expansion that fits one job but not the workflow hits the job cap. | ||
| 1767 | + let mut text = String::new(); | ||
| 1768 | + for i in 0..MAX_JOBS - 1 { | ||
| 1769 | + text.push_str(&format!("[jobs.j{i}]\nimage = \"img\"\nrun = \"true\"\n")); | ||
| 1770 | + } | ||
| 1771 | + text.push_str("[jobs.m]\nimage = \"i\"\nrun = \"x\"\nmatrix = { a = [1, 2] }\n"); | ||
| 1772 | + assert!(matches!(err_of(&text), ConfigError::TooManyJobs { .. })); | ||
| 1773 | + for bad in [ | ||
| 1774 | + "{}", | ||
| 1775 | + "{ a = [] }", | ||
| 1776 | + "{ a = [\"x\", \"x\"] }", | ||
| 1777 | + "{ A = [\"x\"] }", | ||
| 1778 | + "{ a = [\"x,y\"] }", | ||
| 1779 | + "{ a = [\"x\"], exclude = [{ b = \"1\" }] }", | ||
| 1780 | + "{ a = [\"x\"], exclude = [{ a = \"x\" }] }", | ||
| 1781 | + "{ a = [\"x\"], include = [{ b = \"1\" }] }", | ||
| 1782 | + ] { | ||
| 1783 | + let text = format!("[jobs.t]\nimage = \"i\"\nrun = \"x\"\nmatrix = {bad}\n"); | ||
| 1784 | + assert!( | ||
| 1785 | + matches!(err_of(&text), ConfigError::InvalidMatrix { .. }), | ||
| 1786 | + "{bad}" | ||
| 1787 | + ); | ||
| 1788 | + } | ||
| 1789 | + // A typo in an interpolation fails at parse time. | ||
| 1790 | + let text = | ||
| 1791 | + "[jobs.t]\nimage = \"i\"\nrun = \"echo ${matrix.nope}\"\nmatrix = { a = [\"x\"] }\n"; | ||
| 1792 | + assert!(matches!(err_of(text), ConfigError::InvalidMatrix { .. })); | ||
| 1793 | + // Plain job keys cannot smuggle a suffix. | ||
| 1794 | + let text = "[jobs.\"t (x)\"]\nimage = \"i\"\nrun = \"x\"\n"; | ||
| 1795 | + assert!(matches!(err_of(text), ConfigError::InvalidJobName(_))); | ||
| 1796 | + } | ||
| 1797 | + | ||
| 1798 | + #[test] | ||
| 1799 | + fn shell_variables_are_left_alone() { | ||
| 1800 | + let text = "[jobs.t]\nimage = \"i\"\nrun = \"echo ${HOME} ${{ secrets.X }} ${matrix.a}\"\nmatrix = { a = [\"x\"] }\n"; | ||
| 1801 | + let cfg = parse_config(text).unwrap(); | ||
| 1802 | + assert_eq!(cfg.jobs["t (x)"].run, "echo ${HOME} ${{ secrets.X }} x"); | ||
| 1803 | + } | ||
| 1804 | + | ||
| 1805 | + #[test] | ||
| 1806 | + fn release_assets_can_name_a_matrix_job() { | ||
| 1807 | + let text = format!( | ||
| 1808 | + "[on]\ntags = [\"v*\"]\n[release]\nassets = [\"test:*.tar\"]\n{}", | ||
| 1809 | + matrix_toml(GRID, "artifacts = [\"out/a.tar\"]") | ||
| 1810 | + ); | ||
| 1811 | + let cfg = parse_config(&text).unwrap(); | ||
| 1812 | + let release = cfg.release.unwrap(); | ||
| 1813 | + assert!(release.asset_matches("test (stable, x86_64)", "a.tar")); | ||
| 1814 | + assert!(!release.asset_matches("testing", "a.tar")); | ||
| 1815 | + } | ||
| 1343 | } | 1816 | } |
crates/forge-ci/src/cron.rsadded+81 -0
| @@ -0,0 +1,81 @@ | |||
| 1 | +//! Standard 5-field cron expressions in UTC, for `[on] schedule`. | ||
| 2 | +//! | ||
| 3 | +//! Times are Unix seconds. The functions are pure, so the scheduler's tick logic can be tested | ||
| 4 | +//! with a fake clock. | ||
| 5 | + | ||
| 6 | +use chrono::DateTime; | ||
| 7 | +use croner::Cron; | ||
| 8 | + | ||
| 9 | +/// Parses a 5-field cron expression (`minute hour day-of-month month day-of-week`). | ||
| 10 | +pub fn parse(expr: &str) -> Result<Cron, String> { | ||
| 11 | + let trimmed = expr.trim(); | ||
| 12 | + if trimmed.split_whitespace().count() != 5 { | ||
| 13 | + return Err( | ||
| 14 | + "must have exactly 5 fields: minute hour day-of-month month day-of-week".into(), | ||
| 15 | + ); | ||
| 16 | + } | ||
| 17 | + trimmed.parse::<Cron>().map_err(|e| e.to_string()) | ||
| 18 | +} | ||
| 19 | + | ||
| 20 | +/// The first time strictly after `after` that `cron` matches. | ||
| 21 | +fn next_one(cron: &Cron, after: i64) -> Option<i64> { | ||
| 22 | + let start = DateTime::from_timestamp(after, 0)?.naive_utc(); | ||
| 23 | + let next = cron.find_next_occurrence(&start, false).ok()?; | ||
| 24 | + Some(next.and_utc().timestamp()) | ||
| 25 | +} | ||
| 26 | + | ||
| 27 | +/// The first time strictly after `after` that any of `exprs` matches. Expressions that do not | ||
| 28 | +/// parse are ignored. | ||
| 29 | +pub fn next_after<S: AsRef<str>>(exprs: &[S], after: i64) -> Option<i64> { | ||
| 30 | + exprs | ||
| 31 | + .iter() | ||
| 32 | + .filter_map(|e| parse(e.as_ref()).ok()) | ||
| 33 | + .filter_map(|c| next_one(&c, after)) | ||
| 34 | + .min() | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Whether any of `exprs` matched a time `t` with `last < t <= now`. However many ticks fell in | ||
| 38 | +/// that window, the answer is one yes: a scheduler that was down catches up once. | ||
| 39 | +pub fn fired_between<S: AsRef<str>>(exprs: &[S], last: i64, now: i64) -> bool { | ||
| 40 | + next_after(exprs, last).is_some_and(|t| t <= now) | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +#[cfg(test)] | ||
| 44 | +mod tests { | ||
| 45 | + use super::*; | ||
| 46 | + | ||
| 47 | + // 2026-10-15 12:00:00 UTC | ||
| 48 | + const NOON: i64 = 1_791_979_200; | ||
| 49 | + | ||
| 50 | + #[test] | ||
| 51 | + fn requires_five_fields() { | ||
| 52 | + assert!(parse("0 3 * * *").is_ok()); | ||
| 53 | + assert!(parse("0 0 3 * * *").is_err()); | ||
| 54 | + assert!(parse("0 3 * *").is_err()); | ||
| 55 | + assert!(parse("61 3 * * *").is_err()); | ||
| 56 | + assert!(parse("nope").is_err()); | ||
| 57 | + } | ||
| 58 | + | ||
| 59 | + #[test] | ||
| 60 | + fn next_is_strictly_after() { | ||
| 61 | + let day = 86_400; | ||
| 62 | + let three = NOON - 9 * 3600 + day; | ||
| 63 | + assert_eq!(next_after(&["0 3 * * *"], NOON), Some(three)); | ||
| 64 | + assert_eq!(next_after(&["0 3 * * *"], three), Some(three + day)); | ||
| 65 | + assert_eq!( | ||
| 66 | + next_after(&["0 3 * * *", "30 12 * * *"], NOON), | ||
| 67 | + Some(NOON + 1800) | ||
| 68 | + ); | ||
| 69 | + assert_eq!(next_after::<&str>(&[], NOON), None); | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + #[test] | ||
| 73 | + fn fires_inside_the_window_only() { | ||
| 74 | + assert!(fired_between(&["30 12 * * *"], NOON, NOON + 1800)); | ||
| 75 | + assert!(!fired_between(&["30 12 * * *"], NOON, NOON + 1799)); | ||
| 76 | + // The window is open at `last`: a tick already handled does not fire again. | ||
| 77 | + assert!(!fired_between(&["0 12 * * *"], NOON, NOON + 60)); | ||
| 78 | + // A week of downtime is still one yes. | ||
| 79 | + assert!(fired_between(&["* * * * *"], NOON, NOON + 7 * 86_400)); | ||
| 80 | + } | ||
| 81 | +} | ||
crates/forge-ci/src/error.rsmodified+16 -1
| @@ -14,9 +14,24 @@ pub enum ConfigError { | |||
| 14 | #[error("no jobs are defined")] | 14 | #[error("no jobs are defined")] |
| 15 | NoJobs, | 15 | NoJobs, |
| 16 | 16 | ||
| 17 | - #[error("{count} jobs are defined, the limit is {max}")] | 17 | + #[error( |
| 18 | + "{count} jobs are defined (a matrix job counts once per combination), the limit is {max}" | ||
| 19 | + )] | ||
| 18 | TooManyJobs { count: usize, max: usize }, | 20 | TooManyJobs { count: usize, max: usize }, |
| 19 | 21 | ||
| 22 | + #[error("job {job:?}: matrix expands to {count} jobs, the limit is {max} jobs per workflow")] | ||
| 23 | + MatrixTooLarge { | ||
| 24 | + job: String, | ||
| 25 | + count: usize, | ||
| 26 | + max: usize, | ||
| 27 | + }, | ||
| 28 | + | ||
| 29 | + #[error("job {job:?}: invalid matrix: {reason}")] | ||
| 30 | + InvalidMatrix { job: String, reason: String }, | ||
| 31 | + | ||
| 32 | + #[error("invalid schedule {expr:?}: {reason}")] | ||
| 33 | + InvalidSchedule { expr: String, reason: String }, | ||
| 34 | + | ||
| 20 | #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] | 35 | #[error("invalid job name {0:?}: must match ^[a-z0-9][a-z0-9_-]{{0,39}}$")] |
| 21 | InvalidJobName(String), | 36 | InvalidJobName(String), |
| 22 | 37 | ||
crates/forge-ci/src/lib.rsmodified+1 -0
| @@ -2,6 +2,7 @@ | |||
| 2 | //! forge-web and forge-runner. | 2 | //! forge-web and forge-runner. |
| 3 | 3 | ||
| 4 | pub mod config; | 4 | pub mod config; |
| 5 | +pub mod cron; | ||
| 5 | pub mod error; | 6 | pub mod error; |
| 6 | pub mod mask; | 7 | pub mod mask; |
| 7 | pub mod proto; | 8 | pub mod proto; |
crates/forge-core/migrations/0055_attachments.sql → crates/forge-core/migrations/0052_attachments.sqlrenamed+0 -0
crates/forge-core/migrations/0056_review_requests.sql → crates/forge-core/migrations/0053_review_requests.sqlrenamed+0 -0
crates/forge-core/migrations/0054_ci_schedule_state.sqladded+9 -0
| @@ -0,0 +1,9 @@ | |||
| 1 | +-- Where the CI scheduler left off, per repo: the last time (Unix seconds, UTC) it checked the | ||
| 2 | +-- repo's `[on] schedule`. A cron match in (last_tick, now] queues one run, however many ticks that | ||
| 3 | +-- spans, so a server that was down catches up once. A repo with no schedule has no row. Applied by | ||
| 4 | +-- store/migrate.rs. | ||
| 5 | + | ||
| 6 | +CREATE TABLE ci_schedule_state ( | ||
| 7 | + repo_id TEXT PRIMARY KEY REFERENCES repos(id) ON DELETE CASCADE, | ||
| 8 | + last_tick INTEGER NOT NULL | ||
| 9 | +); | ||
crates/forge-core/src/store/ci.rsmodified+54 -0
| @@ -487,6 +487,60 @@ impl Store { | |||
| 487 | .await | 487 | .await |
| 488 | } | 488 | } |
| 489 | 489 | ||
| 490 | + /// Repos the CI scheduler looks at: everything that is not archived. | ||
| 491 | + pub async fn repos_for_ci_schedule(&self) -> Result<Vec<crate::Repo>> { | ||
| 492 | + let conn = self.read_conn().await; | ||
| 493 | + fetch_all( | ||
| 494 | + &conn, | ||
| 495 | + &format!( | ||
| 496 | + "SELECT {} FROM repos r JOIN users u ON u.id = r.owner_id \ | ||
| 497 | + WHERE r.archived = 0 ORDER BY r.id", | ||
| 498 | + super::REPO_COLS | ||
| 499 | + ), | ||
| 500 | + (), | ||
| 501 | + super::map_repo, | ||
| 502 | + ) | ||
| 503 | + .await | ||
| 504 | + } | ||
| 505 | + | ||
| 506 | + /// When (Unix seconds) the scheduler last checked `repo_id`, if it has. | ||
| 507 | + pub async fn ci_schedule_last_tick(&self, repo_id: &str) -> Result<Option<i64>> { | ||
| 508 | + let conn = self.read_conn().await; | ||
| 509 | + fetch_opt( | ||
| 510 | + &conn, | ||
| 511 | + "SELECT last_tick FROM ci_schedule_state WHERE repo_id = ?1", | ||
| 512 | + (repo_id.to_string(),), | ||
| 513 | + |row| col_int(row, 0), | ||
| 514 | + ) | ||
| 515 | + .await | ||
| 516 | + } | ||
| 517 | + | ||
| 518 | + /// Records that the scheduler checked `repo_id` at `tick` (Unix seconds). | ||
| 519 | + pub async fn set_ci_schedule_last_tick(&self, repo_id: &str, tick: i64) -> Result<()> { | ||
| 520 | + let conn = self.inner.conn.lock().await; | ||
| 521 | + conn.execute( | ||
| 522 | + "INSERT INTO ci_schedule_state (repo_id, last_tick) VALUES (?1, ?2) \ | ||
| 523 | + ON CONFLICT(repo_id) DO UPDATE SET last_tick = excluded.last_tick", | ||
| 524 | + (repo_id.to_string(), tick), | ||
| 525 | + ) | ||
| 526 | + .await | ||
| 527 | + .map_err(db_err)?; | ||
| 528 | + Ok(()) | ||
| 529 | + } | ||
| 530 | + | ||
| 531 | + /// Forgets `repo_id`, for a repo whose workflow no longer has a schedule. Turning a schedule | ||
| 532 | + /// back on later then starts from that moment instead of catching up. | ||
| 533 | + pub async fn clear_ci_schedule(&self, repo_id: &str) -> Result<()> { | ||
| 534 | + let conn = self.inner.conn.lock().await; | ||
| 535 | + conn.execute( | ||
| 536 | + "DELETE FROM ci_schedule_state WHERE repo_id = ?1", | ||
| 537 | + (repo_id.to_string(),), | ||
| 538 | + ) | ||
| 539 | + .await | ||
| 540 | + .map_err(db_err)?; | ||
| 541 | + Ok(()) | ||
| 542 | + } | ||
| 543 | + | ||
| 490 | /// Disabled runners get no jobs. `NotFound` if the runner does not exist. | 544 | /// Disabled runners get no jobs. `NotFound` if the runner does not exist. |
| 491 | pub async fn set_runner_disabled(&self, id: &str, disabled: bool) -> Result<()> { | 545 | pub async fn set_runner_disabled(&self, id: &str, disabled: bool) -> Result<()> { |
| 492 | let conn = self.inner.conn.lock().await; | 546 | let conn = self.inner.conn.lock().await; |
crates/forge-core/src/store/migrate.rsmodified+7 -3
| @@ -82,10 +82,14 @@ pub const MIGRATIONS: &[(u32, &str)] = &[ | |||
| 82 | ), | 82 | ), |
| 83 | (50, include_str!("../../migrations/0050_imports.sql")), | 83 | (50, include_str!("../../migrations/0050_imports.sql")), |
| 84 | (51, include_str!("../../migrations/0051_data_exports.sql")), | 84 | (51, include_str!("../../migrations/0051_data_exports.sql")), |
| 85 | - (55, include_str!("../../migrations/0055_attachments.sql")), | 85 | + (52, include_str!("../../migrations/0052_attachments.sql")), |
| 86 | ( | 86 | ( |
| 87 | - 56, | 87 | + 53, |
| 88 | - include_str!("../../migrations/0056_review_requests.sql"), | 88 | + include_str!("../../migrations/0053_review_requests.sql"), |
| 89 | + ), | ||
| 90 | + ( | ||
| 91 | + 54, | ||
| 92 | + include_str!("../../migrations/0054_ci_schedule_state.sql"), | ||
| 89 | ), | 93 | ), |
| 90 | ]; | 94 | ]; |
| 91 | 95 | ||
crates/forge-web/src/boot.rsmodified+1 -0
| @@ -154,6 +154,7 @@ pub async fn serve( | |||
| 154 | crate::replication::worker::spawn(state.clone()); | 154 | crate::replication::worker::spawn(state.clone()); |
| 155 | } | 155 | } |
| 156 | crate::ci::reaper::spawn(state.clone()); | 156 | crate::ci::reaper::spawn(state.clone()); |
| 157 | + crate::ci::scheduled::spawn(state.clone()); | ||
| 157 | 158 | ||
| 158 | // Topcoat's builder-wide compression is off because it cannot filter by content type or path. | 159 | // Topcoat's builder-wide compression is off because it cannot filter by content type or path. |
| 159 | // `ResponseCompression` compresses text responses only and skips git, LFS, raw and archive paths. | 160 | // `ResponseCompression` compresses text responses only and skips git, LFS, raw and archive paths. |
crates/forge-web/src/ci/mod.rsmodified+1 -0
| @@ -15,6 +15,7 @@ pub mod live; | |||
| 15 | pub mod reaper; | 15 | pub mod reaper; |
| 16 | pub mod release; | 16 | pub mod release; |
| 17 | pub mod schedule; | 17 | pub mod schedule; |
| 18 | +pub mod scheduled; | ||
| 18 | 19 | ||
| 19 | pub use live::CiLive; | 20 | pub use live::CiLive; |
| 20 | pub use schedule::{manual_run, on_pull_event, on_ref_update}; | 21 | pub use schedule::{manual_run, on_pull_event, on_ref_update}; |
crates/forge-web/src/ci/schedule.rsmodified+63 -1
| @@ -29,7 +29,7 @@ const MIB: u64 = 1024 * 1024; | |||
| 29 | type PlannedJob = (String, String, Vec<String>); | 29 | type PlannedJob = (String, String, Vec<String>); |
| 30 | 30 | ||
| 31 | /// What `.forge/ci.toml` held at one commit. | 31 | /// What `.forge/ci.toml` held at one commit. |
| 32 | -enum Loaded { | 32 | +pub(super) enum Loaded { |
| 33 | Missing, | 33 | Missing, |
| 34 | Invalid(String), | 34 | Invalid(String), |
| 35 | Valid(CiConfig), | 35 | Valid(CiConfig), |
| @@ -225,6 +225,68 @@ pub async fn manual_run( | |||
| 225 | } | 225 | } |
| 226 | } | 226 | } |
| 227 | 227 | ||
| 228 | +/// The head commit of the repo's default branch and the workflow at it. `None` when the branch | ||
| 229 | +/// has no commits (or cannot be read, which is logged). | ||
| 230 | +pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option<(String, Loaded)> { | ||
| 231 | + let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).ok()?; | ||
| 232 | + let short = repo.default_branch.clone(); | ||
| 233 | + let commit = match blocking(move || resolve_commit(&repo_dir, &short)).await { | ||
| 234 | + Ok(commit) => commit?, | ||
| 235 | + Err(e) => { | ||
| 236 | + tracing::error!(error = %e, repo_id = %repo.id, "ci: resolving the default branch failed"); | ||
| 237 | + return None; | ||
| 238 | + } | ||
| 239 | + }; | ||
| 240 | + let loaded = load(state, &repo.id, &commit).await; | ||
| 241 | + Some((commit, loaded)) | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +/// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is | ||
| 245 | +/// no valid workflow. | ||
| 246 | +pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec<String> { | ||
| 247 | + match default_head_config(state, repo).await { | ||
| 248 | + Some((_, Loaded::Valid(cfg))) => cfg.on.schedule, | ||
| 249 | + _ => Vec::new(), | ||
| 250 | + } | ||
| 251 | +} | ||
| 252 | + | ||
| 253 | +/// Queues a `schedule` run of `commit` on the default branch. A config that does not parse gives | ||
| 254 | +/// an Error run, as a push does. Nothing happens when the workflow has no schedule. | ||
| 255 | +pub(super) async fn scheduled_run( | ||
| 256 | + state: &AppState, | ||
| 257 | + repo: &Repo, | ||
| 258 | + commit: &str, | ||
| 259 | + loaded: Loaded, | ||
| 260 | +) -> forge_core::Result<Option<CiRun>> { | ||
| 261 | + let Plan::Run { | ||
| 262 | + jobs, | ||
| 263 | + config_error, | ||
| 264 | + warnings, | ||
| 265 | + } = plan_for(loaded, &Event::Schedule)? | ||
| 266 | + else { | ||
| 267 | + return Ok(None); | ||
| 268 | + }; | ||
| 269 | + let git_ref = format!("refs/heads/{}", repo.default_branch); | ||
| 270 | + let run = create( | ||
| 271 | + state, | ||
| 272 | + Request { | ||
| 273 | + repo, | ||
| 274 | + trigger: "schedule", | ||
| 275 | + git_ref: &git_ref, | ||
| 276 | + commit, | ||
| 277 | + pull_number: None, | ||
| 278 | + // The column needs a user; the repo owner stands in. The pages show no actor for these. | ||
| 279 | + actor_id: &repo.owner_id, | ||
| 280 | + needs_approval: false, | ||
| 281 | + }, | ||
| 282 | + jobs, | ||
| 283 | + config_error.as_deref(), | ||
| 284 | + &warnings, | ||
| 285 | + ) | ||
| 286 | + .await?; | ||
| 287 | + Ok(Some(run)) | ||
| 288 | +} | ||
| 289 | + | ||
| 228 | /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes | 290 | /// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes |
| 229 | /// the runner claims when a job is queued. | 291 | /// the runner claims when a job is queued. |
| 230 | async fn create( | 292 | async fn create( |
crates/forge-web/src/ci/scheduled.rsadded+283 -0
| @@ -0,0 +1,283 @@ | |||
| 1 | +//! The CI scheduler: queues a `schedule` run for each repo whose `[on] schedule` matched since the | ||
| 2 | +//! last check. It reads `.forge/ci.toml` from the head of the default branch, so a schedule | ||
| 3 | +//! change takes effect without a push. | ||
| 4 | +//! | ||
| 5 | +//! A tick checks the window `(last_tick, now]` per repo. However many cron matches fall inside it, | ||
| 6 | +//! one run is queued: a server that was down for a day catches up once, not once per missed | ||
| 7 | +//! match. A repo seen for the first time starts from now. Archived repos are not looked at, and | ||
| 8 | +//! nothing happens while CI is disabled on the instance. | ||
| 9 | + | ||
| 10 | +use std::time::Duration; | ||
| 11 | + | ||
| 12 | +use forge_ci::cron; | ||
| 13 | +use forge_core::Repo; | ||
| 14 | + | ||
| 15 | +use super::schedule::{Loaded, default_head_config, scheduled_run}; | ||
| 16 | +use crate::state::AppState; | ||
| 17 | + | ||
| 18 | +/// What a tick does for one repo. | ||
| 19 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 20 | +pub enum Decision { | ||
| 21 | + /// No schedule and nothing remembered. | ||
| 22 | + Idle, | ||
| 23 | + /// The schedule is gone: forget the repo, so a later schedule starts fresh. | ||
| 24 | + Forget, | ||
| 25 | + /// A match fell in the window: queue one run, then move the window. | ||
| 26 | + Fire, | ||
| 27 | + /// Nothing is due: move the window. | ||
| 28 | + Advance, | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +/// What to do for a repo with these `schedules`, last checked at `last` (Unix seconds), at `now`. | ||
| 32 | +pub fn decide(schedules: &[String], last: Option<i64>, now: i64) -> Decision { | ||
| 33 | + if schedules.is_empty() { | ||
| 34 | + return if last.is_some() { | ||
| 35 | + Decision::Forget | ||
| 36 | + } else { | ||
| 37 | + Decision::Idle | ||
| 38 | + }; | ||
| 39 | + } | ||
| 40 | + match last { | ||
| 41 | + Some(last) if cron::fired_between(schedules, last, now) => Decision::Fire, | ||
| 42 | + _ => Decision::Advance, | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// Seconds to sleep so the next tick lands just after the next minute starts. | ||
| 47 | +pub fn nap_secs(now: i64) -> u64 { | ||
| 48 | + u64::try_from(61 - now.rem_euclid(60)).unwrap_or(60) | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +/// Starts the scheduler task. It runs until the process exits. | ||
| 52 | +pub fn spawn(state: AppState) { | ||
| 53 | + tokio::spawn(run(state)); | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +async fn run(state: AppState) { | ||
| 57 | + loop { | ||
| 58 | + tick(&state, crate::raw::now_unix()).await; | ||
| 59 | + tokio::time::sleep(Duration::from_secs(nap_secs(crate::raw::now_unix()))).await; | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/// One pass over every repo at `now` (Unix seconds). Returns how many runs it queued. | ||
| 64 | +pub async fn tick(state: &AppState, now: i64) -> usize { | ||
| 65 | + if !state.live().ci.enabled { | ||
| 66 | + return 0; | ||
| 67 | + } | ||
| 68 | + let repos = match state.store.repos_for_ci_schedule().await { | ||
| 69 | + Ok(repos) => repos, | ||
| 70 | + Err(e) => { | ||
| 71 | + tracing::error!(error = %e, "ci: listing repos for the scheduler failed"); | ||
| 72 | + return 0; | ||
| 73 | + } | ||
| 74 | + }; | ||
| 75 | + let mut queued = 0; | ||
| 76 | + for repo in &repos { | ||
| 77 | + match tick_repo(state, repo, now).await { | ||
| 78 | + Ok(true) => queued += 1, | ||
| 79 | + Ok(false) => {} | ||
| 80 | + Err(e) => { | ||
| 81 | + tracing::error!(error = %e, repo_id = %repo.id, "ci: scheduled run failed"); | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + queued | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +async fn tick_repo(state: &AppState, repo: &Repo, now: i64) -> forge_core::Result<bool> { | ||
| 89 | + let last = state.store.ci_schedule_last_tick(&repo.id).await?; | ||
| 90 | + let head = default_head_config(state, repo).await; | ||
| 91 | + let schedules = match &head { | ||
| 92 | + Some((_, Loaded::Valid(cfg))) => cfg.on.schedule.clone(), | ||
| 93 | + _ => Vec::new(), | ||
| 94 | + }; | ||
| 95 | + match decide(&schedules, last, now) { | ||
| 96 | + Decision::Idle => Ok(false), | ||
| 97 | + Decision::Forget => { | ||
| 98 | + state.store.clear_ci_schedule(&repo.id).await?; | ||
| 99 | + Ok(false) | ||
| 100 | + } | ||
| 101 | + Decision::Advance => { | ||
| 102 | + state.store.set_ci_schedule_last_tick(&repo.id, now).await?; | ||
| 103 | + Ok(false) | ||
| 104 | + } | ||
| 105 | + Decision::Fire => { | ||
| 106 | + // A failure leaves the window where it was, so the next tick tries again. | ||
| 107 | + let Some((commit, loaded)) = head else { | ||
| 108 | + return Ok(false); | ||
| 109 | + }; | ||
| 110 | + let run = scheduled_run(state, repo, &commit, loaded).await?; | ||
| 111 | + state.store.set_ci_schedule_last_tick(&repo.id, now).await?; | ||
| 112 | + Ok(run.is_some()) | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +#[cfg(test)] | ||
| 118 | +mod tests { | ||
| 119 | + use std::io::Write; | ||
| 120 | + use std::path::Path; | ||
| 121 | + | ||
| 122 | + use forge_core::Visibility; | ||
| 123 | + use forge_git::repo::{init_bare, repo_path}; | ||
| 124 | + | ||
| 125 | + use super::*; | ||
| 126 | + use crate::test_support::test_state; | ||
| 127 | + | ||
| 128 | + // 2026-10-15 12:00:00 UTC. | ||
| 129 | + const NOON: i64 = 1_791_979_200; | ||
| 130 | + const DAILY_3: [&str; 1] = ["0 3 * * *"]; | ||
| 131 | + | ||
| 132 | + fn schedules(list: &[&str]) -> Vec<String> { | ||
| 133 | + list.iter().map(|s| (*s).to_owned()).collect() | ||
| 134 | + } | ||
| 135 | + | ||
| 136 | + #[test] | ||
| 137 | + fn a_repo_seen_first_starts_from_now() { | ||
| 138 | + assert_eq!( | ||
| 139 | + decide(&schedules(&DAILY_3), None, NOON), | ||
| 140 | + Decision::Advance, | ||
| 141 | + "no catch-up for a schedule nobody has seen" | ||
| 142 | + ); | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + #[test] | ||
| 146 | + fn fires_once_when_a_tick_falls_in_the_window() { | ||
| 147 | + let s = schedules(&DAILY_3); | ||
| 148 | + // 03:00 the next day. | ||
| 149 | + let fire_at = NOON + 15 * 3600; | ||
| 150 | + assert_eq!(decide(&s, Some(NOON), fire_at - 1), Decision::Advance); | ||
| 151 | + assert_eq!(decide(&s, Some(NOON), fire_at), Decision::Fire); | ||
| 152 | + // Having moved the window to the fire time, the same tick does not fire again. | ||
| 153 | + assert_eq!(decide(&s, Some(fire_at), fire_at + 60), Decision::Advance); | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + #[test] | ||
| 157 | + fn downtime_catches_up_at_most_once() { | ||
| 158 | + let s = schedules(&["* * * * *"]); | ||
| 159 | + // A week of missed minutes is one Fire, and the window then restarts at now. | ||
| 160 | + let back = NOON + 7 * 86_400; | ||
| 161 | + assert_eq!(decide(&s, Some(NOON), back), Decision::Fire); | ||
| 162 | + assert_eq!(decide(&s, Some(back), back + 30), Decision::Advance); | ||
| 163 | + assert_eq!(decide(&s, Some(back), back + 60), Decision::Fire); | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + #[test] | ||
| 167 | + fn a_removed_schedule_is_forgotten() { | ||
| 168 | + assert_eq!(decide(&[], Some(NOON), NOON), Decision::Forget); | ||
| 169 | + assert_eq!(decide(&[], None, NOON), Decision::Idle); | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + #[test] | ||
| 173 | + fn naps_land_just_after_the_minute() { | ||
| 174 | + assert_eq!(nap_secs(NOON), 61); | ||
| 175 | + assert_eq!(nap_secs(NOON + 59), 2); | ||
| 176 | + assert_eq!(nap_secs(NOON + 1), 60); | ||
| 177 | + } | ||
| 178 | + | ||
| 179 | + fn git(bare: &Path, args: &[&str], stdin: &str) -> String { | ||
| 180 | + let mut child = std::process::Command::new("git") | ||
| 181 | + .arg("--git-dir") | ||
| 182 | + .arg(bare) | ||
| 183 | + .args(args) | ||
| 184 | + .env("GIT_AUTHOR_NAME", "tahinli") | ||
| 185 | + .env("GIT_AUTHOR_EMAIL", "tahinli@example.com") | ||
| 186 | + .env("GIT_COMMITTER_NAME", "tahinli") | ||
| 187 | + .env("GIT_COMMITTER_EMAIL", "tahinli@example.com") | ||
| 188 | + .stdin(std::process::Stdio::piped()) | ||
| 189 | + .stdout(std::process::Stdio::piped()) | ||
| 190 | + .stderr(std::process::Stdio::piped()) | ||
| 191 | + .spawn() | ||
| 192 | + .expect("spawn git"); | ||
| 193 | + child | ||
| 194 | + .stdin | ||
| 195 | + .take() | ||
| 196 | + .expect("stdin") | ||
| 197 | + .write_all(stdin.as_bytes()) | ||
| 198 | + .expect("write stdin"); | ||
| 199 | + let out = child.wait_with_output().expect("git output"); | ||
| 200 | + assert!(out.status.success(), "git {args:?}"); | ||
| 201 | + String::from_utf8(out.stdout) | ||
| 202 | + .expect("utf8") | ||
| 203 | + .trim() | ||
| 204 | + .to_owned() | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + /// Commits `.forge/ci.toml` with `text` and points `main` at it. | ||
| 208 | + fn commit_config(bare: &Path, text: &str) { | ||
| 209 | + let blob = git(bare, &["hash-object", "-w", "--stdin"], text); | ||
| 210 | + let forge = git(bare, &["mktree"], &format!("100644 blob {blob}\tci.toml\n")); | ||
| 211 | + let root = git(bare, &["mktree"], &format!("040000 tree {forge}\t.forge\n")); | ||
| 212 | + let commit = git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], ""); | ||
| 213 | + git( | ||
| 214 | + bare, | ||
| 215 | + &["update-ref", "refs/heads/main", commit.as_str()], | ||
| 216 | + "", | ||
| 217 | + ); | ||
| 218 | + } | ||
| 219 | + | ||
| 220 | + const WORKFLOW: &str = | ||
| 221 | + "[on]\nschedule = [\"0 3 * * *\"]\n[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n"; | ||
| 222 | + | ||
| 223 | + #[tokio::test] | ||
| 224 | + async fn ticks_queue_one_schedule_run_and_skip_archived_repos() { | ||
| 225 | + let dir = tempfile::tempdir().expect("tempdir"); | ||
| 226 | + let state = test_state(dir.path()).await; | ||
| 227 | + let store = state.store.clone(); | ||
| 228 | + let tahinli = store | ||
| 229 | + .create_user("tahinli", None, "unused", false) | ||
| 230 | + .await | ||
| 231 | + .expect("user"); | ||
| 232 | + let mut repos = Vec::new(); | ||
| 233 | + for name in ["live", "old"] { | ||
| 234 | + let repo = store | ||
| 235 | + .create_repo(&tahinli.id, name, "", Visibility::Private, "main") | ||
| 236 | + .await | ||
| 237 | + .expect("repo"); | ||
| 238 | + let bare = repo_path(&state.git.data_dir, &repo.id).expect("path"); | ||
| 239 | + init_bare(&state.git, &bare, "main").await.expect("init"); | ||
| 240 | + commit_config(&bare, WORKFLOW); | ||
| 241 | + repos.push(repo); | ||
| 242 | + } | ||
| 243 | + store | ||
| 244 | + .set_repo_archived(&repos[1].id, true) | ||
| 245 | + .await | ||
| 246 | + .expect("archive"); | ||
| 247 | + | ||
| 248 | + // First sight only records where the window starts. | ||
| 249 | + assert_eq!(tick(&state, NOON).await, 0); | ||
| 250 | + assert_eq!( | ||
| 251 | + store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), | ||
| 252 | + Some(NOON) | ||
| 253 | + ); | ||
| 254 | + assert_eq!( | ||
| 255 | + store.ci_schedule_last_tick(&repos[1].id).await.unwrap(), | ||
| 256 | + None, | ||
| 257 | + "archived repos are skipped" | ||
| 258 | + ); | ||
| 259 | + // Before 03:00 nothing is due. | ||
| 260 | + assert_eq!(tick(&state, NOON + 3600).await, 0); | ||
| 261 | + // Three days of downtime later: one run, not three. | ||
| 262 | + let later = NOON + 3 * 86_400; | ||
| 263 | + assert_eq!(tick(&state, later).await, 1); | ||
| 264 | + assert_eq!(tick(&state, later + 60).await, 0); | ||
| 265 | + let (runs, total) = store.list_runs(&repos[0].id, 1, 25).await.unwrap(); | ||
| 266 | + assert_eq!(total, 1); | ||
| 267 | + assert_eq!(runs[0].trigger, "schedule"); | ||
| 268 | + assert_eq!(runs[0].git_ref, "refs/heads/main"); | ||
| 269 | + let (_, archived_total) = store.list_runs(&repos[1].id, 1, 25).await.unwrap(); | ||
| 270 | + assert_eq!(archived_total, 0); | ||
| 271 | + | ||
| 272 | + // Dropping the schedule forgets the repo. | ||
| 273 | + commit_config( | ||
| 274 | + &repo_path(&state.git.data_dir, &repos[0].id).unwrap(), | ||
| 275 | + "[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n", | ||
| 276 | + ); | ||
| 277 | + assert_eq!(tick(&state, later + 120).await, 0); | ||
| 278 | + assert_eq!( | ||
| 279 | + store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), | ||
| 280 | + None | ||
| 281 | + ); | ||
| 282 | + } | ||
| 283 | +} | ||
crates/forge-web/src/i18n/mod.rsmodified+1 -1
| @@ -19,8 +19,8 @@ use forge_core::User; | |||
| 19 | 19 | ||
| 20 | pub mod accents; | 20 | pub mod accents; |
| 21 | pub mod admin; | 21 | pub mod admin; |
| 22 | -pub mod browse; | ||
| 23 | pub mod authoring; | 22 | pub mod authoring; |
| 23 | +pub mod browse; | ||
| 24 | pub mod code; | 24 | pub mod code; |
| 25 | pub mod community; | 25 | pub mod community; |
| 26 | pub mod integrations; | 26 | pub mod integrations; |
crates/forge-web/src/i18n/releases_ci.rsmodified+8 -0
| @@ -45,6 +45,8 @@ pub enum K { | |||
| 45 | Runs, | 45 | Runs, |
| 46 | NoRunsYet, | 46 | NoRunsYet, |
| 47 | NoRunsHint, | 47 | NoRunsHint, |
| 48 | + TriggerScheduled, | ||
| 49 | + NextScheduledRun, | ||
| 48 | NoJobs, | 50 | NoJobs, |
| 49 | Newer, | 51 | Newer, |
| 50 | Older, | 52 | Older, |
| @@ -231,6 +233,10 @@ pub fn t(lang: Lang, key: K) -> &'static str { | |||
| 231 | (NoRunsHint, Tr) => { | 233 | (NoRunsHint, Tr) => { |
| 232 | ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." | 234 | ".forge/ci.toml dosyası ekleyin, ardından bir commit gönderin ya da bir çalıştırma başlatın." |
| 233 | } | 235 | } |
| 236 | + (TriggerScheduled, En) => "scheduled", | ||
| 237 | + (TriggerScheduled, Tr) => "zamanlanmış", | ||
| 238 | + (NextScheduledRun, En) => "Next scheduled run", | ||
| 239 | + (NextScheduledRun, Tr) => "Sonraki zamanlanmış çalıştırma", | ||
| 234 | (NoJobs, En) => "No jobs.", | 240 | (NoJobs, En) => "No jobs.", |
| 235 | (NoJobs, Tr) => "İş yok.", | 241 | (NoJobs, Tr) => "İş yok.", |
| 236 | (Newer, En) => "Newer", | 242 | (Newer, En) => "Newer", |
| @@ -565,6 +571,8 @@ mod tests { | |||
| 565 | K::Runs, | 571 | K::Runs, |
| 566 | K::NoRunsYet, | 572 | K::NoRunsYet, |
| 567 | K::NoRunsHint, | 573 | K::NoRunsHint, |
| 574 | + K::TriggerScheduled, | ||
| 575 | + K::NextScheduledRun, | ||
| 568 | K::NoJobs, | 576 | K::NoJobs, |
| 569 | K::Newer, | 577 | K::Newer, |
| 570 | K::Older, | 578 | K::Older, |
crates/forge-web/src/pages/ci_runs.rsmodified+74 -6
| @@ -298,6 +298,36 @@ pub(crate) async fn after_change(state: &AppState, run_id: &str, before: &[CiJob | |||
| 298 | Ok(()) | 298 | Ok(()) |
| 299 | } | 299 | } |
| 300 | 300 | ||
| 301 | +/// A job name as the timeline's label column can hold it: a matrix combination shows its values | ||
| 302 | +/// without the base name (the job list below groups them), and a long name is cut with an ellipsis. | ||
| 303 | +fn gantt_name(name: &str) -> String { | ||
| 304 | + const MAX_CHARS: usize = 14; | ||
| 305 | + let shown = name | ||
| 306 | + .split_once(" (") | ||
| 307 | + .map_or(name, |(_, rest)| rest.trim_end_matches(')')); | ||
| 308 | + if shown.chars().count() <= MAX_CHARS { | ||
| 309 | + return shown.to_owned(); | ||
| 310 | + } | ||
| 311 | + let head: String = shown.chars().take(MAX_CHARS - 1).collect(); | ||
| 312 | + format!("{head}\u{2026}") | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +/// How the run header names what started it. Scheduled runs read "scheduled"; the rest keep the | ||
| 316 | +/// stored word. | ||
| 317 | +fn trigger_text(lang: Lang, trigger: &str) -> String { | ||
| 318 | + match trigger { | ||
| 319 | + "schedule" => g::t(lang, K::TriggerScheduled).to_owned(), | ||
| 320 | + other => other.to_owned(), | ||
| 321 | + } | ||
| 322 | +} | ||
| 323 | + | ||
| 324 | +/// The next scheduled run as `2026-10-21 03:00 UTC`. | ||
| 325 | +fn next_run_text(at: i64) -> Option<String> { | ||
| 326 | + let when = time::OffsetDateTime::from_unix_timestamp(at).ok()?; | ||
| 327 | + let format = time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]"); | ||
| 328 | + Some(format!("{} UTC", when.format(&format).ok()?)) | ||
| 329 | +} | ||
| 330 | + | ||
| 301 | /// One run in the list. `bar` is its duration bar on the page's shared scale. | 331 | /// One run in the list. `bar` is its duration bar on the page's shared scale. |
| 302 | struct RunRow { | 332 | struct RunRow { |
| 303 | href: String, | 333 | href: String, |
| @@ -336,10 +366,18 @@ struct ListView { | |||
| 336 | newer_href: Option<String>, | 366 | newer_href: Option<String>, |
| 337 | older_href: Option<String>, | 367 | older_href: Option<String>, |
| 338 | page_label: String, | 368 | page_label: String, |
| 369 | + /// The next `[on] schedule` match of the default branch's workflow, as text. | ||
| 370 | + next_scheduled: Option<String>, | ||
| 339 | } | 371 | } |
| 340 | 372 | ||
| 341 | /// One job line under the timeline. Its link goes to the job page. | 373 | /// One job line under the timeline. Its link goes to the job page. |
| 342 | struct JobLine { | 374 | struct JobLine { |
| 375 | + /// A heading drawn above this line: the base name of a matrix job, on its first combination. | ||
| 376 | + group: Option<String>, | ||
| 377 | + /// The matrix job this line belongs to, to tell when a new group starts. | ||
| 378 | + group_of: Option<String>, | ||
| 379 | + /// The line is one combination of a matrix job, drawn under its heading. | ||
| 380 | + sub: bool, | ||
| 343 | href: String, | 381 | href: String, |
| 344 | name: String, | 382 | name: String, |
| 345 | dot: String, | 383 | dot: String, |
| @@ -833,7 +871,7 @@ fn gantt(jobs: &[Timing], origin: i64, run_end: Option<i64>, now: i64, lang: Lan | |||
| 833 | x: "0".to_owned(), | 871 | x: "0".to_owned(), |
| 834 | y: (row_mid(i) - 3).to_string(), | 872 | y: (row_mid(i) - 3).to_string(), |
| 835 | anchor: "start", | 873 | anchor: "start", |
| 836 | - text: job.name.clone(), | 874 | + text: gantt_name(&job.name), |
| 837 | ..Default::default() | 875 | ..Default::default() |
| 838 | }); | 876 | }); |
| 839 | if let Some(sub) = row_sub(job, lang) { | 877 | if let Some(sub) = row_sub(job, lang) { |
| @@ -1281,7 +1319,11 @@ async fn runs_split(cx: &Cx, number: Option<&str>) -> Result<SplitPage> { | |||
| 1281 | .iter() | 1319 | .iter() |
| 1282 | .zip(&timings) | 1320 | .zip(&timings) |
| 1283 | .map(|(run, jobs)| { | 1321 | .map(|(run, jobs)| { |
| 1284 | - let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); | 1322 | + let actor = if run.trigger == "schedule" { |
| 1323 | + String::new() | ||
| 1324 | + } else { | ||
| 1325 | + names.get(&run.actor_id).cloned().unwrap_or_default() | ||
| 1326 | + }; | ||
| 1285 | RunRow { | 1327 | RunRow { |
| 1286 | href: row_href(run.number), | 1328 | href: row_href(run.number), |
| 1287 | current: if selected.as_ref().is_some_and(|sel| sel.id == run.id) { | 1329 | 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<SplitPage> { | |||
| 1338 | }; | 1380 | }; |
| 1339 | let detail = match selected.as_ref() { | 1381 | let detail = match selected.as_ref() { |
| 1340 | Some(run) => { | 1382 | Some(run) => { |
| 1341 | - let actor = names.get(&run.actor_id).cloned().unwrap_or_default(); | 1383 | + let actor = if run.trigger == "schedule" { |
| 1384 | + String::new() | ||
| 1385 | + } else { | ||
| 1386 | + names.get(&run.actor_id).cloned().unwrap_or_default() | ||
| 1387 | + }; | ||
| 1342 | let subject = subjects | 1388 | let subject = subjects |
| 1343 | .get(&run.commit_oid) | 1389 | .get(&run.commit_oid) |
| 1344 | .cloned() | 1390 | .cloned() |
| @@ -1374,6 +1420,10 @@ async fn runs_split(cx: &Cx, number: Option<&str>) -> Result<SplitPage> { | |||
| 1374 | newer_href, | 1420 | newer_href, |
| 1375 | older_href, | 1421 | older_href, |
| 1376 | page_label: g::page_label(lang, page), | 1422 | page_label: g::page_label(lang, page), |
| 1423 | + next_scheduled: { | ||
| 1424 | + let schedules = crate::ci::schedule::schedules_of(state, &ctx.repo).await; | ||
| 1425 | + forge_ci::cron::next_after(&schedules, now).and_then(next_run_text) | ||
| 1426 | + }, | ||
| 1377 | }; | 1427 | }; |
| 1378 | let live = (page == 1).then(|| format!("{base}/events")); | 1428 | let live = (page == 1).then(|| format!("{base}/events")); |
| 1379 | let notice = notice_from_query(cx, lang); | 1429 | let notice = notice_from_query(cx, lang); |
| @@ -1443,13 +1493,24 @@ async fn run_detail( | |||
| 1443 | None if job.state == JobState::Queued => state_text(lang, job.state.as_str()), | 1493 | None if job.state == JobState::Queued => state_text(lang, job.state.as_str()), |
| 1444 | None => String::new(), | 1494 | None => String::new(), |
| 1445 | }; | 1495 | }; |
| 1496 | + let (base, variant) = match job.name.split_once(" (") { | ||
| 1497 | + Some((base, rest)) => (base, Some(rest.trim_end_matches(')'))), | ||
| 1498 | + None => (job.name.as_str(), None), | ||
| 1499 | + }; | ||
| 1500 | + let first = variant.is_some() | ||
| 1501 | + && lines | ||
| 1502 | + .last() | ||
| 1503 | + .is_none_or(|prev: &JobLine| prev.group_of.as_deref() != Some(base)); | ||
| 1446 | lines.push(JobLine { | 1504 | lines.push(JobLine { |
| 1447 | id: job.id.clone(), | 1505 | id: job.id.clone(), |
| 1448 | expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()), | 1506 | expanded: !tail.is_empty() && starts_expanded(job.state, jobs.len()), |
| 1449 | preview, | 1507 | preview, |
| 1450 | tail: tail.join("\n"), | 1508 | tail: tail.join("\n"), |
| 1509 | + group: first.then(|| base.to_owned()), | ||
| 1510 | + group_of: variant.map(|_| base.to_owned()), | ||
| 1511 | + sub: variant.is_some(), | ||
| 1451 | href: job_href(title, &job.id), | 1512 | href: job_href(title, &job.id), |
| 1452 | - name: job.name.clone(), | 1513 | + name: variant.unwrap_or(job.name.as_str()).to_owned(), |
| 1453 | dot: format!("ci-dot ci-{}", job.state.as_str()), | 1514 | dot: format!("ci-dot ci-{}", job.state.as_str()), |
| 1454 | detail: job.image.clone(), | 1515 | detail: job.image.clone(), |
| 1455 | rerun: (writer && job.state.is_terminal()) | 1516 | rerun: (writer && job.state.is_terminal()) |
| @@ -1477,7 +1538,7 @@ async fn run_detail( | |||
| 1477 | title: header.title, | 1538 | title: header.title, |
| 1478 | state: state_text(lang, run.state.as_str()), | 1539 | state: state_text(lang, run.state.as_str()), |
| 1479 | state_class: format!("ci-state ci-{}", run.state.as_str()), | 1540 | state_class: format!("ci-state ci-{}", run.state.as_str()), |
| 1480 | - trigger: run.trigger.clone(), | 1541 | + trigger: trigger_text(lang, &run.trigger), |
| 1481 | branch: short_ref(&run.git_ref).to_owned(), | 1542 | branch: short_ref(&run.git_ref).to_owned(), |
| 1482 | commit_href: format!("/{title}/commit/{}", run.commit_oid), | 1543 | commit_href: format!("/{title}/commit/{}", run.commit_oid), |
| 1483 | commit: short_oid(&run.commit_oid).to_owned(), | 1544 | commit: short_oid(&run.commit_oid).to_owned(), |
| @@ -1525,6 +1586,7 @@ async fn runs_body( | |||
| 1525 | newer_href, | 1586 | newer_href, |
| 1526 | older_href, | 1587 | older_href, |
| 1527 | page_label, | 1588 | page_label, |
| 1589 | + next_scheduled, | ||
| 1528 | } = list; | 1590 | } = list; |
| 1529 | let (fm, fs) = duration_templates(lang); | 1591 | let (fm, fs) = duration_templates(lang); |
| 1530 | Ok(view! { | 1592 | Ok(view! { |
| @@ -1581,6 +1643,9 @@ async fn runs_body( | |||
| 1581 | </details> | 1643 | </details> |
| 1582 | </div> | 1644 | </div> |
| 1583 | </div> | 1645 | </div> |
| 1646 | + if let Some(next) = next_scheduled.as_ref() { | ||
| 1647 | + <p class="ci-next muted small">(g::t(lang, K::NextScheduledRun)) ": " <time>(next.as_str())</time></p> | ||
| 1648 | + } | ||
| 1584 | if rows.is_empty() { | 1649 | if rows.is_empty() { |
| 1585 | <div class="ci-empty"> | 1650 | <div class="ci-empty"> |
| 1586 | <p>(g::t(lang, K::NoRunsYet))</p> | 1651 | <p>(g::t(lang, K::NoRunsYet))</p> |
| @@ -1707,7 +1772,10 @@ async fn runs_body( | |||
| 1707 | } | 1772 | } |
| 1708 | <ul class="ci-job-list"> | 1773 | <ul class="ci-job-list"> |
| 1709 | for job in run.jobs.iter() { | 1774 | for job in run.jobs.iter() { |
| 1710 | - <li data-job-row=(job.id.as_str()) data-open=(if job.expanded { "true" } else { "false" })> | 1775 | + if let Some(group) = job.group.as_ref() { |
| 1776 | + <li class="ci-job-group">(group.as_str())</li> | ||
| 1777 | + } | ||
| 1778 | + <li class=(job.sub.then_some("ci-job-sub")) data-job-row=(job.id.as_str()) data-open=(if job.expanded { "true" } else { "false" })> | ||
| 1711 | <div class="ci-job-item"> | 1779 | <div class="ci-job-item"> |
| 1712 | <a class="ci-job-line" href=(job.href.as_str())> | 1780 | <a class="ci-job-line" href=(job.href.as_str())> |
| 1713 | <span class=(job.dot.as_str())></span> | 1781 | <span class=(job.dot.as_str())></span> |
docs/ci.mdmodified+65 -0
| @@ -38,6 +38,7 @@ page and a `ci/config` status set to `error`. | |||
| 38 | | `pull_request` | bool | `false` | Start a run when a pull request is opened, updated or reopened. The config is read at the **head** commit. | | 38 | | `pull_request` | bool | `false` | Start a run when a pull request is opened, updated or reopened. The config is read at the **head** commit. | |
| 39 | | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. | | 39 | | `manual` | bool | `true` | Writers can start a run on an existing branch from the CI tab. | |
| 40 | | `cancel_superseded` | bool | `false` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). | | 40 | | `cancel_superseded` | bool | `false` | A push to a branch cancels the queued and running runs for older commits on that branch (see [Superseded runs](#superseded-runs)). | |
| 41 | +| `schedule` | array of string | `[]` | Cron expressions (5 fields, UTC). See [Scheduled runs](#scheduled-runs). Max 8. | | ||
| 41 | 42 | ||
| 42 | ### `[jobs.<name>]` | 43 | ### `[jobs.<name>]` |
| 43 | 44 | ||
| @@ -54,6 +55,7 @@ There must be at least one job, and at most 20. | |||
| 54 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | | 55 | | `runs_on` | array of string | `[]` | Runner labels. Every label must be present on the runner. | |
| 55 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | | 56 | | `cache` | array of string | `[]` | Workspace-relative directories to keep between runs. Max 8. See [Cache](#cache). | |
| 56 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | | 57 | | `timeout_minutes` | integer | `60` | Range 1 to 360. | |
| 58 | +| `matrix` | table | none | Expands the job into one job per combination. See [Matrix builds](#matrix-builds). | | ||
| 57 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | | 59 | | `network` | bool | `true` | `false` gives the job an empty network namespace (loopback only). `true` shares the runner host's network namespace. Read [the caveats](#builtin-executor-caveats). | |
| 58 | 60 | ||
| 59 | Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. | 61 | Job names match `^[a-z0-9][a-z0-9_-]{0,39}$`. |
| @@ -108,6 +110,69 @@ Artifacts are stored under the flattened name: `dist/forge` is stored as `dist_f | |||
| 108 | - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status | 110 | - Jobs whose `needs` fail or are skipped are marked `skipped`. A skipped job gets the status |
| 109 | `ci/<job>` = `error` with the description `skipped`. | 111 | `ci/<job>` = `error` with the description `skipped`. |
| 110 | 112 | ||
| 113 | +### Scheduled runs | ||
| 114 | + | ||
| 115 | +```toml | ||
| 116 | +[on] | ||
| 117 | +schedule = ["0 3 * * *", "30 12 * * 1"] | ||
| 118 | +``` | ||
| 119 | + | ||
| 120 | +Each entry is a standard 5-field cron expression, `minute hour day-of-month month day-of-week`, | ||
| 121 | +evaluated in **UTC**. A server-side scheduler checks once a minute. When an expression matched since | ||
| 122 | +its last check, it reads `.forge/ci.toml` from the head of the **default branch** and queues one run | ||
| 123 | +of that commit. The run's trigger is `schedule` (shown as "scheduled") and its ref is the default | ||
| 124 | +branch. | ||
| 125 | + | ||
| 126 | +- The config is read from the default branch at each tick, so a schedule change takes effect | ||
| 127 | + without a push, and a schedule on any other branch is ignored. | ||
| 128 | +- Catch-up happens at most once. If the forge was down across several matches, it queues a single | ||
| 129 | + run when it comes back, not one per missed match. | ||
| 130 | +- A repo is looked at for the first time from now on, so adding a schedule does not run anything | ||
| 131 | + until its next match. | ||
| 132 | +- Archived repos are skipped, and nothing is queued while CI is disabled in the server settings. | ||
| 133 | +- A `ci.toml` that does not parse queues no scheduled run. | ||
| 134 | +- The repo's CI page shows the next scheduled run, from the earliest match of all entries. | ||
| 135 | +- An expression with 6 fields (seconds) is rejected. Use `*/5 * * * *` for the fastest practical | ||
| 136 | + rate; there is no minimum interval, so a `* * * * *` schedule queues a run every minute. | ||
| 137 | + | ||
| 138 | +### Matrix builds | ||
| 139 | + | ||
| 140 | +```toml | ||
| 141 | +[jobs.test] | ||
| 142 | +image = "docker.io/rust:${{ matrix.rust }}" | ||
| 143 | +run = "cargo +${{ matrix.rust }} test --target $MATRIX_TARGET" | ||
| 144 | +matrix = { rust = ["stable", "1.85"], target = ["x86_64", "aarch64"] } | ||
| 145 | +``` | ||
| 146 | + | ||
| 147 | +A job with `matrix` is expanded when the file is parsed, into one job per combination of the axis | ||
| 148 | +values (here 4). The jobs are named `test (1.85, aarch64)`, `test (1.85, x86_64)`, | ||
| 149 | +`test (stable, aarch64)` and `test (stable, x86_64)`: the values joined with `, `, with the axes | ||
| 150 | +in alphabetical order of their names. Each one is an ordinary job, with its own log, status | ||
| 151 | +(`ci/test (stable, x86_64)`) and runner. The run page lists them together under the base name. | ||
| 152 | + | ||
| 153 | +- Axis names match `^[a-z][a-z0-9_]{0,31}$`. Values are strings, integers or booleans (read as | ||
| 154 | + text), 1 to 64 characters, with no control characters, commas or parentheses. | ||
| 155 | +- Every combination gets the env vars `MATRIX_<KEY>` (the axis name in upper case), for example | ||
| 156 | + `MATRIX_RUST=stable`. A matrix value overrides an `env` entry with the same name. | ||
| 157 | +- `${{ matrix.key }}` and the shorter `${matrix.key}` are replaced in `image`, `run` and `runs_on`. | ||
| 158 | + A key that is not an axis (or an `include` key) is an error. Any other `${...}`, such as | ||
| 159 | + `${HOME}`, is left to the shell. | ||
| 160 | +- `exclude` is a list of tables. A combination that agrees on every key of an entry is dropped. | ||
| 161 | + An entry may name just one axis, which drops every combination with that value. | ||
| 162 | +- `include` is a list of tables. Each adds one combination, so it must set every axis, and it may | ||
| 163 | + carry more keys, which become `MATRIX_<KEY>` env vars too but are not part of the job name. An | ||
| 164 | + entry that repeats an existing combination adds nothing. | ||
| 165 | + | ||
| 166 | + ```toml | ||
| 167 | + matrix = { rust = ["stable", "1.85"], target = ["x86_64", "aarch64"], exclude = [{ rust = "1.85", target = "aarch64" }], include = [{ rust = "nightly", target = "x86_64", flag = "-Zunstable" }] } | ||
| 168 | + ``` | ||
| 169 | + | ||
| 170 | +- `needs = ["test"]` on another job waits for **all** combinations of `test`. A matrix job's own | ||
| 171 | + `needs` apply to each of its combinations. | ||
| 172 | +- `[release] assets = ["test:*.tar"]` selects the artifacts of every combination of `test`. | ||
| 173 | +- The 20 job limit counts expanded jobs. A matrix that alone expands past it, or a workflow that | ||
| 174 | + reaches it through expansion, is rejected with an error that names the job and the count. | ||
| 175 | + | ||
| 111 | ### Fail fast | 176 | ### Fail fast |
| 112 | 177 | ||
| 113 | When a job fails or errors, the forge cancels every other job in the run at once: queued and | 178 | When a job fails or errors, the forge cancels every other job in the run at once: queued and |
style/main.scssmodified+19 -0
| @@ -4411,6 +4411,10 @@ $ansi-colours: ( | |||
| 4411 | color: var(--muted); | 4411 | color: var(--muted); |
| 4412 | } | 4412 | } |
| 4413 | 4413 | ||
| 4414 | +.ci-next { | ||
| 4415 | + margin: 0 0 8px; | ||
| 4416 | +} | ||
| 4417 | + | ||
| 4414 | .ci-empty { | 4418 | .ci-empty { |
| 4415 | padding: 40px 16px; | 4419 | padding: 40px 16px; |
| 4416 | text-align: center; | 4420 | text-align: center; |
| @@ -4755,6 +4759,21 @@ $ansi-colours: ( | |||
| 4755 | } | 4759 | } |
| 4756 | } | 4760 | } |
| 4757 | 4761 | ||
| 4762 | +// A matrix job's combinations sit under one heading with the base name. | ||
| 4763 | +.ci-job-list .ci-job-group { | ||
| 4764 | + padding: 8px 6px 2px; | ||
| 4765 | + font-size: 0.75rem; | ||
| 4766 | + font-weight: 600; | ||
| 4767 | + letter-spacing: 0.06em; | ||
| 4768 | + text-transform: uppercase; | ||
| 4769 | + color: var(--muted); | ||
| 4770 | + border-bottom: 0; | ||
| 4771 | +} | ||
| 4772 | + | ||
| 4773 | +.ci-job-sub .ci-job-line { | ||
| 4774 | + padding-left: 18px; | ||
| 4775 | +} | ||
| 4776 | + | ||
| 4758 | .ci-job-line { | 4777 | .ci-job-line { |
| 4759 | display: grid; | 4778 | display: grid; |
| 4760 | grid-template-columns: 8px minmax(0, 1fr) auto auto 12px; | 4779 | grid-template-columns: 8px minmax(0, 1fr) auto auto 12px; |