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.

fix(email-service): Notify search on label updates (#635)

Evan Hutnikf8c5ffb99070
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-8a215a76402a93829ee50f11c6274918254527167114c403836c8f2824adc142.json b/rust/cloud-storage/email_db_client/.sqlx/query-8a215a76402a93829ee50f11c6274918254527167114c403836c8f2824adc142.json
deleted file mode 100644
index 101c66b9b3..0000000000
--- a/rust/cloud-storage/email_db_client/.sqlx/query-8a215a76402a93829ee50f11c6274918254527167114c403836c8f2824adc142.json
+++ /dev/null
@@ -1,29 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT id, thread_id\n FROM email_messages\n WHERE link_id = $1 AND provider_id = ANY($2)\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "id",
- "type_info": "Uuid"
- },
- {
- "ordinal": 1,
- "name": "thread_id",
- "type_info": "Uuid"
- }
- ],
- "parameters": {
- "Left": [
- "Uuid",
- "TextArray"
- ]
- },
- "nullable": [
- false,
- false
- ]
- },
- "hash": "8a215a76402a93829ee50f11c6274918254527167114c403836c8f2824adc142"
-}
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-a82ffe9987e55be9eec8188c780cce01f7c42fad5037cb2dd4c98fb29ad4c217.json b/rust/cloud-storage/email_db_client/.sqlx/query-a82ffe9987e55be9eec8188c780cce01f7c42fad5037cb2dd4c98fb29ad4c217.json
deleted file mode 100644
index 7e5f7c8648..0000000000
--- a/rust/cloud-storage/email_db_client/.sqlx/query-a82ffe9987e55be9eec8188c780cce01f7c42fad5037cb2dd4c98fb29ad4c217.json
+++ /dev/null
@@ -1,23 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n SELECT provider_id as \"provider_id!\"\n FROM email_messages\n WHERE provider_id = ANY($1) AND link_id = $2\n ",
- "describe": {
- "columns": [
- {
- "ordinal": 0,
- "name": "provider_id!",
- "type_info": "Text"
- }
- ],
- "parameters": {
- "Left": [
- "TextArray",
- "Uuid"
- ]
- },
- "nullable": [
- true
- ]
- },
- "hash": "a82ffe9987e55be9eec8188c780cce01f7c42fad5037cb2dd4c98fb29ad4c217"
-}
diff --git a/rust/cloud-storage/email_db_client/src/messages/get.rs b/rust/cloud-storage/email_db_client/src/messages/get.rs
index 0925cb5a86..a4fd128bd1 100644
--- a/rust/cloud-storage/email_db_client/src/messages/get.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/get.rs
@@ -58,66 +58,59 @@ pub async fn get_message_sender_and_pretty_sender(
Ok(result)
}
-/// Returns a vector of (message_id, thread_id) tuples for all found messages
-pub async fn get_message_thread_ids_by_provider_ids(
+/// Returns the (message_id, thread_id) for a message with the given (link_id, provider_id).
+/// Errors if no row is found.
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_message_and_thread_id_by_provider_id(
pool: &PgPool,
link_id: Uuid,
- provider_ids: &[String],
-) -> anyhow::Result<Vec<(Uuid, Uuid)>> {
- let db_ids = sqlx::query!(
+ provider_id: &str,
+) -> anyhow::Result<(Uuid, Uuid)> {
+ let row = sqlx::query_as(
r#"
SELECT id, thread_id
FROM email_messages
- WHERE link_id = $1 AND provider_id = ANY($2)
+ WHERE link_id = $1 AND provider_id = $2
+ LIMIT 1
"#,
- link_id,
- provider_ids
)
- .map(|record| (record.id, record.thread_id))
- .fetch_all(pool)
- .await
- .context("Failed to query messages for db_id")?;
-
- Ok(db_ids)
+ .bind(link_id)
+ .bind(provider_id)
+ .fetch_optional(pool)
+ .await?;
+
+ match row {
+ Some((message_id, thread_id)) => Ok((message_id, thread_id)),
+ None => anyhow::bail!(
+ "Message not found for link_id={} provider_id={}",
+ link_id,
+ provider_id
+ ),
+ }
}
-/// Takes a HashSet of provider IDs and a link_id, and returns only those provider IDs
-/// that don't have corresponding messages in the database.
-pub async fn find_missing_provider_ids(
+/// Returns `true` if a message already exists for this (provider_id, link_id), else `false`.
+#[tracing::instrument(skip(pool), err)]
+pub async fn message_exists_by_provider_id(
pool: &PgPool,
- provider_ids: std::collections::HashSet<String>,
+ provider_id: &str,
link_id: Uuid,
-) -> anyhow::Result<Vec<String>> {
- if provider_ids.is_empty() {
- return Ok(Vec::new());
- }
-
- let provider_ids_vec: Vec<String> = provider_ids.into_iter().collect();
-
- let existing_provider_ids = sqlx::query!(
+) -> anyhow::Result<bool> {
+ let exists: bool = sqlx::query_scalar(
r#"
- SELECT provider_id as "provider_id!"
- FROM email_messages
- WHERE provider_id = ANY($1) AND link_id = $2
+ SELECT EXISTS(
+ SELECT 1
+ FROM email_messages
+ WHERE provider_id = $1 AND link_id = $2
+ )
"#,
- &provider_ids_vec,
- link_id
)
- .fetch_all(pool)
- .await
- .with_context(|| format!("Failed to check existing messages for link_id {}", link_id))?;
-
- let existing_set: std::collections::HashSet<String> = existing_provider_ids
- .into_iter()
- .map(|record| record.provider_id)
- .collect();
-
- let missing_provider_ids = provider_ids_vec
- .into_iter()
- .filter(|id| !existing_set.contains(id))
- .collect();
+ .bind(provider_id)
+ .bind(link_id)
+ .fetch_one(pool)
+ .await?;
- Ok(missing_provider_ids)
+ Ok(exists)
}
/// Fetches the thread's messages without attachments and body attributes.
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/mod.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/mod.rs
index c50c3c3df8..694cca1d37 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/mod.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/mod.rs
@@ -1,4 +1,5 @@
pub(in crate::pubsub) mod delete_message;
pub(in crate::pubsub) mod gmail_message;
+pub(in crate::pubsub) mod shared;
pub(in crate::pubsub) mod update_labels;
pub(in crate::pubsub) mod upsert_message;
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/shared.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/shared.rs
new file mode 100644
index 0000000000..bba6ac31a3
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/shared.rs
@@ -0,0 +1,28 @@
+use crate::pubsub::context::PubSubContext;
+use models_email::service::link;
+use models_email::service::pubsub::ProcessingError;
+use sqs_client::search::SearchQueueMessage;
+use sqs_client::search::email::EmailMessage;
+use std::result;
+use uuid::Uuid;
+
+/// Notify search that a message was upserted
+#[tracing::instrument(skip(ctx, link, message_db_id))]
+pub async fn notify_search(
+ ctx: &PubSubContext,
+ link: &link::Link,
+ message_db_id: Uuid,
+) -> result::Result<(), ProcessingError> {
+ ctx.sqs_client
+ .send_message_to_search_event_queue(SearchQueueMessage::ExtractEmailMessage(EmailMessage {
+ message_id: message_db_id.to_string(),
+ macro_user_id: link.macro_id.to_string(),
+ }))
+ .await
+ .inspect_err(
+ |e| tracing::error!(error = ?e, "failed to send message to search extractor queue"),
+ )
+ .ok();
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
index d794a00619..dd65dd4fc3 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/update_labels.rs
@@ -1,5 +1,6 @@
use crate::pubsub::context::PubSubContext;
use crate::pubsub::util::{cg_refresh_email, complete_transaction_with_processing_error};
+use crate::pubsub::webhook::operations::shared::notify_search;
use crate::pubsub::webhook::process;
use crate::pubsub::webhook::process::check_gmail_rate_limit_webhook;
use email_db_client::labels::delete::delete_db_message_labels;
@@ -123,6 +124,7 @@ pub async fn update_labels(
}
if has_label_changes {
+ notify_search(ctx, link, db_message.db_id).await?;
// tell FE to refresh user's inbox
cg_refresh_email(
&ctx.connection_gateway_client,
diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
index 978a6b6288..e2afa64ae4 100644
--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs
@@ -1,13 +1,13 @@
use crate::pubsub::context::PubSubContext;
use crate::pubsub::util::cg_refresh_email;
+use crate::pubsub::webhook::operations::shared::notify_search;
use crate::pubsub::webhook::process;
use crate::pubsub::webhook::process::check_gmail_rate_limit_webhook;
use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};
use crate::util::upload_attachment::{UploadAttachmentContext, upload_attachment};
+use anyhow::Context;
use email_db_client::threads;
-use email_db_client::threads::get::get_outbound_threads_by_thread_ids;
use email_utils::dedupe_emails;
-use futures::future::join_all;
use insight_service_client::InsightContextProvider;
use macro_user_id::user_id::MacroUserIdStr;
use model::contacts::ConnectionsMessage;
@@ -22,7 +22,6 @@ use models_email::db::address::EmailRecipientType;
use models_email::email::service;
use models_email::email::service::link;
use models_email::email::service::message::SimpleMessage;
-use models_email::email::service::thread::UserThreadIds;
use models_email::gmail::operations::GmailApiOperation;
use models_email::gmail::webhook::{UpsertMessagePayload, WebhookOperation};
use models_email::service::attachment::{AttachmentUploadArgs, AttachmentUploadDestination};
@@ -30,9 +29,8 @@ use models_email::service::message::Message;
use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
use models_opensearch::SearchEntityType;
use sqs_client::search::SearchQueueMessage;
-use sqs_client::search::email::EmailMessage;
use sqs_client::search::name::EntityName;
-use std::collections::{HashMap, HashSet};
+use std::collections::HashSet;
use std::result;
use uuid::Uuid;
@@ -108,16 +106,17 @@ pub async fn upsert_message(
})?;
// before upserting, figure out if the message is new so we can send a notification for it if so
- let new_message_provider_ids = email_db_client::messages::get::find_missing_provider_ids(
+ let message_already_exists = email_db_client::messages::get::message_exists_by_provider_id(
&ctx.db,
- HashSet::from([payload.provider_message_id.clone()]),
+ &payload.provider_message_id,
link.id,
)
.await
.map_err(|e| {
ProcessingError::NonRetryable(DetailedError {
reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to find missing provider_ids".to_string()),
+ source: e
+ .context("Failed to check whether provider_message_id already exists".to_string()),
})
})?;
@@ -149,6 +148,20 @@ pub async fn upsert_message(
})?;
}
+ let (message_db_id, thread_db_id) =
+ email_db_client::messages::get::get_message_and_thread_id_by_provider_id(
+ &ctx.db,
+ link.id,
+ &payload.provider_message_id,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to get new message db id".to_string()),
+ })
+ })?;
+
handle_attachment_upload(
ctx,
&gmail_access_token,
@@ -167,6 +180,8 @@ pub async fn upsert_message(
)
.await?;
+ notify_search(ctx, link, message_db_id).await?;
+
// trigger FE inbox refresh
cg_refresh_email(
&ctx.connection_gateway_client,
@@ -176,7 +191,16 @@ pub async fn upsert_message(
.await;
// notify downstream services of new messages
- notify_for_new_messages(ctx, link, new_message_provider_ids).await?;
+ if !message_already_exists {
+ notify_for_new_message(
+ ctx,
+ link,
+ &payload.provider_message_id,
+ message_db_id,
+ thread_db_id,
+ )
+ .await?;
+ }
Ok(())
}
@@ -347,98 +371,51 @@ async fn handle_contacts_sync(
}
/// Sends new message context to the insight service
-async fn generate_email_insights_for_new_messages(
+async fn generate_email_insights_for_new_message(
ctx: &PubSubContext,
link: &service::link::Link,
- message_thread_ids: Vec<(Uuid, Uuid)>,
+ message_id: Uuid,
+ thread_id: Uuid,
) -> anyhow::Result<()> {
- // maps macro user id to list of (thread_id, message_id)
- let mut user_messages: HashMap<String, Vec<NewMessagePayload>> = HashMap::new();
- for (message_id, thread_id) in message_thread_ids {
- // Use the correct macro_user_id for each message
- let macro_user_id = link.macro_id.clone();
- user_messages
- .entry(macro_user_id.to_string())
- .or_default()
- .push(NewMessagePayload {
+ // Fetch the thread and ensure it's an outbound thread (has latest_outbound)
+ let thread =
+ email_db_client::threads::get::get_thread_by_id_and_link_id(&ctx.db, thread_id, link.id)
+ .await
+ .context("Failed to fetch thread for new message")?;
+
+ let Some(thread) = thread else {
+ tracing::warn!(%thread_id, link_id = %link.id, "Thread not found; skipping insight generation");
+ return Ok(());
+ };
+
+ if thread.latest_outbound_message_ts.is_none() {
+ tracing::debug!(
+ %thread_id,
+ link_id = %link.id,
+ "Thread has no latest_outbound_message_ts; skipping insight generation"
+ );
+ return Ok(());
+ }
+
+ let macro_user_id = link.macro_id.to_string();
+
+ let context = GenerateEmailInsightContext {
+ macro_user_id: macro_user_id.clone(),
+ info: EmailInfo::NewMessages(NewMessagesPayload {
+ messages: vec![NewMessagePayload {
thread_id,
message_id,
user_email: link.email_address.0.as_ref().to_string(),
- });
- }
+ }],
+ batch_id: Uuid::new_v4().to_string(),
+ }),
+ };
- let users_thread_ids: Vec<UserThreadIds> = user_messages
- .iter()
- .map(|(macro_user_id, messages)| UserThreadIds {
- macro_user_id: macro_user_id.clone(),
- thread_ids: messages.iter().map(|m| m.thread_id).collect(),
- })
- .collect();
-
- match get_outbound_threads_by_thread_ids(&ctx.db, users_thread_ids).await {
- Ok(users_outbound_threads) => {
- // for each user, filter out messages that are not part of an outbound thread
- let email_insight_new_message_payloads = user_messages
- .into_iter()
- .filter_map(|(macro_user_id, messages)| {
- let user_outbound_thread_ids: HashSet<Uuid> = users_outbound_threads
- .iter()
- .filter_map(|t| {
- if t.macro_user_id == macro_user_id {
- Some(t.thread_ids.clone())
- } else {
- None
- }
- })
- .flatten()
- .collect();
- let outbound_messages = messages
- .iter()
- .filter_map(|m| {
- if user_outbound_thread_ids.contains(&m.thread_id) {
- Some(m.clone())
- } else {
- None
- }
- })
- .collect::<Vec<_>>();
- if outbound_messages.is_empty() {
- return None;
- }
- Some(GenerateEmailInsightContext {
- macro_user_id,
- info: EmailInfo::NewMessages(NewMessagesPayload {
- messages: outbound_messages,
- batch_id: Uuid::new_v4().to_string(),
- }),
- })
- })
- .collect::<Vec<_>>();
-
- let contexts: Vec<_> = email_insight_new_message_payloads.into_iter().collect();
-
- let provider = InsightContextProvider::create(
- ctx.sqs_client.clone(),
- EMAIL_INSIGHT_PROVIDER_SOURCE_NAME,
- );
-
- // send per-user messages to insight service
- let results = join_all(
- contexts
- .iter()
- .map(|context| provider.provide_email_context(context.clone())),
- )
- .await;
-
- for (context, result) in contexts.into_iter().zip(results) {
- if let Err(err) = result {
- tracing::error!(?context, error = %err, "Failed to provide email context to insight service");
- }
- }
- }
- Err(e) => {
- tracing::error!(error = ?e, "failed to get outbound threads");
- }
+ let provider =
+ InsightContextProvider::create(ctx.sqs_client.clone(), EMAIL_INSIGHT_PROVIDER_SOURCE_NAME);
+
+ if let Err(err) = provider.provide_email_context(context.clone()).await {
+ tracing::error!(?context, error = %err, "Failed to provide email context to insight service");
}
Ok(())
@@ -492,7 +469,7 @@ async fn fetch_and_insert_thread(
})
})?;
- // notify search about new entity
+ // when a thread is created, add an entry into the names index for it
ctx.sqs_client
.send_message_to_search_event_queue(SearchQueueMessage::UpdateEntityName(EntityName {
entity_id: thread_id,
@@ -538,84 +515,44 @@ async fn process_and_insert_message(
Ok(())
}
-/// Notify downstream services about new messages in a user's inbox
-#[tracing::instrument(skip(ctx, link, new_message_provider_ids))]
-async fn notify_for_new_messages(
+/// Notify downstream services about new message in a user's inbox
+#[tracing::instrument(skip(ctx, link, new_message_provider_id))]
+async fn notify_for_new_message(
ctx: &PubSubContext,
link: &link::Link,
- new_message_provider_ids: Vec<String>,
+ new_message_provider_id: &str,
+ message_db_id: Uuid,
+ thread_id: Uuid,
) -> result::Result<(), ProcessingError> {
- if new_message_provider_ids.is_empty() {
- return Ok(());
- }
-
- let new_message_db_ids =
- email_db_client::messages::get::get_message_thread_ids_by_provider_ids(
- &ctx.db,
- link.id,
- &new_message_provider_ids,
- )
- .await
- .map_err(|e| {
- ProcessingError::NonRetryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to get new message db ids".to_string()),
- })
- })?;
-
// notify user of new messages
- send_notifications(ctx, link, new_message_provider_ids).await?;
-
- if !new_message_db_ids.is_empty() {
- // send message to search text extractor queue
- ctx.sqs_client
- .bulk_send_message_to_search_event_queue(
- new_message_db_ids
- .iter()
- .map(|(message_id, _thread_id)| {
- SearchQueueMessage::ExtractEmailMessage(EmailMessage {
- message_id: message_id.to_string(),
- macro_user_id: link.macro_id.to_string(),
- })
- })
- .collect(),
- )
- .await
- .inspect_err(
- |e| tracing::error!(error = ?e, "failed to send message to search extractor queue"),
- )
- .ok();
+ send_notifications(ctx, link, new_message_provider_id).await?;
- generate_email_insights_for_new_messages(ctx, link, new_message_db_ids)
- .await
- .ok();
- }
+ generate_email_insights_for_new_message(ctx, link, message_db_id, thread_id)
+ .await
+ .ok();
Ok(())
}
/// Send notifications for new inbound email messages
-#[tracing::instrument(skip(ctx, link, new_message_provider_ids))]
+
+#[tracing::instrument(skip(ctx, link))]
async fn send_notifications(
ctx: &PubSubContext,
link: &link::Link,
- new_message_provider_ids: Vec<String>,
+ new_message_provider_id: &str,
) -> result::Result<(), ProcessingError> {
- if !ctx.notifications_enabled || new_message_provider_ids.is_empty() {
+ if !ctx.notifications_enabled {
return Ok(());
}
- let notifiable_messages =
- filter_notifiable_messages(ctx, link, new_message_provider_ids).await?;
+ let notifiable_message = filter_notifiable_message(ctx, link, new_message_provider_id).await?;
- if notifiable_messages.is_empty() {
+ let Some(message) = notifiable_message else {
return Ok(());
- }
+ };
- let message_ids: Vec<Uuid> = notifiable_messages
- .iter()
- .map(|message| message.db_id)
- .collect();
+ let message_ids: Vec<Uuid> = vec![message.db_id];
let sender_contacts =
email_db_client::contacts::get::fetch_sender_contact_info(&ctx.db, &message_ids)
@@ -627,109 +564,95 @@ async fn send_notifications(
})
})?;
- for message in notifiable_messages {
- let sender_contact = message
- .from_contact_id
- .and_then(|from_id| sender_contacts.get(&from_id));
-
- let sender = sender_contact.map(|contact| {
- contact
- .name
- .clone()
- .unwrap_or_else(|| contact.email.clone())
- });
-
- let sender_id = sender_contact
- .and_then(|contact| MacroUserIdStr::try_from_email(&contact.email).ok())
- .map(|id| id.to_string());
-
- let notification_metadata = NewEmailMetadata {
- sender,
- to_email: link.email_address.0.as_ref().to_string(),
- thread_id: message.thread_db_id.to_string(),
- subject: message.subject.unwrap_or_default(),
- snippet: message.snippet.unwrap_or_default(),
- };
-
- let notification_queue_message = NotificationQueueMessage {
- notification_entity: NotificationEntity::new_email(message.db_id.to_string()),
- notification_event: NotificationEvent::NewEmail(notification_metadata),
- sender_id,
- recipient_ids: Some(vec![link.macro_id.to_string()]),
- is_important_v0: Some(false),
- };
-
- if let Err(e) = ctx
- .macro_notify_client
- .send_notification(notification_queue_message)
- .await
- {
- tracing::error!(error=?e, "unable to send notification");
- }
+ let sender_contact = message
+ .from_contact_id
+ .and_then(|from_id| sender_contacts.get(&from_id));
+
+ let sender = sender_contact.map(|contact| {
+ contact
+ .name
+ .clone()
+ .unwrap_or_else(|| contact.email.clone())
+ });
+
+ let sender_id = sender_contact
+ .and_then(|contact| MacroUserIdStr::try_from_email(&contact.email).ok())
+ .map(|id| id.to_string());
+
+ let notification_metadata = NewEmailMetadata {
+ sender,
+ to_email: link.email_address.0.as_ref().to_string(),
+ thread_id: message.thread_db_id.to_string(),
+ subject: message.subject.unwrap_or_default(),
+ snippet: message.snippet.unwrap_or_default(),
+ };
+
+ let notification_queue_message = NotificationQueueMessage {
+ notification_entity: NotificationEntity::new_email(message.db_id.to_string()),
+ notification_event: NotificationEvent::NewEmail(notification_metadata),
+ sender_id,
+ recipient_ids: Some(vec![link.macro_id.to_string()]),
+ is_important_v0: Some(false),
+ };
+
+ if let Err(e) = ctx
+ .macro_notify_client
+ .send_notification(notification_queue_message)
+ .await
+ {
+ tracing::error!(error=?e, "unable to send notification");
}
Ok(())
}
// filter out messages we don't want to send notifications for
-#[tracing::instrument(skip(ctx, link, new_message_provider_ids))]
-async fn filter_notifiable_messages(
+#[tracing::instrument(skip(ctx, link))]
+async fn filter_notifiable_message(
ctx: &PubSubContext,
link: &link::Link,
- new_message_provider_ids: Vec<String>,
-) -> result::Result<Vec<SimpleMessage>, ProcessingError> {
- let new_messages = email_db_client::messages::get_simple_messages::get_simple_messages(
- &ctx.db,
- new_message_provider_ids,
- link.id,
- )
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch simple messages".to_string()),
- })
- })?;
+ new_message_provider_id: &str,
+) -> result::Result<Option<SimpleMessage>, ProcessingError> {
+ let new_message =
+ email_db_client::messages::get_simple_messages::get_simple_message_by_provider_and_link(
+ &ctx.db,
+ new_message_provider_id,
+ &link.id,
+ )
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch simple message".to_string()),
+ })
+ })?;
- // 1. filter out sent and draft messages
- let inbound_messages: Vec<SimpleMessage> = new_messages
- .into_iter()
- .filter(|message| !(message.is_sent || message.is_draft))
- .collect();
+ let Some(new_message) = new_message else {
+ return Ok(None);
+ };
- if inbound_messages.is_empty() {
- return Ok(Vec::new());
+ // 1. filter out sent and draft messages
+ if new_message.is_sent || new_message.is_draft {
+ return Ok(None);
}
// 2. filter out messages that don't make it to the user's inbox (spam, etc)
- let messages_labels_map = email_db_client::labels::get::fetch_message_labels_in_bulk(
- &ctx.db,
- &inbound_messages
- .iter()
- .map(|m| m.db_id)
- .collect::<Vec<Uuid>>(),
- )
- .await
- .map_err(|e| {
- ProcessingError::Retryable(DetailedError {
- reason: FailureReason::DatabaseQueryFailed,
- source: e.context("Failed to fetch message labels".to_string()),
- })
- })?;
+ let labels = email_db_client::labels::get::fetch_message_labels(&ctx.db, new_message.db_id)
+ .await
+ .map_err(|e| {
+ ProcessingError::Retryable(DetailedError {
+ reason: FailureReason::DatabaseQueryFailed,
+ source: e.context("Failed to fetch message labels".to_string()),
+ })
+ })?;
- let inbox_messages = inbound_messages
- .into_iter()
- .filter(|message| {
- let labels = messages_labels_map
- .get(&message.db_id)
- .unwrap_or(&Vec::new())
- .to_owned();
+ let is_inbox = labels
+ .iter()
+ .any(|label| label.name == service::label::system_labels::INBOX);
- labels
- .iter()
- .any(|label| label.name == service::label::system_labels::INBOX)
- })
- .collect();
+ if !is_inbox {
+ return Ok(None);
+ }
- Ok(inbox_messages)
+ Ok(Some(new_message))
}