Skip to content

Commit ce030d3

Browse files
committed
app/: the hourly sync closes deleted branches' waiting builds (sc-8797, ported): GitHub doesn't send a branch deletion without a pull request (the App has no Contents permission), so each branch with CI builds waiting for review is asked about once a day (500 a run), and a gone one gets BranchClosed { why: branch_deleted }, which the domain handles
1 parent 85a3e43 commit ce030d3

3 files changed

Lines changed: 142 additions & 3 deletions

File tree

‎app/src/forge/github_app.rs‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,27 @@ pub async fn repository(token: &str, repo: &str) -> laravel::Result<Option<Value
169169
get(token, &format!("/repos/{repo}")).await
170170
}
171171

172+
/// Whether a branch exists in a repository (`None` when the installation can't see the repository).
173+
///
174+
/// # Errors
175+
/// When GitHub can't be reached or refuses.
176+
pub async fn branch_exists(token: &str, repo: &str, branch: &str) -> laravel::Result<Option<bool>> {
177+
if get(token, &format!("/repos/{repo}")).await?.is_none() {
178+
return Ok(None);
179+
}
180+
let branch: String = branch
181+
.bytes()
182+
.map(|b| {
183+
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
184+
(b as char).to_string()
185+
} else {
186+
format!("%{b:02X}")
187+
}
188+
})
189+
.collect();
190+
Ok(Some(get(token, &format!("/repos/{repo}/branches/{branch}")).await?.is_some()))
191+
}
192+
172193
/// A repository's permanent ID, by its path (`None` when the installation can't see it).
173194
///
174195
/// # Errors

‎app/src/forge/sync.rs‎

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
//! Nothing changes unless GitHub answered for every repository. When its rate limit runs low the run stops and the
1010
//! next one picks up; that isn't a failure. `VISUALCI_FORGE_SYNC_HEARTBEAT` fails when GitHub or the database can't
1111
//! answer, and when the App isn't configured. Each linked repository's visibility and licence are checked once a day per project
12-
//! (`open_source::recheck_due`). Self-managed GitLab (sc-8634) and closing deleted branches' builds follow.
12+
//! (`open_source::recheck_due`). Branches deleted without a pull request (GitHub doesn't send that event:
13+
//! the App has no Contents permission) are found by asking about each branch with builds waiting for review, once a
14+
//! day, and closed through `BranchClosed` ([`close_deleted_branches`], sc-8797). Self-managed GitLab follows (sc-8634).
1315
1416
use laravel::db;
1517
use laravel::queue::{Queueable, job};
@@ -27,6 +29,8 @@ pub struct Synced {
2729
pub unlinked: usize,
2830
/// Projects made private, or no longer open source, by the daily recheck.
2931
pub open_source: usize,
32+
/// Branches found deleted, whose builds waiting for review were closed.
33+
pub branches_closed: usize,
3034
/// GitHub's rate limit ran low: nothing changed, the next run tries again.
3135
pub deferred: bool,
3236
}
@@ -60,7 +64,12 @@ pub async fn sync_github(app: &GithubApp) -> laravel::Result<Synced> {
6064
Err(e) if github_app::rate_limited(&e) => 0,
6165
Err(e) => return Err(e),
6266
};
63-
Ok(Synced { people: people.len(), changed, unlinked, open_source, deferred: false })
67+
let branches_closed = match close_deleted_branches(app, 500).await {
68+
Ok(n) => n,
69+
Err(e) if github_app::rate_limited(&e) => 0,
70+
Err(e) => return Err(e),
71+
};
72+
Ok(Synced { people: people.len(), changed, unlinked, open_source, branches_closed, deferred: false })
6473
}
6574

6675
/// Give links without GitHub's repository ID their ID. Returns the projects whose repository the App can't see.
@@ -126,6 +135,68 @@ async fn recheck_links(reach: &Reach, unseen: &[i64]) -> laravel::Result<usize>
126135
Ok(lost.len())
127136
}
128137

138+
/// Ask GitHub about up to `limit` branches with CI builds waiting for review (not a fork's, not asked in the last
139+
/// day), and close the ones that are gone through `BranchClosed { why: "branch_deleted" }`, which the domain handles.
140+
/// Returns how many were gone.
141+
///
142+
/// # Errors
143+
/// When GitHub's rate limit is low, or on a database error; one branch GitHub can't answer for is skipped.
144+
pub async fn close_deleted_branches(app: &GithubApp, limit: i64) -> laravel::Result<usize> {
145+
let rows = db::query!(
146+
"SELECT DISTINCT b.project_id, b.branch, p.repository_id, p.repository_url, p.forge_installation \
147+
FROM builds b JOIN projects p ON p.id = b.project_id \
148+
LEFT JOIN branch_checks c ON c.project_id = b.project_id AND c.branch = b.branch \
149+
WHERE b.review_state = 'pending' AND b.mode = 'ci' AND b.branch <> '' AND position(':' in b.branch) = 0 \
150+
AND p.forge = 'github' AND p.forge_installation IS NOT NULL \
151+
AND (c.checked_at IS NULL OR c.checked_at < now() - interval '1 day') \
152+
ORDER BY b.project_id, b.branch LIMIT {limit}"
153+
)
154+
.select()
155+
.await?;
156+
let mut closed = 0;
157+
let mut tokens: std::collections::HashMap<String, String> = std::collections::HashMap::new();
158+
for r in rows {
159+
let (project_id, branch, installation): (i64, String, String) =
160+
(r.try_get("project_id")?, r.try_get("branch")?, r.try_get("forge_installation")?);
161+
let (repository_id, url): (Option<String>, Option<String>) =
162+
(r.try_get("repository_id")?, r.try_get("repository_url")?);
163+
let token = match tokens.get(&installation) {
164+
Some(t) => t.clone(),
165+
None => {
166+
let t = github_app::installation_token(app, &installation).await?;
167+
tokens.insert(installation.clone(), t.clone());
168+
t
169+
}
170+
};
171+
let path = match repository_id.as_deref() {
172+
Some(id) => github_app::repository_path(&token, id).await?,
173+
None => url.as_deref().and_then(super::Repository::parse).map(|r| r.path),
174+
};
175+
let Some(path) = path else { continue };
176+
match github_app::branch_exists(&token, &path, &branch).await {
177+
Ok(Some(false)) => {
178+
super::events::BranchClosed { project_id, branch: branch.clone(), why: "branch_deleted".into() }
179+
.dispatch()
180+
.await?;
181+
closed += 1;
182+
}
183+
Ok(_) => {}
184+
Err(e) if github_app::rate_limited(&e) => return Err(e),
185+
Err(e) => {
186+
tracing::warn!(error = %e, repo = path, branch, "asking whether a branch exists");
187+
continue;
188+
}
189+
}
190+
db::query!(
191+
"INSERT INTO branch_checks (project_id, branch, checked_at) VALUES ({project_id}, {branch}, now()) \
192+
ON CONFLICT (project_id, branch) DO UPDATE SET checked_at = now()"
193+
)
194+
.statement()
195+
.await?;
196+
}
197+
Ok(closed)
198+
}
199+
129200
/// The hourly run.
130201
#[derive(Queueable, Clone, Debug, serde::Serialize, serde::Deserialize)]
131202
pub struct SyncForges;
@@ -147,6 +218,7 @@ impl SyncForges {
147218
changed = s.changed,
148219
unlinked = s.unlinked,
149220
open_source = s.open_source,
221+
branches_closed = s.branches_closed,
150222
deferred = s.deferred,
151223
"forge sync"
152224
);

‎app/tests/forge_sync.rs‎

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ async fn access_github_no_longer_grants_goes_within_the_hour(_app: Application)
3838
let app = GithubApp { app_id: Some("1".into()), private_key_base64: None, webhook_secret: None };
3939
assert_eq!(
4040
sync_github(&app).await?,
41-
Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, deferred: false }
41+
Synced { people: 1, changed: 1, unlinked: 0, open_source: 0, branches_closed: 0, deferred: false }
4242
);
4343
let left: Vec<i64> = db::query!("SELECT organization_id FROM memberships WHERE user_id = {ada_id}")
4444
.select()
@@ -152,3 +152,49 @@ async fn a_repository_gone_private_makes_its_project_private(_app: Application)
152152
assert_eq!(emails, Some(1));
153153
Ok(())
154154
}
155+
156+
/// A branch deleted without a pull request (GitHub doesn't send that event): its builds waiting for review are closed
157+
/// through BranchClosed, and it isn't asked about again for a day.
158+
#[laravel::test]
159+
async fn a_deleted_branchs_waiting_builds_are_closed(_app: Application) -> laravel::Result<()> {
160+
let org: i64 = db::query!(
161+
"INSERT INTO organizations (pid, slug, name, created_at, updated_at) \
162+
VALUES (gen_random_uuid(), 'acme', 'Acme', now(), now()) RETURNING id"
163+
)
164+
.scalar()
165+
.await?
166+
.unwrap();
167+
let project: i64 = db::query!(
168+
"INSERT INTO projects (pid, organization_id, slug, name, forge, repository_url, repository_id, \
169+
forge_installation, created_at, updated_at) \
170+
VALUES (gen_random_uuid(), {org}, 'web', 'Web', 'github', 'https://github.com/acme/web', '42', '7', \
171+
now(), now()) RETURNING id"
172+
)
173+
.scalar()
174+
.await?
175+
.unwrap();
176+
for (number, branch) in [(1, "gone"), (2, "still-here")] {
177+
db::query!(
178+
"INSERT INTO builds (pid, project_id, number, commit_sha, branch, mode, review_state, created_at, updated_at) \
179+
VALUES (gen_random_uuid(), {project}, {number}, 'abc', {branch}, 'ci', 'pending', now(), now())"
180+
)
181+
.insert()
182+
.await?;
183+
}
184+
let events = laravel::event::fake();
185+
let _github = laravel::http::client::fake()
186+
.with("api.github.com/app/installations/7/access_tokens", json!({ "token": "t" }))
187+
.with("api.github.com/repositories/42", json!({ "full_name": "acme/web" }))
188+
.with("api.github.com/repos/acme/web/branches/still-here", json!({ "name": "still-here" }))
189+
.with("api.github.com/repos/acme/web/branches/*", laravel::http::client::response().status(404).json(json!({})))
190+
.with("api.github.com/repos/acme/web", json!({ "id": 42 }));
191+
let app = GithubApp { app_id: Some("1".into()), private_key_base64: Some(app_key().into()), webhook_secret: None };
192+
assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 1);
193+
events.assert_dispatched_where::<app::forge::events::BranchClosed>(|e| {
194+
e.project_id == project && e.branch == "gone" && e.why == "branch_deleted"
195+
});
196+
events.assert_dispatched_times::<app::forge::events::BranchClosed>(1);
197+
// Both were asked about today: neither again until tomorrow
198+
assert_eq!(app::forge::sync::close_deleted_branches(&app, 500).await?, 0);
199+
Ok(())
200+
}

0 commit comments

Comments
 (0)