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): include foreign entity id in github pr preview (#3715)

Will Hutchinsona680d0752033
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts
index 3da2adee18..dded143475 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts
@@ -8,6 +8,7 @@ import type { GithubPullRequestAdditions } from './githubPullRequestAdditions';
import type { GithubPullRequestChecks } from './githubPullRequestChecks';
import type { GithubPullRequestComments } from './githubPullRequestComments';
import type { GithubPullRequestDeletions } from './githubPullRequestDeletions';
+import type { GithubPullRequestForeignEntityId } from './githubPullRequestForeignEntityId';
import type { GithubPullRequestName } from './githubPullRequestName';
import type { GithubPullRequestStatus } from './githubPullRequestStatus';
@@ -31,6 +32,8 @@ export interface GithubPullRequest {
deletions?: GithubPullRequestDeletions;
/** A compact label suitable for display in the UI. */
displayName: string;
+ /** The internal `foreign_entity.id` UUID for the GitHub pull request row. */
+ foreignEntityId?: GithubPullRequestForeignEntityId;
/** The stored GitHub association key, in `owner/repo/pull/number` format. */
githubKey: string;
/** The GitHub pull request title, when enrichment data is available. */
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestForeignEntityId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestForeignEntityId.ts
new file mode 100644
index 0000000000..b920aa69a2
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestForeignEntityId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The internal `foreign_entity.id` UUID for the GitHub pull request row.
+ */
+export type GithubPullRequestForeignEntityId = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 27202f888d..6de20572a7 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -527,6 +527,7 @@ export * from './githubPullRequestComments';
export * from './githubPullRequestCommentUpdatedAt';
export * from './githubPullRequestCommentUrl';
export * from './githubPullRequestDeletions';
+export * from './githubPullRequestForeignEntityId';
export * from './githubPullRequestName';
export * from './githubPullRequestStatus';
export * from './githubPullRequestsResponse';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index e1381d06ca..0b7f4651a2 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -4965,6 +4965,12 @@ export const getDocumentGithubPullRequestsResponse = zod
displayName: zod
.string()
.describe('A compact label suitable for display in the UI.'),
+ foreignEntityId: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'The internal `foreign_entity.id` UUID for the GitHub pull request row.'
+ ),
githubKey: zod
.string()
.describe(
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index f420651a34..65f2d9e0aa 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -13564,6 +13564,11 @@
"type": "string",
"description": "A compact label suitable for display in the UI."
},
+ "foreignEntityId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "The internal `foreign_entity.id` UUID for the GitHub pull request row."
+ },
"githubKey": {
"type": "string",
"description": "The stored GitHub association key, in `owner/repo/pull/number` format."
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 946fca0a6b..6990366e58 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3579,6 +3579,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "foreign_entity",
"futures",
"hex",
"http-body-util",
diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rs
index 5e12a8d2bb..eba5b44756 100644
--- a/rust/cloud-storage/ai_tools/src/build_context.rs
+++ b/rust/cloud-storage/ai_tools/src/build_context.rs
@@ -222,6 +222,9 @@ pub async fn build_tool_service_context_from_env(
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
),
+ foreign_entity_service: ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(
+ pool.clone(),
+ )),
};
let document_tool_context = DocumentToolContext::new(
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index d48834d14e..102fe09bf0 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -421,6 +421,7 @@ pub type ToolDocumentService = documents::domain::service::DocumentServiceImpl<
TaskPropertiesAdapter,
NoOpConnectionService,
ToolEntityAccessManagementService,
+ ToolForeignEntityService,
>;
/// Type alias for the entity access service implementation
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index fa9ee611da..b20f3c0469 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -254,6 +254,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
),
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
);
let test_lexical_client = LexicalClient::new("test".into(), "http://nofileshere".into());
let document_tool_context = documents::inbound::toolset::DocumentToolContext::new(
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 05cda2b2ef..db04a0841e 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -266,6 +266,7 @@ async fn main() -> anyhow::Result<()> {
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(db.clone()),
),
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
);
let lexical_client_for_tools = (*lexical_client).clone();
let document_tool_context = DocumentToolContext::new(
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index a1707b2eb3..99b36d7840 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -201,6 +201,7 @@ pub(crate) type DocumentService = DocumentServiceImpl<
TaskPropertiesAdapter,
ConnectionServiceImpl<EntityAccessService, ConnectionGatewayImpl>,
EntityAccessManagementService,
+ ForeignEntityServiceImpl<PgForeignEntityRepo>,
>;
/// Type alias for the documents router state.
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index e2e271a856..28c23343ab 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -386,6 +386,7 @@ async fn main() -> anyhow::Result<()> {
},
connection_service,
entity_access_management_service.clone(),
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
));
let github_webhook_secret = secretsmanager_client
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index 04e7581428..af503957f4 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -60,7 +60,7 @@ outbound = [
"ports",
]
ports = ["dep:tokio"]
-service = ["dep:entity_access_management", "ports"]
+service = ["dep:entity_access_management", "dep:foreign_entity", "ports"]
[dependencies]
# Core
@@ -84,6 +84,9 @@ entity_access_management = { path = "../entity_access_management", default-featu
"outbound",
"ports",
], optional = true }
+foreign_entity = { path = "../foreign_entity", default-features = false, features = [
+ "ports",
+], optional = true }
macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_entrypoint = { path = "../macro_entrypoint", optional = true }
macro_user_id = { path = "../macro_user_id" }
diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rs
index ea0cae9528..9b39e0cba4 100644
--- a/rust/cloud-storage/documents/src/domain/models.rs
+++ b/rust/cloud-storage/documents/src/domain/models.rs
@@ -164,6 +164,9 @@ pub struct GithubPullRequest {
pub url: String,
/// A compact label suitable for display in the UI.
pub display_name: String,
+ /// The internal `foreign_entity.id` UUID for the GitHub pull request row.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub foreign_entity_id: Option<uuid::Uuid>,
/// The GitHub pull request title, when enrichment data is available.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
@@ -213,6 +216,7 @@ impl GithubPullRequest {
number,
url,
display_name,
+ foreign_entity_id: None,
name: None,
status: None,
additions: None,
diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rs
index 374aa63904..1527c0e9bb 100644
--- a/rust/cloud-storage/documents/src/domain/service.rs
+++ b/rust/cloud-storage/documents/src/domain/service.rs
@@ -20,6 +20,8 @@ use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
};
+use foreign_entity::domain::models::{ForeignEntity, SourceId};
+use foreign_entity::domain::ports::ForeignEntityService;
use macro_user_id::user_id::MacroUserIdStr;
use model::document::response::{DocumentResponseMetadata, LocationResponseData};
use model::document::{ContentType, DocumentBasic, FileAssociation, FileType, FileTypeExt};
@@ -57,6 +59,7 @@ pub struct DocumentServiceImpl<
T: TaskPropertiesPort,
C: ConnectionService,
Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
> {
/// Document repository
pub repo: R,
@@ -72,6 +75,8 @@ pub struct DocumentServiceImpl<
pub connection_service: C,
/// entity access management service
pub entity_access_management_service: Eam,
+ /// Foreign entity service
+ pub foreign_entity_service: F,
}
fn ready_content_for_file_type(file_type: Option<FileType>) -> DocumentContent {
@@ -113,21 +118,47 @@ fn pending_content_for_file_type(file_type: Option<FileType>) -> DocumentContent
}
}
+const GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE: &str = "github_pull_request";
+
fn short_id_for_entity_id(entity_id: &str) -> Result<String, DocumentError> {
let uuid = macro_uuid::string_to_uuid(entity_id)
.map_err(|e| DocumentError::BadRequest(format!("invalid entity_id: {e}")))?;
Ok(macro_uuid::ShortUuidConverter::default().from_uuid(&uuid))
}
+fn foreign_entity_matches_source_id(foreign_entity: &ForeignEntity, source_id: &SourceId) -> bool {
+ foreign_entity.stored_for_id == source_id.id
+ && foreign_entity.stored_for_auth_entity == source_id.auth_entity
+}
+
+fn first_visible_foreign_entity_id(
+ foreign_entities: &[ForeignEntity],
+ source_ids: Option<&[SourceId]>,
+) -> Option<uuid::Uuid> {
+ foreign_entities
+ .iter()
+ .find(|foreign_entity| {
+ foreign_entity.foreign_entity_source == GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE
+ && source_ids.is_none_or(|source_ids| {
+ source_ids.iter().any(|source_id| {
+ foreign_entity_matches_source_id(foreign_entity, source_id)
+ })
+ })
+ })
+ .map(|foreign_entity| foreign_entity.id)
+}
+
impl<
R: DocumentRepo,
U: PresignedUploadUrlPort,
T: TaskPropertiesPort,
C: ConnectionService,
Eam: EntityAccessManagementService,
-> DocumentServiceImpl<R, U, T, C, Eam>
+ F: ForeignEntityService,
+> DocumentServiceImpl<R, U, T, C, Eam, F>
{
/// Create a document service with its repository and external service ports.
+ #[allow(clippy::too_many_arguments)]
pub fn new(
repo: R,
cloudfront_config: CloudFrontConfig,
@@ -136,6 +167,7 @@ impl<
task_properties_service: T,
connection_service: C,
entity_access_management_service: Eam,
+ foreign_entity_service: F,
) -> Self {
Self {
repo,
@@ -145,6 +177,7 @@ impl<
task_properties_service,
connection_service,
entity_access_management_service,
+ foreign_entity_service,
}
}
@@ -409,7 +442,8 @@ impl<
T: TaskPropertiesPort,
C: ConnectionService,
Eam: EntityAccessManagementService,
-> DocumentCreationService for DocumentServiceImpl<R, U, T, C, Eam>
+ F: ForeignEntityService,
+> DocumentCreationService for DocumentServiceImpl<R, U, T, C, Eam, F>
{
async fn create_document(
&self,
@@ -461,7 +495,8 @@ impl<
T: TaskPropertiesPort,
C: ConnectionService,
Eam: EntityAccessManagementService,
-> DocumentService for DocumentServiceImpl<R, U, T, C, Eam>
+ F: ForeignEntityService,
+> DocumentService for DocumentServiceImpl<R, U, T, C, Eam, F>
{
#[tracing::instrument(err, skip(self))]
async fn get_document(
@@ -749,8 +784,44 @@ impl<
.get_task_github_pull_request_keys(&short_id)
.await
.map_err(|e| DocumentError::Internal(e.into()))?;
+ let mut response = GithubPullRequestsResponse::from_github_keys(github_keys);
+
+ if response.pull_requests.is_empty() {
+ return Ok(response);
+ }
+
+ let source_ids = match entity_access_receipt.auth() {
+ EntityAccessAuth::Authenticated(user_id) => {
+ let user_id = user_id.as_ref().to_string();
+ let team_ids = self
+ .repo
+ .get_team_ids_for_user(&user_id)
+ .await
+ .map_err(|e| DocumentError::Internal(e.into()))?;
+ let mut source_ids = Vec::with_capacity(team_ids.len() + 1);
+ source_ids.push(SourceId::user(user_id));
+ source_ids.extend(team_ids.into_iter().map(SourceId::team));
+ Some(source_ids)
+ }
+ EntityAccessAuth::Unauthenticated => Some(Vec::new()),
+ EntityAccessAuth::Internal => None,
+ };
+
+ for pull_request in &mut response.pull_requests {
+ let foreign_entities = self
+ .foreign_entity_service
+ .get_foreign_entities_by_foreign_entity_id(
+ &pull_request.github_key,
+ Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE),
+ )
+ .await
+ .map_err(|error| DocumentError::Internal(error.into()))?;
+
+ pull_request.foreign_entity_id =
+ first_visible_foreign_entity_id(&foreign_entities, source_ids.as_deref());
+ }
- Ok(GithubPullRequestsResponse::from_github_keys(github_keys))
+ Ok(response)
}
#[tracing::instrument(err, skip(self, document_context))]
diff --git a/rust/cloud-storage/documents/src/domain/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rs
index 49087b2889..53d9c019f9 100644
--- a/rust/cloud-storage/documents/src/domain/service/tests.rs
+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs
@@ -1,5 +1,10 @@
+use foreign_entity::domain::models::{
+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,
+};
+use foreign_entity::domain::ports::{ForeignEntityListQuery, ForeignEntityService};
use macro_user_id::cowlike::CowLike;
use model::document::DocumentMetadata;
+use std::sync::{Arc, Mutex};
use crate::domain::models::GithubPullRequest;
use crate::domain::ports::MockDocumentRepo;
@@ -185,15 +190,127 @@ impl EntityAccessManagementService for TestEntityAccessManagementService {
}
}
-fn make_test_service(
- repo: MockDocumentRepo,
-) -> DocumentServiceImpl<
+#[derive(Clone, Debug, Eq, PartialEq)]
+struct ForeignEntityLookupRequest {
+ foreign_entity_id: String,
+ foreign_entity_source: Option<String>,
+}
+
+#[derive(Clone, Default)]
+struct TestForeignEntityService {
+ foreign_entities: Arc<Vec<ForeignEntity>>,
+ lookup_requests: Arc<Mutex<Vec<ForeignEntityLookupRequest>>>,
+}
+
+impl TestForeignEntityService {
+ fn new(foreign_entities: Vec<ForeignEntity>) -> Self {
+ Self {
+ foreign_entities: Arc::new(foreign_entities),
+ lookup_requests: Arc::new(Mutex::new(Vec::new())),
+ }
+ }
+
+ fn lookup_requests(&self) -> Arc<Mutex<Vec<ForeignEntityLookupRequest>>> {
+ Arc::clone(&self.lookup_requests)
+ }
+}
+
+impl ForeignEntityService for TestForeignEntityService {
+ async fn get_foreign_entity(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+
+ async fn get_foreign_entity_by_id(
+ &self,
+ _id: uuid::Uuid,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+
+ async fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ self.lookup_requests
+ .lock()
+ .unwrap()
+ .push(ForeignEntityLookupRequest {
+ foreign_entity_id: foreign_entity_id.to_string(),
+ foreign_entity_source: foreign_entity_source.map(str::to_string),
+ });
+
+ Ok(self
+ .foreign_entities
+ .iter()
+ .filter(|foreign_entity| {
+ foreign_entity.foreign_entity_id == foreign_entity_id
+ && foreign_entity_source
+ .is_none_or(|source| foreign_entity.foreign_entity_source == source)
+ })
+ .cloned()
+ .collect())
+ }
+
+ async fn get_foreign_entities_for_user(
+ &self,
+ _source_ids: Vec<SourceId>,
+ _limit: u32,
+ _query: ForeignEntityListQuery,
+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+
+ async fn create_foreign_entity(
+ &self,
+ _create: CreateForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+
+ async fn delete_foreign_entity(&self, _id: uuid::Uuid) -> Result<(), ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+
+ async fn patch_foreign_entity(
+ &self,
+ _id: uuid::Uuid,
+ _patch: PatchForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ unreachable!("test service only supports foreign entity lookups by external ID")
+ }
+}
+
+type TestDocumentService = DocumentServiceImpl<
MockDocumentRepo,
TestUploadUrlPort,
TestTaskPropertiesPort,
TestConnectionService,
TestEntityAccessManagementService,
-> {
+ TestForeignEntityService,
+>;
+
+fn make_test_service(repo: MockDocumentRepo) -> TestDocumentService {
+ make_test_service_with_foreign_entities(repo, Vec::new())
+}
+
+fn make_test_service_with_foreign_entities(
+ repo: MockDocumentRepo,
+ foreign_entities: Vec<ForeignEntity>,
+) -> TestDocumentService {
+ make_test_service_with_foreign_entity_service(
+ repo,
+ TestForeignEntityService::new(foreign_entities),
+ )
+}
+
+fn make_test_service_with_foreign_entity_service(
+ repo: MockDocumentRepo,
+ foreign_entity_service: TestForeignEntityService,
+) -> TestDocumentService {
DocumentServiceImpl::new(
repo,
test_cloudfront_config(),
@@ -205,10 +322,38 @@ fn make_test_service(
TestTaskPropertiesPort,
TestConnectionService,
TestEntityAccessManagementService,
+ foreign_entity_service,
)
}
-fn assert_raw_pull_request(
+fn make_foreign_entity(
+ id: uuid::Uuid,
+ foreign_entity_id: &str,
+ foreign_entity_source: &str,
+ stored_for_id: &str,
+ stored_for_auth_entity: &str,
+) -> ForeignEntity {
+ let timestamp = chrono::Utc::now();
+
+ ForeignEntity {
+ id,
+ foreign_entity_id: foreign_entity_id.to_string(),
+ foreign_entity_source: foreign_entity_source.to_string(),
+ metadata: serde_json::json!({}),
+ stored_for_id: stored_for_id.to_string(),
+ stored_for_auth_entity: stored_for_auth_entity.to_string(),
+ created_at: timestamp,
+ updated_at: timestamp,
+ }
+}
+
+fn expect_authenticated_team_lookup(repo: &mut MockDocumentRepo, team_ids: Vec<uuid::Uuid>) {
+ repo.expect_get_team_ids_for_user()
+ .withf(|user_id| user_id == "macro|[email protected]")
+ .return_once(move |_| Box::pin(std::future::ready(Ok(team_ids))));
+}
+
+fn assert_pull_request_ref(
pull_request: &GithubPullRequest,
github_key: &str,
owner: &str,
@@ -227,6 +372,17 @@ fn assert_raw_pull_request(
pull_request.display_name.as_str(),
expected_display_name.as_str()
);
+}
+
+fn assert_raw_pull_request(
+ pull_request: &GithubPullRequest,
+ github_key: &str,
+ owner: &str,
+ repo: &str,
+ number: u64,
+) {
+ assert_pull_request_ref(pull_request, github_key, owner, repo, number);
+ assert!(pull_request.foreign_entity_id.is_none());
assert!(pull_request.name.is_none());
assert!(pull_request.status.is_none());
assert!(pull_request.additions.is_none());
@@ -235,6 +391,7 @@ fn assert_raw_pull_request(
assert!(pull_request.checks.is_none());
let pull_request_json = serde_json::to_value(pull_request).unwrap();
+ assert!(pull_request_json.get("foreignEntityId").is_none());
assert!(pull_request_json.get("comments").is_none());
assert!(pull_request_json.get("checks").is_none());
}
@@ -308,6 +465,7 @@ async fn test_get_task_github_pull_requests_returns_raw_refs_for_authenticated_u
"macro/repo/pull/7".to_string(),
])))
});
+ expect_authenticated_team_lookup(&mut repo, Vec::new());
let service = make_test_service(repo);
@@ -330,9 +488,10 @@ async fn test_get_task_github_pull_requests_returns_raw_refs_for_authenticated_u
}
#[tokio::test]
-async fn test_get_task_github_pull_requests_returns_raw_refs_for_internal_access() {
+async fn test_get_task_github_pull_requests_adds_user_foreign_entity_id() {
let document_id = "00000000-0000-0000-0000-000000000002";
let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000101");
let mut repo = make_mock_repo();
repo.expect_get_task_github_pull_request_keys()
@@ -342,6 +501,200 @@ async fn test_get_task_github_pull_requests_returns_raw_refs_for_internal_access
"macro/repo/pull/8".to_string(),
])))
});
+ expect_authenticated_team_lookup(&mut repo, Vec::new());
+
+ let service = make_test_service_with_foreign_entities(
+ repo,
+ vec![make_foreign_entity(
+ foreign_entity_id,
+ "macro/repo/pull/8",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ "user",
+ )],
+ );
+
+ let response = service
+ .get_task_github_pull_requests(
+ authenticated_receipt(document_id),
+ &task_document_context(document_id),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.pull_requests.len(), 1);
+ assert_pull_request_ref(
+ &response.pull_requests[0],
+ "macro/repo/pull/8",
+ "macro",
+ "repo",
+ 8,
+ );
+ assert_eq!(
+ response.pull_requests[0].foreign_entity_id,
+ Some(foreign_entity_id)
+ );
+}
+
+#[tokio::test]
+async fn test_get_task_github_pull_requests_adds_team_foreign_entity_id() {
+ let document_id = "00000000-0000-0000-0000-000000000003";
+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let team_id = uuid::uuid!("00000000-0000-0000-0000-000000000201");
+ let foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000202");
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_task_github_pull_request_keys()
+ .withf(move |task_short_id| task_short_id == expected_short_id)
+ .return_once(|_| {
+ Box::pin(std::future::ready(Ok(vec![
+ "macro/repo/pull/9".to_string(),
+ ])))
+ });
+ expect_authenticated_team_lookup(&mut repo, vec![team_id]);
+
+ let service = make_test_service_with_foreign_entities(
+ repo,
+ vec![make_foreign_entity(
+ foreign_entity_id,
+ "macro/repo/pull/9",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ &team_id.to_string(),
+ "team",
+ )],
+ );
+
+ let response = service
+ .get_task_github_pull_requests(
+ authenticated_receipt(document_id),
+ &task_document_context(document_id),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.pull_requests.len(), 1);
+ assert_pull_request_ref(
+ &response.pull_requests[0],
+ "macro/repo/pull/9",
+ "macro",
+ "repo",
+ 9,
+ );
+ assert_eq!(
+ response.pull_requests[0].foreign_entity_id,
+ Some(foreign_entity_id)
+ );
+}
+
+#[tokio::test]
+async fn test_get_task_github_pull_requests_ignores_unrelated_foreign_entity_source() {
+ let document_id = "00000000-0000-0000-0000-000000000004";
+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let unrelated_foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000301");
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_task_github_pull_request_keys()
+ .withf(move |task_short_id| task_short_id == expected_short_id)
+ .return_once(|_| {
+ Box::pin(std::future::ready(Ok(vec![
+ "macro/repo/pull/10".to_string(),
+ ])))
+ });
+ expect_authenticated_team_lookup(&mut repo, Vec::new());
+
+ let foreign_entity_service = TestForeignEntityService::new(vec![make_foreign_entity(
+ unrelated_foreign_entity_id,
+ "macro/repo/pull/10",
+ "linear_issue",
+ "user",
+ )]);
+ let lookup_requests = foreign_entity_service.lookup_requests();
+ let service = make_test_service_with_foreign_entity_service(repo, foreign_entity_service);
+
+ let response = service
+ .get_task_github_pull_requests(
+ authenticated_receipt(document_id),
+ &task_document_context(document_id),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.pull_requests.len(), 1);
+ assert_raw_pull_request(
+ &response.pull_requests[0],
+ "macro/repo/pull/10",
+ "macro",
+ "repo",
+ 10,
+ );
+ assert_eq!(
+ *lookup_requests.lock().unwrap(),
+ vec![ForeignEntityLookupRequest {
+ foreign_entity_id: "macro/repo/pull/10".to_string(),
+ foreign_entity_source: Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string()),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn test_get_task_github_pull_requests_ignores_unrelated_stored_source() {
+ let document_id = "00000000-0000-0000-0000-000000000005";
+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let unrelated_foreign_entity_id = uuid::uuid!("00000000-0000-0000-0000-000000000401");
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_task_github_pull_request_keys()
+ .withf(move |task_short_id| task_short_id == expected_short_id)
+ .return_once(|_| {
+ Box::pin(std::future::ready(Ok(vec![
+ "macro/repo/pull/11".to_string(),
+ ])))
+ });
+ expect_authenticated_team_lookup(&mut repo, Vec::new());
+
+ let service = make_test_service_with_foreign_entities(
+ repo,
+ vec![make_foreign_entity(
+ unrelated_foreign_entity_id,
+ "macro/repo/pull/11",
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ "user",
+ )],
+ );
+
+ let response = service
+ .get_task_github_pull_requests(
+ authenticated_receipt(document_id),
+ &task_document_context(document_id),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.pull_requests.len(), 1);
+ assert_raw_pull_request(
+ &response.pull_requests[0],
+ "macro/repo/pull/11",
+ "macro",
+ "repo",
+ 11,
+ );
+}
+
+#[tokio::test]
+async fn test_get_task_github_pull_requests_returns_raw_refs_for_internal_access() {
+ let document_id = "00000000-0000-0000-0000-000000000006";
+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_task_github_pull_request_keys()
+ .withf(move |task_short_id| task_short_id == expected_short_id)
+ .return_once(|_| {
+ Box::pin(std::future::ready(Ok(vec![
+ "macro/repo/pull/12".to_string(),
+ ])))
+ });
let service = make_test_service(repo);
@@ -356,9 +709,53 @@ async fn test_get_task_github_pull_requests_returns_raw_refs_for_internal_access
assert_eq!(response.pull_requests.len(), 1);
assert_raw_pull_request(
&response.pull_requests[0],
- "macro/repo/pull/8",
+ "macro/repo/pull/12",
"macro",
"repo",
- 8,
+ 12,
+ );
+}
+
+#[tokio::test]
+async fn test_get_task_github_pull_requests_skips_malformed_keys_before_lookup() {
+ let document_id = "00000000-0000-0000-0000-000000000007";
+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();
+ let mut repo = make_mock_repo();
+
+ repo.expect_get_task_github_pull_request_keys()
+ .withf(move |task_short_id| task_short_id == expected_short_id)
+ .return_once(|_| {
+ Box::pin(std::future::ready(Ok(vec![
+ "not-a-pr-key".to_string(),
+ "macro/repo/pull/13".to_string(),
+ ])))
+ });
+
+ let foreign_entity_service = TestForeignEntityService::default();
+ let lookup_requests = foreign_entity_service.lookup_requests();
+ let service = make_test_service_with_foreign_entity_service(repo, foreign_entity_service);
+
+ let response = service
+ .get_task_github_pull_requests(
+ internal_receipt(document_id),
+ &task_document_context(document_id),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(response.pull_requests.len(), 1);
+ assert_raw_pull_request(
+ &response.pull_requests[0],
+ "macro/repo/pull/13",
+ "macro",
+ "repo",
+ 13,
+ );
+ assert_eq!(
+ *lookup_requests.lock().unwrap(),
+ vec![ForeignEntityLookupRequest {
+ foreign_entity_id: "macro/repo/pull/13".to_string(),
+ foreign_entity_source: Some(GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_string()),
+ }]
);
}
diff --git a/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs b/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs
index 4e81735f15..9ac7b36c02 100644
--- a/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs
+++ b/rust/cloud-storage/documents/src/inbound/axum_router/get_github_pull_requests.rs
@@ -79,5 +79,14 @@ mod tests {
"expected {status} response to be documented"
);
}
+
+ let pull_request_properties = openapi
+ .pointer("/components/schemas/GithubPullRequest/properties")
+ .and_then(Value::as_object)
+ .expect("GithubPullRequest schema should document properties");
+ assert!(
+ pull_request_properties.contains_key("foreignEntityId"),
+ "GithubPullRequest schema should document foreignEntityId"
+ );
}
}
diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
index 5d616af2b4..81db5e7f87 100644
--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs
@@ -1003,6 +1003,7 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgres
number: 5,
url: "https://github.com/macro/api/pull/5".to_string(),
display_name: "macro/api#5".to_string(),
+ foreign_entity_id: None,
name: None,
status: None,
additions: None,
@@ -1017,6 +1018,7 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgres
number: 10,
url: "https://github.com/macro/macro/pull/10".to_string(),
display_name: "macro/macro#10".to_string(),
+ foreign_entity_id: None,
name: None,
status: None,
additions: None,
@@ -1031,6 +1033,7 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgres
number: 20,
url: "https://github.com/macro/macro/pull/20".to_string(),
display_name: "macro/macro#20".to_string(),
+ foreign_entity_id: None,
name: None,
status: None,
additions: None,
diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rs
index 729234ad3a..8606000b8e 100644
--- a/rust/cloud-storage/mcp_service/src/context.rs
+++ b/rust/cloud-storage/mcp_service/src/context.rs
@@ -243,6 +243,7 @@ async fn build_tool_context(
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(db.clone()),
),
+ foreign_entity_service: ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
};
let lexical_client_for_tools = (*lexical_client).clone();
let document_tool_context = DocumentToolContext::new(
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 7e9a3f7dc0..eaf0fe0c0f 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -137,6 +137,7 @@ pub async fn build_tool_service_context(
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(pool.clone()),
),
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
);
let document_tool_context = DocumentToolContext::new(
document_service,