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.

feat(email-service): Backfill sfs attachments script (#619)

Evan Hutnikd38c374861e5
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.toml
index 959ce69b4a..e5b22b80e3 100644
--- a/rust/cloud-storage/email_service/Cargo.toml
+++ b/rust/cloud-storage/email_service/Cargo.toml
@@ -21,6 +21,10 @@ path = "src/bin/backfill_gmail_attachments/backfill_gmail_attachments.rs"
name = "backfill_email_search"
path = "src/bin/backfill_search/backfill_search.rs"
+[[bin]]
+name = "backfill_sfs_attachments"
+path = "src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs"
+
[features]
attachment_upload = []
connection_gateway = []
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/README.md b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/README.md
new file mode 100644
index 0000000000..e987a92cb8
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/README.md
@@ -0,0 +1,18 @@
+# SFS Attachment Backfill Utility
+
+This binary is used to find and upload relevant email attachments for a given user account to SFS.
+It fetches attachment metadata from the local database,
+downloads the actual attachment data from Gmail, and uploads it to SFS.
+
+## Required Environment Variables:
+
+- `DATABASE_URL`: The connection string for the PostgreSQL database.
+- `SFS_URL`: The URL for the Static File Service.
+- `INTERNAL_AUTH_KEY`: The access token for authenticating with internal Macro services.
+- `MACRO_IDS`: The Macro IDs of the user accounts to backfill attachments for
+- `UPLOAD_CONCURRENCY`: Number of concurrent uploads to process (optional, defaults to 10).
+- `FUSIONAUTH_API_KEY`: The API key for authenticating with FusionAuth.
+- `FUSIONAUTH_BASE_URL`: The base URL for the FusionAuth service.
+- `FUSIONAUTH_IDENTITY_PROVIDER_ID`: The identity provider ID for FusionAuth.
+- `GMAIL_CLIENT_ID`: The client ID for Gmail OAuth.
+- `GMAIL_CLIENT_SECRET`: The client secret for Gmail OAuth.
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/auth.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/auth.rs
new file mode 100644
index 0000000000..55062cd5e4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/auth.rs
@@ -0,0 +1,74 @@
+use crate::config::Config;
+use anyhow::Context;
+
+/// Gets a fresh Gmail access token by:
+/// 1. Looking up the user in FusionAuth
+/// 2. Getting their identity provider link with refresh token
+/// 3. Using that refresh token to get a new Gmail access token
+pub async fn get_gmail_access_token(config: &Config, macro_id: &str) -> anyhow::Result<String> {
+ let client = reqwest::Client::builder().build()?;
+
+ // First request: Get user by email
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert("Authorization", config.fusionauth_api_key.parse()?);
+
+ let user_email = macro_id.strip_prefix("macro|").unwrap();
+
+ let url = format!(
+ "{}/api/user?email={}",
+ config.fusionauth_base_url, user_email
+ );
+ let request = client.request(reqwest::Method::GET, &url).headers(headers);
+
+ let response = request.send().await?;
+ let user_response: serde_json::Value = response.json().await?;
+
+ // Extract user.id from the first response
+ let user_id = user_response["user"]["id"]
+ .as_str()
+ .context("Failed to extract user.id from first response")?;
+
+ // Second request: Get identity provider links using the user.id
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert("Authorization", config.fusionauth_api_key.parse()?);
+
+ let url = format!(
+ "{}/api/identity-provider/link?identityProviderId={}&userId={}",
+ config.fusionauth_base_url, config.fusionauth_identity_provider_id, user_id
+ );
+ let request = client.request(reqwest::Method::GET, &url).headers(headers);
+
+ let response = request.send().await?;
+ let identity_response: serde_json::Value = response.json().await?;
+
+ // Extract identityProviderLinks[0].token from the second response
+ let refresh_token = identity_response["identityProviderLinks"][0]["token"]
+ .as_str()
+ .context("Failed to extract identityProviderLinks[0].token from second response")?;
+
+ // Third request: Use the extracted token as refresh_token
+ let mut headers = reqwest::header::HeaderMap::new();
+ headers.insert("Content-Type", "application/json".parse()?);
+
+ let data = serde_json::json!({
+ "client_id": config.gmail_client_id,
+ "client_secret": config.gmail_client_secret,
+ "refresh_token": refresh_token,
+ "grant_type": "refresh_token"
+ });
+
+ let request = client
+ .request(reqwest::Method::POST, "https://oauth2.googleapis.com/token")
+ .headers(headers)
+ .json(&data);
+
+ let response = request.send().await?;
+ let token_response: serde_json::Value = response.json().await?;
+
+ // Extract the access token from the response
+ let access_token = token_response["access_token"]
+ .as_str()
+ .context("Failed to extract access_token from Gmail OAuth response")?;
+
+ Ok(access_token.to_string())
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs
new file mode 100644
index 0000000000..51f28c38a4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs
@@ -0,0 +1,81 @@
+//! # Attachment Backfill Utility
+//!
+//! This binary is used to find and upload image/video email attachments for a given user account.
+//! It fetches attachment metadata from the local database, downloads the actual attachment data
+//! from Gmail, and uploads it to SFS.
+//!
+//! ## Required Environment Variables:
+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.
+//! - `SFS_URL`: The URL for the Static File Service.
+//! - `INTERNAL_AUTH_KEY`: An access token for authenticating with internal Macro services.
+//! - `MACRO_IDS`: The Macro IDs of the user accounts to backfill attachments for
+//! - `UPLOAD_CONCURRENCY`: Number of concurrent uploads to process (optional, defaults to 10).
+//! - `FUSIONAUTH_API_KEY`: The API key for authenticating with FusionAuth.
+//! - `FUSIONAUTH_BASE_URL`: The base URL for the FusionAuth service.
+//! - `FUSIONAUTH_IDENTITY_PROVIDER_ID`: The identity provider ID for FusionAuth.
+//! - `GMAIL_CLIENT_ID`: The client ID for Gmail OAuth.
+//! - `GMAIL_CLIENT_SECRET`: The client secret for Gmail OAuth.
+
+mod auth;
+mod config;
+mod database;
+mod process;
+mod upload;
+
+use anyhow::Context;
+use macro_entrypoint::MacroEntrypoint;
+use sqlx_core::types::chrono;
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ println!("Loading configuration...");
+ MacroEntrypoint::default().init();
+ let config = config::Config::from_env().context("Failed to load configuration")?;
+
+ println!("Connecting to the database...");
+ let db_pool = database::create_db_pool(&config.database_url, config.upload_concurrency as u32)
+ .await
+ .context("Failed to create database pool")?;
+
+ let sfs_client = static_file_service_client::StaticFileServiceClient::new(
+ config.internal_auth_key.clone(),
+ config.sfs_url.clone(),
+ );
+
+ let gmail_client = gmail_client::GmailClient::new("unused".to_string());
+
+ let macro_ids: Vec<String> = config
+ .macro_ids
+ .split(',')
+ .map(|id| id.trim().to_string())
+ .collect();
+
+ println!("Processing {} macro IDs: {:?}", macro_ids.len(), macro_ids);
+
+ for (index, macro_id) in macro_ids.iter().enumerate() {
+ println!(
+ "\n=== Processing macro ID {} ({}/{}) at {} ===",
+ macro_id,
+ index + 1,
+ macro_ids.len(),
+ chrono::Local::now().format("%Y-%m-%d %H:%M:%S")
+ );
+
+ match process::process_macro_id(&config, &db_pool, &sfs_client, &gmail_client, macro_id)
+ .await
+ {
+ Ok((success_count, total_attachments)) => {
+ println!(
+ "Completed processing for {}. Successfully uploaded {} out of {} attachments.",
+ macro_id, success_count, total_attachments
+ );
+ }
+ Err(e) => {
+ println!("Failed to process macro ID {}: {:?}", macro_id, e);
+ // Continue with next macro ID instead of failing completely
+ }
+ }
+ }
+
+ println!("\n=== All macro IDs processed ===");
+ Ok(())
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs
new file mode 100644
index 0000000000..c37e6265fa
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/config.rs
@@ -0,0 +1,45 @@
+use anyhow::Context;
+
+/// Holds all configuration loaded from environment variables.
+pub struct Config {
+ pub sfs_url: String,
+ pub internal_auth_key: String,
+ pub macro_ids: String,
+ pub database_url: String,
+ pub upload_concurrency: usize,
+ pub fusionauth_api_key: String,
+ pub fusionauth_base_url: String,
+ pub fusionauth_identity_provider_id: String,
+ pub gmail_client_id: String,
+ pub gmail_client_secret: String,
+}
+
+impl Config {
+ /// Creates a new `Config` instance by reading from environment variables.
+ /// Returns an error if any required variable is not set.
+ pub fn from_env() -> anyhow::Result<Self> {
+ let upload_concurrency =
+ std::env::var("UPLOAD_CONCURRENCY").context("UPLOAD_CONCURRENCY not set")?;
+ let upload_concurrency = upload_concurrency
+ .parse::<usize>()
+ .context("UPLOAD_CONCURRENCY is not a number")?;
+
+ Ok(Self {
+ sfs_url: std::env::var("SFS_URL").context("SFS_URL not set")?,
+ internal_auth_key: std::env::var("INTERNAL_AUTH_KEY")
+ .context("INTERNAL_AUTH_KEY not set")?,
+ macro_ids: std::env::var("MACRO_IDS").context("MACRO_IDS not set")?, // Changed
+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,
+ upload_concurrency,
+ fusionauth_api_key: std::env::var("FUSIONAUTH_API_KEY")
+ .context("FUSIONAUTH_API_KEY not set")?,
+ fusionauth_base_url: std::env::var("FUSIONAUTH_BASE_URL")
+ .context("FUSIONAUTH_BASE_URL not set")?,
+ fusionauth_identity_provider_id: std::env::var("FUSIONAUTH_IDENTITY_PROVIDER_ID")
+ .context("FUSIONAUTH_IDENTITY_PROVIDER_ID not set")?,
+ gmail_client_id: std::env::var("GMAIL_CLIENT_ID").context("GMAIL_CLIENT_ID not set")?,
+ gmail_client_secret: std::env::var("GMAIL_CLIENT_SECRET")
+ .context("GMAIL_CLIENT_SECRET not set")?,
+ })
+ }
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/database.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/database.rs
new file mode 100644
index 0000000000..f39fde61b0
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/database.rs
@@ -0,0 +1,75 @@
+use anyhow::Context;
+use email_db_client::attachments::provider::upload_filters::ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA;
+use models_email::service::attachment::AttachmentUploadMetadata;
+use sqlx::PgPool;
+use sqlx::postgres::PgPoolOptions;
+use sqlx_core::row::Row;
+
+/// Creates and returns a new PostgreSQL connection pool.
+pub async fn create_db_pool(database_url: &str, min_connections: u32) -> anyhow::Result<PgPool> {
+ PgPoolOptions::new()
+ .min_connections(min_connections)
+ .max_connections(60)
+ .connect(database_url)
+ .await
+ .context("Could not connect to db")
+}
+
+/// fetch the user's image and video attachments, ordered from oldest to newest
+pub async fn fetch_sfs_attachments(
+ db: &sqlx::Pool<sqlx::Postgres>,
+ macro_id: &str,
+) -> anyhow::Result<Vec<AttachmentUploadMetadata>> {
+ let query = format!(
+ r#"
+ WITH link AS (
+ SELECT id
+ FROM public.email_links
+ WHERE macro_id = $1
+ LIMIT 1
+ )
+ 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,
+ m.id as message_db_id,
+ m.thread_id as thread_db_id,
+ from_contact.email_address as sender_email,
+ m.subject as subject
+ FROM public.email_attachments a
+ JOIN public.email_messages m ON a.message_id = m.id
+ JOIN public.email_contacts from_contact ON m.from_contact_id = from_contact.id
+ JOIN link ON m.link_id = link.id
+ LEFT JOIN public.email_attachments_sfs eas ON eas.attachment_id = a.id
+ WHERE
+ -- attachment mime type filters injected below
+ ({})
+ AND eas.attachment_id IS NULL
+ ORDER BY m.internal_date_ts asc
+ "#,
+ ATTACHMENT_MIME_TYPE_FILTERS_WITH_MEDIA
+ );
+
+ let rows = sqlx::query(&query).bind(macro_id).fetch_all(db).await?;
+
+ let attachments = rows
+ .into_iter()
+ .map(|row| AttachmentUploadMetadata {
+ attachment_db_id: row.get("attachment_db_id"),
+ email_provider_id: row.get("email_provider_id"),
+ provider_attachment_id: row.get("provider_attachment_id"),
+ filename: row.get("filename"),
+ mime_type: row.get("mime_type"),
+ internal_date_ts: row.get("internal_date_ts"),
+ message_db_id: row.get("message_db_id"),
+ thread_db_id: row.get("thread_db_id"),
+ sender_email: row.get("sender_email"),
+ subject: row.get("subject"),
+ })
+ .collect();
+
+ Ok(attachments)
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/process.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/process.rs
new file mode 100644
index 0000000000..6e7b91c7f4
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/process.rs
@@ -0,0 +1,115 @@
+use crate::upload::AttachmentProcessor;
+use crate::{auth, config, database, upload};
+use anyhow::Context;
+use futures::{StreamExt, stream};
+use std::sync::Arc;
+use std::sync::atomic::{AtomicUsize, Ordering};
+
+/// Process attachments for a single macro ID
+pub async fn process_macro_id(
+ config: &config::Config,
+ db_pool: &sqlx::PgPool,
+ sfs_client: &static_file_service_client::StaticFileServiceClient,
+ gmail_client: &gmail_client::GmailClient,
+ macro_id: &str,
+) -> anyhow::Result<(usize, usize)> {
+ // Fetch all relevant attachment metadata from the database.
+ println!(
+ "Fetching unique attachment metadata from database for {}...",
+ macro_id
+ );
+ let attachments = database::fetch_sfs_attachments(db_pool, macro_id)
+ .await
+ .context("Failed to fetch attachment metadata")?;
+ println!(
+ "Found {} unique attachments to process for {}.",
+ attachments.len(),
+ macro_id
+ );
+
+ if attachments.is_empty() {
+ return Ok((0, 0));
+ }
+
+ // Get fresh Gmail access token for this macro ID
+ let gmail_access_token = auth::get_gmail_access_token(config, macro_id).await?;
+ println!("Successfully obtained Gmail access token for {}", macro_id);
+
+ // Process and upload each attachment.
+ let processor = Arc::new(upload::AttachmentProcessor::new(
+ db_pool.clone(),
+ sfs_client.clone(),
+ gmail_client.clone(),
+ gmail_access_token,
+ ));
+
+ let success_count = Arc::new(AtomicUsize::new(0));
+ let total_attachments = attachments.len();
+
+ println!("Starting concurrent upload process for {}...", macro_id);
+
+ stream::iter(attachments.into_iter().enumerate())
+ .for_each_concurrent(config.upload_concurrency, |(index, attachment)| {
+ let processor: Arc<AttachmentProcessor> = Arc::clone(&processor);
+ let success_count = Arc::clone(&success_count);
+ let macro_id = macro_id.to_string();
+
+ async move {
+ match processor.upload(&attachment).await {
+ Ok(_) => {
+ success_count.fetch_add(1, Ordering::Relaxed);
+ println!("Successfully uploaded '{}' (index: {}) for {}", attachment.filename.unwrap_or("N/A".to_string()), index, macro_id);
+ }
+ Err(e) => {
+ let err_str = format!("{e:?}");
+
+ if err_str.contains("404") {
+ println!(
+ "Attachment upload got 404; skipping and continuing. filename: {}, provider_attachment_id: {}, provider_message_id: {}, index: {}, macro_id: {}, error: {:?}",
+ attachment.filename.clone().unwrap_or("N/A".to_string()),
+ attachment.provider_attachment_id,
+ attachment.email_provider_id,
+ index,
+ macro_id,
+ e
+ );
+ } else if err_str.contains("500") {
+ println!(
+ "Attachment upload got 500; skipping and continuing. filename: {}, provider_attachment_id: {}, provider_message_id: {}, index: {}, macro_id: {}, error: {:?}",
+ attachment.filename.clone().unwrap_or("N/A".to_string()),
+ attachment.provider_attachment_id,
+ attachment.email_provider_id,
+ index,
+ macro_id,
+ e
+ );
+ } else if err_str.contains("400") {
+ println!(
+ "Attachment upload got 400; skipping and continuing. filename: {}, provider_attachment_id: {}, provider_message_id: {}, index: {}, macro_id: {}, error: {:?}",
+ attachment.filename.clone().unwrap_or("N/A".to_string()),
+ attachment.provider_attachment_id,
+ attachment.email_provider_id,
+ index,
+ macro_id,
+ e
+ );
+ } else {
+ panic!(
+ "Failed to upload attachment - filename: {}, provider_attachment_id: {}, provider_message_id: {}, index: {}, macro_id: {}, error: {:?}",
+ attachment.filename.unwrap_or("N/A".to_string()),
+ attachment.provider_attachment_id,
+ attachment.email_provider_id,
+ index,
+ macro_id,
+ e
+ );
+ }
+ }
+ }
+ }
+ })
+ .await;
+
+ let final_success_count = success_count.load(Ordering::SeqCst);
+ Ok((final_success_count, total_attachments))
+}
diff --git a/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/upload.rs b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/upload.rs
new file mode 100644
index 0000000000..f907380d87
--- /dev/null
+++ b/rust/cloud-storage/email_service/src/bin/backfill_sfs_attachments/upload.rs
@@ -0,0 +1,131 @@
+use anyhow::Context;
+use models_email::service::attachment::{AttachmentSfs, AttachmentUploadMetadata};
+use sqlx::PgPool;
+use static_file_service_client::put_file::PutFileResponse;
+use tracing::instrument;
+use uuid::Uuid;
+
+/// A helper struct to manage clients and tokens required for processing.
+pub struct AttachmentProcessor {
+ db: PgPool,
+ sfs_client: static_file_service_client::StaticFileServiceClient,
+ gmail_client: gmail_client::GmailClient,
+ gmail_access_token: String,
+}
+
+impl AttachmentProcessor {
+ pub fn new(
+ db: PgPool,
+ sfs_client: static_file_service_client::StaticFileServiceClient,
+ gmail_client: gmail_client::GmailClient,
+ gmail_access_token: String,
+ ) -> Self {
+ Self {
+ db,
+ sfs_client,
+ gmail_client,
+ gmail_access_token,
+ }
+ }
+
+ async fn download_attachment_bytes(
+ &self,
+ attachment: &AttachmentUploadMetadata,
+ ) -> anyhow::Result<bytes::Bytes> {
+ let attachment_data = self
+ .gmail_client
+ .get_attachment_data(
+ &self.gmail_access_token,
+ &attachment.email_provider_id,
+ &attachment.provider_attachment_id,
+ )
+ .await
+ .context("Failed to get attachment data from Gmail")?;
+
+ println!(
+ "Successfully downloaded attachment data for {} ({} bytes)",
+ attachment.filename.clone().unwrap_or("N/A".to_string()),
+ attachment_data.len()
+ );
+
+ Ok(bytes::Bytes::from(attachment_data))
+ }
+
+ // using retries because sfs intermittently fails by closing the connection
+ async fn upload_to_sfs_with_retry(
+ &self,
+ bytes: bytes::Bytes,
+ mime_type: String,
+ ) -> anyhow::Result<PutFileResponse> {
+ let mut last_err: Option<anyhow::Error> = None;
+
+ for attempt in 1usize..=5 {
+ let res = self
+ .sfs_client
+ .put_file_with_bytes("a", bytes.clone(), mime_type.clone())
+ .await;
+
+ match res {
+ Ok(ok) => return Ok(ok),
+ Err(e) => {
+ println!(
+ "SFS upload failed (attempt {}/5). Will{} retry. Error: {:?}",
+ attempt,
+ if attempt < 5 { "" } else { " not" },
+ e
+ );
+
+ let err = anyhow::anyhow!("{e:?}").context(format!(
+ "Failed to upload attachment to SFS (attempt {attempt}/5)"
+ ));
+ last_err = Some(err);
+
+ if attempt < 5 {
+ // exponential backoff: 200ms, 400ms, 800ms, 1600ms
+ let backoff_ms =
+ 200u64.saturating_mul(2u64.saturating_pow((attempt - 1) as u32));
+ tokio::time::sleep(std::time::Duration::from_millis(backoff_ms)).await;
+ }
+ }
+ }
+ }
+
+ Err(last_err.unwrap_or_else(|| anyhow::anyhow!("Failed to upload attachment to SFS")))
+ }
+
+ async fn persist_sfs_metadata(
+ &self,
+ attachment: &AttachmentUploadMetadata,
+ sfs_id_str: &str,
+ ) -> anyhow::Result<()> {
+ let attachment_sfs_id = macro_uuid::generate_uuid_v7();
+ let sfs_id = Uuid::parse_str(sfs_id_str).context("Failed to parse SFS ID as UUID")?;
+
+ email_db_client::attachments::sfs::insert_attachment_sfs(
+ &self.db,
+ &AttachmentSfs {
+ id: attachment_sfs_id,
+ attachment_id: Some(attachment.attachment_db_id),
+ sfs_id,
+ },
+ )
+ .await
+ .context("Failed to insert attachment SFS metadata")?;
+
+ Ok(())
+ }
+
+ /// 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 bytes = self.download_attachment_bytes(attachment).await?;
+
+ let sfs_response = self
+ .upload_to_sfs_with_retry(bytes, attachment.mime_type.clone())
+ .await?;
+
+ self.persist_sfs_metadata(attachment, &sfs_response.id)
+ .await?;
+ Ok(())
+ }
+}