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(email-service): ID creation and gmail-to-service struct conv… (#1197)

Evan Hutnik3b409fc12d65
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 5d8c1157e2..18972bafbb 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3150,6 +3150,7 @@ dependencies = [
name = "email_service"
version = "0.1.0"
dependencies = [
+ "ammonia",
"anyhow",
"authentication_service_client",
"aws-config",
@@ -3185,6 +3186,7 @@ dependencies = [
"macro_notify",
"macro_user_id",
"macro_uuid",
+ "mailparse",
"mime_guess",
"model",
"model-entity",
@@ -3195,6 +3197,7 @@ dependencies = [
"models_pagination",
"models_permissions",
"models_properties",
+ "once_cell",
"redis",
"regex",
"reqwest",
@@ -3858,19 +3861,15 @@ checksum = "a8d1add55171497b4705a648c6b583acafb01d58050a51727785f0b2c8e0a2b2"
name = "gmail_client"
version = "0.1.0"
dependencies = [
- "ammonia",
"anyhow",
"base64 0.22.1",
"chrono",
"futures",
"jsonwebtoken",
"mail-builder",
- "mailparse",
"mockall",
"models_email",
- "once_cell",
"reqwest",
- "scraper",
"serde_json",
"tokio",
"tracing",
diff --git a/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
index bb79430f6f..59c18375e0 100644
--- a/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
+++ b/rust/cloud-storage/email_db_client/src/contacts/upsert_sync.rs
@@ -13,10 +13,8 @@ pub async fn upsert_contacts(pool: &PgPool, contacts: &[Contact]) -> anyhow::Res
return Ok(0);
}
- let db_contacts: Vec<db::contact::Contact> = contacts
- .iter()
- .map(|c| map_new_contact_to_db(c, macro_uuid::generate_uuid_v7()))
- .collect();
+ let db_contacts: Vec<db::contact::Contact> =
+ contacts.iter().map(map_new_contact_to_db).collect();
// Filter out contacts without email addresses and prepare vectors for bulk insert
let mut ids = Vec::new();
diff --git a/rust/cloud-storage/email_db_client/src/messages/insert.rs b/rust/cloud-storage/email_db_client/src/messages/insert.rs
index 1ed6e590ea..02c3228510 100644
--- a/rust/cloud-storage/email_db_client/src/messages/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/messages/insert.rs
@@ -90,14 +90,8 @@ async fn insert_db_message(
from_contact_id: Option<Uuid>,
update_thread_metadata: bool,
) -> anyhow::Result<Uuid> {
- let message_db_id = macro_uuid::generate_uuid_v7();
-
- let db_message = parse::service_to_db::map_service_message_to_db(
- message,
- message_db_id,
- thread_id,
- from_contact_id,
- );
+ let db_message =
+ parse::service_to_db::map_service_message_to_db(message, thread_id, from_contact_id);
let result = sqlx::query!(
r#"
diff --git a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs
index 9dfa70dc31..569ae4b30c 100644
--- a/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs
+++ b/rust/cloud-storage/email_db_client/src/parse/db_to_service.rs
@@ -71,7 +71,7 @@ pub fn map_db_attachment_to_service(
db_att: db::attachment::Attachment,
) -> service::attachment::Attachment {
service::attachment::Attachment {
- db_id: Some(db_att.id),
+ db_id: db_att.id,
provider_id: db_att.provider_attachment_id,
data_url: None,
filename: db_att.filename,
@@ -154,10 +154,10 @@ pub fn map_attachmentless_db_message_to_service(
let labels_list = labels_res.into_iter().map(Into::into).collect();
message::Message {
- db_id: Some(db_message.id),
+ db_id: db_message.id,
provider_id: db_message.provider_id,
provider_thread_id: db_message.provider_thread_id,
- thread_db_id: Some(db_message.thread_id),
+ thread_db_id: db_message.thread_id,
replying_to_id: db_message.replying_to_id,
global_id: db_message.global_id,
link_id: db_message.link_id,
@@ -227,7 +227,7 @@ pub fn map_db_thread_to_service(
messages: Vec<message::Message>,
) -> thread::Thread {
thread::Thread {
- db_id: Some(db_thread.id),
+ db_id: db_thread.id,
provider_id: db_thread.provider_id,
link_id: db_thread.link_id,
inbox_visible: db_thread.inbox_visible,
diff --git a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs
index 019618d19e..cb168121ca 100644
--- a/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs
+++ b/rust/cloud-storage/email_db_client/src/parse/service_to_db.rs
@@ -30,11 +30,10 @@ pub fn addresses_from_message<T: HasContactInfo>(message: &T) -> address::Parsed
#[tracing::instrument(skip(service_thread))]
pub fn map_service_thread_to_db(
service_thread: &thread::Thread,
- id: Uuid,
link_id: Uuid,
) -> db::thread::Thread {
db::thread::Thread {
- id,
+ id: service_thread.db_id,
provider_id: service_thread.provider_id.clone(),
link_id,
inbox_visible: service_thread.inbox_visible,
@@ -50,12 +49,11 @@ pub fn map_service_thread_to_db(
#[tracing::instrument]
pub fn map_service_message_to_db(
service_msg: &mut message::Message,
- id: Uuid,
thread_id: Uuid,
from_contact_id: Option<Uuid>,
) -> db::message::Message {
db::message::Message {
- id,
+ id: service_msg.db_id,
provider_id: service_msg.provider_id.clone(),
global_id: service_msg.global_id.clone(),
thread_id,
@@ -138,7 +136,7 @@ pub fn map_service_attachments_to_db(
});
attachment::Attachment {
- id: macro_uuid::generate_uuid_v7(),
+ id: service_attachment.db_id,
message_id: message_db_id,
provider_attachment_id: service_attachment.provider_id.clone(),
filename,
@@ -152,14 +150,14 @@ pub fn map_service_attachments_to_db(
.collect()
}
-pub fn map_new_contact_to_db(service_msg: &Contact, id: Uuid) -> db::contact::Contact {
+pub fn map_new_contact_to_db(service_contact: &Contact) -> db::contact::Contact {
db::contact::Contact {
- id,
- link_id: service_msg.link_id,
- name: service_msg.name.clone(),
- email_address: service_msg.email_address.clone(),
- original_photo_url: service_msg.original_photo_url.clone(),
- sfs_photo_url: service_msg.sfs_photo_url.clone(),
+ id: service_contact.id,
+ link_id: service_contact.link_id,
+ name: service_contact.name.clone(),
+ email_address: service_contact.email_address.clone(),
+ original_photo_url: service_contact.original_photo_url.clone(),
+ sfs_photo_url: service_contact.sfs_photo_url.clone(),
created_at: Utc::now(),
updated_at: Utc::now(),
}
diff --git a/rust/cloud-storage/email_db_client/src/threads/insert.rs b/rust/cloud-storage/email_db_client/src/threads/insert.rs
index 61276f7849..4bc970cccc 100644
--- a/rust/cloud-storage/email_db_client/src/threads/insert.rs
+++ b/rust/cloud-storage/email_db_client/src/threads/insert.rs
@@ -102,9 +102,7 @@ pub async fn insert_thread<'e, E>(
where
E: Executor<'e, Database = Postgres>,
{
- let thread_id = macro_uuid::generate_uuid_v7();
- let db_thread =
- parse::service_to_db::map_service_thread_to_db(service_thread, thread_id, link_id);
+ let db_thread = parse::service_to_db::map_service_thread_to_db(service_thread, link_id);
let result = sqlx::query!(
r#"
@@ -147,7 +145,7 @@ where
E: Executor<'e, Database = Postgres>,
{
let thread = thread::Thread {
- db_id: None,
+ db_id: macro_uuid::generate_uuid_v7(),
provider_id: Some(thread_provider_id.to_string()),
link_id,
inbox_visible: false,
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 6d699295ec..ba403d37c3 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -63,6 +63,7 @@ sfs_map = []
sfs_delete = []
[dependencies]
+ammonia = "4.1.0"
anyhow = { workspace = true }
authentication_service_client = { path = "../authentication_service_client" }
aws-config = { workspace = true }
@@ -93,6 +94,7 @@ macro_auth = { path = "../macro_auth" }
macro_cors = { path = "../macro_cors" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
+mailparse = "0.16.1"
macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
@@ -109,6 +111,7 @@ models_email = { path = "../models_email" }
models_opensearch = { path = "../models_opensearch" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
models_permissions = { path = "../models_permissions" }
+once_cell = { workspace = true }
models_properties = { path = "../models_properties" }
redis = { workspace = true, features = [
"cluster-async",
diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
index cbfc5b617c..fd18f45ec5 100644
--- a/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get.rs
@@ -183,11 +183,6 @@ pub async fn upload_single_attachment(
return Ok("https://example.com/mock-url".to_string());
}
- // Ensure attachment has a db_id
- let attachment_id = attachment
- .db_id
- .ok_or_else(|| anyhow::anyhow!("Attachment must have a db_id to generate an object key"))?;
-
// Upload the attachment data to S3
match state
.s3_client
@@ -201,7 +196,7 @@ pub async fn upload_single_attachment(
.with_context(|| {
format!(
"Failed to generate presigned URL for attachment_id {} in bucket {} with key {}",
- attachment_id, bucket, object_key
+ attachment.db_id, bucket, object_key
)
})?;
@@ -218,7 +213,7 @@ pub async fn upload_single_attachment(
"Failed to upload attachment: {} - link_id: {}, attachment_id: {}, content_length: {}, bucket: {}, key: {}",
e,
link_id,
- attachment_id,
+ attachment.db_id,
attachment_data.len(),
bucket,
object_key
diff --git a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
index 72528164c4..14a1da19c1 100644
--- a/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
+++ b/rust/cloud-storage/email_service/src/api/email/drafts/create.rs
@@ -10,6 +10,7 @@ use email_db_client::contacts::upsert_message::parse_and_upsert_message_contacts
use email_db_client::messages::insert::insert_message_to_send_db;
use email_db_client::parse::service_to_db::addresses_from_message;
use email_db_client::user_history::upsert_user_history;
+use macro_uuid::generate_uuid_v7;
use model::response::ErrorResponse;
use model::user::UserContext;
use models_email::email::db::address::UpsertedRecipients;
@@ -170,8 +171,10 @@ async fn insert_message_to_send(
let thread_db_id = if let Some(id) = draft.thread_db_id {
id
} else {
+ // Generate thread ID in service layer before insertion
+ let thread_id = generate_uuid_v7();
let thread = thread::Thread {
- db_id: None,
+ db_id: thread_id,
provider_id: None,
link_id,
// if we're creating a thread with a sent message, it's not visible in the inbox
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 81877dd045..ef54a8d38e 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
@@ -103,7 +103,7 @@ pub async fn archived_handler(
for m in messages.iter() {
if has_inbox_label(m) == is_archiving {
- message_db_ids.push(m.db_id.unwrap());
+ message_db_ids.push(m.db_id);
// should always exist
message_provider_ids.push(m.provider_id.clone().unwrap_or_default());
}
diff --git a/rust/cloud-storage/email_service/src/api/email/threads/get.rs b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
index fdbf542b35..3086b66b8d 100644
--- a/rust/cloud-storage/email_service/src/api/email/threads/get.rs
+++ b/rust/cloud-storage/email_service/src/api/email/threads/get.rs
@@ -176,7 +176,7 @@ async fn get_thread_handler_inner<U: EmailService>(
let access_level = ctx
.dss_client
- .get_thread_access_level(macro_id, &thread.db_id.unwrap().to_string())
+ .get_thread_access_level(macro_id, &thread.db_id.to_string())
.await
.map_err(|e| {
tracing::error!(error=?e, "unable to get access level for thread for user");
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 eb6a6eeae1..1641205880 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
@@ -103,7 +103,7 @@ pub async fn seen_handler(
return Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response());
}
- let message_db_ids: Vec<Uuid> = unread_messages.iter().map(|m| m.db_id.unwrap()).collect();
+ let message_db_ids: Vec<Uuid> = unread_messages.iter().map(|m| m.db_id).collect();
let message_provider_ids: Vec<String> = unread_messages
.iter()
.map(|m| m.provider_id.clone().unwrap_or_default())
diff --git a/rust/cloud-storage/gmail_client/src/parse/contact.rs b/rust/cloud-storage/email_service/src/convert/contact.rs
similarity index 92%
rename from rust/cloud-storage/gmail_client/src/parse/contact.rs
rename to rust/cloud-storage/email_service/src/convert/contact.rs
index 2aaa9b81c1..251a5f6bef 100644
--- a/rust/cloud-storage/gmail_client/src/parse/contact.rs
+++ b/rust/cloud-storage/email_service/src/convert/contact.rs
@@ -1,3 +1,4 @@
+use macro_uuid::generate_uuid_v7;
use models_email::gmail::contacts::PersonResource;
use models_email::service::contact::Contact;
use uuid::Uuid;
@@ -23,7 +24,7 @@ pub fn map_person_to_contact(link_id: Uuid, person: PersonResource) -> Contact {
.and_then(|p| p.url);
Contact {
- id: None,
+ id: generate_uuid_v7(),
link_id,
name: display_name,
email_address,
diff --git a/rust/cloud-storage/gmail_client/src/parse/history.rs b/rust/cloud-storage/email_service/src/convert/history.rs
similarity index 100%
rename from rust/cloud-storage/gmail_client/src/parse/history.rs
rename to rust/cloud-storage/email_service/src/convert/history.rs
diff --git a/rust/cloud-storage/gmail_client/src/parse/message.rs b/rust/cloud-storage/email_service/src/convert/message.rs
similarity index 95%
rename from rust/cloud-storage/gmail_client/src/parse/message.rs
rename to rust/cloud-storage/email_service/src/convert/message.rs
index 74c4784fa3..1451f170d4 100644
--- a/rust/cloud-storage/gmail_client/src/parse/message.rs
+++ b/rust/cloud-storage/email_service/src/convert/message.rs
@@ -1,6 +1,7 @@
use super::payload::parse_gmail_payload;
use anyhow::{Context, Result};
use chrono::{TimeZone, Utc};
+use macro_uuid::generate_uuid_v7;
use mailparse::{MailAddr, MailAddrList, addrparse};
use models_email::email::service;
use models_email::gmail::labels::SystemLabelID;
@@ -56,24 +57,22 @@ pub fn map_message_resource_to_service(
let attachments = parsed_payload
.attachments_metadata
.into_iter()
- .map(|meta| {
- service::attachment::Attachment {
- db_id: None, // gets populated later
- provider_id: meta.provider_attachment_id,
- data_url: None,
- filename: meta.filename,
- mime_type: meta.mime_type,
- size_bytes: meta.size_bytes,
- content_id: meta.content_id,
- sfs_id: None,
- }
+ .map(|meta| service::attachment::Attachment {
+ db_id: generate_uuid_v7(),
+ provider_id: meta.provider_attachment_id,
+ data_url: None,
+ filename: meta.filename,
+ mime_type: meta.mime_type,
+ size_bytes: meta.size_bytes,
+ content_id: meta.content_id,
+ sfs_id: None,
})
.collect();
Ok(service::message::Message {
- db_id: None, // Omitted - needs to be associated later
+ db_id: generate_uuid_v7(),
provider_id: Some(message.id),
- thread_db_id: None, // Omitted - needs to be associated later
+ thread_db_id: generate_uuid_v7(),
provider_thread_id: Some(message.thread_id),
replying_to_id: None, // gets generated later, once message has been inserted
global_id: Some(parsed_payload.global_id),
diff --git a/rust/cloud-storage/gmail_client/src/parse/mod.rs b/rust/cloud-storage/email_service/src/convert/mod.rs
similarity index 77%
rename from rust/cloud-storage/gmail_client/src/parse/mod.rs
rename to rust/cloud-storage/email_service/src/convert/mod.rs
index d74e258a02..bc0c9322da 100644
--- a/rust/cloud-storage/gmail_client/src/parse/mod.rs
+++ b/rust/cloud-storage/email_service/src/convert/mod.rs
@@ -1,14 +1,15 @@
+//! Conversion utilities for mapping Gmail API responses to service layer models.
+
mod payload;
+mod sanitizer;
pub mod contact;
pub mod history;
pub mod message;
pub mod thread;
-pub mod watch;
// Re-export commonly used functions from the public API
pub use contact::map_person_to_contact;
pub use history::map_history_list_response_to_history;
pub use message::map_message_resource_to_service;
pub use thread::map_thread_resources_to_service;
-pub use watch::map_watch_response_to_service;
diff --git a/rust/cloud-storage/gmail_client/src/parse/payload.rs b/rust/cloud-storage/email_service/src/convert/payload.rs
similarity index 97%
rename from rust/cloud-storage/gmail_client/src/parse/payload.rs
rename to rust/cloud-storage/email_service/src/convert/payload.rs
index 79610684ed..3d6c25a7cf 100644
--- a/rust/cloud-storage/gmail_client/src/parse/payload.rs
+++ b/rust/cloud-storage/email_service/src/convert/payload.rs
@@ -4,9 +4,9 @@ use chrono::{DateTime, TimeZone, Utc};
use models_email::email::service;
use models_email::gmail::{Header, MessagePart};
-use crate::parse::message::find_header;
-use crate::parse::message::parse_address_header;
-use crate::sanitizer::sanitize_email_html;
+use crate::convert::message::find_header;
+use crate::convert::message::parse_address_header;
+use crate::convert::sanitizer::sanitize_email_html;
#[derive(Debug, Default)]
pub struct ParsedGmailPayload {
diff --git a/rust/cloud-storage/gmail_client/src/sanitizer.rs b/rust/cloud-storage/email_service/src/convert/sanitizer.rs
similarity index 85%
rename from rust/cloud-storage/gmail_client/src/sanitizer.rs
rename to rust/cloud-storage/email_service/src/convert/sanitizer.rs
index ead998da5c..bdd4debbdc 100644
--- a/rust/cloud-storage/gmail_client/src/sanitizer.rs
+++ b/rust/cloud-storage/email_service/src/convert/sanitizer.rs
@@ -283,36 +283,3 @@ fn get_safe_css_properties() -> HashSet<&'static str> {
"list-style",
])
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use std::fs;
-
- /// should extract the body attribute and disregard the title attribute
- #[test]
- fn test_sanitize_body_only() {
- let input_html = include_str!("testdata/sanitizer/body-only/original.html");
- let expected_html = include_str!("testdata/sanitizer/body-only/expected.html");
- test_html_sanitization(input_html, expected_html, "body-only");
- }
-
- fn test_html_sanitization(input_html: &str, expected_html: &str, test_name: &str) {
- // Get the sanitizer and sanitize the HTML
- let sanitized_html = sanitize_email_html(input_html);
-
- // Write the sanitized output to a file for inspection (uncomment for debugging if needed)
- let path = format!("src/testdata/sanitizer/{}/actual_output.html", test_name);
- fs::create_dir_all(path.rsplit_once('/').unwrap().0).expect("Failed to create directory");
- fs::write(path, &sanitized_html).expect("Failed to write sanitized output to file");
-
- // Compare the sanitized output with the expected output
- // Normalize whitespace for more reliable comparison
- assert_eq!(
- sanitized_html.replace(" ", "").replace("\n", "").trim(),
- expected_html.replace(" ", "").replace("\n", "").trim(),
- "Test '{}' failed: sanitized HTML doesn't match expected output",
- test_name
- );
- }
-}
diff --git a/rust/cloud-storage/gmail_client/src/parse/thread.rs b/rust/cloud-storage/email_service/src/convert/thread.rs
similarity index 93%
rename from rust/cloud-storage/gmail_client/src/parse/thread.rs
rename to rust/cloud-storage/email_service/src/convert/thread.rs
index 6686723f33..abd115257d 100644
--- a/rust/cloud-storage/gmail_client/src/parse/thread.rs
+++ b/rust/cloud-storage/email_service/src/convert/thread.rs
@@ -1,6 +1,7 @@
use anyhow::{Context, Result};
use chrono::Utc;
use futures::future::try_join_all;
+use macro_uuid::generate_uuid_v7;
use models_email::email::service;
use models_email::email::service::message::{is_inbound, is_outbound, is_spam_or_trash};
use models_email::gmail::ThreadResource;
@@ -86,8 +87,14 @@ pub async fn map_thread_resource_to_service(
.map(|msg| msg.internal_date_ts)
.unwrap_or_else(|| None);
+ // Generate the thread ID and update all messages to reference it
+ let thread_db_id = generate_uuid_v7();
+ for msg in service_messages.iter_mut() {
+ msg.thread_db_id = thread_db_id;
+ }
+
Ok(service::thread::Thread {
- db_id: None,
+ db_id: thread_db_id,
provider_id: Some(thread_resource.id),
link_id, // From argument
inbox_visible,
diff --git a/rust/cloud-storage/email_service/src/lib.rs b/rust/cloud-storage/email_service/src/lib.rs
index fb08291768..ac60a74d68 100644
--- a/rust/cloud-storage/email_service/src/lib.rs
+++ b/rust/cloud-storage/email_service/src/lib.rs
@@ -1,3 +1,4 @@
pub mod config;
+pub mod convert;
pub mod pubsub;
pub mod util;
diff --git a/rust/cloud-storage/email_service/src/openapi.rs b/rust/cloud-storage/email_service/src/openapi.rs
index 53e0d0b752..b3d4782ce3 100644
--- a/rust/cloud-storage/email_service/src/openapi.rs
+++ b/rust/cloud-storage/email_service/src/openapi.rs
@@ -2,6 +2,7 @@
mod api;
mod config;
+mod convert;
mod pubsub;
mod util;
mod utils;
diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
index b70ff0af5b..5ee0b91a0d 100644
--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_message.rs
@@ -1,7 +1,9 @@
+use crate::convert::map_message_resource_to_service;
use crate::pubsub::backfill::increment_counters;
use crate::pubsub::context::PubSubContext;
use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};
use crate::util::process_pre_insert::process_message_pre_insert;
+use anyhow::Context;
use models_email::email::service::backfill::{BackfillMessagePayload, BackfillPubsubMessage};
use models_email::email::service::link;
use models_email::email::service::pubsub::{DetailedError, FailureReason, ProcessingError};
@@ -27,9 +29,9 @@ pub async fn backfill_message(
.await?;
// get message from gmail
- let mut message = match ctx
+ let message_resource = match ctx
.gmail_client
- .get_message(access_token, &p.message_provider_id, link.id)
+ .get_message(access_token, &p.message_provider_id)
.await
{
Ok(Some(message)) => message,
@@ -47,6 +49,16 @@ pub async fn backfill_message(
}
};
+ // Map Gmail resource to service model (IDs are generated in the parse function)
+ let mut message = map_message_resource_to_service(message_resource, link.id)
+ .context("Failed to map message resource to service")
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: e,
+ })
+ })?;
+
process_message_pre_insert(&ctx.db, &ctx.sfs_client, &mut message).await;
// insert message into database
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs
index 46e7d43ddf..c5acb6db1c 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/gmail_message.rs
@@ -1,3 +1,4 @@
+use crate::convert::map_history_list_response_to_history;
use crate::pubsub::context::PubSubContext;
use crate::pubsub::inbox_sync::process::fetch_pubsub_gmail_token;
use crate::pubsub::util::{CheckGmailRateLimitArgs, check_gmail_rate_limit};
@@ -91,7 +92,7 @@ pub async fn gmail_message(
is_backfill: false,
})
.await?;
- let inbox_changes = ctx
+ let history_response = ctx
.gmail_client
.get_history(&gmail_access_token, &db_history_id)
.await
@@ -101,6 +102,7 @@ pub async fn gmail_message(
source: e.context(format!("unable to get history for link id: {}", link.id)),
})
})?;
+ let inbox_changes = map_history_list_response_to_history(history_response);
// Update the history_id in the database immediately to prevent duplicate processing.
// The db history_id is used to determine which inbox changes need processing when
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
index 9b8f4491fd..a9937a179b 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/update_labels.rs
@@ -95,7 +95,7 @@ pub async fn update_labels(
let gmail_message_labels = match ctx
.gmail_client
- .get_message_label_ids(&gmail_access_token, &payload.provider_message_id, link.id)
+ .get_message_label_ids(&gmail_access_token, &payload.provider_message_id)
.await
.map_err(|e| {
ProcessingError::Retryable(DetailedError {
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 db1f564850..f50634bc9f 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
@@ -1,3 +1,4 @@
+use crate::convert::{map_message_resource_to_service, map_thread_resources_to_service};
use crate::pubsub::context::PubSubContext;
use crate::pubsub::inbox_sync::operations::shared::notify_search;
use crate::pubsub::inbox_sync::process;
@@ -42,9 +43,9 @@ pub async fn upsert_message(
)
.await?;
- let message = match ctx
+ let message_resource = match ctx
.gmail_client
- .get_message(&gmail_access_token, &payload.provider_message_id, link.id)
+ .get_message(&gmail_access_token, &payload.provider_message_id)
.await
.map_err(|e| {
// retryable because we don't return an error if message doesn't exist, so this means
@@ -61,6 +62,14 @@ pub async fn upsert_message(
return Ok(());
}
};
+
+ // Map Gmail resource to service model (IDs are generated in the parse function)
+ let message = map_message_resource_to_service(message_resource, link.id).map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: e.context("Failed to map message resource to service".to_string()),
+ })
+ })?;
let message_attachment_count = message.attachments.len();
// will always exist because we just fetched it
@@ -355,13 +364,9 @@ async fn fetch_and_insert_thread(
.await
.map_err(anyhow::Error::from)?;
- let mut threads = ctx
+ let thread_resources = ctx
.gmail_client
- .get_threads(
- link_id,
- gmail_access_token,
- &vec![provider_thread_id.to_string()],
- )
+ .get_threads(gmail_access_token, &vec![provider_thread_id.to_string()])
.await
.map_err(|e| {
ProcessingError::NonRetryable(DetailedError {
@@ -370,6 +375,16 @@ async fn fetch_and_insert_thread(
})
})?;
+ // 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)
+ .await
+ .map_err(|e| {
+ ProcessingError::NonRetryable(DetailedError {
+ reason: FailureReason::GmailApiFailed,
+ source: anyhow::anyhow!("Failed to map thread resources: {}", e),
+ })
+ })?;
+
// process threads
process_threads_pre_insert(&ctx.db, &ctx.sfs_client, &mut threads).await;
diff --git a/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs b/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs
index 6bdf57e443..69f4bd95ad 100644
--- a/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs
+++ b/rust/cloud-storage/email_service/src/util/process_pre_insert/clean_message/remove_trailing_br_tags.rs
@@ -117,10 +117,10 @@ mod tests {
fn test_clean_html(dirty_html: &str, expected_clean_html: &str, test_name: &str) {
// Create a message with HTML content
let mut message = service::message::Message {
- db_id: None,
+ db_id: uuid::Uuid::default(),
provider_id: None,
global_id: None,
- thread_db_id: None,
+ thread_db_id: uuid::Uuid::default(),
provider_thread_id: None,
replying_to_id: None,
link_id: Default::default(),
diff --git a/rust/cloud-storage/email_service/src/util/sync_contacts.rs b/rust/cloud-storage/email_service/src/util/sync_contacts.rs
index bf467fdfd2..8fa1fb03b3 100644
--- a/rust/cloud-storage/email_service/src/util/sync_contacts.rs
+++ b/rust/cloud-storage/email_service/src/util/sync_contacts.rs
@@ -1,3 +1,4 @@
+use crate::convert::map_person_to_contact;
use anyhow::{Context, anyhow};
use futures::{StreamExt, stream};
use gmail_client::GmailClient;
@@ -74,12 +75,10 @@ async fn fetch_new_contacts_from_google(
let mut new_contacts_token = None;
let mut new_other_contacts_token = None;
- match gmail_client
- .get_self_contact(gmail_access_token, link.id)
- .await
- {
- Ok(response) => {
- all_new_contacts.push(response);
+ match gmail_client.get_self_contact(gmail_access_token).await {
+ Ok(person_resource) => {
+ let contact = map_person_to_contact(link.id, person_resource);
+ all_new_contacts.push(contact);
}
Err(e) => {
tracing::error!(error = ?e, link_id = %link.id, "Failed to get own contact");
@@ -87,12 +86,15 @@ async fn fetch_new_contacts_from_google(
};
match gmail_client
- .get_contacts(gmail_access_token, link.id, contacts_sync_token.as_deref())
+ .get_contacts(gmail_access_token, contacts_sync_token.as_deref())
.await
{
- Ok(response) => {
- new_contacts_token = Some(response.next_sync_token);
- all_new_contacts.extend(response.contacts);
+ Ok((person_resources, sync_token)) => {
+ new_contacts_token = Some(sync_token);
+ let contacts = person_resources
+ .into_iter()
+ .map(|p| map_person_to_contact(link.id, p));
+ all_new_contacts.extend(contacts);
}
Err(e) => {
tracing::debug!(error = ?e, link_id = %link.id, "Failed to get primary contacts");
@@ -100,16 +102,15 @@ async fn fetch_new_contacts_from_google(
};
match gmail_client
- .get_other_contacts(
- gmail_access_token,
- link.id,
- other_contacts_sync_token.as_deref(),
- )
+ .get_other_contacts(gmail_access_token, other_contacts_sync_token.as_deref())
.await
{
- Ok(response) => {
- new_other_contacts_token = Some(response.next_sync_token);
- all_new_contacts.extend(response.contacts);
+ Ok((person_resources, sync_token)) => {
+ new_other_contacts_token = Some(sync_token);
+ let contacts = person_resources
+ .into_iter()
+ .map(|p| map_person_to_contact(link.id, p));
+ all_new_contacts.extend(contacts);
}
Err(e) => {
tracing::debug!(error = ?e, link_id = %link.id, "Failed to get other contacts");
diff --git a/rust/cloud-storage/gmail_client/Cargo.toml b/rust/cloud-storage/gmail_client/Cargo.toml
index 104863ad6e..4925fc5ee4 100644
--- a/rust/cloud-storage/gmail_client/Cargo.toml
+++ b/rust/cloud-storage/gmail_client/Cargo.toml
@@ -8,19 +8,15 @@ version = "0.1.0"
gmail_test = []
[dependencies]
-ammonia = "4.1.0"
anyhow = { workspace = true }
base64 = { workspace = true }
chrono = { workspace = true }
futures = { workspace = true }
jsonwebtoken = { workspace = true }
mail-builder = "0.4.3"
-mailparse = "0.16.1"
mockall = { workspace = true }
models_email = { path = "../models_email" }
-once_cell = { workspace = true }
reqwest = { workspace = true, features = ["stream"] }
-scraper = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/gmail_client/src/contacts.rs b/rust/cloud-storage/gmail_client/src/contacts.rs
index d27cf09b06..d08b07c5b5 100644
--- a/rust/cloud-storage/gmail_client/src/contacts.rs
+++ b/rust/cloud-storage/gmail_client/src/contacts.rs
@@ -1,17 +1,14 @@
use crate::GmailClient;
-use crate::parse::map_person_to_contact;
use anyhow::Context;
use models_email::gmail::contacts::{ConnectionsResponse, OtherContactsResponse, PersonResource};
-use models_email::service::contact::{Contact, ContactList};
-use uuid::Uuid;
-/// Get the user's own connection
+/// Get the user's own connection.
+/// Returns raw Gmail PersonResource - callers should map to service layer Contact.
#[tracing::instrument(skip(client, access_token))]
pub(crate) async fn get_self_connection(
client: &GmailClient,
access_token: &str,
- link_id: Uuid,
-) -> anyhow::Result<Contact> {
+) -> anyhow::Result<PersonResource> {
let http_client = client.inner.clone();
let url = format!(
@@ -24,33 +21,31 @@ pub(crate) async fn get_self_connection(
.bearer_auth(access_token)
.send()
.await
- .context("Failed to send request to People API (list connections)")?;
+ .context("Failed to send request to People API (get self connection)")?;
let response = response
.error_for_status()
- .context("People API returned an error status (list connections)")?;
+ .context("People API returned an error status (get self connection)")?;
- let connection_response = response
+ let person_resource = response
.json::<PersonResource>()
.await
- .context("Failed to parse JSON response from People API (list connections)")?;
+ .context("Failed to parse JSON response from People API (get self connection)")?;
- let new_contact = map_person_to_contact(link_id, connection_response);
-
- Ok(new_contact)
+ Ok(person_resource)
}
/// Fetches contacts from the People API.
/// If a sync_token is provided, it fetches only the changes since the last sync.
/// Otherwise, it performs a full sync of all contacts.
+/// Returns raw Gmail PersonResource objects and the next sync token - callers should map to service layer Contacts.
#[tracing::instrument(skip(client, access_token, sync_token))]
pub(crate) async fn list_connections(
client: &GmailClient,
access_token: &str,
- link_id: Uuid,
sync_token: Option<&str>,
-) -> anyhow::Result<ContactList> {
- let mut all_contacts: Vec<Contact> = Vec::new();
+) -> anyhow::Result<(Vec<PersonResource>, String)> {
+ let mut all_persons: Vec<PersonResource> = Vec::new();
let mut next_page_token: Option<String> = None;
let mut final_sync_token: Option<String> = None;
@@ -93,12 +88,7 @@ pub(crate) async fn list_connections(
.await
.context("Failed to parse JSON response from People API (list connections)")?;
- let new_contacts = connection_response
- .connections
- .into_iter()
- .map(|person| map_person_to_contact(link_id, person));
-
- all_contacts.extend(new_contacts);
+ all_persons.extend(connection_response.connections);
// Keep the latest sync token returned by the API.
if let Some(sync_token) = connection_response.next_sync_token {
@@ -115,23 +105,20 @@ pub(crate) async fn list_connections(
let next_sync_token = final_sync_token.context("People API did not return a nextSyncToken")?;
- Ok(ContactList {
- contacts: all_contacts,
- next_sync_token,
- })
+ Ok((all_persons, next_sync_token))
}
/// Fetches "Other Contacts" from the People API.
/// If a sync_token is provided, it fetches only the changes since the last sync.
/// Otherwise, it performs a full sync of all "Other Contacts".
+/// Returns raw Gmail PersonResource objects and the next sync token - callers should map to service layer Contacts.
#[tracing::instrument(skip(client, access_token, sync_token))]
pub(crate) async fn list_other_contacts(
client: &GmailClient,
access_token: &str,
- link_id: Uuid,
sync_token: Option<&str>,
-) -> anyhow::Result<ContactList> {
- let mut all_contacts: Vec<Contact> = Vec::new();
+) -> anyhow::Result<(Vec<PersonResource>, String)> {
+ let mut all_persons: Vec<PersonResource> = Vec::new();
let mut next_page_token: Option<String> = None;
let mut final_sync_token: Option<String> = None;
@@ -174,12 +161,7 @@ pub(crate) async fn list_other_contacts(
.await
.context("Failed to parse JSON response from People API (list other contacts)")?;
- let new_contacts = other_contacts_response
- .other_contacts
- .into_iter()
- .map(|person| map_person_to_contact(link_id, person));
-
- all_contacts.extend(new_contacts);
+ all_persons.extend(other_contacts_response.other_contacts);
// Keep the latest sync token returned by the API.
if let Some(sync_token) = other_contacts_response.next_sync_token {
@@ -196,8 +178,5 @@ pub(crate) async fn list_other_contacts(
let next_sync_token = final_sync_token.context("People API did not return a nextSyncToken")?;
- Ok(ContactList {
- contacts: all_contacts,
- next_sync_token,
- })
+ Ok((all_persons, next_sync_token))
}
diff --git a/rust/cloud-storage/gmail_client/src/history.rs b/rust/cloud-storage/gmail_client/src/history.rs
index 798764d298..a4afc7d927 100644
--- a/rust/cloud-storage/gmail_client/src/history.rs
+++ b/rust/cloud-storage/gmail_client/src/history.rs
@@ -1,18 +1,17 @@
use crate::GmailClient;
-use crate::parse::map_history_list_response_to_history;
use anyhow::Context;
-use models_email::gmail;
use models_email::gmail::{HistoryListResponse, UserProfileResponse};
const MAX_RESULTS: usize = 500;
-/// Gets the changes to a user's inbox that have occurred since start_history_id
+/// Gets the changes to a user's inbox that have occurred since start_history_id.
+/// Returns raw HistoryListResponse - callers should map to InboxChanges using convert module.
#[tracing::instrument(skip(client, access_token))]
pub(crate) async fn get_history(
client: &GmailClient,
access_token: &str,
start_history_id: &str,
-) -> anyhow::Result<gmail::history::InboxChanges> {
+) -> anyhow::Result<HistoryListResponse> {
let url = format!(
"{}/users/me/history?startHistoryId={}&maxResults={}",
client.base_url, start_history_id, MAX_RESULTS
@@ -76,7 +75,7 @@ pub(crate) async fn get_history(
}
}
- Ok(map_history_list_response_to_history(history_list_response))
+ Ok(history_list_response)
}
/// returns the current history id for the user's inbox using the /profile endpoint
diff --git a/rust/cloud-storage/gmail_client/src/lib.rs b/rust/cloud-storage/gmail_client/src/lib.rs
index 119629c1b9..14f8156546 100644
--- a/rust/cloud-storage/gmail_client/src/lib.rs
+++ b/rust/cloud-storage/gmail_client/src/lib.rs
@@ -4,9 +4,7 @@ pub(crate) mod contacts;
pub(crate) mod history;
pub(crate) mod labels;
pub(crate) mod messages;
-pub(crate) mod parse;
pub(crate) mod profile;
-pub(crate) mod sanitizer;
mod settings;
pub(crate) mod threads;
pub(crate) mod watch;
@@ -21,13 +19,14 @@ use crate::threads::{DEFAULT_BATCH_SIZE, get_threads_with_retry};
use mockall::automock;
use models_email::email::service;
use models_email::email::service::address::ContactInfo;
-use models_email::email::service::{message, thread};
+use models_email::email::service::message;
+use models_email::email::service::thread::ThreadList as ServiceThreadList;
+use models_email::gmail::contacts::PersonResource;
pub use models_email::gmail::error::GmailError;
-use models_email::gmail::history::InboxChanges;
use models_email::gmail::inbox_sync::{
GoogleJwtClaims, GooglePublicKeys, JwtVerificationError, KeyMap,
};
-use models_email::service::contact::{Contact, ContactList};
+use models_email::gmail::{HistoryListResponse, MessageResource, ThreadResource};
use uuid::Uuid;
#[derive(Clone, Debug)]
@@ -68,7 +67,7 @@ impl GmailClient {
access_token: &str,
num_threads: u32,
next_page_token: Option<&str>,
- ) -> anyhow::Result<thread::ThreadList> {
+ ) -> anyhow::Result<ServiceThreadList> {
threads::list_threads(self, access_token, num_threads, next_page_token).await
}
@@ -82,24 +81,25 @@ impl GmailClient {
threads::get_message_ids_for_thread(self, access_token, thread_id).await
}
- /// Fetches the threads and messages for the given thread_ids
+ /// Fetches the threads and messages for the given thread_ids.
+ /// Returns raw Gmail ThreadResource objects - callers should map to service layer structs.
#[tracing::instrument(skip(self, access_token))]
pub async fn get_threads(
&self,
- link_id: Uuid,
access_token: &str,
thread_ids: &Vec<String>,
- ) -> anyhow::Result<Vec<thread::Thread>> {
- get_threads_with_retry(self, link_id, access_token, thread_ids, DEFAULT_BATCH_SIZE).await
+ ) -> anyhow::Result<Vec<ThreadResource>> {
+ get_threads_with_retry(self, access_token, thread_ids, DEFAULT_BATCH_SIZE).await
}
- /// Gets the changes to a user's inbox that have occurred since start_history_id
+ /// Gets the changes to a user's inbox that have occurred since start_history_id.
+ /// Returns raw HistoryListResponse - callers should map to InboxChanges using convert module.
#[tracing::instrument(skip(self, access_token))]
pub async fn get_history(
&self,
access_token: &str,
start_history_id: &str,
- ) -> anyhow::Result<InboxChanges> {
+ ) -> anyhow::Result<HistoryListResponse> {
history::get_history(self, access_token, start_history_id).await
}
@@ -189,15 +189,15 @@ impl GmailClient {
.await
}
- /// Fetches a specific message from Gmail by its provider ID
+ /// 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))]
pub async fn get_message(
&self,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
- ) -> anyhow::Result<Option<message::Message>> {
- get_message(self, access_token, message_provider_id, link_id).await
+ ) -> anyhow::Result<Option<MessageResource>> {
+ get_message(self, access_token, message_provider_id).await
}
/// Fetches a specific message's thread ID from Gmail by its provider ID
@@ -206,9 +206,8 @@ impl GmailClient {
&self,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
) -> anyhow::Result<Option<String>> {
- get_message_thread_id(self, access_token, message_provider_id, link_id).await
+ get_message_thread_id(self, access_token, message_provider_id).await
}
#[tracing::instrument(skip(self, access_token))]
@@ -216,9 +215,8 @@ impl GmailClient {
&self,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
) -> anyhow::Result<Option<Vec<String>>> {
- get_message_label_ids(self, access_token, message_provider_id, link_id).await
+ get_message_label_ids(self, access_token, message_provider_id).await
}
/// Sends a new email message
@@ -285,38 +283,36 @@ impl GmailClient {
delete_gmail_label(self, access_token, label_id).await
}
- /// Fetches the user's own contact information
+ /// Fetches the user's own contact information.
+ /// Returns raw Gmail PersonResource - callers should map to service layer Contact.
#[tracing::instrument(skip(self, access_token))]
- pub async fn get_self_contact(
- &self,
- access_token: &str,
- link_id: Uuid,
- ) -> anyhow::Result<Contact> {
- get_self_connection(self, access_token, link_id).await
+ pub async fn get_self_contact(&self, access_token: &str) -> anyhow::Result<PersonResource> {
+ get_self_connection(self, access_token).await
}
/// Fetches all of the user's main contacts, handling pagination.
- /// Returns a list of contacts and a sync token for future incremental updates.
+ /// Returns raw Gmail PersonResource objects and a sync token for future incremental updates.
+ /// Callers should map PersonResource to service layer Contact.
#[tracing::instrument(skip(self, access_token, sync_token))]
pub async fn get_contacts(
&self,
access_token: &str,
- link_id: Uuid,
sync_token: Option<&str>,
- ) -> anyhow::Result<ContactList> {
- contacts::list_connections(self, access_token, link_id, sync_token).await
+ ) -> anyhow::Result<(Vec<PersonResource>, String)> {
+ contacts::list_connections(self, access_token, sync_token).await
}
/// Fetches all of the user's "Other Contacts", handling pagination.
/// These are typically contacts auto-created from interactions.
+ /// Returns raw Gmail PersonResource objects and a sync token.
+ /// Callers should map PersonResource to service layer Contact.
#[tracing::instrument(skip(self, access_token, sync_token))]
pub async fn get_other_contacts(
&self,
access_token: &str,
- link_id: Uuid,
sync_token: Option<&str>,
- ) -> anyhow::Result<ContactList> {
- contacts::list_other_contacts(self, access_token, link_id, sync_token).await
+ ) -> anyhow::Result<(Vec<PersonResource>, String)> {
+ contacts::list_other_contacts(self, access_token, sync_token).await
}
/// Gets the email signature for a specific email address
diff --git a/rust/cloud-storage/gmail_client/src/messages.rs b/rust/cloud-storage/gmail_client/src/messages.rs
index 183c79004b..b8fd0b05db 100644
--- a/rust/cloud-storage/gmail_client/src/messages.rs
+++ b/rust/cloud-storage/gmail_client/src/messages.rs
@@ -1,5 +1,4 @@
use crate::GmailClient;
-use crate::parse::map_message_resource_to_service;
use anyhow::Context;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
@@ -9,15 +8,13 @@ use models_email::email::service::message;
use models_email::gmail::{
MessageResource, MinimalMessageResource, SendMessagePayload, SentMessageResource,
};
-use uuid::Uuid;
#[tracing::instrument(skip(client, access_token))]
pub(crate) async fn get_message(
client: &GmailClient,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
-) -> anyhow::Result<Option<message::Message>> {
+) -> anyhow::Result<Option<MessageResource>> {
let url = format!(
"{}/users/me/messages/{}",
client.base_url, message_provider_id
@@ -30,29 +27,31 @@ pub(crate) async fn get_message(
.bearer_auth(access_token)
.send()
.await
- .with_context(|| format!("Failed to send request to Gmail API (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ .with_context(|| {
+ format!(
+ "Failed to send request to Gmail API (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
- let response = response
- .error_for_status()
- .with_context(|| format!("Gmail API returned an error status (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ let response = response.error_for_status().with_context(|| {
+ format!(
+ "Gmail API returned an error status (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
let message_response = response
.json::<MessageResource>()
.await
- .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}",
+ message_provider_id))?;
- let message = map_message_resource_to_service(message_response, link_id)
- .with_context(|| format!("Failed to map Gmail message response to service message for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
-
- Ok(Some(message))
+ Ok(Some(message_response))
}
// gets a message without the body using ?format=minimal in the gmail api call
@@ -61,7 +60,6 @@ pub(crate) async fn get_message_thread_id(
client: &GmailClient,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
) -> anyhow::Result<Option<String>> {
let url = format!(
"{}/users/me/messages/{}?format=minimal",
@@ -75,22 +73,28 @@ pub(crate) async fn get_message_thread_id(
.bearer_auth(access_token)
.send()
.await
- .with_context(|| format!("Failed to send request to Gmail API (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ .with_context(|| {
+ format!(
+ "Failed to send request to Gmail API (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
- let response = response
- .error_for_status()
- .with_context(|| format!("Gmail API returned an error status (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ let response = response.error_for_status().with_context(|| {
+ format!(
+ "Gmail API returned an error status (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
let message_response = response
.json::<MinimalMessageResource>()
.await
- .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}, link_id: {}", message_provider_id, link_id))?;
+ .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}", message_provider_id))?;
Ok(Some(message_response.thread_id))
}
@@ -101,7 +105,6 @@ pub(crate) async fn get_message_label_ids(
client: &GmailClient,
access_token: &str,
message_provider_id: &str,
- link_id: Uuid,
) -> anyhow::Result<Option<Vec<String>>> {
let url = format!(
"{}/users/me/messages/{}?format=minimal",
@@ -115,22 +118,28 @@ pub(crate) async fn get_message_label_ids(
.bearer_auth(access_token)
.send()
.await
- .with_context(|| format!("Failed to send request to Gmail API (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ .with_context(|| {
+ format!(
+ "Failed to send request to Gmail API (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
if response.status() == reqwest::StatusCode::NOT_FOUND {
return Ok(None);
}
- let response = response
- .error_for_status()
- .with_context(|| format!("Gmail API returned an error status (get message) for message_provider_id: {}, link_id: {}",
- message_provider_id, link_id))?;
+ let response = response.error_for_status().with_context(|| {
+ format!(
+ "Gmail API returned an error status (get message) for message_provider_id: {}",
+ message_provider_id
+ )
+ })?;
let message_response = response
.json::<MinimalMessageResource>()
.await
- .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}, link_id: {}", message_provider_id, link_id))?;
+ .with_context(|| format!("Failed to parse JSON response from Gmail API (get message) for message_provider_id: {}", message_provider_id))?;
Ok(Some(message_response.label_ids))
}
diff --git a/rust/cloud-storage/gmail_client/src/parse/watch.rs b/rust/cloud-storage/gmail_client/src/parse/watch.rs
deleted file mode 100644
index f3e7d977cf..0000000000
--- a/rust/cloud-storage/gmail_client/src/parse/watch.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-use models_email::gmail::history::WatchResponse;
-
-/// Maps the API response to our service model
-pub fn map_watch_response_to_service(
- response: WatchResponse,
-) -> models_email::gmail::history::WatchResponse {
- models_email::gmail::history::WatchResponse {
- history_id: response.history_id,
- expiration: response.expiration,
- }
-}
diff --git a/rust/cloud-storage/gmail_client/src/threads.rs b/rust/cloud-storage/gmail_client/src/threads.rs
index 607954d695..469e32e87d 100644
--- a/rust/cloud-storage/gmail_client/src/threads.rs
+++ b/rust/cloud-storage/gmail_client/src/threads.rs
@@ -1,8 +1,6 @@
use crate::GmailClient;
-use crate::parse::map_thread_resources_to_service;
use anyhow::{Context, anyhow};
-use models_email::email::service::thread;
-use models_email::email::service::thread::ThreadList;
+use models_email::email::service::thread::{ThreadList, ThreadSummary};
use models_email::gmail::error::GmailError;
use models_email::gmail::error::GmailError::{
ApiError, BodyReadError, MultipartParse, RateLimitExceeded,
@@ -13,7 +11,6 @@ use std::cmp::min;
use std::collections::HashMap;
use std::thread::sleep;
use std::time::Duration;
-use uuid::Uuid;
// 500 is max allowed by gmail api
pub const LIST_THREADS_BATCH_SIZE: u32 = 500;
@@ -70,7 +67,7 @@ pub(crate) async fn list_threads(
.threads
.unwrap_or_default()
.into_iter()
- .map(|api_thread| thread::ThreadSummary {
+ .map(|api_thread| ThreadSummary {
provider_id: api_thread.id,
})
.collect();
@@ -88,17 +85,16 @@ pub(crate) async fn list_threads(
#[tracing::instrument(skip(client, access_token, thread_ids), level = "info")]
pub async fn get_threads_with_retry(
client: &GmailClient,
- link_id: Uuid,
access_token: &str,
thread_ids: &[String],
mut batch_size: usize,
-) -> anyhow::Result<Vec<thread::Thread>> {
+) -> 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, link_id, access_token, thread_ids, batch_size).await {
+ match get_threads(client, access_token, thread_ids, batch_size).await {
Ok(results) => {
return Ok(results);
}
@@ -108,10 +104,8 @@ pub async fn get_threads_with_retry(
last_error = Some(RateLimitExceeded); // Store the error type
if attempt == MAX_RETRY_ATTEMPTS - 1 {
// Return the specific error wrapped in anyhow with additional context
- return Err(anyhow!(RateLimitExceeded).context(format!(
- "link_id: {}, thread_ids: {:?}",
- link_id, thread_ids
- )));
+ return Err(anyhow!(RateLimitExceeded)
+ .context(format!("thread_ids: {:?}", thread_ids)));
}
// Reduce batch size for next attempt
@@ -120,7 +114,6 @@ pub async fn get_threads_with_retry(
attempt = attempt + 1,
next_batch_size = batch_size,
delay_ms = current_delay.as_millis(),
- link_id = %link_id,
thread_ids = ?thread_ids,
"Rate limit hit. Reducing batch size and retrying after delay."
);
@@ -130,10 +123,9 @@ pub async fn get_threads_with_retry(
current_delay *= 2;
}
other_error => {
- return Err(anyhow!(other_error).context(format!(
- "link_id: {}, thread_ids: {:?}",
- link_id, thread_ids
- )));
+ return Err(
+ anyhow!(other_error).context(format!("thread_ids: {:?}", thread_ids))
+ );
}
}
}
@@ -153,14 +145,13 @@ pub async fn get_threads_with_retry(
/// 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(link_id = %link_id, thread_ids = ?thread_ids, batch_size = batch_size))]
+ fields(thread_ids = ?thread_ids, batch_size = batch_size))]
pub(crate) async fn get_threads(
client: &GmailClient,
- link_id: Uuid,
access_token: &str,
thread_ids: &[String],
batch_size: usize,
-) -> Result<Vec<thread::Thread>, GmailError> {
+) -> Result<Vec<ThreadResource>, GmailError> {
let mut unordered_responses = Vec::new();
// variable batch size so we can decrease it if we get rate limited
@@ -226,16 +217,7 @@ pub(crate) async fn get_threads(
}
}
- let service_threads = map_thread_resources_to_service(ordered_responses, link_id)
- .await
- .map_err(|e| {
- GmailError::GenericError(format!(
- "Error while mapping thread resources to service: {}",
- e
- ))
- })?;
-
- Ok(service_threads)
+ Ok(ordered_responses)
}
/// Gets all message IDs for a specific thread using the minimal format
diff --git a/rust/cloud-storage/gmail_client/src/watch.rs b/rust/cloud-storage/gmail_client/src/watch.rs
index cb93ecc3dd..ae82c5ba7a 100644
--- a/rust/cloud-storage/gmail_client/src/watch.rs
+++ b/rust/cloud-storage/gmail_client/src/watch.rs
@@ -1,5 +1,4 @@
use crate::GmailClient;
-use crate::parse::map_watch_response_to_service;
use anyhow::Context;
use models_email::gmail::WatchRequest;
use models_email::gmail::error::GmailError;
@@ -52,7 +51,7 @@ pub(crate) async fn register_watch(
.await
.map_err(|e| GmailError::BodyReadError(e.to_string()))?;
- Ok(map_watch_response_to_service(watch_response))
+ Ok(watch_response)
}
/// Stops push notifications for a user's Gmail inbox
diff --git a/rust/cloud-storage/models_email/src/email/service/attachment.rs b/rust/cloud-storage/models_email/src/email/service/attachment.rs
index 5d1087234a..63531a6d82 100644
--- a/rust/cloud-storage/models_email/src/email/service/attachment.rs
+++ b/rust/cloud-storage/models_email/src/email/service/attachment.rs
@@ -11,8 +11,8 @@ use uuid::Uuid;
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct Attachment {
- #[schemars(with = "Option<String>")]
- pub db_id: Option<Uuid>,
+ #[schemars(with = "String")]
+ pub db_id: Uuid,
// a different value is returned by the gmail API for this each time you fetch a message -
// don't make the mistake of using it to uniquely identify an attachment
pub provider_id: Option<String>,
diff --git a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs
index 175cb9f094..e524d80991 100644
--- a/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs
+++ b/rust/cloud-storage/models_email/src/email/service/body_parsing/body_replyless/mod.rs
@@ -89,10 +89,10 @@ mod tests {
fn test_email_extraction(full_email: &str, expected_reply: &str, test_name: &str) {
// Create a message with HTML content
let message = service::message::Message {
- db_id: None,
+ db_id: uuid::Uuid::default(),
provider_id: None,
global_id: None,
- thread_db_id: None,
+ thread_db_id: uuid::Uuid::default(),
provider_thread_id: None,
replying_to_id: None,
link_id: Default::default(),
diff --git a/rust/cloud-storage/models_email/src/email/service/contact.rs b/rust/cloud-storage/models_email/src/email/service/contact.rs
index 638af73352..979ffbbb99 100644
--- a/rust/cloud-storage/models_email/src/email/service/contact.rs
+++ b/rust/cloud-storage/models_email/src/email/service/contact.rs
@@ -5,8 +5,8 @@ use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema, JsonSchema)]
pub struct Contact {
- #[schemars(with = "Option<String>")]
- pub id: Option<Uuid>,
+ #[schemars(with = "String")]
+ pub id: Uuid,
#[schemars(with = "String")]
pub link_id: Uuid,
pub name: Option<String>,
@@ -25,7 +25,7 @@ pub struct ContactList {
impl From<crate::email::db::contact::Contact> for Contact {
fn from(db_contact: crate::email::db::contact::Contact) -> Self {
Self {
- id: Some(db_contact.id),
+ id: db_contact.id,
link_id: db_contact.link_id,
name: db_contact.name,
email_address: db_contact.email_address,
diff --git a/rust/cloud-storage/models_email/src/email/service/message.rs b/rust/cloud-storage/models_email/src/email/service/message.rs
index d6c2e3eb9b..ed62ece8f4 100644
--- a/rust/cloud-storage/models_email/src/email/service/message.rs
+++ b/rust/cloud-storage/models_email/src/email/service/message.rs
@@ -51,11 +51,11 @@ pub struct ParsedSearchMessage {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Message {
// the uuid we generated for the message in our database
- pub db_id: Option<Uuid>,
+ pub db_id: Uuid,
// the id the user's provider (i.e. gmail) uses to identify the message
pub provider_id: Option<String>,
// the uuid we generated for the message's thread in the database
- pub thread_db_id: Option<Uuid>,
+ pub thread_db_id: Uuid,
// the id the user's provider (i.e. gmail) uses to identify the thread
pub provider_thread_id: Option<String>,
// the db id of the specific message this message is replying to (if any)
@@ -114,9 +114,9 @@ impl From<MessageWithBodyReplyless> for ParsedMessage {
fn from(msg: MessageWithBodyReplyless) -> Self {
Self {
body_parsed: get_body_parsed_for_message(&msg),
- db_id: msg.inner.db_id.unwrap_or_default(),
+ db_id: msg.inner.db_id,
link_id: msg.inner.link_id,
- thread_db_id: msg.inner.thread_db_id.unwrap_or_default(),
+ thread_db_id: msg.inner.thread_db_id,
subject: msg.inner.subject,
from: msg.inner.from,
to: msg.inner.to,
@@ -140,9 +140,9 @@ impl From<MessageWithBodyReplyless> for ParsedSearchMessage {
fn from(msg: MessageWithBodyReplyless) -> Self {
Self {
body_parsed_linkless: get_body_parsed_linkless_for_message(&msg),
- db_id: msg.inner.db_id.unwrap_or_default(),
+ db_id: msg.inner.db_id,
link_id: msg.inner.link_id,
- thread_db_id: msg.inner.thread_db_id.unwrap_or_default(),
+ thread_db_id: msg.inner.thread_db_id,
subject: msg.inner.subject,
from: msg.inner.from,
to: msg.inner.to,
diff --git a/rust/cloud-storage/models_email/src/email/service/thread.rs b/rust/cloud-storage/models_email/src/email/service/thread.rs
index 76e72b5cc9..d860752a61 100644
--- a/rust/cloud-storage/models_email/src/email/service/thread.rs
+++ b/rust/cloud-storage/models_email/src/email/service/thread.rs
@@ -29,7 +29,7 @@ pub struct ThreadList {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct Thread {
- pub db_id: Option<Uuid>,
+ pub db_id: Uuid,
pub provider_id: Option<String>,
pub link_id: Uuid,
pub inbox_visible: bool,
@@ -48,7 +48,7 @@ pub struct Thread {
/// Thread object exposed to the FE in Get Threads Call
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct APIThread {
- pub db_id: Option<Uuid>,
+ pub db_id: Uuid,
pub provider_id: Option<String>,
pub link_id: Uuid,
pub inbox_visible: bool,