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
1416use laravel:: db;
1517use 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 ) ]
131202pub 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 ) ;
0 commit comments