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(email): user link history (#2509)
Evan Hutnik4875f26f9d41
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-4857541516ce135939f34754fde00c114cdf9ed7f203553020cf032732892e80.json b/rust/cloud-storage/email_db_client/.sqlx/query-4857541516ce135939f34754fde00c114cdf9ed7f203553020cf032732892e80.jsonnew file mode 100644index 0000000000..cb80ad13ca--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-4857541516ce135939f34754fde00c114cdf9ed7f203553020cf032732892e80.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO email_links_history (id, link_id, fusionauth_user_id, email_address, provider, created_at)\n VALUES ($1, $2, $3, $4, $5, NOW())\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Varchar",+ {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "4857541516ce135939f34754fde00c114cdf9ed7f203553020cf032732892e80"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-6aa68cd66ced924e43b012c317e1efe33721073350ae49882e066ac544bbb995.json b/rust/cloud-storage/email_db_client/.sqlx/query-6aa68cd66ced924e43b012c317e1efe33721073350ae49882e066ac544bbb995.jsonnew file mode 100644index 0000000000..d29fdf9117--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-6aa68cd66ced924e43b012c317e1efe33721073350ae49882e066ac544bbb995.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE email_links_history\n SET deleted_at = NOW(),\n deletion_reason = $2\n WHERE link_id = $1\n AND deleted_at IS NULL\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6aa68cd66ced924e43b012c317e1efe33721073350ae49882e066ac544bbb995"+}diff --git a/rust/cloud-storage/email_db_client/src/lib.rs b/rust/cloud-storage/email_db_client/src/lib.rsindex d0ff7aa26c..c1bdc26cd7 100644--- a/rust/cloud-storage/email_db_client/src/lib.rs+++ b/rust/cloud-storage/email_db_client/src/lib.rs@@ -4,6 +4,7 @@ pub mod contacts;pub mod histories;pub mod labels;pub mod links;+pub mod links_history;pub mod messages;pub mod parse;pub mod settings;diff --git a/rust/cloud-storage/email_db_client/src/links_history/insert.rs b/rust/cloud-storage/email_db_client/src/links_history/insert.rsnew file mode 100644index 0000000000..e615241fcf--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links_history/insert.rs@@ -0,0 +1,33 @@+use doppleganger::Mirror;+use sqlx::PgPool;+use sqlx::types::Uuid;++use crate::links::types::DbUserProvider;++#[tracing::instrument(skip(pool), err)]+pub async fn insert_email_link_history(+ pool: &PgPool,+ link_id: Uuid,+ fusionauth_user_id: &str,+ email_address: &str,+ provider: models_email::service::link::UserProvider,+) -> anyhow::Result<()> {+ let id = macro_uuid::generate_uuid_v7();+ let db_provider = DbUserProvider::mirror(provider);++ sqlx::query!(+ r#"+ INSERT INTO email_links_history (id, link_id, fusionauth_user_id, email_address, provider, created_at)+ VALUES ($1, $2, $3, $4, $5, NOW())+ "#,+ id,+ link_id,+ fusionauth_user_id,+ email_address,+ db_provider as _,+ )+ .execute(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/email_db_client/src/links_history/mod.rs b/rust/cloud-storage/email_db_client/src/links_history/mod.rsnew file mode 100644index 0000000000..92376f375e--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links_history/mod.rs@@ -0,0 +1,2 @@+pub mod insert;+pub mod update;diff --git a/rust/cloud-storage/email_db_client/src/links_history/update.rs b/rust/cloud-storage/email_db_client/src/links_history/update.rsnew file mode 100644index 0000000000..947cb774b3--- /dev/null+++ b/rust/cloud-storage/email_db_client/src/links_history/update.rs@@ -0,0 +1,25 @@+use sqlx::PgPool;+use sqlx::types::Uuid;++#[tracing::instrument(skip(pool), err)]+pub async fn set_deleted_at(+ pool: &PgPool,+ link_id: Uuid,+ deletion_reason: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ UPDATE email_links_history+ SET deleted_at = NOW(),+ deletion_reason = $2+ WHERE link_id = $1+ AND deleted_at IS NULL+ "#,+ link_id,+ deletion_reason,+ )+ .execute(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/email_refresh_handler/.sqlx/query-32900d38a985678b10e8b72c3a250033052a9fb05c14a92e0d2b89b3b47330a2.json b/rust/cloud-storage/email_refresh_handler/.sqlx/query-32900d38a985678b10e8b72c3a250033052a9fb05c14a92e0d2b89b3b47330a2.jsonnew file mode 100644index 0000000000..4a65e67f3d--- /dev/null+++ b/rust/cloud-storage/email_refresh_handler/.sqlx/query-32900d38a985678b10e8b72c3a250033052a9fb05c14a92e0d2b89b3b47330a2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n l.id AS \"link_id!\"\n FROM\n public.email_links l\n JOIN\n public.email_user_history h ON l.id = h.link_id\n WHERE\n l.macro_id NOT LIKE '%@macro.com'\n GROUP BY\n l.id\n HAVING\n MAX(h.updated_at) < NOW() - (make_interval(days => $1))\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "32900d38a985678b10e8b72c3a250033052a9fb05c14a92e0d2b89b3b47330a2"+}diff --git a/rust/cloud-storage/email_refresh_handler/.sqlx/query-850d9317ed6b8e21fbb7602beaf6b8c05f43739f31587aa63e57dbfd0093ab1d.json b/rust/cloud-storage/email_refresh_handler/.sqlx/query-850d9317ed6b8e21fbb7602beaf6b8c05f43739f31587aa63e57dbfd0093ab1d.jsonnew file mode 100644index 0000000000..03e8dd41b0--- /dev/null+++ b/rust/cloud-storage/email_refresh_handler/.sqlx/query-850d9317ed6b8e21fbb7602beaf6b8c05f43739f31587aa63e57dbfd0093ab1d.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n l.id AS \"link_id!\"\n FROM\n public.email_links l\n LEFT JOIN\n public.email_user_history h ON l.id = h.link_id\n WHERE\n l.macro_id NOT LIKE '%@macro.com'\n AND l.created_at < NOW() - (make_interval(days => $1))\n GROUP BY\n l.id\n HAVING\n COUNT(h.link_id) = 0\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "link_id!",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Int4"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "850d9317ed6b8e21fbb7602beaf6b8c05f43739f31587aa63e57dbfd0093ab1d"+}diff --git a/rust/cloud-storage/email_refresh_handler/.sqlx/query-c4f9c493fa0e3816a20a0494d5513617cdb7a83c37ecdb2df1faae1a83e14e37.json b/rust/cloud-storage/email_refresh_handler/.sqlx/query-c4f9c493fa0e3816a20a0494d5513617cdb7a83c37ecdb2df1faae1a83e14e37.jsondeleted file mode 100644index 787cf562dc..0000000000--- a/rust/cloud-storage/email_refresh_handler/.sqlx/query-c4f9c493fa0e3816a20a0494d5513617cdb7a83c37ecdb2df1faae1a83e14e37.json+++ /dev/null@@ -1,23 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n -- Condition A: Created > X days ago and has NO history - hasn't viewed a thread\n SELECT\n l.id AS \"link_id!\"\n FROM\n public.email_links l\n LEFT JOIN\n public.email_user_history h ON l.id = h.link_id\n WHERE\n l.macro_id NOT LIKE '%@macro.com'\n AND l.created_at < NOW() - (make_interval(days => $1))\n GROUP BY\n l.id\n HAVING\n COUNT(h.link_id) = 0\n\n UNION\n\n -- Condition B: Has history rows, but latest thread viewed was > Y days ago\n SELECT\n l.id AS \"link_id!\"\n FROM\n public.email_links l\n JOIN\n public.email_user_history h ON l.id = h.link_id\n WHERE\n l.macro_id NOT LIKE '%@macro.com'\n GROUP BY\n l.id\n HAVING\n MAX(h.updated_at) < NOW() - (make_interval(days => $2))\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "link_id!",- "type_info": "Uuid"- }- ],- "parameters": {- "Left": [- "Int4",- "Int4"- ]- },- "nullable": [- null- ]- },- "hash": "c4f9c493fa0e3816a20a0494d5513617cdb7a83c37ecdb2df1faae1a83e14e37"-}diff --git a/rust/cloud-storage/email_refresh_handler/src/handler.rs b/rust/cloud-storage/email_refresh_handler/src/handler.rsindex 0144827e70..70c9a38850 100644--- a/rust/cloud-storage/email_refresh_handler/src/handler.rs+++ b/rust/cloud-storage/email_refresh_handler/src/handler.rs@@ -6,7 +6,7 @@ use lambda_runtime::{tracing::{self},};use macro_env::Environment;-use models_email::email::service::pubsub::LinkManagerMessage;+use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};use sqlx::types::uuid;use sqlx::{Pool, Postgres, Type};@@ -82,49 +82,67 @@ async fn send_refresh_messages(ctx: &context::Context) -> Result<(), Error> {Ok(())}-/// delete inactive links from our database+/// delete unused and inactive links from our databaseasync fn send_delete_messages(ctx: &context::Context) -> Result<(), Error> {- let inactive_links = fetch_inactive_link_ids(- &ctx.db,- ctx.config.delete_unused_after_days as i32,- ctx.config.delete_inactive_after_days as i32,- )- .await- .unwrap_or_else(|e| {- tracing::error!(error=?e, "Error fetching inactive links for deletion");- Vec::new()- });+ let unused_links = fetch_unused_link_ids(&ctx.db, ctx.config.delete_unused_after_days as i32)+ .await+ .unwrap_or_else(|e| {+ tracing::error!(error=?e, "Error fetching unused links for deletion");+ Vec::new()+ });- if !inactive_links.is_empty() {- tracing::info!(- "Sending delete notifications for {} inactive links",- inactive_links.len()- );+ let inactive_links =+ fetch_inactive_link_ids(&ctx.db, ctx.config.delete_inactive_after_days as i32)+ .await+ .unwrap_or_else(|e| {+ tracing::error!(error=?e, "Error fetching inactive links for deletion");+ Vec::new()+ });- for link_id in inactive_links {- let notif = LinkManagerMessage::DeleteLink { link_id };- ctx.sqs_client- .enqueue_link_manager_notification(notif)- .await- .inspect_err(|e| {- tracing::error!(error=?e, link_id=%link_id, "Error enqueueing delete notification for inactive link");- })- .ok();- }+ tracing::info!(+ "Sending delete notifications for {} unused and {} inactive links",+ unused_links.len(),+ inactive_links.len()+ );++ for link_id in unused_links {+ let notif = LinkManagerMessage::DeleteLink {+ link_id,+ deletion_reason: DeletionReason::Unused,+ };+ ctx.sqs_client+ .enqueue_link_manager_notification(notif)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, link_id=%link_id, "Error enqueueing delete notification for unused link");+ })+ .ok();+ }++ for link_id in inactive_links {+ let notif = LinkManagerMessage::DeleteLink {+ link_id,+ deletion_reason: DeletionReason::Inactive,+ };+ ctx.sqs_client+ .enqueue_link_manager_notification(notif)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, link_id=%link_id, "Error enqueueing delete notification for inactive link");+ })+ .ok();}Ok(())}-/// Fetch link IDs that should be deleted due to inactivity-pub async fn fetch_inactive_link_ids(+/// Fetch link IDs that were created > X days ago and have never viewed a thread+pub async fn fetch_unused_link_ids(pool: &Pool<Postgres>,delete_unused_after_days: i32,- delete_inactive_after_days: i32,) -> Result<Vec<uuid::Uuid>, sqlx::Error> {sqlx::query_scalar!(r#"- -- Condition A: Created > X days ago and has NO history - hasn't viewed a threadSELECTl.id AS "link_id!"FROM@@ -138,10 +156,20 @@ pub async fn fetch_inactive_link_ids(l.idHAVINGCOUNT(h.link_id) = 0+ "#,+ delete_unused_after_days+ )+ .fetch_all(pool)+ .await+}- UNION-- -- Condition B: Has history rows, but latest thread viewed was > Y days ago+/// Fetch link IDs where the latest thread viewed was > Y days ago+pub async fn fetch_inactive_link_ids(+ pool: &Pool<Postgres>,+ delete_inactive_after_days: i32,+) -> Result<Vec<uuid::Uuid>, sqlx::Error> {+ sqlx::query_scalar!(+ r#"SELECTl.id AS "link_id!"FROM@@ -153,9 +181,8 @@ pub async fn fetch_inactive_link_ids(GROUP BYl.idHAVING- MAX(h.updated_at) < NOW() - (make_interval(days => $2))+ MAX(h.updated_at) < NOW() - (make_interval(days => $1))"#,- delete_unused_after_days,delete_inactive_after_days).fetch_all(pool)diff --git a/rust/cloud-storage/email_refresh_handler/src/test.rs b/rust/cloud-storage/email_refresh_handler/src/test.rsindex 1f43418300..0bbb594877 100644--- a/rust/cloud-storage/email_refresh_handler/src/test.rs+++ b/rust/cloud-storage/email_refresh_handler/src/test.rs@@ -1,4 +1,4 @@-use crate::handler::fetch_inactive_link_ids;+use crate::handler::{fetch_inactive_link_ids, fetch_unused_link_ids};use anyhow::Result;use macro_db_migrator::MACRO_DB_MIGRATIONS;use sqlx::{Pool, Postgres};@@ -12,7 +12,7 @@ async fn fetch_inactive_link_ids_returns_unused_links(pool: Pool<Postgres>) -> Rconst _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS;// Link created 40 days ago with no history should be returned (threshold: 30 days)- let result = fetch_inactive_link_ids(&pool, 30, 60).await?;+ let result = fetch_unused_link_ids(&pool, 30).await?;let unused_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;assert!(@@ -29,7 +29,7 @@ async fn fetch_inactive_link_ids_returns_unused_links(pool: Pool<Postgres>) -> R)]async fn fetch_inactive_link_ids_returns_stale_history_links(pool: Pool<Postgres>) -> Result<()> {// Link with history last updated 90 days ago should be returned (threshold: 60 days)- let result = fetch_inactive_link_ids(&pool, 30, 60).await?;+ let result = fetch_inactive_link_ids(&pool, 60).await?;let stale_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000002")?;assert!(@@ -45,19 +45,20 @@ async fn fetch_inactive_link_ids_returns_stale_history_links(pool: Pool<Postgresfixtures(path = "../fixtures", scripts("fetch_inactive_links")))]async fn fetch_inactive_link_ids_excludes_active_links(pool: Pool<Postgres>) -> Result<()> {- let result = fetch_inactive_link_ids(&pool, 30, 60).await?;+ let unused_result = fetch_unused_link_ids(&pool, 30).await?;+ let inactive_result = fetch_inactive_link_ids(&pool, 60).await?;// Link with recent history should NOT be returnedlet active_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000003")?;assert!(- !result.contains(&active_link_id),+ !unused_result.contains(&active_link_id) && !inactive_result.contains(&active_link_id),"Should not include link with recent history");// Recently created link with no history should NOT be returnedlet new_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000004")?;assert!(- !result.contains(&new_link_id),+ !unused_result.contains(&new_link_id) && !inactive_result.contains(&new_link_id),"Should not include recently created link");@@ -69,12 +70,13 @@ async fn fetch_inactive_link_ids_excludes_active_links(pool: Pool<Postgres>) ->fixtures(path = "../fixtures", scripts("fetch_inactive_links")))]async fn fetch_inactive_link_ids_excludes_macro_internal_links(pool: Pool<Postgres>) -> Result<()> {- let result = fetch_inactive_link_ids(&pool, 30, 60).await?;+ let unused_result = fetch_unused_link_ids(&pool, 30).await?;+ let inactive_result = fetch_inactive_link_ids(&pool, 60).await?;// Links with @macro.com in macro_id should never be deletedlet internal_link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000005")?;assert!(- !result.contains(&internal_link_id),+ !unused_result.contains(&internal_link_id) && !inactive_result.contains(&internal_link_id),"Should not include internal @macro.com links");@@ -87,13 +89,18 @@ async fn fetch_inactive_link_ids_excludes_macro_internal_links(pool: Pool<Postgr)]async fn fetch_inactive_link_ids_respects_threshold_parameters(pool: Pool<Postgres>) -> Result<()> {// With very high thresholds, nothing should be returned- let result = fetch_inactive_link_ids(&pool, 365, 365).await?;- assert!(result.is_empty(), "High thresholds should return no links");+ let unused_result = fetch_unused_link_ids(&pool, 365).await?;+ let inactive_result = fetch_inactive_link_ids(&pool, 365).await?;+ assert!(+ unused_result.is_empty() && inactive_result.is_empty(),+ "High thresholds should return no links"+ );// With very low thresholds, more links should be returned- let result = fetch_inactive_link_ids(&pool, 1, 1).await?;+ let unused_result = fetch_unused_link_ids(&pool, 1).await?;+ let inactive_result = fetch_inactive_link_ids(&pool, 1).await?;assert!(- !result.is_empty(),+ !unused_result.is_empty() || !inactive_result.is_empty(),"Low thresholds should return some links");diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex 3b98d8dcc7..676a89df1c 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -132,6 +132,20 @@ pub async fn handler(return Err(InitError::TooManyJobs);}+ // Record link creation in history table for tracking (best-effort)+ email_db_client::links_history::insert::insert_email_link_history(+ &ctx.db,+ link.id,+ &link.fusionauth_user_id,+ link.email_address.0.as_ref(),+ link.provider,+ )+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, link_id=?link.id, "Failed to insert email link history");+ })+ .ok();+// create job to backfill user's inbox historylet backfill_job = email_db_client::backfill::job::insert::create_backfill_job(&ctx.db,diff --git a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs b/rust/cloud-storage/email_service/src/api/email/sync/disable.rsindex 55b841d50e..e1bd3f5651 100644--- a/rust/cloud-storage/email_service/src/api/email/sync/disable.rs+++ b/rust/cloud-storage/email_service/src/api/email/sync/disable.rs@@ -55,7 +55,10 @@ pub async fn disable_handler(tracing::info!(user_id = %user_context.user_id, "Disable called");// Enqueue the delete operation to handle cleanup asynchronously- let message = LinkManagerMessage::DeleteLink { link_id: link.id };+ let message = LinkManagerMessage::DeleteLink {+ link_id: link.id,+ deletion_reason: models_email::email::service::pubsub::DeletionReason::ManuallyDisabled,+ };ctx.sqs_client.enqueue_link_manager_notification(message)diff --git a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs b/rust/cloud-storage/email_service/src/api/internal/delete_user.rsindex 2ca294ea23..f5e18e8df9 100644--- a/rust/cloud-storage/email_service/src/api/internal/delete_user.rs+++ b/rust/cloud-storage/email_service/src/api/internal/delete_user.rs@@ -30,7 +30,10 @@ pub async fn handler(})?;for link in links {- let message = LinkManagerMessage::DeleteLink { link_id: link.id };+ let message = LinkManagerMessage::DeleteLink {+ link_id: link.id,+ deletion_reason: models_email::email::service::pubsub::DeletionReason::UserDeleted,+ };ctx.sqs_client.enqueue_link_manager_notification(message)diff --git a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rsindex a90a8ca830..a41b96d200 100644--- a/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/link_manager/process.rs@@ -4,7 +4,7 @@ use crate::util::gmail::auth::{};use crate::util::sync_contacts::sync_contacts;use anyhow::{Context, anyhow};-use models_email::email::service::pubsub::LinkManagerMessage;+use models_email::email::service::pubsub::{DeletionReason, LinkManagerMessage};use models_email::service::cache::TokenCacheKey;use models_email::service::link::{Link, UserProvider};use sqs_client::search::SearchQueueMessage;@@ -32,7 +32,10 @@ pub async fn process_message(.await?;handle_refresh(&ctx, &link, &gmail_access_token).await?;}- LinkManagerMessage::DeleteLink { link_id } => {+ LinkManagerMessage::DeleteLink {+ link_id,+ deletion_reason,+ } => {let link = get_link_or_skip(&ctx, message, link_id).await?;let Some(link) = link else { return Ok(()) };@@ -43,7 +46,7 @@ pub async fn process_message().await.ok();- handle_delete(&ctx, &link, gmail_access_token.as_deref()).await?;+ handle_delete(&ctx, &link, gmail_access_token.as_deref(), &deletion_reason).await?;}LinkManagerMessage::DeleteUser { fusionauth_user_id } => {handle_delete_all_user_links(&ctx, &fusionauth_user_id).await?;@@ -133,7 +136,14 @@ async fn handle_delete_all_user_links(.await.ok();- if let Err(e) = handle_delete(ctx, link, gmail_access_token.as_deref()).await {+ if let Err(e) = handle_delete(+ ctx,+ link,+ gmail_access_token.as_deref(),+ &DeletionReason::UserDeleted,+ )+ .await+ {tracing::error!(error=?e, link_id=?link.id, "Failed to delete link during user cleanup");}}@@ -147,6 +157,7 @@ async fn handle_delete(ctx: &LinkManagerContext,link: &Link,gmail_access_token: Option<&str>,+ deletion_reason: &DeletionReason,) -> anyhow::Result<()> {tracing::info!("Deleting link");// set sync status to false so any future inbox updates get ignored@@ -215,6 +226,17 @@ async fn handle_delete(.await.context("Failed to delete link in background task")?;+ // Mark the link as deleted in history table for tracking (best-effort)+ if let Err(e) = email_db_client::links_history::update::set_deleted_at(+ &ctx.db,+ link.id,+ deletion_reason.as_str(),+ )+ .await+ {+ tracing::error!(error=?e, link_id=?link.id, "Failed to set deleted_at on email link history");+ }+tracing::info!("Successfully deleted link");Ok(())diff --git a/rust/cloud-storage/email_service/src/util/gmail/auth.rs b/rust/cloud-storage/email_service/src/util/gmail/auth.rsindex 29826d6f61..136da65ed5 100644--- a/rust/cloud-storage/email_service/src/util/gmail/auth.rs+++ b/rust/cloud-storage/email_service/src/util/gmail/auth.rs@@ -37,6 +37,7 @@ pub async fn fetch_token_or_delete_on_revocation(sqs_client.enqueue_link_manager_notification(LinkManagerMessage::DeleteLink {link_id: link.id,+ deletion_reason: models_email::email::service::pubsub::DeletionReason::AccessRevoked,}).await.inspect_err(|e| {diff --git a/rust/cloud-storage/macro_db_client/migrations/20260410144431_create_email_links_history.sql b/rust/cloud-storage/macro_db_client/migrations/20260410144431_create_email_links_history.sqlnew file mode 100644index 0000000000..504192914f--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260410144431_create_email_links_history.sql@@ -0,0 +1,13 @@+CREATE TABLE IF NOT EXISTS email_links_history (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ link_id UUID NOT NULL,+ fusionauth_user_id TEXT NOT NULL,+ email_address VARCHAR(320) NOT NULL,+ provider email_user_provider_enum NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ deleted_at TIMESTAMPTZ,+ deletion_reason TEXT+);++CREATE INDEX IF NOT EXISTS idx_email_links_history_fusionauth_user_id ON email_links_history (fusionauth_user_id);+CREATE INDEX IF NOT EXISTS idx_email_links_history_link_id_not_deleted ON email_links_history (link_id) WHERE deleted_at IS NULL;diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rsindex 66048288a4..772cd56119 100644--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs@@ -39,6 +39,28 @@ pub enum FailureReason {InvalidData,}+/// The reason a link was deleted, stored in the email_links_history table.+#[derive(Debug, Clone, Copy, Serialize, Deserialize)]+pub enum DeletionReason {+ Unused,+ Inactive,+ ManuallyDisabled,+ UserDeleted,+ AccessRevoked,+}++impl DeletionReason {+ pub fn as_str(&self) -> &'static str {+ match self {+ DeletionReason::Unused => "Unused",+ DeletionReason::Inactive => "Inactive",+ DeletionReason::ManuallyDisabled => "ManuallyDisabled",+ DeletionReason::UserDeleted => "UserDeleted",+ DeletionReason::AccessRevoked => "AccessRevoked",+ }+ }+}+/// The message sent to the link manager SQS queue.#[derive(Debug, Serialize, Deserialize)]#[serde(tag = "operation")]@@ -47,7 +69,10 @@ pub enum LinkManagerMessage {/// inbox notifications for the user.Refresh { link_id: Uuid },/// Delete a single link from the database.- DeleteLink { link_id: Uuid },+ DeleteLink {+ link_id: Uuid,+ deletion_reason: DeletionReason,+ },/// Delete all links for a user, identified by fusionauth_user_id.DeleteUser { fusionauth_user_id: String },}diff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zipindex 560e869d5c..533916d6b9 100644Binary files a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip differ