Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(email-service): Async link deletion handler (#916)

Evan Hutnikbe0c0388f39e
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index 12a386f04a..7495db8a13 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -154,6 +154,8 @@ export const inboxSyncRetryQueueName = pulumi.interpolate`${inbox_sync_retry_que
const link_manager_queue = new Queue('email-service-refresh', {
tags,
+ // deleting a link from the database can sometimes take a long time
+ visibilityTimeoutSeconds: 300,
});
export const linkManagerQueueArn = pulumi.interpolate`${link_manager_queue.queue.arn}`;
diff --git a/rust/cloud-storage/email_refresh_handler/src/handler.rs b/rust/cloud-storage/email_refresh_handler/src/handler.rs
index 8a136ac5a7..73119f2038 100644
--- a/rust/cloud-storage/email_refresh_handler/src/handler.rs
+++ b/rust/cloud-storage/email_refresh_handler/src/handler.rs
@@ -6,6 +6,7 @@ use lambda_runtime::{
tracing::{self},
};
use models_email::email::service::pubsub::LinkManagerMessage;
+use models_email::service::pubsub::LinkManagerOperation;
use sqlx::Type;
#[derive(Type, Debug, Clone, Copy)]
@@ -23,8 +24,7 @@ pub async fn handler(
let provider_filter = DbUserProvider::Gmail;
// uses the index idx_links_active_provider_hash_bucket
- let notifications = sqlx::query_as!(
- LinkManagerMessage,
+ let link_ids = sqlx::query_scalar!(
r#"
SELECT
id as "link_id"
@@ -44,31 +44,30 @@ pub async fn handler(
Vec::new()
});
- if !notifications.is_empty() {
+ if !link_ids.is_empty() {
tracing::info!(
"Hour {}. Sending refresh notifications for users with link_ids: {}",
current_hour,
- notifications
+ link_ids
.iter()
- .map(|n| n.link_id.to_string())
+ .map(|id| id.to_string())
.collect::<Vec<String>>()
.join(", ")
);
- }
- for notif in notifications {
- let link_id = notif.link_id;
- if let Err(e) = ctx
- .sqs_client
- .enqueue_email_refresh_notification(notif)
- .await
- {
- tracing::error!(
- "Error enqueueing refresh notification for link_id {}: {}",
+ for link_id in link_ids {
+ let notif = LinkManagerMessage {
link_id,
- e
- );
- };
+ operation: LinkManagerOperation::Refresh,
+ };
+ ctx.sqs_client
+ .enqueue_link_manager_notification(notif)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=%link_id, "Error enqueueing refresh notification for link");
+ })
+ .ok();
+ }
}
Ok(())
diff --git a/rust/cloud-storage/email_scheduled_handler/src/handler.rs b/rust/cloud-storage/email_scheduled_handler/src/handler.rs
index fbe3722925..8a58cf2f22 100644
--- a/rust/cloud-storage/email_scheduled_handler/src/handler.rs
+++ b/rust/cloud-storage/email_scheduled_handler/src/handler.rs
@@ -42,7 +42,7 @@ pub async fn handler(
error = ?e,
link_id = link_id.to_string(),
message_id = message_id.to_string(),
- "Error enqueueing refresh notification",
+ "Error enqueueing scheduled notification",
);
};
}
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.rs
index eb7da4e042..b261a41c05 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
@@ -1,45 +1,30 @@
use crate::api::context::ApiContext;
-use anyhow::Context;
-use axum::Extension;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
+use axum::{Extension, Json};
use model::response::{EmptyResponse, ErrorResponse};
use model::user::UserContext;
use models_email::email::service::link::Link;
-use models_email::service::cache::TokenCacheKey;
-use models_email::service::link::UserProvider;
-use sqs_client::search::SearchQueueMessage;
-use sqs_client::search::email::EmailLinkMessage;
+use models_email::email::service::pubsub::LinkManagerMessage;
+use models_email::service::pubsub::LinkManagerOperation;
use strum_macros::AsRefStr;
use thiserror::Error;
#[derive(Debug, Error, AsRefStr)]
pub enum DisableSyncError {
- #[error("Failed to stop Gmail watch")]
- StopWatchError(#[from] anyhow::Error),
-
- #[error("Database query error")]
- QueryError(#[from] sqlx::Error),
+ #[error("Failed to enqueue delete notification")]
+ EnqueueError(#[from] anyhow::Error),
}
impl IntoResponse for DisableSyncError {
fn into_response(self) -> Response {
let status_code = match &self {
- DisableSyncError::StopWatchError(_) | DisableSyncError::QueryError(_) => {
- StatusCode::INTERNAL_SERVER_ERROR
- }
+ DisableSyncError::EnqueueError(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
- if status_code.is_server_error() {
- tracing::error!(
- nested_error = ?self,
- error_type = "DisableSyncError",
- variant = self.as_ref(),
- "Internal server error");
- }
-
- (status_code, self.to_string()).into_response()
+ let message = self.to_string();
+ (status_code, Json(ErrorResponse { message: &message })).into_response()
}
}
@@ -56,83 +41,26 @@ impl IntoResponse for DisableSyncError {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link, gmail_token), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, link), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn disable_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
link: Extension<Link>,
- gmail_token: Extension<String>,
) -> Result<Response, DisableSyncError> {
tracing::info!(user_id = %user_context.user_id, "Disable called");
- // should cancel backfill jobs
- if let Err(e) =
- email_db_client::backfill::job::update::cancel_active_jobs_by_link_id(&ctx.db, link.id)
- .await
- {
- tracing::error!(error=?e, link_id=?link.id, "Failed to update backfill job statuses");
- };
- // delete cached access token, in case user re-enables within cache window
- if let Err(e) = ctx
- .redis_client
- .delete_gmail_access_token(&TokenCacheKey {
- fusion_user_id: link.fusionauth_user_id.clone(),
- macro_id: link.macro_id.to_string(),
- provider: UserProvider::Gmail,
- })
- .await
- {
- tracing::warn!(error=?e, "Failed to delete Gmail access token");
+ // Enqueue the delete operation to handle cleanup asynchronously
+ let message = LinkManagerMessage {
+ link_id: link.id,
+ operation: LinkManagerOperation::Delete,
};
- // make call to gmail to unregister
- ctx.gmail_client
- .stop_watch(gmail_token.as_str())
- .await
- .context("Gmail call to stop watch failed")?;
-
- email_db_client::links::update::update_link_sync_status(&ctx.db, link.id, false)
- .await
- .context("Failed to update link sync status")?;
-
- // TODO: this will need to be dynamic once we have multiple email providers
- let _ = ctx
- .auth_service_client
- .remove_link(
- &user_context.fusion_user_id,
- &user_context.user_id,
- "google_gmail",
- )
+ ctx.sqs_client
+ .enqueue_link_manager_notification(message)
.await
.inspect_err(|e| {
- tracing::error!(error=?e, "unable to unlink idp");
- });
-
- // delete all of the user's data from the database.
- let db = ctx.db.clone();
- let link_id = link.id;
- let link_context_cloned = link.clone();
- tokio::spawn(async move {
- // send message to search text extractor queue
- ctx.sqs_client
- .send_message_to_search_event_queue(SearchQueueMessage::RemoveEmailLink(
- EmailLinkMessage {
- link_id: link_context_cloned.id.to_string(),
- macro_user_id: link_context_cloned.macro_id.to_string(),
- },
- ))
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to send message to search extractor queue");
- })
- .ok();
-
- if let Err(e) = email_db_client::links::delete::delete_link_by_id(&db, link_id).await {
- tracing::error!(error=?e, link_id=?link_id, "Failed to delete link in background task");
- } else {
- tracing::info!(link_id=?link_id, "Successfully deleted link in background task");
- }
- });
+ tracing::error!(error=?e, link_id=?link.id, "Failed to enqueue delete notification");
+ })?;
Ok(StatusCode::NO_CONTENT.into_response())
}
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.rs
index dfeeec1efb..af943ba3f3 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
@@ -4,8 +4,8 @@ use axum::extract::{Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use model::response::ErrorResponse;
-use sqs_client::search::SearchQueueMessage;
-use sqs_client::search::email::EmailLinkMessage;
+use models_email::email::service::pubsub::LinkManagerMessage;
+use models_email::service::pubsub::LinkManagerOperation;
#[tracing::instrument(skip(ctx))]
pub async fn handler(
@@ -31,67 +31,18 @@ pub async fn handler(
})?;
for link in links {
- // should cancel backfill jobs
- if let Err(e) =
- email_db_client::backfill::job::update::cancel_active_jobs_by_link_id(&ctx.db, link.id)
- .await
- {
- tracing::error!(error=?e, link_id=?link.id, "Failed to update backfill job statuses");
+ let message = LinkManagerMessage {
+ link_id: link.id,
+ operation: LinkManagerOperation::Delete,
};
- let gmail_access_token =
- match email_service::util::gmail::auth::fetch_gmail_access_token_from_link(
- &link,
- &ctx.redis_client,
- &ctx.auth_service_client,
- )
+ ctx.sqs_client
+ .enqueue_link_manager_notification(message)
.await
- {
- Ok(token) => Some(token),
- Err(e) => {
- tracing::error!(error=?e, link_id=?link.id, "unable to fetch access token - skipping stop watch");
- None
- }
- };
-
- if let Some(token) = gmail_access_token
- && let Err(e) = ctx.gmail_client.stop_watch(&token).await
- {
- tracing::error!(error=?e, link_id=?link.id, "gmail call to stop watch failed");
- }
-
- if let Err(e) =
- email_db_client::links::update::update_link_sync_status(&ctx.db, link.id, false).await
- {
- tracing::error!(error=?e, link_id=?link.id, "update link sync status failed");
- }
-
- // delete all of the user's data from the database.
- let db = ctx.db.clone();
- let sqs_client = ctx.sqs_client.clone();
- let link_id = link.id;
- let macro_user_id = link.macro_id;
- tokio::spawn(async move {
- // send message to search text extractor queue
- sqs_client
- .send_message_to_search_event_queue(SearchQueueMessage::RemoveEmailLink(
- EmailLinkMessage {
- link_id: link.id.to_string(),
- macro_user_id: macro_user_id.to_string(),
- },
- ))
- .await
- .inspect_err(|e| {
- tracing::error!(error=?e, "failed to send message to search extractor queue");
- })
- .ok();
-
- if let Err(e) = email_db_client::links::delete::delete_link_by_id(&db, link_id).await {
- tracing::error!(error=?e, link_id=?link_id, "Failed to delete link in background task");
- } else {
- tracing::info!(link_id=?link_id, "Successfully deleted link in background task");
- }
- });
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=?link.id, "Failed to enqueue delete notification");
+ })
+ .ok();
}
Ok(StatusCode::NO_CONTENT.into_response())
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index 37a076e3d4..bc446b63bd 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -86,7 +86,8 @@ async fn main() -> anyhow::Result<()> {
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
.sfs_uploader_queue(&config.sfs_uploader_queue)
- .contacts_queue(&config.contacts_queue);
+ .contacts_queue(&config.contacts_queue)
+ .email_link_manager_queue(&config.link_manager_queue);
let auth_service_client = authentication_service_client::AuthServiceClient::new(
auth_service_secret_key,
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.rs
index 75d4647f26..71ab27fc31 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
@@ -3,11 +3,13 @@ use crate::pubsub::util::{fetch_access_token_for_link, fetch_link};
use crate::util::sync_contacts::sync_contacts;
use anyhow::{Context, anyhow};
use models_email::email::service::pubsub::LinkManagerMessage;
-use models_email::service::link::Link;
+use models_email::service::cache::TokenCacheKey;
+use models_email::service::link::{Link, UserProvider};
+use models_email::service::pubsub::LinkManagerOperation;
+use sqs_client::search::SearchQueueMessage;
+use sqs_client::search::email::EmailLinkMessage;
use sqs_worker::cleanup_message;
-// --- Main Orchestrator Function ---
-/// Processes a link manager message by orchestrating data fetching, API calls, and database updates.
pub async fn process_message(
ctx: LinkManagerContext,
message: &aws_sdk_sqs::types::Message,
@@ -18,27 +20,54 @@ pub async fn process_message(
// Step 2: Fetch the user's link details from the database
let link = fetch_link(&ctx.db, notification_data.link_id).await?;
- // Step 3: Get a valid Gmail access token
- let gmail_access_token =
- fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link).await?;
+ // Step 3: Execute the appropriate operation
+ match notification_data.operation {
+ LinkManagerOperation::Refresh => {
+ // Access token is required for refresh - fail if we can't get it
+ let gmail_access_token =
+ fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link)
+ .await?;
+ handle_refresh(&ctx, &link, &gmail_access_token).await?;
+ }
+ LinkManagerOperation::Delete => {
+ // Access token is optional for delete - we still want to clean up the database
+ // even if the user has revoked access
+ let gmail_access_token =
+ fetch_access_token_for_link(&ctx.redis_client, &ctx.auth_service_client, &link)
+ .await
+ .ok();
+ handle_delete(&ctx, &link, gmail_access_token.as_deref()).await?;
+ }
+ }
+
+ // Step 4: Cleanup the message from the queue
+ cleanup_message(&ctx.sqs_worker, message).await?;
+
+ Ok(())
+}
- // Step 4: Renew the Gmail watch subscription to ensure we keep getting updates.
+/// Handles the Refresh operation: renews Gmail watch subscription and syncs contacts.
+async fn handle_refresh(
+ ctx: &LinkManagerContext,
+ link: &Link,
+ gmail_access_token: &str,
+) -> anyhow::Result<()> {
+ // Renew the Gmail watch subscription to ensure we keep getting updates.
// We can proceed with contact sync even if this fails, so we'll just log the error.
- if let Err(e) = renew_gmail_watch(&ctx, &gmail_access_token, &link).await {
- tracing::error!(
- error = ?e,
- link_id = %link.id,
- "Failed to renew Gmail watch"
- );
- }
+ renew_gmail_watch(ctx, gmail_access_token, link)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=%link.id, "Failed to renew Gmail watch");
+ })
+ .ok();
- // Step 5: Sync contacts and update sync tokens in the database
+ // Sync contacts and update sync tokens in the database
if let Err(e) = sync_contacts(
- &link,
+ link,
&ctx.db,
&ctx.gmail_client,
&ctx.sqs_client,
- &gmail_access_token,
+ gmail_access_token,
)
.await
{
@@ -47,11 +76,87 @@ pub async fn process_message(
link_id = %link.id,
"Failed to sync contacts"
);
- };
+ }
- // Step 6: Even if above steps fail due to transient errors, we can just try again when this is
+ // Even if above steps fail due to transient errors, we can just try again when this is
// triggered for the user in 24h.
- cleanup_message(&ctx.sqs_worker, message).await?;
+ Ok(())
+}
+
+/// notifies downstream dependencies of link deletion, and deletes link (and all data) from database
+async fn handle_delete(
+ ctx: &LinkManagerContext,
+ link: &Link,
+ gmail_access_token: Option<&str>,
+) -> anyhow::Result<()> {
+ tracing::info!(link=?link, "Deleting link");
+ // set sync status to false so any future inbox updates get ignored
+ email_db_client::links::update::update_link_sync_status(&ctx.db, link.id, false)
+ .await
+ .context("Failed to update link sync status")?;
+
+ // cancel any running backfill jobs
+ email_db_client::backfill::job::update::cancel_active_jobs_by_link_id(&ctx.db, link.id)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, link_id=?link.id, "Failed to update backfill job statuses");
+ })
+ .ok();
+
+ // delete cached access token, in case user re-enables within cache window
+ ctx.redis_client
+ .delete_gmail_access_token(&TokenCacheKey {
+ fusion_user_id: link.fusionauth_user_id.clone(),
+ macro_id: link.macro_id.to_string(),
+ provider: UserProvider::Gmail,
+ })
+ .await
+ .inspect_err(|e| {
+ tracing::warn!(error=?e, "Failed to delete Gmail access token");
+ })
+ .ok();
+
+ // make call to gmail to unregister. may fail if the user revoked our access (which is a reason
+ // that we may be deleting their link in the first place)
+ if let Some(token) = gmail_access_token {
+ if let Err(e) = ctx.gmail_client.stop_watch(token).await {
+ tracing::warn!(error=?e, link_id=?link.id, "Gmail call to stop watch failed");
+ }
+ } else {
+ tracing::info!(link_id=?link.id, "Skipping Gmail stop_watch - no access token available");
+ }
+
+ // remove google fusionauth link with gmail inbox permissions
+ let _ = ctx
+ .auth_service_client
+ .remove_link(
+ &link.fusionauth_user_id,
+ link.macro_id.as_ref(),
+ "google_gmail",
+ )
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "unable to unlink idp");
+ });
+
+ // inform search of deletion so it can wipe the email records from OS
+ ctx.sqs_client
+ .send_message_to_search_event_queue(SearchQueueMessage::RemoveEmailLink(EmailLinkMessage {
+ link_id: link.id.to_string(),
+ macro_user_id: link.macro_id.to_string(),
+ }))
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "failed to send message to search extractor queue");
+ })
+ .ok();
+
+ // finally, delete all the user's link as well as all of their email data in a big cascading delete
+ email_db_client::links::delete::delete_link_by_id(&ctx.db, link.id)
+ .await
+ .context("Failed to delete link in background task")?;
+
+ tracing::info!(link_id=?link.id, "Successfully deleted link");
Ok(())
}
diff --git a/rust/cloud-storage/models_email/src/email/service/pubsub.rs b/rust/cloud-storage/models_email/src/email/service/pubsub.rs
index 4b3caaf740..924ce18f1f 100644
--- a/rust/cloud-storage/models_email/src/email/service/pubsub.rs
+++ b/rust/cloud-storage/models_email/src/email/service/pubsub.rs
@@ -43,6 +43,17 @@ pub enum FailureReason {
#[derive(Debug, Serialize, Deserialize)]
pub struct LinkManagerMessage {
pub link_id: Uuid,
+ pub operation: LinkManagerOperation,
+}
+
+/// The operations that can be performed by the LinkManager.
+#[derive(Debug, Serialize, Deserialize)]
+pub enum LinkManagerOperation {
+ /// Triggers a contact sync and refreshes the Gmail watch subscription to continue receiving
+ /// inbox notifications for the user.
+ Refresh,
+ /// Delete the link from the database.
+ Delete,
}
/// The message we send from the email_scheduled_handler lambda to the service via SQS to trigger
diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rs
index 629b28aa12..d1703e2560 100644
--- a/rust/cloud-storage/sqs_client/src/email.rs
+++ b/rust/cloud-storage/sqs_client/src/email.rs
@@ -26,12 +26,13 @@ impl SQS {
/// Sends a notification message to the email refresh queue
#[tracing::instrument(skip(self))]
- pub async fn enqueue_email_refresh_notification(
+ pub async fn enqueue_link_manager_notification(
&self,
message: LinkManagerMessage,
) -> anyhow::Result<()> {
if let Some(link_manager_queue) = &self.link_manager_queue {
- return enqueue_refresh_notification(&self.inner, link_manager_queue, message).await;
+ return enqueue_link_manager_notification(&self.inner, link_manager_queue, message)
+ .await;
}
Err(anyhow::anyhow!("link_manager_queue is not configured"))
}
@@ -76,7 +77,7 @@ impl SQS {
}
#[tracing::instrument(skip(sqs_client))]
-pub async fn enqueue_refresh_notification(
+pub async fn enqueue_link_manager_notification(
sqs_client: &aws_sdk_sqs::Client,
queue_url: &str,
message: LinkManagerMessage,
diff --git a/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_refresh_handler/bootstrap.zip
index 1bedcfbb8a..45cae836a9 100644
Binary 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
diff --git a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip
index ef7b364caa..20baa63e35 100644
Binary files a/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/email_scheduled_handler/bootstrap.zip differ