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.

refactor(soup): list foreign entities through the github_pull_requests crate (#7104)

dev-rb19208ad42a90
diff --git a/.sqlx/query-16c98d8bb484fd33da108a68411a99403d8ccdceb35347b7bb07e1f44a5561c5.json b/.sqlx/query-16c98d8bb484fd33da108a68411a99403d8ccdceb35347b7bb07e1f44a5561c5.json
new file mode 100644
index 0000000000..0956e6c1f7
--- /dev/null
+++ b/.sqlx/query-16c98d8bb484fd33da108a68411a99403d8ccdceb35347b7bb07e1f44a5561c5.json
@@ -0,0 +1,74 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE fe.foreign_entity_source = $11::text\n AND EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n AND (\n $8::text[] IS NULL\n OR (fe.metadata -> 'participantGithubUserIds') ?| $8::text[]\n )\n AND (\n $9::int[] IS NULL\n OR ($10::text IS NOT NULL AND (\n SELECT COALESCE(bit_or(CASE un.state\n WHEN 'unseen' THEN 1 WHEN 'seen' THEN 2 WHEN 'done' THEN 4 END), 0)\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n WHERE un.user_id = $10::text\n AND un.deleted_at IS NULL\n AND n.event_item_type = 'foreign_entity'\n AND n.event_item_id = fe.id::text\n ) = ANY($9::int[]))\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "foreign_entity_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "foreign_entity_source!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata!: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "stored_for_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "stored_for_auth_entity!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "TextArray",
+ "TextArray",
+ "Text",
+ "Text",
+ "Timestamptz",
+ "Uuid",
+ "Int8",
+ "TextArray",
+ "Int4Array",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "16c98d8bb484fd33da108a68411a99403d8ccdceb35347b7bb07e1f44a5561c5"
+}
diff --git a/.sqlx/query-e6f7363ac8776c527b52b16904b4d7659bb4ffbf24bc339cc99d35c9d36bac2a.json b/.sqlx/query-1d0f03407fc0fef8baa25126450f6050484306b2aa908e9ee9474ce818790354.json
similarity index 62%
rename from .sqlx/query-e6f7363ac8776c527b52b16904b4d7659bb4ffbf24bc339cc99d35c9d36bac2a.json
rename to .sqlx/query-1d0f03407fc0fef8baa25126450f6050484306b2aa908e9ee9474ce818790354.json
index ac471d4459..7fd5106a17 100644
--- a/.sqlx/query-e6f7363ac8776c527b52b16904b4d7659bb4ffbf24bc339cc99d35c9d36bac2a.json
+++ b/.sqlx/query-1d0f03407fc0fef8baa25126450f6050484306b2aa908e9ee9474ce818790354.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n AND (\n $8::text IS NULL\n OR (fe.metadata -> 'participantGithubUserIds') ? $8::text\n )\n AND (\n $9::int[] IS NULL\n OR ($10::text IS NOT NULL AND (\n SELECT COALESCE(bit_or(CASE un.state\n WHEN 'unseen' THEN 1 WHEN 'seen' THEN 2 WHEN 'done' THEN 4 END), 0)\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n WHERE un.user_id = $10::text\n AND un.deleted_at IS NULL\n AND n.event_item_type = 'foreign_entity'\n AND n.event_item_id = fe.id::text\n ) = ANY($9::int[]))\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ",
+ "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n AND (\n $8::int[] IS NULL\n OR ($9::text IS NOT NULL AND (\n SELECT COALESCE(bit_or(CASE un.state\n WHEN 'unseen' THEN 1 WHEN 'seen' THEN 2 WHEN 'done' THEN 4 END), 0)\n FROM notification n\n JOIN user_notification un ON un.notification_id = n.id\n WHERE un.user_id = $9::text\n AND un.deleted_at IS NULL\n AND n.event_item_type = 'foreign_entity'\n AND n.event_item_id = fe.id::text\n ) = ANY($8::int[]))\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ",
"describe": {
"columns": [
{
@@ -53,7 +53,6 @@
"Timestamptz",
"Uuid",
"Int8",
- "Text",
"Int4Array",
"Text"
]
@@ -69,5 +68,5 @@
false
]
},
- "hash": "e6f7363ac8776c527b52b16904b4d7659bb4ffbf24bc339cc99d35c9d36bac2a"
+ "hash": "1d0f03407fc0fef8baa25126450f6050484306b2aa908e9ee9474ce818790354"
}
diff --git a/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json b/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json
new file mode 100644
index 0000000000..ee321949b6
--- /dev/null
+++ b/.sqlx/query-1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT COUNT(*) as \"persisted_count!\"\n FROM foreign_entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "persisted_count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "1daa88e349f8067e35be783a31260caad8711fe6793f600a90599f9f84a783b1"
+}
diff --git a/.sqlx/query-272cb961c7808fac2017ab886d31d0b3e35de71145189f0e7295e13fa275725b.json b/.sqlx/query-272cb961c7808fac2017ab886d31d0b3e35de71145189f0e7295e13fa275725b.json
new file mode 100644
index 0000000000..3bdc5f555f
--- /dev/null
+++ b/.sqlx/query-272cb961c7808fac2017ab886d31d0b3e35de71145189f0e7295e13fa275725b.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)\n VALUES ($1, $2, $3, $4, $5)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Uuid",
+ "Varchar",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "272cb961c7808fac2017ab886d31d0b3e35de71145189f0e7295e13fa275725b"
+}
diff --git a/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json b/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json
new file mode 100644
index 0000000000..ba7824ec45
--- /dev/null
+++ b/.sqlx/query-280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f.json
@@ -0,0 +1,16 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE foreign_entity\n SET created_at = $2, updated_at = $3\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Timestamptz",
+ "Timestamptz"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "280b524fe0ce00b66ee0adb59a63d54749a76b03fc7006ea64270c34763f605f"
+}
diff --git a/.sqlx/query-648149fc2ffdfd0e53c63a53fccc141a08478d52ef87049002fee65901e82ee1.json b/.sqlx/query-648149fc2ffdfd0e53c63a53fccc141a08478d52ef87049002fee65901e82ee1.json
new file mode 100644
index 0000000000..f119c37a8b
--- /dev/null
+++ b/.sqlx/query-648149fc2ffdfd0e53c63a53fccc141a08478d52ef87049002fee65901e82ee1.json
@@ -0,0 +1,17 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO user_notification (user_id, notification_id, state, seen_at)\n VALUES ($1, $2, CASE WHEN $3::bool THEN 'done'::notification_state\n WHEN $4::timestamp IS NOT NULL THEN 'seen'::notification_state\n ELSE 'unseen'::notification_state END, $4)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid",
+ "Bool",
+ "Timestamp"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "648149fc2ffdfd0e53c63a53fccc141a08478d52ef87049002fee65901e82ee1"
+}
diff --git a/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json b/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json
new file mode 100644
index 0000000000..ecd353f8c0
--- /dev/null
+++ b/.sqlx/query-68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE foreign_entity\n SET updated_at = NOW() - INTERVAL '1 hour'\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "68ba7cb71623522b89eee53109b6c6030fa4b339e95d3965b2ea4e447054673e"
+}
diff --git a/Cargo.lock b/Cargo.lock
index d53eeacc4d..7d73cd99e9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -889,6 +889,7 @@ dependencies = [
"foreign_entity",
"frecency",
"futures",
+ "github_pull_requests",
"image_generation",
"import",
"initiative",
@@ -5958,6 +5959,7 @@ dependencies = [
"foreign_entity",
"frecency",
"futures",
+ "github_pull_requests",
"http 1.4.0",
"http-body-util",
"import",
@@ -8145,8 +8147,11 @@ dependencies = [
"anyhow",
"chrono",
"entity_access",
+ "filter_ast",
"foreign_entity",
+ "item_filters",
"macro_db_migrator",
+ "models_pagination",
"serde",
"serde_json",
"sqlx",
@@ -11643,6 +11648,7 @@ dependencies = [
"frecency",
"fusionauth",
"futures",
+ "github_pull_requests",
"http 1.4.0",
"lexical_client",
"macro_auth",
@@ -11767,6 +11773,7 @@ dependencies = [
"foreign_entity",
"frecency",
"futures",
+ "github_pull_requests",
"lexical_client",
"macro_authorization",
"macro_aws_config",
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index ee3a929006..158ebc005f 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -49,6 +49,7 @@ entity_access_management = { path = "../entity_access_management" }
entity_registry = { path = "../entity_registry/entity_registry" }
entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }
foreign_entity = { path = "../foreign_entity" }
+github_pull_requests = { path = "../github_pull_requests" }
frecency = { path = "../frecency", features = ["outbound", "postgres"] }
futures.workspace = true
image_generation = { path = "../image_generation" }
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 822348cd67..f05a00a678 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -33,6 +33,10 @@ use foreign_entity::{
};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
+use github_pull_requests::{
+ domain::service::GithubPullRequestServiceImpl,
+ outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
+};
use image_generation::domain::ports::{ImageGenerator, UnconfiguredImageGenerator};
use image_generation::outbound::gemini::GeminiImageGenerator;
use lexical_client::LexicalClient;
@@ -244,8 +248,10 @@ pub async fn build_tool_service_context_from_env(
);
let email_service_for_tools: Arc<crate::tool_context::ToolEmailService> =
Arc::new(email_service.clone());
- let foreign_entity_service =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));
+ let github_pull_request_service = GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
+ PgGithubPullRequestRepo::new(pool.clone()),
+ );
let soup_service = Arc::new(SoupImpl::new(
PgSoupRepo::new(ReadOnlyPool(pool.clone())),
frecency_service,
@@ -255,7 +261,7 @@ pub async fn build_tool_service_context_from_env(
call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
),
crm::domain::service::NoOpCrmService,
- foreign_entity_service,
+ github_pull_request_service,
reminders::domain::service::NoOpRemindersService,
));
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 916a4e4515..2d76559644 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -68,17 +68,18 @@ pub use tool_context::{
ToolDatabasesService, ToolDatabasesSqlToolContext, ToolDatabasesToolContext,
ToolDocumentService, ToolDocumentToolContext, ToolEmailService, ToolEmailToolContext,
ToolEntityAccessManagementService, ToolEntityAccessService, ToolEntityCreator,
- ToolForeignEntityService, ToolFrecencyService, ToolImageGenerationToolContext,
- ToolImportService, ToolImportToolContext, ToolInitiativeToolContext, ToolMcpSelector,
- ToolNotificationQueue, ToolNotificationService, ToolNotificationToolContext,
- ToolPipedreamConnection, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,
- ToolPropertiesToolContext, ToolRemindersService, ToolRemindersToolContext, ToolServiceContext,
- ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,
- ToolTableEventPublisher, ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
- ToolViewOnlyDatabasesSqlToolContext, build_activity_tool_context, build_bot_tool_context,
- build_calendar_tool_context, build_channel_tool_context_with_dispatcher,
- build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
- build_crm_tool_context, build_databases_sql_tool_context, build_databases_tool_context,
+ ToolForeignEntityService, ToolFrecencyService, ToolGithubPullRequestService,
+ ToolImageGenerationToolContext, ToolImportService, ToolImportToolContext,
+ ToolInitiativeToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,
+ ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,
+ ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolRemindersService,
+ ToolRemindersToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
+ ToolSoupService, ToolSystemPropertiesService, ToolTableEventPublisher, ToolTeamService,
+ ToolTeamToolContext, ToolUserEmailService, ToolViewOnlyDatabasesSqlToolContext,
+ build_activity_tool_context, build_bot_tool_context, build_calendar_tool_context,
+ build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,
+ build_channel_tool_context_without_side_effects, build_crm_tool_context,
+ build_databases_sql_tool_context, build_databases_tool_context,
build_image_generation_tool_context, build_initiative_tool_context,
build_message_service_with_side_effects, build_message_service_without_side_effects,
build_project_tool_context, build_properties_service, build_properties_service_with_broker,
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index b07cdcff29..d887430166 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -49,6 +49,10 @@ use foreign_entity::{
domain::service::ForeignEntityServiceImpl,
outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
};
+use github_pull_requests::{
+ domain::service::GithubPullRequestServiceImpl,
+ outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
+};
use lexical_mention_extractor::LexicalMentionExtractor;
use macro_event_broker::{
EventBrokerError, KafkaEventPublisher, MacroEvent, MacroEventBroker, MacroEventBrokerService,
@@ -903,6 +907,10 @@ pub type ToolDocumentToolContext = DocumentToolContext<
/// Type alias for the foreign entity service implementation used by AI tools.
pub type ToolForeignEntityService = ForeignEntityServiceImpl<PgForeignEntityRepo>;
+/// Type alias for the GitHub pull request service used by AI tools.
+pub type ToolGithubPullRequestService =
+ GithubPullRequestServiceImpl<ToolForeignEntityService, PgGithubPullRequestRepo>;
+
/// Type alias for the soup service implementation
pub type ToolSoupService = SoupImpl<
soup::outbound::pg_soup_repo::PgSoupRepo,
@@ -911,7 +919,7 @@ pub type ToolSoupService = SoupImpl<
ToolCommsService,
ToolCallRecordQueryService,
crm::domain::service::NoOpCrmService,
- ToolForeignEntityService,
+ ToolGithubPullRequestService,
reminders::domain::service::NoOpRemindersService,
>;
diff --git a/crates/foreign_entity/src/domain/models.rs b/crates/foreign_entity/src/domain/models.rs
index 3c65c78c06..33546d8e0f 100644
--- a/crates/foreign_entity/src/domain/models.rs
+++ b/crates/foreign_entity/src/domain/models.rs
@@ -35,8 +35,8 @@ impl SourceId {
Self::new(id.to_string(), "team")
}
- #[allow(dead_code)]
- pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
+ /// Reject blank ids and auth entities.
+ pub fn validate(&self) -> Result<(), ForeignEntityError> {
validate_non_blank("sourceId.id", &self.id)?;
validate_non_blank("sourceId.authEntity", &self.auth_entity)
}
diff --git a/crates/foreign_entity/src/domain/ports.rs b/crates/foreign_entity/src/domain/ports.rs
index daef7fa531..08ce3a5dbe 100644
--- a/crates/foreign_entity/src/domain/ports.rs
+++ b/crates/foreign_entity/src/domain/ports.rs
@@ -42,8 +42,8 @@ pub trait ForeignEntityRepository: Send + Sync + 'static {
/// List foreign entities visible through the supplied source identifiers.
///
- /// `requesting_user` is the macro user id used to resolve participant filters such as
- /// [`ForeignEntityLiteral::IncludesMe`]; when `None`, participant filters match nothing.
+ /// `requesting_user` is the macro user id notification-state filters are scoped to; when
+ /// `None`, they match nothing. [`ForeignEntityLiteral::IncludesMe`] never matches here.
fn get_foreign_entities_for_user(
&self,
requesting_user: Option<String>,
@@ -106,8 +106,8 @@ pub trait ForeignEntityService: Send + Sync + 'static {
/// List foreign entities visible through the supplied source identifiers.
///
- /// `requesting_user` is the macro user id used to resolve participant filters such as
- /// [`ForeignEntityLiteral::IncludesMe`]; when `None`, participant filters match nothing.
+ /// `requesting_user` is the macro user id notification-state filters are scoped to; when
+ /// `None`, they match nothing. [`ForeignEntityLiteral::IncludesMe`] never matches here.
fn get_foreign_entities_for_user(
&self,
requesting_user: Option<String>,
diff --git a/crates/foreign_entity/src/outbound/pg_foreign_entity_repo.rs b/crates/foreign_entity/src/outbound/pg_foreign_entity_repo.rs
index 81f66cd646..d9a5425699 100644
--- a/crates/foreign_entity/src/outbound/pg_foreign_entity_repo.rs
+++ b/crates/foreign_entity/src/outbound/pg_foreign_entity_repo.rs
@@ -18,7 +18,6 @@ struct ForeignEntityBatchQuery<'a> {
source_auth_entities: &'a [String],
sort_method: SimpleSortMethod,
filter_jsonpath: Option<&'a str>,
- participant_github_user_id: Option<&'a str>,
/// Macro user id used to scope the per-user notification state predicates.
/// When a notification filter is requested but this is `None`, nothing matches.
notification_user_id: Option<&'a str>,
@@ -37,15 +36,14 @@ fn source_id_parts(source_ids: &[SourceId]) -> (Vec<String>, Vec<String>) {
.unzip()
}
-/// A participant or mixed metadata/notification subtree cannot be lifted safely.
-/// Pure notification subtrees support AND, OR, and NOT.
+/// A mixed metadata/notification subtree cannot be lifted safely. Pure notification subtrees
+/// support AND, OR, and NOT.
struct UnsupportedHoistedFilter;
/// Filters lifted off the top-level AND spine into dedicated SQL predicates because they cannot be
-/// expressed in the metadata jsonpath (they need indexed-containment or notification-table joins).
+/// expressed in the metadata jsonpath (they need notification-table joins).
#[derive(Default)]
struct HoistedForeignEntityFilters {
- includes_me: bool,
// A truth table over the eight possible sets of notification states present
// on an entity. AND combines truth tables, not row-level state predicates:
// an unseen literal and a seen literal can match different notifications.
@@ -56,7 +54,6 @@ struct HoistedForeignEntityFilters {
impl HoistedForeignEntityFilters {
fn and(self, other: Self) -> Self {
Self {
- includes_me: self.includes_me || other.includes_me,
notification_matches: match (self.notification_matches, other.notification_matches) {
(Some(a), Some(b)) => Some(a & b),
(a, b) => a.or(b),
@@ -105,8 +102,8 @@ fn notification_truth_table(expr: &Expr<ForeignEntityLiteral>) -> Option<u8> {
})
}
-/// Literals that cannot be represented in the metadata jsonpath and must be lifted into dedicated
-/// SQL predicates instead.
+/// Literals that cannot be represented in the metadata jsonpath. Notification states are lifted
+/// into SQL predicates; IncludesMe fails closed in this generic repository.
fn is_hoisted_literal(literal: &ForeignEntityLiteral) -> bool {
matches!(
literal,
@@ -124,9 +121,9 @@ fn contains_hoisted_literal(expr: &Expr<ForeignEntityLiteral>) -> bool {
}
}
-/// Lift participant predicates and pure notification subtrees off the AND spine.
-/// Notification subtrees preserve their full boolean expression through a truth table;
-/// other literals remain in the metadata jsonpath. Mixed OR/NOT subtrees fail closed.
+/// Lift pure notification subtrees off the AND spine. Notification subtrees preserve their full
+/// boolean expression through a truth table; other literals remain in the metadata jsonpath.
+/// Mixed OR/NOT subtrees fail closed.
fn extract_hoisted_filters(
expr: &Expr<ForeignEntityLiteral>,
) -> Result<HoistedForeignEntityFilters, UnsupportedHoistedFilter> {
@@ -140,10 +137,6 @@ fn extract_hoisted_filters(
Expr::And(left, right) => {
Ok(extract_hoisted_filters(left)?.and(extract_hoisted_filters(right)?))
}
- Expr::Literal(ForeignEntityLiteral::IncludesMe) => Ok(HoistedForeignEntityFilters {
- includes_me: true,
- ..Default::default()
- }),
other => {
if contains_hoisted_literal(other) {
Err(UnsupportedHoistedFilter)
@@ -181,9 +174,8 @@ fn foreign_entity_literal_jsonpath(literal: &ForeignEntityLiteral) -> String {
ForeignEntityLiteral::ForeignEntitySource(source) => {
jsonpath_text_eq("foreignEntitySource", source)
}
- // IncludesMe and the notification literals are hoisted into dedicated SQL predicates by
- // extract_hoisted_filters and never reach the jsonpath; if one slips through, match nothing
- // rather than everything.
+ // IncludesMe cannot be resolved in this generic repository, and notification literals
+ // require dedicated SQL predicates. extract_hoisted_filters rejects either if unhandled.
ForeignEntityLiteral::IncludesMe | ForeignEntityLiteral::NotificationState(_) => {
"(1 == 0)".to_string()
}
@@ -217,7 +209,6 @@ impl PgForeignEntityRepo {
source_auth_entities,
sort_method,
filter_jsonpath,
- participant_github_user_id,
notification_user_id,
notification_sets,
cursor_id,
@@ -267,21 +258,17 @@ impl PgForeignEntityRepo {
)
)
AND (
- $8::text IS NULL
- OR (fe.metadata -> 'participantGithubUserIds') ? $8::text
- )
- AND (
- $9::int[] IS NULL
- OR ($10::text IS NOT NULL AND (
+ $8::int[] IS NULL
+ OR ($9::text IS NOT NULL AND (
SELECT COALESCE(bit_or(CASE un.state
WHEN 'unseen' THEN 1 WHEN 'seen' THEN 2 WHEN 'done' THEN 4 END), 0)
FROM notification n
JOIN user_notification un ON un.notification_id = n.id
- WHERE un.user_id = $10::text
+ WHERE un.user_id = $9::text
AND un.deleted_at IS NULL
AND n.event_item_type = 'foreign_entity'
AND n.event_item_id = fe.id::text
- ) = ANY($9::int[]))
+ ) = ANY($8::int[]))
)
ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC
)
@@ -307,29 +294,12 @@ impl PgForeignEntityRepo {
cursor_value,
cursor_id,
limit,
- participant_github_user_id,
notification_sets,
notification_user_id,
)
.fetch_all(&self.pool)
.await
}
-
- async fn github_user_id_for_macro_user(
- &self,
- macro_user_id: &str,
- ) -> Result<Option<String>, sqlx::Error> {
- sqlx::query_scalar!(
- r#"
- SELECT github_user_id
- FROM github_links
- WHERE macro_id = $1
- "#,
- macro_user_id,
- )
- .fetch_optional(&self.pool)
- .await
- }
}
impl ForeignEntityRepository for PgForeignEntityRepo {
@@ -402,7 +372,6 @@ impl ForeignEntityRepository for PgForeignEntityRepo {
}
let HoistedForeignEntityFilters {
- includes_me,
notification_matches,
jsonpath: filter_jsonpath,
} = match query
@@ -426,19 +395,6 @@ impl ForeignEntityRepository for PgForeignEntityRepo {
return Ok(Vec::new());
}
- let participant_github_user_id = if includes_me {
- let Some(requesting_user) = requesting_user.as_deref() else {
- return Ok(Vec::new());
- };
- match self.github_user_id_for_macro_user(requesting_user).await? {
- Some(github_user_id) => Some(github_user_id),
- // No linked GitHub identity: the user participates in nothing.
- None => return Ok(Vec::new()),
- }
- } else {
- None
- };
-
let notification_sets: Option<Vec<i32>> = notification_matches.map(|table| {
(0..8)
.filter(|present| table & (1 << present) != 0)
@@ -446,7 +402,7 @@ impl ForeignEntityRepository for PgForeignEntityRepo {
});
// Notification states are scoped to the requesting user's per-user notification row.
// Without a requesting user the predicate matches nothing, so an active notification
- // filter yields no results (consistent with the participant filter above).
+ // filter yields no results.
let notification_user_id = requesting_user.as_deref();
let (source_ids, source_auth_entities) = source_id_parts(&source_ids);
@@ -457,7 +413,6 @@ impl ForeignEntityRepository for PgForeignEntityRepo {
source_auth_entities: &source_auth_entities,
sort_method: *query.sort_method(),
filter_jsonpath: filter_jsonpath.as_deref(),
- participant_github_user_id: participant_github_user_id.as_deref(),
notification_user_id,
notification_sets: notification_sets.as_deref(),
cursor_id: cursor_id.copied(),
diff --git a/crates/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs b/crates/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs
index 49d2349118..d59f16d880 100644
--- a/crates/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs
+++ b/crates/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs
@@ -626,33 +626,10 @@ fn includes_me_filter() -> LiteralTree<ForeignEntityLiteral> {
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn get_for_user_includes_me_filters_to_participant_metadata(pool: PgPool) {
+async fn get_for_user_includes_me_matches_nothing(pool: PgPool) {
let repo = PgForeignEntityRepo::new(pool.clone());
let macro_id = "macro|[email protected]";
insert_github_link(&pool, macro_id, "42").await;
-
- let involved =
- insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["7", "42"])).await;
- insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
- insert_pr_with_participants(&repo, "legacy-pr", macro_id, None).await;
-
- let entities = repo
- .get_foreign_entities_for_user(
- Some(macro_id.to_string()),
- vec![SourceId::user(macro_id)],
- 10,
- filter_query(includes_me_filter()),
- )
- .await
- .expect("includes_me filter should be applied");
-
- assert_eq!(entities, vec![involved]);
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn get_for_user_includes_me_without_github_link_returns_empty(pool: PgPool) {
- let repo = PgForeignEntityRepo::new(pool);
- let macro_id = "macro|[email protected]";
insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
let entities = repo
@@ -663,82 +640,41 @@ async fn get_for_user_includes_me_without_github_link_returns_empty(pool: PgPool
filter_query(includes_me_filter()),
)
.await
- .expect("includes_me without a github link should succeed");
-
- assert!(entities.is_empty());
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn get_for_user_includes_me_without_requesting_user_returns_empty(pool: PgPool) {
- let repo = PgForeignEntityRepo::new(pool.clone());
- let macro_id = "macro|[email protected]";
- insert_github_link(&pool, macro_id, "42").await;
- insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
-
- let entities = repo
- .get_foreign_entities_for_user(
- None,
- vec![SourceId::user(macro_id)],
- 10,
- filter_query(includes_me_filter()),
- )
- .await
- .expect("includes_me without a requesting user should succeed");
+ .expect("includes_me filter should be applied");
assert!(entities.is_empty());
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn get_for_user_includes_me_composes_with_other_filters(pool: PgPool) {
- let repo = PgForeignEntityRepo::new(pool.clone());
- let macro_id = "macro|[email protected]";
- insert_github_link(&pool, macro_id, "42").await;
-
- let involved = insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
- insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
- insert_foreign_entity_for_source(&repo, "linear-issue", "linear_issue", macro_id, "user").await;
-
- let filter = Some(Arc::new(Expr::and(
- Expr::val(ForeignEntityLiteral::ForeignEntitySource(
- "github_pull_request".to_string(),
- )),
- Expr::val(ForeignEntityLiteral::IncludesMe),
- )));
- let entities = repo
- .get_foreign_entities_for_user(
- Some(macro_id.to_string()),
- vec![SourceId::user(macro_id)],
- 10,
- filter_query(filter),
- )
- .await
- .expect("includes_me composed with a source filter should be applied");
-
- assert_eq!(entities, vec![involved]);
-}
-
-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn get_for_user_includes_me_under_not_fails_closed(pool: PgPool) {
- let repo = PgForeignEntityRepo::new(pool.clone());
+async fn get_for_user_rejects_negated_and_nested_includes_me(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool);
let macro_id = "macro|[email protected]";
- insert_github_link(&pool, macro_id, "42").await;
insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
- insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
-
- let filter = Some(Arc::new(Expr::is_not(Expr::val(
- ForeignEntityLiteral::IncludesMe,
- ))));
- let entities = repo
- .get_foreign_entities_for_user(
- Some(macro_id.to_string()),
- vec![SourceId::user(macro_id)],
- 10,
- filter_query(filter),
- )
- .await
- .expect("unsupported includes_me placement should fail closed");
- assert!(entities.is_empty());
+ let filters = [
+ Expr::is_not(Expr::val(ForeignEntityLiteral::IncludesMe)),
+ Expr::and(
+ Expr::val(ForeignEntityLiteral::ForeignEntitySource(
+ "github_pull_request".to_string(),
+ )),
+ Expr::or(
+ Expr::val(ForeignEntityLiteral::Id(Uuid::now_v7())),
+ Expr::is_not(Expr::val(ForeignEntityLiteral::IncludesMe)),
+ ),
+ ),
+ ];
+ for filter in filters {
+ let entities = repo
+ .get_foreign_entities_for_user(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(Some(Arc::new(filter))),
+ )
+ .await
+ .expect("unsupported includes_me placement should fail closed");
+ assert!(entities.is_empty());
+ }
}
/// Insert a `foreign_entity`-scoped notification and the matching per-user row so the
diff --git a/crates/github_pull_requests/Cargo.toml b/crates/github_pull_requests/Cargo.toml
index 22755bdde9..436bd37ec5 100644
--- a/crates/github_pull_requests/Cargo.toml
+++ b/crates/github_pull_requests/Cargo.toml
@@ -6,15 +6,24 @@ version = "0.1.0"
[features]
default = ["outbound", "ports", "service"]
-outbound = ["dep:sqlx", "ports"]
-ports = []
+outbound = [
+ "dep:filter_ast",
+ "dep:item_filters",
+ "dep:models_pagination",
+ "dep:sqlx",
+ "ports",
+]
+ports = ["foreign_entity/ports"]
schema = ["dep:utoipa"]
-service = ["foreign_entity/ports", "ports"]
+service = ["ports"]
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true }
+filter_ast = { path = "../filter_ast", optional = true }
foreign_entity = { path = "../foreign_entity", default-features = false }
+item_filters = { path = "../item_filters", optional = true }
+models_pagination = { path = "../models_pagination", optional = true }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true, optional = true }
@@ -26,5 +35,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
entity_access = { path = "../entity_access", default-features = false, features = ["ports"] }
+foreign_entity = { path = "../foreign_entity", default-features = false, features = ["outbound"] }
macro_db_migrator = { path = "../macro_db_migrator" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/crates/github_pull_requests/src/domain/ports.rs b/crates/github_pull_requests/src/domain/ports.rs
index 4db7f2ada2..257063dfa4 100644
--- a/crates/github_pull_requests/src/domain/ports.rs
+++ b/crates/github_pull_requests/src/domain/ports.rs
@@ -2,7 +2,10 @@
use std::future::Future;
-use foreign_entity::domain::models::ForeignEntity;
+use foreign_entity::domain::{
+ models::{ForeignEntity, SourceId},
+ ports::ForeignEntityListQuery,
+};
use super::models::{
EnrichedGithubPullRequest, GithubPullRequestError, GithubPullRequestRow,
@@ -84,3 +87,33 @@ pub trait GithubPullRequestIndexRepository: Send + Sync + 'static {
name: &str,
) -> impl Future<Output = Result<Vec<serde_json::Value>, Self::Err>> + Send;
}
+
+/// Lists the GitHub pull requests a caller can see.
+pub trait GithubPullRequestListing: Send + Sync + 'static {
+ /// Up to `limit` pull request records stored for one of `source_ids` and matching `query`,
+ /// one per pull request, in the query's sort order. `requesting_user` scopes the
+ /// participant and notification-state filters; without one they match nothing.
+ fn list_pull_requests(
+ &self,
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ query: ForeignEntityListQuery,
+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, GithubPullRequestError>> + Send;
+}
+
+/// Reads pull request records for listings.
+pub trait GithubPullRequestListingRepository: Send + Sync + 'static {
+ /// Error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Up to `limit` pull request records stored for one of `source_ids` and matching `query`,
+ /// one per pull request, in the query's sort order.
+ fn list_pull_requests(
+ &self,
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ query: ForeignEntityListQuery,
+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, Self::Err>> + Send;
+}
diff --git a/crates/github_pull_requests/src/domain/service.rs b/crates/github_pull_requests/src/domain/service.rs
index 4f2f454f95..3ea7118c60 100644
--- a/crates/github_pull_requests/src/domain/service.rs
+++ b/crates/github_pull_requests/src/domain/service.rs
@@ -4,8 +4,8 @@
mod test;
use foreign_entity::domain::{
- models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity},
- ports::ForeignEntityService,
+ models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity, SourceId},
+ ports::{ForeignEntityListQuery, ForeignEntityService},
};
use super::{
@@ -15,8 +15,8 @@ use super::{
GithubRepositoryIdentity, UpsertGithubPullRequest, UpsertedGithubPullRequest,
},
ports::{
- GithubPullRequestIndexRepository, GithubPullRequestIndexer, GithubPullRequestRepository,
- GithubPullRequestService,
+ GithubPullRequestIndexRepository, GithubPullRequestIndexer, GithubPullRequestListing,
+ GithubPullRequestListingRepository, GithubPullRequestRepository, GithubPullRequestService,
},
};
@@ -269,6 +269,39 @@ where
}
}
+impl<F, R> GithubPullRequestListing for GithubPullRequestServiceImpl<F, R>
+where
+ F: ForeignEntityService,
+ R: GithubPullRequestListingRepository,
+{
+ #[tracing::instrument(err, skip(self, source_ids, query))]
+ async fn list_pull_requests(
+ &self,
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ query: ForeignEntityListQuery,
+ ) -> Result<Vec<ForeignEntity>, GithubPullRequestError> {
+ if source_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ for source_id in &source_ids {
+ source_id.validate()?;
+ }
+
+ GithubPullRequestListingRepository::list_pull_requests(
+ &self.repo,
+ requesting_user,
+ source_ids,
+ limit,
+ query,
+ )
+ .await
+ .map_err(repository_error)
+ }
+}
+
fn repository_error(error: impl Into<anyhow::Error>) -> GithubPullRequestError {
GithubPullRequestError::Repository(error.into())
}
diff --git a/crates/github_pull_requests/src/domain/service/test.rs b/crates/github_pull_requests/src/domain/service/test.rs
index 677b9b5e4a..f39a374323 100644
--- a/crates/github_pull_requests/src/domain/service/test.rs
+++ b/crates/github_pull_requests/src/domain/service/test.rs
@@ -1,7 +1,7 @@
use std::convert::Infallible;
use std::sync::{Arc, Mutex};
-use chrono::Utc;
+use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
use foreign_entity::domain::{
models::{
@@ -9,17 +9,19 @@ use foreign_entity::domain::{
},
ports::{ForeignEntityListQuery, ForeignEntityService},
};
+use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};
use uuid::Uuid;
use super::GithubPullRequestServiceImpl;
use crate::domain::{
models::{
- EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, GithubPullRequestRow,
- GithubPullRequestStatus, GithubRepositoryIdentity, UpsertGithubPullRequest,
+ EnrichedGithubPullRequest, GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ GithubPullRequestError, GithubPullRequestRow, GithubPullRequestStatus,
+ GithubRepositoryIdentity, UpsertGithubPullRequest,
},
ports::{
- GithubPullRequestIndexRepository, GithubPullRequestIndexer, GithubPullRequestRepository,
- GithubPullRequestService,
+ GithubPullRequestIndexRepository, GithubPullRequestIndexer, GithubPullRequestListing,
+ GithubPullRequestListingRepository, GithubPullRequestRepository, GithubPullRequestService,
},
};
@@ -160,12 +162,28 @@ struct StubPullRequestRows {
rows: Arc<Mutex<Vec<GithubPullRequestRow>>>,
/// Stored pull request metadata by repository owner and name.
stored: Arc<Mutex<Vec<(String, String, serde_json::Value)>>>,
+ listing_calls: Arc<Mutex<Vec<ListingCall>>>,
+ fail_listings: Arc<Mutex<bool>>,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+struct ListingCall {
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ sort_method: String,
+ cursor_id: Option<Uuid>,
+ cursor_value: Option<DateTime<Utc>>,
}
impl StubPullRequestRows {
fn rows(&self) -> Vec<GithubPullRequestRow> {
self.rows.lock().unwrap().clone()
}
+
+ fn listing_calls(&self) -> Vec<ListingCall> {
+ self.listing_calls.lock().unwrap().clone()
+ }
}
impl GithubPullRequestRepository for StubPullRequestRows {
@@ -231,6 +249,32 @@ impl GithubPullRequestIndexRepository for StubPullRequestRows {
}
}
+impl GithubPullRequestListingRepository for StubPullRequestRows {
+ type Err = anyhow::Error;
+
+ async fn list_pull_requests(
+ &self,
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ query: ForeignEntityListQuery,
+ ) -> Result<Vec<ForeignEntity>, Self::Err> {
+ if *self.fail_listings.lock().unwrap() {
+ anyhow::bail!("listing failed");
+ }
+ let (cursor_id, cursor_value) = query.vals();
+ self.listing_calls.lock().unwrap().push(ListingCall {
+ requesting_user,
+ source_ids,
+ limit,
+ sort_method: query.sort_method().to_string(),
+ cursor_id: cursor_id.copied(),
+ cursor_value: cursor_value.copied(),
+ });
+ Ok(Vec::new())
+ }
+}
+
type TestService = GithubPullRequestServiceImpl<StubForeignEntityService, StubPullRequestRows>;
fn service(foreign_entities: &StubForeignEntityService, rows: &StubPullRequestRows) -> TestService {
@@ -639,3 +683,96 @@ async fn index_writes_a_row_for_each_stored_pull_request_of_each_known_repositor
assert_eq!(stored_rows[0].repository_id, Some(99));
assert_eq!(stored_rows[0].status, Some(GithubPullRequestStatus::Closed));
}
+
+fn listing_query() -> ForeignEntityListQuery {
+ Query::Sort(SimpleSortMethod::UpdatedAt, None)
+}
+
+#[tokio::test]
+async fn listing_without_sources_skips_the_repository() {
+ let rows = StubPullRequestRows::default();
+ let service = service(&StubForeignEntityService::default(), &rows);
+
+ let listed = service
+ .list_pull_requests(Some(USER_ID.to_string()), Vec::new(), 10, listing_query())
+ .await
+ .unwrap();
+
+ assert!(listed.is_empty());
+ assert!(rows.listing_calls().is_empty());
+}
+
+#[tokio::test]
+async fn listing_forwards_the_caller_sources_limit_and_query() {
+ let rows = StubPullRequestRows::default();
+ let service = service(&StubForeignEntityService::default(), &rows);
+ let cursor_id = Uuid::new_v4();
+ let cursor_value = Utc::now();
+
+ service
+ .list_pull_requests(
+ Some(USER_ID.to_string()),
+ vec![user(), team()],
+ 37,
+ Query::Cursor(Cursor {
+ id: cursor_id,
+ limit: 37,
+ val: CursorVal {
+ sort_type: SimpleSortMethod::CreatedAt,
+ last_val: cursor_value,
+ },
+ filter: None,
+ }),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ rows.listing_calls(),
+ vec![ListingCall {
+ requesting_user: Some(USER_ID.to_string()),
+ source_ids: vec![user(), team()],
+ limit: 37,
+ sort_method: "created_at".to_string(),
+ cursor_id: Some(cursor_id),
+ cursor_value: Some(cursor_value),
+ }]
+ );
+}
+
+#[tokio::test]
+async fn listing_rejects_blank_sources() {
+ let rows = StubPullRequestRows::default();
+ let service = service(&StubForeignEntityService::default(), &rows);
+
+ let error = service
+ .list_pull_requests(None, vec![SourceId::new(" ", "user")], 10, listing_query())
+ .await
+ .unwrap_err();
+
+ assert!(
+ matches!(
+ error,
+ GithubPullRequestError::ForeignEntity(ForeignEntityError::BadRequest(_))
+ ),
+ "{error:?}"
+ );
+ assert!(rows.listing_calls().is_empty());
+}
+
+#[tokio::test]
+async fn listing_reports_repository_failures() {
+ let rows = StubPullRequestRows::default();
+ *rows.fail_listings.lock().unwrap() = true;
+ let service = service(&StubForeignEntityService::default(), &rows);
+
+ let error = service
+ .list_pull_requests(None, vec![user()], 10, listing_query())
+ .await
+ .unwrap_err();
+
+ let GithubPullRequestError::Repository(error) = error else {
+ panic!("expected a repository error, got {error:?}");
+ };
+ assert!(error.to_string().contains("listing failed"));
+}
diff --git a/crates/github_pull_requests/src/lib.rs b/crates/github_pull_requests/src/lib.rs
index ceb938ee0e..560f440aa7 100644
--- a/crates/github_pull_requests/src/lib.rs
+++ b/crates/github_pull_requests/src/lib.rs
@@ -2,7 +2,7 @@
//!
//! Owns the pull request model, the rules for merging refreshed pull request data into what is
//! already stored, the typed `github_pull_request` columns read from that data, and the service
-//! that writes pull request records.
+//! that writes pull request records and lists the ones a caller can see.
//!
//! # Architecture
//!
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
index 5651ca1bd3..1bd9998848 100644
--- a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo.rs
@@ -1,6 +1,7 @@
//! PostgreSQL storage for the typed columns of GitHub pull requests.
mod index;
+mod listing;
#[cfg(test)]
mod test;
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing.rs
new file mode 100644
index 0000000000..c4b83dd491
--- /dev/null
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing.rs
@@ -0,0 +1,412 @@
+//! Listing the pull request records a caller can see, for Soup's foreign entity leg.
+
+#[cfg(test)]
+mod test;
+
+use chrono::{DateTime, Utc};
+use filter_ast::Expr;
+use foreign_entity::domain::{
+ models::{ForeignEntity, SourceId},
+ ports::ForeignEntityListQuery,
+};
+use item_filters::ast::foreign_entity::ForeignEntityLiteral;
+use models_pagination::SimpleSortMethod;
+use uuid::Uuid;
+
+use super::PgGithubPullRequestRepo;
+use crate::domain::{
+ models::GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE, ports::GithubPullRequestListingRepository,
+};
+
+struct ListingQuery<'a> {
+ source_ids: &'a [String],
+ source_auth_entities: &'a [String],
+ sort_method: SimpleSortMethod,
+ filter_jsonpath: Option<&'a str>,
+ participant_github_user_ids: Option<&'a [String]>,
+ /// Macro user id used to scope the per-user notification state predicates.
+ /// When a notification filter is requested but this is `None`, nothing matches.
+ notification_user_id: Option<&'a str>,
+ /// Accepted sets of states present on the entity (unseen=1, seen=2, done=4).
+ /// None means no notification filter; an empty list matches nothing.
+ notification_sets: Option<&'a [i32]>,
+ cursor_id: Option<Uuid>,
+ cursor_value: Option<DateTime<Utc>>,
+ limit: i64,
+}
+
+fn source_id_parts(source_ids: &[SourceId]) -> (Vec<String>, Vec<String>) {
+ source_ids
+ .iter()
+ .map(|source_id| (source_id.id.clone(), source_id.auth_entity.clone()))
+ .unzip()
+}
+
+/// A participant or mixed metadata/notification subtree cannot be lifted safely.
+/// Pure notification subtrees support AND, OR, and NOT.
+struct UnsupportedHoistedFilter;
+
+/// Filters lifted off the top-level AND spine into dedicated SQL predicates because they cannot be
+/// expressed in the metadata jsonpath (they need indexed-containment or notification-table joins).
+#[derive(Default)]
+struct HoistedForeignEntityFilters {
+ includes_me: bool,
+ // A truth table over the eight possible sets of notification states present
+ // on an entity. AND combines truth tables, not row-level state predicates:
+ // an unseen literal and a seen literal can match different notifications.
+ notification_matches: Option<u8>,
+ jsonpath: Option<String>,
+}
+
+impl HoistedForeignEntityFilters {
+ fn and(self, other: Self) -> Self {
+ Self {
+ includes_me: self.includes_me || other.includes_me,
+ notification_matches: match (self.notification_matches, other.notification_matches) {
+ (Some(a), Some(b)) => Some(a & b),
+ (a, b) => a.or(b),
+ },
+ jsonpath: match (self.jsonpath, other.jsonpath) {
+ (Some(a), Some(b)) => Some(format!("({a} && {b})")),
+ (a, b) => a.or(b),
+ },
+ }
+ }
+}
+
+fn notification_matches(expr: &Expr<ForeignEntityLiteral>, present: u8) -> Option<bool> {
+ match expr {
+ Expr::Literal(ForeignEntityLiteral::NotificationState(state)) => {
+ use item_filters::NotificationState::*;
+ let bit = match state {
+ Unseen => 1,
+ Seen => 2,
+ Done => 4,
+ };
+ Some(present & bit != 0)
+ }
+ Expr::And(a, b) => {
+ let (a, b) = (
+ notification_matches(a, present)?,
+ notification_matches(b, present)?,
+ );
+ Some(a && b)
+ }
+ Expr::Or(a, b) => {
+ let (a, b) = (
+ notification_matches(a, present)?,
+ notification_matches(b, present)?,
+ );
+ Some(a || b)
+ }
+ Expr::Not(expr) => notification_matches(expr, present).map(|v| !v),
+ _ => None,
+ }
+}
+
+fn notification_truth_table(expr: &Expr<ForeignEntityLiteral>) -> Option<u8> {
+ (0..8).try_fold(0, |table, present| {
+ notification_matches(expr, present).map(|matches| table | (u8::from(matches) << present))
+ })
+}
+
+/// Literals that cannot be represented in the metadata jsonpath and must be lifted into dedicated
+/// SQL predicates instead.
+fn is_hoisted_literal(literal: &ForeignEntityLiteral) -> bool {
+ matches!(
+ literal,
+ ForeignEntityLiteral::IncludesMe | ForeignEntityLiteral::NotificationState(_)
+ )
+}
+
+fn contains_hoisted_literal(expr: &Expr<ForeignEntityLiteral>) -> bool {
+ match expr {
+ Expr::And(left, right) | Expr::Or(left, right) => {
+ contains_hoisted_literal(left) || contains_hoisted_literal(right)
+ }
+ Expr::Not(inner) => contains_hoisted_literal(inner),
+ Expr::Literal(literal) => is_hoisted_literal(literal),
+ }
+}
+
+/// Lift participant predicates and pure notification subtrees off the AND spine.
+/// Notification subtrees preserve their full boolean expression through a truth table;
+/// other literals remain in the metadata jsonpath. Mixed OR/NOT subtrees fail closed.
+fn extract_hoisted_filters(
+ expr: &Expr<ForeignEntityLiteral>,
+) -> Result<HoistedForeignEntityFilters, UnsupportedHoistedFilter> {
+ if let Some(table) = notification_truth_table(expr) {
+ return Ok(HoistedForeignEntityFilters {
+ notification_matches: Some(table),
+ ..Default::default()
+ });
+ }
+ match expr {
+ Expr::And(left, right) => {
+ Ok(extract_hoisted_filters(left)?.and(extract_hoisted_filters(right)?))
+ }
+ Expr::Literal(ForeignEntityLiteral::IncludesMe) => Ok(HoistedForeignEntityFilters {
+ includes_me: true,
+ ..Default::default()
+ }),
+ other => {
+ if contains_hoisted_literal(other) {
+ Err(UnsupportedHoistedFilter)
+ } else {
+ Ok(HoistedForeignEntityFilters {
+ jsonpath: Some(foreign_entity_expr_jsonpath(other)),
+ ..Default::default()
+ })
+ }
+ }
+ }
+}
+
+fn foreign_entity_expr_jsonpath(expr: &Expr<ForeignEntityLiteral>) -> String {
+ match expr {
+ Expr::And(left, right) => format!(
+ "({} && {})",
+ foreign_entity_expr_jsonpath(left),
+ foreign_entity_expr_jsonpath(right)
+ ),
+ Expr::Or(left, right) => format!(
+ "({} || {})",
+ foreign_entity_expr_jsonpath(left),
+ foreign_entity_expr_jsonpath(right)
+ ),
+ Expr::Not(inner) => format!("(!{})", foreign_entity_expr_jsonpath(inner)),
+ Expr::Literal(literal) => foreign_entity_literal_jsonpath(literal),
+ }
+}
+
+fn foreign_entity_literal_jsonpath(literal: &ForeignEntityLiteral) -> String {
+ match literal {
+ ForeignEntityLiteral::Id(id) => jsonpath_text_eq("id", &id.to_string()),
+ ForeignEntityLiteral::ForeignEntityId(id) => jsonpath_text_eq("foreignEntityId", id),
+ ForeignEntityLiteral::ForeignEntitySource(source) => {
+ jsonpath_text_eq("foreignEntitySource", source)
+ }
+ // IncludesMe and the notification literals are hoisted into dedicated SQL predicates by
+ // extract_hoisted_filters and never reach the jsonpath; if one slips through, match nothing
+ // rather than everything.
+ ForeignEntityLiteral::IncludesMe | ForeignEntityLiteral::NotificationState(_) => {
+ "(1 == 0)".to_string()
+ }
+ }
+}
+
+fn jsonpath_text_eq(field_name: &str, expected_value: &str) -> String {
+ let expected_value = serde_json::to_string(expected_value)
+ .expect("serializing a string literal to JSON should not fail");
+ format!("($.{field_name} == {expected_value})")
+}
+
+impl PgGithubPullRequestRepo {
+ async fn fetch_listing(
+ &self,
+ query: ListingQuery<'_>,
+ ) -> Result<Vec<ForeignEntity>, sqlx::Error> {
+ let ListingQuery {
+ source_ids,
+ source_auth_entities,
+ sort_method,
+ filter_jsonpath,
+ participant_github_user_ids,
+ notification_user_id,
+ notification_sets,
+ cursor_id,
+ cursor_value,
+ limit,
+ } = query;
+ let sort_method = sort_method.to_string();
+
+ sqlx::query_as!(
+ ForeignEntity,
+ r#"
+ WITH source_ids AS (
+ SELECT DISTINCT stored_for_id, stored_for_auth_entity
+ FROM UNNEST($1::text[], $2::text[])
+ AS source_rows(stored_for_id, stored_for_auth_entity)
+ ),
+ deduped AS (
+ SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)
+ fe.id,
+ fe.foreign_entity_id,
+ fe.foreign_entity_source,
+ fe.metadata,
+ fe.stored_for_id,
+ fe.stored_for_auth_entity,
+ fe.created_at,
+ fe.updated_at,
+ CASE $3::text
+ WHEN 'created_at' THEN fe.created_at
+ ELSE fe.updated_at
+ END AS sort_at
+ FROM foreign_entity fe
+ WHERE fe.foreign_entity_source = $11::text
+ AND EXISTS (
+ SELECT 1
+ FROM source_ids s
+ WHERE s.stored_for_id = fe.stored_for_id
+ AND s.stored_for_auth_entity = fe.stored_for_auth_entity
+ )
+ AND (
+ $4::text IS NULL
+ OR jsonb_path_match(
+ jsonb_build_object(
+ 'id', fe.id::text,
+ 'foreignEntityId', fe.foreign_entity_id,
+ 'foreignEntitySource', fe.foreign_entity_source
+ ),
+ ($4::text)::jsonpath
+ )
+ )
+ AND (
+ $8::text[] IS NULL
+ OR (fe.metadata -> 'participantGithubUserIds') ?| $8::text[]
+ )
+ AND (
+ $9::int[] IS NULL
+ OR ($10::text IS NOT NULL AND (
+ SELECT COALESCE(bit_or(CASE un.state
+ WHEN 'unseen' THEN 1 WHEN 'seen' THEN 2 WHEN 'done' THEN 4 END), 0)
+ FROM notification n
+ JOIN user_notification un ON un.notification_id = n.id
+ WHERE un.user_id = $10::text
+ AND un.deleted_at IS NULL
+ AND n.event_item_type = 'foreign_entity'
+ AND n.event_item_id = fe.id::text
+ ) = ANY($9::int[]))
+ )
+ ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC
+ )
+ SELECT
+ id as "id!: Uuid",
+ foreign_entity_id as "foreign_entity_id!: String",
+ foreign_entity_source as "foreign_entity_source!: String",
+ metadata as "metadata!: serde_json::Value",
+ stored_for_id as "stored_for_id!: String",
+ stored_for_auth_entity as "stored_for_auth_entity!: String",
+ created_at as "created_at!: DateTime<Utc>",
+ updated_at as "updated_at!: DateTime<Utc>"
+ FROM deduped
+ WHERE $5::timestamptz IS NULL
+ OR (sort_at, id) < ($5::timestamptz, $6::uuid)
+ ORDER BY sort_at DESC, id DESC
+ LIMIT $7
+ "#,
+ source_ids,
+ source_auth_entities,
+ sort_method,
+ filter_jsonpath,
+ cursor_value,
+ cursor_id,
+ limit,
+ participant_github_user_ids,
+ notification_sets,
+ notification_user_id,
+ GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE,
+ )
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ async fn github_user_ids_for_macro_user(
+ &self,
+ macro_user_id: &str,
+ ) -> Result<Vec<String>, sqlx::Error> {
+ sqlx::query_scalar!(
+ r#"
+ SELECT github_user_id
+ FROM github_links
+ WHERE macro_id = $1
+ "#,
+ macro_user_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ }
+}
+
+impl GithubPullRequestListingRepository for PgGithubPullRequestRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(err, skip(self, source_ids, query))]
+ async fn list_pull_requests(
+ &self,
+ requesting_user: Option<String>,
+ source_ids: Vec<SourceId>,
+ limit: u32,
+ query: ForeignEntityListQuery,
+ ) -> Result<Vec<ForeignEntity>, Self::Err> {
+ if source_ids.is_empty() || limit == 0 {
+ return Ok(Vec::new());
+ }
+
+ let HoistedForeignEntityFilters {
+ includes_me,
+ notification_matches,
+ jsonpath: filter_jsonpath,
+ } = match query
+ .filter()
+ .as_deref()
+ .map(extract_hoisted_filters)
+ .transpose()
+ {
+ Ok(hoisted) => hoisted.unwrap_or_default(),
+ Err(UnsupportedHoistedFilter) => {
+ tracing::warn!(
+ "IncludesMe or mixed metadata/notification literal under Or/Not in a foreign entity filter is unsupported; returning no results"
+ );
+ return Ok(Vec::new());
+ }
+ };
+
+ // No possible set of notifications satisfies this boolean expression.
+ // Different state literals joined by AND are not inherently contradictory.
+ if notification_matches == Some(0) {
+ return Ok(Vec::new());
+ }
+
+ let participant_github_user_ids = if includes_me {
+ let Some(requesting_user) = requesting_user.as_deref() else {
+ return Ok(Vec::new());
+ };
+ let github_user_ids = self.github_user_ids_for_macro_user(requesting_user).await?;
+ if github_user_ids.is_empty() {
+ // No linked GitHub identity: the user participates in nothing.
+ return Ok(Vec::new());
+ }
+ Some(github_user_ids)
+ } else {
+ None
+ };
+
+ let notification_sets: Option<Vec<i32>> = notification_matches.map(|table| {
+ (0..8)
+ .filter(|present| table & (1 << present) != 0)
+ .collect()
+ });
+ // Notification states are scoped to the requesting user's per-user notification row.
+ // Without a requesting user the predicate matches nothing, so an active notification
+ // filter yields no results (consistent with the participant filter above).
+ let notification_user_id = requesting_user.as_deref();
+
+ let (source_ids, source_auth_entities) = source_id_parts(&source_ids);
+ let (cursor_id, cursor_value) = query.vals();
+
+ self.fetch_listing(ListingQuery {
+ source_ids: &source_ids,
+ source_auth_entities: &source_auth_entities,
+ sort_method: *query.sort_method(),
+ filter_jsonpath: filter_jsonpath.as_deref(),
+ participant_github_user_ids: participant_github_user_ids.as_deref(),
+ notification_user_id,
+ notification_sets: notification_sets.as_deref(),
+ cursor_id: cursor_id.copied(),
+ cursor_value: cursor_value.copied(),
+ limit: limit as i64,
+ })
+ .await
+ }
+}
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test.rs
new file mode 100644
index 0000000000..a37e36e33c
--- /dev/null
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test.rs
@@ -0,0 +1,1033 @@
+mod notification_state;
+
+use std::sync::Arc;
+
+use chrono::Utc;
+use filter_ast::Expr;
+use foreign_entity::{
+ domain::{
+ models::{CreateForeignEntity, ForeignEntity, SourceId},
+ ports::{ForeignEntityListQuery, ForeignEntityRepository},
+ },
+ outbound::pg_foreign_entity_repo::PgForeignEntityRepo,
+};
+use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use models_pagination::{Cursor, CursorVal, Query, SimpleSortMethod};
+use serde_json::json;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::super::PgGithubPullRequestRepo;
+use crate::domain::ports::GithubPullRequestListingRepository;
+
+fn create_request_for_source(
+ foreign_entity_id: impl Into<String>,
+ foreign_entity_source: impl Into<String>,
+ stored_for_id: impl Into<String>,
+ stored_for_auth_entity: impl Into<String>,
+) -> CreateForeignEntity {
+ CreateForeignEntity {
+ foreign_entity_id: foreign_entity_id.into(),
+ foreign_entity_source: foreign_entity_source.into(),
+ metadata: json!({ "origin": "test" }),
+ stored_for_id: stored_for_id.into(),
+ stored_for_auth_entity: stored_for_auth_entity.into(),
+ }
+}
+
+async fn insert_foreign_entity_for_source(
+ repo: &PgForeignEntityRepo,
+ foreign_entity_id: &str,
+ foreign_entity_source: &str,
+ stored_for_id: &str,
+ stored_for_auth_entity: &str,
+) -> ForeignEntity {
+ repo.create_foreign_entity(
+ Uuid::now_v7(),
+ create_request_for_source(
+ foreign_entity_id,
+ foreign_entity_source,
+ stored_for_id,
+ stored_for_auth_entity,
+ ),
+ )
+ .await
+ .expect("foreign entity should be inserted")
+}
+
+fn list_query(sort_method: SimpleSortMethod) -> ForeignEntityListQuery {
+ Query::Sort(sort_method, None)
+}
+
+fn cursor_query(entity: &ForeignEntity, sort_method: SimpleSortMethod) -> ForeignEntityListQuery {
+ let last_val = match sort_method {
+ SimpleSortMethod::CreatedAt => entity.created_at,
+ SimpleSortMethod::ViewedAt
+ | SimpleSortMethod::UpdatedAt
+ | SimpleSortMethod::ViewedUpdated => entity.updated_at,
+ };
+
+ Query::Cursor(Cursor {
+ id: entity.id,
+ limit: 2,
+ val: CursorVal {
+ sort_type: sort_method,
+ last_val,
+ },
+ filter: None,
+ })
+}
+
+fn filter_query(filter: LiteralTree<ForeignEntityLiteral>) -> ForeignEntityListQuery {
+ Query::Sort(SimpleSortMethod::UpdatedAt, filter)
+}
+
+fn ids(entities: &[ForeignEntity]) -> Vec<Uuid> {
+ entities.iter().map(|entity| entity.id).collect()
+}
+
+async fn set_timestamps(
+ pool: &PgPool,
+ repo: &PgForeignEntityRepo,
+ entity: &ForeignEntity,
+ created_at: chrono::DateTime<chrono::Utc>,
+ updated_at: chrono::DateTime<chrono::Utc>,
+) -> ForeignEntity {
+ sqlx::query!(
+ r#"
+ UPDATE foreign_entity
+ SET created_at = $2, updated_at = $3
+ WHERE id = $1
+ "#,
+ entity.id,
+ created_at,
+ updated_at,
+ )
+ .execute(pool)
+ .await
+ .expect("foreign entity timestamps should be updated");
+
+ repo.get_foreign_entity_by_id(entity.id)
+ .await
+ .expect("updated foreign entity lookup should succeed")
+ .expect("updated foreign entity should exist")
+}
+
+async fn insert_pr_with_participants(
+ repo: &PgForeignEntityRepo,
+ foreign_entity_id: &str,
+ stored_for_id: &str,
+ participant_github_user_ids: Option<&[&str]>,
+) -> ForeignEntity {
+ let mut metadata = json!({ "displayName": foreign_entity_id });
+ if let Some(participants) = participant_github_user_ids {
+ metadata["participantGithubUserIds"] = json!(participants);
+ }
+
+ repo.create_foreign_entity(
+ Uuid::now_v7(),
+ CreateForeignEntity {
+ foreign_entity_id: foreign_entity_id.into(),
+ foreign_entity_source: "github_pull_request".into(),
+ metadata,
+ stored_for_id: stored_for_id.into(),
+ stored_for_auth_entity: "user".into(),
+ },
+ )
+ .await
+ .expect("pull request foreign entity should be inserted")
+}
+
+async fn insert_github_link(pool: &PgPool, macro_id: &str, github_user_id: &str) {
+ let macro_user_id = Uuid::now_v7();
+ let email = format!("{macro_user_id}@example.com");
+
+ sqlx::query(
+ r#"
+ INSERT INTO public.macro_user (id, username, email, stripe_customer_id)
+ VALUES ($1, $2, $3, $4)
+ "#,
+ )
+ .bind(macro_user_id)
+ .bind(macro_id)
+ .bind(&email)
+ .bind(format!("cus_{macro_user_id}"))
+ .execute(pool)
+ .await
+ .expect("macro_user row should be inserted");
+
+ sqlx::query(
+ r#"
+ INSERT INTO public."User" (id, email, macro_user_id)
+ VALUES ($1, $2, $3)
+ "#,
+ )
+ .bind(macro_id)
+ .bind(&email)
+ .bind(macro_user_id)
+ .execute(pool)
+ .await
+ .expect("User row should be inserted");
+
+ sqlx::query(
+ r#"
+ INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)
+ VALUES ($1, $2, $3, $4, $5)
+ "#,
+ )
+ .bind(Uuid::now_v7())
+ .bind(macro_id)
+ .bind(Uuid::now_v7())
+ .bind(format!("gh-{github_user_id}"))
+ .bind(github_user_id)
+ .execute(pool)
+ .await
+ .expect("github_links row should be inserted");
+}
+
+fn includes_me_filter() -> LiteralTree<ForeignEntityLiteral> {
+ Some(Arc::new(Expr::val(ForeignEntityLiteral::IncludesMe)))
+}
+/// Insert a `foreign_entity`-scoped notification and the matching per-user row so the
+/// notification done/seen predicates have something to match against.
+async fn insert_foreign_entity_notification(
+ pool: &PgPool,
+ foreign_entity_id: Uuid,
+ user_id: &str,
+ done: bool,
+ seen: bool,
+) {
+ let notification_id = Uuid::now_v7();
+ sqlx::query(
+ r#"
+ INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender)
+ VALUES ($1, 'github_pr_status_changed', $2, 'foreign_entity', 'test')
+ "#,
+ )
+ .bind(notification_id)
+ .bind(foreign_entity_id.to_string())
+ .execute(pool)
+ .await
+ .expect("notification row should be inserted");
+
+ let seen_at: Option<chrono::NaiveDateTime> = seen.then(|| Utc::now().naive_utc());
+ sqlx::query!(
+ r#"
+ INSERT INTO user_notification (user_id, notification_id, state, seen_at)
+ VALUES ($1, $2, CASE WHEN $3::bool THEN 'done'::notification_state
+ WHEN $4::timestamp IS NOT NULL THEN 'seen'::notification_state
+ ELSE 'unseen'::notification_state END, $4)
+ "#,
+ user_id,
+ notification_id,
+ done,
+ seen_at,
+ )
+ .execute(pool)
+ .await
+ .expect("user_notification row should be inserted");
+}
+
+fn notification_states_filter(
+ states: &[item_filters::NotificationState],
+) -> LiteralTree<ForeignEntityLiteral> {
+ states
+ .iter()
+ .map(|state| Expr::val(ForeignEntityLiteral::NotificationState(*state)))
+ .reduce(Expr::or)
+ .map(Arc::new)
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_returns_matching_user_and_team_sources(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let team_id = Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
+ let user_entity = insert_foreign_entity_for_source(
+ &repo,
+ "user-visible-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let team_entity = insert_foreign_entity_for_source(
+ &repo,
+ "team-visible-pr",
+ "github_pull_request",
+ &team_id.to_string(),
+ "team",
+ )
+ .await;
+ insert_foreign_entity_for_source(
+ &repo,
+ "unrelated-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+
+ let entities = listing
+ .list_pull_requests(
+ None,
+ vec![
+ SourceId::user("macro|[email protected]"),
+ SourceId::team(team_id),
+ ],
+ 10,
+ list_query(SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("foreign entities should be listed for matching sources");
+
+ let mut actual_ids = ids(&entities);
+ actual_ids.sort_unstable();
+ let mut expected_ids = vec![user_entity.id, team_entity.id];
+ expected_ids.sort_unstable();
+
+ assert_eq!(actual_ids, expected_ids);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_empty_sources_returns_empty(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ insert_foreign_entity_for_source(
+ &repo,
+ "user-visible-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+
+ let entities = listing
+ .list_pull_requests(
+ None,
+ Vec::new(),
+ 10,
+ list_query(SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("empty source list should succeed");
+
+ assert!(entities.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_dedupes_duplicate_source_grants(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let team_id = Uuid::parse_str("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb").unwrap();
+ let older = insert_foreign_entity_for_source(
+ &repo,
+ "shared-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let newer = insert_foreign_entity_for_source(
+ &repo,
+ "shared-pr",
+ "github_pull_request",
+ &team_id.to_string(),
+ "team",
+ )
+ .await;
+
+ let now = Utc::now();
+ let older = set_timestamps(
+ &pool,
+ &repo,
+ &older,
+ now - chrono::Duration::minutes(2),
+ now - chrono::Duration::minutes(2),
+ )
+ .await;
+ let newer = set_timestamps(
+ &pool,
+ &repo,
+ &newer,
+ now - chrono::Duration::minutes(1),
+ now - chrono::Duration::minutes(1),
+ )
+ .await;
+
+ let entities = listing
+ .list_pull_requests(
+ None,
+ vec![
+ SourceId::user("macro|[email protected]"),
+ SourceId::team(team_id),
+ ],
+ 10,
+ list_query(SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("duplicate foreign entity grants should be listed once");
+
+ assert_eq!(entities, vec![newer]);
+ assert_ne!(entities[0].id, older.id);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_paginates_by_created_at(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let first = insert_foreign_entity_for_source(
+ &repo,
+ "first-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let second = insert_foreign_entity_for_source(
+ &repo,
+ "second-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let third = insert_foreign_entity_for_source(
+ &repo,
+ "third-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let now = Utc::now();
+ let first = set_timestamps(
+ &pool,
+ &repo,
+ &first,
+ now - chrono::Duration::minutes(1),
+ now - chrono::Duration::minutes(30),
+ )
+ .await;
+ let second = set_timestamps(
+ &pool,
+ &repo,
+ &second,
+ now - chrono::Duration::minutes(2),
+ now - chrono::Duration::minutes(10),
+ )
+ .await;
+ let third = set_timestamps(
+ &pool,
+ &repo,
+ &third,
+ now - chrono::Duration::minutes(3),
+ now - chrono::Duration::minutes(20),
+ )
+ .await;
+
+ let first_page = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 2,
+ list_query(SimpleSortMethod::CreatedAt),
+ )
+ .await
+ .expect("first created_at page should be fetched");
+ let second_page = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 2,
+ cursor_query(&first_page[1], SimpleSortMethod::CreatedAt),
+ )
+ .await
+ .expect("second created_at page should be fetched");
+
+ assert_eq!(first_page, vec![first, second]);
+ assert_eq!(second_page, vec![third]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_paginates_by_updated_at(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let first = insert_foreign_entity_for_source(
+ &repo,
+ "first-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let second = insert_foreign_entity_for_source(
+ &repo,
+ "second-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let third = insert_foreign_entity_for_source(
+ &repo,
+ "third-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ let now = Utc::now();
+ let first = set_timestamps(
+ &pool,
+ &repo,
+ &first,
+ now - chrono::Duration::minutes(30),
+ now - chrono::Duration::minutes(1),
+ )
+ .await;
+ let second = set_timestamps(
+ &pool,
+ &repo,
+ &second,
+ now - chrono::Duration::minutes(10),
+ now - chrono::Duration::minutes(2),
+ )
+ .await;
+ let third = set_timestamps(
+ &pool,
+ &repo,
+ &third,
+ now - chrono::Duration::minutes(20),
+ now - chrono::Duration::minutes(3),
+ )
+ .await;
+
+ let first_page = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 2,
+ list_query(SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("first updated_at page should be fetched");
+ let second_page = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 2,
+ cursor_query(&first_page[1], SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("second updated_at page should be fetched");
+
+ assert_eq!(first_page, vec![first, second]);
+ assert_eq!(second_page, vec![third]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_applies_foreign_entity_filters(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let github = insert_foreign_entity_for_source(
+ &repo,
+ "github-pr",
+ "github_pull_request",
+ "user",
+ )
+ .await;
+ insert_foreign_entity_for_source(
+ &repo,
+ "linear-issue",
+ "linear_issue",
+ "user",
+ )
+ .await;
+
+ let source_filter = Some(Arc::new(Expr::val(
+ ForeignEntityLiteral::ForeignEntitySource("github_pull_request".to_string()),
+ )));
+ let source_matches = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 10,
+ filter_query(source_filter),
+ )
+ .await
+ .expect("foreign entity source filter should be applied");
+
+ let not_linear_filter = Some(Arc::new(Expr::is_not(Expr::val(
+ ForeignEntityLiteral::ForeignEntityId("linear-issue".to_string()),
+ ))));
+ let not_linear_matches = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user("macro|[email protected]")],
+ 10,
+ filter_query(not_linear_filter),
+ )
+ .await
+ .expect("foreign entity negated filter should be applied");
+
+ assert_eq!(source_matches, vec![github.clone()]);
+ assert_eq!(not_linear_matches, vec![github]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_filters_to_participant_metadata(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_github_link(&pool, macro_id, "42").await;
+
+ let involved =
+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["7", "42"])).await;
+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
+ insert_pr_with_participants(&repo, "legacy-pr", macro_id, None).await;
+
+ let entities = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(includes_me_filter()),
+ )
+ .await
+ .expect("includes_me filter should be applied");
+
+ assert_eq!(entities, vec![involved]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_matches_every_linked_github_identity(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_github_link(&pool, macro_id, "42").await;
+ sqlx::query!(
+ r#"
+ INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)
+ VALUES ($1, $2, $3, $4, $5)
+ "#,
+ Uuid::now_v7(),
+ macro_id,
+ Uuid::now_v7(),
+ "gh-99",
+ "99",
+ )
+ .execute(&pool)
+ .await
+ .expect("second github link should be inserted");
+
+ let first = insert_pr_with_participants(&repo, "first-pr", macro_id, Some(&["42"])).await;
+ let second = insert_pr_with_participants(&repo, "second-pr", macro_id, Some(&["99"])).await;
+ insert_pr_with_participants(&repo, "unrelated-pr", macro_id, Some(&["7"])).await;
+ insert_pr_with_participants(&repo, "legacy-pr", macro_id, None).await;
+
+ let entities = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(includes_me_filter()),
+ )
+ .await
+ .expect("includes_me should match both linked identities");
+
+ assert_eq!(ids(&entities).len(), 2);
+ assert!(ids(&entities).contains(&first.id));
+ assert!(ids(&entities).contains(&second.id));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_without_github_link_returns_empty(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
+
+ let entities = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(includes_me_filter()),
+ )
+ .await
+ .expect("includes_me without a github link should succeed");
+
+ assert!(entities.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_without_requesting_user_returns_empty(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_github_link(&pool, macro_id, "42").await;
+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
+
+ let entities = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(includes_me_filter()),
+ )
+ .await
+ .expect("includes_me without a requesting user should succeed");
+
+ assert!(entities.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_composes_with_other_filters(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_github_link(&pool, macro_id, "42").await;
+
+ let involved = insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
+ insert_foreign_entity_for_source(&repo, "linear-issue", "linear_issue", macro_id, "user").await;
+
+ let filter = Some(Arc::new(Expr::and(
+ Expr::val(ForeignEntityLiteral::ForeignEntitySource(
+ "github_pull_request".to_string(),
+ )),
+ Expr::val(ForeignEntityLiteral::IncludesMe),
+ )));
+ let entities = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(filter),
+ )
+ .await
+ .expect("includes_me composed with a source filter should be applied");
+
+ assert_eq!(entities, vec![involved]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_includes_me_under_not_fails_closed(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ insert_github_link(&pool, macro_id, "42").await;
+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;
+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;
+
+ let filter = Some(Arc::new(Expr::is_not(Expr::val(
+ ForeignEntityLiteral::IncludesMe,
+ ))));
+ let entities = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(filter),
+ )
+ .await
+ .expect("unsupported includes_me placement should fail closed");
+
+ assert!(entities.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_done_filters_by_done_state(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+
+ let done =
+ insert_foreign_entity_for_source(&repo, "done-pr", "github_pull_request", macro_id, "user")
+ .await;
+ let not_done = insert_foreign_entity_for_source(
+ &repo,
+ "not-done-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+ // No notification at all: matches neither done=true nor done=false.
+ insert_foreign_entity_for_source(
+ &repo,
+ "no-notif-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+
+ insert_foreign_entity_notification(&pool, done.id, macro_id, true, false).await;
+ insert_foreign_entity_notification(&pool, not_done.id, macro_id, false, false).await;
+
+ let done_matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Done,
+ ])),
+ )
+ .await
+ .expect("done=true filter should be applied");
+
+ let not_done_matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Unseen,
+ item_filters::NotificationState::Seen,
+ ])),
+ )
+ .await
+ .expect("done=false filter should be applied");
+
+ assert_eq!(done_matches, vec![done]);
+ assert_eq!(not_done_matches, vec![not_done]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_seen_filters_by_seen_state(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+
+ let seen =
+ insert_foreign_entity_for_source(&repo, "seen-pr", "github_pull_request", macro_id, "user")
+ .await;
+ let unseen = insert_foreign_entity_for_source(
+ &repo,
+ "unseen-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+
+ insert_foreign_entity_notification(&pool, seen.id, macro_id, false, true).await;
+ insert_foreign_entity_notification(&pool, unseen.id, macro_id, false, false).await;
+
+ let seen_matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Seen,
+ item_filters::NotificationState::Done,
+ ])),
+ )
+ .await
+ .expect("seen=true filter should be applied");
+
+ let unseen_matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Unseen,
+ ])),
+ )
+ .await
+ .expect("seen=false filter should be applied");
+
+ assert_eq!(seen_matches, vec![seen]);
+ assert_eq!(unseen_matches, vec![unseen]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_done_composes_with_source(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+
+ let github = insert_foreign_entity_for_source(
+ &repo,
+ "github-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+ let linear =
+ insert_foreign_entity_for_source(&repo, "linear-issue", "linear_issue", macro_id, "user")
+ .await;
+
+ insert_foreign_entity_notification(&pool, github.id, macro_id, true, false).await;
+ insert_foreign_entity_notification(&pool, linear.id, macro_id, true, false).await;
+
+ let filter = Some(Arc::new(Expr::and(
+ Expr::val(ForeignEntityLiteral::ForeignEntitySource(
+ "github_pull_request".to_string(),
+ )),
+ Expr::val(ForeignEntityLiteral::NotificationState(
+ item_filters::NotificationState::Done,
+ )),
+ )));
+
+ let matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(filter),
+ )
+ .await
+ .expect("source AND notification done filter should be applied");
+
+ assert_eq!(matches, vec![github]);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_done_scopes_to_requesting_user(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ let other_id = "macro|[email protected]";
+
+ let entity = insert_foreign_entity_for_source(
+ &repo,
+ "shared-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+ // The done notification belongs to a different user.
+ insert_foreign_entity_notification(&pool, entity.id, other_id, true, false).await;
+
+ let matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Done,
+ ])),
+ )
+ .await
+ .expect("notification filter scoped to requesting user should be applied");
+
+ assert!(matches.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_filter_without_requesting_user_returns_empty(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+
+ let entity =
+ insert_foreign_entity_for_source(&repo, "done-pr", "github_pull_request", macro_id, "user")
+ .await;
+ insert_foreign_entity_notification(&pool, entity.id, macro_id, true, false).await;
+
+ let matches = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Done,
+ ])),
+ )
+ .await
+ .expect("notification filter without a requesting user should succeed");
+
+ assert!(matches.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_notification_state_and_requires_each_witness(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+
+ let entity =
+ insert_foreign_entity_for_source(&repo, "done-pr", "github_pull_request", macro_id, "user")
+ .await;
+ insert_foreign_entity_notification(&pool, entity.id, macro_id, true, false).await;
+
+ // Sanity check: done=true alone matches the entity.
+ let one_sided = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(notification_states_filter(&[
+ item_filters::NotificationState::Done,
+ ])),
+ )
+ .await
+ .expect("done=true filter should be applied");
+ assert_eq!(one_sided, vec![entity.clone()]);
+
+ // done=true AND done=false is contradictory and must match nothing rather than
+ // collapsing to a single-sided predicate.
+ let contradiction = Some(Arc::new(Expr::and(
+ Expr::val(ForeignEntityLiteral::NotificationState(
+ item_filters::NotificationState::Done,
+ )),
+ Expr::or(
+ filter_ast::Expr::val(ForeignEntityLiteral::NotificationState(
+ item_filters::NotificationState::Unseen,
+ )),
+ filter_ast::Expr::val(ForeignEntityLiteral::NotificationState(
+ item_filters::NotificationState::Seen,
+ )),
+ ),
+ )));
+ let matches = listing
+ .list_pull_requests(
+ Some(macro_id.to_string()),
+ vec![SourceId::user(macro_id)],
+ 10,
+ filter_query(contradiction),
+ )
+ .await
+ .expect("contradictory notification filter should be applied");
+
+ assert!(matches.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn list_excludes_other_foreign_entity_sources(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let macro_id = "macro|[email protected]";
+ let pull_request = insert_foreign_entity_for_source(
+ &repo,
+ "github-pr",
+ "github_pull_request",
+ macro_id,
+ "user",
+ )
+ .await;
+ insert_foreign_entity_for_source(&repo, "linear-issue", "linear_issue", macro_id, "user").await;
+
+ let entities = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user(macro_id)],
+ 10,
+ list_query(SimpleSortMethod::UpdatedAt),
+ )
+ .await
+ .expect("listing should succeed");
+
+ assert_eq!(entities, vec![pull_request]);
+}
diff --git a/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test/notification_state.rs b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test/notification_state.rs
new file mode 100644
index 0000000000..a4fcc2da34
--- /dev/null
+++ b/crates/github_pull_requests/src/outbound/pg_github_pull_request_repo/listing/test/notification_state.rs
@@ -0,0 +1,93 @@
+use super::*;
+use item_filters::NotificationState::{Done, Seen, Unseen};
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn notification_boolean_filters_match_every_present_state_set(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let listing = PgGithubPullRequestRepo::new(pool.clone());
+ let user = "macro|[email protected]";
+ let mut ids = Vec::new();
+ for present in 0..8 {
+ let entity = insert_foreign_entity_for_source(
+ &repo,
+ &format!("pr-{present}"),
+ "github_pull_request",
+ user,
+ "user",
+ )
+ .await;
+ ids.push(entity.id);
+ for (bit, done, seen) in [(1, false, false), (2, false, true), (4, true, true)] {
+ if present & bit != 0 {
+ insert_foreign_entity_notification(&pool, entity.id, user, done, seen).await;
+ }
+ }
+ }
+ // Neither another user's notification nor a deleted row may affect our set.
+ insert_foreign_entity_notification(&pool, ids[0], "macro|[email protected]", true, true).await;
+ insert_foreign_entity_notification(&pool, ids[0], user, false, true).await;
+ sqlx::query!(
+ "UPDATE user_notification un SET deleted_at = NOW() FROM notification n
+ WHERE un.notification_id = n.id AND n.event_item_id = $1 AND un.user_id = $2",
+ ids[0].to_string(),
+ user,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let leaf = |state| Expr::val(ForeignEntityLiteral::NotificationState(state));
+ let cases: Vec<(_, fn(u8) -> bool)> = vec![
+ (leaf(Unseen), |set| set & 1 != 0),
+ (leaf(Seen), |set| set & 2 != 0),
+ (leaf(Done), |set| set & 4 != 0),
+ (Expr::or(leaf(Unseen), leaf(Seen)), |set| set & 3 != 0),
+ (Expr::and(leaf(Unseen), leaf(Done)), |set| {
+ set & 1 != 0 && set & 4 != 0
+ }),
+ (Expr::is_not(leaf(Done)), |set| set & 4 == 0),
+ (Expr::is_not(Expr::and(leaf(Unseen), leaf(Seen))), |set| {
+ set & 3 != 3
+ }),
+ ];
+ for (expr, matches) in cases {
+ let mut actual = listing
+ .list_pull_requests(
+ Some(user.to_owned()),
+ vec![SourceId::user(user)],
+ 100,
+ filter_query(Some(Arc::new(expr))),
+ )
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|row| row.id)
+ .collect::<Vec<_>>();
+ let mut expected = ids
+ .iter()
+ .enumerate()
+ .filter_map(|(set, id)| matches(set as u8).then_some(*id))
+ .collect::<Vec<_>>();
+ actual.sort();
+ expected.sort();
+ assert_eq!(actual, expected);
+ }
+ let missing_viewer = listing
+ .list_pull_requests(
+ None,
+ vec![SourceId::user(user)],
+ 100,
+ filter_query(Some(Arc::new(Expr::is_not(leaf(Done))))),
+ )
+ .await
+ .unwrap();
+ assert!(missing_viewer.is_empty());
+}
+
+#[test]
+fn mixed_subtrees_cannot_be_misclassified_by_boolean_short_circuiting() {
+ let state = || Expr::val(ForeignEntityLiteral::NotificationState(Done));
+ let impossible = Expr::and(state(), Expr::is_not(state()));
+ let mixed = Expr::and(impossible, Expr::val(ForeignEntityLiteral::Id(Uuid::nil())));
+ assert!(super::super::notification_truth_table(&mixed).is_none());
+}
diff --git a/crates/item_filters/src/ast/foreign_entity.rs b/crates/item_filters/src/ast/foreign_entity.rs
index cdde1bb075..0596ad5235 100644
--- a/crates/item_filters/src/ast/foreign_entity.rs
+++ b/crates/item_filters/src/ast/foreign_entity.rs
@@ -16,7 +16,8 @@ pub enum ForeignEntityLiteral {
/// Filter by the external source name.
#[serde(rename = "fes")]
ForeignEntitySource(String),
- /// Filter to entities whose metadata participant list contains the requesting user.
+ /// The requesting user takes part in the record. The GitHub pull request listing matches it
+ /// against a pull request's participants; the generic foreign entity listing matches nothing.
#[serde(rename = "me")]
IncludesMe,
/// An entity has a non-deleted notification in this exact state.
diff --git a/crates/memory/Cargo.toml b/crates/memory/Cargo.toml
index 14d7238c28..5220b5474d 100644
--- a/crates/memory/Cargo.toml
+++ b/crates/memory/Cargo.toml
@@ -46,6 +46,7 @@ entity_access_management = { path = "../entity_access_management" }
entity_registry = { path = "../entity_registry/entity_registry" }
entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }
foreign_entity = { path = "../foreign_entity" }
+github_pull_requests = { path = "../github_pull_requests" }
frecency = { path = "../frecency" }
lexical_client = { path = "../lexical_client" }
macro_aws_config = { path = "../macro_aws_config" }
diff --git a/crates/soup/Cargo.toml b/crates/soup/Cargo.toml
index 1f01a62d90..071d2a26e9 100644
--- a/crates/soup/Cargo.toml
+++ b/crates/soup/Cargo.toml
@@ -69,7 +69,7 @@ foreign_entity = { path = "../foreign_entity", default-features = false, feature
"ports",
] }
frecency = { path = "../frecency" }
-github_pull_requests = { path = "../github_pull_requests", default-features = false }
+github_pull_requests = { path = "../github_pull_requests", default-features = false, features = ["ports"] }
indexmap = { workspace = true }
item_filters = { path = "../item_filters" }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
diff --git a/crates/soup/src/domain/models.rs b/crates/soup/src/domain/models.rs
index 4426ae6501..08c0752d99 100644
--- a/crates/soup/src/domain/models.rs
+++ b/crates/soup/src/domain/models.rs
@@ -12,11 +12,9 @@ use crm::domain::companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor};
use email::domain::models::{GetEmailsRequest, PreviewView};
use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
use filter_ast::Expr;
-use foreign_entity::domain::{
- models::{ForeignEntityError, SourceId},
- ports::ForeignEntityListQuery,
-};
+use foreign_entity::domain::{models::SourceId, ports::ForeignEntityListQuery};
use frecency::domain::models::{AggregateFrecency, FrecencyQueryErr};
+use github_pull_requests::domain::models::GithubPullRequestError;
use item_filters::{
EntityFilters,
ast::{
@@ -1349,9 +1347,9 @@ pub enum SoupErr {
/// role is below admin/owner.
#[error("Querying hidden CRM companies requires admin/owner team role")]
CrmAdminRequired,
- /// Foreign entity lookup failed.
+ /// GitHub pull request listing failed.
#[error(transparent)]
- ForeignEntityErr(#[from] ForeignEntityError),
+ GithubPullRequestErr(#[from] GithubPullRequestError),
/// Entity filter AST expansion failed.
#[error(transparent)]
AstErr(#[from] ExpandErr),
diff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rs
index d44a89fc81..7f1bdceb7e 100644
--- a/crates/soup/src/domain/service.rs
+++ b/crates/soup/src/domain/service.rs
@@ -26,7 +26,7 @@ use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};
use filter_ast::Expr;
use foreign_entity::domain::{
models::{ForeignEntity, SourceId},
- ports::{ForeignEntityListQuery, ForeignEntityService},
+ ports::ForeignEntityListQuery,
};
use frecency::domain::{
models::{
@@ -34,6 +34,7 @@ use frecency::domain::{
},
ports::FrecencyQueryService,
};
+use github_pull_requests::domain::ports::GithubPullRequestListing;
use item_filters::ast::{
EntityFilterAst,
channel::{ChannelLiteral, ChannelThreadLiteral},
@@ -211,8 +212,8 @@ pub struct SoupImpl<T, U, V, C, K, Crm, F, Rem> {
call_record_service: K,
/// the interface for interacting with CRM (companies)
crm_service: Crm,
- /// the interface for interacting with foreign entities
- foreign_entity_service: F,
+ /// the interface for listing GitHub pull requests
+ github_pull_request_service: F,
/// the interface for interacting with reminders
reminders_service: Rem,
/// Optional captured branch facts supplied by the owning changes domain.
@@ -229,7 +230,7 @@ where
C: ChannelListService,
K: CallRecordQueryService,
Crm: CrmService,
- F: ForeignEntityService,
+ F: GithubPullRequestListing,
Rem: RemindersService,
{
/// Creates a soup service from its repository and dependent domain services.
@@ -241,7 +242,7 @@ where
comms_service: C,
call_record_service: K,
crm_service: Crm,
- foreign_entity_service: F,
+ github_pull_request_service: F,
reminders_service: Rem,
) -> Self {
SoupImpl {
@@ -251,7 +252,7 @@ where
comms_service,
call_record_service,
crm_service,
- foreign_entity_service,
+ github_pull_request_service,
reminders_service,
agent_branches: None,
favorites: None,
@@ -1300,8 +1301,8 @@ where
};
Ok(Either::Right(
- self.foreign_entity_service
- .get_foreign_entities_for_user(requesting_user, source_ids, limit, query)
+ self.github_pull_request_service
+ .list_pull_requests(requesting_user, source_ids, limit, query)
.await?
.into_iter()
.map(|entity| SoupCandidate::plain(foreign_entity_to_soup_item(entity))),
@@ -1753,7 +1754,7 @@ where
SoupOutput::Notified(page) => &mut page.items,
};
agent_metadata::enrich(
- &self.foreign_entity_service,
+ &self.github_pull_request_service,
self.agent_branches.as_deref(),
metadata_user,
metadata_source_ids,
@@ -1773,7 +1774,7 @@ where
C: ChannelListService,
K: CallRecordQueryService,
Crm: CrmService,
- F: ForeignEntityService,
+ F: GithubPullRequestListing,
Rem: RemindersService,
{
#[tracing::instrument(err, skip(self, req, team_receipt))]
diff --git a/crates/soup/src/domain/service/agent_metadata.rs b/crates/soup/src/domain/service/agent_metadata.rs
index 5dc37b140b..b1ceb4ad47 100644
--- a/crates/soup/src/domain/service/agent_metadata.rs
+++ b/crates/soup/src/domain/service/agent_metadata.rs
@@ -6,7 +6,6 @@ use agent_changes::domain::{
model::{AgentSessionId, PullRequestRef},
ports::SessionBranchReader,
};
-use github_pull_requests::domain::models::GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE;
use models_soup::agent_session::AgentPullRequestState;
use super::*;
@@ -21,8 +20,8 @@ fn pull_request_key(url: &str) -> Option<String> {
/// Enrich only returned rows, so metadata work is bounded by the page size and
/// never reads branch facts for sessions outside the caller's visible page.
-pub(super) async fn enrich<F: ForeignEntityService>(
- foreign_entities: &F,
+pub(super) async fn enrich<F: GithubPullRequestListing>(
+ pull_requests: &F,
branches: Option<&dyn SessionBranchReader>,
user: String,
sources: Vec<SourceId>,
@@ -74,18 +73,12 @@ pub(super) async fn enrich<F: ForeignEntityService>(
) else {
return Ok(Vec::new());
};
- let filter = Expr::and(
- Expr::Literal(ForeignEntityLiteral::ForeignEntitySource(
- GITHUB_PULL_REQUEST_FOREIGN_ENTITY_SOURCE.to_owned(),
- )),
- Arc::unwrap_or_clone(ids),
- );
- foreign_entities
- .get_foreign_entities_for_user(
+ pull_requests
+ .list_pull_requests(
Some(user),
sources,
keys.len() as u32,
- Query::new(None, SimpleSortMethod::UpdatedAt, Some(Arc::new(filter))),
+ Query::new(None, SimpleSortMethod::UpdatedAt, Some(ids)),
)
.await
.map_err(anyhow::Error::from)
diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rs
index e182ac50b8..4cf70db0b5 100644
--- a/crates/soup/src/domain/service/tests.rs
+++ b/crates/soup/src/domain/service/tests.rs
@@ -10,20 +10,17 @@ use chrono::Days;
use chrono::{DateTime, Utc};
use cool_asserts::assert_matches;
use email::domain::models::{EnrichedEmailThreadPreview, PreviewView};
-use entity_access::domain::models::{
- AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
-};
+use entity_access::domain::models::{AnyEntityPermission, EntityAccessReceipt, OwnerAccessLevel};
use filter_ast::Expr;
use foreign_entity::domain::{
- models::{
- CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity, SourceId,
- },
- ports::{ForeignEntityListQuery, ForeignEntityService},
+ models::{ForeignEntity, SourceId},
+ ports::ForeignEntityListQuery,
};
use frecency::domain::models::{FrecencyPageRequest, FrecencyPageResponse};
use frecency::domain::ports::MockFrecencyQueryService;
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::{domain::models::AggregateFrecency, outbound::mock::MockFrecencyStorage};
+use github_pull_requests::domain::models::GithubPullRequestError;
use item_filters::{
ChannelThreadFilters, EntityFilters, ForeignEntityFilters,
ast::{EntityFilterAst, foreign_entity::ForeignEntityLiteral},
@@ -261,93 +258,36 @@ fn call_record(
}
}
-fn foreign_entity_id_from_receipt(
- receipt: EntityAccessReceipt<ViewAccessLevel>,
-) -> Result<Uuid, ForeignEntityError> {
- let entity = receipt.entity();
- if entity.entity_type != EntityType::ForeignEntity {
- return Err(ForeignEntityError::BadRequest(format!(
- "expected ForeignEntity receipt, got {:?}",
- entity.entity_type
- )));
- }
-
- Uuid::parse_str(&entity.entity_id).map_err(|_| {
- ForeignEntityError::BadRequest("foreign entity receipt id must be a valid UUID".to_string())
- })
-}
use crm::domain::service::NoOpCrmService;
use reminders::domain::service::NoOpRemindersService;
#[derive(Clone)]
-struct NoopForeignEntityService;
-
-impl ForeignEntityService for NoopForeignEntityService {
- async fn get_foreign_entity(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- let id = foreign_entity_id_from_receipt(receipt)?;
- self.get_foreign_entity_by_id(id).await
- }
+struct NoopPullRequestListing;
- async fn get_foreign_entity_by_id(
- &self,
- id: Uuid,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- Err(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> {
- Ok(Vec::new())
- }
-
- async fn get_foreign_entities_for_user(
+impl GithubPullRequestListing for NoopPullRequestListing {
+ async fn list_pull_requests(
&self,
_requesting_user: Option<String>,
_source_ids: Vec<SourceId>,
_limit: u32,
_query: ForeignEntityListQuery,
- ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ ) -> Result<Vec<ForeignEntity>, GithubPullRequestError> {
Ok(Vec::new())
}
-
- async fn create_foreign_entity(
- &self,
- _create: CreateForeignEntity,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- unreachable!("NoopForeignEntityService does not create foreign entities")
- }
-
- async fn delete_foreign_entity(&self, _id: Uuid) -> Result<(), ForeignEntityError> {
- unreachable!("NoopForeignEntityService does not delete foreign entities")
- }
-
- async fn patch_foreign_entity(
- &self,
- _id: Uuid,
- _patch: PatchForeignEntity,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- unreachable!("NoopForeignEntityService does not patch foreign entities")
- }
}
#[derive(Clone)]
-struct RecordingForeignEntityService {
- state: Arc<RecordingForeignEntityState>,
+struct RecordingPullRequestListing {
+ state: Arc<RecordingPullRequestListingState>,
}
-struct RecordingForeignEntityState {
- calls: Mutex<Vec<RecordedForeignEntityCall>>,
+struct RecordingPullRequestListingState {
+ calls: Mutex<Vec<RecordedPullRequestListingCall>>,
entities: Vec<ForeignEntity>,
}
#[derive(Clone)]
-struct RecordedForeignEntityCall {
+struct RecordedPullRequestListingCall {
requesting_user: Option<String>,
source_ids: Vec<SourceId>,
limit: u32,
@@ -393,75 +333,36 @@ fn foreign_entity_matches_literal(entity: &ForeignEntity, literal: &ForeignEntit
}
}
-impl RecordingForeignEntityService {
+impl RecordingPullRequestListing {
fn new(entities: Vec<ForeignEntity>) -> Self {
Self {
- state: Arc::new(RecordingForeignEntityState {
+ state: Arc::new(RecordingPullRequestListingState {
calls: Mutex::new(Vec::new()),
entities,
}),
}
}
- fn calls(&self) -> Vec<RecordedForeignEntityCall> {
+ fn calls(&self) -> Vec<RecordedPullRequestListingCall> {
self.state.calls.lock().unwrap().clone()
}
}
-impl ForeignEntityService for RecordingForeignEntityService {
- async fn get_foreign_entity(
- &self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- let id = foreign_entity_id_from_receipt(receipt)?;
- self.get_foreign_entity_by_id(id).await
- }
-
- async fn get_foreign_entity_by_id(
- &self,
- id: Uuid,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- self.state
- .entities
- .iter()
- .find(|entity| entity.id == id)
- .cloned()
- .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> {
- Ok(self
- .state
- .entities
- .iter()
- .filter(|entity| entity.foreign_entity_id == foreign_entity_id)
- .filter(|entity| {
- foreign_entity_source
- .map(|source| entity.foreign_entity_source == source)
- .unwrap_or(true)
- })
- .cloned()
- .collect())
- }
-
- async fn get_foreign_entities_for_user(
+impl GithubPullRequestListing for RecordingPullRequestListing {
+ async fn list_pull_requests(
&self,
requesting_user: Option<String>,
source_ids: Vec<SourceId>,
limit: u32,
query: ForeignEntityListQuery,
- ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ ) -> Result<Vec<ForeignEntity>, GithubPullRequestError> {
let filter = query.filter().clone();
self.state
.calls
.lock()
.unwrap()
- .push(RecordedForeignEntityCall {
+ .push(RecordedPullRequestListingCall {
requesting_user,
source_ids: source_ids.clone(),
limit,
@@ -472,6 +373,7 @@ impl ForeignEntityService for RecordingForeignEntityService {
.state
.entities
.iter()
+ .filter(|entity| entity.foreign_entity_source == "github_pull_request")
.filter(|entity| {
source_ids.iter().any(|source_id| {
entity.stored_for_id.as_str() == source_id.id.as_str()
@@ -483,25 +385,6 @@ impl ForeignEntityService for RecordingForeignEntityService {
.cloned()
.collect())
}
-
- async fn create_foreign_entity(
- &self,
- _create: CreateForeignEntity,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- unreachable!("RecordingForeignEntityService does not create foreign entities")
- }
-
- async fn delete_foreign_entity(&self, _id: Uuid) -> Result<(), ForeignEntityError> {
- unreachable!("RecordingForeignEntityService does not delete foreign entities")
- }
-
- async fn patch_foreign_entity(
- &self,
- _id: Uuid,
- _patch: PatchForeignEntity,
- ) -> Result<ForeignEntity, ForeignEntityError> {
- unreachable!("RecordingForeignEntityService does not patch foreign entities")
- }
}
fn soup_document(id: &str) -> SoupDocument {
@@ -581,6 +464,18 @@ fn foreign_entity_for_source(
}
}
+fn pull_request_for_source(
+ id: Uuid,
+ stored_for_id: impl Into<String>,
+ stored_for_auth_entity: impl Into<String>,
+ updated_at: DateTime<Utc>,
+) -> ForeignEntity {
+ let mut entity =
+ foreign_entity_for_source(id, stored_for_id, stored_for_auth_entity, updated_at);
+ entity.foreign_entity_source = "github_pull_request".to_string();
+ entity
+}
+
fn channel_thread_message(
channel_id: Uuid,
thread_id: Uuid,
@@ -645,7 +540,7 @@ async fn simple_soup_includes_channel_threads() {
comms_service.clone(),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -708,7 +603,7 @@ async fn simple_soup_includes_call_records() {
NoopCommsService,
call_query_service.clone(),
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -763,7 +658,7 @@ async fn simple_soup_uses_channel_thread_filters_without_touching_channel_filter
comms_service.clone(),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -806,13 +701,20 @@ async fn simple_soup_uses_channel_thread_filters_without_touching_channel_filter
async fn simple_soup_includes_foreign_entities() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let foreign_entity_id = Uuid::from_u128(2);
- let foreign_entity_service =
- RecordingForeignEntityService::new(vec![foreign_entity_for_source(
+ let pull_request_listing = RecordingPullRequestListing::new(vec![
+ foreign_entity_for_source(
+ Uuid::from_u128(3),
+ user.as_ref(),
+ "user",
+ DateTime::default() + Days::new(3),
+ ),
+ pull_request_for_source(
foreign_entity_id,
user.as_ref(),
"user",
DateTime::default() + Days::new(2),
- )]);
+ ),
+ ]);
let mut soup_mock = MockSoupRepo::new();
soup_mock
@@ -834,7 +736,7 @@ async fn simple_soup_includes_foreign_entities() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- foreign_entity_service.clone(),
+ pull_request_listing.clone(),
NoOpRemindersService,
)
.get_user_soup(
@@ -866,7 +768,7 @@ async fn simple_soup_includes_foreign_entities() {
);
assert_matches!(&page.items[1], SoupItem::Document(_));
- let calls = foreign_entity_service.calls();
+ let calls = pull_request_listing.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].limit, 20);
assert_eq!(calls[0].source_ids, vec![SourceId::user(user.as_ref())]);
@@ -876,13 +778,12 @@ async fn simple_soup_includes_foreign_entities() {
#[tokio::test]
async fn frecency_soup_does_not_query_foreign_entities() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let foreign_entity_service =
- RecordingForeignEntityService::new(vec![foreign_entity_for_source(
- Uuid::from_u128(42),
- user.as_ref(),
- "user",
- DateTime::default(),
- )]);
+ let pull_request_listing = RecordingPullRequestListing::new(vec![pull_request_for_source(
+ Uuid::from_u128(42),
+ user.as_ref(),
+ "user",
+ DateTime::default(),
+ )]);
let mut frecency = MockFrecencyQueryService::new();
frecency
@@ -918,7 +819,7 @@ async fn frecency_soup_does_not_query_foreign_entities() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- foreign_entity_service.clone(),
+ pull_request_listing.clone(),
NoOpRemindersService,
)
.get_user_soup(
@@ -938,14 +839,14 @@ async fn frecency_soup_does_not_query_foreign_entities() {
.await
.unwrap();
- assert!(foreign_entity_service.calls().is_empty());
+ assert!(pull_request_listing.calls().is_empty());
}
#[tokio::test]
async fn team_receipt_contributes_team_foreign_entity_source_id() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
let team_id = Uuid::from_u128(100);
- let foreign_entity_service = RecordingForeignEntityService::new(Vec::new());
+ let pull_request_listing = RecordingPullRequestListing::new(Vec::new());
let mut soup_mock = MockSoupRepo::new();
soup_mock
@@ -966,7 +867,7 @@ async fn team_receipt_contributes_team_foreign_entity_source_id() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- foreign_entity_service.clone(),
+ pull_request_listing.clone(),
NoOpRemindersService,
)
.get_user_soup(
@@ -989,7 +890,7 @@ async fn team_receipt_contributes_team_foreign_entity_source_id() {
.await
.unwrap();
- let calls = foreign_entity_service.calls();
+ let calls = pull_request_listing.calls();
assert_eq!(calls.len(), 1);
assert_eq!(
calls[0].source_ids,
@@ -1028,7 +929,7 @@ async fn crm_filters_without_team_receipt_are_rejected() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- RecordingForeignEntityService::new(Vec::new()),
+ RecordingPullRequestListing::new(Vec::new()),
NoOpRemindersService,
)
.get_user_soup(
@@ -1055,13 +956,12 @@ async fn crm_filters_without_team_receipt_are_rejected() {
#[tokio::test]
async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {
let user = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
- let foreign_entity_service =
- RecordingForeignEntityService::new(vec![foreign_entity_for_source(
- Uuid::from_u128(1),
- user.as_ref(),
- "user",
- DateTime::default(),
- )]);
+ let pull_request_listing = RecordingPullRequestListing::new(vec![pull_request_for_source(
+ Uuid::from_u128(1),
+ user.as_ref(),
+ "user",
+ DateTime::default(),
+ )]);
let mut soup_mock = MockSoupRepo::new();
soup_mock
@@ -1076,7 +976,7 @@ async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- foreign_entity_service.clone(),
+ pull_request_listing.clone(),
NoOpRemindersService,
)
.get_user_soup(
@@ -1108,7 +1008,7 @@ async fn foreign_entity_filter_suppresses_non_matching_foreign_entities() {
.unwrap();
assert!(page.items.is_empty());
- assert!(foreign_entity_service.calls()[0].query.filter().is_some());
+ assert!(pull_request_listing.calls()[0].query.filter().is_some());
}
#[tokio::test]
@@ -1150,7 +1050,7 @@ async fn it_should_not_query_frecency() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -1213,7 +1113,7 @@ async fn properties_are_populated_once_after_pagination() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_properties(
@@ -1288,7 +1188,7 @@ async fn frecency_is_populated_once_after_pagination() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -1358,7 +1258,7 @@ async fn properties_and_frecency_are_composed_after_pagination() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_properties_and_frecency(
@@ -1433,7 +1333,7 @@ async fn grouped_properties_are_populated_by_the_service() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
);
let items = service
@@ -1524,7 +1424,7 @@ async fn it_should_query_frecency() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -1610,7 +1510,7 @@ async fn it_should_sort_frecency_descending() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -1710,7 +1610,7 @@ async fn frecency_should_fallback() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -1795,7 +1695,7 @@ async fn frecency_should_paginate() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -1882,7 +1782,7 @@ async fn frecency_should_resume_cursor() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -1985,7 +1885,7 @@ async fn frecency_fallback_cursor_should_resume() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_frecency(
@@ -2061,7 +1961,7 @@ async fn cursor_should_return_simple_sort() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2135,7 +2035,7 @@ async fn cursor_should_return_frecency() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2196,7 +2096,7 @@ async fn it_should_return_is_completed_true_for_completed_tasks() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2247,7 +2147,7 @@ async fn it_should_return_is_completed_false_for_incomplete_tasks() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2298,7 +2198,7 @@ async fn it_should_return_is_completed_none_for_non_tasks() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2361,7 +2261,7 @@ async fn it_should_preserve_is_completed_for_mixed_items() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2446,7 +2346,7 @@ async fn it_should_preserve_is_completed_in_by_ids_queries() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2579,7 +2479,7 @@ async fn touched_soup_orders_by_touch_and_drops_unhydrated() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_properties(
@@ -2686,7 +2586,7 @@ async fn touched_soup_projection_preserves_authoritative_attachment_facts() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_projection(
@@ -2793,7 +2693,7 @@ async fn unexpanded_touched_hydrates_projects_in_the_main_query() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -2864,7 +2764,7 @@ async fn touched_soup_full_page_builds_keyset_cursor() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -3030,7 +2930,7 @@ async fn touched_soup_hydrates_emails_with_the_unfiltered_view() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -3096,7 +2996,7 @@ async fn touched_soup_rejects_unfoldable_filters() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(
@@ -3234,7 +3134,7 @@ async fn notified_soup_refills_after_hydration_drops_and_ends_when_exhausted() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup_with_properties(notified_request(3, vec![], EntityFilters::default()), None)
@@ -3296,7 +3196,7 @@ async fn notified_soup_full_page_builds_keyset_cursor() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(notified_request(2, vec![], EntityFilters::default()), None)
@@ -3347,7 +3247,7 @@ async fn notified_soup_caps_refill_rounds_and_keeps_a_cursor() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(notified_request(1, vec![], EntityFilters::default()), None)
@@ -3432,7 +3332,7 @@ async fn notified_soup_hydrates_channels_and_emails_with_the_request_tree() {
comms_service.clone(),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(notified_request(20, vec![link], filters), None)
@@ -3511,7 +3411,7 @@ async fn notified_soup_narrows_the_reminder_leg_to_the_request_ids() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
reminders_service,
)
.get_user_soup(
@@ -3560,7 +3460,7 @@ async fn notified_soup_skips_the_reminder_leg_when_no_candidate_is_named() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
reminders_service,
)
.get_user_soup(
@@ -3597,7 +3497,7 @@ async fn notified_soup_rejects_unfoldable_calendar_filters() {
RecordingCommsService::new(vec![]),
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
)
.get_user_soup(notified_request(20, vec![], filters), None)
diff --git a/crates/soup/src/domain/service/tests/agent_metadata.rs b/crates/soup/src/domain/service/tests/agent_metadata.rs
index e59bf999a8..700e4ebd56 100644
--- a/crates/soup/src/domain/service/tests/agent_metadata.rs
+++ b/crates/soup/src/domain/service/tests/agent_metadata.rs
@@ -71,7 +71,7 @@ async fn metadata_is_batched_and_only_uses_visible_prs_and_captured_branches() {
)]),
..Default::default()
};
- let foreign = RecordingForeignEntityService::new(vec![
+ let foreign = RecordingPullRequestListing::new(vec![
pull_request("1", user, "merged"),
pull_request("2", "macro|[email protected]", "closed"),
pull_request("3", user, "unknown"),
@@ -131,7 +131,7 @@ async fn metadata_is_batched_and_only_uses_visible_prs_and_captured_branches() {
#[tokio::test]
async fn no_pr_links_skip_foreign_entity_lookup() {
let branches = Branches::default();
- let foreign = RecordingForeignEntityService::new(Vec::new());
+ let foreign = RecordingPullRequestListing::new(Vec::new());
let mut items = vec![agent(AgentSessionId::new(), None)];
super::super::agent_metadata::enrich(
&foreign,
@@ -159,7 +159,7 @@ async fn runtime_branch_without_pr_survives_enrichment_and_takes_precedence() {
)]),
..Default::default()
};
- let foreign = RecordingForeignEntityService::new(Vec::new());
+ let foreign = RecordingPullRequestListing::new(Vec::new());
let mut item = agent(session, None);
let SoupItem::AgentSession(row) = &mut item.item else {
unreachable!()
@@ -198,7 +198,7 @@ async fn changed_or_missing_repository_does_not_restore_an_old_captured_branch()
)]),
..Default::default()
};
- let foreign = RecordingForeignEntityService::new(Vec::new());
+ let foreign = RecordingPullRequestListing::new(Vec::new());
let mut item = agent(session, None);
let SoupItem::AgentSession(row) = &mut item.item else {
unreachable!()
diff --git a/crates/soup/src/domain/service/tests/exclusions.rs b/crates/soup/src/domain/service/tests/exclusions.rs
index 2acf7023fc..eef1f3c3fa 100644
--- a/crates/soup/src/domain/service/tests/exclusions.rs
+++ b/crates/soup/src/domain/service/tests/exclusions.rs
@@ -16,7 +16,7 @@ async fn document_only_soup_never_calls_excluded_entity_services() {
let emails = RecordingEmailPreviewService::default();
let channels = RecordingCommsService::new(Vec::new());
let calls = RecordingCallRecordQueryService::new(Vec::new());
- let foreign_entities = RecordingForeignEntityService::new(Vec::new());
+ let foreign_entities = RecordingPullRequestListing::new(Vec::new());
let mut soup = MockSoupRepo::new();
soup.expect_unexpanded_generic_cursor_soup()
.times(1)
diff --git a/crates/soup/src/domain/service/tests/favorites.rs b/crates/soup/src/domain/service/tests/favorites.rs
index 78449f4cf3..208d06ceaa 100644
--- a/crates/soup/src/domain/service/tests/favorites.rs
+++ b/crates/soup/src/domain/service/tests/favorites.rs
@@ -51,7 +51,7 @@ async fn favorites_are_scoped_before_pagination_and_cursor_keeps_the_filter() {
NoopCommsService,
NoopCallRecordQueryService,
NoOpCrmService,
- NoopForeignEntityService,
+ NoopPullRequestListing,
NoOpRemindersService,
);
service.favorites = Some(Arc::new(ViewerFavorites));
diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.toml
index 2b72275dec..07e8be8f2c 100644
--- a/services/document_cognition_service/Cargo.toml
+++ b/services/document_cognition_service/Cargo.toml
@@ -68,6 +68,7 @@ entity_access_management = { path = "../../crates/entity_access_management" }
entity_registry = { path = "../../crates/entity_registry/entity_registry" }
entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }
foreign_entity = { path = "../../crates/foreign_entity" }
+github_pull_requests = { path = "../../crates/github_pull_requests" }
frecency = { path = "../../crates/frecency", features = ["outbound", "postgres"] }
futures = { workspace = true }
http = { workspace = true }
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index cd399a8da9..5f39da92ce 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -183,6 +183,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
+ use github_pull_requests::{
+ domain::service::GithubPullRequestServiceImpl,
+ outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
+ };
use lexical_client::LexicalClient;
use notification::domain::service::{
NotificationReaderService, PlatformArnConfig, SqsNotificationIngress,
@@ -242,8 +246,10 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
frecency_storage,
);
let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
- let foreign_entity_service =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone()));
+ let github_pull_request_service = GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(pool.clone())),
+ PgGithubPullRequestRepo::new(pool.clone()),
+ );
let soup_service = Arc::new(SoupImpl::new(
PgSoupRepo::new(readonly_pool::ReadOnlyPool(pool.clone())),
frecency_service,
@@ -253,7 +259,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
call::outbound::pg_call_repo::PgCallRepo::new(pool.clone()),
),
crm::domain::service::NoOpCrmService,
- foreign_entity_service,
+ github_pull_request_service,
reminders::domain::service::NoOpRemindersService,
));
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 13f127c807..39fd7cbf46 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -30,6 +30,10 @@ use foreign_entity::{
};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
+use github_pull_requests::{
+ domain::service::GithubPullRequestServiceImpl,
+ outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_authorization::{
InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
@@ -253,8 +257,10 @@ async fn main() -> anyhow::Result<()> {
frecency_storage,
);
let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
- let foreign_entity_service =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));
+ let github_pull_request_service = GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
+ PgGithubPullRequestRepo::new(db.clone()),
+ );
let soup_service = Arc::new(soup::domain::service::SoupImpl::new(
soup::outbound::pg_soup_repo::PgSoupRepo::new(ReadOnlyPool(db.clone())),
frecency_service,
@@ -262,7 +268,7 @@ async fn main() -> anyhow::Result<()> {
channels_service,
CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
crm::domain::service::NoOpCrmService,
- foreign_entity_service,
+ github_pull_request_service,
reminders::domain::service::NoOpRemindersService,
));
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 9ac9dcb700..c585476c5e 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -191,7 +191,7 @@ pub(crate) type DssSoupService = SoupImpl<
ChannelListServiceImpl<PgChannelsRepo, PgChannelsRepo, FrecencyPgStorage>,
call::domain::service::CallRecordQueryServiceImpl<call::outbound::pg_call_repo::PgCallRepo>,
DssCrmService,
- ForeignEntityServiceType,
+ GithubPullRequestServiceType,
RemindersServiceType,
>;
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 06cfde2111..eab63e71d4 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -1429,7 +1429,10 @@ async fn run() -> anyhow::Result<()> {
),
call::domain::service::CallRecordQueryServiceImpl::new(PgCallRepo::new(db.clone())),
crm_service.clone(),
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
+ GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
+ PgGithubPullRequestRepo::new(db.clone()),
+ ),
reminders_service.clone(),
)
.with_agent_branches(agent_changes::outbound::postgres::PgChangesetRepo::new(
@@ -1457,7 +1460,10 @@ async fn run() -> anyhow::Result<()> {
readonly_db.clone(),
)),
crm_service.clone(),
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(readonly_db.clone())),
+ GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(readonly_db.clone())),
+ PgGithubPullRequestRepo::new(readonly_db.clone()),
+ ),
reminders_service.clone(),
)
.with_favorites(favorites_service.clone())
diff --git a/services/mcp_service/Cargo.toml b/services/mcp_service/Cargo.toml
index 07f74497b8..b887d396a4 100644
--- a/services/mcp_service/Cargo.toml
+++ b/services/mcp_service/Cargo.toml
@@ -53,6 +53,7 @@ frecency = { path = "../../crates/frecency", features = [
] }
fusionauth = { path = "../../crates/fusionauth" }
futures = { workspace = true }
+github_pull_requests = { path = "../../crates/github_pull_requests" }
http = { workspace = true }
lexical_client = { path = "../../crates/lexical_client" }
macro_auth = { path = "../../crates/macro_auth" }
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index 327d3ec873..25ac659122 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -30,6 +30,10 @@ use foreign_entity::{
};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
+use github_pull_requests::{
+ domain::service::GithubPullRequestServiceImpl,
+ outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_service_urls::{
AiEditingWorkerUrl, CalendarServiceUrl, ConnectionGatewayUrl, DocumentStorageServiceUrl,
@@ -191,8 +195,10 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
frecency_storage,
);
let email_service_for_tools: Arc<ai_tools::ToolEmailService> = Arc::new(email_service.clone());
- let foreign_entity_service =
- ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone()));
+ let github_pull_request_service = GithubPullRequestServiceImpl::new(
+ ForeignEntityServiceImpl::new(PgForeignEntityRepo::new(db.clone())),
+ PgGithubPullRequestRepo::new(db.clone()),
+ );
let soup_service = Arc::new(SoupImpl::new(
PgSoupRepo::new(readonly_pool::ReadOnlyPool(db.clone())),
frecency_service,
@@ -202,7 +208,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
call::outbound::pg_call_repo::PgCallRepo::new(db.clone()),
),
crm::domain::service::NoOpCrmService,
- foreign_entity_service,
+ github_pull_request_service,
reminders::domain::service::NoOpRemindersService,
));