forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBb00f3f4Tahinli1 month ago147 commits

mod.rs208 lines, 6.8 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 reaper;
16pub mod release;
17pub mod schedule;
18pub mod scheduled;
19
20pub use live::CiLive;
21pub use schedule::{manual_run, on_pull_event, on_ref_update};
22
23/// Longest status description written, in characters. Longer text is cut.
24const MAX_DESCRIPTION: usize = 140;
25
26/// Where the log of job `job_id` is kept: `<data_dir>/ci/logs/<job_id>.log`.
27pub fn log_path(data_dir: &Path, job_id: &str) -> PathBuf {
28 data_dir
29 .join("ci")
30 .join("logs")
31 .join(format!("{job_id}.log"))
32}
33
34/// The blob store key of artifact `artifact_id`.
35pub fn artifact_key(artifact_id: &str) -> String {
36 format!("ci/{artifact_id}")
37}
38
39/// Sets the `ci/<job>` commit status of `job` to match its state. A failed write is logged and
40/// never fails the caller.
41pub async fn sync_status(state: &AppState, run: &CiRun, job: &CiJob) {
42 let repo = match state.store.repo_by_id(&run.repo_id).await {
43 Ok(Some(repo)) => repo,
44 Ok(None) => return,
45 Err(e) => {
46 tracing::error!(error = %e, run_id = %run.id, "ci: loading repo for status failed");
47 return;
48 }
49 };
50 let (status, description) = status_for(run, job);
51 let url = format!(
52 "{}/{}/{}/ci/jobs/{}",
53 state.config.base_url.trim_end_matches('/'),
54 repo.owner_name,
55 repo.name,
56 job.id
57 );
58 publish(
59 state,
60 &repo,
61 run,
62 &format!("ci/{}", job.name),
63 status,
64 &description,
65 &url,
66 )
67 .await;
68}
69
70/// Syncs the status of every job of `run`. Returns whether any job is Queued, so the caller knows
71/// to wake the runner claims.
72pub async fn sync_run_statuses(state: &AppState, run: &CiRun) -> forge_core::Result<bool> {
73 let jobs = state.store.jobs_for_run(&run.id).await?;
74 let mut queued = false;
75 for job in &jobs {
76 sync_status(state, run, job).await;
77 queued |= matches!(job.state, JobState::Queued);
78 }
79 Ok(queued)
80}
81
82/// Writes one commit status for `run`. The creator is the run's actor, or the repo owner for a
83/// system run (the status table references users).
84pub(crate) async fn publish(
85 state: &AppState,
86 repo: &Repo,
87 run: &CiRun,
88 context: &str,
89 status: StatusState,
90 description: &str,
91 target_url: &str,
92) {
93 let Some(creator) = status_creator(state, repo, &run.actor_id).await else {
94 tracing::error!(run_id = %run.id, context, "ci: no person to record the status for");
95 return;
96 };
97 let description = short(description);
98 if let Err(e) = state
99 .store
100 .set_status(
101 &repo.id,
102 &run.commit_oid,
103 context,
104 status,
105 Some(&description),
106 Some(target_url),
107 &creator,
108 )
109 .await
110 {
111 tracing::error!(error = %e, run_id = %run.id, context, "ci: writing commit status failed");
112 return;
113 }
114 state
115 .live
116 .bump(&crate::live::Topic::CommitStatuses(repo.id.clone()));
117 crate::automerge::on_status(state, &repo.id, &run.commit_oid).await;
118 // Boxed: a queue advance can start the next candidate's run, which publishes again.
119 Box::pin(crate::merge_queue::on_status(state, repo, &run.commit_oid)).await;
120}
121
122/// The person a CI status is recorded for: the run's actor, or the repo owner for a system run.
123/// An organization never acts, so an org owner (or a missing user) falls back to the ghost
124/// account. `None` only when even the ghost account cannot be read or created.
125async fn status_creator(state: &AppState, repo: &Repo, actor_id: &str) -> Option<String> {
126 let candidate = if actor_id.is_empty() {
127 repo.owner_id.clone()
128 } else {
129 actor_id.to_owned()
130 };
131 match state.store.user_by_id(&candidate).await {
132 Ok(Some(user)) if !user.is_org() => Some(candidate),
133 _ => state
134 .store
135 .ensure_ghost_user()
136 .await
137 .ok()
138 .map(|ghost| ghost.id),
139 }
140}
141
142/// The commit status state and description for a job.
143fn status_for(run: &CiRun, job: &CiJob) -> (StatusState, String) {
144 let message = |fallback: &str| job.message.clone().unwrap_or_else(|| fallback.to_owned());
145 match job.state {
146 JobState::Blocked => {
147 let why = if matches!(run.state, RunState::WaitingApproval) {
148 "Waiting for approval"
149 } else {
150 "Waiting for other jobs"
151 };
152 (StatusState::Pending, why.to_owned())
153 }
154 JobState::Queued => (StatusState::Pending, "Queued".to_owned()),
155 JobState::Running => (StatusState::Pending, "Running".to_owned()),
156 JobState::Success => (StatusState::Success, "Succeeded".to_owned()),
157 JobState::Failure => (StatusState::Failure, "Failed".to_owned()),
158 JobState::Cancelled => (StatusState::Error, message("Cancelled")),
159 JobState::Error => (StatusState::Error, message("Errored")),
160 JobState::Skipped => (StatusState::Error, "skipped".to_owned()),
161 }
162}
163
164/// The first line of `text`, cut to `MAX_DESCRIPTION` characters.
165fn short(text: &str) -> String {
166 text.lines()
167 .next()
168 .unwrap_or_default()
169 .chars()
170 .take(MAX_DESCRIPTION)
171 .collect()
172}
173
174#[cfg(test)]
175mod org_tests {
176 use super::*;
177 use forge_core::Visibility;
178
179 /// A status is recorded for a person. An org actor, or an org owner of a system run, falls
180 /// back to the ghost account.
181 #[tokio::test]
182 async fn an_org_never_is_the_status_creator() {
183 let dir = tempfile::tempdir().unwrap();
184 let state = crate::test_support::test_state(dir.path()).await;
185 let tahinli = state
186 .store
187 .create_user("tahinli", None, "h", false)
188 .await
189 .unwrap();
190 let org = state.store.create_org("acme", &tahinli.id).await.unwrap();
191 let repo = state
192 .store
193 .create_repo(&org.id, "proj", "", Visibility::Private, "main")
194 .await
195 .unwrap();
196 let ghost = state.store.ensure_ghost_user().await.unwrap();
197
198 assert_eq!(
199 status_creator(&state, &repo, &tahinli.id).await,
200 Some(tahinli.id.clone())
201 );
202 assert_eq!(
203 status_creator(&state, &repo, &org.id).await,
204 Some(ghost.id.clone())
205 );
206 assert_eq!(status_creator(&state, &repo, "").await, Some(ghost.id));
207 }
208}