forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

mod.rs240 lines, 8.0 KiBHistoryRawDownload
1//! Continuous integration on the forge side: schedules runs for pushes, tags, pull requests and
2//! manual requests (`schedule`), reaps jobs whose runner went silent (`reaper`), and mirrors job
3//! states into commit statuses (`sync_status`). The workflow file is `.forge/ci.toml`.
4
5use std::path::{Path, PathBuf};
6
7use forge_core::Repo;
8use forge_core::ci::{CiJob, CiRun, JobState, RunState};
9use forge_core::store::commit_status::StatusState;
10
11use crate::state::AppState;
12
13pub mod api;
14pub mod live;
15pub mod metrics_chart;
16pub mod reaper;
17pub mod release;
18pub mod runner_log;
19pub mod runner_metrics;
20pub mod schedule;
21pub mod scheduled;
22
23pub use live::CiLive;
24pub use schedule::{manual_run, on_pull_event, on_ref_update};
25
26/// Longest status description written, in characters. Longer text is cut.
27const MAX_DESCRIPTION: usize = 140;
28
29/// Where the log of job `job_id` is kept: `<data_dir>/ci/logs/<job_id>.log`.
30pub 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/// The blob store key of artifact `artifact_id`.
38pub fn artifact_key(artifact_id: &str) -> String {
39 format!("ci/{artifact_id}")
40}
41
42/// Sets the `ci/<job>` commit status of `job` to match its state. A failed write is logged and
43/// never fails the caller.
44pub 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/// Syncs the status of every job of `run`. Returns whether any job is Queued, so the caller knows
74/// to wake the runner claims.
75pub 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/// Writes one commit status for `run`. The creator is the run's actor, or the repo owner for a
86/// system run (the status table references users).
87pub 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 // Boxed: a queue advance can start the next candidate's run, which publishes again.
122 Box::pin(crate::merge_queue::on_status(state, repo, &run.commit_oid)).await;
123}
124
125/// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.
126/// An organization never acts, so an org owner (or a missing user) falls back to the ghost
127/// account. `None` only when even the ghost account cannot be read or created.
128async 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/// The commit status state and description for a job.
146fn 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/// The first line of `text`, cut to `MAX_DESCRIPTION` characters.
168fn short(text: &str) -> String {
169 text.lines()
170 .next()
171 .unwrap_or_default()
172 .chars()
173 .take(MAX_DESCRIPTION)
174 .collect()
175}
176
177/// Wakes the job queue and syncs the commit status of every job whose state changed since `before`.
178/// A job missing from `before` (a fresh run) counts as changed.
179pub 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 // A cancel request on a running job changes no state, but its row shows "stopping".
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)]
207mod org_tests {
208 use super::*;
209 use forge_core::Visibility;
210
211 /// A status is recorded for a person. An org actor, or an org owner of a system run, falls
212 /// back to the ghost account.
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}