forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·8.8 MiB·7e521ed·Tahinli·2 hours ago·329 commits
| 1 | use std::time::Duration; |
| 2 | |
| 3 | use forge_ci::cron; |
| 4 | use forge_core::Repo; |
| 5 | |
| 6 | use super::schedule::{Loaded, default_head_config, scheduled_run}; |
| 7 | use crate::state::AppState; |
| 8 | |
| 9 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 10 | pub enum Decision { |
| 11 | Idle, |
| 12 | Forget, |
| 13 | Fire, |
| 14 | Advance, |
| 15 | } |
| 16 | |
| 17 | pub fn decide(schedules: &[String], last: Option<i64>, now: i64) -> Decision { |
| 18 | if schedules.is_empty() { |
| 19 | return if last.is_some() { |
| 20 | Decision::Forget |
| 21 | } else { |
| 22 | Decision::Idle |
| 23 | }; |
| 24 | } |
| 25 | match last { |
| 26 | Some(last) if cron::fired_between(schedules, last, now) => Decision::Fire, |
| 27 | _ => Decision::Advance, |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | pub fn nap_secs(now: i64) -> u64 { |
| 32 | u64::try_from(61 - now.rem_euclid(60)).unwrap_or(60) |
| 33 | } |
| 34 | |
| 35 | pub fn spawn(state: AppState) { |
| 36 | tokio::spawn(run(state)); |
| 37 | } |
| 38 | |
| 39 | async fn run(state: AppState) { |
| 40 | loop { |
| 41 | tick(&state, crate::raw::now_unix()).await; |
| 42 | tokio::time::sleep(Duration::from_secs(nap_secs(crate::raw::now_unix()))).await; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | pub async fn tick(state: &AppState, now: i64) -> usize { |
| 47 | if !state.live().ci.enabled { |
| 48 | return 0; |
| 49 | } |
| 50 | let repos = match state.store.repos_for_ci_schedule().await { |
| 51 | Ok(repos) => repos, |
| 52 | Err(e) => { |
| 53 | tracing::error!(error = %e, "ci: listing repos for the scheduler failed"); |
| 54 | return 0; |
| 55 | } |
| 56 | }; |
| 57 | let mut queued = 0; |
| 58 | for repo in &repos { |
| 59 | match tick_repo(state, repo, now).await { |
| 60 | Ok(true) => queued += 1, |
| 61 | Ok(false) => {} |
| 62 | Err(e) => { |
| 63 | tracing::error!(error = %e, repo_id = %repo.id, "ci: scheduled run failed"); |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | queued |
| 68 | } |
| 69 | |
| 70 | async fn tick_repo(state: &AppState, repo: &Repo, now: i64) -> forge_core::Result<bool> { |
| 71 | let last = state.store.ci_schedule_last_tick(&repo.id).await?; |
| 72 | let head = default_head_config(state, repo).await; |
| 73 | let schedules = match &head { |
| 74 | Some((_, Loaded::Valid(cfg))) => cfg.on.schedule.clone(), |
| 75 | _ => Vec::new(), |
| 76 | }; |
| 77 | match decide(&schedules, last, now) { |
| 78 | Decision::Idle => Ok(false), |
| 79 | Decision::Forget => { |
| 80 | state.store.clear_ci_schedule(&repo.id).await?; |
| 81 | Ok(false) |
| 82 | } |
| 83 | Decision::Advance => { |
| 84 | state.store.set_ci_schedule_last_tick(&repo.id, now).await?; |
| 85 | Ok(false) |
| 86 | } |
| 87 | Decision::Fire => { |
| 88 | let Some((commit, loaded)) = head else { |
| 89 | return Ok(false); |
| 90 | }; |
| 91 | let run = scheduled_run(state, repo, &commit, loaded).await?; |
| 92 | state.store.set_ci_schedule_last_tick(&repo.id, now).await?; |
| 93 | Ok(run.is_some()) |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | #[cfg(test)] |
| 99 | mod tests { |
| 100 | use std::io::Write; |
| 101 | use std::path::Path; |
| 102 | |
| 103 | use forge_core::Visibility; |
| 104 | use forge_git::repo::{init_bare, repo_path}; |
| 105 | |
| 106 | use super::*; |
| 107 | use crate::test_support::test_state; |
| 108 | |
| 109 | const NOON: i64 = 1_791_979_200; |
| 110 | const DAILY_3: [&str; 1] = ["0 3 * * *"]; |
| 111 | |
| 112 | fn schedules(list: &[&str]) -> Vec<String> { |
| 113 | list.iter().map(|s| (*s).to_owned()).collect() |
| 114 | } |
| 115 | |
| 116 | #[test] |
| 117 | fn a_repo_seen_first_starts_from_now() { |
| 118 | assert_eq!( |
| 119 | decide(&schedules(&DAILY_3), None, NOON), |
| 120 | Decision::Advance, |
| 121 | "no catch-up for a schedule nobody has seen" |
| 122 | ); |
| 123 | } |
| 124 | |
| 125 | #[test] |
| 126 | fn fires_once_when_a_tick_falls_in_the_window() { |
| 127 | let s = schedules(&DAILY_3); |
| 128 | let fire_at = NOON + 15 * 3600; |
| 129 | assert_eq!(decide(&s, Some(NOON), fire_at - 1), Decision::Advance); |
| 130 | assert_eq!(decide(&s, Some(NOON), fire_at), Decision::Fire); |
| 131 | assert_eq!(decide(&s, Some(fire_at), fire_at + 60), Decision::Advance); |
| 132 | } |
| 133 | |
| 134 | #[test] |
| 135 | fn downtime_catches_up_at_most_once() { |
| 136 | let s = schedules(&["* * * * *"]); |
| 137 | let back = NOON + 7 * 86_400; |
| 138 | assert_eq!(decide(&s, Some(NOON), back), Decision::Fire); |
| 139 | assert_eq!(decide(&s, Some(back), back + 30), Decision::Advance); |
| 140 | assert_eq!(decide(&s, Some(back), back + 60), Decision::Fire); |
| 141 | } |
| 142 | |
| 143 | #[test] |
| 144 | fn a_removed_schedule_is_forgotten() { |
| 145 | assert_eq!(decide(&[], Some(NOON), NOON), Decision::Forget); |
| 146 | assert_eq!(decide(&[], None, NOON), Decision::Idle); |
| 147 | } |
| 148 | |
| 149 | #[test] |
| 150 | fn naps_land_just_after_the_minute() { |
| 151 | assert_eq!(nap_secs(NOON), 61); |
| 152 | assert_eq!(nap_secs(NOON + 59), 2); |
| 153 | assert_eq!(nap_secs(NOON + 1), 60); |
| 154 | } |
| 155 | |
| 156 | fn git(bare: &Path, args: &[&str], stdin: &str) -> String { |
| 157 | let mut child = std::process::Command::new("git") |
| 158 | .arg("--git-dir") |
| 159 | .arg(bare) |
| 160 | .args(args) |
| 161 | .env("GIT_AUTHOR_NAME", "tahinli") |
| 162 | .env("GIT_AUTHOR_EMAIL", "tahinli@example.com") |
| 163 | .env("GIT_COMMITTER_NAME", "tahinli") |
| 164 | .env("GIT_COMMITTER_EMAIL", "tahinli@example.com") |
| 165 | .stdin(std::process::Stdio::piped()) |
| 166 | .stdout(std::process::Stdio::piped()) |
| 167 | .stderr(std::process::Stdio::piped()) |
| 168 | .spawn() |
| 169 | .expect("spawn git"); |
| 170 | child |
| 171 | .stdin |
| 172 | .take() |
| 173 | .expect("stdin") |
| 174 | .write_all(stdin.as_bytes()) |
| 175 | .expect("write stdin"); |
| 176 | let out = child.wait_with_output().expect("git output"); |
| 177 | assert!(out.status.success(), "git {args:?}"); |
| 178 | String::from_utf8(out.stdout) |
| 179 | .expect("utf8") |
| 180 | .trim() |
| 181 | .to_owned() |
| 182 | } |
| 183 | |
| 184 | fn commit_config(bare: &Path, text: &str) { |
| 185 | let blob = git(bare, &["hash-object", "-w", "--stdin"], text); |
| 186 | let forge = git(bare, &["mktree"], &format!("100644 blob {blob}\tci.toml\n")); |
| 187 | let root = git(bare, &["mktree"], &format!("040000 tree {forge}\t.forge\n")); |
| 188 | let commit = git(bare, &["commit-tree", root.as_str(), "-m", "ci config"], ""); |
| 189 | git( |
| 190 | bare, |
| 191 | &["update-ref", "refs/heads/main", commit.as_str()], |
| 192 | "", |
| 193 | ); |
| 194 | } |
| 195 | |
| 196 | const WORKFLOW: &str = |
| 197 | "[on]\nschedule = [\"0 3 * * *\"]\n[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n"; |
| 198 | |
| 199 | #[tokio::test] |
| 200 | async fn ticks_queue_one_schedule_run_and_skip_archived_repos() { |
| 201 | let dir = tempfile::tempdir().expect("tempdir"); |
| 202 | let state = test_state(dir.path()).await; |
| 203 | let store = state.store.clone(); |
| 204 | let tahinli = store |
| 205 | .create_user("tahinli", None, "unused", false) |
| 206 | .await |
| 207 | .expect("user"); |
| 208 | let mut repos = Vec::new(); |
| 209 | for name in ["live", "old"] { |
| 210 | let repo = store |
| 211 | .create_repo(&tahinli.id, name, "", Visibility::Private, "main") |
| 212 | .await |
| 213 | .expect("repo"); |
| 214 | let bare = repo_path(&state.git.data_dir, &repo.id).expect("path"); |
| 215 | init_bare(&state.git, &bare, "main").await.expect("init"); |
| 216 | commit_config(&bare, WORKFLOW); |
| 217 | repos.push(repo); |
| 218 | } |
| 219 | store |
| 220 | .set_repo_archived(&repos[1].id, true) |
| 221 | .await |
| 222 | .expect("archive"); |
| 223 | |
| 224 | assert_eq!(tick(&state, NOON).await, 0); |
| 225 | assert_eq!( |
| 226 | store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), |
| 227 | Some(NOON) |
| 228 | ); |
| 229 | assert_eq!( |
| 230 | store.ci_schedule_last_tick(&repos[1].id).await.unwrap(), |
| 231 | None, |
| 232 | "archived repos are skipped" |
| 233 | ); |
| 234 | assert_eq!(tick(&state, NOON + 3600).await, 0); |
| 235 | let later = NOON + 3 * 86_400; |
| 236 | assert_eq!(tick(&state, later).await, 1); |
| 237 | assert_eq!(tick(&state, later + 60).await, 0); |
| 238 | let (runs, total) = store.list_runs(&repos[0].id, 1, 25).await.unwrap(); |
| 239 | assert_eq!(total, 1); |
| 240 | assert_eq!(runs[0].trigger, "schedule"); |
| 241 | assert_eq!(runs[0].git_ref, "refs/heads/main"); |
| 242 | let (_, archived_total) = store.list_runs(&repos[1].id, 1, 25).await.unwrap(); |
| 243 | assert_eq!(archived_total, 0); |
| 244 | |
| 245 | commit_config( |
| 246 | &repo_path(&state.git.data_dir, &repos[0].id).unwrap(), |
| 247 | "[jobs.nightly]\nimage = \"img\"\nrun = \"true\"\n", |
| 248 | ); |
| 249 | assert_eq!(tick(&state, later + 120).await, 0); |
| 250 | assert_eq!( |
| 251 | store.ci_schedule_last_tick(&repos[0].id).await.unwrap(), |
| 252 | None |
| 253 | ); |
| 254 | } |
| 255 | } |