Skip to content

g1t/services/work/src/statuses.rs

334 lines13,365 bytesCodeBlame
1//! Statuses on commits: what workflow runs (and other tools, such as
2//! deployments) say about a pull request's head. These are its checks.
3//!
4//! The rules of the branch a pull request merges into name the checks that
5//! must pass (rulesets.rs; `RepoSettings::required_checks` as they stack):
6//! a required check that failed, is still running or has not reported
7//! refuses the merge, for everyone and for the merge queue (`g1t_rules`
8//! says so). Where g1t sees an agent's pull request through,
9//! any check that failed sends the agent back to fix it, with what the
10//! failing jobs printed; once it is out of revisions, only a required
11//! check holds the pull request for a person.
12
13use g1t_contracts::events::ChecksEvent;
14use g1t_contracts::time::rfc3339;
15use g1t_contracts::work::{
16 CommitStatus, RequiredCheck, RequiredState, SeenCheck, SeenChecksArgs, SetCommitStatusArgs, check_name,
17 required_checks,
18};
19use g1t_contracts::{FailureCode, Outcome};
20use g1t_kit::now_ms;
21use serde::Deserialize;
22use worker::Result;
23
24use crate::Work;
25
26#[derive(Deserialize)]
27struct StatusRow {
28 context: String,
29 state: String,
30 description: Option<String>,
31 target_url: Option<String>,
32 updated_at: String,
33 #[serde(default)]
34 source: Option<String>,
35 #[serde(default)]
36 check_run_id: Option<String>,
37}
38
39impl From<StatusRow> for CommitStatus {
40 fn from(row: StatusRow) -> Self {
41 CommitStatus {
42 context: row.context,
43 state: row.state,
44 description: row.description,
45 target_url: row.target_url,
46 updated_at: row.updated_at,
47 source: row.source,
48 check_run_id: row.check_run_id,
49 }
50 }
51}
52
53#[derive(Deserialize)]
54struct HeadRow {
55 id: String,
56 number: u32,
57}
58
59/// What a commit's checks say: every status still running and every one
60/// that failed, by context, and where each required check stands.
61#[derive(Clone, Debug, Default, PartialEq)]
62pub(crate) struct WorkflowFacts {
63 pub(crate) pending: Vec<String>,
64 pub(crate) failed: Vec<String>,
65 pub(crate) required: Vec<RequiredCheck>,
66}
67
68impl WorkflowFacts {
69 /// `required` names the checks the default branch's protection requires.
70 pub(crate) fn of(statuses: &[CommitStatus], required: &[String]) -> WorkflowFacts {
71 WorkflowFacts {
72 pending: statuses.iter().filter(|s| s.state == "pending").map(|s| s.context.clone()).collect(),
73 failed: statuses.iter().filter(|s| s.state == "failure" || s.state == "error").map(|s| s.context.clone()).collect(),
74 required: required_checks(required, statuses),
75 }
76 }
77
78 fn required_in(&self, state: RequiredState) -> Vec<String> {
79 self.required.iter().filter(|check| check.state == state).map(|check| check.name.clone()).collect()
80 }
81
82 /// The required checks that failed, by name.
83 pub(crate) fn required_failed(&self) -> Vec<String> {
84 self.required_in(RequiredState::Failure)
85 }
86
87 /// The required checks nothing has reported on the commit yet.
88 pub(crate) fn expected(&self) -> Vec<String> {
89 self.required_in(RequiredState::Expected)
90 }
91}
92
93/// The check names in `(context, last reported)` rows, most recent first:
94/// each name once, with the events it was reported for.
95pub(crate) fn seen(rows: Vec<(String, String)>) -> Vec<SeenCheck> {
96 let mut rows = rows;
97 rows.sort_by(|a, b| b.1.cmp(&a.1));
98 let mut out: Vec<SeenCheck> = Vec::new();
99 for (context, at) in rows {
100 let (name, event) = check_name(&context);
101 match out.iter_mut().find(|seen| seen.name.eq_ignore_ascii_case(name)) {
102 Some(seen) => {
103 if let Some(event) = event
104 && !seen.events.iter().any(|known| known == event)
105 {
106 seen.events.push(event.to_owned());
107 }
108 }
109 None => out.push(SeenCheck {
110 name: name.to_owned(),
111 events: event.map(|event| vec![event.to_owned()]).unwrap_or_default(),
112 last_seen: at,
113 }),
114 }
115 }
116 out
117}
118
119/// How far back `seen_checks` looks, and the most contexts it reads.
120const SEEN_DAYS: u64 = 30;
121const SEEN_LIMIT: u32 = 200;
122
123#[derive(Deserialize)]
124struct SeenRow {
125 context: String,
126 at: String,
127}
128
129pub(crate) fn list(names: &[String]) -> String {
130 match names {
131 [] => String::new(),
132 [one] => one.clone(),
133 [rest @ .., last] => format!("{} and {last}", rest.join(", ")),
134 }
135}
136
137impl Work {
138 /// Where a commit's checks stand, against the repository's required ones.
139 pub(crate) async fn facts(&self, repo_id: &str, sha: Option<&str>) -> Result<WorkflowFacts> {
140 let (statuses, settings) =
141 futures_util::future::try_join(self.statuses(repo_id, sha), self.settings_by_id(repo_id)).await?;
142 Ok(WorkflowFacts::of(&statuses, &settings.required_checks))
143 }
144
145 /// The check names reported on a repository's commits lately, for
146 /// choosing which to require.
147 pub(crate) async fn seen_checks(&self, a: SeenChecksArgs) -> Result<Outcome<Vec<SeenCheck>>> {
148 let repo = match self.repo(&a.repo, &a.viewer).await? {
149 Outcome::Ok(repo) => repo,
150 Outcome::Fail(failure) => return Ok(Outcome::Fail(failure)),
151 };
152 let since = rfc3339(now_ms().saturating_sub(SEEN_DAYS * 24 * 60 * 60 * 1000));
153 let rows = self
154 .db
155 .prepare(
156 "SELECT context, MAX(updated_at) AS at FROM commit_statuses
157 WHERE repo_id = ? AND updated_at >= ? GROUP BY context ORDER BY at DESC LIMIT ?",
158 )
159 .bind(&[repo.id.as_str().into(), since.into(), SEEN_LIMIT.into()])?
160 .all()
161 .await?
162 .results::<SeenRow>()?;
163 Ok(Outcome::Ok(seen(rows.into_iter().map(|row| (row.context, row.at)).collect())))
164 }
165
166 pub(crate) async fn statuses(&self, repo_id: &str, sha: Option<&str>) -> Result<Vec<CommitStatus>> {
167 let Some(sha) = sha else { return Ok(Vec::new()) };
168 if let Some(found) = self.prefetched_repo(repo_id).filter(|found| found.head.as_deref() == Some(sha)) {
169 return Ok(found
170 .rows::<StatusRow>(crate::prefetch::Slot::Statuses)?
171 .into_iter()
172 .map(CommitStatus::from)
173 .collect());
174 }
175 Ok(self
176 .db
177 .prepare("SELECT context, state, description, target_url, updated_at, source, check_run_id FROM commit_statuses WHERE repo_id = ? AND sha = ? ORDER BY context")
178 .bind(&[repo_id.into(), sha.into()])?
179 .all()
180 .await?
181 .results::<StatusRow>()?
182 .into_iter()
183 .map(CommitStatus::from)
184 .collect())
185 }
186
187 pub(crate) async fn set_commit_status(&self, a: SetCommitStatusArgs) -> Result<Outcome<bool>> {
188 self.store_status(a, None).await
189 }
190
191 /// Sets a status, standing for check run `check_run_id` if it does,
192 /// and moves on what was waiting for the commit's checks.
193 pub(crate) async fn store_status(&self, a: SetCommitStatusArgs, check_run_id: Option<&str>) -> Result<Outcome<bool>> {
194 if !matches!(a.state.as_str(), "pending" | "success" | "failure" | "error") {
195 return Ok(Outcome::fail(FailureCode::Invalid, "`state` is pending, success, failure or error."));
196 }
197 self.db
198 .prepare(
199 "INSERT INTO commit_statuses (repo_id, sha, context, state, description, target_url, updated_at, source, check_run_id)
200 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
201 ON CONFLICT (repo_id, sha, context) DO UPDATE SET
202 state = excluded.state, description = excluded.description,
203 target_url = excluded.target_url, updated_at = excluded.updated_at,
204 source = excluded.source, check_run_id = excluded.check_run_id",
205 )
206 .bind(&[
207 a.repo_id.as_str().into(),
208 a.sha.as_str().into(),
209 a.context.as_str().into(),
210 a.state.as_str().into(),
211 a.description.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
212 a.target_url.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
213 rfc3339(now_ms()).into(),
214 a.source.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
215 check_run_id.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
216 ])?
217 .run()
218 .await?;
219 if a.state == "pending" {
220 return Ok(Outcome::Ok(true));
221 }
222 // Once every workflow on a pull request's head has finished, its
223 // lifecycle moves on, as it does when its checks finish.
224 let facts = self.facts(&a.repo_id, Some(&a.sha)).await?;
225 if !facts.pending.is_empty() {
226 return Ok(Outcome::Ok(true));
227 }
228 // A merge queue state waiting on its merge_group workflows.
229 self.merge_group_finished(&a.repo_id, &a.sha, &facts).await?;
230 let heads = self
231 .db
232 .prepare("SELECT id, number FROM pulls WHERE repo_id = ? AND head_commit = ? AND status IN ('draft', 'open')")
233 .bind(&[a.repo_id.as_str().into(), a.sha.as_str().into()])?
234 .all()
235 .await?
236 .results::<HeadRow>()?;
237 for head in heads {
238 // A pull request g1t stopped on picks back up once what stopped
239 // it passes: its workflows, and its checks if it has any. The
240 // lifecycle then decides again, within its usual limits.
241 if facts.failed.is_empty() {
242 let resumed = self
243 .db
244 .prepare(
245 "UPDATE pulls SET stalled = NULL WHERE id = ? AND managed = 1 AND stalled IS NOT NULL
246 AND (check_status IS NULL OR check_status = 'passed') RETURNING id AS value",
247 )
248 .bind(&[head.id.as_str().into()])?
249 .first::<crate::rows::ValueRow>(None)
250 .await?;
251 if resumed.is_some() {
252 self.announce_resumed(&head.id, None).await?;
253 self.note(
254 &a.repo_id,
255 head.number,
256 (crate::lifecycle::POLICY_ACTOR_ID, crate::lifecycle::POLICY_ACTOR_NAME),
257 "picked this back up: its workflows pass now",
258 )
259 .await?;
260 }
261 }
262 self.publish_as(
263 "checks.completed",
264 &a.repo_id,
265 None,
266 ChecksEvent {
267 pull_id: head.id,
268 repo_id: a.repo_id.clone(),
269 number: head.number,
270 status: if facts.failed.is_empty() { "passed" } else { "failed" },
271 commit: a.sha.clone(),
272 },
273 )
274 .await?;
275 }
276 Ok(Outcome::Ok(true))
277 }
278}
279
280#[cfg(test)]
281mod tests {
282 use super::*;
283
284 fn status(context: &str, state: &str) -> CommitStatus {
285 CommitStatus {
286 context: context.into(),
287 state: state.into(),
288 description: None,
289 target_url: None,
290 updated_at: String::new(),
291 source: None,
292 check_run_id: None,
293 }
294 }
295
296 fn names(list: &[&str]) -> Vec<String> {
297 list.iter().map(|name| (*name).to_owned()).collect()
298 }
299
300 #[test]
301 fn only_required_checks_hold_a_merge() {
302 let statuses = [status("CI / push", "pending"), status("Lint / pull_request", "failure"), status("Docs", "success")];
303 // Nothing required: nothing holds it, whatever failed.
304 let free = WorkflowFacts::of(&statuses, &[]);
305 assert_eq!(free.pending, ["CI / push"]);
306 assert_eq!(free.failed, ["Lint / pull_request"]);
307 assert!(free.required_failed().is_empty() && free.expected().is_empty());
308 let both = WorkflowFacts::of(&statuses, &names(&["CI", "Lint"]));
309 assert_eq!(both.required_failed(), ["Lint"]);
310 assert!(WorkflowFacts::of(&[status("Docs", "success")], &names(&["Docs"])).required_failed().is_empty());
311 }
312
313 #[test]
314 fn a_required_check_nothing_reported_is_expected() {
315 let facts = WorkflowFacts::of(&[status("CI / pull_request", "success")], &names(&["CI", "Deploy"]));
316 assert_eq!(facts.expected(), ["Deploy"]);
317 }
318
319 #[test]
320 fn seen_checks_are_named_once_with_their_events() {
321 let rows = vec![
322 ("CI / push".to_owned(), "2026-10-01T00:00:00Z".to_owned()),
323 ("CI / pull_request".to_owned(), "2026-10-03T00:00:00Z".to_owned()),
324 ("g1t / deploy".to_owned(), "2026-10-02T00:00:00Z".to_owned()),
325 ];
326 let seen = seen(rows);
327 assert_eq!(seen.len(), 2);
328 assert_eq!(seen[0].name, "CI");
329 assert_eq!(seen[0].events, ["pull_request", "push"]);
330 assert_eq!(seen[0].last_seen, "2026-10-03T00:00:00Z");
331 assert_eq!(seen[1].name, "g1t / deploy");
332 assert!(seen[1].events.is_empty());
333 }
334}