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): add gmail_ops worker for async Gmail API operations with rate limit retry (#2226)

Evan Hutnik68e92fdf7f31
diff --git a/infra/stacks/email-service/Pulumi.dev.yaml b/infra/stacks/email-service/Pulumi.dev.yaml
index 3840228fd7..bd7768fc21 100644
--- a/infra/stacks/email-service/Pulumi.dev.yaml
+++ b/infra/stacks/email-service/Pulumi.dev.yaml
@@ -17,8 +17,12 @@ config:
email-service:backfill_queue_max_messages: 1
email-service:inbox_sync_queue_workers: 25
email-service:inbox_sync_queue_max_messages: 1
- email-service:inbox_sync_retry_queue_workers: 15
+ email-service:inbox_sync_retry_queue_workers: 1
email-service:inbox_sync_retry_queue_max_messages: 1
+ email-service:gmail_ops_queue_workers: 1
+ email-service:gmail_ops_queue_max_messages: 1
+ email-service:gmail_ops_retry_queue_workers: 1
+ email-service:gmail_ops_retry_queue_max_messages: 1
email-service:sfs_uploader_workers: 3
email-service:presigned_url_ttl_secs: 3600
email-service:gmail_gcp_queue: gmail-gcp-queue-dev
diff --git a/infra/stacks/email-service/Pulumi.prod.yaml b/infra/stacks/email-service/Pulumi.prod.yaml
index 7142e91709..cd39394b9d 100644
--- a/infra/stacks/email-service/Pulumi.prod.yaml
+++ b/infra/stacks/email-service/Pulumi.prod.yaml
@@ -17,8 +17,12 @@ config:
email-service:backfill_queue_max_messages: 1
email-service:inbox_sync_queue_workers: 25
email-service:inbox_sync_queue_max_messages: 1
- email-service:inbox_sync_retry_queue_workers: 15
+ email-service:inbox_sync_retry_queue_workers: 5
email-service:inbox_sync_retry_queue_max_messages: 1
+ email-service:gmail_ops_queue_workers: 25
+ email-service:gmail_ops_queue_max_messages: 1
+ email-service:gmail_ops_retry_queue_workers: 5
+ email-service:gmail_ops_retry_queue_max_messages: 1
email-service:sfs_uploader_workers: 3
email-service:presigned_url_ttl_secs: 3600
email-service:gmail_gcp_queue: gmail-gcp-queue-prod
diff --git a/infra/stacks/email-service/index.ts b/infra/stacks/email-service/index.ts
index 500c4d18aa..131a134faf 100644
--- a/infra/stacks/email-service/index.ts
+++ b/infra/stacks/email-service/index.ts
@@ -65,6 +65,16 @@ const INBOX_SYNC_RETRY_QUEUE_WORKERS = config.require(
const INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES = config.require(
`inbox_sync_retry_queue_max_messages`
);
+const GMAIL_OPS_QUEUE_WORKERS = config.require(`gmail_ops_queue_workers`);
+const GMAIL_OPS_QUEUE_MAX_MESSAGES = config.require(
+ `gmail_ops_queue_max_messages`
+);
+const GMAIL_OPS_RETRY_QUEUE_WORKERS = config.require(
+ `gmail_ops_retry_queue_workers`
+);
+const GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES = config.require(
+ `gmail_ops_retry_queue_max_messages`
+);
const SFS_UPLOADER_WORKERS = config.require(`sfs_uploader_workers`);
const gmailGcpQueue = config.require(`gmail_gcp_queue`);
const GMAIL_GCP_QUEUE = aws.secretsmanager
@@ -153,7 +163,7 @@ const macroDbUrlArn: pulumi.Output<string> = aws.secretsmanager
const inbox_sync_queue = new Queue('email-service-gmail-webhook', {
tags,
- maxReceiveCount: 5,
+ maxReceiveCount: 3,
visibilityTimeoutSeconds: 60,
});
@@ -169,6 +179,24 @@ const inbox_sync_retry_queue = new Queue('email-service-gmail-webhook-retry', {
export const inboxSyncRetryQueueArn = pulumi.interpolate`${inbox_sync_retry_queue.queue.arn}`;
export const inboxSyncRetryQueueName = pulumi.interpolate`${inbox_sync_retry_queue.queue.name}`;
+const gmail_ops_queue = new Queue('email-service-gmail-ops', {
+ tags,
+ maxReceiveCount: 3,
+ visibilityTimeoutSeconds: 60,
+});
+
+export const gmailOpsQueueArn = pulumi.interpolate`${gmail_ops_queue.queue.arn}`;
+export const gmailOpsQueueName = pulumi.interpolate`${gmail_ops_queue.queue.name}`;
+
+const gmail_ops_retry_queue = new Queue('email-service-gmail-ops-retry', {
+ tags,
+ maxReceiveCount: 100,
+ visibilityTimeoutSeconds: 60,
+});
+
+export const gmailOpsRetryQueueArn = pulumi.interpolate`${gmail_ops_retry_queue.queue.arn}`;
+export const gmailOpsRetryQueueName = pulumi.interpolate`${gmail_ops_retry_queue.queue.name}`;
+
const link_manager_queue = new Queue('email-service-refresh', {
tags,
// deleting a link from the database can sometimes take a long time
@@ -249,6 +277,8 @@ const queueArns = [
notificationIngressQueueArn,
inboxSyncQueueArn,
inboxSyncRetryQueueArn,
+ gmailOpsQueueArn,
+ gmailOpsRetryQueueArn,
linkManagerQueueArn,
scheduledQueueArn,
searchEventQueueArn,
@@ -375,6 +405,14 @@ const containerEnvVars = [
name: 'GMAIL_INBOX_SYNC_RETRY_QUEUE',
value: inboxSyncRetryQueueName,
},
+ {
+ name: 'GMAIL_OPS_QUEUE',
+ value: gmailOpsQueueName,
+ },
+ {
+ name: 'GMAIL_OPS_RETRY_QUEUE',
+ value: gmailOpsRetryQueueName,
+ },
{
name: 'BACKFILL_QUEUE',
value: backfillQueueName,
@@ -479,6 +517,22 @@ const containerEnvVars = [
name: 'INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES',
value: pulumi.interpolate`${INBOX_SYNC_RETRY_QUEUE_MAX_MESSAGES}`,
},
+ {
+ name: 'GMAIL_OPS_QUEUE_WORKERS',
+ value: pulumi.interpolate`${GMAIL_OPS_QUEUE_WORKERS}`,
+ },
+ {
+ name: 'GMAIL_OPS_QUEUE_MAX_MESSAGES',
+ value: pulumi.interpolate`${GMAIL_OPS_QUEUE_MAX_MESSAGES}`,
+ },
+ {
+ name: 'GMAIL_OPS_RETRY_QUEUE_WORKERS',
+ value: pulumi.interpolate`${GMAIL_OPS_RETRY_QUEUE_WORKERS}`,
+ },
+ {
+ name: 'GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES',
+ value: pulumi.interpolate`${GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES}`,
+ },
{
name: 'SFS_UPLOADER_WORKERS',
value: pulumi.interpolate`${SFS_UPLOADER_WORKERS}`,
diff --git a/js/app/packages/queries/email/thread.ts b/js/app/packages/queries/email/thread.ts
index a6d5108188..826a756425 100644
--- a/js/app/packages/queries/email/thread.ts
+++ b/js/app/packages/queries/email/thread.ts
@@ -383,15 +383,7 @@ export async function blockSenderWithToast(senderEmail: string) {
});
if (isErr(result)) {
- if (result[0].some((e) => e.code === 'FORBIDDEN')) {
- toast.failure(
- 'Insufficient permissions',
- 'Enable new email permissions on sign-in.',
- 5_000
- );
- } else {
- toast.failure('Failed to block sender', senderEmail);
- }
+ toast.failure('Failed to block sender', senderEmail);
return;
}
diff --git a/js/app/packages/service-clients/service-email/client.ts b/js/app/packages/service-clients/service-email/client.ts
index 4d9b7c3739..d21c30ebd4 100644
--- a/js/app/packages/service-clients/service-email/client.ts
+++ b/js/app/packages/service-clients/service-email/client.ts
@@ -14,7 +14,6 @@ import type {
AddDraftAttachmentRequest,
AddDraftAttachmentResponse,
ApiPaginatedThreadCursor,
- BlockSenderResponse,
CreateDraftRequest,
CreateDraftResponse,
GetAttachmentDocumentIDResponse,
@@ -340,13 +339,10 @@ export const emailClient = {
);
},
async blockSender(args: { email_address: string }) {
- return mapOk(
- await emailFetch<BlockSenderResponse>('/email/contacts/block', {
- method: 'POST',
- body: JSON.stringify({ email_address: args.email_address }),
- }),
- (result) => result
- );
+ return emailFetch('/email/contacts/block', {
+ method: 'POST',
+ body: JSON.stringify({ email_address: args.email_address }),
+ });
},
async unblockSender(args: { email_address: string }) {
return emailFetch('/email/contacts/unblock', {
diff --git a/js/app/packages/service-clients/service-email/generated/client.ts b/js/app/packages/service-clients/service-email/generated/client.ts
index c2a36a3443..acae0886ed 100644
--- a/js/app/packages/service-clients/service-email/generated/client.ts
+++ b/js/app/packages/service-clients/service-email/generated/client.ts
@@ -12,7 +12,6 @@ import type {
ApiPaginatedThreadCursor,
ArchiveThreadRequest,
BlockSenderRequest,
- BlockSenderResponse,
CancelBackfillParams,
CreateDraftRequest,
CreateDraftResponse,
@@ -445,10 +444,11 @@ export const listContacts = async (
/**
* @summary Block a sender by creating a Gmail filter that sends their emails to trash.
+The actual Gmail API call is performed asynchronously by the gmail_ops worker.
*/
-export type blockSenderResponse201 = {
- data: BlockSenderResponse;
- status: 201;
+export type blockSenderResponse200 = {
+ data: void;
+ status: 200;
};
export type blockSenderResponse400 = {
@@ -461,29 +461,17 @@ export type blockSenderResponse401 = {
status: 401;
};
-export type blockSenderResponse403 = {
- data: ErrorResponse;
- status: 403;
-};
-
-export type blockSenderResponse409 = {
- data: ErrorResponse;
- status: 409;
-};
-
export type blockSenderResponse500 = {
data: ErrorResponse;
status: 500;
};
-export type blockSenderResponseSuccess = blockSenderResponse201 & {
+export type blockSenderResponseSuccess = blockSenderResponse200 & {
headers: Headers;
};
export type blockSenderResponseError = (
| blockSenderResponse400
| blockSenderResponse401
- | blockSenderResponse403
- | blockSenderResponse409
| blockSenderResponse500
) & {
headers: Headers;
@@ -581,6 +569,7 @@ export const listBlockedSenders = async (
/**
* @summary Unblock a sender by removing their block filter from Gmail.
+The actual Gmail API call is performed asynchronously by the gmail_ops worker.
*/
export type unblockSenderResponse204 = {
data: void;
@@ -597,16 +586,6 @@ export type unblockSenderResponse401 = {
status: 401;
};
-export type unblockSenderResponse403 = {
- data: ErrorResponse;
- status: 403;
-};
-
-export type unblockSenderResponse404 = {
- data: ErrorResponse;
- status: 404;
-};
-
export type unblockSenderResponse500 = {
data: ErrorResponse;
status: 500;
@@ -618,8 +597,6 @@ export type unblockSenderResponseSuccess = unblockSenderResponse204 & {
export type unblockSenderResponseError = (
| unblockSenderResponse400
| unblockSenderResponse401
- | unblockSenderResponse403
- | unblockSenderResponse404
| unblockSenderResponse500
) & {
headers: Headers;
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts
deleted file mode 100644
index d14ee57970..0000000000
--- a/js/app/packages/service-clients/service-email/generated/schemas/blockSenderResponse.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * email_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Response after blocking a sender.
- */
-export interface BlockSenderResponse {
- /** The ID of the filter created in Gmail. */
- filter_id: string;
-}
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
index 24c4820116..dc3e473cf3 100644
--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts
@@ -140,7 +140,6 @@ export * from './backfillJobLinkId';
export * from './backfillJobStatus';
export * from './backfillJobThreadsRequestedLimit';
export * from './blockSenderRequest';
-export * from './blockSenderResponse';
export * from './cancelBackfillParams';
export * from './contact';
export * from './contactEmailAddress';
diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.json
index 2499891a71..c2c8599c02 100644
--- a/js/app/packages/service-clients/service-email/openapi.json
+++ b/js/app/packages/service-clients/service-email/openapi.json
@@ -373,7 +373,7 @@
"/email/contacts/block": {
"post": {
"tags": ["Contacts"],
- "summary": "Block a sender by creating a Gmail filter that sends their emails to trash.",
+ "summary": "Block a sender by creating a Gmail filter that sends their emails to trash.\nThe actual Gmail API call is performed asynchronously by the gmail_ops worker.",
"operationId": "block_sender",
"requestBody": {
"content": {
@@ -386,15 +386,8 @@
"required": true
},
"responses": {
- "201": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/BlockSenderResponse"
- }
- }
- }
+ "200": {
+ "description": ""
},
"400": {
"description": "",
@@ -416,26 +409,6 @@
}
}
},
- "403": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "409": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -501,7 +474,7 @@
"/email/contacts/unblock": {
"post": {
"tags": ["Contacts"],
- "summary": "Unblock a sender by removing their block filter from Gmail.",
+ "summary": "Unblock a sender by removing their block filter from Gmail.\nThe actual Gmail API call is performed asynchronously by the gmail_ops worker.",
"operationId": "unblock_sender",
"requestBody": {
"content": {
@@ -537,26 +510,6 @@
}
}
},
- "403": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
- "404": {
- "description": "",
- "content": {
- "application/json": {
- "schema": {
- "$ref": "#/components/schemas/ErrorResponse"
- }
- }
- }
- },
"500": {
"description": "",
"content": {
@@ -3692,17 +3645,6 @@
}
}
},
- "BlockSenderResponse": {
- "type": "object",
- "description": "Response after blocking a sender.",
- "required": ["filter_id"],
- "properties": {
- "filter_id": {
- "type": "string",
- "description": "The ID of the filter created in Gmail."
- }
- }
- },
"CancelBackfillParams": {
"type": "object",
"required": ["job_id"],
diff --git a/rust/cloud-storage/ai_tools/src/tool_context.rs b/rust/cloud-storage/ai_tools/src/tool_context.rs
index 8f0e7e8b5b..560f43cd0d 100644
--- a/rust/cloud-storage/ai_tools/src/tool_context.rs
+++ b/rust/cloud-storage/ai_tools/src/tool_context.rs
@@ -35,12 +35,8 @@ pub type ToolScribe =
pub type ToolFrecencyService = FrecencyQueryServiceImpl<FrecencyPgStorage>;
/// Type alias for the email service implementation
-pub type ToolEmailService = EmailServiceImpl<
- EmailPgRepo,
- ToolFrecencyService,
- email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
->;
+pub type ToolEmailService =
+ EmailServiceImpl<EmailPgRepo, ToolFrecencyService, email::domain::ports::NoOpEnqueuer>;
/// Type alias for the comms/channels service implementation
pub type ToolCommsService = ChannelServiceImpl<PgCommsRepo, PgUserRepo, FrecencyPgStorage>;
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index d72f60f73e..e16f292a86 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -190,7 +190,6 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
EmailPgRepo::new(pool.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
let user_repo = PgUserRepo::new(pool.clone());
diff --git a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
index 0e0544a9f4..4ce92f1a53 100644
--- a/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
+++ b/rust/cloud-storage/document_cognition_service/src/bin/mcp_server.rs
@@ -157,7 +157,6 @@ async fn main() -> anyhow::Result<()> {
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
let channels_service = ChannelServiceImpl::new(
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index fee908aede..8c11830057 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -150,7 +150,6 @@ async fn main() -> anyhow::Result<()> {
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
let channels_service = ChannelServiceImpl::new(
diff --git a/rust/cloud-storage/document_storage_service/src/api/context.rs b/rust/cloud-storage/document_storage_service/src/api/context.rs
index fb6affa7c8..25fc14f4bd 100644
--- a/rust/cloud-storage/document_storage_service/src/api/context.rs
+++ b/rust/cloud-storage/document_storage_service/src/api/context.rs
@@ -68,7 +68,6 @@ type DssEmailService = EmailServiceImpl<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
>;
type DssSoupState = SoupRouterState<
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 473d2e001e..2fede74f93 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -229,14 +229,12 @@ async fn main() -> anyhow::Result<()> {
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
let readonly_email_service = ReadonlyEmailPreviewAdapter(EmailServiceImpl::new(
EmailPgRepo::new(readonly_db.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
));
let system_properties_service =
diff --git a/rust/cloud-storage/email/examples/ai_tools_cli.rs b/rust/cloud-storage/email/examples/ai_tools_cli.rs
index 57973f1d99..df477a588d 100644
--- a/rust/cloud-storage/email/examples/ai_tools_cli.rs
+++ b/rust/cloud-storage/email/examples/ai_tools_cli.rs
@@ -20,7 +20,7 @@ use ai::tool::types::RequestContext;
use ai::types::Model;
use email::domain::service::EmailServiceImpl;
use email::inbound::toolset::{EmailToolContext, email_toolset};
-use email::outbound::{EmailPgRepo, GmailClientLabelModifier, GmailTokenProviderImpl};
+use email::outbound::{EmailPgRepo, GmailTokenProviderImpl};
use frecency::domain::services::FrecencyQueryServiceImpl;
use frecency::outbound::postgres::FrecencyPgStorage;
use macro_user_id::user_id::MacroUserIdStr;
@@ -68,9 +68,6 @@ async fn main() {
let gmail_token_provider =
Arc::new(GmailTokenProviderImpl::new(redis_conn, auth_service_client));
- let gmail_client = Arc::new(gmail_client::GmailClient::new("unused".to_string()));
- let gmail_label_modifier = GmailClientLabelModifier::new(gmail_client);
-
let frecency_storage = FrecencyPgStorage::new(pool.clone());
let frecency_service = FrecencyQueryServiceImpl::new(frecency_storage);
@@ -85,7 +82,6 @@ async fn main() {
email_repo,
frecency_service,
email::domain::ports::NoOpEnqueuer,
- gmail_label_modifier,
0,
);
diff --git a/rust/cloud-storage/email/src/domain/models/error.rs b/rust/cloud-storage/email/src/domain/models/error.rs
index 78b618c989..5377e2f4eb 100644
--- a/rust/cloud-storage/email/src/domain/models/error.rs
+++ b/rust/cloud-storage/email/src/domain/models/error.rs
@@ -44,6 +44,9 @@ pub enum EmailErr {
/// The caller does not have permission to perform this action.
#[error("You do not have permission to perform this action")]
Unauthorized,
+ /// Failed to enqueue a message to a worker queue.
+ #[error("Enqueue error: {0}")]
+ EnqueueErr(anyhow::Error),
/// Invalid email filter input.
#[error("{0}")]
InvalidEmailFilter(String),
diff --git a/rust/cloud-storage/email/src/domain/ports.rs b/rust/cloud-storage/email/src/domain/ports.rs
index 9cf088021a..696c92e841 100644
--- a/rust/cloud-storage/email/src/domain/ports.rs
+++ b/rust/cloud-storage/email/src/domain/ports.rs
@@ -28,6 +28,15 @@ pub trait EmailMessageEnqueuer: Send + Sync + 'static {
message_id: Uuid,
delay_seconds: Option<i32>,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Enqueue a batch of Gmail label modification operations to the gmail_ops worker queue.
+ fn enqueue_gmail_ops_modify_labels_batch(
+ &self,
+ link_id: Uuid,
+ messages: Vec<(Uuid, String)>,
+ labels_to_add: Vec<String>,
+ labels_to_remove: Vec<String>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
}
pub trait EmailRepo: Send + Sync + 'static {
@@ -384,18 +393,6 @@ pub trait EmailService: Send + Sync + 'static {
) -> impl Future<Output = Result<Vec<EmailFilter>, EmailErr>> + Send;
}
-/// Port for modifying Gmail message labels via the provider API.
-pub trait GmailLabelModifier: Send + Sync + 'static {
- /// Add and remove labels on a single message identified by its provider message ID.
- fn modify_message_labels(
- &self,
- access_token: &str,
- provider_message_id: &str,
- label_ids_to_add: &[String],
- label_ids_to_remove: &[String],
- ) -> impl Future<Output = Result<(), EmailErr>> + Send;
-}
-
/// Port for fetching a Gmail access token for a given email link.
///
/// The domain service receives the token as an opaque `&str`. This trait
@@ -433,22 +430,6 @@ impl GmailTokenProvider for NoOpGmailTokenProvider {
}
}
-/// No-op label modifier for callers that don't need Gmail label operations.
-#[derive(Clone)]
-pub struct NoOpGmailLabelModifier;
-
-impl GmailLabelModifier for NoOpGmailLabelModifier {
- async fn modify_message_labels(
- &self,
- _access_token: &str,
- _provider_message_id: &str,
- _label_ids_to_add: &[String],
- _label_ids_to_remove: &[String],
- ) -> Result<(), EmailErr> {
- Ok(())
- }
-}
-
/// No-op enqueuer for callers that don't need send capability.
#[derive(Clone)]
pub struct NoOpEnqueuer;
@@ -464,4 +445,14 @@ impl EmailMessageEnqueuer for NoOpEnqueuer {
) -> Result<(), Self::Err> {
Ok(())
}
+
+ async fn enqueue_gmail_ops_modify_labels_batch(
+ &self,
+ _link_id: Uuid,
+ _messages: Vec<(Uuid, String)>,
+ _labels_to_add: Vec<String>,
+ _labels_to_remove: Vec<String>,
+ ) -> Result<(), Self::Err> {
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/email/src/domain/service/draft.rs b/rust/cloud-storage/email/src/domain/service/draft.rs
index 50682fb6a2..8464dc4539 100644
--- a/rust/cloud-storage/email/src/domain/service/draft.rs
+++ b/rust/cloud-storage/email/src/domain/service/draft.rs
@@ -12,7 +12,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/mod.rs b/rust/cloud-storage/email/src/domain/service/mod.rs
index 19b8985340..7bfc92308e 100644
--- a/rust/cloud-storage/email/src/domain/service/mod.rs
+++ b/rust/cloud-storage/email/src/domain/service/mod.rs
@@ -10,7 +10,7 @@ use crate::domain::{
GetEmailsRequest, Link, LinkLabel, ParsedThread, Thread, UpdateThreadLabelsResult,
UpsertEmailFilterInput,
},
- ports::{EmailMessageEnqueuer, EmailRepo, EmailService, GmailLabelModifier},
+ ports::{EmailMessageEnqueuer, EmailRepo, EmailService},
};
use entity_access::domain::models::{
AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, ViewAccessLevel,
@@ -20,39 +20,35 @@ use models_pagination::{PaginatedCursor, SimpleSortMethod};
use uuid::Uuid;
#[derive(Clone)]
-pub struct EmailServiceImpl<T, U, E, G> {
+pub struct EmailServiceImpl<T, U, E> {
email_repo: T,
frecency_service: U,
enqueuer: E,
- gmail_label_modifier: G,
sent_undo_delay_secs: u32,
}
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
- G: GmailLabelModifier,
{
pub fn new(
email_repo: T,
frecency_service: U,
enqueuer: E,
- gmail_label_modifier: G,
sent_undo_delay_secs: u32,
- ) -> EmailServiceImpl<T, U, E, G> {
+ ) -> EmailServiceImpl<T, U, E> {
EmailServiceImpl {
email_repo,
frecency_service,
enqueuer,
- gmail_label_modifier,
sent_undo_delay_secs,
}
}
}
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G> {
+impl<T, U, E> EmailServiceImpl<T, U, E> {
/// Validate and normalize email filter input.
fn validate_email_filter_input(
input: UpsertEmailFilterInput,
@@ -112,12 +108,11 @@ impl<T, U, E, G> EmailServiceImpl<T, U, E, G> {
}
}
-impl<T, U, E, G> EmailService for EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailService for EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
- G: GmailLabelModifier,
anyhow::Error: From<T::Err>,
anyhow::Error: From<E::Err>,
{
diff --git a/rust/cloud-storage/email/src/domain/service/previews.rs b/rust/cloud-storage/email/src/domain/service/previews.rs
index 77e22d0745..6785b1141e 100644
--- a/rust/cloud-storage/email/src/domain/service/previews.rs
+++ b/rust/cloud-storage/email/src/domain/service/previews.rs
@@ -16,7 +16,7 @@ use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/send.rs b/rust/cloud-storage/email/src/domain/service/send.rs
index 1c07c0863a..13b281ce0c 100644
--- a/rust/cloud-storage/email/src/domain/service/send.rs
+++ b/rust/cloud-storage/email/src/domain/service/send.rs
@@ -8,7 +8,7 @@ use frecency::domain::ports::FrecencyQueryService;
use super::EmailServiceImpl;
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread.rs b/rust/cloud-storage/email/src/domain/service/thread.rs
index 2478068cec..e04036a666 100644
--- a/rust/cloud-storage/email/src/domain/service/thread.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread.rs
@@ -27,7 +27,7 @@ struct ThreadFetchResult {
is_owner: bool,
}
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
diff --git a/rust/cloud-storage/email/src/domain/service/thread_labels.rs b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
index 007bfbd467..ec53e1750b 100644
--- a/rust/cloud-storage/email/src/domain/service/thread_labels.rs
+++ b/rust/cloud-storage/email/src/domain/service/thread_labels.rs
@@ -1,25 +1,24 @@
use crate::domain::{
models::{EmailErr, Link, UpdateThreadLabelsResult, label::system_labels},
- ports::{EmailMessageEnqueuer, EmailRepo, GmailLabelModifier},
+ ports::{EmailMessageEnqueuer, EmailRepo},
};
use frecency::domain::ports::FrecencyQueryService;
-use futures::{StreamExt, stream};
use uuid::Uuid;
use super::EmailServiceImpl;
-impl<T, U, E, G> EmailServiceImpl<T, U, E, G>
+impl<T, U, E> EmailServiceImpl<T, U, E>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
- G: GmailLabelModifier,
anyhow::Error: From<T::Err>,
+ anyhow::Error: From<E::Err>,
{
- #[tracing::instrument(err, skip(self, access_token, link))]
+ #[tracing::instrument(err, skip(self, _access_token, link))]
pub(crate) async fn update_thread_labels_impl(
&self,
- access_token: &str,
+ _access_token: &str,
link: &Link,
thread_id: Uuid,
label_id: Uuid,
@@ -48,128 +47,96 @@ where
return Err(EmailErr::EmptyProviderLabelId);
}
- // Separate draft messages (no provider_id) from provider messages.
- // Drafts only exist locally so we update their labels in the DB directly.
- // Provider messages need a Gmail API call first.
- let mut draft_ids = Vec::new();
- let mut provider_messages = Vec::new();
- for msg in &messages {
- match &msg.provider_id {
- Some(id) if !id.is_empty() => provider_messages.push(msg),
- _ => draft_ids.push(msg.db_id),
- }
+ let all_ids: Vec<Uuid> = messages.iter().map(|m| m.db_id).collect();
+
+ // Optimistic DB update: update all messages first
+ let db_result = if add {
+ self.email_repo
+ .insert_message_labels_batch(&all_ids, &provider_label_id, link.id)
+ .await
+ } else {
+ self.email_repo
+ .delete_message_labels_batch(&all_ids, &provider_label_id, link.id)
+ .await
+ };
+
+ if let Err(e) = db_result {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to update message labels in database");
+ return Err(EmailErr::RepoErr(err));
}
- // Fan out Gmail API calls with limited concurrency.
- // Take a reference to the modifier outside the loop so each future
- // only borrows the modifier (not all of `self`), allowing true
- // concurrent polling via buffer_unordered.
- const MAX_CONCURRENT: usize = 10;
- let modifier = &self.gmail_label_modifier;
- let mut join_handles = Vec::with_capacity(provider_messages.len());
- for msg in &provider_messages {
- let db_id = msg.db_id;
- let provider_msg_id = msg.provider_id.clone().unwrap();
- let plid = provider_label_id.clone();
- let token = access_token.to_owned();
- let (to_add, to_remove) = if add {
- (vec![plid], vec![])
- } else {
- (vec![], vec![plid])
- };
- join_handles.push(async move {
- let result = modifier
- .modify_message_labels(&token, &provider_msg_id, &to_add, &to_remove)
- .await;
- (db_id, result)
- });
- }
-
- let results: Vec<_> = stream::iter(join_handles)
- .buffer_unordered(MAX_CONCURRENT)
- .collect()
- .await;
-
- // Draft messages are always successful (no Gmail call needed)
- let mut successful_ids = draft_ids;
- let mut failed_ids = Vec::new();
-
- for (msg_id, result) in results {
- match result {
- Ok(()) => successful_ids.push(msg_id),
- Err(e) => {
- tracing::error!(error=?e, message_id=%msg_id, "failed to modify labels in Gmail");
- failed_ids.push(msg_id);
- }
- }
- }
-
- // Bulk DB update for successful messages
- if !successful_ids.is_empty() {
- let db_result = if add {
- self.email_repo
- .insert_message_labels_batch(&successful_ids, &provider_label_id, link.id)
- .await
- } else {
- self.email_repo
- .delete_message_labels_batch(&successful_ids, &provider_label_id, link.id)
- .await
- };
-
- if let Err(e) = db_result {
+ // Side effects for system labels
+ if provider_label_id == system_labels::UNREAD {
+ if let Err(e) = self
+ .email_repo
+ .update_message_read_status_batch(&all_ids, link.id, !add)
+ .await
+ {
let err = anyhow::Error::from(e);
- tracing::error!(error=?err, "failed to update message labels in database");
- failed_ids.append(&mut successful_ids);
+ tracing::error!(error=?err, "failed to update message read status");
}
+ } else if provider_label_id == system_labels::STARRED
+ && let Err(e) = self
+ .email_repo
+ .update_message_starred_status_batch(&all_ids, link.id, add)
+ .await
+ {
+ let err = anyhow::Error::from(e);
+ tracing::error!(error=?err, "failed to update message starred status");
}
- // Side effects for system labels
- if !successful_ids.is_empty() {
- if provider_label_id == system_labels::UNREAD {
- if let Err(e) = self
- .email_repo
- .update_message_read_status_batch(&successful_ids, link.id, !add)
- .await
- {
- let err = anyhow::Error::from(e);
- tracing::error!(error=?err, "failed to update message read status");
- }
- } else if provider_label_id == system_labels::STARRED
+ // When trashing a thread, cancel any pending scheduled sends for drafts
+ if add && provider_label_id == system_labels::TRASH {
+ let draft_message_ids: Vec<_> = messages
+ .iter()
+ .filter(|m| m.is_draft)
+ .map(|m| m.db_id)
+ .collect();
+
+ if !draft_message_ids.is_empty()
&& let Err(e) = self
.email_repo
- .update_message_starred_status_batch(&successful_ids, link.id, add)
+ .delete_scheduled_messages_batch(&draft_message_ids, link.id)
.await
{
let err = anyhow::Error::from(e);
- tracing::error!(error=?err, "failed to update message starred status");
- }
-
- // When trashing a thread, cancel any pending scheduled sends for drafts
- if add && provider_label_id == system_labels::TRASH {
- let draft_message_ids: Vec<_> = messages
- .iter()
- .filter(|m| m.is_draft && successful_ids.contains(&m.db_id))
- .map(|m| m.db_id)
- .collect();
-
- if !draft_message_ids.is_empty()
- && let Err(e) = self
- .email_repo
- .delete_scheduled_messages_batch(&draft_message_ids, link.id)
- .await
- {
- let err = anyhow::Error::from(e);
- tracing::error!(error=?err, "failed to cancel scheduled sends for trashed drafts");
- }
+ tracing::error!(error=?err, "failed to cancel scheduled sends for trashed drafts");
}
}
- successful_ids.sort();
- failed_ids.sort();
+ // Enqueue Gmail API calls via the gmail_ops worker (provider messages only)
+ let provider_messages: Vec<(Uuid, String)> = messages
+ .iter()
+ .filter_map(|msg| {
+ msg.provider_id
+ .as_ref()
+ .filter(|pid| !pid.is_empty())
+ .map(|pid| (msg.db_id, pid.clone()))
+ })
+ .collect();
+
+ if !provider_messages.is_empty() {
+ let (labels_to_add, labels_to_remove) = if add {
+ (vec![provider_label_id.clone()], vec![])
+ } else {
+ (vec![], vec![provider_label_id.clone()])
+ };
+
+ self.enqueuer
+ .enqueue_gmail_ops_modify_labels_batch(
+ link.id,
+ provider_messages,
+ labels_to_add,
+ labels_to_remove,
+ )
+ .await
+ .map_err(|e| EmailErr::EnqueueErr(anyhow::Error::from(e)))?;
+ }
Ok(UpdateThreadLabelsResult {
- successful_ids,
- failed_ids,
+ successful_ids: all_ids,
+ failed_ids: vec![],
})
}
}
diff --git a/rust/cloud-storage/email/src/outbound.rs b/rust/cloud-storage/email/src/outbound.rs
index 024f329042..7a9a180826 100644
--- a/rust/cloud-storage/email/src/outbound.rs
+++ b/rust/cloud-storage/email/src/outbound.rs
@@ -1,11 +1,7 @@
mod email_pg_repo;
#[cfg(feature = "gmail_token")]
-mod gmail_label_modifier;
-#[cfg(feature = "gmail_token")]
mod gmail_token_provider;
pub use email_pg_repo::*;
#[cfg(feature = "gmail_token")]
-pub use gmail_label_modifier::*;
-#[cfg(feature = "gmail_token")]
pub use gmail_token_provider::*;
diff --git a/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs b/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs
deleted file mode 100644
index d1608b2375..0000000000
--- a/rust/cloud-storage/email/src/outbound/gmail_label_modifier.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-use std::sync::Arc;
-
-use crate::domain::{models::EmailErr, ports::GmailLabelModifier};
-
-/// Adapter implementing [`GmailLabelModifier`] via the Gmail API client.
-#[derive(Clone)]
-pub struct GmailClientLabelModifier {
- gmail_client: Arc<gmail_client::GmailClient>,
-}
-
-impl GmailClientLabelModifier {
- /// Create a new modifier wrapping the given Gmail client.
- pub fn new(gmail_client: Arc<gmail_client::GmailClient>) -> Self {
- Self { gmail_client }
- }
-}
-
-impl GmailLabelModifier for GmailClientLabelModifier {
- async fn modify_message_labels(
- &self,
- access_token: &str,
- provider_message_id: &str,
- label_ids_to_add: &[String],
- label_ids_to_remove: &[String],
- ) -> Result<(), EmailErr> {
- self.gmail_client
- .modify_message_labels(
- access_token,
- provider_message_id,
- label_ids_to_add,
- label_ids_to_remove,
- )
- .await
- .map_err(EmailErr::ProviderErr)
- }
-}
diff --git a/rust/cloud-storage/email_db_client/src/messages/update.rs b/rust/cloud-storage/email_db_client/src/messages/update.rs
index 17613a4d99..4b52c0faa5 100644
--- a/rust/cloud-storage/email_db_client/src/messages/update.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/update.rs
@@ -89,13 +89,16 @@ where
Ok(updated_count)
}
-#[tracing::instrument(skip(pool), err)]
-pub async fn update_message_starred_status_batch(
- pool: &sqlx::PgPool,
+#[tracing::instrument(skip(executor), err)]
+pub async fn update_message_starred_status_batch<'e, E>(
+ executor: E,
message_ids: Vec<Uuid>,
fusionauth_user_id: &str,
is_starred: bool,
-) -> anyhow::Result<usize> {
+) -> anyhow::Result<usize>
+where
+ E: sqlx::Executor<'e, Database = sqlx::Postgres>,
+{
if message_ids.is_empty() {
return Ok(0);
}
@@ -117,7 +120,7 @@ pub async fn update_message_starred_status_batch(
&message_ids,
fusionauth_user_id
)
- .fetch_all(pool)
+ .fetch_all(executor)
.await?;
let updated_count = result.len();
diff --git a/rust/cloud-storage/email_service/src/api/context.rs b/rust/cloud-storage/email_service/src/api/context.rs
index ef24bdfadd..8c8ed19cc5 100644
--- a/rust/cloud-storage/email_service/src/api/context.rs
+++ b/rust/cloud-storage/email_service/src/api/context.rs
@@ -6,7 +6,6 @@ use email::{
outbound::{EmailPgRepo, GmailTokenProviderImpl},
};
-use email::outbound::GmailClientLabelModifier;
use email_service::config::Config;
use email_service::util::redis::RedisClient;
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
@@ -19,12 +18,8 @@ use std::sync::Arc;
use system_properties::{PgSystemPropertiesRepository, SystemPropertiesServiceImpl};
pub(crate) type EmailEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
-pub(crate) type EmailSvc = EmailServiceImpl<
- EmailPgRepo,
- FrecencyQueryServiceImpl<FrecencyPgStorage>,
- sqs_client::SQS,
- GmailClientLabelModifier,
->;
+pub(crate) type EmailSvc =
+ EmailServiceImpl<EmailPgRepo, FrecencyQueryServiceImpl<FrecencyPgStorage>, sqs_client::SQS>;
#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs b/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs
index 1ae4fd6dee..d5faa7ee72 100644
--- a/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/block_sender.rs
@@ -3,8 +3,8 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use gmail_client::{Filter, GmailError};
use model::response::ErrorResponse;
+use models_email::service::link::Link;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
@@ -14,14 +14,8 @@ pub enum BlockSenderError {
#[error("Validation error: {0}")]
Validation(String),
- #[error("Sender is already blocked")]
- AlreadyBlocked,
-
- #[error("Insufficient Gmail permissions. Please re-authenticate to grant the required scope.")]
- Forbidden,
-
- #[error("Gmail API error: {0}")]
- GmailError(String),
+ #[error("Failed to enqueue block sender operation")]
+ EnqueueFailed,
#[error("Internal error")]
InternalError(#[from] anyhow::Error),
@@ -31,9 +25,7 @@ impl IntoResponse for BlockSenderError {
fn into_response(self) -> Response {
let status_code = match &self {
BlockSenderError::Validation(_) => StatusCode::BAD_REQUEST,
- BlockSenderError::AlreadyBlocked => StatusCode::CONFLICT,
- BlockSenderError::Forbidden => StatusCode::FORBIDDEN,
- BlockSenderError::GmailError(_) | BlockSenderError::InternalError(_) => {
+ BlockSenderError::EnqueueFailed | BlockSenderError::InternalError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
};
@@ -48,16 +40,6 @@ impl IntoResponse for BlockSenderError {
}
}
-impl From<GmailError> for BlockSenderError {
- fn from(e: GmailError) -> Self {
- match e {
- GmailError::Conflict(_) => BlockSenderError::AlreadyBlocked,
- GmailError::Forbidden => BlockSenderError::Forbidden,
- _ => BlockSenderError::GmailError(e.to_string()),
- }
- }
-}
-
/// Request to block a sender.
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BlockSenderRequest {
@@ -65,14 +47,8 @@ pub struct BlockSenderRequest {
pub email_address: String,
}
-/// Response after blocking a sender.
-#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
-pub struct BlockSenderResponse {
- /// The ID of the filter created in Gmail.
- pub filter_id: String,
-}
-
/// Block a sender by creating a Gmail filter that sends their emails to trash.
+/// The actual Gmail API call is performed asynchronously by the gmail_ops worker.
#[utoipa::path(
post,
tag = "Contacts",
@@ -80,41 +56,34 @@ pub struct BlockSenderResponse {
operation_id = "block_sender",
request_body = BlockSenderRequest,
responses(
- (status = 201, body = BlockSenderResponse),
+ (status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
- (status = 403, body = ErrorResponse),
- (status = 409, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, gmail_token), err)]
+#[tracing::instrument(skip(ctx, link, req), fields(link_id = %link.id), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- gmail_token: Extension<String>,
+ link: Extension<Link>,
Json(req): Json<BlockSenderRequest>,
-) -> Result<(StatusCode, Json<BlockSenderResponse>), BlockSenderError> {
+) -> Result<StatusCode, BlockSenderError> {
validate_email(&req.email_address)?;
- // Check if sender is already blocked
- let existing_filter = ctx
- .gmail_client
- .find_block_filter_for_sender(&gmail_token, &req.email_address)
- .await?;
-
- if existing_filter.is_some() {
- return Err(BlockSenderError::AlreadyBlocked);
- }
-
- // Create the block filter
- let filter: Filter = ctx
- .gmail_client
- .block_sender(&gmail_token, &req.email_address)
- .await?;
-
- let filter_id = filter.id.unwrap_or_default();
-
- Ok((StatusCode::CREATED, Json(BlockSenderResponse { filter_id })))
+ ctx.sqs_client
+ .enqueue_gmail_ops_notification(models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation: models_email::gmail::gmail_ops::GmailOpsOperation::BlockSender(
+ models_email::gmail::gmail_ops::BlockSenderPayload {
+ email_address: req.email_address,
+ },
+ ),
+ })
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "Failed to enqueue block sender operation"))
+ .map_err(|_| BlockSenderError::EnqueueFailed)?;
+
+ Ok(StatusCode::OK)
}
fn validate_email(email: &str) -> Result<(), BlockSenderError> {
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs b/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
index f18f39ebdc..fb8719a8ce 100644
--- a/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/mod.rs
@@ -13,20 +13,16 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
.route("/", get(list::list_contacts_handler))
.route(
"/block",
- post(block_sender::handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ),
+ post(block_sender::handler).layer(axum::middleware::from_fn_with_state(
+ state.email_service.clone(),
+ crate::api::middleware::link::attach_link_context,
)),
)
.route(
"/unblock",
- post(unblock_sender::handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ),
+ post(unblock_sender::handler).layer(axum::middleware::from_fn_with_state(
+ state.email_service.clone(),
+ crate::api::middleware::link::attach_link_context,
)),
)
.route(
diff --git a/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs b/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs
index 034b77bf30..748361acdf 100644
--- a/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs
+++ b/rust/cloud-storage/email_service/src/api/email/contacts/unblock_sender.rs
@@ -3,8 +3,8 @@ use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use gmail_client::GmailError;
use model::response::ErrorResponse;
+use models_email::service::link::Link;
use strum_macros::AsRefStr;
use thiserror::Error;
use utoipa::ToSchema;
@@ -14,14 +14,8 @@ pub enum UnblockSenderError {
#[error("Validation error: {0}")]
Validation(String),
- #[error("Sender is not blocked")]
- NotBlocked,
-
- #[error("Insufficient Gmail permissions. Please re-authenticate to grant the required scope.")]
- Forbidden,
-
- #[error("Gmail API error: {0}")]
- GmailError(String),
+ #[error("Failed to enqueue unblock sender operation")]
+ EnqueueFailed,
#[error("Internal error")]
InternalError(#[from] anyhow::Error),
@@ -31,9 +25,7 @@ impl IntoResponse for UnblockSenderError {
fn into_response(self) -> Response {
let status_code = match &self {
UnblockSenderError::Validation(_) => StatusCode::BAD_REQUEST,
- UnblockSenderError::NotBlocked => StatusCode::NOT_FOUND,
- UnblockSenderError::Forbidden => StatusCode::FORBIDDEN,
- UnblockSenderError::GmailError(_) | UnblockSenderError::InternalError(_) => {
+ UnblockSenderError::EnqueueFailed | UnblockSenderError::InternalError(_) => {
StatusCode::INTERNAL_SERVER_ERROR
}
};
@@ -48,16 +40,6 @@ impl IntoResponse for UnblockSenderError {
}
}
-impl From<GmailError> for UnblockSenderError {
- fn from(e: GmailError) -> Self {
- match e {
- GmailError::NotFound(_) => UnblockSenderError::NotBlocked,
- GmailError::Forbidden => UnblockSenderError::Forbidden,
- _ => UnblockSenderError::GmailError(e.to_string()),
- }
- }
-}
-
/// Request to unblock a sender.
#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct UnblockSenderRequest {
@@ -66,6 +48,7 @@ pub struct UnblockSenderRequest {
}
/// Unblock a sender by removing their block filter from Gmail.
+/// The actual Gmail API call is performed asynchronously by the gmail_ops worker.
#[utoipa::path(
post,
tag = "Contacts",
@@ -76,38 +59,29 @@ pub struct UnblockSenderRequest {
(status = 204),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
- (status = 403, body = ErrorResponse),
- (status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, gmail_token), err)]
+#[tracing::instrument(skip(ctx, link, req), fields(link_id = %link.id), err)]
pub async fn handler(
State(ctx): State<ApiContext>,
- gmail_token: Extension<String>,
+ link: Extension<Link>,
Json(req): Json<UnblockSenderRequest>,
-) -> Result<impl IntoResponse, UnblockSenderError> {
+) -> Result<StatusCode, UnblockSenderError> {
validate_email(&req.email_address)?;
- // Check if sender is currently blocked
- let existing_filter = ctx
- .gmail_client
- .find_block_filter_for_sender(&gmail_token, &req.email_address)
- .await?;
-
- if existing_filter.is_none() {
- return Err(UnblockSenderError::NotBlocked);
- }
-
- // Unblock the sender
- let was_unblocked = ctx
- .gmail_client
- .unblock_sender(&gmail_token, &req.email_address)
- .await?;
-
- if !was_unblocked {
- return Err(UnblockSenderError::NotBlocked);
- }
+ ctx.sqs_client
+ .enqueue_gmail_ops_notification(models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation: models_email::gmail::gmail_ops::GmailOpsOperation::UnblockSender(
+ models_email::gmail::gmail_ops::UnblockSenderPayload {
+ email_address: req.email_address,
+ },
+ ),
+ })
+ .await
+ .inspect_err(|e| tracing::error!(error = ?e, "Failed to enqueue unblock sender operation"))
+ .map_err(|_| UnblockSenderError::EnqueueFailed)?;
Ok(StatusCode::NO_CONTENT)
}
diff --git a/rust/cloud-storage/email_service/src/api/email/labels/delete.rs b/rust/cloud-storage/email_service/src/api/email/labels/delete.rs
index de794bed4c..3b5a9628e7 100644
--- a/rust/cloud-storage/email_service/src/api/email/labels/delete.rs
+++ b/rust/cloud-storage/email_service/src/api/email/labels/delete.rs
@@ -25,12 +25,11 @@ use uuid::Uuid;
(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))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
link: Extension<Link>,
- gmail_token: Extension<String>,
Path(label_id): Path<Uuid>,
) -> Result<Response, Response> {
let label = email_db_client::labels::get::fetch_label_by_id(&ctx.db, label_id, link.id)
@@ -55,38 +54,7 @@ pub async fn handler(
.into_response()
})?;
- let gmail_result = ctx
- .gmail_client
- .delete_label(gmail_token.as_str(), &label.provider_label_id)
- .await;
-
- if let Err(e) = &gmail_result {
- match e {
- gmail_client::GmailError::NotFound(_) => {
- tracing::warn!(
- label_id = %label_id,
- provider_label_id = %label.provider_label_id,
- "Label not found in Gmail, but continuing with database deletion"
- );
- }
- _ => {
- tracing::error!(
- error = ?e,
- label_id = %label_id,
- provider_label_id = %label.provider_label_id,
- "Gmail API call to delete label failed"
- );
- return Err((
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "delete label gmail api call failed".into(),
- }),
- )
- .into_response());
- }
- }
- }
-
+ // Optimistic: delete from DB first, then enqueue Gmail deletion
let label_deleted =
email_db_client::labels::delete::delete_label_by_id(&ctx.db, label_id, link.id)
.await
@@ -102,7 +70,6 @@ pub async fn handler(
})?;
if !label_deleted {
- // This should be rare since we already checked for existence, but handle it just in case
return Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse {
@@ -112,5 +79,21 @@ pub async fn handler(
.into_response());
}
+ // Enqueue Gmail label deletion to be processed by the gmail_ops worker
+ ctx.sqs_client
+ .enqueue_gmail_ops_notification(models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation: models_email::gmail::gmail_ops::GmailOpsOperation::DeleteLabel(
+ models_email::gmail::gmail_ops::DeleteLabelPayload {
+ provider_label_id: label.provider_label_id.clone(),
+ },
+ ),
+ })
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to enqueue gmail delete label operation");
+ })
+ .ok();
+
Ok(StatusCode::NO_CONTENT.into_response())
}
diff --git a/rust/cloud-storage/email_service/src/api/email/labels/mod.rs b/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
index 38a574fbe2..42036422eb 100644
--- a/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/labels/mod.rs
@@ -11,12 +11,14 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
email::inbound::list_labels_router::<ApiContext, crate::api::context::EmailSvc>();
Router::new()
- .route("/", post(create::handler))
+ .route(
+ "/",
+ post(create::handler).layer(axum::middleware::from_fn_with_state(
+ state.clone(),
+ crate::api::middleware::gmail_token::attach_gmail_token,
+ )),
+ )
.route("/{id}", delete(delete::handler))
- .layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ))
.layer(axum::middleware::from_fn_with_state(
state.email_service,
crate::api::middleware::link::attach_link_context,
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs b/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
index 0861cb4da2..c029658e26 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/labels.rs
@@ -1,17 +1,14 @@
use crate::api::context::ApiContext;
use crate::api::email::messages::BATCH_UPDATE_MESSAGE_LIMIT;
+use anyhow::Context;
use axum::extract::State;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::{Extension, Json};
-use futures::{StreamExt, stream};
-use gmail_client::GmailClient;
use model::response::ErrorResponse;
use model::user::UserContext;
-use models_email::email::service::message::SimpleMessage;
use models_email::service;
use models_email::service::link::Link;
-use sqlx::PgPool;
use sqlx::types::Uuid;
use utoipa::ToSchema;
@@ -45,11 +42,10 @@ pub struct UpdateLabelBatchResponse {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, link, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
pub async fn handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
- gmail_token: Extension<String>,
link: Extension<Link>,
Json(body): Json<UpdateLabelBatchRequest>,
) -> Result<Response, Response> {
@@ -120,310 +116,142 @@ pub async fn handler(
tracing::warn!(message_ids=?missing_ids, "unable to find messages in db");
}
- let gmail_access_token = gmail_token.as_str();
+ let message_db_ids: Vec<Uuid> = db_messages.iter().map(|m| m.db_id).collect();
+ let provider_label_id = label.provider_label_id.clone();
+ let is_adding = body.value;
- let (successful_ids, failed_ids) = if body.value {
- add_label_to_messages(
- &ctx.db,
- gmail_access_token,
- &ctx.gmail_client,
- db_messages,
- label.provider_label_id.as_str(),
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to add label to messages");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to add label to messages".into(),
- }),
- )
- .into_response()
- })?
- } else {
- remove_label_from_messages(
- &ctx.db,
- gmail_access_token,
- &ctx.gmail_client,
- db_messages,
- label.provider_label_id.as_str(),
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to remove label from messages");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to remove label from messages".into(),
- }),
- )
- .into_response()
- })?
- };
-
- // need to update flags on message object for certain labels
- if label.provider_label_id.as_str() == service::label::system_labels::UNREAD {
- email_db_client::messages::update::update_message_read_status_batch(
- &ctx.db,
- successful_ids.clone(),
- &user_context.fusion_user_id,
- !body.value,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to update message read status");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to update message read status".into(),
- }),
- )
- .into_response()
- })?;
- } else if label.provider_label_id.as_str() == service::label::system_labels::STARRED {
- email_db_client::messages::update::update_message_starred_status_batch(
- &ctx.db,
- successful_ids.clone(),
- &user_context.fusion_user_id,
- body.value,
+ // Optimistic DB update: update the database first, then sync to Gmail in the background
+ let mut tx = ctx.db.begin().await.map_err(|e| {
+ tracing::error!(error=?e, "unable to begin transaction");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to begin transaction".into(),
+ }),
)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "unable to update message starred status");
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(ErrorResponse {
- message: "unable to update message starred status".into(),
- }),
- )
- .into_response()
- })?;
- }
-
- Ok((
- StatusCode::OK,
- Json(UpdateLabelBatchResponse {
- successful_ids,
- failed_ids,
- missing_ids,
- }),
- )
- .into_response())
-}
-
-// add a given label to a batch of messages in gmail and db
-pub async fn add_label_to_messages(
- db: &PgPool,
- gmail_access_token: &str,
- gmail_client: &GmailClient,
- messages: Vec<SimpleMessage>,
- provider_label_id: &str,
-) -> anyhow::Result<(Vec<Uuid>, Vec<Uuid>)> {
- if messages.is_empty() {
- return Ok((vec![], vec![]));
- }
-
- if provider_label_id.is_empty() {
- anyhow::bail!("Provider label ID cannot be empty");
- }
-
- // First clone for the Gmail API operations
- let api_provider_label_id = provider_label_id.to_string();
-
- // Second clone for the database operations
- let db_provider_label_id = provider_label_id.to_string();
-
- // Use into_iter() on a clone of messages to avoid lifetime issues
- let label_tasks = messages.clone().into_iter().map(move |message| {
- let gmail_client = gmail_client.clone();
- let gmail_access_token = gmail_access_token.to_string();
- let provider_label_id = api_provider_label_id.clone();
-
- async move {
- let labels_to_add = vec![provider_label_id.clone()];
- let labels_to_remove = vec![];
+ .into_response()
+ })?;
- // First update in Gmail
- let gmail_result = gmail_client
- .modify_message_labels(
- &gmail_access_token,
- &message.provider_id.clone().unwrap_or_default(),
- &labels_to_add,
- &labels_to_remove,
+ let transaction_result = async {
+ if !message_db_ids.is_empty() {
+ if is_adding {
+ email_db_client::labels::insert::insert_message_labels_batch(
+ &mut *tx,
+ &message_db_ids,
+ &provider_label_id,
+ link.id,
)
- .await;
-
- if let Err(e) = gmail_result {
- tracing::error!(
- error = ?e,
- message_id = %message.db_id,
- provider_id = %message.provider_id.unwrap_or_default(),
- "Failed to modify labels in Gmail"
- );
- return (message.db_id, Err(e));
+ .await
+ .context("Failed to add label to messages in database")?;
+ } else {
+ email_db_client::labels::delete::delete_message_labels_batch(
+ &mut *tx,
+ &message_db_ids,
+ &provider_label_id,
+ link.id,
+ )
+ .await
+ .context("Failed to remove label from messages in database")?;
}
- (message.db_id, Ok(()))
- }
- });
-
- // Process tasks with limited concurrency
- const MAX_CONCURRENT: usize = 10;
- let results = stream::iter(label_tasks)
- .buffer_unordered(MAX_CONCURRENT)
- .collect::<Vec<_>>()
- .await;
-
- // Separate successful and failed messages
- let mut successful_msg_ids = Vec::new();
- let mut failed_msg_ids = Vec::new();
-
- for (msg_id, result) in results {
- match result {
- Ok(_) => successful_msg_ids.push(msg_id),
- Err(_) => failed_msg_ids.push(msg_id),
- }
- }
-
- // If there are any successful messages, update the database in bulk
- if !successful_msg_ids.is_empty() {
- let link_id = messages.first().map(|m| m.link_id).unwrap_or_default();
-
- // Use bulk insert function to add labels in database
- match email_db_client::labels::insert::insert_message_labels_batch(
- db,
- &successful_msg_ids,
- &db_provider_label_id,
- link_id,
- )
- .await
- {
- Ok(_) => {}
- Err(e) => {
- tracing::error!(
- error = ?e,
- message_ids = successful_msg_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>().join(", "),
- provider_label_id = %db_provider_label_id,
- "Failed to add label to messages in database"
- );
- // Move all messages to failed if database update fails
- failed_msg_ids.extend(successful_msg_ids.clone());
- successful_msg_ids.clear();
+ if provider_label_id.as_str() == service::label::system_labels::UNREAD {
+ email_db_client::messages::update::update_message_read_status_batch(
+ &mut *tx,
+ message_db_ids.clone(),
+ &user_context.fusion_user_id,
+ !is_adding,
+ )
+ .await
+ .context("Failed to update message read status")?;
+ } else if provider_label_id.as_str() == service::label::system_labels::STARRED {
+ email_db_client::messages::update::update_message_starred_status_batch(
+ &mut *tx,
+ message_db_ids.clone(),
+ &user_context.fusion_user_id,
+ is_adding,
+ )
+ .await
+ .context("Failed to update message starred status")?;
}
}
- }
- successful_msg_ids.sort();
- failed_msg_ids.sort();
-
- Ok((successful_msg_ids, failed_msg_ids))
-}
-
-/// Remove a label from multiple messages in gmail and in db concurrently
-pub async fn remove_label_from_messages(
- db: &PgPool,
- gmail_access_token: &str,
- gmail_client: &GmailClient,
- messages: Vec<SimpleMessage>,
- provider_label_id: &str,
-) -> anyhow::Result<(Vec<Uuid>, Vec<Uuid>)> {
- if messages.is_empty() {
- return Ok((vec![], vec![]));
+ anyhow::Ok(())
}
-
- if provider_label_id.is_empty() {
- anyhow::bail!("Provider label ID cannot be empty");
- }
-
- // First clone for the Gmail API operations
- let api_provider_label_id = provider_label_id.to_string();
-
- // Second clone for the database operations
- let db_provider_label_id = provider_label_id.to_string();
-
- // Use into_iter() on a clone of messages to avoid lifetime issues
- let label_tasks = messages.clone().into_iter().map(move |message| {
- let gmail_client = gmail_client.clone();
- let gmail_access_token = gmail_access_token.to_string();
- let provider_label_id = api_provider_label_id.clone();
-
- async move {
- let labels_to_add = vec![];
- let labels_to_remove = vec![provider_label_id.clone()];
-
- // Update in Gmail - remove the label
- let gmail_result = gmail_client
- .modify_message_labels(
- &gmail_access_token,
- &message.provider_id.clone().unwrap_or_default(),
- &labels_to_add,
- &labels_to_remove,
+ .await;
+
+ match transaction_result {
+ Ok(_) => {
+ tx.commit().await.map_err(|e| {
+ tracing::error!(error=?e, "unable to commit transaction");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to commit transaction".into(),
+ }),
)
- .await;
-
- if let Err(e) = gmail_result {
- tracing::error!(
- error = ?e,
- message_id = %message.db_id,
- provider_id = %message.provider_id.unwrap_or_default(),
- "Failed to remove label in Gmail"
- );
- return (message.db_id, Err(e));
- }
-
- (message.db_id, Ok(()))
+ .into_response()
+ })?;
}
- });
-
- // Process tasks with limited concurrency
- const MAX_CONCURRENT: usize = 10;
- let results = stream::iter(label_tasks)
- .buffer_unordered(MAX_CONCURRENT)
- .collect::<Vec<_>>()
- .await;
-
- // Separate successful and failed messages
- let mut successful_msg_ids = Vec::new();
- let mut failed_msg_ids = Vec::new();
-
- for (msg_id, result) in results {
- match result {
- Ok(_) => successful_msg_ids.push(msg_id),
- Err(_) => failed_msg_ids.push(msg_id),
+ Err(e) => {
+ tracing::error!(error=?e, "Transaction failed, rolling back");
+ if let Err(rollback_err) = tx.rollback().await {
+ tracing::error!(error=?rollback_err, "Failed to rollback transaction");
+ }
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ Json(ErrorResponse {
+ message: "unable to update labels in database".into(),
+ }),
+ )
+ .into_response());
}
}
- // If there are any successful messages, update the database in bulk
- if !successful_msg_ids.is_empty() {
- let link_id = messages.first().map(|m| m.link_id).unwrap_or_default();
+ // Enqueue gmail ops messages in batch (drafts have no provider_id, skip them)
+ let (labels_to_add, labels_to_remove) = if is_adding {
+ (vec![provider_label_id.clone()], Vec::new())
+ } else {
+ (Vec::new(), vec![provider_label_id.clone()])
+ };
- // Use bulk delete function to remove labels from database
- match email_db_client::labels::delete::delete_message_labels_batch(
- db,
- &successful_msg_ids,
- &db_provider_label_id,
- link_id,
- )
- .await
- {
- Ok(_) => {}
- Err(e) => {
- tracing::error!(
- error = ?e,
- message_ids = successful_msg_ids.iter().map(|id| id.to_string()).collect::<Vec<_>>().join(", "),
- provider_label_id = %db_provider_label_id,
- "Failed to remove label from messages in database"
- );
- // Move all messages to failed if database update fails
- failed_msg_ids.extend(successful_msg_ids.clone());
- successful_msg_ids.clear();
- }
- }
- }
+ let gmail_ops_messages: Vec<_> = db_messages
+ .iter()
+ .filter_map(|msg| {
+ msg.provider_id
+ .as_ref()
+ .filter(|pid| !pid.is_empty())
+ .map(
+ |pid| models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation:
+ models_email::gmail::gmail_ops::GmailOpsOperation::ModifyMessageLabels(
+ models_email::gmail::gmail_ops::ModifyMessageLabelsPayload {
+ db_message_id: msg.db_id,
+ provider_message_id: pid.clone(),
+ labels_to_add: labels_to_add.clone(),
+ labels_to_remove: labels_to_remove.clone(),
+ },
+ ),
+ },
+ )
+ })
+ .collect();
- successful_msg_ids.sort();
- failed_msg_ids.sort();
+ ctx.sqs_client
+ .enqueue_gmail_ops_notifications_batch(gmail_ops_messages)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to enqueue gmail ops notifications batch");
+ })
+ .ok();
- Ok((successful_msg_ids, failed_msg_ids))
+ Ok((
+ StatusCode::OK,
+ Json(UpdateLabelBatchResponse {
+ successful_ids: message_db_ids,
+ failed_ids: vec![],
+ missing_ids,
+ }),
+ )
+ .into_response())
}
diff --git a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
index fdd74c650e..1944ef1b11 100644
--- a/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/messages/mod.rs
@@ -12,13 +12,7 @@ const BATCH_UPDATE_MESSAGE_LIMIT: usize = 10;
pub fn router(state: ApiContext) -> Router<ApiContext> {
Router::new()
.merge(send_router(state.email_service.clone()))
- .route(
- "/labels",
- patch(labels::handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- )),
- )
+ .route("/labels", patch(labels::handler))
.route("/batch", post(get::batch_handler))
.layer(axum::middleware::from_fn_with_state(
state.email_service,
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs b/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
index 53e9635def..8ff164bce3 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/archived.rs
@@ -67,16 +67,14 @@ pub struct ArchiveThreadRequest {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, link, gmail_token, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id))]
+#[tracing::instrument(skip(ctx, user_context, link, body), fields(user_id=user_context.user_id, fusionauth_user_id=user_context.fusion_user_id), err)]
pub async fn archived_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
link: Extension<Link>,
- gmail_token: Extension<String>,
Path(thread_id): Path<Uuid>,
Json(body): Json<ArchiveThreadRequest>,
) -> Result<Response, ArchiveThreadError> {
- let gmail_access_token = gmail_token.as_str();
let is_archiving = body.value;
let thread =
@@ -92,7 +90,6 @@ pub async fn archived_handler(
.await?;
let mut message_db_ids = Vec::new();
- let mut provider_message_tuples: Vec<(Uuid, String)> = Vec::new();
// if we are archiving the thread, any messages with the INBOX label are affected. and vice versa
let has_inbox_label = |m: &Message| {
@@ -101,16 +98,14 @@ pub async fn archived_handler(
.any(|l| l.provider_label_id == system_labels::INBOX)
};
- for m in messages.iter() {
- if has_inbox_label(m) == is_archiving {
- message_db_ids.push(m.db_id);
- // Only send provider messages to Gmail (drafts have no provider_id)
- if let Some(ref pid) = m.provider_id
- && !pid.is_empty()
- {
- provider_message_tuples.push((m.db_id, pid.clone()));
- }
- }
+ // Collect affected messages
+ let affected_messages: Vec<&Message> = messages
+ .iter()
+ .filter(|m| has_inbox_label(m) == is_archiving)
+ .collect();
+
+ for m in &affected_messages {
+ message_db_ids.push(m.db_id);
}
// Early return if no messages need to be updated
@@ -168,103 +163,43 @@ pub async fn archived_handler(
}
}
- // async send requests to gmail async. if they fail, revert db changes we made earlier. we make
- // the calls async at Teo's request because they are slow and doing it sync causes this endpoint
- // to take >300ms
-
- let db_clone = ctx.db.clone();
- let gmail_client_clone = ctx.gmail_client.clone();
- let gmail_access_token_clone = gmail_access_token.to_string();
- let thread_id_clone = thread_id;
- let link_id_clone = link.id;
- let message_db_ids_clone = message_db_ids.clone();
-
+ // Enqueue one gmail_ops message per provider message
let (labels_to_add, labels_to_remove) = if is_archiving {
(Vec::new(), vec![system_labels::INBOX.to_string()])
} else {
(vec![system_labels::INBOX.to_string()], Vec::new())
};
- tokio::spawn(async move {
- // Only send provider messages to Gmail (drafts are already updated in DB)
- let (success_ids, failed_ids) = gmail_client_clone
- .batch_modify_labels(
- &gmail_access_token_clone,
- provider_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 {
- update_inbox_visible_status(
- &mut revert_tx,
- thread_id_clone,
- link_id_clone,
- is_archiving,
+ let gmail_ops_messages: Vec<_> = affected_messages
+ .iter()
+ .filter_map(|msg| {
+ msg.provider_id
+ .as_ref()
+ .filter(|pid| !pid.is_empty())
+ .map(
+ |pid| models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation:
+ models_email::gmail::gmail_ops::GmailOpsOperation::ModifyMessageLabels(
+ models_email::gmail::gmail_ops::ModifyMessageLabelsPayload {
+ db_message_id: msg.db_id,
+ provider_message_id: pid.clone(),
+ labels_to_add: labels_to_add.clone(),
+ labels_to_remove: labels_to_remove.clone(),
+ },
+ ),
+ },
)
- .await
- .context("Failed to revert thread inbox_visible status")?;
-
- if !is_archiving {
- email_db_client::labels::delete::delete_message_labels_batch(
- &mut *revert_tx,
- &message_db_ids_clone,
- system_labels::INBOX,
- link_id_clone,
- )
- .await
- .context("Failed to revert removing 'INBOX' label from messages")?;
- } else {
- email_db_client::labels::insert::insert_message_labels_batch(
- &mut *revert_tx,
- &message_db_ids_clone,
- system_labels::INBOX,
- link_id_clone,
- )
- .await
- .context("Failed to revert adding 'INBOX' 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!");
- }
- }
- }
- }
- });
+ })
+ .collect();
+
+ ctx.sqs_client
+ .enqueue_gmail_ops_notifications_batch(gmail_ops_messages)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to enqueue gmail ops notifications batch for archived");
+ })
+ .ok();
Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
index 3d689e99c7..2554048b8b 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/mod.rs
@@ -4,7 +4,6 @@ pub(crate) mod seen;
use axum::Router;
use axum::routing::{get, patch, post};
-use tower::ServiceBuilder;
use crate::api::ApiContext;
@@ -14,23 +13,9 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/previews",
email::inbound::router(state.email_service.clone()),
)
- .route(
- "/{id}/seen",
- post(seen::seen_handler).layer(axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- )),
- )
+ .route("/{id}/seen", post(seen::seen_handler))
.route("/{id}/messages", get(get::get_thread_messages_handler))
- .route(
- "/{id}/archived",
- patch(archived::archived_handler).layer(ServiceBuilder::new().layer(
- axum::middleware::from_fn_with_state(
- state.clone(),
- crate::api::middleware::gmail_token::attach_gmail_token,
- ),
- )),
- )
+ .route("/{id}/archived", patch(archived::archived_handler))
.layer(axum::middleware::from_fn_with_state(
state.email_service.clone(),
crate::api::middleware::link::attach_link_context,
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.rs
index f7117738e3..a86098ef18 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
@@ -67,12 +67,11 @@ pub struct PathParams {
(status = 500, body=ErrorResponse),
)
)]
-#[tracing::instrument(skip(ctx, user_context, gmail_token))]
+#[tracing::instrument(skip(ctx, user_context), err)]
pub async fn seen_handler(
State(ctx): State<ApiContext>,
user_context: Extension<UserContext>,
link: Extension<Link>,
- gmail_token: Extension<String>,
Path(PathParams { id: thread_id }): Path<PathParams>,
) -> Result<Response, SeenThreadError> {
// update viewed_at value in user_history table for thread
@@ -104,16 +103,6 @@ pub async fn seen_handler(
}
let message_db_ids: Vec<Uuid> = unread_messages.iter().map(|m| m.db_id).collect();
- // Only collect provider messages for Gmail API calls (drafts have no provider_id)
- let provider_message_tuples: Vec<(Uuid, String)> = unread_messages
- .iter()
- .filter_map(|m| {
- m.provider_id
- .as_ref()
- .filter(|pid| !pid.is_empty())
- .map(|pid| (m.db_id, pid.clone()))
- })
- .collect();
let mut tx = ctx.db.begin().await?;
@@ -162,99 +151,37 @@ pub async fn seen_handler(
}
}
- // 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 labels_to_add = Vec::new();
- let labels_to_remove = vec![system_labels::UNREAD.to_string()];
-
- // Only send provider messages to Gmail (drafts are already updated in DB)
- let (success_ids, failed_ids) = gmail_client_clone
- .batch_modify_labels(
- &gmail_access_token,
- provider_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,
+ // Enqueue gmail ops messages in batch
+ let gmail_ops_messages: Vec<_> = unread_messages
+ .iter()
+ .filter_map(|msg| {
+ msg.provider_id
+ .as_ref()
+ .filter(|pid| !pid.is_empty())
+ .map(
+ |pid| models_email::gmail::gmail_ops::GmailOpsPubsubMessage {
+ link_id: link.id,
+ operation:
+ models_email::gmail::gmail_ops::GmailOpsOperation::ModifyMessageLabels(
+ models_email::gmail::gmail_ops::ModifyMessageLabelsPayload {
+ db_message_id: msg.db_id,
+ provider_message_id: pid.clone(),
+ labels_to_add: Vec::new(),
+ labels_to_remove: vec![system_labels::UNREAD.to_string()],
+ },
+ ),
+ },
)
- .await
- .context("Failed to revert adding 'UNREAD' label to messages")?;
-
- anyhow::Ok(())
- }
- .await;
+ })
+ .collect();
- 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");
- }
- }
- }
- }
- });
+ ctx.sqs_client
+ .enqueue_gmail_ops_notifications_batch(gmail_ops_messages)
+ .await
+ .inspect_err(|e| {
+ tracing::error!(error=?e, "Failed to enqueue gmail ops notifications batch for seen");
+ })
+ .ok();
Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())
}
diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rs
index 016c8633cf..c9e52261e7 100644
--- a/rust/cloud-storage/email_service/src/api/swagger.rs
+++ b/rust/cloud-storage/email_service/src/api/swagger.rs
@@ -2,7 +2,7 @@ use crate::api::email::attachments::get::GetAttachmentResponse;
use crate::api::email::attachments::get_document_id::GetAttachmentDocumentIDResponse;
use crate::api::email::backfill::cancel::CancelBackfillParams;
use crate::api::email::backfill::get::{GetActiveBackfillJobResponse, GetBackfillJobResponse};
-use crate::api::email::contacts::block_sender::{BlockSenderRequest, BlockSenderResponse};
+use crate::api::email::contacts::block_sender::BlockSenderRequest;
use crate::api::email::contacts::list::ListContactsResponse;
use crate::api::email::contacts::list_blocked::ListBlockedResponse;
use crate::api::email::contacts::unblock_sender::UnblockSenderRequest;
@@ -148,7 +148,6 @@ use utoipa::OpenApi;
ListContactsResponse,
ContactInfoWithInteraction,
BlockSenderRequest,
- BlockSenderResponse,
UnblockSenderRequest,
ListBlockedResponse,
// Email filter types
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index f09f7fc6b8..a11f84c60c 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -77,6 +77,8 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&gmail_queue_aws_config))
.gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue)
.gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue)
+ .gmail_ops_queue(&config.gmail_ops_queue)
+ .gmail_ops_retry_queue(&config.gmail_ops_retry_queue)
.search_event_queue(&config.search_event_queue)
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
@@ -128,6 +130,28 @@ async fn main() -> anyhow::Result<()> {
})
.collect::<Vec<_>>();
+ let gmail_ops_workers = (0..config.gmail_ops_queue_workers)
+ .map(|_| {
+ sqs_worker::SQSWorker::new(
+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
+ config.gmail_ops_queue.clone(),
+ config.gmail_ops_queue_max_messages,
+ config.queue_wait_time_seconds,
+ )
+ })
+ .collect::<Vec<_>>();
+
+ let gmail_ops_retry_workers = (0..config.gmail_ops_retry_queue_workers)
+ .map(|_| {
+ sqs_worker::SQSWorker::new(
+ aws_sdk_sqs::Client::new(&gmail_queue_aws_config),
+ config.gmail_ops_retry_queue.clone(),
+ config.gmail_ops_retry_queue_max_messages,
+ config.queue_wait_time_seconds,
+ )
+ })
+ .collect::<Vec<_>>();
+
let inbox_sync_workers = (0..config.inbox_sync_queue_workers)
.map(|_| {
sqs_worker::SQSWorker::new(
@@ -273,10 +297,60 @@ async fn main() -> anyhow::Result<()> {
});
}
tracing::info!(
- num_workers = config.inbox_sync_queue_workers,
+ num_workers = config.inbox_sync_retry_queue_workers,
"inbox_sync retry workers started"
);
+ // process async gmail operations (label changes, block/unblock sender, etc.)
+ for worker in gmail_ops_workers {
+ let db_gmail_ops = db.clone();
+ let sqs_client_gmail_ops = sqs_client.clone();
+ let gmail_client_gmail_ops = gmail_client.clone();
+ let auth_service_client_gmail_ops = auth_service_client.clone();
+ let redis_client_gmail_ops = redis_client.clone();
+ tokio::spawn(async move {
+ email_service::pubsub::gmail_ops::worker::run_worker(
+ db_gmail_ops,
+ worker,
+ sqs_client_gmail_ops,
+ gmail_client_gmail_ops,
+ auth_service_client_gmail_ops,
+ redis_client_gmail_ops,
+ false,
+ )
+ .await;
+ });
+ }
+ tracing::info!(
+ num_workers = config.gmail_ops_queue_workers,
+ "gmail_ops workers started"
+ );
+
+ // separate queue for retries to avoid backups for rate-limited gmail operations
+ for worker in gmail_ops_retry_workers {
+ let db_gmail_ops = db.clone();
+ let sqs_client_gmail_ops = sqs_client.clone();
+ let gmail_client_gmail_ops = gmail_client.clone();
+ let auth_service_client_gmail_ops = auth_service_client.clone();
+ let redis_client_gmail_ops = redis_client.clone();
+ tokio::spawn(async move {
+ email_service::pubsub::gmail_ops::worker::run_worker(
+ db_gmail_ops,
+ worker,
+ sqs_client_gmail_ops,
+ gmail_client_gmail_ops,
+ auth_service_client_gmail_ops,
+ redis_client_gmail_ops,
+ true,
+ )
+ .await;
+ });
+ }
+ tracing::info!(
+ num_workers = config.gmail_ops_retry_queue_workers,
+ "gmail_ops retry workers started"
+ );
+
// backfill user emails upon signup
for worker in backfill_workers {
let db_backfill = db_backfill.clone();
diff --git a/rust/cloud-storage/email_service/src/config.rs b/rust/cloud-storage/email_service/src/config.rs
index 8045d97217..3f34d1bfbe 100644
--- a/rust/cloud-storage/email_service/src/config.rs
+++ b/rust/cloud-storage/email_service/src/config.rs
@@ -29,6 +29,12 @@ pub struct Config {
/// to avoid backups for large inbox update operations
pub gmail_inbox_sync_retry_queue: String,
+ /// The SQS queue name for async Gmail operations (label changes, block/unblock, etc.)
+ pub gmail_ops_queue: String,
+
+ /// The SQS queue name for retrying rate-limited Gmail operations
+ pub gmail_ops_retry_queue: String,
+
/// The SQS queue name for search event
pub search_event_queue: String,
@@ -80,6 +86,18 @@ pub struct Config {
/// The queue max messages per poll for gmail retry inbox sync
pub inbox_sync_retry_queue_max_messages: i32,
+ /// The number of workers we spawn for gmail ops
+ pub gmail_ops_queue_workers: i32,
+
+ /// The queue max messages per poll for gmail ops
+ pub gmail_ops_queue_max_messages: i32,
+
+ /// The number of workers we spawn for gmail ops retry
+ pub gmail_ops_retry_queue_workers: i32,
+
+ /// The queue max messages per poll for gmail ops retry
+ pub gmail_ops_retry_queue_max_messages: i32,
+
/// The number of workers we spawn for sfs uploader
pub sfs_uploader_workers: i32,
@@ -158,6 +176,12 @@ impl Config {
let gmail_inbox_sync_retry_queue = std::env::var("GMAIL_INBOX_SYNC_RETRY_QUEUE")
.context("GMAIL_INBOX_SYNC_RETRY_QUEUE must be provided")?;
+ let gmail_ops_queue =
+ std::env::var("GMAIL_OPS_QUEUE").context("GMAIL_OPS_QUEUE must be provided")?;
+
+ let gmail_ops_retry_queue = std::env::var("GMAIL_OPS_RETRY_QUEUE")
+ .context("GMAIL_OPS_RETRY_QUEUE must be provided")?;
+
let search_event_queue =
std::env::var("SEARCH_EVENT_QUEUE").context("SEARCH_EVENT_QUEUE must be provided")?;
@@ -228,6 +252,27 @@ impl Config {
.parse::<i32>()
.unwrap();
+ let gmail_ops_queue_workers: i32 = std::env::var("GMAIL_OPS_QUEUE_WORKERS")
+ .unwrap_or("5".to_string())
+ .parse::<i32>()
+ .unwrap();
+
+ let gmail_ops_queue_max_messages: i32 = std::env::var("GMAIL_OPS_QUEUE_MAX_MESSAGES")
+ .unwrap_or("10".to_string())
+ .parse::<i32>()
+ .unwrap();
+
+ let gmail_ops_retry_queue_workers: i32 = std::env::var("GMAIL_OPS_RETRY_QUEUE_WORKERS")
+ .unwrap_or("2".to_string())
+ .parse::<i32>()
+ .unwrap();
+
+ let gmail_ops_retry_queue_max_messages: i32 =
+ std::env::var("GMAIL_OPS_RETRY_QUEUE_MAX_MESSAGES")
+ .unwrap_or("10".to_string())
+ .parse::<i32>()
+ .unwrap();
+
let sfs_uploader_workers: i32 = std::env::var("SFS_UPLOADER_WORKERS")
.unwrap_or("3".to_string())
.parse::<i32>()
@@ -292,6 +337,8 @@ impl Config {
email_scheduled_queue,
gmail_inbox_sync_queue,
gmail_inbox_sync_retry_queue,
+ gmail_ops_queue,
+ gmail_ops_retry_queue,
search_event_queue,
gmail_gcp_queue,
notification_queue,
@@ -310,6 +357,10 @@ impl Config {
inbox_sync_queue_max_messages,
inbox_sync_retry_queue_workers,
inbox_sync_retry_queue_max_messages,
+ gmail_ops_queue_workers,
+ gmail_ops_queue_max_messages,
+ gmail_ops_retry_queue_workers,
+ gmail_ops_retry_queue_max_messages,
sfs_uploader_workers,
redis_rate_limit_reqs,
redis_rate_limit_reqs_backfill,
diff --git a/rust/cloud-storage/email_service/src/main.rs b/rust/cloud-storage/email_service/src/main.rs
index a0037f1e6c..f7102ce883 100644
--- a/rust/cloud-storage/email_service/src/main.rs
+++ b/rust/cloud-storage/email_service/src/main.rs
@@ -71,6 +71,7 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = sqs_client::SQS::new(macro_aws_config::sqs_client().await)
.gmail_inbox_sync_queue(&config.gmail_inbox_sync_queue)
.gmail_inbox_sync_retry_queue(&config.gmail_inbox_sync_retry_queue)
+ .gmail_ops_queue(&config.gmail_ops_queue)
.search_event_queue(&config.search_event_queue)
.email_backfill_queue(&config.backfill_queue)
.email_scheduled_queue(&config.email_scheduled_queue)
@@ -126,12 +127,10 @@ async fn main() -> anyhow::Result<()> {
let sqs_client = Arc::new(sqs_client);
let gmail_client = Arc::new(gmail_client);
- let gmail_label_modifier = email::outbound::GmailClientLabelModifier::new(gmail_client.clone());
let email_service = EmailRouterState::new(EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
FrecencyQueryServiceImpl::new(FrecencyPgStorage::new(db.clone())),
(*sqs_client).clone(),
- gmail_label_modifier,
config.sent_undo_delay_secs,
));
let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/error_handlers.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/error_handlers.rs
new file mode 100644
index 0000000000..d45fbc00fe
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/error_handlers.rs
@@ -0,0 +1,47 @@
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use models_email::gmail::gmail_ops::GmailOpsPubsubMessage;
+use models_email::service::pubsub::{DetailedError, ProcessingError};
+use sqs_worker::cleanup_message;
+
+/// Handles non-retryable errors by cleaning up the SQS message.
+#[tracing::instrument(skip(ctx, message), err)]
+pub async fn handle_non_retryable_error(
+ ctx: &GmailOpsContext,
+ message: &aws_sdk_sqs::types::Message,
+ data: &GmailOpsPubsubMessage,
+ e: &DetailedError,
+) -> anyhow::Result<()> {
+ tracing::error!(error = ?e, payload = ?data.operation, "Non-retryable error processing gmail ops message. The message will be deleted.");
+
+ cleanup_message(&ctx.sqs_worker, message).await?;
+ Ok(())
+}
+
+/// Handles retryable errors by leaving the message in the queue.
+#[tracing::instrument(skip(data, e), err)]
+pub async fn handle_retryable_error(
+ data: &GmailOpsPubsubMessage,
+ e: &DetailedError,
+) -> anyhow::Result<()> {
+ tracing::debug!(error = ?e, payload = ?data.operation, "Retryable error processing gmail ops message.");
+
+ Ok(())
+}
+
+/// Adds an operation name prefix to a ProcessingError's source field.
+pub fn prefix_error_source(error: ProcessingError, operation_name: &str) -> ProcessingError {
+ match error {
+ ProcessingError::Retryable(DetailedError { reason, source }) => {
+ ProcessingError::Retryable(DetailedError {
+ reason,
+ source: anyhow::anyhow!("{}: {}", operation_name, source),
+ })
+ }
+ ProcessingError::NonRetryable(DetailedError { reason, source }) => {
+ ProcessingError::NonRetryable(DetailedError {
+ reason,
+ source: anyhow::anyhow!("{}: {}", operation_name, source),
+ })
+ }
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/mod.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/mod.rs
new file mode 100644
index 0000000000..02edf7f6b0
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/mod.rs
@@ -0,0 +1,4 @@
+pub mod error_handlers;
+pub mod operations;
+pub mod process;
+pub mod worker;
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/block_sender.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/block_sender.rs
new file mode 100644
index 0000000000..83d563c7a0
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/block_sender.rs
@@ -0,0 +1,53 @@
+use crate::pubsub::gmail_ops::process::{check_gmail_rate_limit, fetch_gmail_token};
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use models_email::gmail::gmail_ops::BlockSenderPayload;
+use models_email::gmail::operations::GmailApiOperation;
+use models_email::service::link::Link;
+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
+
+/// Creates a filter to block a sender in Gmail.
+#[tracing::instrument(skip(ctx, link), err)]
+pub async fn block_sender(
+ ctx: &GmailOpsContext,
+ link: &Link,
+ payload: &BlockSenderPayload,
+) -> Result<(), ProcessingError> {
+ check_gmail_rate_limit(
+ ctx,
+ link.id,
+ GmailApiOperation::SettingsFiltersCreate,
+ models_email::gmail::gmail_ops::GmailOpsOperation::BlockSender(payload.clone()),
+ )
+ .await?;
+
+ let gmail_access_token = fetch_gmail_token(ctx, link).await?;
+
+ // Check if already blocked
+ let existing_filter = ctx
+ .gmail_client
+ .find_block_filter_for_sender(&gmail_access_token, &payload.email_address)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("Failed to check existing block filters: {}", e),
+ })
+ })?;
+
+ if existing_filter.is_some() {
+ tracing::debug!("Sender is already blocked, skipping");
+ return Ok(());
+ }
+
+ ctx.gmail_client
+ .block_sender(&gmail_access_token, &payload.email_address)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("Failed to block sender in Gmail: {}", e),
+ })
+ })?;
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/delete_label.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/delete_label.rs
new file mode 100644
index 0000000000..9bd44a5e8b
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/delete_label.rs
@@ -0,0 +1,46 @@
+use crate::pubsub::gmail_ops::process::{check_gmail_rate_limit, fetch_gmail_token};
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use models_email::gmail::gmail_ops::DeleteLabelPayload;
+use models_email::gmail::operations::GmailApiOperation;
+use models_email::service::link::Link;
+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
+
+/// Deletes a label from Gmail.
+#[tracing::instrument(skip(ctx, link), err)]
+pub async fn delete_label(
+ ctx: &GmailOpsContext,
+ link: &Link,
+ payload: &DeleteLabelPayload,
+) -> Result<(), ProcessingError> {
+ check_gmail_rate_limit(
+ ctx,
+ link.id,
+ GmailApiOperation::LabelsDelete,
+ models_email::gmail::gmail_ops::GmailOpsOperation::DeleteLabel(payload.clone()),
+ )
+ .await?;
+
+ let gmail_access_token = fetch_gmail_token(ctx, link).await?;
+
+ match ctx
+ .gmail_client
+ .delete_label(&gmail_access_token, &payload.provider_label_id)
+ .await
+ {
+ Ok(()) => {}
+ Err(models_email::gmail::error::GmailError::NotFound(_)) => {
+ tracing::warn!(
+ provider_label_id = %payload.provider_label_id,
+ "Label not found in Gmail when attempting to delete, ignoring"
+ );
+ }
+ Err(e) => {
+ return Err(ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("Failed to delete label from Gmail: {}", e),
+ }));
+ }
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/mod.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/mod.rs
new file mode 100644
index 0000000000..fad70c0ff4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/mod.rs
@@ -0,0 +1,4 @@
+pub mod block_sender;
+pub mod delete_label;
+pub mod modify_message_labels;
+pub mod unblock_sender;
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/modify_message_labels.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/modify_message_labels.rs
new file mode 100644
index 0000000000..98e4d57f23
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/modify_message_labels.rs
@@ -0,0 +1,165 @@
+use crate::pubsub::gmail_ops::process::{check_gmail_rate_limit, fetch_gmail_token};
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use anyhow::Context;
+use models_email::gmail::error::GmailError;
+use models_email::gmail::gmail_ops::ModifyMessageLabelsPayload;
+use models_email::gmail::operations::GmailApiOperation;
+use models_email::service;
+use models_email::service::link::Link;
+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
+
+/// Modifies labels for a single message in Gmail. Reverts DB changes on permanent failure.
+/// Transient errors (5xx, network) are retried; permanent errors (4xx) trigger revert.
+#[tracing::instrument(skip(ctx, link), err)]
+pub async fn modify_message_labels(
+ ctx: &GmailOpsContext,
+ link: &Link,
+ payload: &ModifyMessageLabelsPayload,
+) -> Result<(), ProcessingError> {
+ check_gmail_rate_limit(
+ ctx,
+ link.id,
+ GmailApiOperation::MessagesModify,
+ models_email::gmail::gmail_ops::GmailOpsOperation::ModifyMessageLabels(payload.clone()),
+ )
+ .await?;
+
+ let gmail_access_token = fetch_gmail_token(ctx, link).await?;
+
+ let result = ctx
+ .gmail_client
+ .modify_message_labels(
+ &gmail_access_token,
+ &payload.provider_message_id,
+ &payload.labels_to_add,
+ &payload.labels_to_remove,
+ )
+ .await;
+
+ match result {
+ Ok(()) => Ok(()),
+ Err(
+ e @ (GmailError::ServerError(..)
+ | GmailError::HttpRequest(_)
+ | GmailError::RateLimitExceeded),
+ ) => {
+ tracing::warn!(
+ error = ?e,
+ db_message_id = %payload.db_message_id,
+ provider_message_id = %payload.provider_message_id,
+ "Transient Gmail error modifying labels, will retry"
+ );
+ Err(ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("{}", e),
+ }))
+ }
+ Err(e) => {
+ tracing::error!(
+ error = ?e,
+ db_message_id = %payload.db_message_id,
+ provider_message_id = %payload.provider_message_id,
+ "Permanent Gmail error modifying labels, reverting database changes"
+ );
+
+ revert_db_changes(ctx, link, payload).await;
+
+ Err(ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("{}", e),
+ }))
+ }
+ }
+}
+
+/// Reverts the optimistic DB changes for a single message that failed in Gmail.
+/// Derives revert context from the link and payload.
+async fn revert_db_changes(
+ ctx: &GmailOpsContext,
+ link: &Link,
+ payload: &ModifyMessageLabelsPayload,
+) {
+ let mut tx = match ctx.db.begin().await {
+ Ok(tx) => tx,
+ Err(e) => {
+ tracing::error!(error=?e, "Failed to begin transaction for reversion");
+ return;
+ }
+ };
+
+ let failed_ids = vec![payload.db_message_id];
+ let is_adding = !payload.labels_to_add.is_empty();
+
+ let Some(provider_label_id) = (if is_adding {
+ payload.labels_to_add.first()
+ } else {
+ payload.labels_to_remove.first()
+ }) else {
+ tracing::error!("No label IDs in payload, cannot revert");
+ return;
+ };
+
+ let revert_result = async {
+ if is_adding {
+ email_db_client::labels::delete::delete_message_labels_batch(
+ &mut *tx,
+ &failed_ids,
+ provider_label_id,
+ link.id,
+ )
+ .await
+ .context("Failed to revert adding labels")?;
+ } else {
+ email_db_client::labels::insert::insert_message_labels_batch(
+ &mut *tx,
+ &failed_ids,
+ provider_label_id,
+ link.id,
+ )
+ .await
+ .context("Failed to revert removing labels")?;
+ }
+
+ if *provider_label_id == service::label::system_labels::UNREAD {
+ email_db_client::messages::update::update_message_read_status_batch(
+ &mut *tx,
+ failed_ids.clone(),
+ &link.fusionauth_user_id,
+ is_adding,
+ )
+ .await
+ .context("Failed to revert message read status")?;
+ } else if *provider_label_id == service::label::system_labels::STARRED {
+ email_db_client::messages::update::update_message_starred_status_batch(
+ &mut *tx,
+ failed_ids,
+ &link.fusionauth_user_id,
+ !is_adding,
+ )
+ .await
+ .context("Failed to revert message starred status")?;
+ }
+
+ anyhow::Ok(())
+ }
+ .await;
+
+ match revert_result {
+ Ok(_) => {
+ if let Err(e) = tx.commit().await {
+ tracing::error!(error=?e, "Unable to commit transaction for revert");
+ } else {
+ tracing::info!(
+ db_message_id = %payload.db_message_id,
+ "Successfully reverted database changes after Gmail API failure"
+ );
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "Revert failed, rolling back");
+ if let Err(rollback_err) = tx.rollback().await {
+ tracing::error!(error=?rollback_err, "Failed to rollback revert transaction");
+ }
+ }
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/unblock_sender.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/unblock_sender.rs
new file mode 100644
index 0000000000..e3f8ec1f30
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/operations/unblock_sender.rs
@@ -0,0 +1,41 @@
+use crate::pubsub::gmail_ops::process::{check_gmail_rate_limit, fetch_gmail_token};
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use models_email::gmail::gmail_ops::UnblockSenderPayload;
+use models_email::gmail::operations::GmailApiOperation;
+use models_email::service::link::Link;
+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
+
+/// Finds and removes a block filter for a sender in Gmail.
+#[tracing::instrument(skip(ctx, link), err)]
+pub async fn unblock_sender(
+ ctx: &GmailOpsContext,
+ link: &Link,
+ payload: &UnblockSenderPayload,
+) -> Result<(), ProcessingError> {
+ check_gmail_rate_limit(
+ ctx,
+ link.id,
+ GmailApiOperation::SettingsFiltersDelete,
+ models_email::gmail::gmail_ops::GmailOpsOperation::UnblockSender(payload.clone()),
+ )
+ .await?;
+
+ let gmail_access_token = fetch_gmail_token(ctx, link).await?;
+
+ let result = ctx
+ .gmail_client
+ .unblock_sender(&gmail_access_token, &payload.email_address)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("Failed to unblock sender in Gmail: {}", e),
+ })
+ })?;
+
+ if !result {
+ tracing::warn!("No block filter found for sender in Gmail");
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs
new file mode 100644
index 0000000000..0f144532bc
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/process.rs
@@ -0,0 +1,191 @@
+use crate::pubsub::gmail_ops::error_handlers::prefix_error_source;
+use crate::pubsub::gmail_ops::operations::block_sender::block_sender;
+use crate::pubsub::gmail_ops::operations::delete_label::delete_label;
+use crate::pubsub::gmail_ops::operations::modify_message_labels::modify_message_labels;
+use crate::pubsub::gmail_ops::operations::unblock_sender::unblock_sender;
+use crate::pubsub::gmail_ops::worker::GmailOpsContext;
+use crate::util::redis::rate_limit::RateLimitArgs;
+use anyhow::{Context, Result, anyhow};
+use models_email::gmail::gmail_ops::{GmailOpsOperation, GmailOpsPubsubMessage};
+use models_email::gmail::operations::GmailApiOperation;
+use models_email::service::link::Link;
+use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
+use sqs_worker::cleanup_message;
+use uuid::Uuid;
+
+/// Processes a message from the gmail ops queue.
+pub async fn process_message(
+ ctx: GmailOpsContext,
+ message: &aws_sdk_sqs::types::Message,
+) -> Result<()> {
+ let data = match extract_gmail_ops_message(message) {
+ Ok(data) => data,
+ Err(e) => {
+ tracing::error!(error = %e, "Failed to extract gmail ops message, this is non-retryable.");
+ if let Err(cleanup_err) = cleanup_message(&ctx.sqs_worker, message).await {
+ tracing::error!(error = %cleanup_err, "Failed to clean up message after extraction error");
+ }
+ return Err(e);
+ }
+ };
+
+ let processing_result = inner_process_message(&ctx, &data).await;
+
+ match processing_result {
+ Ok(()) => {
+ cleanup_message(&ctx.sqs_worker, message).await?;
+ Ok(())
+ }
+ Err(ProcessingError::NonRetryable(e)) => {
+ crate::pubsub::gmail_ops::error_handlers::handle_non_retryable_error(
+ &ctx, message, &data, &e,
+ )
+ .await
+ }
+ Err(ProcessingError::Retryable(e)) => {
+ crate::pubsub::gmail_ops::error_handlers::handle_retryable_error(&data, &e).await
+ }
+ }
+}
+
+#[tracing::instrument(skip(ctx, data), err)]
+async fn inner_process_message(
+ ctx: &GmailOpsContext,
+ data: &GmailOpsPubsubMessage,
+) -> Result<(), ProcessingError> {
+ let link = email_db_client::links::get::fetch_link_by_id(&ctx.db, data.link_id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch link from database"),
+ })
+ })?
+ .ok_or_else(|| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::LinkNotFound,
+ source: anyhow!("No link found for id {}", data.link_id),
+ })
+ })?;
+
+ match &data.operation {
+ GmailOpsOperation::ModifyMessageLabels(payload) => {
+ modify_message_labels(ctx, &link, payload)
+ .await
+ .map_err(|e| prefix_error_source(e, "modify_message_labels"))?;
+ tracing::debug!("Successfully processed modify message labels operation");
+ }
+ GmailOpsOperation::DeleteLabel(payload) => {
+ delete_label(ctx, &link, payload)
+ .await
+ .map_err(|e| prefix_error_source(e, "delete_label"))?;
+ tracing::debug!("Successfully processed delete label operation");
+ }
+ GmailOpsOperation::BlockSender(payload) => {
+ block_sender(ctx, &link, payload)
+ .await
+ .map_err(|e| prefix_error_source(e, "block_sender"))?;
+ tracing::debug!("Successfully processed block sender operation");
+ }
+ GmailOpsOperation::UnblockSender(payload) => {
+ unblock_sender(ctx, &link, payload)
+ .await
+ .map_err(|e| prefix_error_source(e, "unblock_sender"))?;
+ tracing::debug!("Successfully processed unblock sender operation");
+ }
+ }
+
+ Ok(())
+}
+
+/// Extracts the message from the SQS message body.
+#[tracing::instrument(skip(message))]
+fn extract_gmail_ops_message(
+ message: &aws_sdk_sqs::types::Message,
+) -> anyhow::Result<GmailOpsPubsubMessage> {
+ let message_body = message.body().context("message body not found")?;
+ let gmail_ops_message: GmailOpsPubsubMessage = serde_json::from_str(message_body)
+ .context("Failed to deserialize message body to GmailOpsPubsubMessage")?;
+ Ok(gmail_ops_message)
+}
+
+/// Fetches a Gmail access token for use in pubsub workers.
+#[tracing::instrument(skip(ctx, link), err)]
+pub async fn fetch_gmail_token(
+ ctx: &GmailOpsContext,
+ link: &Link,
+) -> Result<String, ProcessingError> {
+ let gmail_access_token = crate::util::gmail::auth::fetch_token_or_delete_on_revocation(
+ link,
+ &ctx.redis_client,
+ &ctx.auth_service_client,
+ &ctx.sqs_client,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::AccessTokenFetchFailed,
+ source: e.context("Failed to fetch gmail access token"),
+ })
+ })?;
+ Ok(gmail_access_token)
+}
+
+/// Checks Gmail API rate limits and routes processing accordingly.
+///
+/// Uses a two-tier system to prevent rate limit backpressure:
+/// - **Primary worker**: If rate limited, enqueues to retry queue and returns non-retryable error
+/// - **Retry worker**: If rate limited, returns retryable error so it gets tried again later
+#[tracing::instrument(skip(ctx, gmail_ops_operation), err)]
+pub async fn check_gmail_rate_limit(
+ ctx: &GmailOpsContext,
+ link_id: Uuid,
+ operation: GmailApiOperation,
+ gmail_ops_operation: GmailOpsOperation,
+) -> Result<(), ProcessingError> {
+ if !ctx
+ .redis_client
+ .is_rate_limited(RateLimitArgs {
+ user_id: link_id,
+ operation,
+ is_backfill: false,
+ })
+ .await
+ {
+ return Ok(());
+ }
+
+ if !ctx.retry_worker {
+ tracing::info!(
+ link_id = %link_id,
+ "Gmail API rate limited, moving message from primary queue to retry queue"
+ );
+ ctx.sqs_client
+ .enqueue_gmail_ops_retry_notification(GmailOpsPubsubMessage {
+ link_id,
+ operation: gmail_ops_operation,
+ })
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::SqsEnqueueFailed,
+ source: e.context("Failed to enqueue gmail ops retry message"),
+ })
+ })?;
+ Err(ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::GmailApiRateLimited,
+ source: anyhow::Error::msg(
+ "Gmail API rate limit exceeded, enqueued message on retry queue",
+ ),
+ }))
+ } else {
+ tracing::info!(
+ link_id = %link_id,
+ "Gmail API rate limited in retry worker, message will be retried after visibility timeout"
+ );
+ Err(ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::GmailApiRateLimited,
+ source: anyhow::Error::msg("Gmail API rate limit exceeded in retry worker"),
+ }))
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/gmail_ops/worker.rs b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/worker.rs
new file mode 100644
index 0000000000..ce199db1e2
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/gmail_ops/worker.rs
@@ -0,0 +1,106 @@
+use crate::pubsub::gmail_ops::process;
+use crate::util::redis::RedisClient;
+use authentication_service_client::AuthServiceClient;
+use futures::StreamExt;
+use gmail_client::GmailClient;
+use sqlx::PgPool;
+
+/// Context for the Gmail operations worker. Simpler than PubSubContext since
+/// these operations only need Gmail API access and DB for reverts.
+#[derive(Clone)]
+pub struct GmailOpsContext {
+ pub db: PgPool,
+ pub sqs_worker: sqs_worker::SQSWorker,
+ pub sqs_client: sqs_client::SQS,
+ pub gmail_client: GmailClient,
+ pub auth_service_client: AuthServiceClient,
+ pub redis_client: RedisClient,
+ pub retry_worker: bool,
+}
+
+/// Runs the Gmail operations worker, processing messages from the queue.
+pub async fn run_worker(
+ db: PgPool,
+ worker: sqs_worker::SQSWorker,
+ sqs_client: sqs_client::SQS,
+ gmail_client: GmailClient,
+ auth_service_client: AuthServiceClient,
+ redis_client: RedisClient,
+ retry_worker: bool,
+) {
+ let ctx = GmailOpsContext {
+ db,
+ sqs_worker: worker.clone(),
+ sqs_client,
+ gmail_client,
+ auth_service_client,
+ redis_client,
+ retry_worker,
+ };
+
+ loop {
+ let worker_result = tokio::spawn({
+ let ctx = ctx.clone();
+ let worker = worker.clone();
+ async move {
+ loop {
+ match worker.receive_messages().await {
+ Ok(messages) => {
+ if messages.is_empty() {
+ continue;
+ }
+ let result = futures::stream::iter(messages.iter())
+ .then(|message| {
+ let ctx = ctx.clone();
+ async move {
+ let result =
+ process::process_message(ctx, message).await;
+
+ match result {
+ Ok(_) => Ok(()),
+ Err(e) => Err((
+ message
+ .message_id
+ .clone()
+ .unwrap_or_default(),
+ e,
+ )),
+ }
+ }
+ })
+ .collect::<Vec<Result<(), (String, anyhow::Error)>>>()
+ .await;
+
+ let errors = result
+ .into_iter()
+ .filter_map(|result| result.err())
+ .collect::<Vec<(String, anyhow::Error)>>();
+
+ if !errors.is_empty() {
+ for (message_id, error) in errors {
+ tracing::error!(message_id, error=?error, "error processing gmail ops message");
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "error receiving gmail ops messages");
+ }
+ }
+ }
+ }
+ })
+ .await;
+
+ match worker_result {
+ Ok(_) => {
+ tracing::error!("gmail ops worker exited successfully?");
+ }
+ Err(e) => {
+ tracing::error!(error=?e, "gmail ops worker crashed with error");
+ }
+ }
+
+ tracing::info!("GMAIL OPS WORKER RESTARTING...");
+ tokio::time::sleep(std::time::Duration::from_secs(5)).await;
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/mod.rs b/rust/cloud-storage/email_service/src/pubsub/mod.rs
index 94b21ae452..7bb16e02f4 100644
--- a/rust/cloud-storage/email_service/src/pubsub/mod.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/mod.rs
@@ -1,5 +1,6 @@
pub mod backfill;
pub(crate) mod context;
+pub mod gmail_ops;
pub mod inbox_sync;
pub mod link_manager;
pub mod scheduled;
diff --git a/rust/cloud-storage/gmail_client/src/labels.rs b/rust/cloud-storage/gmail_client/src/labels.rs
index 97e6ef04eb..f62511fd23 100644
--- a/rust/cloud-storage/gmail_client/src/labels.rs
+++ b/rust/cloud-storage/gmail_client/src/labels.rs
@@ -1,6 +1,5 @@
use crate::GmailClient;
use anyhow::Context;
-use futures::{StreamExt, stream};
use models_email::email::service;
use models_email::gmail::ModifyLabelsRequest;
use models_email::gmail::error::GmailError;
@@ -20,7 +19,7 @@ pub async fn modify_message_labels(
provider_message_id: &str,
label_ids_to_add: &[String],
label_ids_to_remove: &[String],
-) -> anyhow::Result<()> {
+) -> Result<(), GmailError> {
let url = format!(
"{}/users/me/messages/{}/modify",
client.base_url, provider_message_id
@@ -39,7 +38,7 @@ pub async fn modify_message_labels(
.json(&payload)
.send()
.await
- .context("Failed to send request to Gmail API (modify message labels)")?;
+ .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
let status = response.status();
if !status.is_success() {
@@ -47,83 +46,21 @@ pub async fn modify_message_labels(
.text()
.await
.unwrap_or_else(|_| "Failed to read error body".to_string());
- anyhow::bail!(
- "Gmail API error {} (modify message labels) for provider_message_id: {}: {}",
- status,
- provider_message_id,
- error_body
- );
- }
-
- Ok(())
-}
-
-#[tracing::instrument(skip_all, fields(message_count = db_provider_id_tuples.len()))]
-pub async fn batch_modify_labels(
- client: &GmailClient,
- gmail_access_token: &str,
- db_provider_id_tuples: Vec<(Uuid, String)>,
- labels_to_add: Vec<String>,
- labels_to_remove: Vec<String>,
-) -> (Vec<Uuid>, Vec<Uuid>) {
- let label_tasks = db_provider_id_tuples
- .clone()
- .into_iter()
- .map(move |message| {
- let client = client.clone();
- let gmail_access_token = gmail_access_token.to_string();
- let labels_to_add = labels_to_add.clone();
- let labels_to_remove = labels_to_remove.clone();
-
- async move {
- let db_id = message.0;
- let provider_id = message.1;
- let labels_to_add = labels_to_add;
- let labels_to_remove = labels_to_remove;
- // Update in Gmail - remove the label
- let gmail_result = client
- .modify_message_labels(
- &gmail_access_token,
- &provider_id,
- &labels_to_add,
- &labels_to_remove,
- )
- .await;
-
- if let Err(e) = gmail_result {
- tracing::error!(
- error = ?e,
- message_id = %db_id,
- provider_id = %provider_id,
- "Failed to remove label in Gmail"
- );
- return (db_id, Err(e));
- }
-
- (db_id, Ok(()))
- }
+ return Err(match status.as_u16() {
+ 401 => GmailError::Unauthorized,
+ 403 => GmailError::Forbidden,
+ 404 => GmailError::NotFound(error_body),
+ 429 => GmailError::RateLimitExceeded,
+ s if s >= 500 => GmailError::ServerError(s, error_body),
+ _ => GmailError::ApiError(format!(
+ "Gmail API error {} (modify message labels): {}",
+ status, error_body
+ )),
});
-
- // Process tasks with limited concurrency
- const MAX_CONCURRENT: usize = 20;
- let results = stream::iter(label_tasks)
- .buffer_unordered(MAX_CONCURRENT)
- .collect::<Vec<_>>()
- .await;
-
- // Separate successful and failed messages
- let mut successful_msg_ids = Vec::new();
- let mut failed_msg_ids = Vec::new();
-
- for (msg_id, result) in results {
- match result {
- Ok(_) => successful_msg_ids.push(msg_id),
- Err(_) => failed_msg_ids.push(msg_id),
- }
}
- (successful_msg_ids, failed_msg_ids)
+ Ok(())
}
#[tracing::instrument(skip(client, access_token), err)]
diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rs
index ad157a3069..82e129aa8b 100644
--- a/rust/cloud-storage/gmail_client/src/lib.rs
+++ b/rust/cloud-storage/gmail_client/src/lib.rs
@@ -171,7 +171,7 @@ impl GmailClient {
provider_message_id: &str,
label_ids_to_add: &[String],
label_ids_to_remove: &[String],
- ) -> anyhow::Result<()> {
+ ) -> Result<(), GmailError> {
labels::modify_message_labels(
self,
access_token,
@@ -184,27 +184,6 @@ impl GmailClient {
// Batch adds and removes Gmail labels from multiple messages
/// Returns a tuple of (successful_message_ids, failed_message_ids)
- #[tracing::instrument(
- skip(self, gmail_access_token),
- fields(message_count = %db_provider_id_tuples.len())
- )]
- pub async fn batch_modify_labels(
- &self,
- gmail_access_token: &str,
- db_provider_id_tuples: Vec<(Uuid, String)>,
- labels_to_add: Vec<String>,
- labels_to_remove: Vec<String>,
- ) -> (Vec<Uuid>, Vec<Uuid>) {
- labels::batch_modify_labels(
- self,
- gmail_access_token,
- db_provider_id_tuples,
- labels_to_add,
- labels_to_remove,
- )
- .await
- }
-
/// Fetches a specific message from Gmail by its provider ID.
/// Returns raw Gmail MessageResource - callers should map to service layer structs.
#[tracing::instrument(skip(self, access_token), err)]
diff --git a/rust/cloud-storage/memory/src/context.rs b/rust/cloud-storage/memory/src/context.rs
index 915a5dcbac..51c19d63ce 100644
--- a/rust/cloud-storage/memory/src/context.rs
+++ b/rust/cloud-storage/memory/src/context.rs
@@ -99,7 +99,6 @@ pub async fn build_tool_service_context(pool: sqlx::PgPool) -> anyhow::Result<To
EmailPgRepo::new(pool.clone()),
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
let channels_service = ChannelServiceImpl::new(
diff --git a/rust/cloud-storage/models_email/src/gmail/error.rs b/rust/cloud-storage/models_email/src/gmail/error.rs
index edc30d6053..5e403787b1 100644
--- a/rust/cloud-storage/models_email/src/gmail/error.rs
+++ b/rust/cloud-storage/models_email/src/gmail/error.rs
@@ -11,6 +11,9 @@ pub enum GmailError {
#[error("Forbidden: Insufficient permissions (403)")]
Forbidden,
+ #[error("Server Error ({0}): {1}")]
+ ServerError(u16, String),
+
#[error("HTTP Request Error: {0}")]
HttpRequest(String),
diff --git a/rust/cloud-storage/models_email/src/gmail/gmail_ops.rs b/rust/cloud-storage/models_email/src/gmail/gmail_ops.rs
new file mode 100644
index 0000000000..b5d8da13ec
--- /dev/null
+++ b/rust/cloud-storage/models_email/src/gmail/gmail_ops.rs
@@ -0,0 +1,55 @@
+use serde::{Deserialize, Serialize};
+use strum::Display;
+use uuid::Uuid;
+
+/// Message type for the Gmail operations worker queue.
+/// Contains the link_id (to fetch the Gmail access token) and the operation to perform.
+#[derive(Debug, Deserialize, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct GmailOpsPubsubMessage {
+ pub link_id: Uuid,
+ pub operation: GmailOpsOperation,
+}
+
+/// Operations that can be performed asynchronously against the Gmail API.
+#[derive(Debug, Deserialize, Serialize, Clone, Display)]
+#[serde(rename_all = "snake_case")]
+pub enum GmailOpsOperation {
+ /// Add or remove labels from messages in Gmail
+ ModifyMessageLabels(ModifyMessageLabelsPayload),
+ /// Delete a label from Gmail
+ DeleteLabel(DeleteLabelPayload),
+ /// Create a filter to block a sender in Gmail
+ BlockSender(BlockSenderPayload),
+ /// Remove a block filter for a sender in Gmail
+ UnblockSender(UnblockSenderPayload),
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct ModifyMessageLabelsPayload {
+ /// The database ID of the message to modify
+ pub db_message_id: Uuid,
+ /// The Gmail provider message ID
+ pub provider_message_id: String,
+ pub labels_to_add: Vec<String>,
+ pub labels_to_remove: Vec<String>,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct DeleteLabelPayload {
+ pub provider_label_id: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct BlockSenderPayload {
+ pub email_address: String,
+}
+
+#[derive(Debug, Deserialize, Serialize, Clone)]
+#[serde(rename_all = "camelCase")]
+pub struct UnblockSenderPayload {
+ pub email_address: String,
+}
diff --git a/rust/cloud-storage/models_email/src/gmail/mod.rs b/rust/cloud-storage/models_email/src/gmail/mod.rs
index f352e8993f..205926c8c5 100644
--- a/rust/cloud-storage/models_email/src/gmail/mod.rs
+++ b/rust/cloud-storage/models_email/src/gmail/mod.rs
@@ -1,6 +1,7 @@
pub mod contacts;
pub mod error;
pub mod filters;
+pub mod gmail_ops;
pub mod history;
pub mod inbox_sync;
pub mod labels;
diff --git a/rust/cloud-storage/soup/examples/ai_tools_cli.rs b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
index faa9b9567c..2c13db2edd 100644
--- a/rust/cloud-storage/soup/examples/ai_tools_cli.rs
+++ b/rust/cloud-storage/soup/examples/ai_tools_cli.rs
@@ -55,7 +55,6 @@ async fn main() {
email_repo,
frecency_service.clone(),
email::domain::ports::NoOpEnqueuer,
- email::domain::ports::NoOpGmailLabelModifier,
0,
);
diff --git a/rust/cloud-storage/sqs_client/src/email.rs b/rust/cloud-storage/sqs_client/src/email.rs
index 81d0a4f8ff..d0d805140a 100644
--- a/rust/cloud-storage/sqs_client/src/email.rs
+++ b/rust/cloud-storage/sqs_client/src/email.rs
@@ -44,7 +44,7 @@ impl SQS {
return enqueue_link_manager_notification(&self.inner, link_manager_queue, message)
.await;
}
- Err(anyhow::anyhow!("link_manager_queue is not configured"))
+ anyhow::bail!("link_manager_queue is not configured")
}
/// Sends a message to the email backfill queue
@@ -125,6 +125,37 @@ impl EmailMessageEnqueuer for SQS {
)
.await
}
+
+ #[tracing::instrument(skip(self, messages, labels_to_add, labels_to_remove), err)]
+ async fn enqueue_gmail_ops_modify_labels_batch(
+ &self,
+ link_id: Uuid,
+ messages: Vec<(Uuid, String)>,
+ labels_to_add: Vec<String>,
+ labels_to_remove: Vec<String>,
+ ) -> Result<(), Self::Err> {
+ use models_email::gmail::gmail_ops::{
+ GmailOpsOperation, GmailOpsPubsubMessage, ModifyMessageLabelsPayload,
+ };
+
+ let gmail_ops_messages: Vec<GmailOpsPubsubMessage> = messages
+ .into_iter()
+ .map(
+ |(db_message_id, provider_message_id)| GmailOpsPubsubMessage {
+ link_id,
+ operation: GmailOpsOperation::ModifyMessageLabels(ModifyMessageLabelsPayload {
+ db_message_id,
+ provider_message_id,
+ labels_to_add: labels_to_add.clone(),
+ labels_to_remove: labels_to_remove.clone(),
+ }),
+ },
+ )
+ .collect();
+
+ self.enqueue_gmail_ops_notifications_batch(gmail_ops_messages)
+ .await
+ }
}
#[tracing::instrument(skip(sqs_client))]
diff --git a/rust/cloud-storage/sqs_client/src/gmail.rs b/rust/cloud-storage/sqs_client/src/gmail.rs
index 7d3b044672..74ffda332d 100644
--- a/rust/cloud-storage/sqs_client/src/gmail.rs
+++ b/rust/cloud-storage/sqs_client/src/gmail.rs
@@ -1,4 +1,7 @@
-use crate::SQS;
+use crate::{MAX_BATCH_SIZE, SQS};
+use anyhow::Context;
+use aws_sdk_sqs::types::SendMessageBatchRequestEntry;
+use models_email::gmail::gmail_ops::GmailOpsPubsubMessage;
use models_email::gmail::inbox_sync::InboxSyncPubsubMessage;
impl SQS {
@@ -12,6 +15,16 @@ impl SQS {
self
}
+ pub fn gmail_ops_queue(mut self, gmail_ops_queue: &str) -> Self {
+ self.gmail_ops_queue = Some(gmail_ops_queue.to_string());
+ self
+ }
+
+ pub fn gmail_ops_retry_queue(mut self, gmail_ops_retry_queue: &str) -> Self {
+ self.gmail_ops_retry_queue = Some(gmail_ops_retry_queue.to_string());
+ self
+ }
+
/// Sends a notification message to the Gmail inbox sync queue
#[tracing::instrument(skip(self))]
pub async fn enqueue_gmail_inbox_sync_notification(
@@ -19,10 +32,9 @@ impl SQS {
message: InboxSyncPubsubMessage,
) -> anyhow::Result<()> {
if let Some(gmail_inbox_sync_queue) = &self.gmail_inbox_sync_queue {
- return enqueue_inbox_sync_notification(&self.inner, gmail_inbox_sync_queue, message)
- .await;
+ return enqueue_notification(&self.inner, gmail_inbox_sync_queue, &message).await;
}
- anyhow::bail!("gmail_inbox_sync__queue is not configured")
+ anyhow::bail!("gmail_inbox_sync_queue is not configured")
}
/// Sends a notification message to the Gmail retry inbox sync queue
@@ -32,24 +44,97 @@ impl SQS {
message: InboxSyncPubsubMessage,
) -> anyhow::Result<()> {
if let Some(gmail_inbox_sync_retry_queue) = &self.gmail_inbox_sync_retry_queue {
- return enqueue_inbox_sync_notification(
- &self.inner,
- gmail_inbox_sync_retry_queue,
- message,
- )
- .await;
+ return enqueue_notification(&self.inner, gmail_inbox_sync_retry_queue, &message).await;
}
anyhow::bail!("gmail_inbox_sync_retry_queue is not configured")
}
+
+ /// Sends a message to the Gmail operations queue
+ #[tracing::instrument(skip(self), err)]
+ pub async fn enqueue_gmail_ops_notification(
+ &self,
+ message: GmailOpsPubsubMessage,
+ ) -> anyhow::Result<()> {
+ if let Some(gmail_ops_queue) = &self.gmail_ops_queue {
+ return enqueue_notification(&self.inner, gmail_ops_queue, &message).await;
+ }
+ anyhow::bail!("gmail_ops_queue is not configured")
+ }
+
+ /// Sends a batch of messages to the Gmail operations queue.
+ /// Messages are batched into groups of up to 10 (SQS limit).
+ #[tracing::instrument(skip(self, messages), fields(message_count = messages.len()), err)]
+ pub async fn enqueue_gmail_ops_notifications_batch(
+ &self,
+ messages: Vec<GmailOpsPubsubMessage>,
+ ) -> anyhow::Result<()> {
+ let Some(gmail_ops_queue) = &self.gmail_ops_queue else {
+ anyhow::bail!("gmail_ops_queue is not configured")
+ };
+
+ if messages.is_empty() {
+ return Ok(());
+ }
+
+ let entries: Vec<SendMessageBatchRequestEntry> = messages
+ .iter()
+ .enumerate()
+ .map(|(i, msg)| {
+ let body = serde_json::to_string(msg)?;
+ SendMessageBatchRequestEntry::builder()
+ .id(i.to_string())
+ .message_body(body)
+ .build()
+ .context("Failed to build batch entry")
+ })
+ .collect::<anyhow::Result<Vec<_>>>()?;
+
+ for chunk in entries.chunks(MAX_BATCH_SIZE) {
+ let result = self
+ .inner
+ .send_message_batch()
+ .queue_url(gmail_ops_queue)
+ .set_entries(Some(chunk.to_vec()))
+ .send()
+ .await
+ .context("Failed to send gmail ops batch")?;
+
+ let failed = result.failed();
+ if !failed.is_empty() {
+ tracing::error!(
+ failed_count = failed.len(),
+ "Partial failure in gmail ops batch send"
+ );
+ anyhow::bail!(
+ "Partial batch failure: {} messages failed to send",
+ failed.len()
+ );
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Sends a message to the Gmail operations retry queue
+ #[tracing::instrument(skip(self), err)]
+ pub async fn enqueue_gmail_ops_retry_notification(
+ &self,
+ message: GmailOpsPubsubMessage,
+ ) -> anyhow::Result<()> {
+ if let Some(gmail_ops_retry_queue) = &self.gmail_ops_retry_queue {
+ return enqueue_notification(&self.inner, gmail_ops_retry_queue, &message).await;
+ }
+ anyhow::bail!("gmail_ops_retry_queue is not configured")
+ }
}
#[tracing::instrument(skip(sqs_client))]
-pub async fn enqueue_inbox_sync_notification(
+async fn enqueue_notification<T: serde::Serialize + std::fmt::Debug>(
sqs_client: &aws_sdk_sqs::Client,
queue_url: &str,
- message: InboxSyncPubsubMessage,
+ message: &T,
) -> anyhow::Result<()> {
- let message_str = serde_json::to_string(&message)?;
+ let message_str = serde_json::to_string(message)?;
sqs_client
.send_message()
diff --git a/rust/cloud-storage/sqs_client/src/lib.rs b/rust/cloud-storage/sqs_client/src/lib.rs
index ce0639b332..304ba1805a 100644
--- a/rust/cloud-storage/sqs_client/src/lib.rs
+++ b/rust/cloud-storage/sqs_client/src/lib.rs
@@ -73,6 +73,10 @@ pub struct SQS {
gmail_inbox_sync_queue: Option<String>,
#[cfg(feature = "gmail")]
gmail_inbox_sync_retry_queue: Option<String>,
+ #[cfg(feature = "gmail")]
+ gmail_ops_queue: Option<String>,
+ #[cfg(feature = "gmail")]
+ gmail_ops_retry_queue: Option<String>,
#[cfg(feature = "email")]
link_manager_queue: Option<String>,
#[cfg(feature = "email")]
@@ -109,6 +113,10 @@ impl SQS {
gmail_inbox_sync_queue: None,
#[cfg(feature = "gmail")]
gmail_inbox_sync_retry_queue: None,
+ #[cfg(feature = "gmail")]
+ gmail_ops_queue: None,
+ #[cfg(feature = "gmail")]
+ gmail_ops_retry_queue: None,
#[cfg(feature = "email")]
link_manager_queue: None,
#[cfg(feature = "email")]