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
feat(email-service): Get document id for email attachment endpoint (#309)
Evan Hutnik5b2045112fbd
diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.json b/rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.jsonnew file mode 100644index 0000000000..efbec5c18e--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n a.id AS attachment_db_id,\n m.provider_id as \"email_provider_id!\",\n a.provider_attachment_id as \"provider_attachment_id!\",\n a.filename as \"filename!\",\n a.mime_type as \"mime_type!\",\n m.internal_date_ts as \"internal_date_ts!\"\n FROM email_attachments a\n JOIN email_messages m ON a.message_id = m.id\n JOIN email_threads t ON m.thread_id = t.id\n WHERE a.id = $1 AND t.link_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "attachment_db_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "email_provider_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "provider_attachment_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "filename!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "mime_type!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 5,+ "name": "internal_date_ts!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false,+ true,+ true,+ true,+ true,+ true+ ]+ },+ "hash": "6e4fcdd716bd4ede49c7bdf7c23518c7f030dabda7317a2f1453cd2617629d58"+}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.json b/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.jsondeleted file mode 100644index acee8efe17..0000000000--- a/rust/cloud-storage/email_db_client/.sqlx/query-ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc.json+++ /dev/null@@ -1,22 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n SELECT document_id\n FROM document_email\n WHERE email_attachment_id = $1\n ",- "describe": {- "columns": [- {- "ordinal": 0,- "name": "document_id",- "type_info": "Text"- }- ],- "parameters": {- "Left": [- "Uuid"- ]- },- "nullable": [- false- ]- },- "hash": "ef2a07e87db8a0cad371d7c5df36edeaec2153579d54c7bc4153ffca231930bc"-}diff --git a/rust/cloud-storage/email_db_client/.sqlx/query-f253c2b856a3a264b27a08d68b36286344bdef6e504225847b094c87d7cdaa95.json b/rust/cloud-storage/email_db_client/.sqlx/query-f253c2b856a3a264b27a08d68b36286344bdef6e504225847b094c87d7cdaa95.jsonnew file mode 100644index 0000000000..643f654141--- /dev/null+++ b/rust/cloud-storage/email_db_client/.sqlx/query-f253c2b856a3a264b27a08d68b36286344bdef6e504225847b094c87d7cdaa95.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT document_id\n FROM document_email de\n INNER JOIN email_attachments ea on de.email_attachment_id = ea.id\n INNER JOIN email_messages em on ea.message_id = em.id\n WHERE em.link_id = $1 AND email_attachment_id = $2\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "document_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "f253c2b856a3a264b27a08d68b36286344bdef6e504225847b094c87d7cdaa95"+}diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rsindex ded4ded816..1cf24b5890 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/mod.rs@@ -191,7 +191,7 @@ whereOk(())}-#[tracing::instrument(skip(pool))]+#[tracing::instrument(skip(pool), err)]pub async fn fetch_attachment_by_id(pool: &PgPool,attachment_id: Uuid,@@ -309,22 +309,26 @@ pub async fn get_attachments_by_thread_ids(Ok(result)}-/// return if record exists for email attachment+/// Get document_id for email attachment if record exists#[tracing::instrument(skip(db), err)]-pub async fn document_email_record_exists(+pub async fn get_document_id_by_attachment_id(db: &Pool<Postgres>,+ link_id: Uuid,email_attachment_id: Uuid,-) -> anyhow::Result<bool> {- let exists = sqlx::query!(+) -> anyhow::Result<Option<String>> {+ let result = sqlx::query!(r#"SELECT document_id- FROM document_email- WHERE email_attachment_id = $1+ FROM document_email de+ INNER JOIN email_attachments ea on de.email_attachment_id = ea.id+ INNER JOIN email_messages em on ea.message_id = em.id+ WHERE em.link_id = $1 AND email_attachment_id = $2"#,+ link_id,email_attachment_id,).fetch_optional(db).await?;- Ok(exists.is_some())+ Ok(result.map(|record| record.document_id))}diff --git a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rsindex 63a8299696..8501f29436 100644--- a/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs+++ b/rust/cloud-storage/email_db_client/src/attachments/provider/upload.rs@@ -355,5 +355,34 @@ pub async fn fetch_insertable_attachments_for_new_email(Ok(attachments)}+pub async fn fetch_attachment_upload_metadata_by_id(+ db: &Pool<Postgres>,+ link_id: Uuid,+ attachment_id: Uuid,+) -> anyhow::Result<Option<AttachmentUploadMetadata>> {+ let row = sqlx::query_as!(+ AttachmentUploadMetadata,+ r#"+ SELECT+ a.id AS attachment_db_id,+ m.provider_id as "email_provider_id!",+ a.provider_attachment_id as "provider_attachment_id!",+ a.filename as "filename!",+ a.mime_type as "mime_type!",+ m.internal_date_ts as "internal_date_ts!"+ FROM email_attachments a+ JOIN email_messages m ON a.message_id = m.id+ JOIN email_threads t ON m.thread_id = t.id+ WHERE a.id = $1 AND t.link_id = $2+ "#,+ attachment_id,+ link_id+ )+ .fetch_optional(db)+ .await?;++ Ok(row)+}+#[cfg(test)]mod test;diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rsnew file mode 100644index 0000000000..f0ebd63dc3--- /dev/null+++ b/rust/cloud-storage/email_service/src/api/email/attachments/get_document_id.rs@@ -0,0 +1,112 @@+use crate::api::context::ApiContext;+use crate::util::upload_attachment::upload_attachment;+use axum::extract::{Path, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::{Extension, Json};+use model::response::ErrorResponse;+use models_email::email::service::link::Link;+use strum_macros::AsRefStr;+use thiserror::Error;+use utoipa::ToSchema;+use uuid::Uuid;++#[derive(Debug, Error, AsRefStr)]+pub enum GetAttachmentDocumentIdError {+ #[error("Attachment not found")]+ AttachmentNotFound,++ #[error("Database error occurred")]+ DatabaseError(anyhow::Error),++ #[error("Failed to upload attachment")]+ UploadError(anyhow::Error),+}++impl IntoResponse for GetAttachmentDocumentIdError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ GetAttachmentDocumentIdError::AttachmentNotFound => StatusCode::NOT_FOUND,+ GetAttachmentDocumentIdError::DatabaseError(_)+ | GetAttachmentDocumentIdError::UploadError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (status_code, self.to_string()).into_response()+ }+}++/// The response returned from the get attachment endpoint+#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct GetAttachmentDocumentIDResponse {+ pub attachment_id: Uuid,+ pub document_id: String,+}++/// Get the Macro document id for an email attachment, uploading it if it doesn't already exist.+#[utoipa::path(+ get,+ tag = "Attachments",+ path = "/email/attachments/{id}/document_id",+ operation_id = "get_attachment_document_id",+ params(+ ("id" = Uuid, Path, description = "Attachment ID."),+ ),+ responses(+ (status = 200, body = GetAttachmentDocumentIDResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx))]+pub async fn handler(+ State(ctx): State<ApiContext>,+ link: Extension<Link>,+ gmail_token: Extension<String>,+ Path(attachment_id): Path<Uuid>,+) -> Result<Json<GetAttachmentDocumentIDResponse>, GetAttachmentDocumentIdError> {+ // return ID if attachment already exists in Macro+ let existing_document_id =+ email_db_client::attachments::provider::get_document_id_by_attachment_id(+ &ctx.db,+ link.id,+ attachment_id,+ )+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?;++ if let Some(document_id) = existing_document_id {+ return Ok(Json(GetAttachmentDocumentIDResponse {+ attachment_id,+ document_id,+ }));+ }++ // upload attachment if it doesn't already exist+ let attachment_metadata =+ email_db_client::attachments::provider::upload::fetch_attachment_upload_metadata_by_id(+ &ctx.db,+ link.id,+ attachment_id,+ )+ .await+ .map_err(GetAttachmentDocumentIdError::DatabaseError)?+ .ok_or(GetAttachmentDocumentIdError::AttachmentNotFound)?;++ let document_id = upload_attachment(+ &ctx.redis_client,+ &ctx.gmail_client,+ &ctx.dss_client,+ &gmail_token,+ &link,+ &attachment_metadata,+ )+ .await+ .map_err(GetAttachmentDocumentIdError::UploadError)?;++ Ok(Json(GetAttachmentDocumentIDResponse {+ attachment_id,+ document_id,+ }))+}diff --git a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rsindex 175fc656b7..95ff0fedd0 100644--- a/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs+++ b/rust/cloud-storage/email_service/src/api/email/attachments/mod.rs@@ -5,20 +5,21 @@ use tower::ServiceBuilder;use crate::api::ApiContext;pub(crate) mod get;+pub(crate) mod get_document_id;pub fn router(state: ApiContext) -> Router<ApiContext> {- Router::new().route(- "/:id",- get(get::handler).layer(+ Router::new()+ .route("/:id", get(get::handler))+ .route("/:id/document_id", get(get_document_id::handler))+ .layer(ServiceBuilder::new().layer(axum::middleware::from_fn_with_state(state.clone(),crate::api::middleware::link::attach_link_context,)).layer(axum::middleware::from_fn_with_state(- state,+ state.clone(),crate::api::middleware::gmail_token::attach_gmail_token,)),- ),- )+ )}diff --git a/rust/cloud-storage/email_service/src/api/swagger.rs b/rust/cloud-storage/email_service/src/api/swagger.rsindex f24501d42f..946dda5eee 100644--- a/rust/cloud-storage/email_service/src/api/swagger.rs+++ b/rust/cloud-storage/email_service/src/api/swagger.rs@@ -1,4 +1,5 @@use crate::api::email::attachments::get::GetAttachmentResponse;+use crate::api::email::attachments::get_document_id::GetAttachmentDocumentIDResponse;use crate::api::email::backfill::cancel::CancelBackfillParams;use crate::api::email::backfill::get::{GetActiveBackfillJobResponse, GetBackfillJobResponse};use crate::api::email::contacts::list::ListContactsResponse;@@ -36,6 +37,7 @@ use utoipa::OpenApi;paths(health::health_handler,email::attachments::get::handler,+ email::attachments::get_document_id::handler,email::backfill::cancel::handler,email::backfill::get::handler,email::backfill::get::active_handler,@@ -97,6 +99,7 @@ use utoipa::OpenApi;PreviewViewStandardLabel,// Attachment typesGetAttachmentResponse,+ GetAttachmentDocumentIDResponse,// Link typesListLinksResponse,Link,diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/process.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/process.rsindex cfe491dfe6..ecdb3ef677 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/process.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/process.rs@@ -62,7 +62,7 @@ pub async fn process_macro_id(let macro_id = macro_id.to_string();async move {- match processor.upload(&attachment).await {+ match processor.upload(link_id, &attachment).await {Ok(_) => {success_count.fetch_add(1, Ordering::Relaxed);println!("Successfully uploaded '{}' (index: {}) for {}", attachment.filename, index, macro_id);diff --git a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rsindex 51bbe870f3..f89caa1ddd 100644--- a/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs+++ b/rust/cloud-storage/email_service/src/bin/backfill_gmail_attachments/upload.rs@@ -5,6 +5,7 @@ use models_email::service::attachment::AttachmentUploadMetadata;use sha2::{Digest, Sha256};use sqlx::PgPool;use tracing::instrument;+use uuid::Uuid;/// A helper struct to manage clients and tokens required for processing.pub struct AttachmentProcessor {@@ -34,12 +35,18 @@ impl AttachmentProcessor {/// Orchestrates the full upload process for a single attachment.#[instrument(skip(self), fields(file_name = %attachment.filename, mime_type = %attachment.mime_type))]- pub async fn upload(&self, attachment: &AttachmentUploadMetadata) -> anyhow::Result<()> {- let exists = email_db_client::attachments::provider::document_email_record_exists(+ pub async fn upload(+ &self,+ link_id: Uuid,+ attachment: &AttachmentUploadMetadata,+ ) -> anyhow::Result<()> {+ let exists = email_db_client::attachments::provider::get_document_id_by_attachment_id(&self.db,+ link_id,attachment.attachment_db_id,)- .await?;+ .await?+ .is_some();if exists {println!("Attachment {} already exists in DSS, skipping",diff --git a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rsindex b70cfda2be..e22e3a89b5 100644--- a/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs+++ b/rust/cloud-storage/email_service/src/pubsub/backfill/backfill_attachment.rs@@ -1,5 +1,5 @@use crate::pubsub::context::PubSubContext;-use crate::pubsub::upload_attachment::upload_attachment;+use crate::util::upload_attachment::upload_attachment;use models_email::service::backfill::BackfillAttachmentPayload;use models_email::service::link;use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};@@ -16,24 +16,47 @@ pub async fn backfill_attachment(p: &BackfillAttachmentPayload,) -> Result<(), ProcessingError> {// Check if a document for this attachment already exists before uploading.- if attachment_document_exists(ctx, p.metadata.attachment_db_id).await? {+ if attachment_document_exists(ctx, link.id, p.metadata.attachment_db_id).await? {return Ok(());}- upload_attachment(ctx, access_token, link, &p.metadata).await+ upload_attachment(+ &ctx.redis_client,+ &ctx.gmail_client,+ &ctx.dss_client,+ access_token,+ link,+ &p.metadata,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::GmailApiFailed,+ source: e.context("Failed to fetch attachment data from Gmail"),+ })+ })?;++ Ok(())}/// Checks the database to see if a document has already been created for this attachment.async fn attachment_document_exists(ctx: &PubSubContext,+ link_id: Uuid,attachment_db_id: Uuid,) -> Result<bool, ProcessingError> {- email_db_client::attachments::provider::document_email_record_exists(&ctx.db, attachment_db_id)- .await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DatabaseQueryFailed,- source: e.context("Failed to query for document email record"),- })+ let document_id = email_db_client::attachments::provider::get_document_id_by_attachment_id(+ &ctx.db,+ link_id,+ attachment_db_id,+ )+ .await+ .map_err(|e| {+ ProcessingError::NonRetryable(DetailedError {+ reason: FailureReason::DatabaseQueryFailed,+ source: e.context("Failed to query for document email record"),})+ })?;++ Ok(document_id.is_some())}diff --git a/rust/cloud-storage/email_service/src/pubsub/mod.rs b/rust/cloud-storage/email_service/src/pubsub/mod.rsindex af080b678a..193a40550d 100644--- a/rust/cloud-storage/email_service/src/pubsub/mod.rs+++ b/rust/cloud-storage/email_service/src/pubsub/mod.rs@@ -3,6 +3,5 @@ pub(crate) mod context;pub(crate) mod refresh;pub(crate) mod scheduled;pub(crate) mod sfs_uploader;-pub(crate) mod upload_attachment;-mod util;+pub(crate) mod util;pub(crate) mod webhook;diff --git a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rsindex e3bd79a448..c26b353e7c 100644--- a/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs+++ b/rust/cloud-storage/email_service/src/pubsub/webhook/operations/upsert_message.rs@@ -1,8 +1,8 @@use crate::pubsub::context::PubSubContext;-use crate::pubsub::upload_attachment::upload_attachment;use crate::pubsub::util::{cg_refresh_email, check_gmail_rate_limit};use crate::pubsub::webhook::process;use crate::util::process_pre_insert::{process_message_pre_insert, process_threads_pre_insert};+use crate::util::upload_attachment::upload_attachment;use email_db_client::threads;use email_db_client::threads::get::get_outbound_threads_by_thread_ids;use email_utils::dedupe_emails;@@ -212,7 +212,16 @@ async fn handle_attachment_upload(for attachment in attachments {// keep processing if it fails, best effort- if let Err(e) = upload_attachment(ctx, gmail_access_token, link, &attachment).await {+ if let Err(e) = upload_attachment(+ &ctx.redis_client,+ &ctx.gmail_client,+ &ctx.dss_client,+ gmail_access_token,+ link,+ &attachment,+ )+ .await+ {tracing::error!("Failed to upload attachment to Macro: {e}");}}diff --git a/rust/cloud-storage/email_service/src/util/mod.rs b/rust/cloud-storage/email_service/src/util/mod.rsindex fafda97b34..5cb8f6e08c 100644--- a/rust/cloud-storage/email_service/src/util/mod.rs+++ b/rust/cloud-storage/email_service/src/util/mod.rs@@ -3,3 +3,4 @@ pub mod gmail;pub mod process_pre_insert;pub mod redis;pub mod sync_contacts;+pub mod upload_attachment;diff --git a/rust/cloud-storage/email_service/src/pubsub/upload_attachment.rs b/rust/cloud-storage/email_service/src/util/upload_attachment.rssimilarity index 60%rename from rust/cloud-storage/email_service/src/pubsub/upload_attachment.rsrename to rust/cloud-storage/email_service/src/util/upload_attachment.rsindex 1c142b8ccf..a62f1da88a 100644--- a/rust/cloud-storage/email_service/src/pubsub/upload_attachment.rs+++ b/rust/cloud-storage/email_service/src/util/upload_attachment.rs@@ -1,34 +1,38 @@-use crate::pubsub::context::PubSubContext;use crate::pubsub::util::check_gmail_rate_limit;+use crate::util::redis::RedisClient;use anyhow::{Context, anyhow};use base64::Engine;use base64::engine::general_purpose::STANDARD;+use document_storage_service_client::DocumentStorageServiceClient;+use gmail_client::GmailClient;use model::document::response::{CreateDocumentRequest, CreateDocumentResponse};use models_email::gmail::operations::GmailApiOperation;use models_email::service::attachment::AttachmentUploadMetadata;use models_email::service::link;-use models_email::service::pubsub::{DetailedError, FailureReason, ProcessingError};use sha2::{Digest, Sha256};/// Upload an email attachment to DSS as a document.-#[tracing::instrument(skip(ctx, access_token))]+#[tracing::instrument(skip(redis_client, gmail_client, dss_client, access_token), err)]pub async fn upload_attachment(- ctx: &PubSubContext,+ redis_client: &RedisClient,+ gmail_client: &GmailClient,+ dss_client: &DocumentStorageServiceClient,access_token: &str,link: &link::Link,p: &AttachmentUploadMetadata,-) -> Result<(), ProcessingError> {+) -> anyhow::Result<String> {// 1. Check rate limits before making a Gmail API call.check_gmail_rate_limit(- &ctx.redis_client,+ redis_client,link.id,GmailApiOperation::MessagesAttachmentsGet,true,)- .await?;+ .await+ .context("Rate limit check failed")?;// 2. Fetch the raw attachment data from Gmail.- let attachment_data = fetch_gmail_attachment_data(ctx, access_token, p).await?;+ let attachment_data = fetch_gmail_attachment_data(gmail_client, access_token, p).await?;// 3. Calculate hashes required for the upload process.let (hex_hash, base64_hash) = calculate_hashes(&attachment_data);@@ -38,33 +42,35 @@ pub async fn upload_attachment(// 5. Create the document record in DSS and get a presigned URL for the upload.let dss_response =- create_dss_document_record(ctx, link, p, &hex_hash, &file_name, &file_type).await?;+ create_dss_document_record(dss_client, link, p, &hex_hash, &file_name, &file_type).await?;// 6. Upload the attachment data to the presigned URL.- upload_data_to_presigned_url(dss_response, attachment_data, &base64_hash).await?;+ upload_data_to_presigned_url(&dss_response, attachment_data, &base64_hash).await?;- Ok(())+ // 7. Return document id to caller+ let document_id = dss_response+ .data+ .document_response+ .document_metadata+ .document_id;++ Ok(document_id)}/// Fetches the raw attachment data from the Gmail API.async fn fetch_gmail_attachment_data(- ctx: &PubSubContext,+ gmail_client: &GmailClient,access_token: &str,p: &AttachmentUploadMetadata,-) -> Result<Vec<u8>, ProcessingError> {- ctx.gmail_client+) -> anyhow::Result<Vec<u8>> {+ gmail_client.get_attachment_data(access_token,&p.email_provider_id,&p.provider_attachment_id,).await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::GmailApiFailed,- source: e.context("Failed to fetch attachment data from Gmail"),- })- })+ .context("Failed to fetch attachment data from Gmail")}/// Calculates the SHA256 hash of the attachment data in both hex and base64 formats.@@ -80,9 +86,7 @@ fn calculate_hashes(data: &[u8]) -> (String, String) {}/// Determines the file name (without extension) and file type (extension) from the payload.-fn determine_file_metadata(- p: &AttachmentUploadMetadata,-) -> Result<(String, String), ProcessingError> {+fn determine_file_metadata(p: &AttachmentUploadMetadata) -> anyhow::Result<(String, String)> {let file_name = p.filename.split('.')@@ -93,13 +97,10 @@ fn determine_file_metadata(let file_type = mime_guess::get_mime_extensions_str(&p.mime_type).and_then(|exts| exts.first().map(|s| s.to_string())).ok_or_else(|| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::AttachmentParsingFailed,- source: anyhow!(- "Failed to determine file extension from mime type: {}",- p.mime_type- ),- })+ anyhow!(+ "Failed to determine file extension from mime type: {}",+ p.mime_type+ )})?;Ok((file_name, file_type))@@ -108,13 +109,13 @@ fn determine_file_metadata(/// Creates a document record in the Document Storage Service (DSS) and returns the response,/// which includes the presigned URL for the upload.async fn create_dss_document_record(- ctx: &PubSubContext,+ dss_client: &DocumentStorageServiceClient,link: &link::Link,p: &AttachmentUploadMetadata,hex_hash: &str,file_name: &str,file_type: &str,-) -> Result<CreateDocumentResponse, ProcessingError> {+) -> anyhow::Result<CreateDocumentResponse> {let request = CreateDocumentRequest {id: None,sha: hex_hash.to_string(),@@ -130,61 +131,42 @@ async fn create_dss_document_record(email_attachment_id: Some(p.attachment_db_id),};- ctx.dss_client+ dss_client.create_document_internal(request, &link.macro_id).await- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DSSUploadFailed,- source: e.context("Failed to create document record in DSS"),- })- })+ .context("Failed to create document record in DSS")}/// Uploads the provided data to the presigned URL from the DSS response.async fn upload_data_to_presigned_url(- dss_response: CreateDocumentResponse,+ dss_response: &CreateDocumentResponse,attachment_data: Vec<u8>,base64_hash: &str,-) -> Result<(), ProcessingError> {+) -> anyhow::Result<()> {let presigned_url = dss_response.data.document_response.presigned_url- .context("DSS response did not include a presigned URL")- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DSSUploadFailed,- source: e,- })- })?;+ .as_ref()+ .context("DSS response did not include a presigned URL")?;let response = reqwest::Client::new().put(presigned_url)- .header("content-type", dss_response.data.content_type)+ .header("content-type", &dss_response.data.content_type).header("x-amz-checksum-sha256", base64_hash).body(attachment_data).send().await- .context("HTTP PUT request to presigned URL failed")- .map_err(|e| {- ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DSSUploadFailed,- source: e,- })- })?;+ .context("HTTP PUT request to presigned URL failed")?;if !response.status().is_success() {let status = response.status();let body = response.text().await.unwrap_or_default();- return Err(ProcessingError::NonRetryable(DetailedError {- reason: FailureReason::DSSUploadFailed,- source: anyhow!(- "Failed to upload attachment to presigned url: {} {}",- status,- body- ),- }));+ return Err(anyhow!(+ "Failed to upload attachment to presigned url: {} {}",+ status,+ body+ ));}Ok(())