Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(search_processing_service): replace email_service_client with direct email_db_client calls (#1578)
Will Hutchinson20e047121cbd
diff --git a/infra/stacks/search-event-queue/index.ts b/infra/stacks/search-event-queue/index.tsindex 025d89041c..0bc3dd4b19 100644--- a/infra/stacks/search-event-queue/index.ts+++ b/infra/stacks/search-event-queue/index.ts@@ -38,6 +38,8 @@ const queue = new aws.sqs.Queue('queue',{name: `${BASE_NAME}-${stack}`,+ // Give each message up to 2 minutes to process before it's re-queued+ visibilityTimeoutSeconds: 120,redrivePolicy: dlq.arn.apply((arn) =>JSON.stringify({deadLetterTargetArn: arn,diff --git a/infra/stacks/search-processing-service/index.ts b/infra/stacks/search-processing-service/index.tsindex 7ab8831604..4891b81f41 100644--- a/infra/stacks/search-processing-service/index.ts+++ b/infra/stacks/search-processing-service/index.ts@@ -133,12 +133,6 @@ const searchProcessingService = new SearchProcessingService(name: 'SYNC_SERVICE_AUTH_KEY',value: SYNC_SERVICE_AUTH_KEY,},- {- name: 'EMAIL_SERVICE_URL',- value: `https://email-service${- stack === 'prod' ? '' : `-${stack}`- }.macro.com`,- },{name: 'WORKER_COUNT',value: '3', // 3 workers per instancediff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex dc30ba36fb..a0ee90312e 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7884,7 +7884,6 @@ dependencies = ["chrono","comms_db_client","email_db_client",- "email_service_client","futures","http-body-util","lexical_client",diff --git a/rust/cloud-storage/email_service/src/api/internal/get_search_message_by_id.rs b/rust/cloud-storage/email_service/src/api/internal/get_search_message_by_id.rsdeleted file mode 100644index 9c96b397ca..0000000000--- a/rust/cloud-storage/email_service/src/api/internal/get_search_message_by_id.rs+++ /dev/null@@ -1,47 +0,0 @@-use crate::api::ApiContext;-use axum::{- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};-use model::response::ErrorResponse;-use sqlx::types::Uuid;--#[derive(serde::Serialize, serde::Deserialize, Debug)]-pub struct PathParams {- pub id: Uuid,-}--/// Internal endpoint to get an email message by ID. Uses a-// different response object than get_message_by_thread_id-#[tracing::instrument(skip(ctx))]-pub async fn handler(- State(ctx): State<ApiContext>,- Path(PathParams { id }): Path<PathParams>,-) -> Result<Response, Response> {- let message =- email_db_client::messages::get_parsed_search::get_parsed_search_message_by_id(&ctx.db, &id)- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to get message ids for thread");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "internal server error",- }),- )- .into_response()- })?;-- if let Some(message) = message {- Ok(Json(message).into_response())- } else {- Err((- StatusCode::NOT_FOUND,- Json(ErrorResponse {- message: "message not found",- }),- )- .into_response())- }-}diff --git a/rust/cloud-storage/email_service/src/api/internal/get_search_messages_by_thread_id.rs b/rust/cloud-storage/email_service/src/api/internal/get_search_messages_by_thread_id.rsdeleted file mode 100644index 8b271384ff..0000000000--- a/rust/cloud-storage/email_service/src/api/internal/get_search_messages_by_thread_id.rs+++ /dev/null@@ -1,80 +0,0 @@-use crate::api::ApiContext;-use axum::{- extract::{self, State},- http::StatusCode,- response::{IntoResponse, Json, Response},-};-use model::response::ErrorResponse;-use sqlx::types::Uuid;--/// Parameters for listing messages.-#[derive(serde::Serialize, serde::Deserialize, Debug)]-pub struct ListThreadsParams {- pub message_offset: Option<i64>,- pub message_limit: Option<i64>,-}--/// The default number of messages to return in each thread-const DEFAULT_MESSAGE_LIMIT: i64 = 5;-/// The max number of messages that can be returned in a response-const MESSAGE_MAX: i64 = 100;--/// Represents pagination parameters with defaults applied-#[derive(Debug, Clone, Copy)]-struct ListThreadsPaginationParams {- message_offset: i64,- message_limit: i64,-}--impl From<ListThreadsParams> for ListThreadsPaginationParams {- fn from(params: ListThreadsParams) -> Self {- ListThreadsPaginationParams {- message_offset: params- .message_offset- .filter(|&offset| offset >= 0)- .unwrap_or(0),-- message_limit: params- .message_limit- .filter(|&limit| 0 < limit && limit <= MESSAGE_MAX)- .unwrap_or(DEFAULT_MESSAGE_LIMIT),- }- }-}--#[derive(serde::Serialize, serde::Deserialize, Debug)]-pub struct PathParams {- pub id: Uuid,-}--/// Internal endpoint to get a paginated email messages by thread ID for search-service. Uses a-/// different response object than get_messages_by_thread_id-#[tracing::instrument(skip(ctx))]-pub async fn handler(- State(ctx): State<ApiContext>,- extract::Path(PathParams { id }): extract::Path<PathParams>,- extract::Query(query_params): extract::Query<ListThreadsParams>,-) -> Result<Response, Response> {- let p: ListThreadsPaginationParams = query_params.into();-- let messages =- email_db_client::messages::get_parsed_search::get_paginated_parsed_search_messages_by_thread_id(- &ctx.db,- id,- p.message_offset,- p.message_limit,- )- .await- .map_err(|e| {- tracing::error!(error=?e, "unable to list messages");- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to list messages",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK, Json(messages)).into_response())-}diff --git a/rust/cloud-storage/email_service/src/api/internal/mod.rs b/rust/cloud-storage/email_service/src/api/internal/mod.rsindex 3f1eb37eab..d4c7fb5101 100644--- a/rust/cloud-storage/email_service/src/api/internal/mod.rs+++ b/rust/cloud-storage/email_service/src/api/internal/mod.rs@@ -7,8 +7,6 @@ mod delete_user;mod get_message_by_id;mod get_message_senders;mod get_messages_by_thread_id;-mod get_search_message_by_id;-mod get_search_messages_by_thread_id;mod get_thread_histories;mod get_thread_owner;mod gmail;@@ -16,10 +14,6 @@ mod gmail;pub fn router() -> Router<ApiContext> {Router::new().route("/messages/:id", get(get_message_by_id::handler))- .route(- "/messages/:id/search",- get(get_search_message_by_id::handler),- ).route("/messages/batch",post(get_message_by_id::get_message_by_id_batch_handler),@@ -30,10 +24,6 @@ pub fn router() -> Router<ApiContext> {"/threads/:id/messages",get(get_messages_by_thread_id::handler),)- .route(- "/threads/:id/messages/search",- get(get_search_messages_by_thread_id::handler),- ).route("/backfill/provider/gmail", post(gmail::create::handler)).route("/backfill/provider/gmail", delete(gmail::cancel::handler)).route("/backfill/provider/gmail/:id", get(gmail::get::handler))diff --git a/rust/cloud-storage/email_service_client/src/get_message_by_id.rs b/rust/cloud-storage/email_service_client/src/get_message_by_id.rsindex b01701d811..18ad751c3c 100644--- a/rust/cloud-storage/email_service_client/src/get_message_by_id.rs+++ b/rust/cloud-storage/email_service_client/src/get_message_by_id.rs@@ -87,31 +87,6 @@ impl EmailServiceClient {}}- pub async fn get_search_message_by_id_internal(- &self,- id: &str,- ) -> anyhow::Result<message::ParsedSearchMessage> {- let res = self- .client- .get(format!("{}/internal/messages/{}/search", self.url, id))- .send()- .await?;-- match res.status() {- reqwest::StatusCode::OK => {- let result = res.json::<message::ParsedSearchMessage>().await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(format!(- "unexpected response from email service status code {}: {}",- status_code, body- ))- }- }- }-pub async fn get_message_by_id_batch_internal(&self,ids: &[String],diff --git a/rust/cloud-storage/email_service_client/src/get_messages_by_thread_id.rs b/rust/cloud-storage/email_service_client/src/get_messages_by_thread_id.rsindex 7215ec613d..c8d932fb5b 100644--- a/rust/cloud-storage/email_service_client/src/get_messages_by_thread_id.rs+++ b/rust/cloud-storage/email_service_client/src/get_messages_by_thread_id.rs@@ -69,34 +69,4 @@ impl EmailServiceClient {}}}-- pub async fn get_search_messages_by_thread_id_internal(- &self,- id: &str,- message_offset: i64,- message_limit: i64,- ) -> anyhow::Result<Vec<message::ParsedSearchMessage>> {- let res = self- .client- .get(format!(- "{}/internal/threads/{}/messages/search?message_offset={}&message_limit={}",- self.url, id, message_offset, message_limit- ))- .send()- .await?;-- match res.status() {- reqwest::StatusCode::OK => {- let result = res.json::<Vec<message::ParsedSearchMessage>>().await?;- Ok(result)- }- status_code => {- let body: String = res.text().await?;- anyhow::bail!(format!(- "unexpected response from email service status code {}: {}",- status_code, body- ))- }- }- }}diff --git a/rust/cloud-storage/search_processing_service/Cargo.toml b/rust/cloud-storage/search_processing_service/Cargo.tomlindex 4c2cc695c6..aed79c6e8a 100644--- a/rust/cloud-storage/search_processing_service/Cargo.toml+++ b/rust/cloud-storage/search_processing_service/Cargo.toml@@ -28,8 +28,7 @@ aws-sdk-sqs = { workspace = true }axum = { workspace = true }chrono = { workspace = true }comms_db_client = { path = "../comms_db_client" }-email_db_client = { path = "../email_db_client", optional = true }-email_service_client = { path = "../email_service_client" }+email_db_client = { path = "../email_db_client" }futures = { workspace = true }http-body-util = { workspace = true }lexical_client = { path = "../lexical_client" }diff --git a/rust/cloud-storage/search_processing_service/src/config.rs b/rust/cloud-storage/search_processing_service/src/config.rsindex e1106d52c0..973cd616cd 100644--- a/rust/cloud-storage/search_processing_service/src/config.rs+++ b/rust/cloud-storage/search_processing_service/src/config.rs@@ -32,9 +32,6 @@ pub struct Config {/// API key for sync servicepub sync_service_auth_key: String,- /// The email service URL- pub email_service_url: String,-/// The number of workers to spawnpub worker_count: u8,@@ -80,9 +77,6 @@ impl Config {let sync_service_auth_key = std::env::var("SYNC_SERVICE_AUTH_KEY").context("SYNC_SERVICE_AUTH_KEY must be provided")?;- let email_service_url =- std::env::var("EMAIL_SERVICE_URL").context("EMAIL_SERVICE_URL must be provided")?;-let worker_count: u8 = std::env::var("WORKER_COUNT").unwrap_or("10".to_string()).parse::<u8>()@@ -103,7 +97,6 @@ impl Config {opensearch_password,document_storage_bucket,sync_service_auth_key,- email_service_url,worker_count,lexical_service_url,})diff --git a/rust/cloud-storage/search_processing_service/src/main.rs b/rust/cloud-storage/search_processing_service/src/main.rsindex 6e7d31a95f..3d660e35b0 100644--- a/rust/cloud-storage/search_processing_service/src/main.rs+++ b/rust/cloud-storage/search_processing_service/src/main.rs@@ -62,7 +62,7 @@ async fn main() -> anyhow::Result<()> {};let (min_connections, max_connections): (u32, u32) = match config.environment {- Environment::Production => (3, 25),+ Environment::Production => (5, 50),Environment::Develop => (1, 25),Environment::Local => (1, 10),};@@ -119,11 +119,6 @@ async fn main() -> anyhow::Result<()> {config.lexical_service_url.clone(),);- let email_service_client = email_service_client::EmailServiceClient::new(- internal_auth_key.as_ref().to_string(),- config.email_service_url.clone(),- );-let worker = sqs_worker::SQSWorker::new(aws_sdk_sqs::Client::new(&aws_config),config.search_event_queue.clone(),@@ -137,7 +132,6 @@ async fn main() -> anyhow::Result<()> {s3_client: Arc::new(s3_client),opensearch_client: Arc::new(opensearch_client.clone()),lexical_client: Arc::new(lexical_client),- email_client: email_service_client.into(),};run_search_processing_workers(ctx, config.worker_count);}diff --git a/rust/cloud-storage/search_processing_service/src/process/context.rs b/rust/cloud-storage/search_processing_service/src/process/context.rsindex 9f7e54bd86..f69769442e 100644--- a/rust/cloud-storage/search_processing_service/src/process/context.rs+++ b/rust/cloud-storage/search_processing_service/src/process/context.rs@@ -8,5 +8,4 @@ pub struct SearchProcessingContext {pub s3_client: Arc<s3_client::S3>,pub opensearch_client: Arc<opensearch_client::OpensearchClient>,pub lexical_client: Arc<lexical_client::LexicalClient>,- pub email_client: Arc<email_service_client::EmailServiceClient>,}diff --git a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rsindex b25757d3b9..cb132fb526 100644--- a/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs+++ b/rust/cloud-storage/search_processing_service/src/process/email/upsert.rs@@ -1,22 +1,37 @@use anyhow::Context;use chrono::Utc;-use email_service_client::EmailServiceClient;use models_email::service::label::system_labels;use opensearch_client::{OpensearchClient, date_format::EpochSeconds, upsert::email::UpsertEmailArgs,};+use sqlx::PgPool;use sqs_client::search::email::{EmailMessage, EmailThreadMessage};+use uuid::Uuid;pub async fn process_upsert_message(opensearch_client: &OpensearchClient,- email_client: &EmailServiceClient,+ db: &PgPool,upsert_email_message: &EmailMessage,) -> anyhow::Result<()> {- let message_info = email_client- .get_search_message_by_id_internal(&upsert_email_message.message_id)+ let message_id: Uuid = upsert_email_message+ .message_id+ .parse()+ .context("failed to parse message_id as UUID")?;++ let message_info =+ email_db_client::messages::get_parsed_search::get_parsed_search_message_by_id(+ db,+ &message_id,+ ).await.context("failed to get message info")?;+ let message_info = if let Some(message_info) = message_info {+ message_info+ } else {+ return Ok(());+ };+// don't insert spam or trash messagesif message_info.labels.iter().any(|label| {label.provider_id == system_labels::SPAM || label.provider_id == system_labels::TRASH@@ -87,19 +102,25 @@ pub async fn process_upsert_message(pub async fn process_upsert_thread_message(opensearch_client: &OpensearchClient,- email_client: &EmailServiceClient,+ db: &PgPool,upsert_email_thread_message: &EmailThreadMessage,) -> anyhow::Result<()> {let mut message_offset = 0;// Max is 100let message_limit = 10;+ let thread_id: Uuid = upsert_email_thread_message+ .thread_id+ .parse()+ .context("failed to parse thread_id as UUID")?;+let now = EpochSeconds::new(Utc::now().timestamp())?;loop {- let messages = email_client- .get_search_messages_by_thread_id_internal(- &upsert_email_thread_message.thread_id,+ let messages =+ email_db_client::messages::get_parsed_search::get_paginated_parsed_search_messages_by_thread_id(+ db,+ thread_id,message_offset,message_limit,)diff --git a/rust/cloud-storage/search_processing_service/src/process/mod.rs b/rust/cloud-storage/search_processing_service/src/process/mod.rsindex 17cec2b1d6..21d34132e4 100644--- a/rust/cloud-storage/search_processing_service/src/process/mod.rs+++ b/rust/cloud-storage/search_processing_service/src/process/mod.rs@@ -47,23 +47,15 @@ pub async fn process_message(.await?;}SearchQueueMessage::ExtractEmailThreadMessage(message) => {- email::upsert::process_upsert_thread_message(- &ctx.opensearch_client,- &ctx.email_client,- &message,- )- .await?;+ email::upsert::process_upsert_thread_message(&ctx.opensearch_client, &ctx.db, &message)+ .await?;}SearchQueueMessage::RemoveEmailMessage(message) => {email::remove::process_remove_message(&ctx.opensearch_client, &message).await?;}SearchQueueMessage::ExtractEmailMessage(message) => {- email::upsert::process_upsert_message(- &ctx.opensearch_client,- &ctx.email_client,- &message,- )- .await?;+ email::upsert::process_upsert_message(&ctx.opensearch_client, &ctx.db, &message)+ .await?;}SearchQueueMessage::RemoveDocument(message) => {document::process_remove_message(&ctx.opensearch_client, &message).await?;