Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): allow non-teams to use sync (#3566)
Will Hutchinson809542c27a70
diff --git a/rust/cloud-storage/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.json b/rust/cloud-storage/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.jsonnew file mode 100644index 0000000000..05a17cf734--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT DISTINCT tt.document_id\n FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)\n JOIN github_app_installation gai\n ON gai.id = $1\n AND gai.source_type = 'team'::github_app_installation_source_type\n JOIN team t\n ON t.id = gai.source_id::uuid\n AND LOWER(t.slug) = LOWER(refs.team_slug)\n JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "Int4Array"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "2d689689caf98fbfbb437fe34129b37a1ece02e7c4189d0619ea741f74f05bdf"+}diff --git a/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.json b/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.jsondeleted file mode 100644index d816a21685..0000000000--- a/rust/cloud-storage/.sqlx/query-69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4.json+++ /dev/null@@ -1,24 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT DISTINCT tt.document_id\n FROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)\n JOIN github_app_installation_team gait ON gait.id = $1\n JOIN team t ON t.id = gait.team_id AND LOWER(t.slug) = LOWER(refs.team_slug)\n JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "document_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Text",- "TextArray",- "Int4Array"- ]- },- "nullable": [- false- ]- },- "hash": "69eb6f834b928cea392026149a61b09f53c38f7ef7f43720f16d7ecf98bfe0f4"-}diff --git a/rust/cloud-storage/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.json b/rust/cloud-storage/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.jsondeleted file mode 100644index 88be9c45d5..0000000000--- a/rust/cloud-storage/.sqlx/query-6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n INSERT INTO github_app_installation_team (id, team_id, installed_by)\n SELECT * FROM UNNEST($1::text[], $2::uuid[], $3::text[])\n ON CONFLICT (id, team_id) DO NOTHING\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "TextArray",- "UuidArray",- "TextArray"- ]- },- "nullable": []- },- "hash": "6a83d04482526e2ceb9e9eb812d3ceaf1c8c7fafb25ba1cbecb4dadc543fad67"-}diff --git a/rust/cloud-storage/.sqlx/query-6e98cffdfa6200686281b3c2c540f07f517dca38e8a70bad08b4b655cb1cd550.json b/rust/cloud-storage/.sqlx/query-6e98cffdfa6200686281b3c2c540f07f517dca38e8a70bad08b4b655cb1cd550.jsonnew file mode 100644index 0000000000..b666e9c736--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-6e98cffdfa6200686281b3c2c540f07f517dca38e8a70bad08b4b655cb1cd550.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO github_app_installation (id, source_id, source_type)\n SELECT $1::text, source_id, source_type::github_app_installation_source_type\n FROM UNNEST($2::text[], $3::text[])\n AS source_rows(source_id, source_type)\n ON CONFLICT (id, source_id, source_type) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "6e98cffdfa6200686281b3c2c540f07f517dca38e8a70bad08b4b655cb1cd550"+}diff --git a/rust/cloud-storage/github/fixtures/github_installation_test_data.sql b/rust/cloud-storage/github/fixtures/github_installation_test_data.sqlindex 9e669bb4ce..0e229d6cff 100644--- a/rust/cloud-storage/github/fixtures/github_installation_test_data.sql+++ b/rust/cloud-storage/github/fixtures/github_installation_test_data.sql@@ -2,18 +2,21 @@ INSERT INTOpublic.macro_user (id, username, email, stripe_customer_id)VALUES('bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '[email protected]', 'cus_test'),- ('cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid, 'testuser2', '[email protected]', 'cus_test2');+ ('cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid, 'testuser2', '[email protected]', 'cus_test2'),+ ('ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid, 'solo', '[email protected]', 'cus_test3');INSERT INTOpublic."User" (id, email, macro_user_id)VALUES('macro|[email protected]', '[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid),- ('macro|[email protected]', '[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid);+ ('macro|[email protected]', '[email protected]', 'cccccccc-cccc-cccc-cccc-cccccccccccc'::uuid),+ ('macro|[email protected]', '[email protected]', 'ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid);INSERT INTOpublic.github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)VALUES- ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid, 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '12345');+ ('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa'::uuid, 'macro|[email protected]', 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb'::uuid, 'testuser', '12345'),+ ('99999999-9999-9999-9999-999999999999'::uuid, 'macro|[email protected]', 'ffffffff-ffff-ffff-ffff-ffffffffffff'::uuid, 'solo', '67890');INSERT INTOpublic.team (id, name, owner_id)diff --git a/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql b/rust/cloud-storage/github/fixtures/github_team_task_test_data.sqlindex d7eb6b7fc5..70447b6566 100644--- a/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql+++ b/rust/cloud-storage/github/fixtures/github_team_task_test_data.sql@@ -41,7 +41,7 @@ VALUES('eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, '11111111-1111-1111-1111-111111111111', 7);INSERT INTO- public.github_app_installation_team (id, team_id, installed_by)+ public.github_app_installation (id, source_id, source_type)VALUES- ('12345', 'dddddddd-dddd-dddd-dddd-dddddddddddd'::uuid, 'macro|[email protected]'),- ('12345', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee'::uuid, 'macro|[email protected]');+ ('12345', 'dddddddd-dddd-dddd-dddd-dddddddddddd', 'team'::github_app_installation_source_type),+ ('12345', 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee', 'team'::github_app_installation_source_type);diff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rsindex b1f125c560..87993d198d 100644--- a/rust/cloud-storage/github/src/domain/models/mod.rs+++ b/rust/cloud-storage/github/src/domain/models/mod.rs@@ -14,8 +14,8 @@ pub use pull_request::{GithubPullRequestStatus,};pub use sync::{- GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,- TeamTaskReference, ValidatedGithubWebhookEvent,+ GithubAppInstallationSource, GithubInstallationAccessToken, GithubKey, GithubWebhookEventType,+ MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent,};/// Errors that can occur during github operations.#[derive(Debug, thiserror::Error)]diff --git a/rust/cloud-storage/github/src/domain/models/sync.rs b/rust/cloud-storage/github/src/domain/models/sync.rsindex 22ec938665..ac4ae17b49 100644--- a/rust/cloud-storage/github/src/domain/models/sync.rs+++ b/rust/cloud-storage/github/src/domain/models/sync.rs@@ -39,6 +39,33 @@ pub struct GithubInstallationAccessToken {pub expires_at: String,}+/// Source that grants a GitHub App installation access to Macro sync data.+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum GithubAppInstallationSource {+ /// A Macro team source.+ Team(uuid::Uuid),+ /// A Macro user source.+ User(String),+}++impl GithubAppInstallationSource {+ /// Returns the value persisted in `github_app_installation.source_id`.+ pub fn source_id(&self) -> String {+ match self {+ Self::Team(team_id) => team_id.to_string(),+ Self::User(user_id) => user_id.clone(),+ }+ }++ /// Returns the value persisted in `github_app_installation.source_type`.+ pub fn source_type(&self) -> &'static str {+ match self {+ Self::Team(_) => "team",+ Self::User(_) => "user",+ }+ }+}+/// A validated github webhook event#[derive(Debug)]pub struct ValidatedGithubWebhookEvent {diff --git a/rust/cloud-storage/github/src/domain/ports/sync.rs b/rust/cloud-storage/github/src/domain/ports/sync.rsindex 66aa214895..90a586461c 100644--- a/rust/cloud-storage/github/src/domain/ports/sync.rs+++ b/rust/cloud-storage/github/src/domain/ports/sync.rs@@ -3,8 +3,8 @@use std::future::Future;use crate::domain::models::{- GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, TeamTaskReference,- ValidatedGithubWebhookEvent,+ GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,+ MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent,};/// Repository for accessing github sync data from the database.@@ -39,9 +39,9 @@ pub trait GithubSyncRepo: Send + Sync + 'static {/// Resolves team-scoped task references for a GitHub App installation.///- /// Implementations should use the installation's teams (via- /// `github_app_installation_team`) and the referenced team slug/task number- /// to find the backing Macro task document.+ /// Implementations should use the installation's team sources from+ /// `github_app_installation` (`source_type = 'team'`) and the referenced+ /// team slug/task number to find the backing Macro task document.fn resolve_team_task_references(&self,installation_id: &str,@@ -61,13 +61,12 @@ pub trait GithubSyncRepo: Send + Sync + 'static {macro_id: &str,) -> impl Future<Output = Result<Vec<uuid::Uuid>, Self::Err>> + Send;- /// Inserts associations between a GitHub App installation and the given teams.+ /// Upserts associations between a GitHub App installation and its sources./// Ignores conflicts (idempotent).- fn insert_installation_team_associations(+ fn upsert_installation_sources(&self,installation_id: &str,- team_ids: &[uuid::Uuid],- installed_by: &str,+ sources: &[GithubAppInstallationSource],) -> impl Future<Output = Result<(), Self::Err>> + Send;}diff --git a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rsindex 89b5e4b92e..02a9be95ce 100644--- a/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/handle_installation.rs@@ -1,7 +1,7 @@//! Installation event handlers.use crate::domain::{- models::{GithubError, ValidatedGithubWebhookEvent},+ models::{GithubAppInstallationSource, GithubError, ValidatedGithubWebhookEvent},ports::{GithubSyncClient, GithubSyncRepo},};use documents::domain::ports::DocumentService;@@ -11,7 +11,7 @@ use super::GithubSyncServiceImpl;impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiceImpl<D, R, C> {/// Handle `installation` events with action `created`.///- /// Associates the GitHub App installation with all teams the installer belongs to.+ /// Associates the GitHub App installation with the installer's team or user source.#[tracing::instrument(skip(self, event), err)]pub(crate) async fn handle_installation_created(&self,@@ -39,7 +39,7 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServiNone => {tracing::warn!(installation_id,- "no github link found for sender, cannot associate installation with teams"+ "no github link found for sender, cannot associate installation with a source");return Ok(());}@@ -51,22 +51,26 @@ impl<D: DocumentService, R: GithubSyncRepo, C: GithubSyncClient> GithubSyncServi.await.map_err(|e| GithubError::Internal(e.into()))?;- if team_ids.is_empty() {+ let sources = if team_ids.is_empty() {tracing::info!(installation_id,- "user has no teams, skipping installation association"+ "user has no teams, associating installation with user source");- return Ok(());- }-- tracing::info!(- installation_id,- team_count = team_ids.len(),- "associating installation with user teams"- );+ vec![GithubAppInstallationSource::User(macro_id)]+ } else {+ tracing::info!(+ installation_id,+ team_count = team_ids.len(),+ "associating installation with user teams"+ );+ team_ids+ .into_iter()+ .map(GithubAppInstallationSource::Team)+ .collect()+ };self.repo- .insert_installation_team_associations(&installation_id_str, &team_ids, ¯o_id)+ .upsert_installation_sources(&installation_id_str, &sources).await.map_err(|e| GithubError::Internal(e.into()))?;diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex d72e8d4a2b..786b19f61e 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -3,8 +3,8 @@ use std::sync::{Arc, Mutex};use crate::domain::{models::{- GithubError, GithubInstallationAccessToken, GithubKey, MacroTaskId, TeamTaskReference,- ValidatedGithubWebhookEvent,+ GithubAppInstallationSource, GithubError, GithubInstallationAccessToken, GithubKey,+ MacroTaskId, TeamTaskReference, ValidatedGithubWebhookEvent,},ports::{GithubSyncClient, GithubSyncRepo, GithubSyncService},};@@ -256,8 +256,8 @@ struct StubSyncRepo {github_links: Mutex<HashMap<String, String>>,/// Maps macro_id -> team_ids for installation event lookups.user_teams: Mutex<HashMap<String, Vec<uuid::Uuid>>>,- /// Recorded installation-team association inserts: (installation_id, team_ids, installed_by).- installation_associations: Mutex<Vec<(String, Vec<uuid::Uuid>, String)>>,+ /// Recorded installation source upserts: (installation_id, sources).+ installation_sources: Mutex<Vec<(String, Vec<GithubAppInstallationSource>)>>,}impl StubSyncRepo {@@ -267,7 +267,7 @@ impl StubSyncRepo {team_task_references: Mutex::new(HashMap::new()),github_links: Mutex::new(HashMap::new()),user_teams: Mutex::new(HashMap::new()),- installation_associations: Mutex::new(Vec::new()),+ installation_sources: Mutex::new(Vec::new()),}}@@ -305,8 +305,8 @@ impl StubSyncRepo {self}- fn installation_associations(&self) -> Vec<(String, Vec<uuid::Uuid>, String)> {- self.installation_associations.lock().unwrap().clone()+ fn installation_sources(&self) -> Vec<(String, Vec<GithubAppInstallationSource>)> {+ self.installation_sources.lock().unwrap().clone()}}@@ -404,17 +404,15 @@ impl GithubSyncRepo for StubSyncRepo {.unwrap_or_default())}- async fn insert_installation_team_associations(+ async fn upsert_installation_sources(&self,installation_id: &str,- team_ids: &[uuid::Uuid],- installed_by: &str,+ sources: &[GithubAppInstallationSource],) -> Result<(), Self::Err> {- self.installation_associations.lock().unwrap().push((- installation_id.to_string(),- team_ids.to_vec(),- installed_by.to_string(),- ));+ self.installation_sources+ .lock()+ .unwrap()+ .push((installation_id.to_string(), sources.to_vec()));Ok(())}}@@ -1461,13 +1459,17 @@ async fn installation_created_associates_teams() {service.process_webhook_event(&event).await.unwrap();- let associations = service.repo.installation_associations();- assert_eq!(associations.len(), 1);- assert_eq!(associations[0].0, "99999");- assert_eq!(associations[0].1.len(), 2);- assert!(associations[0].1.contains(&team_a));- assert!(associations[0].1.contains(&team_b));- assert_eq!(associations[0].2, "macro|[email protected]");+ let sources = service.repo.installation_sources();+ assert_eq!(+ sources,+ vec![(+ "99999".to_string(),+ vec![+ GithubAppInstallationSource::Team(team_a),+ GithubAppInstallationSource::Team(team_b),+ ],+ )]+ );}#[tokio::test]@@ -1478,11 +1480,11 @@ async fn installation_created_no_github_link() {// No github link for sender — should succeed without inserting anythingservice.process_webhook_event(&event).await.unwrap();- assert!(service.repo.installation_associations().is_empty());+ assert!(service.repo.installation_sources().is_empty());}#[tokio::test]-async fn installation_created_no_teams() {+async fn installation_created_no_teams_associates_user() {let repo = StubSyncRepo::new().with_github_link("12345", "macro|[email protected]");// user_teams is empty by default@@ -1491,8 +1493,16 @@ async fn installation_created_no_teams() {service.process_webhook_event(&event).await.unwrap();- let associations = service.repo.installation_associations();- assert!(associations.is_empty());+ let sources = service.repo.installation_sources();+ assert_eq!(+ sources,+ vec![(+ "11111".to_string(),+ vec![GithubAppInstallationSource::User(+ "macro|[email protected]".to_string(),+ )],+ )]+ );}#[tokio::test]@@ -1510,5 +1520,5 @@ async fn installation_deleted_is_skipped() {// Should not error — just skipsservice.process_webhook_event(&event).await.unwrap();- assert!(service.repo.installation_associations().is_empty());+ assert!(service.repo.installation_sources().is_empty());}diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rsindex 6f207c8617..4056429729 100644--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo.rs@@ -8,7 +8,7 @@ use std::collections::HashSet;use sqlx::PgPool;use crate::domain::{- models::{GithubKey, MacroTaskId, TeamTaskReference},+ models::{GithubAppInstallationSource, GithubKey, MacroTaskId, TeamTaskReference},ports::GithubSyncRepo,};@@ -124,8 +124,12 @@ impl GithubSyncRepo for PgGithubSyncRepo {r#"SELECT DISTINCT tt.document_idFROM UNNEST($2::text[], $3::int4[]) AS refs(team_slug, task_num)- JOIN github_app_installation_team gait ON gait.id = $1- JOIN team t ON t.id = gait.team_id AND LOWER(t.slug) = LOWER(refs.team_slug)+ JOIN github_app_installation gai+ ON gai.id = $1+ AND gai.source_type = 'team'::github_app_installation_source_type+ JOIN team t+ ON t.id = gai.source_id::uuid+ AND LOWER(t.slug) = LOWER(refs.team_slug)JOIN team_task tt ON tt.team_id = t.id AND tt.task_num = refs.task_num"#,installation_id,@@ -190,25 +194,25 @@ impl GithubSyncRepo for PgGithubSyncRepo {}#[tracing::instrument(skip(self), err)]- async fn insert_installation_team_associations(+ async fn upsert_installation_sources(&self,installation_id: &str,- team_ids: &[uuid::Uuid],- installed_by: &str,+ sources: &[GithubAppInstallationSource],) -> Result<(), Self::Err> {- let installation_ids: Vec<&str> =- std::iter::repeat_n(installation_id, team_ids.len()).collect();- let installed_bys: Vec<&str> = std::iter::repeat_n(installed_by, team_ids.len()).collect();+ let source_ids: Vec<String> = sources.iter().map(|source| source.source_id()).collect();+ let source_types: Vec<&str> = sources.iter().map(|source| source.source_type()).collect();sqlx::query!(r#"- INSERT INTO github_app_installation_team (id, team_id, installed_by)- SELECT * FROM UNNEST($1::text[], $2::uuid[], $3::text[])- ON CONFLICT (id, team_id) DO NOTHING+ INSERT INTO github_app_installation (id, source_id, source_type)+ SELECT $1::text, source_id, source_type::github_app_installation_source_type+ FROM UNNEST($2::text[], $3::text[])+ AS source_rows(source_id, source_type)+ ON CONFLICT (id, source_id, source_type) DO NOTHING"#,- &installation_ids as &[&str],- team_ids,- &installed_bys as &[&str],+ installation_id,+ &source_ids,+ &source_types as &[&str],).execute(&self.pool).await?;diff --git a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rsindex 29381c60b6..d39996670e 100644--- a/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs+++ b/rust/cloud-storage/github/src/outbound/pg_github_sync_repo/test.rs@@ -2,7 +2,9 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::{Pool, Postgres};use uuid::Uuid;-use crate::domain::models::{GithubKey, MacroTaskId};+use crate::domain::models::{+ GithubAppInstallationSource, GithubKey, MacroTaskId, TeamTaskReference,+};use crate::domain::ports::GithubSyncRepo;use crate::outbound::pg_github_sync_repo::PgGithubSyncRepo;@@ -182,8 +184,8 @@ async fn test_resolve_team_task_references(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);let refs = vec![- crate::domain::models::TeamTaskReference::new("eng", 123).unwrap(),- crate::domain::models::TeamTaskReference::new("platform_api", 7).unwrap(),+ TeamTaskReference::new("eng", 123).unwrap(),+ TeamTaskReference::new("platform_api", 7).unwrap(),];let task_ids = repo@@ -205,9 +207,9 @@ async fn test_resolve_team_task_references(pool: Pool<Postgres>) {migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_team_task_test_data")))]-async fn test_resolve_team_task_references_requires_installation_team(pool: Pool<Postgres>) {+async fn test_resolve_team_task_references_requires_team_source(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);- let refs = vec![crate::domain::models::TeamTaskReference::new("eng", 123).unwrap()];+ let refs = vec![TeamTaskReference::new("eng", 123).unwrap()];let task_ids = repo.resolve_team_task_references("99999", &refs)@@ -217,6 +219,34 @@ async fn test_resolve_team_task_references_requires_installation_team(pool: Poolassert!(task_ids.is_empty());}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_team_task_test_data"))+)]+async fn test_resolve_team_task_references_ignores_user_source(pool: Pool<Postgres>) {+ sqlx::query(+ r#"+ INSERT INTO github_app_installation (id, source_id, source_type)+ VALUES ($1, $2, 'user'::github_app_installation_source_type)+ "#,+ )+ .bind("user-installation")+ .bind("dddddddd-dddd-dddd-dddd-dddddddddddd")+ .execute(&pool)+ .await+ .unwrap();++ let repo = PgGithubSyncRepo::new(pool);+ let refs = vec![TeamTaskReference::new("eng", 123).unwrap()];++ let task_ids = repo+ .resolve_team_task_references("user-installation", &refs)+ .await+ .unwrap();++ assert!(task_ids.is_empty());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_sync_test_data"))@@ -292,70 +322,131 @@ async fn test_get_user_team_ids(pool: Pool<Postgres>) {);}-#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))+)]async fn test_get_user_team_ids_no_teams(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool);- let team_ids = repo- .get_user_team_ids("macro|[email protected]")- .await- .unwrap();+ let team_ids = repo.get_user_team_ids("macro|[email protected]").await.unwrap();assert!(team_ids.is_empty());}// ----------------------------------------------------------------------------// insert_installation_team_associations+// upsert_installation_sources// ---------------------------------------------------------------------------+async fn get_installation_sources(+ pool: &Pool<Postgres>,+ installation_id: &str,+) -> Vec<(String, String, String)> {+ sqlx::query_as(+ r#"+ SELECT id, source_id, source_type::text+ FROM github_app_installation+ WHERE id = $1+ ORDER BY source_type, source_id+ "#,+ )+ .bind(installation_id)+ .fetch_all(pool)+ .await+ .unwrap()+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_installation_test_data")))]-async fn test_insert_installation_team_associations(pool: Pool<Postgres>) {+async fn test_upsert_installation_sources_inserts_team_sources(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool.clone());- let team_ids: Vec<Uuid> = vec![- "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),- "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap(),+ let sources = vec![+ GithubAppInstallationSource::Team("dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap()),+ GithubAppInstallationSource::Team("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".parse().unwrap()),];- repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")+ repo.upsert_installation_sources("123456", &sources).await.unwrap();- let rows: Vec<(String, Uuid)> =- sqlx::query_as("SELECT id, team_id FROM github_app_installation_team ORDER BY team_id")- .fetch_all(&pool)- .await- .unwrap();+ let rows = get_installation_sources(&pool, "123456").await;- assert_eq!(rows.len(), 2);- assert!(rows.iter().all(|r| r.0 == "123456"));+ assert_eq!(+ rows,+ vec![+ (+ "123456".to_string(),+ "dddddddd-dddd-dddd-dddd-dddddddddddd".to_string(),+ "team".to_string(),+ ),+ (+ "123456".to_string(),+ "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee".to_string(),+ "team".to_string(),+ ),+ ]+ );}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "../../../fixtures", scripts("github_installation_test_data")))]-async fn test_insert_installation_team_associations_idempotent(pool: Pool<Postgres>) {+async fn test_upsert_installation_sources_idempotent_team_source(pool: Pool<Postgres>) {let repo = PgGithubSyncRepo::new(pool.clone());- let team_ids: Vec<Uuid> = vec!["dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap()];+ let sources = vec![GithubAppInstallationSource::Team(+ "dddddddd-dddd-dddd-dddd-dddddddddddd".parse().unwrap(),+ )];- repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")+ repo.upsert_installation_sources("123456", &sources).await.unwrap();- // Insert again — should not error- repo.insert_installation_team_associations("123456", &team_ids, "macro|[email protected]")+ repo.upsert_installation_sources("123456", &sources).await.unwrap();- let count: (i64,) =- sqlx::query_as("SELECT COUNT(*) FROM github_app_installation_team WHERE id = '123456'")- .fetch_one(&pool)- .await- .unwrap();+ let rows = get_installation_sources(&pool, "123456").await;++ assert_eq!(+ rows,+ vec![(+ "123456".to_string(),+ "dddddddd-dddd-dddd-dddd-dddddddddddd".to_string(),+ "team".to_string(),+ )]+ );+}- assert_eq!(count.0, 1);+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("github_installation_test_data"))+)]+async fn test_upsert_installation_sources_idempotent_user_source(pool: Pool<Postgres>) {+ let repo = PgGithubSyncRepo::new(pool.clone());++ let sources = vec![GithubAppInstallationSource::User(+ "macro|[email protected]".to_string(),+ )];++ repo.upsert_installation_sources("654321", &sources)+ .await+ .unwrap();+ repo.upsert_installation_sources("654321", &sources)+ .await+ .unwrap();++ let rows = get_installation_sources(&pool, "654321").await;++ assert_eq!(+ rows,+ vec![(+ "654321".to_string(),+ "macro|[email protected]".to_string(),+ "user".to_string(),+ )]+ );}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260527141944_github_app_installation_sources.sql b/rust/cloud-storage/macro_db_client/migrations/20260527141944_github_app_installation_sources.sqlnew file mode 100644index 0000000000..0b2ce08279--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260527141944_github_app_installation_sources.sql@@ -0,0 +1,24 @@+CREATE TYPE github_app_installation_source_type AS ENUM ('team', 'user');++CREATE TABLE github_app_installation+(+ id TEXT NOT NULL, -- The github installation id converted to a string+ source_id TEXT NOT NULL, -- A team id or user id, depending on source_type+ source_type github_app_installation_source_type NOT NULL,+ PRIMARY KEY (id, source_id, source_type)+);++CREATE INDEX "github_app_installation_id_source_type_idx"+ ON github_app_installation (id, source_type);++CREATE INDEX "github_app_installation_source_type_source_id_idx"+ ON github_app_installation (source_type, source_id);++INSERT INTO github_app_installation (id, source_id, source_type)+SELECT id,+ team_id::TEXT,+ 'team'::github_app_installation_source_type+FROM github_app_installation_team+ON CONFLICT DO NOTHING;++DROP TABLE github_app_installation_team;