| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use std::path::PathBuf; |
| 16 | |
| 17 | use forge_core::issue_refs::{find_closing_refs, find_issue_refs}; |
| 18 | use forge_core::time::now_stamp; |
| 19 | use forge_core::{IssueState, Repo, StateReason}; |
| 20 | use forge_git::{history, trailers}; |
| 21 | use serde_json::json; |
| 22 | |
| 23 | use crate::internal::is_zero_oid; |
| 24 | use crate::notify::{self, Activity}; |
| 25 | use crate::pulls_sync; |
| 26 | use crate::state::AppState; |
| 27 | use crate::webhooks::emit::{Sender, emit_item_action, emit_ref_update, lookup_sender}; |
| 28 | |
| 29 | |
| 30 | const MAX_PUSH_COMMITS: usize = 500; |
| 31 | |
| 32 | const MAX_NEW_BRANCH_COMMITS: usize = 50; |
| 33 | |
| 34 | const MAX_COAUTHOR_COMMITS: usize = 200; |
| 35 | |
| 36 | |
| 37 | |
| 38 | |
| 39 | pub async fn after_ref_update( |
| 40 | state: &AppState, |
| 41 | repo: &Repo, |
| 42 | actor_id: &str, |
| 43 | refname: &str, |
| 44 | old: &str, |
| 45 | new: &str, |
| 46 | ) -> forge_core::Result<()> { |
| 47 | let sender = lookup_sender(state, actor_id).await; |
| 48 | emit_ref_update(state, repo, &sender, refname, old, new).await; |
| 49 | |
| 50 | state |
| 51 | .live |
| 52 | .bump(&crate::live::Topic::RepoRefs(repo.id.clone())); |
| 53 | |
| 54 | if !actor_id.is_empty() { |
| 55 | state |
| 56 | .live |
| 57 | .bump(&crate::live::Topic::User(actor_id.to_owned())); |
| 58 | } |
| 59 | |
| 60 | if repo.owner_id != actor_id { |
| 61 | state |
| 62 | .live |
| 63 | .bump(&crate::live::Topic::User(repo.owner_id.clone())); |
| 64 | } |
| 65 | |
| 66 | if repo.visibility == forge_core::Visibility::Public { |
| 67 | state.live.bump(&crate::live::Topic::Explore); |
| 68 | } |
| 69 | crate::ci::on_ref_update(state, repo, actor_id, refname, new).await; |
| 70 | if (refname.starts_with("refs/heads/") || refname.starts_with("refs/tags/")) |
| 71 | && let Err(e) = crate::mirrors::enqueue_push_mirrors(state, &repo.id).await |
| 72 | { |
| 73 | tracing::error!(error = %e, repo_id = %repo.id, "mirrors: could not queue push mirrors"); |
| 74 | } |
| 75 | if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) { |
| 76 | crate::advisories::scan::spawn_repo_scan(state, repo); |
| 77 | } |
| 78 | crate::replication::enqueue_repo(state, &repo.id); |
| 79 | if refname == format!("refs/heads/{}", repo.default_branch) && !is_zero_oid(new) { |
| 80 | match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { |
| 81 | Ok(repo_dir) => { |
| 82 | tokio::spawn(close_from_pushed_commits( |
| 83 | state.clone(), |
| 84 | repo.clone(), |
| 85 | sender, |
| 86 | repo_dir, |
| 87 | actor_id.to_owned(), |
| 88 | old.to_owned(), |
| 89 | new.to_owned(), |
| 90 | )); |
| 91 | } |
| 92 | Err(e) => { |
| 93 | tracing::error!(error = %e, repo_id = %repo.id, "issue refs: bad repo path"); |
| 94 | } |
| 95 | } |
| 96 | } |
| 97 | if refname.starts_with("refs/heads/") && !is_zero_oid(new) { |
| 98 | match forge_git::repo::repo_path(&state.git.data_dir, &repo.id) { |
| 99 | Ok(repo_dir) => { |
| 100 | tokio::spawn(credit_coauthors( |
| 101 | state.clone(), |
| 102 | repo.clone(), |
| 103 | repo_dir, |
| 104 | actor_id.to_owned(), |
| 105 | old.to_owned(), |
| 106 | new.to_owned(), |
| 107 | )); |
| 108 | } |
| 109 | Err(e) => { |
| 110 | tracing::error!(error = %e, repo_id = %repo.id, "co-authors: bad repo path"); |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | let synced = pulls_sync::sync_pulls_for_ref(state, repo, actor_id, refname, old, new).await; |
| 115 | |
| 116 | crate::live::bump_repo_pulls(state, &repo.id).await; |
| 117 | synced |
| 118 | } |
| 119 | |
| 120 | |
| 121 | async fn close_from_pushed_commits( |
| 122 | state: AppState, |
| 123 | repo: Repo, |
| 124 | sender: Sender, |
| 125 | repo_dir: PathBuf, |
| 126 | actor_id: String, |
| 127 | old: String, |
| 128 | new: String, |
| 129 | ) { |
| 130 | let old = (!is_zero_oid(&old)).then_some(old.as_str()); |
| 131 | let max = if old.is_some() { |
| 132 | MAX_PUSH_COMMITS |
| 133 | } else { |
| 134 | MAX_NEW_BRANCH_COMMITS |
| 135 | }; |
| 136 | let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await { |
| 137 | Ok(commits) => commits, |
| 138 | Err(e) => { |
| 139 | tracing::error!(error = %e, repo_id = %repo.id, "issue refs: listing commits failed"); |
| 140 | return; |
| 141 | } |
| 142 | }; |
| 143 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); |
| 144 | for commit in &commits { |
| 145 | let text = format!("{}\n{}", commit.summary, commit.message); |
| 146 | if let Err(e) = apply_commit_refs(&state, &repo, &sender, actor, &commit.oid, &text).await { |
| 147 | tracing::error!(error = %e, repo_id = %repo.id, commit = %commit.oid, "issue refs: applying commit failed"); |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | async fn credit_coauthors( |
| 156 | state: AppState, |
| 157 | repo: Repo, |
| 158 | repo_dir: PathBuf, |
| 159 | actor_id: String, |
| 160 | old: String, |
| 161 | new: String, |
| 162 | ) { |
| 163 | let old = (!is_zero_oid(&old)).then_some(old.as_str()); |
| 164 | let max = if old.is_some() { |
| 165 | MAX_COAUTHOR_COMMITS |
| 166 | } else { |
| 167 | MAX_NEW_BRANCH_COMMITS |
| 168 | }; |
| 169 | let commits = match history::new_commits(&state.git, &repo_dir, old, &new, max).await { |
| 170 | Ok(commits) => commits, |
| 171 | Err(e) => { |
| 172 | tracing::error!(error = %e, repo_id = %repo.id, "co-authors: listing commits failed"); |
| 173 | return; |
| 174 | } |
| 175 | }; |
| 176 | let actor = (!actor_id.is_empty()).then_some(actor_id.as_str()); |
| 177 | let at = now_stamp(); |
| 178 | for commit in &commits { |
| 179 | for co in trailers::co_authors(&commit.message) { |
| 180 | if co.email.eq_ignore_ascii_case(&commit.author_email) { |
| 181 | continue; |
| 182 | } |
| 183 | let user = match state.store.verified_user_by_email(&co.email).await { |
| 184 | Ok(Some(user)) => user, |
| 185 | Ok(None) => continue, |
| 186 | Err(e) => { |
| 187 | tracing::error!(error = %e, repo_id = %repo.id, "co-authors: user lookup failed"); |
| 188 | continue; |
| 189 | } |
| 190 | }; |
| 191 | if Some(user.id.as_str()) == actor { |
| 192 | continue; |
| 193 | } |
| 194 | let recorded = state |
| 195 | .store |
| 196 | .record_coauthored_commit(&user.id, &repo.id, &commit.oid, &commit.summary, &at) |
| 197 | .await; |
| 198 | if let Err(e) = recorded { |
| 199 | tracing::error!(error = %e, repo_id = %repo.id, commit = %commit.oid, "co-authors: recording failed"); |
| 200 | continue; |
| 201 | } |
| 202 | state.live.bump(&crate::live::Topic::User(user.id.clone())); |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | async fn apply_commit_refs( |
| 210 | state: &AppState, |
| 211 | repo: &Repo, |
| 212 | sender: &Sender, |
| 213 | actor: Option<&str>, |
| 214 | oid: &str, |
| 215 | text: &str, |
| 216 | ) -> forge_core::Result<()> { |
| 217 | let store = &state.store; |
| 218 | let closing = find_closing_refs(text); |
| 219 | for number in find_issue_refs(text) { |
| 220 | let Some(issue) = store.issue_by_number(&repo.id, number).await? else { |
| 221 | continue; |
| 222 | }; |
| 223 | if closing.contains(&number) { |
| 224 | if issue.state == IssueState::Open { |
| 225 | let closed = store |
| 226 | .set_issue_state( |
| 227 | &issue.id, |
| 228 | actor, |
| 229 | IssueState::Closed, |
| 230 | Some(StateReason::Completed), |
| 231 | json!({"commit": oid}), |
| 232 | ) |
| 233 | .await?; |
| 234 | if closed { |
| 235 | state.live.bump_issue(&repo.id, &issue.id); |
| 236 | |
| 237 | crate::live::bump_pull(state, &repo.id, &issue.id); |
| 238 | emit_item_action(state, repo, sender, false, number, "closed").await; |
| 239 | notify::dispatch( |
| 240 | state, |
| 241 | repo, |
| 242 | &issue, |
| 243 | actor.unwrap_or(""), |
| 244 | Activity::Closed, |
| 245 | None, |
| 246 | ) |
| 247 | .await; |
| 248 | } |
| 249 | } |
| 250 | continue; |
| 251 | } |
| 252 | let already = store.list_events(&issue.id).await?.iter().any(|e| { |
| 253 | e.kind == "referenced" && e.data.get("commit").and_then(|c| c.as_str()) == Some(oid) |
| 254 | }); |
| 255 | if !already { |
| 256 | store |
| 257 | .add_event(&issue.id, actor, "referenced", json!({"commit": oid})) |
| 258 | .await?; |
| 259 | state.live.bump_issue(&repo.id, &issue.id); |
| 260 | crate::live::bump_pull(state, &repo.id, &issue.id); |
| 261 | } |
| 262 | } |
| 263 | Ok(()) |
| 264 | } |
| 265 | |
| 266 | #[cfg(test)] |
| 267 | mod tests { |
| 268 | use std::path::{Path, PathBuf}; |
| 269 | |
| 270 | use forge_core::Visibility; |
| 271 | use forge_core::webhooks::{Delivery, WebhookEvent}; |
| 272 | use forge_git::repo::{init_bare, repo_path}; |
| 273 | use serde_json::Value; |
| 274 | use tempfile::TempDir; |
| 275 | |
| 276 | use super::*; |
| 277 | use crate::test_support::{KEY, test_state}; |
| 278 | |
| 279 | const ZERO: &str = "0000000000000000000000000000000000000000"; |
| 280 | |
| 281 | fn git(dir: &Path, args: &[&str]) -> String { |
| 282 | let out = std::process::Command::new("git") |
| 283 | .arg("-C") |
| 284 | .arg(dir) |
| 285 | .args(args) |
| 286 | .env("GIT_AUTHOR_NAME", "test") |
| 287 | .env("GIT_AUTHOR_EMAIL", "test@example.com") |
| 288 | .env("GIT_COMMITTER_NAME", "test") |
| 289 | .env("GIT_COMMITTER_EMAIL", "test@example.com") |
| 290 | .output() |
| 291 | .expect("git runs"); |
| 292 | assert!( |
| 293 | out.status.success(), |
| 294 | "git {args:?} failed: {}", |
| 295 | String::from_utf8_lossy(&out.stderr) |
| 296 | ); |
| 297 | String::from_utf8_lossy(&out.stdout).trim().to_string() |
| 298 | } |
| 299 | |
| 300 | fn commit(work: &Path, file: &str, contents: &str) -> String { |
| 301 | std::fs::write(work.join(file), contents).expect("write file"); |
| 302 | git(work, &["add", file]); |
| 303 | git(work, &["commit", "-m", contents]); |
| 304 | git(work, &["rev-parse", "HEAD"]) |
| 305 | } |
| 306 | |
| 307 | |
| 308 | struct Fixture { |
| 309 | _tmp: TempDir, |
| 310 | state: AppState, |
| 311 | repo: Repo, |
| 312 | owner_id: String, |
| 313 | hook_id: String, |
| 314 | bare: PathBuf, |
| 315 | work: PathBuf, |
| 316 | } |
| 317 | |
| 318 | async fn fixture() -> Fixture { |
| 319 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 320 | let state = test_state(tmp.path()).await; |
| 321 | let owner = state |
| 322 | .store |
| 323 | .create_user("tahinli", None, "unused", false) |
| 324 | .await |
| 325 | .expect("user"); |
| 326 | let repo = state |
| 327 | .store |
| 328 | .create_repo(&owner.id, "proj", "", Visibility::Private, "main") |
| 329 | .await |
| 330 | .expect("repo"); |
| 331 | let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path"); |
| 332 | init_bare(&state.git, &bare, "main") |
| 333 | .await |
| 334 | .expect("init bare"); |
| 335 | let work = tmp.path().join("work"); |
| 336 | git(tmp.path(), &["init", "-b", "main", "work"]); |
| 337 | let sealed = forge_core::secret::seal(&KEY, b"s").expect("seal"); |
| 338 | let hook = state |
| 339 | .store |
| 340 | .create_webhook( |
| 341 | &repo.id, |
| 342 | &owner.id, |
| 343 | "https://hooks.example/h", |
| 344 | sealed.as_bytes(), |
| 345 | &[ |
| 346 | WebhookEvent::Push, |
| 347 | WebhookEvent::Create, |
| 348 | WebhookEvent::Delete, |
| 349 | ], |
| 350 | true, |
| 351 | ) |
| 352 | .await |
| 353 | .expect("hook"); |
| 354 | Fixture { |
| 355 | _tmp: tmp, |
| 356 | state, |
| 357 | repo, |
| 358 | owner_id: owner.id, |
| 359 | hook_id: hook.id, |
| 360 | bare, |
| 361 | work, |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | impl Fixture { |
| 366 | |
| 367 | |
| 368 | async fn update_ref(&self, refname: &str, old: &str, new: &str) { |
| 369 | let bare = self.bare.to_str().expect("utf8"); |
| 370 | if new == ZERO { |
| 371 | git(&self.work, &["push", bare, &format!(":{refname}")]); |
| 372 | } else { |
| 373 | git(&self.work, &["push", bare, &format!("{new}:{refname}")]); |
| 374 | } |
| 375 | after_ref_update(&self.state, &self.repo, &self.owner_id, refname, old, new) |
| 376 | .await |
| 377 | .expect("post-update"); |
| 378 | } |
| 379 | |
| 380 | |
| 381 | async fn deliveries(&self, event: WebhookEvent) -> Vec<(Delivery, Value)> { |
| 382 | let mut rows = self |
| 383 | .state |
| 384 | .store |
| 385 | .list_deliveries(&self.hook_id, 50) |
| 386 | .await |
| 387 | .expect("list"); |
| 388 | rows.reverse(); |
| 389 | rows.into_iter() |
| 390 | .filter(|d| d.event == event) |
| 391 | .map(|d| { |
| 392 | let body = serde_json::from_str(&d.request_body).expect("json body"); |
| 393 | (d, body) |
| 394 | }) |
| 395 | .collect() |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | #[tokio::test] |
| 400 | async fn push_through_post_update_enqueues_before_and_after() { |
| 401 | let fx = fixture().await; |
| 402 | let c1 = commit(&fx.work, "a.txt", "one"); |
| 403 | fx.update_ref("refs/heads/main", ZERO, &c1).await; |
| 404 | |
| 405 | let pushes = fx.deliveries(WebhookEvent::Push).await; |
| 406 | assert_eq!(pushes.len(), 1); |
| 407 | let (_, body) = &pushes[0]; |
| 408 | assert_eq!(body["ref"], "refs/heads/main"); |
| 409 | assert_eq!(body["before"], ZERO); |
| 410 | assert_eq!(body["after"], c1.as_str()); |
| 411 | assert_eq!(body["total_commits"], 1); |
| 412 | assert_eq!(body["commits"][0]["id"], c1.as_str()); |
| 413 | assert_eq!(body["commits"][0]["message"], "one"); |
| 414 | |
| 415 | |
| 416 | let creates = fx.deliveries(WebhookEvent::Create).await; |
| 417 | assert_eq!(creates.len(), 1); |
| 418 | assert_eq!(creates[0].1["ref"], "main"); |
| 419 | assert_eq!(creates[0].1["ref_type"], "branch"); |
| 420 | |
| 421 | let c2 = commit(&fx.work, "b.txt", "two"); |
| 422 | fx.update_ref("refs/heads/main", &c1, &c2).await; |
| 423 | let pushes = fx.deliveries(WebhookEvent::Push).await; |
| 424 | assert_eq!(pushes.len(), 2); |
| 425 | let (_, body) = &pushes[1]; |
| 426 | assert_eq!(body["before"], c1.as_str()); |
| 427 | assert_eq!(body["after"], c2.as_str()); |
| 428 | assert_eq!(body["total_commits"], 1); |
| 429 | assert_eq!(body["commits"][0]["id"], c2.as_str()); |
| 430 | |
| 431 | |
| 432 | |
| 433 | fx.update_ref("refs/heads/topic", ZERO, &c2).await; |
| 434 | fx.update_ref("refs/heads/topic", &c2, ZERO).await; |
| 435 | let deletes = fx.deliveries(WebhookEvent::Delete).await; |
| 436 | assert_eq!(deletes.len(), 1); |
| 437 | assert_eq!(deletes[0].1["ref"], "topic"); |
| 438 | assert_eq!(deletes[0].1["ref_type"], "branch"); |
| 439 | let pushes = fx.deliveries(WebhookEvent::Push).await; |
| 440 | assert_eq!(pushes.len(), 4); |
| 441 | assert_eq!(pushes[3].1["ref"], "refs/heads/topic"); |
| 442 | assert_eq!(pushes[3].1["after"], ZERO); |
| 443 | assert_eq!(pushes[3].1["total_commits"], 0); |
| 444 | } |
| 445 | |
| 446 | #[tokio::test] |
| 447 | async fn refs_outside_heads_and_tags_produce_no_events() { |
| 448 | let fx = fixture().await; |
| 449 | let c1 = commit(&fx.work, "a.txt", "one"); |
| 450 | let bare = fx.bare.to_str().expect("utf8"); |
| 451 | git(&fx.work, &["push", bare, &format!("{c1}:refs/notes/x")]); |
| 452 | after_ref_update(&fx.state, &fx.repo, &fx.owner_id, "refs/notes/x", ZERO, &c1) |
| 453 | .await |
| 454 | .expect("post-update"); |
| 455 | assert!(fx.deliveries(WebhookEvent::Push).await.is_empty()); |
| 456 | assert!(fx.deliveries(WebhookEvent::Create).await.is_empty()); |
| 457 | } |
| 458 | } |