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): update foreign entity when github pr is enriched (#3743)

Will Hutchinson0e86b84c0b94
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 533c7ba491..072263ef2e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -654,6 +654,7 @@ dependencies = [
"doppleganger",
"email_validator",
"entity_access",
+ "foreign_entity",
"fusionauth",
"futures",
"github",
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 0557f0067d..c5acee8d9d 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -43,6 +43,7 @@ document_storage_service_client = { path = "../document_storage_service_client"
doppleganger = { workspace = true }
email_validator = { path = "../email_validator" }
entity_access = { path = "../entity_access" }
+foreign_entity = { path = "../foreign_entity" }
fusionauth = { path = "../fusionauth" }
futures = { workspace = true }
github = { path = "../github", default-features = false, features = [
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index f7b4e74524..ba32a62147 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -4,6 +4,8 @@ use analytics_client::AnalyticsClient;
use axum::extract::FromRef;
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
+use foreign_entity::domain::service::ForeignEntityServiceImpl;
+use foreign_entity::outbound::pg_foreign_entity_repo::PgForeignEntityRepo;
use github::domain::service::GithubLinkServiceImpl;
use github::outbound::github_auth_client::GithubAuthImpl;
use github::outbound::github_oauth_client::GithubOauthImpl;
@@ -51,8 +53,12 @@ pub(crate) type ReferralServiceType = ReferralServiceImpl<
Arc<SqsNotificationIngress<SqsQueue>>,
>;
-pub(crate) type GithubLinkServiceType =
- GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;
+pub(crate) type GithubLinkServiceType = GithubLinkServiceImpl<
+ PgGithubRepo,
+ GithubOauthImpl,
+ GithubAuthImpl,
+ ForeignEntityServiceImpl<PgForeignEntityRepo>,
+>;
pub(crate) type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 594d0fcdcf..a971fa9a26 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -6,6 +6,10 @@ use anyhow::{Context, anyhow};
use config::{Config, Environment};
use document_storage_service_client::DocumentStorageServiceClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
+use foreign_entity::{
+ domain::service::ForeignEntityServiceImpl,
+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
+};
use github::{
domain::service::{GithubLinkConfig, GithubLinkServiceImpl},
outbound::{
@@ -261,10 +265,14 @@ async fn main() -> anyhow::Result<()> {
team_crm_settings_repo_impl,
);
+ let foreign_entity_service =
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));
+
let github_link_service_impl = GithubLinkServiceImpl::new(
PgGithubRepo::new(db.clone()),
GithubOauthImpl::default(),
GithubAuthImpl::new(auth_client.clone(), redis_multiplexed_conn),
+ foreign_entity_service,
GithubLinkConfig {
client_id: config.github_client_id,
client_secret: config.github_client_secret,
diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.toml
index a82e1f3ae0..c536fe38e8 100644
--- a/rust/cloud-storage/github/Cargo.toml
+++ b/rust/cloud-storage/github/Cargo.toml
@@ -8,7 +8,7 @@ version = "0.1.0"
axum = ["dep:axum", "dep:axum-extra", "dep:model-error-response", "dep:utoipa"]
default = ["axum", "inbound", "link", "outbound", "ports", "sync"]
inbound = ["axum", "ports"]
-link = ["ports"]
+link = ["dep:entity_access", "dep:foreign_entity", "ports"]
outbound = [
"dep:fusionauth",
"dep:redis",
diff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rs
index 58432abe1d..08637b45ae 100644
--- a/rust/cloud-storage/github/src/domain/models/mod.rs
+++ b/rust/cloud-storage/github/src/domain/models/mod.rs
@@ -10,8 +10,9 @@ mod sync;
pub use link::{GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubUserInfo};
pub use pull_request::{
EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,
- EnrichedGithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment,
- GithubPullRequestDetails, GithubPullRequestRef, GithubPullRequestStatus,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestDetails,
+ GithubPullRequestRef, GithubPullRequestStatus,
};
pub use sync::{
GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,
diff --git a/rust/cloud-storage/github/src/domain/models/pull_request.rs b/rust/cloud-storage/github/src/domain/models/pull_request.rs
index d6f8c37d9f..2a3fdbdeb6 100644
--- a/rust/cloud-storage/github/src/domain/models/pull_request.rs
+++ b/rust/cloud-storage/github/src/domain/models/pull_request.rs
@@ -4,6 +4,9 @@ use std::fmt;
use serde::{Deserialize, Serialize};
+/// Foreign entity source used for GitHub pull request metadata rows.
+pub const GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE: &str = "github_pull_request";
+
/// A pull request reference that can be enriched with live GitHub data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
@@ -241,6 +244,37 @@ impl EnrichedGithubPullRequest {
checks: details.checks,
}
}
+
+ /// Serialize this pull request into the metadata shape stored on GitHub pull request foreign entities.
+ ///
+ /// Partial refreshes may omit `comments` or `checks`. When an omitted field exists as an array in
+ /// `existing_metadata`, the existing array is copied forward so richer metadata is not discarded.
+ pub fn foreign_entity_metadata(
+ &self,
+ existing_metadata: Option<&serde_json::Value>,
+ ) -> serde_json::Result<serde_json::Value> {
+ let mut metadata = serde_json::to_value(self)?;
+ let Some(existing_object) = existing_metadata.and_then(|value| value.as_object()) else {
+ return Ok(metadata);
+ };
+ let Some(metadata_object) = metadata.as_object_mut() else {
+ return Ok(metadata);
+ };
+
+ for field in ["comments", "checks"] {
+ if metadata_object.contains_key(field) {
+ continue;
+ }
+
+ if let Some(existing_value) = existing_object.get(field)
+ && existing_value.is_array()
+ {
+ metadata_object.insert(field.to_string(), existing_value.clone());
+ }
+ }
+
+ Ok(metadata)
+ }
}
/// Request body for the authenticated pull request enrichment proxy.
diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rs
index f20e8551d9..7d44d0834e 100644
--- a/rust/cloud-storage/github/src/domain/models/test.rs
+++ b/rust/cloud-storage/github/src/domain/models/test.rs
@@ -288,6 +288,150 @@ fn pull_request_enrichment_copies_details_fields() {
assert_eq!(enriched.checks, Some(checks));
}
+#[test]
+fn pull_request_foreign_entity_metadata_serializes_enriched_pull_request() {
+ assert_eq!(
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ "github_pull_request"
+ );
+
+ let reference = pull_request_reference();
+ let details = GithubPullRequestDetails {
+ title: "Add pull request enrichment".to_string(),
+ state: "closed".to_string(),
+ merged_at: Some(utc_datetime("2026-05-25T18:54:21Z")),
+ additions: 42,
+ deletions: 12,
+ comments: Some(vec![pull_request_comment()]),
+ checks: Some(vec![pull_request_check_run()]),
+ };
+ let enriched = EnrichedGithubPullRequest::from_details(reference, details);
+
+ let metadata = enriched.foreign_entity_metadata(None).unwrap();
+
+ assert_eq!(
+ metadata,
+ serde_json::json!({
+ "githubKey": "macro/app/pull/7",
+ "owner": "macro",
+ "repo": "app",
+ "number": 7,
+ "url": "https://github.com/macro/app/pull/7",
+ "displayName": "macro/app#7",
+ "name": "Add pull request enrichment",
+ "status": "merged",
+ "additions": 42,
+ "deletions": 12,
+ "comments": [
+ {
+ "id": 101,
+ "body": "Looks good to me",
+ "authorLogin": "octocat",
+ "authorAssociation": "MEMBER",
+ "url": "https://github.com/macro/app/pull/7#issuecomment-101",
+ "createdAt": "2026-05-25T18:54:21Z",
+ "updatedAt": "2026-05-25T19:00:00Z",
+ "source": "issue_comment"
+ }
+ ],
+ "checks": [
+ {
+ "id": 202,
+ "name": "ci",
+ "status": "completed",
+ "conclusion": "success",
+ "url": "https://github.com/macro/app/actions/runs/202",
+ "startedAt": "2026-05-25T18:55:00Z",
+ "completedAt": "2026-05-25T18:59:00Z"
+ }
+ ]
+ })
+ );
+}
+
+#[test]
+fn pull_request_foreign_entity_metadata_preserves_existing_arrays_when_refresh_omits_them() {
+ let enriched = EnrichedGithubPullRequest::from_details(
+ pull_request_reference(),
+ pull_request_details("open", None),
+ );
+ let existing_metadata = serde_json::json!({
+ "comments": [
+ {
+ "id": 303,
+ "body": "Existing comment"
+ }
+ ],
+ "checks": [
+ {
+ "id": 404,
+ "name": "existing-ci"
+ }
+ ]
+ });
+
+ let metadata = enriched
+ .foreign_entity_metadata(Some(&existing_metadata))
+ .unwrap();
+
+ assert_eq!(
+ metadata,
+ serde_json::json!({
+ "githubKey": "macro/app/pull/7",
+ "owner": "macro",
+ "repo": "app",
+ "number": 7,
+ "url": "https://github.com/macro/app/pull/7",
+ "displayName": "macro/app#7",
+ "name": "Add pull request enrichment",
+ "status": "open",
+ "additions": 42,
+ "deletions": 12,
+ "comments": [
+ {
+ "id": 303,
+ "body": "Existing comment"
+ }
+ ],
+ "checks": [
+ {
+ "id": 404,
+ "name": "existing-ci"
+ }
+ ]
+ })
+ );
+}
+
+#[test]
+fn pull_request_foreign_entity_metadata_keeps_fresh_arrays() {
+ let comments = vec![pull_request_comment()];
+ let checks = vec![pull_request_check_run()];
+ let details = GithubPullRequestDetails {
+ title: "Add pull request enrichment".to_string(),
+ state: "open".to_string(),
+ merged_at: None,
+ additions: 42,
+ deletions: 12,
+ comments: Some(comments.clone()),
+ checks: Some(checks.clone()),
+ };
+ let enriched = EnrichedGithubPullRequest::from_details(pull_request_reference(), details);
+ let existing_metadata = serde_json::json!({
+ "comments": [{ "id": 303, "body": "Existing comment" }],
+ "checks": [{ "id": 404, "name": "existing-ci" }]
+ });
+ let fresh_comments = serde_json::to_value(&comments).unwrap();
+ let fresh_checks = serde_json::to_value(&checks).unwrap();
+
+ let metadata = enriched
+ .foreign_entity_metadata(Some(&existing_metadata))
+ .unwrap();
+
+ assert_eq!(metadata.get("comments"), Some(&fresh_comments));
+ assert_eq!(metadata.get("checks"), Some(&fresh_checks));
+}
+
// ---------------------------------------------------------------------------
// MacroTaskId::from_short_uuid
// ---------------------------------------------------------------------------
diff --git a/rust/cloud-storage/github/src/domain/service/link.rs b/rust/cloud-storage/github/src/domain/service/link.rs
index bf4f99e347..f73b3ece73 100644
--- a/rust/cloud-storage/github/src/domain/service/link.rs
+++ b/rust/cloud-storage/github/src/domain/service/link.rs
@@ -1,6 +1,7 @@
//! Github Link Service implemenation
use chrono::Utc;
+use foreign_entity::domain::{models::PatchForeignEntity, ports::ForeignEntityService};
use macro_user_id::{
lowercased::Lowercase,
user_id::{MacroUserId, MacroUserIdStr},
@@ -8,7 +9,8 @@ use macro_user_id::{
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubLink, GithubPullRequestRef,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubAccessToken,
+ GithubError, GithubLink, GithubPullRequestRef,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -25,20 +27,30 @@ pub struct GithubLinkConfig {
}
/// The concrete github link service implementation.
-pub struct GithubLinkServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth> {
+pub struct GithubLinkServiceImpl<R: GithubRepo, U: GithubOauth, F: Auth, E: ForeignEntityService> {
repo: R,
oauth: U,
auth: F,
+ foreign_entity_service: E,
config: super::GithubLinkConfig,
}
-impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {
+impl<R: GithubRepo, U: GithubOauth, F: Auth, E: ForeignEntityService>
+ GithubLinkServiceImpl<R, U, F, E>
+{
/// Create a new github link service.
- pub fn new(repo: R, oauth: U, auth: F, config: super::GithubLinkConfig) -> Self {
+ pub fn new(
+ repo: R,
+ oauth: U,
+ auth: F,
+ foreign_entity_service: E,
+ config: super::GithubLinkConfig,
+ ) -> Self {
Self {
repo,
oauth,
auth,
+ foreign_entity_service,
config,
}
}
@@ -87,9 +99,68 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkServiceImpl<R, U, F> {
Ok(access_token)
}
+
+ async fn patch_pull_request_foreign_entities(&self, pull_request: &EnrichedGithubPullRequest) {
+ let foreign_entities = match self
+ .foreign_entity_service
+ .get_foreign_entities_by_foreign_entity_id(
+ &pull_request.github_key,
+ Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE),
+ )
+ .await
+ {
+ Ok(foreign_entities) => foreign_entities,
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ github_key=%pull_request.github_key,
+ source=%GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ "failed to fetch GitHub pull request foreign entities"
+ );
+ return;
+ }
+ };
+
+ for foreign_entity in foreign_entities {
+ let foreign_entity_record_id = foreign_entity.id;
+ let metadata =
+ match pull_request.foreign_entity_metadata(Some(&foreign_entity.metadata)) {
+ Ok(metadata) => metadata,
+ Err(error) => {
+ tracing::warn!(
+ error=?error,
+ foreign_entity_record_id=%foreign_entity_record_id,
+ github_key=%pull_request.github_key,
+ "failed to serialize GitHub pull request foreign entity metadata"
+ );
+ continue;
+ }
+ };
+
+ let patch = PatchForeignEntity {
+ metadata: Some(metadata),
+ ..PatchForeignEntity::default()
+ };
+
+ if let Err(error) = self
+ .foreign_entity_service
+ .patch_foreign_entity(foreign_entity_record_id, patch)
+ .await
+ {
+ tracing::warn!(
+ error=?error,
+ foreign_entity_record_id=%foreign_entity_record_id,
+ github_key=%pull_request.github_key,
+ "failed to patch GitHub pull request foreign entity"
+ );
+ }
+ }
+ }
}
-impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkServiceImpl<R, U, F> {
+impl<R: GithubRepo, U: GithubOauth, F: Auth, E: ForeignEntityService> GithubLinkService
+ for GithubLinkServiceImpl<R, U, F, E>
+{
#[tracing::instrument(skip(self), err)]
fn construct_oauth_url<T: serde::Serialize + std::fmt::Debug + 'static>(
&self,
@@ -147,7 +218,13 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkSer
.await;
let enriched_pull_request = match details {
- Ok(details) => EnrichedGithubPullRequest::from_details(pull_request, details),
+ Ok(details) => {
+ let enriched_pull_request =
+ EnrichedGithubPullRequest::from_details(pull_request, details);
+ self.patch_pull_request_foreign_entities(&enriched_pull_request)
+ .await;
+ enriched_pull_request
+ }
Err(e) => {
tracing::warn!(
error=?e,
diff --git a/rust/cloud-storage/github/src/domain/service/link_test.rs b/rust/cloud-storage/github/src/domain/service/link_test.rs
index 5e3310fb1e..17590ba43c 100644
--- a/rust/cloud-storage/github/src/domain/service/link_test.rs
+++ b/rust/cloud-storage/github/src/domain/service/link_test.rs
@@ -1,6 +1,13 @@
use std::sync::{Arc, Mutex};
use chrono::Utc;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use foreign_entity::domain::{
+ models::{
+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,
+ },
+ ports::{ForeignEntityListQuery, ForeignEntityService},
+};
use macro_user_id::{
lowercased::Lowercase,
user_id::{MacroUserId, MacroUserIdStr},
@@ -8,8 +15,9 @@ use macro_user_id::{
use crate::domain::{
models::{
- GithubAccessToken, GithubError, GithubExchangeTokenResponse, GithubLink,
- GithubPullRequestDetails, GithubPullRequestRef, GithubUserInfo,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubAccessToken,
+ GithubError, GithubExchangeTokenResponse, GithubLink, GithubPullRequestDetails,
+ GithubPullRequestRef, GithubUserInfo,
},
ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},
};
@@ -80,6 +88,8 @@ struct StubGithubOauthState {
token_is_expired: bool,
validated_tokens: Vec<String>,
pull_request_detail_calls: Vec<PullRequestDetailCall>,
+ pull_request_details: Option<GithubPullRequestDetails>,
+ pull_request_detail_error: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -107,6 +117,22 @@ impl StubGithubOauth {
fn pull_request_detail_calls(&self) -> Vec<PullRequestDetailCall> {
self.state.lock().unwrap().pull_request_detail_calls.clone()
}
+
+ fn fail_pull_request_details(&self, error: &str) {
+ self.state.lock().unwrap().pull_request_detail_error = Some(error.to_string());
+ }
+}
+
+fn default_pull_request_details() -> GithubPullRequestDetails {
+ GithubPullRequestDetails {
+ title: "Add token validation".to_string(),
+ state: "open".to_string(),
+ merged_at: None,
+ additions: 12,
+ deletions: 3,
+ comments: None,
+ checks: None,
+ }
}
impl GithubOauth for StubGithubOauth {
@@ -160,26 +186,22 @@ impl GithubOauth for StubGithubOauth {
repo: &str,
number: u64,
) -> Result<GithubPullRequestDetails, Self::Err> {
- self.state
- .lock()
- .unwrap()
- .pull_request_detail_calls
- .push(PullRequestDetailCall {
- access_token: access_token.to_string(),
- owner: owner.to_string(),
- repo: repo.to_string(),
- number,
- });
-
- Ok(GithubPullRequestDetails {
- title: "Add token validation".to_string(),
- state: "open".to_string(),
- merged_at: None,
- additions: 12,
- deletions: 3,
- comments: None,
- checks: None,
- })
+ let mut state = self.state.lock().unwrap();
+ state.pull_request_detail_calls.push(PullRequestDetailCall {
+ access_token: access_token.to_string(),
+ owner: owner.to_string(),
+ repo: repo.to_string(),
+ number,
+ });
+
+ if let Some(error) = &state.pull_request_detail_error {
+ return Err(anyhow::anyhow!(error.clone()));
+ }
+
+ Ok(state
+ .pull_request_details
+ .clone()
+ .unwrap_or_else(default_pull_request_details))
}
}
@@ -227,6 +249,182 @@ impl Auth for StubAuth {
}
}
+#[derive(Clone, Default)]
+struct StubForeignEntityService {
+ state: Arc<Mutex<StubForeignEntityState>>,
+}
+
+#[derive(Default)]
+struct StubForeignEntityState {
+ entities: Vec<ForeignEntity>,
+ fetch_error: Option<String>,
+ patch_error: Option<String>,
+ fetch_calls: Vec<FetchForeignEntitiesCall>,
+ patch_calls: Vec<PatchForeignEntityCall>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct FetchForeignEntitiesCall {
+ foreign_entity_id: String,
+ foreign_entity_source: Option<String>,
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct PatchForeignEntityCall {
+ id: uuid::Uuid,
+ patch: PatchForeignEntity,
+}
+
+impl StubForeignEntityService {
+ fn with_entities(entities: Vec<ForeignEntity>) -> Self {
+ Self {
+ state: Arc::new(Mutex::new(StubForeignEntityState {
+ entities,
+ ..StubForeignEntityState::default()
+ })),
+ }
+ }
+
+ fn fail_patches(&self, error: &str) {
+ self.state.lock().unwrap().patch_error = Some(error.to_string());
+ }
+
+ fn fetch_calls(&self) -> Vec<FetchForeignEntitiesCall> {
+ self.state.lock().unwrap().fetch_calls.clone()
+ }
+
+ fn patch_calls(&self) -> Vec<PatchForeignEntityCall> {
+ self.state.lock().unwrap().patch_calls.clone()
+ }
+
+ fn foreign_entity_by_id(&self, id: uuid::Uuid) -> Option<ForeignEntity> {
+ self.state
+ .lock()
+ .unwrap()
+ .entities
+ .iter()
+ .find(|entity| entity.id == id)
+ .cloned()
+ }
+}
+
+fn unimplemented_foreign_entity_error() -> ForeignEntityError {
+ ForeignEntityError::Internal(anyhow::anyhow!("not implemented"))
+}
+
+impl ForeignEntityService for StubForeignEntityService {
+ async fn get_foreign_entity(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ Err(unimplemented_foreign_entity_error())
+ }
+
+ async fn get_foreign_entity_by_id(
+ &self,
+ id: uuid::Uuid,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ self.foreign_entity_by_id(id)
+ .ok_or(ForeignEntityError::NotFound(id))
+ }
+
+ async fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ let mut state = self.state.lock().unwrap();
+ state.fetch_calls.push(FetchForeignEntitiesCall {
+ foreign_entity_id: foreign_entity_id.to_string(),
+ foreign_entity_source: foreign_entity_source.map(str::to_string),
+ });
+
+ if let Some(error) = &state.fetch_error {
+ return Err(ForeignEntityError::Internal(anyhow::anyhow!(error.clone())));
+ }
+
+ Ok(state
+ .entities
+ .iter()
+ .filter(|entity| {
+ let source_matches = match foreign_entity_source {
+ Some(source) => entity.foreign_entity_source == source,
+ None => true,
+ };
+
+ entity.foreign_entity_id == foreign_entity_id && source_matches
+ })
+ .cloned()
+ .collect())
+ }
+
+ async fn get_foreign_entities_for_user(
+ &self,
+ _source_ids: Vec<SourceId>,
+ _limit: u32,
+ _query: ForeignEntityListQuery,
+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ Err(unimplemented_foreign_entity_error())
+ }
+
+ async fn create_foreign_entity(
+ &self,
+ _create: CreateForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ Err(unimplemented_foreign_entity_error())
+ }
+
+ async fn delete_foreign_entity(&self, _id: uuid::Uuid) -> Result<(), ForeignEntityError> {
+ Err(unimplemented_foreign_entity_error())
+ }
+
+ async fn patch_foreign_entity(
+ &self,
+ id: uuid::Uuid,
+ patch: PatchForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ let mut state = self.state.lock().unwrap();
+ state.patch_calls.push(PatchForeignEntityCall {
+ id,
+ patch: patch.clone(),
+ });
+
+ if let Some(error) = &state.patch_error {
+ return Err(ForeignEntityError::Internal(anyhow::anyhow!(error.clone())));
+ }
+
+ let entity = state
+ .entities
+ .iter_mut()
+ .find(|entity| entity.id == id)
+ .ok_or(ForeignEntityError::NotFound(id))?;
+
+ if let Some(foreign_entity_id) = patch.foreign_entity_id {
+ entity.foreign_entity_id = foreign_entity_id;
+ }
+
+ if let Some(foreign_entity_source) = patch.foreign_entity_source {
+ entity.foreign_entity_source = foreign_entity_source;
+ }
+
+ if let Some(metadata) = patch.metadata {
+ entity.metadata = metadata;
+ }
+
+ if let Some(stored_for_id) = patch.stored_for_id {
+ entity.stored_for_id = stored_for_id;
+ }
+
+ if let Some(stored_for_auth_entity) = patch.stored_for_auth_entity {
+ entity.stored_for_auth_entity = stored_for_auth_entity;
+ }
+
+ entity.updated_at = Utc::now();
+
+ Ok(entity.clone())
+ }
+}
+
fn test_user_id() -> MacroUserId<Lowercase<'static>> {
MacroUserIdStr::try_from_email("[email protected]")
.unwrap()
@@ -256,15 +454,43 @@ fn pull_request_ref() -> GithubPullRequestRef {
}
}
+fn foreign_entity(
+ id: uuid::Uuid,
+ foreign_entity_id: &str,
+ foreign_entity_source: &str,
+ metadata: serde_json::Value,
+) -> ForeignEntity {
+ ForeignEntity {
+ id,
+ foreign_entity_id: foreign_entity_id.to_string(),
+ foreign_entity_source: foreign_entity_source.to_string(),
+ metadata,
+ stored_for_id: "stored-for-id".to_string(),
+ stored_for_auth_entity: "user".to_string(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+}
+
fn service(
repo: StubGithubRepo,
oauth: StubGithubOauth,
auth: StubAuth,
-) -> GithubLinkServiceImpl<StubGithubRepo, StubGithubOauth, StubAuth> {
+) -> GithubLinkServiceImpl<StubGithubRepo, StubGithubOauth, StubAuth, StubForeignEntityService> {
+ service_with_foreign_entities(repo, oauth, auth, StubForeignEntityService::default())
+}
+
+fn service_with_foreign_entities(
+ repo: StubGithubRepo,
+ oauth: StubGithubOauth,
+ auth: StubAuth,
+ foreign_entity_service: StubForeignEntityService,
+) -> GithubLinkServiceImpl<StubGithubRepo, StubGithubOauth, StubAuth, StubForeignEntityService> {
GithubLinkServiceImpl::new(
repo,
oauth,
auth,
+ foreign_entity_service,
GithubLinkConfig {
client_id: "client-id".to_string(),
client_secret: "client-secret".to_string(),
@@ -339,3 +565,165 @@ async fn check_user_link_token_enrich_pull_requests_reauthenticates_before_detai
assert_eq!(oauth.validated_tokens(), vec!["expired-token".to_string()]);
assert!(oauth.pull_request_detail_calls().is_empty());
}
+
+#[tokio::test]
+async fn enrich_pull_requests_patches_existing_foreign_entities_on_success() {
+ let user_id = test_user_id();
+ let pull_request = pull_request_ref();
+ let first_foreign_entity_id = uuid::Uuid::from_u128(1);
+ let second_foreign_entity_id = uuid::Uuid::from_u128(2);
+ let skipped_foreign_entity_id = uuid::Uuid::from_u128(3);
+ let existing_metadata = serde_json::json!({
+ "comments": [
+ {
+ "id": 42,
+ "body": "existing comment",
+ "source": "issue_comment"
+ }
+ ],
+ "checks": [
+ {
+ "id": 99,
+ "name": "ci",
+ "status": "completed"
+ }
+ ]
+ });
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![
+ foreign_entity(
+ first_foreign_entity_id,
+ &pull_request.github_key,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ existing_metadata.clone(),
+ ),
+ foreign_entity(
+ second_foreign_entity_id,
+ &pull_request.github_key,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({ "other": true }),
+ ),
+ foreign_entity(
+ skipped_foreign_entity_id,
+ &pull_request.github_key,
+ "github_issue",
+ serde_json::json!({ "unchanged": true }),
+ ),
+ ]);
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ StubGithubOauth::new(false),
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+
+ let pull_requests = service
+ .enrich_pull_requests(&user_id, vec![pull_request.clone()])
+ .await
+ .unwrap();
+
+ assert_eq!(pull_requests.len(), 1);
+ let enriched_pull_request = &pull_requests[0];
+ assert_eq!(
+ enriched_pull_request.name.as_deref(),
+ Some("Add token validation")
+ );
+ assert_eq!(
+ foreign_entity_service.fetch_calls(),
+ vec![FetchForeignEntitiesCall {
+ foreign_entity_id: pull_request.github_key.clone(),
+ foreign_entity_source: Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string()),
+ }]
+ );
+
+ let patch_calls = foreign_entity_service.patch_calls();
+ assert_eq!(patch_calls.len(), 2);
+ assert_eq!(patch_calls[0].id, first_foreign_entity_id);
+ assert_eq!(patch_calls[1].id, second_foreign_entity_id);
+
+ let first_metadata = foreign_entity_service
+ .foreign_entity_by_id(first_foreign_entity_id)
+ .unwrap()
+ .metadata;
+ let expected_first_metadata = enriched_pull_request
+ .foreign_entity_metadata(Some(&existing_metadata))
+ .unwrap();
+ assert_eq!(first_metadata, expected_first_metadata);
+ assert_eq!(first_metadata["comments"], existing_metadata["comments"]);
+ assert_eq!(first_metadata["checks"], existing_metadata["checks"]);
+
+ let second_metadata = foreign_entity_service
+ .foreign_entity_by_id(second_foreign_entity_id)
+ .unwrap()
+ .metadata;
+ assert_eq!(
+ second_metadata,
+ enriched_pull_request.foreign_entity_metadata(None).unwrap()
+ );
+
+ let skipped_metadata = foreign_entity_service
+ .foreign_entity_by_id(skipped_foreign_entity_id)
+ .unwrap()
+ .metadata;
+ assert_eq!(skipped_metadata, serde_json::json!({ "unchanged": true }));
+}
+
+#[tokio::test]
+async fn enrich_pull_requests_does_not_patch_foreign_entities_on_detail_failure() {
+ let user_id = test_user_id();
+ let pull_request = pull_request_ref();
+ let oauth = StubGithubOauth::new(false);
+ oauth.fail_pull_request_details("GitHub details unavailable");
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![foreign_entity(
+ uuid::Uuid::from_u128(1),
+ &pull_request.github_key,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({}),
+ )]);
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ oauth,
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+ let expected_pull_request = EnrichedGithubPullRequest::from_reference(pull_request.clone());
+
+ let pull_requests = service
+ .enrich_pull_requests(&user_id, vec![pull_request])
+ .await
+ .unwrap();
+
+ assert_eq!(pull_requests, vec![expected_pull_request]);
+ assert!(foreign_entity_service.fetch_calls().is_empty());
+ assert!(foreign_entity_service.patch_calls().is_empty());
+}
+
+#[tokio::test]
+async fn enrich_pull_requests_returns_enriched_response_when_foreign_entity_patch_fails() {
+ let user_id = test_user_id();
+ let pull_request = pull_request_ref();
+ let foreign_entity_service = StubForeignEntityService::with_entities(vec![foreign_entity(
+ uuid::Uuid::from_u128(1),
+ &pull_request.github_key,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ serde_json::json!({}),
+ )]);
+ foreign_entity_service.fail_patches("database unavailable");
+ let service = service_with_foreign_entities(
+ StubGithubRepo::linked(test_link(&user_id)),
+ StubGithubOauth::new(false),
+ StubAuth::new("valid-token"),
+ foreign_entity_service.clone(),
+ );
+
+ let pull_requests = service
+ .enrich_pull_requests(&user_id, vec![pull_request])
+ .await
+ .unwrap();
+
+ assert_eq!(pull_requests.len(), 1);
+ assert_eq!(
+ pull_requests[0].name.as_deref(),
+ Some("Add token validation")
+ );
+ assert_eq!(foreign_entity_service.patch_calls().len(), 1);
+}
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 b6f17920e5..aa6bd42a2c 100644
--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs
+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs
@@ -10,10 +10,10 @@ mod notify_pr;
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GithubAppInstallationSource, GithubError,
- GithubInstallationAccessToken, GithubKey, GithubPullRequestDetails,
- GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId, TeamTaskReference,
- ValidatedGithubWebhookEvent,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,
+ GithubPullRequestDetails, GithubPullRequestStatus, GithubWebhookEventType, MacroTaskId,
+ TeamTaskReference, ValidatedGithubWebhookEvent,
},
ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},
};
@@ -31,8 +31,6 @@ use subtle::ConstantTimeEq;
type HmacSha256 = Hmac<Sha256>;
-const GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE: &str = "github_pull_request";
-
/// Github sync config
#[derive(Debug)]
pub struct GithubSyncConfig {
@@ -296,33 +294,6 @@ impl<
}
}
- /// Preserve existing metadata arrays when a partial refresh omits them.
- fn metadata_with_preserved_partial_arrays(
- mut metadata: serde_json::Value,
- existing_metadata: Option<&serde_json::Value>,
- ) -> serde_json::Value {
- let Some(existing_object) = existing_metadata.and_then(|value| value.as_object()) else {
- return metadata;
- };
- let Some(metadata_object) = metadata.as_object_mut() else {
- return metadata;
- };
-
- for field in ["comments", "checks"] {
- if metadata_object.contains_key(field) {
- continue;
- }
-
- if let Some(existing_value) = existing_object.get(field)
- && existing_value.is_array()
- {
- metadata_object.insert(field.to_string(), existing_value.clone());
- }
- }
-
- metadata
- }
-
/// Derive a normalized pull request status from the webhook payload.
fn pull_request_status_from_event(
event: &ValidatedGithubWebhookEvent,
@@ -441,14 +412,6 @@ impl<
pull_request: EnrichedGithubPullRequest,
stored_for_sources: &[GithubAppInstallationSource],
) -> Vec<PullRequestForeignEntityUpsert> {
- let base_metadata = match serde_json::to_value(&pull_request) {
- Ok(metadata) => metadata,
- Err(error) => {
- tracing::error!(error=?error, "failed to serialize PR foreign entity metadata");
- return Vec::new();
- }
- };
-
let existing = match self
.foreign_entity_service
.get_foreign_entities_by_foreign_entity_id(
@@ -482,10 +445,13 @@ impl<
let existing_metadata = existing_entity
.map(|entity| &entity.metadata)
.or_else(|| existing.first().map(|entity| &entity.metadata));
- let metadata = Self::metadata_with_preserved_partial_arrays(
- base_metadata.clone(),
- existing_metadata,
- );
+ let metadata = match pull_request.foreign_entity_metadata(existing_metadata) {
+ Ok(metadata) => metadata,
+ Err(error) => {
+ tracing::error!(error=?error, "failed to serialize PR foreign entity metadata");
+ return Vec::new();
+ }
+ };
let foreign_entity = if let Some(entity) = existing_entity {
self.patch_pull_request_foreign_entity(