| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use std::path::{Path, PathBuf}; |
| 6 | |
| 7 | use forge_core::Repo; |
| 8 | use forge_core::ci::{CiJob, CiRun, JobState, RunState}; |
| 9 | use forge_core::store::commit_status::StatusState; |
| 10 | |
| 11 | use crate::state::AppState; |
| 12 | |
| 13 | pub mod api; |
| 14 | pub mod live; |
| 15 | pub mod metrics_chart; |
| 16 | pub mod reaper; |
| 17 | pub mod release; |
| 18 | pub mod runner_log; |
| 19 | pub mod runner_metrics; |
| 20 | pub mod schedule; |
| 21 | pub mod scheduled; |
| 22 | |
| 23 | pub use live::CiLive; |
| 24 | pub use schedule::{manual_run, on_pull_event, on_ref_update}; |
| 25 | |
| 26 | |
| 27 | const MAX_DESCRIPTION: usize = 140; |
| 28 | |
| 29 | |
| 30 | pub fn log_path(data_dir: &Path, job_id: &str) -> PathBuf { |
| 31 | data_dir |
| 32 | .join("ci") |
| 33 | .join("logs") |
| 34 | .join(format!("{job_id}.log")) |
| 35 | } |
| 36 | |
| 37 | |
| 38 | pub fn artifact_key(artifact_id: &str) -> String { |
| 39 | format!("ci/{artifact_id}") |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | pub async fn sync_status(state: &AppState, run: &CiRun, job: &CiJob) { |
| 45 | let repo = match state.store.repo_by_id(&run.repo_id).await { |
| 46 | Ok(Some(repo)) => repo, |
| 47 | Ok(None) => return, |
| 48 | Err(e) => { |
| 49 | tracing::error!(error = %e, run_id = %run.id, "ci: loading repo for status failed"); |
| 50 | return; |
| 51 | } |
| 52 | }; |
| 53 | let (status, description) = status_for(run, job); |
| 54 | let url = format!( |
| 55 | "{}/{}/{}/ci/jobs/{}", |
| 56 | state.config.base_url.trim_end_matches('/'), |
| 57 | repo.owner_name, |
| 58 | repo.name, |
| 59 | job.id |
| 60 | ); |
| 61 | publish( |
| 62 | state, |
| 63 | &repo, |
| 64 | run, |
| 65 | &format!("ci/{}", job.name), |
| 66 | status, |
| 67 | &description, |
| 68 | &url, |
| 69 | ) |
| 70 | .await; |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | pub async fn sync_run_statuses(state: &AppState, run: &CiRun) -> forge_core::Result<bool> { |
| 76 | let jobs = state.store.jobs_for_run(&run.id).await?; |
| 77 | let mut queued = false; |
| 78 | for job in &jobs { |
| 79 | sync_status(state, run, job).await; |
| 80 | queued |= matches!(job.state, JobState::Queued); |
| 81 | } |
| 82 | Ok(queued) |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | pub async fn publish( |
| 88 | state: &AppState, |
| 89 | repo: &Repo, |
| 90 | run: &CiRun, |
| 91 | context: &str, |
| 92 | status: StatusState, |
| 93 | description: &str, |
| 94 | target_url: &str, |
| 95 | ) { |
| 96 | let Some(creator) = status_creator(state, repo, &run.actor_id).await else { |
| 97 | tracing::error!(run_id = %run.id, context, "ci: no person to record the status for"); |
| 98 | return; |
| 99 | }; |
| 100 | let description = short(description); |
| 101 | if let Err(e) = state |
| 102 | .store |
| 103 | .set_status( |
| 104 | &repo.id, |
| 105 | &run.commit_oid, |
| 106 | context, |
| 107 | status, |
| 108 | Some(&description), |
| 109 | Some(target_url), |
| 110 | &creator, |
| 111 | ) |
| 112 | .await |
| 113 | { |
| 114 | tracing::error!(error = %e, run_id = %run.id, context, "ci: writing commit status failed"); |
| 115 | return; |
| 116 | } |
| 117 | state |
| 118 | .live |
| 119 | .bump(&crate::live::Topic::CommitStatuses(repo.id.clone())); |
| 120 | crate::automerge::on_status(state, &repo.id, &run.commit_oid).await; |
| 121 | |
| 122 | Box::pin(crate::merge_queue::on_status(state, repo, &run.commit_oid)).await; |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | async fn status_creator(state: &AppState, repo: &Repo, actor_id: &str) -> Option<String> { |
| 129 | let candidate = if actor_id.is_empty() { |
| 130 | repo.owner_id.clone() |
| 131 | } else { |
| 132 | actor_id.to_owned() |
| 133 | }; |
| 134 | match state.store.user_by_id(&candidate).await { |
| 135 | Ok(Some(user)) if !user.is_org() => Some(candidate), |
| 136 | _ => state |
| 137 | .store |
| 138 | .ensure_ghost_user() |
| 139 | .await |
| 140 | .ok() |
| 141 | .map(|ghost| ghost.id), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | |
| 146 | fn status_for(run: &CiRun, job: &CiJob) -> (StatusState, String) { |
| 147 | let message = |fallback: &str| job.message.clone().unwrap_or_else(|| fallback.to_owned()); |
| 148 | match job.state { |
| 149 | JobState::Blocked => { |
| 150 | let why = if matches!(run.state, RunState::WaitingApproval) { |
| 151 | "Waiting for approval" |
| 152 | } else { |
| 153 | "Waiting for other jobs" |
| 154 | }; |
| 155 | (StatusState::Pending, why.to_owned()) |
| 156 | } |
| 157 | JobState::Queued => (StatusState::Pending, "Queued".to_owned()), |
| 158 | JobState::Running => (StatusState::Pending, "Running".to_owned()), |
| 159 | JobState::Success => (StatusState::Success, "Succeeded".to_owned()), |
| 160 | JobState::Failure => (StatusState::Failure, "Failed".to_owned()), |
| 161 | JobState::Cancelled => (StatusState::Error, message("Cancelled")), |
| 162 | JobState::Error => (StatusState::Error, message("Errored")), |
| 163 | JobState::Skipped => (StatusState::Error, "skipped".to_owned()), |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | |
| 168 | fn short(text: &str) -> String { |
| 169 | text.lines() |
| 170 | .next() |
| 171 | .unwrap_or_default() |
| 172 | .chars() |
| 173 | .take(MAX_DESCRIPTION) |
| 174 | .collect() |
| 175 | } |
| 176 | |
| 177 | |
| 178 | |
| 179 | pub async fn after_change(state: &AppState, run_id: &str, before: &[CiJob]) -> topcoat::Result<()> { |
| 180 | state.ci_waker.notify_waiters(); |
| 181 | let Some(run) = state.store.run_by_id(run_id).await? else { |
| 182 | return Ok(()); |
| 183 | }; |
| 184 | state.ci_live.bump_run(run_id); |
| 185 | state.ci_live.bump_repo(&run.repo_id); |
| 186 | for job in state.store.jobs_for_run(run_id).await? { |
| 187 | |
| 188 | let changed = before |
| 189 | .iter() |
| 190 | .find(|old| old.id == job.id) |
| 191 | .is_none_or(|old| { |
| 192 | old.state != job.state || old.cancel_requested != job.cancel_requested |
| 193 | }); |
| 194 | if changed { |
| 195 | if job.state.is_terminal() { |
| 196 | state.ci_live.close_job(&job.id); |
| 197 | } else { |
| 198 | state.ci_live.bump_job(&job.id); |
| 199 | } |
| 200 | sync_status(state, &run, &job).await; |
| 201 | } |
| 202 | } |
| 203 | Ok(()) |
| 204 | } |
| 205 | |
| 206 | #[cfg(test)] |
| 207 | mod org_tests { |
| 208 | use super::*; |
| 209 | use forge_core::Visibility; |
| 210 | |
| 211 | |
| 212 | |
| 213 | #[tokio::test] |
| 214 | async fn an_org_never_is_the_status_creator() { |
| 215 | let dir = tempfile::tempdir().unwrap(); |
| 216 | let state = crate::test_support::test_state(dir.path()).await; |
| 217 | let tahinli = state |
| 218 | .store |
| 219 | .create_user("tahinli", None, "h", false) |
| 220 | .await |
| 221 | .unwrap(); |
| 222 | let org = state.store.create_org("acme", &tahinli.id).await.unwrap(); |
| 223 | let repo = state |
| 224 | .store |
| 225 | .create_repo(&org.id, "proj", "", Visibility::Private, "main") |
| 226 | .await |
| 227 | .unwrap(); |
| 228 | let ghost = state.store.ensure_ghost_user().await.unwrap(); |
| 229 | |
| 230 | assert_eq!( |
| 231 | status_creator(&state, &repo, &tahinli.id).await, |
| 232 | Some(tahinli.id.clone()) |
| 233 | ); |
| 234 | assert_eq!( |
| 235 | status_creator(&state, &repo, &org.id).await, |
| 236 | Some(ghost.id.clone()) |
| 237 | ); |
| 238 | assert_eq!(status_creator(&state, &repo, "").await, Some(ghost.id)); |
| 239 | } |
| 240 | } |