Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(github): handle installation.deleted events (#5334)

Will Hutchinson3bd873f26554
diff --git a/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json b/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json
new file mode 100644
index 0000000000..8b8cc329a2
--- /dev/null
+++ b/.sqlx/query-43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM github_app_installation_installer\n WHERE installation_id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "43bf593bf69fc1d4f0afdac8738096fc0c1b5ede2c495656d4d7912e55eaaa41"
+}
diff --git a/.sqlx/query-e5d13b4af61fa5124ac0425c0a617db6e78bfeb23ae218cdda2d3ebe7619733d.json b/.sqlx/query-e5d13b4af61fa5124ac0425c0a617db6e78bfeb23ae218cdda2d3ebe7619733d.json
new file mode 100644
index 0000000000..9101a16898
--- /dev/null
+++ b/.sqlx/query-e5d13b4af61fa5124ac0425c0a617db6e78bfeb23ae218cdda2d3ebe7619733d.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM github_app_installation\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "e5d13b4af61fa5124ac0425c0a617db6e78bfeb23ae218cdda2d3ebe7619733d"
+}
diff --git a/crates/github/src/domain/ports/sync.rs b/crates/github/src/domain/ports/sync.rs
index 7cf8eeef4e..5d8c6cc6fc 100644
--- a/crates/github/src/domain/ports/sync.rs
+++ b/crates/github/src/domain/ports/sync.rs
@@ -114,6 +114,20 @@ pub trait GithubSyncRepo: Send + Sync + 'static {
&self,
github_user_id: &str,
) -> impl Future<Output = Result<Vec<String>, Self::Err>> + Send;
+
+ /// Deletes all source associations for a GitHub App installation.
+ /// Deleting an installation with no associations is a no-op (idempotent).
+ fn delete_installation_sources(
+ &self,
+ installation_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Deletes the recorded installer for a GitHub App installation.
+ /// Deleting an installation with no recorded installer is a no-op (idempotent).
+ fn delete_installation_installer(
+ &self,
+ installation_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
/// Client interface for making GitHub sync API calls.
diff --git a/crates/github/src/domain/service/sync/handle_installation.rs b/crates/github/src/domain/service/sync/handle_installation.rs
index dda4217d3e..3ddf28c83b 100644
--- a/crates/github/src/domain/service/sync/handle_installation.rs
+++ b/crates/github/src/domain/service/sync/handle_installation.rs
@@ -56,6 +56,37 @@ impl<
.await
}
+ /// Handle `installation` events with action `deleted`.
+ ///
+ /// Removes the installation's source associations and recorded installer
+ /// so the installation is no longer used for PR backfills or retroactive
+ /// association when a github link is created later. Idempotent: GitHub
+ /// retries webhooks, so deleting an already-removed installation succeeds.
+ #[tracing::instrument(skip(self, event), err)]
+ pub(crate) async fn handle_installation_deleted(
+ &self,
+ event: &ValidatedGithubWebhookEvent,
+ ) -> Result<(), GithubError> {
+ let installation_id = event
+ .installation_id()
+ .ok_or_else(|| GithubError::Internal(anyhow::anyhow!("missing installation.id")))?
+ .to_string();
+
+ tracing::info!(installation_id, "processing installation deleted event");
+
+ self.repo
+ .delete_installation_sources(&installation_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ self.repo
+ .delete_installation_installer(&installation_id)
+ .await
+ .map_err(|e| GithubError::Internal(e.into()))?;
+
+ Ok(())
+ }
+
/// Compute the Macro sources (teams or users) for every Macro user linked
/// to the given GitHub user. Returns an empty list when no link exists.
pub(crate) async fn sources_for_github_user(
diff --git a/crates/github/src/domain/service/sync/mod.rs b/crates/github/src/domain/service/sync/mod.rs
index 5a31db951c..0c0868fdad 100644
--- a/crates/github/src/domain/service/sync/mod.rs
+++ b/crates/github/src/domain/service/sync/mod.rs
@@ -981,6 +981,7 @@ impl<
}
GithubWebhookEventType::Installation => match action {
Some("created") => self.handle_installation_created(webhook_event).await,
+ Some("deleted") => self.handle_installation_deleted(webhook_event).await,
_ => {
tracing::debug!(action, "skipping unhandled installation action");
Ok(())
diff --git a/crates/github/src/domain/service/sync/test.rs b/crates/github/src/domain/service/sync/test.rs
index 73884747aa..41cc93a287 100644
--- a/crates/github/src/domain/service/sync/test.rs
+++ b/crates/github/src/domain/service/sync/test.rs
@@ -618,6 +618,22 @@ impl GithubSyncRepo for StubSyncRepo {
installation_ids.sort();
Ok(installation_ids)
}
+
+ async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {
+ self.installation_source_rows
+ .lock()
+ .unwrap()
+ .remove(installation_id);
+ Ok(())
+ }
+
+ async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {
+ self.installation_installers
+ .lock()
+ .unwrap()
+ .remove(installation_id);
+ Ok(())
+ }
}
#[tokio::test]
@@ -4087,6 +4103,94 @@ async fn installation_created_records_installer_with_github_link() {
);
}
+// ---------------------------------------------------------------------------
+// installation deleted
+// ---------------------------------------------------------------------------
+
+fn installation_deleted_event(sender_id: u64, installation_id: u64) -> ValidatedGithubWebhookEvent {
+ ValidatedGithubWebhookEvent::new(
+ "installation".to_string(),
+ serde_json::json!({
+ "action": "deleted",
+ "installation": { "id": installation_id },
+ "sender": { "login": "testuser", "id": sender_id }
+ }),
+ )
+}
+
+#[tokio::test]
+async fn installation_deleted_removes_sources_and_installer() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+
+ let repo = StubSyncRepo::new()
+ .with_installation_sources("99999", vec![GithubAppInstallationSource::Team(team_id)])
+ .with_installation_sources(
+ "88888",
+ vec![GithubAppInstallationSource::User(
+ "macro|[email protected]".to_string(),
+ )],
+ )
+ .with_installation_installer("99999", "12345")
+ .with_installation_installer("88888", "67890");
+
+ let service = make_sync_service_with_repo(repo);
+ let event = installation_deleted_event(12345, 99999);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert!(
+ service
+ .repo
+ .get_installation_sources("99999")
+ .await
+ .unwrap()
+ .is_empty()
+ );
+ assert_eq!(
+ service.repo.installation_installers(),
+ HashMap::from([("88888".to_string(), "67890".to_string())])
+ );
+
+ // Other installations are untouched.
+ assert_eq!(
+ service
+ .repo
+ .get_installation_sources("88888")
+ .await
+ .unwrap(),
+ vec![GithubAppInstallationSource::User(
+ "macro|[email protected]".to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn installation_deleted_unknown_installation_succeeds() {
+ let service = make_sync_service();
+ let event = installation_deleted_event(12345, 99999);
+
+ // GitHub retries webhooks: deleting an installation we never recorded
+ // (or already deleted) must succeed.
+ service.process_webhook_event(&event).await.unwrap();
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert!(service.repo.installation_installers().is_empty());
+}
+
+#[tokio::test]
+async fn installation_deleted_missing_installation_id_errors() {
+ let service = make_sync_service();
+ let event = ValidatedGithubWebhookEvent::new(
+ "installation".to_string(),
+ serde_json::json!({
+ "action": "deleted",
+ "sender": { "login": "testuser", "id": 12345 }
+ }),
+ );
+
+ service.process_webhook_event(&event).await.unwrap_err();
+}
+
#[tokio::test]
async fn associate_installations_for_github_user_associates_and_backfills() {
let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
diff --git a/crates/github/src/outbound/pg_github_sync_repo.rs b/crates/github/src/outbound/pg_github_sync_repo.rs
index 9f95feb2fe..cf57e36ee6 100644
--- a/crates/github/src/outbound/pg_github_sync_repo.rs
+++ b/crates/github/src/outbound/pg_github_sync_repo.rs
@@ -408,4 +408,34 @@ impl GithubSyncRepo for PgGithubSyncRepo {
Ok(installation_ids)
}
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete_installation_sources(&self, installation_id: &str) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ DELETE FROM github_app_installation
+ WHERE id = $1
+ "#,
+ installation_id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete_installation_installer(&self, installation_id: &str) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ DELETE FROM github_app_installation_installer
+ WHERE installation_id = $1
+ "#,
+ installation_id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
}
diff --git a/crates/github/src/outbound/pg_github_sync_repo/test.rs b/crates/github/src/outbound/pg_github_sync_repo/test.rs
index 1097e8d646..c2353a3323 100644
--- a/crates/github/src/outbound/pg_github_sync_repo/test.rs
+++ b/crates/github/src/outbound/pg_github_sync_repo/test.rs
@@ -929,3 +929,69 @@ async fn test_get_installation_ids_by_installer_empty(pool: Pool<Postgres>) {
assert!(installation_ids.is_empty());
}
+
+// ---------------------------------------------------------------------------
+// delete_installation_sources / delete_installation_installer
+// ---------------------------------------------------------------------------
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))
+)]
+async fn test_delete_installation_sources_removes_all_sources(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool.clone());
+
+ let sources = vec![
+ GithubAppInstallationSource::Team("dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap()),
+ GithubAppInstallationSource::User("macro|[email protected]".to_string()),
+ ];
+ repo.upsert_installation_sources("123456", &sources)
+ .await
+ .unwrap();
+ repo.upsert_installation_sources("654321", &sources)
+ .await
+ .unwrap();
+
+ repo.delete_installation_sources("123456").await.unwrap();
+
+ assert!(get_installation_sources(&pool, "123456").await.is_empty());
+ // Other installations keep their sources.
+ assert_eq!(get_installation_sources(&pool, "654321").await.len(), 2);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_delete_installation_sources_missing_installation_is_noop(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ repo.delete_installation_sources("missing").await.unwrap();
+ repo.delete_installation_sources("missing").await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_delete_installation_installer_removes_installer(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ repo.upsert_installation_installer("11111", "12345")
+ .await
+ .unwrap();
+ repo.upsert_installation_installer("22222", "12345")
+ .await
+ .unwrap();
+
+ repo.delete_installation_installer("11111").await.unwrap();
+
+ assert_eq!(
+ repo.get_installation_ids_by_installer("12345")
+ .await
+ .unwrap(),
+ vec!["22222"]
+ );
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_delete_installation_installer_missing_installation_is_noop(pool: Pool<Postgres>) {
+ let repo = PgGithubSyncRepo::new(pool);
+
+ repo.delete_installation_installer("missing").await.unwrap();
+ repo.delete_installation_installer("missing").await.unwrap();
+}