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.

refactor(gmail-client): simplify get_threads to get_thread for single thread fetch (#2219)

Evan Hutnike2c3fb51e8cf
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
index 0ec200e68a..576830813d 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
@@ -383,19 +383,21 @@ async fn fetch_and_insert_thread(
.await
.map_err(anyhow::Error::from)?;
- let thread_resources = ctx
+ let thread_resource = ctx
.gmail_client
- .get_threads(gmail_access_token, &vec![provider_thread_id.to_string()])
+ .get_thread(gmail_access_token, provider_thread_id)
.await
.map_err(|e| {
- ProcessingError::NonRetryable(DetailedError {
+ // retryable because a failure here is likely a transient Gmail API error,
+ // matching the get_message error handling above
+ ProcessingError::Retryable(DetailedError {
reason: FailureReason::GmailApiFailed,
- source: e.context("Failed to get threads from gmail api".to_string()),
+ source: e.context("Failed to get thread from gmail api".to_string()),
})
})?;
// Map Gmail resources to service models (IDs are generated in the parse functions)
- let mut threads = map_thread_resources_to_service(thread_resources, link_id)
+ let mut threads = map_thread_resources_to_service(vec![thread_resource], link_id)
.await
.map_err(|e| {
ProcessingError::NonRetryable(DetailedError {
diff --git a/rust/cloud-storage/gmail_client/Cargo.toml b/rust/cloud-storage/gmail_client/Cargo.toml
index 2817dc1492..4855ac592f 100644
--- a/rust/cloud-storage/gmail_client/Cargo.toml
+++ b/rust/cloud-storage/gmail_client/Cargo.toml
@@ -18,6 +18,7 @@ mockall = { workspace = true }
models_email = { path = "../models_email" }
regex = { workspace = true }
reqwest = { workspace = true, features = ["stream"] }
+serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rs
index c31631045a..ad157a3069 100644
--- a/rust/cloud-storage/gmail_client/src/lib.rs
+++ b/rust/cloud-storage/gmail_client/src/lib.rs
@@ -33,7 +33,7 @@ pub(crate) fn sanitize_error_body(body: &str) -> String {
use crate::auth::{fetch_google_public_keys, verify_google_jwt};
use crate::contacts::get_self_connection;
use crate::messages::{get_message, get_message_label_ids, get_message_thread_id};
-use crate::threads::{DEFAULT_BATCH_SIZE, get_threads_with_retry};
+use crate::threads::get_thread;
#[allow(unused_imports)]
use mockall::automock;
use models_email::email::service;
@@ -55,8 +55,6 @@ pub struct GmailClient {
inner: reqwest::Client,
/// The base url for Gmail API
base_url: String,
- /// The base url for batch requests to the Gmail API
- base_batch_url: String,
/// The url for fetching google certs
certs_url: String,
/// The url for fetching contact information via People API
@@ -72,7 +70,6 @@ impl GmailClient {
Self {
inner: reqwest::Client::new(),
base_url: String::from("https://www.googleapis.com/gmail/v1"),
- base_batch_url: String::from("https://www.googleapis.com/batch/gmail/v1"),
certs_url: String::from("https://www.googleapis.com/oauth2/v3/certs"),
contacts_url: String::from("https://people.googleapis.com/v1"),
audience: "macro-gmail-webhook".to_string(),
@@ -101,15 +98,15 @@ impl GmailClient {
threads::get_message_ids_for_thread(self, access_token, thread_id).await
}
- /// Fetches the threads and messages for the given thread_ids.
- /// Returns raw Gmail ThreadResource objects - callers should map to service layer structs.
+ /// Fetches a single thread and its messages from Gmail.
+ /// Returns a raw Gmail ThreadResource - callers should map to service layer structs.
#[tracing::instrument(skip(self, access_token), err)]
- pub async fn get_threads(
+ pub async fn get_thread(
&self,
access_token: &str,
- thread_ids: &Vec<String>,
- ) -> anyhow::Result<Vec<ThreadResource>> {
- get_threads_with_retry(self, access_token, thread_ids, DEFAULT_BATCH_SIZE).await
+ thread_id: &str,
+ ) -> anyhow::Result<ThreadResource> {
+ get_thread(self, access_token, thread_id).await
}
/// Gets the changes to a user's inbox that have occurred since start_history_id.
diff --git a/rust/cloud-storage/gmail_client/src/threads.rs b/rust/cloud-storage/gmail_client/src/threads.rs
index 6011179ce1..2a5d6d468c 100644
--- a/rust/cloud-storage/gmail_client/src/threads.rs
+++ b/rust/cloud-storage/gmail_client/src/threads.rs
@@ -1,22 +1,12 @@
use crate::{GmailClient, sanitize_error_body};
-use anyhow::{Context, anyhow};
+use anyhow::Context;
use models_email::email::service::thread::{ThreadList, ThreadSummary};
-use models_email::gmail::error::GmailError;
-use models_email::gmail::error::GmailError::{
- ApiError, BodyReadError, MultipartParse, RateLimitExceeded,
-};
use models_email::gmail::{ListThreadsResponse, MinimalThreadResource, ThreadResource};
-use reqwest::header::HeaderValue;
+use serde::de::DeserializeOwned;
use std::cmp::min;
-use std::collections::HashMap;
-use std::thread::sleep;
-use std::time::Duration;
// 500 is max allowed by gmail api
pub const LIST_THREADS_BATCH_SIZE: u32 = 500;
-pub const DEFAULT_BATCH_SIZE: usize = 25;
-const MAX_RETRY_ATTEMPTS: usize = 5;
-const INITIAL_RETRY_DELAY_MS: u64 = 1000;
/// lists thread provider ids up to the requested number, or all if none specified
#[tracing::instrument(skip(client, access_token, next_page_token), err)]
@@ -86,159 +76,21 @@ pub(crate) async fn list_threads(
Ok(result)
}
-/// Wrapper for get_threads that retries on GmailBatchError::RateLimitExceeded,
-/// reducing batch size each time with exponential backoff.
-#[tracing::instrument(skip(client, access_token, thread_ids), err)]
-pub async fn get_threads_with_retry(
- client: &GmailClient,
- access_token: &str,
- thread_ids: &[String],
- mut batch_size: usize,
-) -> anyhow::Result<Vec<ThreadResource>> {
- let mut last_error: Option<GmailError> = None;
- let mut current_delay = Duration::from_millis(INITIAL_RETRY_DELAY_MS);
-
- for attempt in 0..MAX_RETRY_ATTEMPTS {
- // Call the actual get_threads function
- match get_threads(client, access_token, thread_ids, batch_size).await {
- Ok(results) => {
- return Ok(results);
- }
- Err(e) => {
- match e {
- RateLimitExceeded => {
- last_error = Some(RateLimitExceeded); // Store the error type
- if attempt == MAX_RETRY_ATTEMPTS - 1 {
- // Return the specific error wrapped in anyhow with additional context
- anyhow::bail!(RateLimitExceeded);
- }
-
- // Reduce batch size for next attempt
- batch_size = (batch_size as f64 * 0.8).floor().max(1.0) as usize;
- tracing::info!(
- attempt = attempt + 1,
- next_batch_size = batch_size,
- delay_ms = current_delay.as_millis(),
- thread_ids = ?thread_ids,
- "Rate limit hit. Reducing batch size and retrying after delay."
- );
-
- // Wait before retrying
- sleep(current_delay);
- current_delay *= 2;
- }
- other_error => {
- anyhow::bail!(other_error);
- }
- }
- }
- }
- }
-
- // If loop finishes, it means all attempts failed, return the last error encountered
- Err(anyhow!(last_error.unwrap_or_else(|| {
- GmailError::GenericError(format!(
- "Exited retry loop unexpectedly after {} attempts",
- MAX_RETRY_ATTEMPTS
- ))
- })))
-}
-
-/// Fetches multiple email threads in a single batch request as per https://developers.google.com/workspace/gmail/api/guides/batch.
-/// The Gmail batch API accepts a multipart/mixed request containing multiple individual requests consolidated into one.
-/// It returns a multipart/mixed response that needs to be parsed into individual thread responses.
-#[tracing::instrument(skip(client, access_token, thread_ids),
- fields(thread_ids = ?thread_ids, batch_size = batch_size), err)]
-pub(crate) async fn get_threads(
- client: &GmailClient,
- access_token: &str,
- thread_ids: &[String],
- batch_size: usize,
-) -> Result<Vec<ThreadResource>, GmailError> {
- let mut unordered_responses = Vec::new();
-
- // variable batch size so we can decrease it if we get rate limited
- // see https://developers.google.com/workspace/gmail/api/guides/handle-errors#resolve_a_429_error_too_many_requests
- for id_chunk in thread_ids.chunks(batch_size) {
- // the boundary is what separates each of the requests in the batch request body. can be anything
- let boundary = "multipart_boundary_12345";
-
- let batch_body = build_batch_body(boundary, id_chunk, access_token);
-
- let content_type_value = format!("multipart/mixed; boundary={}", boundary);
-
- let response = client
- .inner
- .post(&client.base_batch_url)
- .header(reqwest::header::CONTENT_TYPE, content_type_value)
- .body(batch_body)
- .send()
- .await
- .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
-
- let response = response
- .error_for_status()
- .map_err(|e| GmailError::HttpRequest(e.to_string()))?;
-
- let response_content_type = response
- .headers()
- .get(reqwest::header::CONTENT_TYPE)
- .cloned()
- .ok_or_else(|| GmailError::GenericError("No content-type header found".to_string()))?;
-
- let response_body_text = response.text().await.map_err(|_| {
- GmailError::BodyReadError(format!(
- "Failed to read batch response body for thread_ids {:?}",
- id_chunk
- ))
- })?;
-
- match parse_multipart_response(&response_body_text, &response_content_type) {
- Ok(mut chunk_responses) => {
- unordered_responses.append(&mut chunk_responses);
- }
- Err(e) => {
- return Err(e);
- }
- }
- }
-
- // the batch request can return the responses in any order. need to make sure they are in
- // the same order as the thread_ids passed into the method.
- let mut response_map: HashMap<String, ThreadResource> =
- HashMap::with_capacity(unordered_responses.len());
- for response in unordered_responses {
- response_map.insert(response.id.clone(), response);
- }
-
- let mut ordered_responses = Vec::with_capacity(thread_ids.len());
- for original_id in thread_ids {
- if let Some(response) = response_map.remove(original_id) {
- ordered_responses.push(response);
- } else {
- tracing::warn!(thread_id = %original_id, "Requested thread ID not found in batch response results.");
- }
- }
-
- Ok(ordered_responses)
-}
-
-/// Gets all message IDs for a specific thread using the minimal format
-/// to reduce data transfer and processing time
-#[tracing::instrument(skip(client, access_token), err)]
-pub(crate) async fn get_message_ids_for_thread(
+/// Fetches a thread from the Gmail API with the given format and deserializes the response.
+async fn fetch_thread<T: DeserializeOwned>(
client: &GmailClient,
access_token: &str,
thread_id: &str,
-) -> anyhow::Result<Vec<String>> {
- let request_url = format!(
- "{}/users/me/threads/{}?format=minimal",
- client.base_url, thread_id
+ format: &str,
+) -> anyhow::Result<T> {
+ let url = format!(
+ "{}/users/me/threads/{}?format={}",
+ client.base_url, thread_id, format
);
let response = client
.inner
- .get(&request_url)
+ .get(&url)
.bearer_auth(access_token)
.send()
.await
@@ -255,22 +107,41 @@ pub(crate) async fn get_message_ids_for_thread(
.unwrap_or_else(|_| "Failed to read error body".to_string());
let sanitized = sanitize_error_body(&error_body);
anyhow::bail!(
- "Gmail API error {} (get message ids for thread) for thread_id: {}: {}",
+ "Gmail API error {} (get thread, format={}) for thread_id {}: {}",
status,
+ format,
thread_id,
sanitized
);
}
- let thread_resource = response
- .json::<MinimalThreadResource>()
- .await
- .context(format!(
- "Failed to parse JSON response from Gmail API for thread {}",
- thread_id
- ))?;
+ response.json::<T>().await.context(format!(
+ "Failed to parse JSON response from Gmail API for thread {}",
+ thread_id
+ ))
+}
+
+/// Fetches a single email thread with full message content from the Gmail API.
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn get_thread(
+ client: &GmailClient,
+ access_token: &str,
+ thread_id: &str,
+) -> anyhow::Result<ThreadResource> {
+ fetch_thread(client, access_token, thread_id, "full").await
+}
+
+/// Gets all message IDs for a specific thread using the minimal format
+/// to reduce data transfer and processing time
+#[tracing::instrument(skip(client, access_token), err)]
+pub(crate) async fn get_message_ids_for_thread(
+ client: &GmailClient,
+ access_token: &str,
+ thread_id: &str,
+) -> anyhow::Result<Vec<String>> {
+ let thread_resource: MinimalThreadResource =
+ fetch_thread(client, access_token, thread_id, "minimal").await?;
- // Extract message IDs from the response
let message_ids = thread_resource
.messages
.iter()
@@ -279,91 +150,3 @@ pub(crate) async fn get_message_ids_for_thread(
Ok(message_ids)
}
-
-/// build the batch request object - one sub-request for each thread_id
-fn build_batch_body(boundary: &str, thread_ids: &[String], access_token: &str) -> String {
- let mut batch_body = String::new();
- let content_id_prefix = "content_id_";
-
- for thread_id in thread_ids {
- let content_id = format!("<{}_{}>", content_id_prefix, thread_id);
- let part = format!(
- "--{boundary}\r\n\
- Content-Type: application/http\r\n\
- Content-ID: {content_id}\r\n\
- \r\n\
- GET /gmail/v1/users/me/threads/{thread_id}?format=full HTTP/1.1\r\n\
- Authorization: Bearer {access_token}\r\n\
- Accept: application/json\r\n\
- \r\n",
- boundary = boundary,
- content_id = content_id,
- thread_id = thread_id,
- access_token = access_token
- );
- batch_body.push_str(&part);
- }
-
- batch_body.push_str(&format!("--{}--\r\n", boundary));
- batch_body
-}
-
-/// the response from the batch request is a multipart response - parse it into separate threads
-fn parse_multipart_response(
- response_body: &str,
- response_content_type: &HeaderValue,
-) -> Result<Vec<ThreadResource>, GmailError> {
- // boundary is what separates each of the responses in the batch
- let boundary = response_content_type
- .to_str()
- .map_err(|e| GmailError::MultipartParse(format!("Content-Type invalid UTF-8: {}", e)))?
- .split("boundary=")
- .nth(1)
- .ok_or_else(|| {
- GmailError::MultipartParse("Could not find boundary in Content-Type".into())
- })?
- .trim_matches('"');
-
- let mut results = Vec::new();
- let boundary_marker = format!("--{}", boundary);
-
- for part in response_body.split(&boundary_marker) {
- let trimmed_part = part.trim();
-
- if trimmed_part.is_empty() || trimmed_part == "--" {
- continue;
- }
-
- if let Some(separator_index) = trimmed_part.find("{") {
- let headers_and_status = &trimmed_part[..separator_index];
- let body_json = &trimmed_part[separator_index..]; // Skip \r\n\r\n
-
- if let Some(status_line) = headers_and_status.lines().nth(3) {
- if status_line.contains("HTTP/1.1 200 OK") {
- match serde_json::from_str::<ThreadResource>(body_json) {
- Ok(thread_response) => {
- results.push(thread_response);
- }
- Err(e) => {
- return Err(BodyReadError(e.to_string()));
- }
- }
- } else if status_line.contains("HTTP/1.1 429 Too Many Requests") {
- return Err(RateLimitExceeded);
- } else {
- return Err(ApiError(status_line.to_string()));
- }
- } else {
- return Err(MultipartParse(
- "Could not find status line in batch response part".to_string(),
- ));
- }
- } else {
- return Err(MultipartParse(
- "Could not find header/body separator in batch response part".to_string(),
- ));
- }
- }
-
- Ok(results)
-}