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; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Decision { Idle, Forget, Fire, Advance, } 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, } } pub fn nap_secs(now: i64) -> u64 { u64::try_from(61 - now.rem_euclid(60)).unwrap_or(60) } 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; } } 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 => { 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; 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); 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); assert_eq!(decide(&s, Some(fire_at), fire_at + 60), Decision::Advance); } #[test] fn downtime_catches_up_at_most_once() { let s = schedules(&["* * * * *"]); 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() } 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"); 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" ); assert_eq!(tick(&state, NOON + 3600).await, 0); 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); 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 ); } }