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): backfill open prs when sync app is installed (#3675)

Will Hutchinsona3867988968b
diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rs
index 573a229371..911be73c88 100644
--- a/rust/cloud-storage/github/src/domain/ports/sync.rs
+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs
@@ -3,8 +3,9 @@
use std::future::Future;
use crate::domain::models::{
- GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,
- GithubPullRequestDetails, MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent,
+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,
+ GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails, MacroTaskId,
+ TeamTaskReference, ValidatedGithubWebhookEvent,
};
/// Repository for accessing github sync data from the database.
@@ -106,6 +107,12 @@ pub trait GithubSyncClient: Send + Sync + 'static {
repo: &str,
number: u64,
) -> impl Future<Output = Result<GithubPullRequestDetails, GithubError>> + Send;
+
+ /// Lists open pull requests for repositories accessible to a GitHub App installation token.
+ fn list_open_pull_requests(
+ &self,
+ access_token: &str,
+ ) -> impl Future<Output = Result<Vec<EnrichedGithubPullRequest>, GithubError>> + Send;
}
/// Service interface for github sync operations (webhooks and sync app).
diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
index c42c4c7353..abf41d1893 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs
@@ -77,6 +77,9 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
.await
.map_err(|e| GithubError::Internal(e.into()))?;
+ self.backfill_open_pull_request_foreign_entities(installation_id, &sources)
+ .await?;
+
Ok(())
}
}
diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
index da66c83252..d4b4b1d269 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -9,9 +9,10 @@ mod handle_pr;
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GithubError, GithubInstallationAccessToken, GithubKey,
- GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId,
- TeamTaskReference, ValidatedGithubWebhookEvent,
+ EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,
+ GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails,
+ GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId, TeamTaskReference,
+ ValidatedGithubWebhookEvent,
},
ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},
};
@@ -318,6 +319,41 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
GithubPullRequestStatus::Open
}
+ /// Backfill foreign entity rows for open pull requests visible to a GitHub App installation.
+ #[tracing::instrument(skip(self, stored_for_sources), err)]
+ async fn backfill_open_pull_request_foreign_entities(
+ &self,
+ installation_id: u64,
+ stored_for_sources: &[GithubAppInstallationSource],
+ ) -> Result<(), GithubError> {
+ if stored_for_sources.is_empty() {
+ tracing::trace!(
+ installation_id,
+ "no GitHub App installation sources found for PR backfill"
+ );
+ return Ok(());
+ }
+
+ let token = self
+ .generate_installation_access_token(installation_id)
+ .await?;
+ let pull_requests = self.client.list_open_pull_requests(&token.token).await?;
+
+ tracing::info!(
+ installation_id,
+ pull_request_count = pull_requests.len(),
+ source_count = stored_for_sources.len(),
+ "backfilling open pull request foreign entities"
+ );
+
+ for pull_request in pull_requests {
+ self.upsert_enriched_pull_request_foreign_entities(pull_request, stored_for_sources)
+ .await;
+ }
+
+ Ok(())
+ }
+
/// Create or refresh foreign entity rows for a pull request, scoped to the
/// Macro source (team or user) associated with the GitHub App installation.
#[tracing::instrument(skip(self, event))]
@@ -353,6 +389,17 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient, F: ForeignEntit
return;
};
+ self.upsert_enriched_pull_request_foreign_entities(pull_request, &stored_for_sources)
+ .await;
+ }
+
+ /// Create or refresh foreign entity rows from already-enriched pull request metadata.
+ #[tracing::instrument(skip(self, pull_request, stored_for_sources))]
+ async fn upsert_enriched_pull_request_foreign_entities(
+ &self,
+ pull_request: EnrichedGithubPullRequest,
+ stored_for_sources: &[GithubAppInstallationSource],
+ ) {
let base_metadata = match serde_json::to_value(&pull_request) {
Ok(metadata) => metadata,
Err(error) => {
diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rs
index 81a8f9d917..5fece4aa01 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs
@@ -480,6 +480,8 @@ struct StubSyncClient {
pr_comments: Mutex<Vec<PrCommentCall>>,
pull_request_details: Mutex<HashMap<String, GithubPullRequestDetails>>,
pull_request_details_calls: Mutex<Vec<PullRequestDetailsCall>>,
+ open_pull_requests: Mutex<Vec<EnrichedGithubPullRequest>>,
+ list_open_pull_requests_calls: Mutex<Vec<String>>,
}
impl StubSyncClient {
@@ -488,6 +490,8 @@ impl StubSyncClient {
pr_comments: Mutex::new(Vec::new()),
pull_request_details: Mutex::new(HashMap::new()),
pull_request_details_calls: Mutex::new(Vec::new()),
+ open_pull_requests: Mutex::new(Vec::new()),
+ list_open_pull_requests_calls: Mutex::new(Vec::new()),
}
}
@@ -499,6 +503,14 @@ impl StubSyncClient {
self.pull_request_details_calls.lock().unwrap().clone()
}
+ fn list_open_pull_requests_calls(&self) -> Vec<String> {
+ self.list_open_pull_requests_calls.lock().unwrap().clone()
+ }
+
+ fn set_open_pull_requests(&self, pull_requests: Vec<EnrichedGithubPullRequest>) {
+ *self.open_pull_requests.lock().unwrap() = pull_requests;
+ }
+
fn set_pull_request_details(
&self,
owner: &str,
@@ -569,6 +581,18 @@ impl GithubSyncClient for StubSyncClient {
.cloned()
.ok_or_else(|| GithubError::Internal(anyhow::anyhow!("missing stub PR details")))
}
+
+ async fn list_open_pull_requests(
+ &self,
+ access_token: &str,
+ ) -> Result<Vec<EnrichedGithubPullRequest>, GithubError> {
+ self.list_open_pull_requests_calls
+ .lock()
+ .unwrap()
+ .push(access_token.to_string());
+
+ Ok(self.open_pull_requests.lock().unwrap().clone())
+ }
}
fn foreign_entity_id_from_receipt(
@@ -830,6 +854,23 @@ fn expected_pull_request_metadata(
.unwrap()
}
+fn backfilled_pull_request(title: &str) -> EnrichedGithubPullRequest {
+ EnrichedGithubPullRequest {
+ github_key: "my-org/my-repo/pull/42".to_string(),
+ owner: "my-org".to_string(),
+ repo: "my-repo".to_string(),
+ number: 42,
+ url: "https://github.com/my-org/my-repo/pull/42".to_string(),
+ display_name: "my-org/my-repo#42".to_string(),
+ name: Some(title.to_string()),
+ status: Some(GithubPullRequestStatus::Open),
+ additions: None,
+ deletions: None,
+ comments: None,
+ checks: None,
+ }
+}
+
fn expected_pull_request_metadata_from_details(
details: &GithubPullRequestDetails,
) -> serde_json::Value {
@@ -2508,6 +2549,130 @@ async fn installation_created_associates_teams() {
);
}
+#[tokio::test]
+async fn installation_created_backfills_open_pr_for_single_source() {
+ let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");
+
+ let service = make_sync_service_with_repo(repo);
+ let doc_service = service.document_service.clone();
+ let foreign_entity_service = service.foreign_entity_service.clone();
+ let pull_request = backfilled_pull_request("fixes MACRO-2BuyvtY3aeEvHx4uG8iD51");
+ let expected_metadata = serde_json::to_value(&pull_request).unwrap();
+ service.client.set_open_pull_requests(vec![pull_request]);
+ let event = installation_created_event(12345, 99999);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(
+ service.client.list_open_pull_requests_calls(),
+ vec!["test-token".to_string()]
+ );
+
+ let foreign_entities = foreign_entity_service.foreign_entities();
+ assert_eq!(foreign_entities.len(), 1);
+
+ let foreign_entity = &foreign_entities[0];
+ assert_eq!(foreign_entity.foreign_entity_id, "my-org/my-repo/pull/42");
+ assert_eq!(
+ foreign_entity.foreign_entity_source,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE
+ );
+ assert_eq!(foreign_entity.stored_for_id, "macro|[email protected]");
+ assert_eq!(foreign_entity.stored_for_auth_entity, "user");
+ assert_eq!(foreign_entity.metadata, expected_metadata);
+ assert_eq!(foreign_entity_service.create_calls().len(), 1);
+ assert!(foreign_entity_service.patch_calls().is_empty());
+ assert!(service.client.pr_comments().is_empty());
+ assert!(doc_service.task_status_calls().is_empty());
+}
+
+#[tokio::test]
+async fn installation_created_backfills_open_pr_for_multiple_sources() {
+ let team_a: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let team_b: uuid::Uuid = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_github_link("12345", "macro|[email protected]")
+ .with_user_teams("macro|[email protected]", vec![team_a, team_b]);
+
+ let service = make_sync_service_with_repo(repo);
+ let doc_service = service.document_service.clone();
+ let foreign_entity_service = service.foreign_entity_service.clone();
+ let pull_request = backfilled_pull_request("backfilled PR");
+ let expected_metadata = serde_json::to_value(&pull_request).unwrap();
+ service.client.set_open_pull_requests(vec![pull_request]);
+ let event = installation_created_event(12345, 99999);
+
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(
+ service.client.list_open_pull_requests_calls(),
+ vec!["test-token".to_string()]
+ );
+
+ let mut foreign_entities = foreign_entity_service.foreign_entities();
+ foreign_entities.sort_by(|left, right| left.stored_for_id.cmp(&right.stored_for_id));
+ assert_eq!(foreign_entities.len(), 2);
+
+ for foreign_entity in &foreign_entities {
+ assert_eq!(foreign_entity.foreign_entity_id, "my-org/my-repo/pull/42");
+ assert_eq!(
+ foreign_entity.foreign_entity_source,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE
+ );
+ assert_eq!(foreign_entity.stored_for_auth_entity, "team");
+ assert_eq!(foreign_entity.metadata, expected_metadata);
+ }
+
+ assert_eq!(foreign_entities[0].stored_for_id, team_a.to_string());
+ assert_eq!(foreign_entities[1].stored_for_id, team_b.to_string());
+ assert_eq!(foreign_entity_service.create_calls().len(), 2);
+ assert!(foreign_entity_service.patch_calls().is_empty());
+ assert!(service.client.pr_comments().is_empty());
+ assert!(doc_service.task_status_calls().is_empty());
+}
+
+#[tokio::test]
+async fn installation_created_backfill_is_idempotent() {
+ let team_id: uuid::Uuid = "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap();
+ let repo = StubSyncRepo::new()
+ .with_github_link("12345", "macro|[email protected]")
+ .with_user_teams("macro|[email protected]", vec![team_id]);
+
+ let service = make_sync_service_with_repo(repo);
+ let doc_service = service.document_service.clone();
+ let foreign_entity_service = service.foreign_entity_service.clone();
+ let pull_request = backfilled_pull_request("fixes MACRO-2BuyvtY3aeEvHx4uG8iD51");
+ let expected_metadata = serde_json::to_value(&pull_request).unwrap();
+ service.client.set_open_pull_requests(vec![pull_request]);
+ let event = installation_created_event(12345, 99999);
+
+ service.process_webhook_event(&event).await.unwrap();
+ service.process_webhook_event(&event).await.unwrap();
+
+ assert_eq!(
+ service.client.list_open_pull_requests_calls(),
+ vec!["test-token".to_string(), "test-token".to_string()]
+ );
+
+ let foreign_entities = foreign_entity_service.foreign_entities();
+ assert_eq!(foreign_entities.len(), 1);
+ assert_eq!(
+ foreign_entities[0].foreign_entity_id,
+ "my-org/my-repo/pull/42"
+ );
+ assert_eq!(foreign_entities[0].stored_for_id, team_id.to_string());
+ assert_eq!(foreign_entities[0].stored_for_auth_entity, "team");
+ assert_eq!(foreign_entities[0].metadata, expected_metadata);
+ assert_eq!(foreign_entity_service.create_calls().len(), 1);
+
+ let patch_calls = foreign_entity_service.patch_calls();
+ assert_eq!(patch_calls.len(), 1);
+ assert_eq!(patch_calls[0].0, foreign_entities[0].id);
+ assert_eq!(patch_calls[0].1.metadata, Some(expected_metadata));
+ assert!(service.client.pr_comments().is_empty());
+ assert!(doc_service.task_status_calls().is_empty());
+}
+
#[tokio::test]
async fn installation_created_no_github_link() {
let service = make_sync_service();
@@ -2517,6 +2682,7 @@ async fn installation_created_no_github_link() {
service.process_webhook_event(&event).await.unwrap();
assert!(service.repo.installation_sources().is_empty());
+ assert!(service.client.list_open_pull_requests_calls().is_empty());
}
#[tokio::test]
diff --git a/rust/cloud-storage/github/src/outbound/github_sync_client.rs b/rust/cloud-storage/github/src/outbound/github_sync_client.rs
index 3eaf5e92e2..515e87c4be 100644
--- a/rust/cloud-storage/github/src/outbound/github_sync_client.rs
+++ b/rust/cloud-storage/github/src/outbound/github_sync_client.rs
@@ -1,9 +1,14 @@
//! Github Sync Client implementation of the [`GithubSyncClient`] port.
-use super::pull_request_metadata::fetch_pull_request_metadata;
+use super::pull_request_metadata::{
+ fetch_open_pull_requests_for_installation, fetch_pull_request_metadata,
+};
use crate::domain::{
- models::{GithubError, GithubInstallationAccessToken, GithubPullRequestDetails},
+ models::{
+ EnrichedGithubPullRequest, GithubError, GithubInstallationAccessToken,
+ GithubPullRequestDetails,
+ },
ports::GithubSyncClient,
};
@@ -102,4 +107,14 @@ impl GithubSyncClient for GithubSyncClientImpl {
.await
.map_err(GithubError::Internal)
}
+
+ #[tracing::instrument(skip(self, access_token), err)]
+ async fn list_open_pull_requests(
+ &self,
+ access_token: &str,
+ ) -> Result<Vec<EnrichedGithubPullRequest>, GithubError> {
+ fetch_open_pull_requests_for_installation(&self.client, access_token)
+ .await
+ .map_err(GithubError::Internal)
+ }
}
diff --git a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
index a5e16a27ac..eed0a600d7 100644
--- a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
+++ b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs
@@ -5,7 +5,8 @@ use std::time::Duration;
use serde::de::DeserializeOwned;
use crate::domain::models::{
- GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
+ EnrichedGithubPullRequest, GithubKey, GithubPullRequestCheckRun, GithubPullRequestComment,
+ GithubPullRequestDetails, GithubPullRequestStatus,
};
const GITHUB_API_BASE_URL: &str = "https://api.github.com";
@@ -43,6 +44,98 @@ pub(crate) async fn fetch_pull_request_metadata(
})
}
+/// Fetch open pull requests for every repository accessible to an installation token.
+pub(crate) async fn fetch_open_pull_requests_for_installation(
+ client: &reqwest::Client,
+ access_token: &str,
+) -> Result<Vec<EnrichedGithubPullRequest>, anyhow::Error> {
+ let repositories = fetch_installation_repositories(client, access_token).await?;
+ let mut open_pull_requests = Vec::new();
+
+ for repository in repositories {
+ match fetch_open_pull_requests_for_repository(client, access_token, &repository).await {
+ Ok(repository_pull_requests) => open_pull_requests.extend(repository_pull_requests),
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ owner=%repository.owner.login,
+ repo=%repository.name,
+ "failed to fetch GitHub open pull requests for repository"
+ );
+ }
+ }
+ }
+
+ Ok(open_pull_requests)
+}
+
+async fn fetch_installation_repositories(
+ client: &reqwest::Client,
+ access_token: &str,
+) -> Result<Vec<GithubInstallationRepositoryResponse>, anyhow::Error> {
+ fetch_paginated_github_items(
+ client,
+ access_token,
+ |page| {
+ format!(
+ "{GITHUB_API_BASE_URL}/installation/repositories?per_page={METADATA_PAGE_SIZE}&page={page}"
+ )
+ },
+ "installation repositories",
+ |response: GithubInstallationRepositoriesResponse| response.repositories,
+ )
+ .await
+}
+
+async fn fetch_open_pull_requests_for_repository(
+ client: &reqwest::Client,
+ access_token: &str,
+ repository: &GithubInstallationRepositoryResponse,
+) -> Result<Vec<EnrichedGithubPullRequest>, anyhow::Error> {
+ let owner = repository.owner.login.as_str();
+ let repo = repository.name.as_str();
+ let pull_requests = fetch_paginated_github_items(
+ client,
+ access_token,
+ |page| {
+ format!(
+ "{GITHUB_API_BASE_URL}/repos/{owner}/{repo}/pulls?state=open&per_page={METADATA_PAGE_SIZE}&page={page}"
+ )
+ },
+ "open pull requests",
+ |pull_requests: Vec<GithubOpenPullRequestResponse>| pull_requests,
+ )
+ .await?;
+
+ Ok(pull_requests
+ .into_iter()
+ .map(|pull_request| pull_request.into_enriched_pull_request(owner, repo))
+ .collect())
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct GithubInstallationRepositoriesResponse {
+ repositories: Vec<GithubInstallationRepositoryResponse>,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct GithubInstallationRepositoryResponse {
+ name: String,
+ owner: GithubRepositoryOwnerResponse,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct GithubRepositoryOwnerResponse {
+ login: String,
+}
+
+#[derive(Debug, serde::Deserialize)]
+struct GithubOpenPullRequestResponse {
+ number: u64,
+ title: String,
+ html_url: String,
+}
+
#[derive(Debug, serde::Deserialize)]
struct GithubPullRequestResponse {
title: String,
@@ -370,6 +463,25 @@ fn github_get(
.timeout(REQUEST_TIMEOUT)
}
+impl GithubOpenPullRequestResponse {
+ fn into_enriched_pull_request(self, owner: &str, repo: &str) -> EnrichedGithubPullRequest {
+ EnrichedGithubPullRequest {
+ github_key: GithubKey::new(owner, repo, self.number).to_string(),
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ number: self.number,
+ url: self.html_url,
+ display_name: format!("{owner}/{repo}#{}", self.number),
+ name: Some(self.title),
+ status: Some(GithubPullRequestStatus::Open),
+ additions: None,
+ deletions: None,
+ comments: None,
+ checks: None,
+ }
+ }
+}
+
impl GithubCommentResponse {
fn into_pull_request_comment(self, source: &str) -> GithubPullRequestComment {
GithubPullRequestComment {