forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBb00f3f4Tahinli1 month ago147 commits

post_update.rs366 lines, 13.5 KiBHistoryRawDownload
1//! Side effects of one updated ref, shared by the post-receive hook and the web merge route.
2//!
3//! [`after_ref_update`] runs, in order:
4//! 0. Webhook events for the ref: push, and create or delete (see `webhooks::emit`).
5//! 1. Closing keywords and references from the commits a default-branch update added. These run
6//! in a spawned task and are not coalesced: every range must be processed.
7//! 2. Pull request sync for `refs/heads/<b>` (see `pulls_sync`), inline.
8//!
9//! Maintenance is not part of this: it is coalesced per repo and runs once per push through
10//! `internal::trigger_maintenance`. Callers that update a ref outside receive-pack (the merge
11//! route) call it themselves.
12
13use std::path::PathBuf;
14
15use forge_core::issue_refs::{find_closing_refs, find_issue_refs};
16use forge_core::{IssueState, Repo, StateReason};
17use forge_git::history;
18use serde_json::json;
19
20use crate::internal::is_zero_oid;
21use crate::notify::{self, Activity};
22use crate::pulls_sync;
23use crate::state::AppState;
24use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_sender};
25
26/// Commits read for a push that updates an existing branch.
27const MAX_PUSH_COMMITS: usize = 500;
28/// Commits read for a push that creates the branch.
29const MAX_NEW_BRANCH_COMMITS: usize = 50;
30
31/// Runs the per-ref post-update work for `refname`, moving `old` to `new`. `actor_id` is the user
32/// who made the change (empty for system updates). Closing-keyword work is spawned; pull request
33/// sync is awaited, so its errors are returned, while per-pull failures are logged and skipped.
34pub async fn after_ref_update(
35 state: &AppState,
36 repo: &Repo,
37 actor_id: &str,
38 refname: &str,
39 old: &str,
40 new: &str,
41) -> forge_core::Result<()> {
42 let sender = lookup_sender(state, actor_id).await;
43 emit_ref_update(state, repo, &sender, refname, old, new).await;
44 // Code views that follow a branch or the ref list re-read it.
45 state
46 .live
47 .bump(&crate::live::Topic::RepoRefs(repo.id.clone()));
48 // The pusher's contribution calendar (dashboard and profile) counts the push.
49 if !actor_id.is_empty() {
50 state
51 .live
52 .bump(&crate::live::Topic::User(actor_id.to_owned()));
53 }
54 crate::ci::on_ref_update(state, repo, actor_id, refname, new).await;
55 if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/"))
56 && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await
57 {
58 tracing::error!(error = %e, repo_id = %repo.id, "mirrors: could not queue push mirrors");
59 }
60 if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) {
61 crate::advisories::scan::spawn_repo_scan(state, repo);
62 }
63 crate::replication::enqueue_repo(state, &repo.id);
64 if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) {
65 match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) {
66 Ok(repo_dir) => {
67 tokio::spawn(close_from_pushed_commits(
68 state.clone(),
69 repo.clone(),
70 sender,
71 repo_dir,
72 actor_id.to_owned(),
73 old.to_owned(),
74 new.to_owned(),
75 ));
76 }
77 Err(e) => {
78 tracing::error!(error = %e, repo_id = %repo.id, "issue refs: bad repo path");
79 }
80 }
81 }
82 let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await;
83 // A push can move, merge or open any pull of the repo, so every pull page is woken.
84 crate::pages::pull_live::bump_repo_pulls(state, &repo.id).await;
85 synced
86}
87
88/// Processes the commits added to the default branch by one ref update, oldest first.
89async fn close_from_pushed_commits(
90 state: AppState,
91 repo: Repo,
92 sender: Sender,
93 repo_dir: PathBuf,
94 actor_id: String,
95 old: String,
96 new: String,
97) {
98 let old = (!is_zero_oid(&old)).then_some(old.as_str());
99 let max = if old.is_some() {
100 MAX_PUSH_COMMITS
101 } else {
102 MAX_NEW_BRANCH_COMMITS
103 };
104 let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await {
105 Ok(commits) => commits,
106 Err(e) => {
107 tracing::error!(error = %e, repo_id = %repo.id, "issue refs: listing commits failed");
108 return;
109 }
110 };
111 let actor = (!actor_id.is_empty()).then_some(actor_id.as_str());
112 for commit in &commits {
113 let text = format!("{}\n{}", commit.summary, commit.message);
114 if let Err(e) = apply_commit_refs(&state, &repo, &sender, actor, &commit.oid, &text).await {
115 tracing::error!(error = %e, repo_id = %repo.id, commit = %commit.oid, "issue refs: applying commit failed");
116 }
117 }
118}
119
120/// Closes open issues named by closing keywords in `text`, and records a `referenced` event on
121/// every other issue it mentions, once per (issue, commit).
122async fn apply_commit_refs(
123 state: &AppState,
124 repo: &Repo,
125 sender: &Sender,
126 actor: Option<&str>,
127 oid: &str,
128 text: &str,
129) -> forge_core::Result<()> {
130 let store = &state.store;
131 let closing = find_closing_refs(text);
132 for number in find_issue_refs(text) {
133 let Some(issue) = store.issue_by_number(&repo.id, number).await? else {
134 continue;
135 };
136 if closing.contains(&number) {
137 if issue.state == IssueState::Open {
138 let closed = store
139 .set_issue_state(
140 &issue.id,
141 actor,
142 IssueState::Closed,
143 Some(StateReason::Completed),
144 json!({"commit": oid}),
145 )
146 .await?;
147 if closed {
148 emit_item_action(state, repo, sender, false, number, "closed").await;
149 notify::dispatch(
150 state,
151 repo,
152 &issue,
153 actor.unwrap_or(""),
154 Activity::Closed,
155 None,
156 )
157 .await;
158 }
159 }
160 continue;
161 }
162 let already = store.list_events(&issue.id).await?.iter().any(|e| {
163 e.kind == "referenced" && e.data.get("commit").and_then(|c| c.as_str()) == Some(oid)
164 });
165 if !already {
166 store
167 .add_event(&issue.id, actor, "referenced", json!({"commit": oid}))
168 .await?;
169 }
170 }
171 Ok(())
172}
173
174#[cfg(test)]
175mod tests {
176 use std::path::{Path, PathBuf};
177
178 use forge_core::Visibility;
179 use forge_core::webhooks::{Delivery, WebhookEvent};
180 use forge_git::repo::{init_bare, repo_path};
181 use serde_json::Value;
182 use tempfile::TempDir;
183
184 use super::*;
185 use crate::test_support::{KEY, test_state};
186
187 const ZERO: &str = "0000000000000000000000000000000000000000";
188
189 fn git(dir: &Path, args: &[&str]) -> String {
190 let out = std::process::Command::new("git")
191 .arg("-C")
192 .arg(dir)
193 .args(args)
194 .env("GIT_AUTHOR_NAME", "test")
195 .env("GIT_AUTHOR_EMAIL", "test@example.com")
196 .env("GIT_COMMITTER_NAME", "test")
197 .env("GIT_COMMITTER_EMAIL", "test@example.com")
198 .output()
199 .expect("git runs");
200 assert!(
201 out.status.success(),
202 "git {args:?} failed: {}",
203 String::from_utf8_lossy(&out.stderr)
204 );
205 String::from_utf8_lossy(&out.stdout).trim().to_string()
206 }
207
208 fn commit(work: &Path, file: &str, contents: &str) -> String {
209 std::fs::write(work.join(file), contents).expect("write file");
210 git(work, &["add", file]);
211 git(work, &["commit", "-m", contents]);
212 git(work, &["rev-parse", "HEAD"])
213 }
214
215 /// A repo with a bare copy on disk, a hook subscribed to push and create, and a work tree.
216 struct Fixture {
217 _tmp: TempDir,
218 state: AppState,
219 repo: Repo,
220 owner_id: String,
221 hook_id: String,
222 bare: PathBuf,
223 work: PathBuf,
224 }
225
226 async fn fixture() -> Fixture {
227 let tmp = tempfile::tempdir().expect("tempdir");
228 let state = test_state(tmp.path()).await;
229 let owner = state
230 .store
231 .create_user("tahinli", None, "unused", false)
232 .await
233 .expect("user");
234 let repo = state
235 .store
236 .create_repo(&owner.id, "proj", "", Visibility::Private, "main")
237 .await
238 .expect("repo");
239 let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path");
240 init_bare(&state.git, &bare, "main")
241 .await
242 .expect("init bare");
243 let work = tmp.path().join("work");
244 git(tmp.path(), &["init", "-b", "main", "work"]);
245 let sealed = forge_core::secret::seal(&KEY, b"s").expect("seal");
246 let hook = state
247 .store
248 .create_webhook(
249 &repo.id,
250 &owner.id,
251 "https://hooks.example/h",
252 sealed.as_bytes(),
253 &[
254 WebhookEvent::Push,
255 WebhookEvent::Create,
256 WebhookEvent::Delete,
257 ],
258 true,
259 )
260 .await
261 .expect("hook");
262 Fixture {
263 _tmp: tmp,
264 state,
265 repo,
266 owner_id: owner.id,
267 hook_id: hook.id,
268 bare,
269 work,
270 }
271 }
272
273 impl Fixture {
274 /// Pushes `new` to `refname` on the bare repo (`ZERO` deletes it) and runs the post-update
275 /// work the hook would run.
276 async fn update_ref(&self, refname: &str, old: &str, new: &str) {
277 let bare = self.bare.to_str().expect("utf8");
278 if new == ZERO {
279 git(&self.work, &["push", bare, &format!(":{refname}")]);
280 } else {
281 git(&self.work, &["push", bare, &format!("{new}:{refname}")]);
282 }
283 after_ref_update(&self.state, &self.repo, &self.owner_id, refname, old, new)
284 .await
285 .expect("post-update");
286 }
287
288 /// The hook's deliveries of `event`, oldest first, with their bodies parsed.
289 async fn deliveries(&self, event: WebhookEvent) -> Vec<(Delivery, Value)> {
290 let mut rows = self
291 .state
292 .store
293 .list_deliveries(&self.hook_id, 50)
294 .await
295 .expect("list");
296 rows.reverse();
297 rows.into_iter()
298 .filter(|d| d.event == event)
299 .map(|d| {
300 let body = serde_json::from_str(&d.request_body).expect("json body");
301 (d, body)
302 })
303 .collect()
304 }
305 }
306
307 #[tokio::test]
308 async fn push_through_post_update_enqueues_before_and_after() {
309 let fx = fixture().await;
310 let c1 = commit(&fx.work, "a.txt", "one");
311 fx.update_ref("refs/heads/main", ZERO, &c1).await;
312
313 let pushes = fx.deliveries(WebhookEvent::Push).await;
314 assert_eq!(pushes.len(), 1);
315 let (_, body) = &pushes[0];
316 assert_eq!(body["ref"], "refs/heads/main");
317 assert_eq!(body["before"], ZERO);
318 assert_eq!(body["after"], c1.as_str());
319 assert_eq!(body["total_commits"], 1);
320 assert_eq!(body["commits"][0]["id"], c1.as_str());
321 assert_eq!(body["commits"][0]["message"], "one");
322
323 // Creating the branch also sends a create event for it.
324 let creates = fx.deliveries(WebhookEvent::Create).await;
325 assert_eq!(creates.len(), 1);
326 assert_eq!(creates[0].1["ref"], "main");
327 assert_eq!(creates[0].1["ref_type"], "branch");
328
329 let c2 = commit(&fx.work, "b.txt", "two");
330 fx.update_ref("refs/heads/main", &c1, &c2).await;
331 let pushes = fx.deliveries(WebhookEvent::Push).await;
332 assert_eq!(pushes.len(), 2);
333 let (_, body) = &pushes[1];
334 assert_eq!(body["before"], c1.as_str());
335 assert_eq!(body["after"], c2.as_str());
336 assert_eq!(body["total_commits"], 1);
337 assert_eq!(body["commits"][0]["id"], c2.as_str());
338
339 // A topic branch: create, then delete. Git will not delete the bare repo's
340 // current branch, so the delete uses a branch that is not HEAD.
341 fx.update_ref("refs/heads/topic", ZERO, &c2).await;
342 fx.update_ref("refs/heads/topic", &c2, ZERO).await;
343 let deletes = fx.deliveries(WebhookEvent::Delete).await;
344 assert_eq!(deletes.len(), 1);
345 assert_eq!(deletes[0].1["ref"], "topic");
346 assert_eq!(deletes[0].1["ref_type"], "branch");
347 let pushes = fx.deliveries(WebhookEvent::Push).await;
348 assert_eq!(pushes.len(), 4);
349 assert_eq!(pushes[3].1["ref"], "refs/heads/topic");
350 assert_eq!(pushes[3].1["after"], ZERO);
351 assert_eq!(pushes[3].1["total_commits"], 0);
352 }
353
354 #[tokio::test]
355 async fn refs_outside_heads_and_tags_produce_no_events() {
356 let fx = fixture().await;
357 let c1 = commit(&fx.work, "a.txt", "one");
358 let bare = fx.bare.to_str().expect("utf8");
359 git(&fx.work, &["push", bare, &format!("{c1}:refs/notes/x")]);
360 after_ref_update(&fx.state, &fx.repo, &fx.owner_id, "refs/notes/x", ZERO, &c1)
361 .await
362 .expect("post-update");
363 assert!(fx.deliveries(WebhookEvent::Push).await.is_empty());
364 assert!(fx.deliveries(WebhookEvent::Create).await.is_empty());
365 }
366}