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): Proper attachment upload retry logic, backfill rate limit tiering (#720)
Evan Hutnikeb0ed482de8b
diff --git a/infra/stacks/email-service/Pulumi.dev.yaml b/infra/stacks/email-service/Pulumi.dev.yamlindex facd7b5fc4..216802c812 100644--- a/infra/stacks/email-service/Pulumi.dev.yaml+++ b/infra/stacks/email-service/Pulumi.dev.yaml@@ -10,6 +10,7 @@ config:email-service:cf_private_key: email-attachments-private-key-devemail-service:notifications_enabled: trueemail-service:redis_rate_limit_reqs: 14000+ email-service:redis_rate_limit_reqs_backfill: 13000email-service:redis_rate_limit_window_secs: 60email-service:backfill_queue_workers: 25email-service:backfill_queue_max_messages: 1diff --git a/infra/stacks/email-service/Pulumi.prod.yaml b/infra/stacks/email-service/Pulumi.prod.yamlindex e34866da5c..43c90a1035 100644--- a/infra/stacks/email-service/Pulumi.prod.yaml+++ b/infra/stacks/email-service/Pulumi.prod.yaml@@ -10,6 +10,7 @@ config:email-service:cf_private_key: email-attachments-private-key-prodemail-service:notifications_enabled: trueemail-service:redis_rate_limit_reqs: 14000+ email-service:redis_rate_limit_reqs_backfill: 13000email-service:redis_rate_limit_window_secs: 60email-service:backfill_queue_workers: 25email-service:backfill_queue_max_messages: 1diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.tsindex 51ee2ed9bb..2e0d15c690 100644--- a/infra/stacks/email-service/index.ts+++ b/infra/stacks/email-service/index.ts@@ -34,6 +34,9 @@ const AUDIENCE = aws.secretsmanagerconst ISSUER = config.require(`fusionauth_issuer`);const NOTIFICATIONS_ENABLED = config.require(`notifications_enabled`);const REDIS_RATE_LIMIT_REQS = config.require(`redis_rate_limit_reqs`);+const REDIS_RATE_LIMIT_REQS_BACKFILL = config.require(+ `redis_rate_limit_reqs_backfill`+);const REDIS_RATE_LIMIT_WINDOW_SECS = config.require(`redis_rate_limit_window_secs`);@@ -351,6 +354,10 @@ const emailService = new EmailService('email-service', {name: 'REDIS_RATE_LIMIT_REQS',value: pulumi.interpolate`${REDIS_RATE_LIMIT_REQS}`,},+ {+ name: 'REDIS_RATE_LIMIT_REQS_BACKFILL',+ value: pulumi.interpolate`${REDIS_RATE_LIMIT_REQS_BACKFILL}`,+ },{name: 'REDIS_RATE_LIMIT_WINDOW_SECS',value: pulumi.interpolate`${REDIS_RATE_LIMIT_WINDOW_SECS}`,diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsindex aa0cb9322b..bbda9a956c 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -1,5 +1,7 @@use crate::api::context::ApiContext;-use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};+use crate::util::upload_attachment::{+ UploadAttachmentContext, UploadAttachmentError, upload_attachment,+};use axum::extract::{Path, State};use axum::http::StatusCode;use axum::response::{IntoResponse, Response};@@ -22,7 +24,7 @@ pub enum GetAttachmentDocumentIdError {DatabaseError(anyhow::Error),#[error("Failed to upload attachment")]- UploadError(anyhow::Error),+ UploadError(UploadAttachmentError),}impl IntoResponse for GetAttachmentDocumentIdError {diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rsindex 5def6020e5..28cf71c62d 100644--- a/rust/cloud-storage/email_service/src/config.rs+++ b/rust/cloud-storage/email_service/src/config.rs@@ -80,6 +80,10 @@ pub struct Config {/// The number of workers we spawn for sfs uploaderpub sfs_uploader_workers: i32,+ /// The number of requests we allow per window for backfilling. Less than redis_rate_limit_reqs+ /// so we have room for normal gmail operations while backfilling is occurring+ pub redis_rate_limit_reqs_backfill: u32,+/// The number of requests we allow per window.pub redis_rate_limit_reqs: u32,@@ -219,7 +223,12 @@ impl Config {.unwrap();let redis_rate_limit_reqs: u32 = std::env::var("REDIS_RATE_LIMIT_REQS")- .unwrap_or("1500".to_string())+ .unwrap_or("14000".to_string())+ .parse::<u32>()+ .unwrap();++ let redis_rate_limit_reqs_backfill: u32 = std::env::var("REDIS_RATE_LIMIT_REQS_BACKFILL")+ .unwrap_or("13000".to_string()).parse::<u32>().unwrap();@@ -288,6 +297,7 @@ impl Config {inbox_sync_retry_queue_max_messages,sfs_uploader_workers,redis_rate_limit_reqs,+ redis_rate_limit_reqs_backfill,redis_rate_limit_window_secs,environment,auth_service_secret_key,diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rsindex 39b8f70bbe..d75f4cda19 100644--- a/rust/cloud-storage/email_service/src/main.rs+++ b/rust/cloud-storage/email_service/src/main.rs@@ -192,6 +192,7 @@ async fn main() -> anyhow::Result<()> {let redis_client = util::redis::RedisClient::new(redis_inner_client,config.redis_rate_limit_reqs,+ config.redis_rate_limit_reqs_backfill,config.redis_rate_limit_window_secs,);diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rsindex 6f32d76152..b5c161a4ea 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -1,5 +1,7 @@use crate::pubsub::context::PubSubContext;-use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};+use crate::util::upload_attachment::{+ UploadAttachmentContext, UploadAttachmentError, upload_attachment,+};use models_email::service::backfill::BackfillAttachmentPayload;use models_email::service::link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -41,11 +43,17 @@ pub async fn backfill_attachment(upload_attachment(ctx_upload, &attachment_args).await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {+ .map_err(|e| match e {+ UploadAttachmentError::RateLimitCheckFailed(_) => {+ ProcessingError::Retryable(DetailedError {+ reason: FailureReason::GmailApiRateLimited,+ source: anyhow::Error::new(e).context("Failed to upload attachment"),+ })+ }+ _ => ProcessingError::NonRetryable(DetailedError {reason: FailureReason::GmailApiFailed,- source: e.context("Failed to upload attachment"),- })+ source: anyhow::Error::new(e).context("Failed to upload attachment"),+ }),})?;Ok(())diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rsindex b395cb187f..b70ff0af5b 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs@@ -1,12 +1,11 @@use crate::pubsub::backfill::increment_counters;use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::check_gmail_rate_limit;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use crate::util::process_pre_insert::process_message_pre_insert;use models_email::email::service::backfill::{BackfillMessagePayload, BackfillPubsubMessage};use models_email::email::service::link;use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use models_email::gmail::operations::GmailApiOperation;-/// This step is invoked by BackfillThread once for each message in the thread./// Creates a message object in the database. If the message is the last message in/// the thread to be processed, it sends an UpdateThreadMetadata message for the thread.@@ -18,12 +17,13 @@ pub async fn backfill_message(link: &link::Link,p: &BackfillMessagePayload,) -> Result<(), ProcessingError> {- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::MessagesGet,- true,- )+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::MessagesGet,+ retryable: true,+ is_backfill: true,+ }).await?;// get message from gmaildiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rsindex dda5ccf6d7..6dcba137cd 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_thread.rs@@ -1,6 +1,6 @@use crate::pubsub::backfill::increment_counters::incr_completed_threads;use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::check_gmail_rate_limit;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use models_email::email::service::backfill::{BackfillMessagePayload, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload,};@@ -44,12 +44,13 @@ pub async fn backfill_thread(return Ok(());}- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::ThreadsGet,- true,- )+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::ThreadsGet,+ retryable: true,+ is_backfill: true,+ }).await?;// fetch all message_ids of the threadlet message_ids = match ctxdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rsindex 4186571388..2a7bdff91c 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/error_handlers.rs@@ -17,7 +17,11 @@ pub async fn handle_non_retryable_error(data: &BackfillPubsubMessage,e: &DetailedError,) -> anyhow::Result<()> {- tracing::error!(error = %e, "Non-retryable error processing message. The message will be deleted.");+ tracing::error!(+ error = %e,+ source = { format!("{:#}", e.source) },+ "Non-retryable error processing message. The message will be deleted."+ );match &data.backfill_operation {BackfillOperation::Init | BackfillOperation::ListThreads(_) => {@@ -49,21 +53,23 @@ pub async fn handle_non_retryable_error(}/// Handles retryable errors by updating status to InProgress and adding the error message-#[tracing::instrument(err)]+#[tracing::instrument(skip(_e), err)]pub async fn handle_retryable_error(data: &BackfillPubsubMessage,_e: &DetailedError,) -> anyhow::Result<()> {+ let error_chain = format!("{:#}", _e.source);match &data.backfill_operation {BackfillOperation::Init => {- tracing::debug!("Retryable error in Init")+ tracing::debug!(error = %error_chain, "Retryable error in Init")}BackfillOperation::ListThreads(_) => {- tracing::debug!("Retryable error listing threads")+ tracing::debug!(error = %error_chain, "Retryable error listing threads")}BackfillOperation::BackfillThread(p) => {tracing::debug!(thread_id = %p.thread_provider_id,+ error = %error_chain,"Retryable error backfilling thread");}@@ -71,18 +77,21 @@ pub async fn handle_retryable_error(tracing::debug!(thread_id = %p.thread_provider_id,message_id = %p.message_provider_id,+ error = %error_chain,"Retryable error backfilling message");}BackfillOperation::UpdateThreadMetadata(p) => {tracing::debug!(thread_id = %p.thread_provider_id,- "Retryable error backfilling thread"+ error = %error_chain,+ "Retryable error updating thread metadata");}BackfillOperation::BackfillAttachment(p) => {tracing::debug!(attachment_db_id = %p.metadata.attachment_metadata.attachment_db_id,+ error = %error_chain,"Retryable error backfilling attachment")}diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rsindex 09cebf138f..69e268e260 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/init.rs@@ -1,5 +1,5 @@use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::check_gmail_rate_limit;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use crate::util::process_pre_insert::sync_labels::sync_labels;use crate::util::sync_contacts::sync_contacts;use models_email::email::service::backfill::{@@ -47,12 +47,13 @@ pub async fn init_backfill(let threads_requested_limit = backfill_job.threads_requested_limit;- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::UsersGetProfile,- true,- )+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::UsersGetProfile,+ retryable: true,+ is_backfill: true,+ }).await?;// get the total number of threads the user has in their accountlet total_threads = match ctxdiff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rsindex 008d63a444..d84a0eb47d 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/list_threads.rs@@ -1,5 +1,5 @@use crate::pubsub::context::PubSubContext;-use crate::pubsub::util::check_gmail_rate_limit;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use models_email::email::service::backfill::{BackfillJob, BackfillOperation, BackfillPubsubMessage, BackfillThreadPayload,};@@ -33,12 +33,13 @@ pub async fn list_threads(total_threads - threads_retrieved_count,);- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::ThreadsList,- true,- )+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::ThreadsList,+ retryable: true,+ is_backfill: true,+ }).await?;// get batch of thread idslet thread_list = match ctxdiff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rsindex ae9b48cd3a..46e7d43ddf 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs@@ -1,6 +1,6 @@use crate::pubsub::context::PubSubContext;use crate::pubsub::inbox_sync::process::fetch_pubsub_gmail_token;-use crate::pubsub::util::check_gmail_rate_limit;+use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};use crate::util::process_pre_insert::sync_labels::sync_labels;use models_email::gmail::history::InboxChanges;use models_email::gmail::inbox_sync::{@@ -56,15 +56,16 @@ pub async fn gmail_message(}// ensure user's labels are synced before we start processing changes.- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::LabelsList,+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::LabelsList,// don't retry if rate limited, just wait until the next inbox update comes in. if we're// rate limited it's likely because of a large previous inbox update, so let that get// fully processed before the next one.- false,- )+ retryable: false,+ is_backfill: false,+ }).await?;sync_labels(&ctx.db, &ctx.gmail_client, &gmail_access_token, link.id).await@@ -79,15 +80,16 @@ pub async fn gmail_message(// we pass the db_history_id, aka history_id at the time of the last update. once// we update the database, we set the db history_id to be the message history_id// (the current history_id for the user)- check_gmail_rate_limit(- &ctx.redis_client,- link.id,- GmailApiOperation::HistoryList,+ check_gmail_rate_limit(CheckGmailRateLimitArgs {+ redis_client: &ctx.redis_client,+ link_id: link.id,+ gmail_operation: GmailApiOperation::HistoryList,// don't retry if rate limited, just wait until the next inbox update comes in. if we're// rate limited it's likely because of a large previous inbox update, so let that get// fully processed before the next one.- false,- )+ retryable: false,+ is_backfill: false,+ }).await?;let inbox_changes = ctx.gmail_clientdiff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rsindex eee2029415..a6f9dd8470 100644--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/process.rs@@ -4,6 +4,7 @@ use crate::pubsub::inbox_sync::operations::delete_message::delete_message;use crate::pubsub::inbox_sync::operations::gmail_message::gmail_message;use crate::pubsub::inbox_sync::operations::update_labels::update_labels;use crate::pubsub::inbox_sync::operations::upsert_message::upsert_message;+use crate::util::redis::rate_limit::RateLimitArgs;use anyhow::{Context, Result, anyhow};use models_email::email::service::cache;use models_email::email::service::link::UserProvider;@@ -165,7 +166,15 @@ pub async fn check_gmail_rate_limit_inbox_sync(operation: GmailApiOperation,sync_operation: InboxSyncOperation,) -> result::Result<(), ProcessingError> {- if !ctx.redis_client.is_rate_limited(link_id, operation).await {+ if !ctx+ .redis_client+ .is_rate_limited(RateLimitArgs {+ user_id: link_id,+ operation,+ is_backfill: false,+ })+ .await+ {// Not rate limited, continue processingreturn Ok(());}diff --git a/rust/cloud-storage/email_service/src/pubsub/util.rs b/rust/cloud-storage/email_service/src/pubsub/util.rsindex a9978c2008..4d4dffc2cc 100644--- a/rust/cloud-storage/email_service/src/pubsub/util.rs+++ b/rust/cloud-storage/email_service/src/pubsub/util.rs@@ -1,5 +1,6 @@use crate::util::gmail::auth::fetch_gmail_access_token;use crate::util::redis::RedisClient;+use crate::util::redis::rate_limit::RateLimitArgs;use anyhow::anyhow;use authentication_service_client::AuthServiceClient;use connection_gateway_client::client::ConnectionGatewayClient;@@ -11,15 +12,29 @@ use models_email::service::link::Link;use sqlx::PgPool;use uuid::Uuid;+/// Arguments for checking Gmail API rate limits+pub struct CheckGmailRateLimitArgs<'a> {+ pub redis_client: &'a RedisClient,+ pub link_id: Uuid,+ pub gmail_operation: GmailApiOperation,+ pub retryable: bool,+ pub is_backfill: bool,+}+// check if we are rate limited by gmail before making any requests to the apipub async fn check_gmail_rate_limit(- redis_client: &RedisClient,- link_id: Uuid,- gmail_operation: GmailApiOperation,- retryable: bool, // true for backfill, false for inbox sync (avoid thundering herd if there is an issue)+ args: CheckGmailRateLimitArgs<'_>,) -> Result<(), ProcessingError> {- if redis_client.is_rate_limited(link_id, gmail_operation).await {- return if retryable {+ if args+ .redis_client+ .is_rate_limited(RateLimitArgs {+ user_id: args.link_id,+ operation: args.gmail_operation,+ is_backfill: args.is_backfill,+ })+ .await+ {+ return if args.retryable {Err(ProcessingError::Retryable(DetailedError {reason: FailureReason::GmailApiRateLimited,source: anyhow::Error::msg("Gmail API rate limit exceeded"),diff --git a/rust/cloud-storage/email_service/src/util/redis/mod.rs b/rust/cloud-storage/email_service/src/util/redis/mod.rsindex fb50324695..500e61c23c 100644--- a/rust/cloud-storage/email_service/src/util/redis/mod.rs+++ b/rust/cloud-storage/email_service/src/util/redis/mod.rs@@ -6,20 +6,31 @@ pub mod rate_limit;pub struct RedisClient {pub inner: redis::Client,- /// Maximum allowed Gmail API quota units within the rate limiting window.+ /// Maximum allowed Gmail API quota units within the rate limiting window, for normal operations./// Gmail API per-user quota is 15,000 units per minute.pub rate_limit_units: u32,+ /// Maximum allowed Gmail API quota units within the rate limiting window, for backfill. Less+ /// than redis_rate_limit_reqs so we have room for normal gmail operations while backfilling+ /// is occurring+ pub rate_limit_units_backfill: u32,+/// Duration of the sliding window for Gmail API rate limiting in seconds./// Uses a 60-second window to align with Gmail's per-minute quota period.pub rate_limit_secs: u32,}impl RedisClient {- pub fn new(inner: redis::Client, rate_limit_units: u32, rate_limit_secs: u32) -> Self {+ pub fn new(+ inner: redis::Client,+ rate_limit_units: u32,+ rate_limit_units_backfill: u32,+ rate_limit_secs: u32,+ ) -> Self {Self {inner,rate_limit_units,+ rate_limit_units_backfill,rate_limit_secs,}}diff --git a/rust/cloud-storage/email_service/src/util/redis/rate_limit.rs b/rust/cloud-storage/email_service/src/util/redis/rate_limit.rsindex 4b45f5f27e..fb8ae5c15f 100644--- a/rust/cloud-storage/email_service/src/util/redis/rate_limit.rs+++ b/rust/cloud-storage/email_service/src/util/redis/rate_limit.rs@@ -4,6 +4,12 @@ use redis::Script;use std::time::{SystemTime, UNIX_EPOCH};use uuid::Uuid;+pub struct RateLimitArgs {+ pub user_id: Uuid,+ pub operation: GmailApiOperation,+ pub is_backfill: bool,+}+impl RedisClient {/// Checks if a Gmail API operation is rate-limited and returns the status./// Uses a 60-second sliding window implemented via a Lua script for efficiency and atomicity.@@ -18,7 +24,20 @@ impl RedisClient {/// # Returns/// Returns `true` if the operation should be rate limited (blocked), `false` otherwise.///- pub async fn is_rate_limited(&self, user_id: Uuid, operation: GmailApiOperation) -> bool {+ pub async fn is_rate_limited(&self, args: RateLimitArgs) -> bool {+ let RateLimitArgs {+ user_id,+ operation,+ is_backfill,+ } = args;+ // If we're backfilling, use a lower rate limit than if we are not. This is to allow some room+ // for normal inbox operations while backfill is occurring.+ let rate_limit_units = if is_backfill {+ self.rate_limit_units_backfill+ } else {+ self.rate_limit_units+ };+let cost = operation.cost();let mut con = match self.inner.get_multiplexed_async_connection().await {Ok(conn) => conn,@@ -45,7 +64,7 @@ impl RedisClient {let (is_limited, _current_units): (i32, u32) = match script.key(&redis_key)- .arg(self.rate_limit_units)+ .arg(rate_limit_units).arg(self.rate_limit_secs * 1_000_000).arg(now_micros).arg(cost)diff --git a/rust/cloud-storage/email_service/src/util/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rsindex 68fdb6b868..d10711c2ef 100644--- a/rust/cloud-storage/email_service/src/util/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -1,6 +1,5 @@-use crate::pubsub::util::check_gmail_rate_limit;use crate::util::redis::RedisClient;-use anyhow::{Context, anyhow};+use crate::util::redis::rate_limit::RateLimitArgs;use base64::Engine;use base64::engine::general_purpose::STANDARD;use document_storage_service_client::DocumentStorageServiceClient;@@ -20,8 +19,47 @@ use system_properties::{EmailAttachmentInput, EmailAttachmentProperty, PgSystemPropertiesRepository, SourceEntity,SystemPropertiesService, SystemPropertiesServiceImpl,};+use thiserror::Error;use uuid::Uuid;+#[derive(Error, Debug)]+pub enum UploadAttachmentError {+ #[error("Rate limit check failed: {0}")]+ RateLimitCheckFailed(String),++ #[error("Failed to fetch attachment data from Gmail: {0}")]+ GmailFetchFailed(String),++ #[error("Failed to upload media to SFS: {0}")]+ SfsUploadFailed(String),++ #[error("Parse error: {0}")]+ ParseError(String),++ #[error("Database error: {0}")]+ DatabaseError(String),++ #[error("Attachment filename is missing")]+ FilenameMissing,++ #[error(+ "Failed to determine file extension from mime type ({mime_type}) or filename ({filename})"+ )]+ FileExtensionDeterminationFailed { mime_type: String, filename: String },++ #[error("Failed to create document record in DSS: {0}")]+ DssCreateFailed(String),++ #[error("DSS response did not include a presigned URL")]+ PresignedUrlMissing,++ #[error("Failed to upload attachment to presigned URL. Status: {0}, Body: {1}")]+ PresignedUrlUploadFailed(reqwest::StatusCode, String),++ #[error("Failed to set email attachment properties: {0}")]+ SystemPropertiesSetFailed(String),+}+/// Context required for uploading an email attachment.pub struct UploadAttachmentContext<'a> {pub db: &'a sqlx::Pool<sqlx::Postgres>,@@ -36,20 +74,25 @@ pub struct UploadAttachmentContext<'a> {}/// Upload an email attachment to DSS as a document or SFS as media.-#[tracing::instrument(skip(ctx, args), err)]+#[tracing::instrument(skip(ctx), err)]pub async fn upload_attachment(ctx: UploadAttachmentContext<'_>,args: &AttachmentUploadArgs,-) -> anyhow::Result<String> {+) -> Result<String, UploadAttachmentError> {// 1. Check rate limits before making a Gmail API call.- check_gmail_rate_limit(- ctx.redis_client,- ctx.link.id,- GmailApiOperation::MessagesAttachmentsGet,- true,- )- .await- .context("Rate limit check failed")?;+ if ctx+ .redis_client+ .is_rate_limited(RateLimitArgs {+ user_id: ctx.link.id,+ operation: GmailApiOperation::MessagesAttachmentsGet,+ is_backfill: args.backfill,+ })+ .await+ {+ return Err(UploadAttachmentError::RateLimitCheckFailed(+ "Gmail API rate limit exceeded".to_string(),+ ));+ }// 2. Fetch the raw attachment data from Gmail.let attachment_data = fetch_gmail_attachment_data(@@ -78,17 +121,19 @@ async fn upload_media_attachment(args: &AttachmentUploadArgs,attachment_data: Vec<u8>,mime_type: String,-) -> anyhow::Result<String> {+) -> Result<String, UploadAttachmentError> {// Upload to SFSlet sfs_response = ctx.sfs_client.put_file_with_bytes("a", bytes::Bytes::from(attachment_data), mime_type).await- .context("Failed to upload media to SFS")?;+ .map_err(|e| UploadAttachmentError::SfsUploadFailed(e.to_string()))?;// Store metadata in email_attachments_sfs tablelet attachment_sfs_id = macro_uuid::generate_uuid_v7();- let sfs_id = Uuid::parse_str(&sfs_response.id).context("Failed to parse SFS ID as UUID")?;+ let sfs_id = Uuid::parse_str(&sfs_response.id).map_err(|e| {+ UploadAttachmentError::ParseError(format!("Failed to parse SFS ID as UUID: {}", e))+ })?;email_db_client::attachments::sfs::insert_attachment_sfs(ctx.db,@@ -98,7 +143,8 @@ async fn upload_media_attachment(sfs_id,},)- .await?;+ .await+ .map_err(|e| UploadAttachmentError::DatabaseError(e.to_string()))?;Ok(sfs_response.id)}@@ -109,7 +155,7 @@ async fn upload_document_attachment(ctx: &UploadAttachmentContext<'_>,args: &AttachmentUploadArgs,attachment_data: Vec<u8>,-) -> anyhow::Result<String> {+) -> Result<String, UploadAttachmentError> {// 1. Calculate hashes required for the upload process.let (hex_hash, base64_hash) = calculate_hashes(&attachment_data);@@ -150,7 +196,7 @@ async fn fetch_gmail_attachment_data(gmail_client: &GmailClient,access_token: &str,p: &AttachmentUploadMetadata,-) -> anyhow::Result<Vec<u8>> {+) -> Result<Vec<u8>, UploadAttachmentError> {gmail_client.get_attachment_data(access_token,@@ -158,7 +204,7 @@ async fn fetch_gmail_attachment_data(&p.provider_attachment_id,).await- .context("Failed to fetch attachment data from Gmail")+ .map_err(|e| UploadAttachmentError::GmailFetchFailed(e.to_string()))}/// Calculates the SHA256 hash of the attachment data in both hex and base64 formats.@@ -174,12 +220,14 @@ fn calculate_hashes(data: &[u8]) -> (String, String) {}/// Determines the file name (without extension) and file type (extension) from the payload.-fn determine_file_metadata(p: &AttachmentUploadMetadata) -> anyhow::Result<(String, String)> {+fn determine_file_metadata(+ p: &AttachmentUploadMetadata,+) -> Result<(String, String), UploadAttachmentError> {// documents must have a file name to be inserted into Document table.let original_file_name = p.filename.as_deref()- .context("attachment filename is missing")?;+ .ok_or(UploadAttachmentError::FilenameMissing)?;let file_name = original_file_name.split('.')@@ -204,12 +252,9 @@ fn determine_file_metadata(p: &AttachmentUploadMetadata) -> anyhow::Result<(Stri.filter(|ext| !ext.is_empty()).map(|ext| ext.to_string())})- .ok_or_else(|| {- anyhow!(- "Failed to determine file extension from mime type ({}) or filename ({})",- p.mime_type,- original_file_name- )+ .ok_or_else(|| UploadAttachmentError::FileExtensionDeterminationFailed {+ mime_type: p.mime_type.clone(),+ filename: original_file_name.to_string(),})?,};@@ -226,7 +271,7 @@ async fn create_dss_document_record(file_name: &str,file_type: &str,backfill: bool,-) -> anyhow::Result<CreateDocumentResponse> {+) -> Result<CreateDocumentResponse, UploadAttachmentError> {// if we are backfilling, use the email timestamp. if it's an on-demand upload, use the current// time so the document shows up at the top of soup views.let created_at = backfill.then_some(p.internal_date_ts);@@ -250,7 +295,7 @@ async fn create_dss_document_record(dss_client.create_document_internal(request, link.macro_id.0.as_ref()).await- .map_err(|e| anyhow::anyhow!("Failed to create document record in DSS: {}", e))+ .map_err(|e| UploadAttachmentError::DssCreateFailed(e.to_string()))}/// Uploads the provided data to the presigned URL from the DSS response.@@ -258,13 +303,13 @@ async fn upload_data_to_presigned_url(dss_response: &CreateDocumentResponse,attachment_data: Vec<u8>,base64_hash: &str,-) -> anyhow::Result<()> {+) -> Result<(), UploadAttachmentError> {let presigned_url = dss_response.data.document_response.presigned_url.as_ref()- .context("DSS response did not include a presigned URL")?;+ .ok_or(UploadAttachmentError::PresignedUrlMissing)?;let response = reqwest::Client::new().put(presigned_url)@@ -273,15 +318,18 @@ async fn upload_data_to_presigned_url(.body(attachment_data).send().await- .context("HTTP PUT request to presigned URL failed")?;+ .map_err(|e| {+ UploadAttachmentError::PresignedUrlUploadFailed(+ reqwest::StatusCode::INTERNAL_SERVER_ERROR,+ e.to_string(),+ )+ })?;if !response.status().is_success() {let status = response.status();let body = response.text().await.unwrap_or_default();- return Err(anyhow!(- "Failed to upload attachment to presigned url: {} {}",- status,- body+ return Err(UploadAttachmentError::PresignedUrlUploadFailed(+ status, body,));}@@ -294,14 +342,14 @@ async fn set_email_attachment_properties(system_properties_service: &Arc<SystemPropertiesServiceImpl<PgSystemPropertiesRepository>>,document_id: &str,p: &AttachmentUploadArgs,-) -> anyhow::Result<()> {+) -> Result<(), UploadAttachmentError> {let sender_email = format!("macro|{}", p.attachment_metadata.sender_email);let sender = MacroUserId::parse_from_str(&sender_email)- .with_context(|| {- format!(- "Failed to parse sender email {} into macro user id",- p.attachment_metadata.sender_email- )+ .map_err(|e| {+ UploadAttachmentError::ParseError(format!(+ "Failed to parse sender email {} into macro user id: {}",+ p.attachment_metadata.sender_email, e+ ))})?.lowercase();@@ -315,11 +363,11 @@ async fn set_email_attachment_properties(let recipients: Result<Vec<MacroUserId<ArcCowStr>>, _> = prefixed_emails.iter().map(|email| {- MacroUserId::parse_from_str(email).with_context(|| {- format!(- "Failed to parse recipient email {} into macro user id",- )+ MacroUserId::parse_from_str(email).map_err(|e| {+ UploadAttachmentError::ParseError(format!(+ "Failed to parse recipient email {} into macro user id: {}",+ email, e+ ))})}).collect();@@ -343,7 +391,7 @@ async fn set_email_attachment_properties(},}]).await- .context("Failed to set email attachment properties")?;+ .map_err(|e| UploadAttachmentError::SystemPropertiesSetFailed(e.to_string()))?;Ok(())}