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.

fix(crm): resolve user's own inbox by email for CRM backfill (#4782)

Evan Hutnikae6f04e8fa83
diff --git a/.sqlx/query-286734198c1d9f78365847be644b9172a73b4d0a9c2f95dd053dc948647fc2ff.json b/.sqlx/query-286734198c1d9f78365847be644b9172a73b4d0a9c2f95dd053dc948647fc2ff.json
new file mode 100644
index 0000000000..ef52482d80
--- /dev/null
+++ b/.sqlx/query-286734198c1d9f78365847be644b9172a73b4d0a9c2f95dd053dc948647fc2ff.json
@@ -0,0 +1,92 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, macro_id, fusionauth_user_id, email_address, provider as \"provider: _\",\n is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at\n FROM email_links\n WHERE macro_id = $1 AND LOWER(email_address) = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "macro_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "fusionauth_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "email_address",
+ "type_info": "Varchar"
+ },
+ {
+ "ordinal": 4,
+ "name": "provider: _",
+ "type_info": {
+ "Custom": {
+ "name": "email_user_provider_enum",
+ "kind": {
+ "Enum": [
+ "GMAIL"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 5,
+ "name": "is_sync_active",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 6,
+ "name": "is_primary",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 7,
+ "name": "needs_reauth",
+ "type_info": "Bool"
+ },
+ {
+ "ordinal": 8,
+ "name": "last_sync_error_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 9,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 10,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "286734198c1d9f78365847be644b9172a73b4d0a9c2f95dd053dc948647fc2ff"
+}
diff --git a/crates/email_db_client/src/links/get.rs b/crates/email_db_client/src/links/get.rs
index ce16884d56..85b9ab37d6 100644
--- a/crates/email_db_client/src/links/get.rs
+++ b/crates/email_db_client/src/links/get.rs
@@ -67,6 +67,47 @@ pub async fn fetch_link_by_macro_id(
Ok(db_link.map(service::link::Link::try_from).transpose()?)
}
+/// Fetches the link for a `macro_id` whose `email_address` matches the given
+/// address. Used by the CRM backfill/teardown path, where the address is
+/// derived from the macro_id itself (`macro|<email>`) — this resolves the
+/// inbox that *is* the user rather than the most-recently-connected one that
+/// [`fetch_link_by_macro_id`] would return. The comparison is
+/// case-insensitive: the macro_id email part is always lowercased, but
+/// `email_address` preserves its original casing.
+#[tracing::instrument(skip(pool), err)]
+pub async fn fetch_link_by_macro_id_and_email_address(
+ pool: &PgPool,
+ macro_id: &str,
+ email_address: &str,
+) -> anyhow::Result<Option<link::Link>> {
+ if macro_id.is_empty() {
+ anyhow::bail!("Macro ID cannot be empty");
+ }
+ if email_address.is_empty() {
+ anyhow::bail!("Email address cannot be empty");
+ }
+
+ let email_address = email_address.to_lowercase();
+
+ let db_link = sqlx::query_as!(
+ DbLink,
+ r#"
+ SELECT id, macro_id, fusionauth_user_id, email_address, provider as "provider: _",
+ is_sync_active, is_primary, needs_reauth, last_sync_error_at, created_at, updated_at
+ FROM email_links
+ WHERE macro_id = $1 AND LOWER(email_address) = $2
+ ORDER BY created_at DESC
+ LIMIT 1
+ "#,
+ macro_id,
+ email_address
+ )
+ .fetch_optional(pool)
+ .await?;
+
+ Ok(db_link.map(service::link::Link::try_from).transpose()?)
+}
+
/// Fetches all email_links the user can access via their macro_id, including any
/// inboxes delegated via macro_user_links. The union is the read-side half of the
/// multi-inbox narrow-graph design — it surfaces both the user's own inboxes
diff --git a/crates/email_db_client/src/links/get/test.rs b/crates/email_db_client/src/links/get/test.rs
index 3e468a07c4..e30b38e4c7 100644
--- a/crates/email_db_client/src/links/get/test.rs
+++ b/crates/email_db_client/src/links/get/test.rs
@@ -1,6 +1,6 @@
use crate::links::get::{
- fetch_inboxes_for_macro_id, fetch_link_by_email, fetch_owned_link_for_message,
- fetch_owned_link_for_thread,
+ fetch_inboxes_for_macro_id, fetch_link_by_email, fetch_link_by_macro_id_and_email_address,
+ fetch_owned_link_for_message, fetch_owned_link_for_thread,
};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use models_email::service::link::UserProvider;
@@ -239,3 +239,59 @@ async fn fetch_link_by_email_none_when_mailbox_unconnected(
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn fetch_link_by_macro_id_and_email_address_picks_own_inbox_not_newest(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // A user with two inboxes under one macro_id. CRM backfill must resolve the
+ // inbox that IS the user (address == the macro_id email), not the newest
+ // link — which is what a plain macro_id lookup would return.
+ insert_user(&pool, CHILD, "[email protected]").await;
+
+ // Own inbox first...
+ let (own_link, _, _) =
+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;
+ // ...then a second, newer inbox on the same macro_id.
+ let (other_link, _, _) =
+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;
+ assert_ne!(own_link, other_link);
+
+ let found =
+ fetch_link_by_macro_id_and_email_address(&pool, CHILD, "[email protected]").await?;
+ assert_eq!(found.map(|l| l.id), Some(own_link));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn fetch_link_by_macro_id_and_email_address_is_case_insensitive(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // The macro_id email is always lowercased, but a stored email_address may
+ // preserve its original casing — the match must still succeed.
+ insert_user(&pool, CHILD, "[email protected]").await;
+ let (link_id, _, _) =
+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;
+
+ let found =
+ fetch_link_by_macro_id_and_email_address(&pool, CHILD, "[email protected]").await?;
+ assert_eq!(found.map(|l| l.id), Some(link_id));
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn fetch_link_by_macro_id_and_email_address_none_when_no_match(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ // Macro_id has a link, but none whose address matches the macro_id email.
+ insert_user(&pool, CHILD, "[email protected]").await;
+ insert_inbox_with_thread_and_message(&pool, CHILD, "[email protected]").await;
+
+ let found =
+ fetch_link_by_macro_id_and_email_address(&pool, CHILD, "[email protected]").await?;
+ assert!(found.is_none());
+
+ Ok(())
+}
diff --git a/services/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs b/services/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs
index a5715c6644..33af6966ab 100644
--- a/services/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs
+++ b/services/email_service/src/pubsub/backfill/depopulate_crm_for_user.rs
@@ -24,15 +24,23 @@ pub async fn depopulate_crm_for_user(
payload: &DepopulateCrmForUserPayload,
) -> Result<(), ProcessingError> {
let macro_id_str = payload.macro_id.0.as_ref();
+ // Must resolve the same link `populate_crm_for_user` seeded from — the
+ // inbox whose address matches the macro_id email — so teardown targets
+ // the link that was actually populated.
+ let email_address = payload.macro_id.email_str();
- let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, macro_id_str)
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch link by macro_id"),
- })
- })?;
+ let link = email_db_client::links::get::fetch_link_by_macro_id_and_email_address(
+ &ctx.db,
+ macro_id_str,
+ email_address,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch link by macro_id and email_address"),
+ })
+ })?;
let Some(link) = link else {
tracing::debug!("User has no email link; skipping CRM teardown");
diff --git a/services/email_service/src/pubsub/backfill/populate_crm_for_user.rs b/services/email_service/src/pubsub/backfill/populate_crm_for_user.rs
index 9d7a1686dc..b92fd27d17 100644
--- a/services/email_service/src/pubsub/backfill/populate_crm_for_user.rs
+++ b/services/email_service/src/pubsub/backfill/populate_crm_for_user.rs
@@ -20,15 +20,22 @@ pub async fn populate_crm_for_user(
payload: &PopulateCrmForUserPayload,
) -> Result<(), ProcessingError> {
let macro_id_str = payload.macro_id.0.as_ref();
+ // Resolve the user's own inbox — the link whose address matches the email
+ // embedded in the macro_id — not merely the newest link on the macro_id.
+ let email_address = payload.macro_id.email_str();
- let link = email_db_client::links::get::fetch_link_by_macro_id(&ctx.db, macro_id_str)
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch link by macro_id"),
- })
- })?;
+ let link = email_db_client::links::get::fetch_link_by_macro_id_and_email_address(
+ &ctx.db,
+ macro_id_str,
+ email_address,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch link by macro_id and email_address"),
+ })
+ })?;
let Some(link) = link else {
tracing::debug!("User has no email link; skipping CRM fan-out");