Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions app/src/forge/events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
//! What a forge's webhook tells the domain (sc-8900, the seam with visualci features): one event per linked project,
//! dispatched by `forge::webhooks`, with the domain's listeners doing the work. Every event may arrive twice (a forge
//! retries a delivery), so listeners must be idempotent.

use serde::{Deserialize, Serialize};

/// A pull request merged: its approvals become the base branch's at the merge commit (`baselines::record_merge`).
#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)]
pub struct PullRequestMerged {
pub project_id: i64,
pub head: String,
pub base: String,
pub merge_commit: String,
}

/// A pull request closed without merging (`why` "pull_request"), or its branch deleted ("branch_deleted"): the
/// branch's builds waiting for review stop waiting.
#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)]
pub struct BranchClosed {
pub project_id: i64,
pub branch: String,
pub why: String,
}

/// A closed pull request reopened: its branch's newest closed build waits for review again.
#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)]
pub struct BranchReopened {
pub project_id: i64,
pub branch: String,
}

/// The repository was made private (`private`), or public or edited: the project's open source status is checked
/// again (when private, GitHub's word is enough).
#[derive(laravel::event::Event, Clone, Debug, Serialize, Deserialize)]
pub struct RepositoryVisibilityChanged {
pub project_id: i64,
pub private: bool,
}
1 change: 1 addition & 0 deletions app/src/forge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
//! side). These are the forge-neutral types: kinds, permissions, repository URLs, and what a sign-in learns. Each
//! forge's API calls are in its own module.

pub mod events;
pub mod github;
pub mod gitlab;

Expand Down
26 changes: 26 additions & 0 deletions app/src/listeners/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,29 @@ pub async fn purge_the_gallery(event: Event<crate::events::BuildChanged>) -> lar
.await?;
Ok(())
}

/// A pull request merged: its approvals become the base branch's at the merge commit. A delivery the forge sends twice
/// records nothing new the second time.
#[listener]
pub async fn record_merged_approvals(event: Event<crate::forge::events::PullRequestMerged>) -> laravel::Result<()> {
let recorded =
crate::domain::baselines::record_merge(event.project_id, &event.head, &event.base, &event.merge_commit).await?;
tracing::info!(project = event.project_id, head = %event.head, base = %event.base, recorded, "pull request merged");
Ok(())
}

/// A pull request closed without merging, or its branch deleted: the branch's builds waiting for review stop waiting.
#[listener]
pub async fn close_the_branchs_builds(event: Event<crate::forge::events::BranchClosed>) -> laravel::Result<()> {
let closed = crate::domain::builds::close_branch(event.project_id, &event.branch, &event.why).await?;
tracing::info!(project = event.project_id, branch = %event.branch, why = %event.why, closed, "branch closed");
Ok(())
}

/// A closed pull request reopened: its branch's newest closed build waits for review again.
#[listener]
pub async fn reopen_the_branchs_builds(event: Event<crate::forge::events::BranchReopened>) -> laravel::Result<()> {
let reopened = crate::domain::builds::reopen_branch(event.project_id, &event.branch).await?;
tracing::info!(project = event.project_id, branch = %event.branch, reopened, "branch reopened");
Ok(())
}
59 changes: 59 additions & 0 deletions app/tests/forge_events.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! The forge's events reach the domain through listeners (subdomains' webhooks dispatch them, one per linked project):
//! a merged pull request's approvals become the base branch's, and closing or reopening a branch closes or brings back
//! its builds waiting for review. A forge may deliver an event twice, so each is idempotent.

use app::domain::builds::{self, CreateParams};
use app::forge::events::{BranchClosed, BranchReopened, PullRequestMerged};
use app::models::Build;
use app::testing::fixtures;
use laravel::db;
use laravel::testing::prelude::*;

async fn waiting_build(project: &app::models::Project, branch: &str, commit: &str) -> laravel::Result<i64> {
let params: CreateParams = serde_json::from_value(serde_json::json!({ "commit": commit, "branch": branch }))?;
let build = builds::create(project, &params, None).await.map_err(|e| laravel::Error::msg(format!("{e:?}")))?;
let id = build.id;
db::query!("UPDATE builds SET state = 'completed', review_state = 'pending' WHERE id = {id}").update().await?;
Ok(id)
}

#[laravel::test]
async fn a_merged_pull_request_hands_its_approvals_to_the_base_branch(_app: Application) -> laravel::Result<()> {
let org = fixtures::organization("acme").await?;
let project = fixtures::project(&org, "docs").await?;
let build = waiting_build(&project, "feat", &"a".repeat(40)).await?;
let project_id = project.id;
db::query!(
"INSERT INTO baselines (project_id, build_name, name, platform, environment, branch, commit_sha, build_id, \
approval, mode, created_at) \
VALUES ({project_id}, 'default', 'invoice', '', '', 'feat', 'aaaa', {build}, 'review', 'ci', now())"
)
.insert()
.await?;
let merge = PullRequestMerged { project_id, head: "feat".into(), base: "main".into(), merge_commit: "m1".into() };
merge.clone().dispatch().await?;
merge.dispatch().await?;
let on_main: i64 = db::query!(
"SELECT COUNT(*) FROM baselines WHERE project_id = {project_id} AND branch = 'main' AND commit_sha = 'm1' \
AND approval = 'merged'"
)
.scalar()
.await?
.unwrap_or_default();
assert_eq!(on_main, 1, "the approval moved to main once, however often the event came");
Ok(())
}

#[laravel::test]
async fn closing_and_reopening_a_branch_closes_and_brings_back_its_builds(_app: Application) -> laravel::Result<()> {
let org = fixtures::organization("acme").await?;
let project = fixtures::project(&org, "docs").await?;
let id = waiting_build(&project, "feat", &"b".repeat(40)).await?;
let closed = BranchClosed { project_id: project.id, branch: "feat".into(), why: "pull_request".into() };
closed.clone().dispatch().await?;
closed.dispatch().await?;
assert_eq!(Build::find_or_fail(id).await?.review_state, "closed");
BranchReopened { project_id: project.id, branch: "feat".into() }.dispatch().await?;
assert_eq!(Build::find_or_fail(id).await?.review_state, "pending");
Ok(())
}
Loading