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
fix(email-service): Slow `/seen` endpoint (#705)
Evan Hutnik253e89d15d4b
diff --git a/rust/cloud-storage/email_db_client/src/messages/update.rs b/rust/cloud-storage/email_db_client/src/messages/update.rsindex 0d83ce68bf..63b2604b04 100644--- a/rust/cloud-storage/email_db_client/src/messages/update.rs+++ b/rust/cloud-storage/email_db_client/src/messages/update.rs@@ -48,13 +48,16 @@ pub async fn update_message_read_status<'t>(/// Update the read status of multiple messages at once/// Returns the count of messages that were successfully updated-#[tracing::instrument(skip(pool), level = "info")]-pub async fn update_message_read_status_batch(- pool: &sqlx::PgPool,+#[tracing::instrument(skip(executor), err)]+pub async fn update_message_read_status_batch<'e, E>(+ executor: E,message_ids: Vec<Uuid>,fusionauth_user_id: &str,is_read: bool,-) -> anyhow::Result<usize> {+) -> anyhow::Result<usize>+where+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,+{if message_ids.is_empty() {return Ok(0);}@@ -76,15 +79,8 @@ pub async fn update_message_read_status_batch(&message_ids,fusionauth_user_id)- .fetch_all(pool)- .await- .with_context(|| {- format!(- "Failed to update read status for {} messages for user {}",- message_ids.len(),- fusionauth_user_id- )- })?;+ .fetch_all(executor)+ .await?;let updated_count = result.len();diff --git a/rust/cloud-storage/email_db_client/src/threads/update.rs b/rust/cloud-storage/email_db_client/src/threads/update.rsindex d6c1bdb47b..70a84dd76b 100644--- a/rust/cloud-storage/email_db_client/src/threads/update.rs+++ b/rust/cloud-storage/email_db_client/src/threads/update.rs@@ -3,7 +3,6 @@ use anyhow::Context;use chrono::{DateTime, Utc};use models_email::email::service::message::{is_inbound, is_outbound, is_spam_or_trash};use models_email::service;-use sqlx::PgPool;use sqlx::types::Uuid;/// Updates a thread's metadata@@ -83,14 +82,16 @@ pub async fn update_inbox_visible_status(Ok(())}-/// Updates a thread's read status-#[tracing::instrument(skip(db))]-pub async fn update_thread_read_status(- db: &PgPool,+#[tracing::instrument(skip(executor), err)]+pub async fn update_thread_read_status<'e, E>(+ executor: E,thread_id: Uuid,link_id: Uuid,is_read: bool,-) -> anyhow::Result<()> {+) -> anyhow::Result<()>+where+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,+{sqlx::query!(r#"UPDATE email_threads@@ -105,12 +106,8 @@ pub async fn update_thread_read_status(thread_id,link_id,)- .execute(db)- .await- .context(format!(- "Failed to update read status to {} for thread ID {} with link_id {}",- is_read, thread_id, link_id- ))?;+ .execute(executor)+ .await?;Ok(())}diff --git a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs b/rust/cloud-storage/email_service/src/api/email/threads/seen.rsindex 5561416825..eb6a6eeae1 100644--- a/rust/cloud-storage/email_service/src/api/email/threads/seen.rs+++ b/rust/cloud-storage/email_service/src/api/email/threads/seen.rs@@ -1,5 +1,4 @@use crate::api::context::ApiContext;-use crate::api::email::messages::labels::remove_label_from_messages;use anyhow::Context;use axum::extract::{Path, State};use axum::http::StatusCode;@@ -7,8 +6,9 @@ use axum::response::{IntoResponse, Response};use axum::{Extension, Json};use model::response::{EmptyResponse, ErrorResponse};use model::user::UserContext;-use models_email::email::service;+use models_email::service::label::system_labels;use models_email::service::link::Link;+use models_email::service::message::Message;use sqlx::types::Uuid;use strum_macros::AsRefStr;use thiserror::Error;@@ -20,13 +20,18 @@ pub enum SeenThreadError {#[error("Database query error")]QueryError(#[from] anyhow::Error),++ #[error("Transaction error")]+ TransactionError(#[from] sqlx::Error),}impl IntoResponse for SeenThreadError {fn into_response(self) -> Response {let status_code = match &self {SeenThreadError::ThreadNotFound => StatusCode::NOT_FOUND,- SeenThreadError::QueryError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ SeenThreadError::QueryError(_) | SeenThreadError::TransactionError(_) => {+ StatusCode::INTERNAL_SERVER_ERROR+ }};if status_code.is_server_error() {@@ -70,60 +75,185 @@ pub async fn seen_handler(gmail_token: Extension<String>,Path(PathParams { id: thread_id }): Path<PathParams>,) -> Result<Response, SeenThreadError> {- let messages = email_db_client::messages::get_simple_messages::get_simple_messages_for_thread(- &ctx.db, thread_id, link.id,- )- .await- .context("Failed to fetch messages from database")?;-- if messages.is_empty() {- return Err(SeenThreadError::ThreadNotFound);- }-// update viewed_at value in user_history table for threademail_db_client::user_history::upsert_user_history(&ctx.db, link.id, thread_id).await.context("Failed to upsert user history")?;- let gmail_access_token = gmail_token.as_str();+ let messages =+ email_db_client::messages::get::fetch_messages_with_labels(&ctx.db, thread_id, link.id)+ .await?;- // remove UNREAD label from thread's messages that are currently unread- let (successful_ids, failed_ids) = remove_label_from_messages(- &ctx.db,- gmail_access_token,- &ctx.gmail_client,- messages.iter().filter(|m| !m.is_read).cloned().collect(),- service::label::system_labels::UNREAD,- )- .await- .context("Failed to remove label from messages")?;-- if !failed_ids.is_empty() {- tracing::warn!(- "unable to mark messages as read in seen_handler: {:?}",- failed_ids- );+ if messages.is_empty() {+ return Err(SeenThreadError::ThreadNotFound);}- // only need to update read statuses if there were unread messages that got marked as read- if !successful_ids.is_empty() {- // update is_read in threads table+ // Filter for messages that have the UNREAD label+ let unread_messages: Vec<&Message> = messages+ .iter()+ .filter(|m| {+ m.labels+ .iter()+ .any(|l| l.provider_label_id == system_labels::UNREAD)+ })+ .collect();++ if unread_messages.is_empty() {+ // Nothing to mark as read+ return Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response());+ }++ let message_db_ids: Vec<Uuid> = unread_messages.iter().map(|m| m.db_id.unwrap()).collect();+ let message_provider_ids: Vec<String> = unread_messages+ .iter()+ .map(|m| m.provider_id.clone().unwrap_or_default())+ .collect();++ let mut tx = ctx.db.begin().await?;++ let transaction_result = async {+ // Update thread read statusemail_db_client::threads::update::update_thread_read_status(- &ctx.db, thread_id, link.id, true,+ &mut *tx, thread_id, link.id, true,).await.context("Failed to update thread read status")?;- // update is_read in messages table+ // Update messages read statusemail_db_client::messages::update::update_message_read_status_batch(- &ctx.db,- successful_ids.clone(),+ &mut *tx,+ message_db_ids.clone(),&user_context.fusion_user_id,true,).await.context("Failed to update message read status")?;++ // Remove UNREAD label from messages in DB+ email_db_client::labels::delete::delete_message_labels_batch(+ &mut *tx,+ &message_db_ids,+ system_labels::UNREAD,+ link.id,+ )+ .await+ .context("Failed to remove 'UNREAD' label from messages")?;++ anyhow::Ok(())+ }+ .await;++ match transaction_result {+ Ok(_) => {+ tx.commit().await?;+ }+ Err(e) => {+ tracing::error!(error = ?e, "Transaction failed for thread {}, rolling back.", thread_id);+ if let Err(rollback_err) = tx.rollback().await {+ tracing::error!(error = ?rollback_err, "Failed to rollback transaction");+ }+ return Err(SeenThreadError::QueryError(e));+ }}+ // async send requests to gmail. if they fail, revert db changes.+ let db_clone = ctx.db.clone();+ let gmail_client_clone = ctx.gmail_client.clone();+ let gmail_access_token = gmail_token.as_str().to_string();+ let thread_id_clone = thread_id;+ let link_id_clone = link.id;+ let message_db_ids_clone = message_db_ids.clone();+ let fusion_user_id = user_context.fusion_user_id.clone();++ tokio::spawn(async move {+ let message_tuples = message_db_ids_clone+ .iter()+ .zip(message_provider_ids)+ .map(|(id, provider_id)| (*id, provider_id))+ .collect();++ let labels_to_add = Vec::new();+ let labels_to_remove = vec![system_labels::UNREAD.to_string()];++ let (success_ids, failed_ids) = gmail_client_clone+ .batch_modify_labels(+ &gmail_access_token,+ message_tuples,+ labels_to_add,+ labels_to_remove,+ )+ .await;++ if !failed_ids.is_empty() {+ tracing::error!(+ failed_ids = ?failed_ids,+ success_ids = ?success_ids,+ "Gmail API failed to modify labels for some messages, reverting database changes"+ );++ let mut revert_tx = match db_clone.begin().await {+ Ok(tx) => tx,+ Err(e) => {+ tracing::error!(error = ?e, "Failed to begin transaction for reversion");+ return;+ }+ };++ // revert the changes we made in the previous transaction+ let revert_result = async {+ // Revert thread read status to unread+ email_db_client::threads::update::update_thread_read_status(+ &mut *revert_tx,+ thread_id_clone,+ link_id_clone,+ false,+ )+ .await+ .context("Failed to revert thread read status")?;++ // Revert messages read status to unread+ email_db_client::messages::update::update_message_read_status_batch(+ &mut *revert_tx,+ message_db_ids_clone.clone(),+ &fusion_user_id,+ false,+ )+ .await+ .context("Failed to revert message read status")?;++ // Revert: Add UNREAD label back to messages+ email_db_client::labels::insert::insert_message_labels_batch(+ &mut *revert_tx,+ &message_db_ids_clone,+ system_labels::UNREAD,+ link_id_clone,+ )+ .await+ .context("Failed to revert adding 'UNREAD' label to messages")?;++ anyhow::Ok(())+ }+ .await;++ match revert_result {+ Ok(_) => {+ if let Err(e) = revert_tx.commit().await {+ tracing::error!(error = ?e, "Unable to commit transaction for revert");+ } else {+ tracing::info!(+ "Successfully reverted database changes after Gmail API failure"+ );+ }+ }+ Err(e) => {+ tracing::error!(error = ?e, "Revert failed for thread {}, rolling back", thread_id_clone);+ if let Err(rollback_err) = revert_tx.rollback().await {+ tracing::error!(error = ?rollback_err, "Failed to rollback revert transaction");+ }+ }+ }+ }+ });+Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())}