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
tool(email): Reverse sfs mappings (#1909)
Evan Hutnikb5d0332bcee8
diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex cfd017b34a..047f8a521f 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -41,6 +41,10 @@ path = "src/bin/find_unused_sfs_ids/find_unused_sfs_ids.rs"name = "cleanup_unused_sfs"path = "src/bin/cleanup_unused_sfs/cleanup_unused_sfs.rs"+[[bin]]+name = "reverse_sfs_mappings"+path = "src/bin/reverse_sfs_mappings/reverse_sfs_mappings.rs"+[[bin]]name = "email_service_openapi"path = "src/openapi.rs"diff --git a/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rsnew file mode 100644index 0000000000..1126eae73a--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/config.rs@@ -0,0 +1,47 @@+//! Configuration for the reverse_sfs_mappings binary.++use anyhow::Context;++/// Holds all configuration loaded from environment variables.+pub struct Config {+ /// Database connection URL.+ pub database_url: String,+ /// Optional comma-separated list of link_ids to filter by.+ pub link_ids: Option<Vec<uuid::Uuid>>,+ /// Batch size for processing messages.+ pub batch_size: i64,+ /// Starting offset for pagination (useful for pause/resume).+ pub offset: i64,+}++impl Config {+ /// Creates a new `Config` instance by reading from environment variables.+ pub fn from_env() -> anyhow::Result<Self> {+ let link_ids = std::env::var("LINK_IDS")+ .ok()+ .map(|s| {+ s.split(',')+ .map(|id| id.trim().parse::<uuid::Uuid>())+ .collect::<Result<Vec<_>, _>>()+ })+ .transpose()+ .context("LINK_IDS contains invalid UUIDs")?;++ let batch_size = std::env::var("BATCH_SIZE")+ .unwrap_or_else(|_| "10".to_string())+ .parse::<i64>()+ .context("BATCH_SIZE is not a valid number")?;++ let offset = std::env::var("OFFSET")+ .unwrap_or_else(|_| "0".to_string())+ .parse::<i64>()+ .context("OFFSET is not a valid number")?;++ Ok(Self {+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,+ link_ids,+ batch_size,+ offset,+ })+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/process.rs b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/process.rsnew file mode 100644index 0000000000..0b2da7c169--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/process.rs@@ -0,0 +1,242 @@+//! Processing logic for reversing SFS mappings in email message HTML bodies.++use std::future::Future;+use std::time::Duration;++use anyhow::Context;+use regex::Regex;+use sqlx::{FromRow, PgPool};+use uuid::Uuid;++const QUERY_TIMEOUT: Duration = Duration::from_secs(5);+const MAX_RETRIES: usize = 10;++/// Runs an async closure with a timeout, retrying up to MAX_RETRIES times.+async fn retry_with_timeout<F, Fut, T>(label: &str, f: F) -> anyhow::Result<T>+where+ F: Fn() -> Fut,+ Fut: Future<Output = anyhow::Result<T>>,+{+ for attempt in 1..=MAX_RETRIES {+ match tokio::time::timeout(QUERY_TIMEOUT, f()).await {+ Ok(Ok(result)) => return Ok(result),+ Ok(Err(e)) => {+ println!(+ " [RETRY] {} failed on attempt {}/{}: {:?}",+ label, attempt, MAX_RETRIES, e+ );+ if attempt == MAX_RETRIES {+ return Err(e)+ .context(format!("{} failed after {} attempts", label, MAX_RETRIES));+ }+ }+ Err(_) => {+ println!(+ " [RETRY] {} timed out on attempt {}/{} ({}s limit)",+ label,+ attempt,+ MAX_RETRIES,+ QUERY_TIMEOUT.as_secs()+ );+ if attempt == MAX_RETRIES {+ anyhow::bail!("{} timed out after {} attempts", label, MAX_RETRIES);+ }+ }+ }+ }+ unreachable!()+}++/// A message row with its id and HTML body.+#[derive(FromRow)]+pub struct MessageRow {+ pub id: Uuid,+ pub body_html_sanitized: Option<String>,+}++/// Fetches a batch of email messages using OFFSET/LIMIT pagination.+/// No server-side filtering — HTML parsing is done in the binary.+/// Retries with a 5s timeout per attempt.+pub async fn fetch_messages_batch(+ db: &PgPool,+ link_ids: &Option<Vec<Uuid>>,+ offset: i64,+ limit: i64,+) -> anyhow::Result<Vec<MessageRow>> {+ retry_with_timeout("fetch_messages_batch", || async {+ let rows = if let Some(link_ids) = link_ids {+ sqlx::query_as::<_, MessageRow>(+ "SELECT id, body_html_sanitized+ FROM public.email_messages+ WHERE link_id = ANY($1)+ AND body_html_sanitized IS NOT NULL+ ORDER BY id+ OFFSET $2+ LIMIT $3",+ )+ .bind(link_ids)+ .bind(offset)+ .bind(limit)+ .fetch_all(db)+ .await+ .context("Failed to fetch messages batch")?+ } else {+ sqlx::query_as::<_, MessageRow>(+ "SELECT id, body_html_sanitized+ FROM public.email_messages+ WHERE body_html_sanitized IS NOT NULL+ ORDER BY id+ OFFSET $1+ LIMIT $2",+ )+ .bind(offset)+ .bind(limit)+ .fetch_all(db)+ .await+ .context("Failed to fetch messages batch")?+ };+ Ok(rows)+ })+ .await+}++/// Prints debug info about the link_ids and message counts to help diagnose issues.+pub async fn print_debug_info(db: &PgPool, link_ids: &Option<Vec<Uuid>>) -> anyhow::Result<()> {+ if let Some(link_ids) = link_ids {+ let existing_count: i64 =+ sqlx::query_scalar("SELECT COUNT(*) FROM public.email_links WHERE id = ANY($1)")+ .bind(link_ids)+ .fetch_one(db)+ .await+ .context("Failed to count email_links")?;+ println!(+ "[DEBUG] email_links matching provided link_ids: {}",+ existing_count+ );++ let total_messages: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM public.email_messages WHERE link_id = ANY($1)",+ )+ .bind(link_ids)+ .fetch_one(db)+ .await+ .context("Failed to count messages")?;+ println!(+ "[DEBUG] Total messages for these link_ids: {}",+ total_messages+ );++ let with_html: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM public.email_messages WHERE link_id = ANY($1) AND body_html_sanitized IS NOT NULL",+ )+ .bind(link_ids)+ .fetch_one(db)+ .await+ .context("Failed to count messages with html")?;+ println!(+ "[DEBUG] Messages with non-null body_html_sanitized: {}",+ with_html+ );++ let with_sfs: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM public.email_messages WHERE link_id = ANY($1) AND body_html_sanitized LIKE '%static-file-service%'",+ )+ .bind(link_ids)+ .fetch_one(db)+ .await+ .context("Failed to count messages with sfs")?;+ println!(+ "[DEBUG] Messages containing 'static-file-service': {}",+ with_sfs+ );+ } else {+ let total_messages: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM public.email_messages")+ .fetch_one(db)+ .await+ .context("Failed to count messages")?;+ println!("[DEBUG] Total messages: {}", total_messages);++ let with_html: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM public.email_messages WHERE body_html_sanitized IS NOT NULL",+ )+ .fetch_one(db)+ .await+ .context("Failed to count messages with html")?;+ println!(+ "[DEBUG] Messages with non-null body_html_sanitized: {}",+ with_html+ );+ }++ println!();+ Ok(())+}++/// Extracts all URLs containing "static-file-service" from an HTML string.+pub fn extract_sfs_urls(html: &str) -> Vec<String> {+ let re =+ Regex::new(r#"https?://[^\s"'<>]*static-file-service[^\s"'<>]*"#).expect("Invalid regex");+ re.find_iter(html).map(|m| m.as_str().to_string()).collect()+}++/// Mapping row from email_sfs_mappings.+#[derive(FromRow)]+pub struct SfsMapping {+ pub source: String,+ pub destination: String,+}++/// Looks up original source URLs for multiple SFS destination URLs in a single query.+/// Returns a vec of (destination, source) pairs for found mappings.+/// Retries with a 5s timeout per attempt.+pub async fn lookup_source_urls_bulk(+ db: &PgPool,+ destination_urls: &[String],+) -> anyhow::Result<Vec<SfsMapping>> {+ if destination_urls.is_empty() {+ return Ok(vec![]);+ }++ retry_with_timeout("lookup_source_urls_bulk", || async {+ let rows = sqlx::query_as::<_, SfsMapping>(+ "SELECT source, destination+ FROM public.email_sfs_mappings+ WHERE destination = ANY($1)",+ )+ .bind(destination_urls)+ .fetch_all(db)+ .await+ .context("Failed to bulk lookup source URLs")?;+ Ok(rows)+ })+ .await+}++/// Bulk updates body_html_sanitized for multiple messages in a single query.+/// Uses unnest to join arrays of ids and html values.+/// Retries with a 5s timeout per attempt.+pub async fn bulk_update_message_html(+ db: &PgPool,+ ids: &[Uuid],+ htmls: &[String],+) -> anyhow::Result<u64> {+ if ids.is_empty() {+ return Ok(0);+ }++ retry_with_timeout("bulk_update_message_html", || async {+ let result = sqlx::query(+ "UPDATE public.email_messages AS m+ SET body_html_sanitized = v.new_html+ FROM unnest($1::uuid[], $2::text[]) AS v(id, new_html)+ WHERE m.id = v.id",+ )+ .bind(ids)+ .bind(htmls)+ .execute(db)+ .await+ .context("Failed to bulk update message HTML")?;+ Ok(result.rows_affected())+ })+ .await+}diff --git a/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/reverse_sfs_mappings.rs b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/reverse_sfs_mappings.rsnew file mode 100644index 0000000000..cb271ff0e1--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/reverse_sfs_mappings/reverse_sfs_mappings.rs@@ -0,0 +1,249 @@+//! # Reverse SFS Mappings Utility+//!+//! This binary reverses static-file-service URL mappings in email message HTML bodies.+//! It scans `email_messages.body_html_sanitized` for URLs containing "static-file-service",+//! looks up the original source URL in `email_sfs_mappings`, and replaces the SFS URL+//! with the original source URL.+//!+//! ## Required Environment Variables:+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.+//!+//! ## Optional Environment Variables:+//! - `LINK_IDS`: Comma-separated list of link_id UUIDs to filter messages by.+//! - `BATCH_SIZE`: Number of messages to process per batch (default: 10).+//! - `OFFSET`: Starting offset for pagination, useful for pause/resume (default: 0).++mod config;+mod process;++use std::time::Instant;++use anyhow::Context;+use macro_entrypoint::MacroEntrypoint;+use sqlx::postgres::PgPoolOptions;++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ println!("=== Reverse SFS Mappings ===\n");++ // Initialize and load configuration+ MacroEntrypoint::default().init();+ let config = config::Config::from_env().context("Failed to load configuration")?;++ println!("Configuration:");+ println!(" Batch size: {}", config.batch_size);+ println!(" Starting offset: {}", config.offset);+ if let Some(ref link_ids) = config.link_ids {+ println!(" Filtering by {} link_id(s):", link_ids.len());+ for id in link_ids {+ println!(" - {}", id);+ }+ } else {+ println!(" Processing ALL messages (no link_id filter)");+ }+ println!();++ // Connect to database+ println!("Connecting to the database...");+ let db_pool = PgPoolOptions::new()+ .min_connections(2)+ .max_connections(10)+ .connect(&config.database_url)+ .await+ .context("Failed to connect to database")?;+ println!("Connected.\n");++ // Debug: print counts to diagnose empty results+ process::print_debug_info(&db_pool, &config.link_ids).await?;++ // Process messages in batches+ let start = Instant::now();+ let mut total_messages_scanned: usize = 0;+ let mut total_messages_updated: usize = 0;+ let mut total_urls_reversed: usize = 0;+ let mut total_urls_not_found: usize = 0;+ let mut current_offset = config.offset;++ // Fetch the first batch+ println!(+ "Fetching batch at offset {} (limit {})...",+ current_offset, config.batch_size+ );+ let mut current_batch = process::fetch_messages_batch(+ &db_pool,+ &config.link_ids,+ current_offset,+ config.batch_size,+ )+ .await?;++ loop {+ if current_batch.is_empty() {+ println!("No more messages to process.");+ break;+ }++ let batch_len = current_batch.len();+ let is_last_batch = (batch_len as i64) < config.batch_size;+ let next_offset = current_offset + batch_len as i64;++ total_messages_scanned += batch_len;+ println!(+ "Processing {} messages at offset {} (total scanned so far: {})",+ batch_len, current_offset, total_messages_scanned+ );++ // Start prefetching the next batch immediately (unless this is the last batch)+ let next_batch_fut = if !is_last_batch {+ println!(" Prefetching next batch at offset {} ...", next_offset);+ Some(process::fetch_messages_batch(+ &db_pool,+ &config.link_ids,+ next_offset,+ config.batch_size,+ ))+ } else {+ None+ };++ // Process the current batch while next batch is being fetched+ // Collect all SFS URLs across all messages in this batch+ let mut all_sfs_urls: Vec<String> = Vec::new();+ let mut messages_with_urls: Vec<(usize, &process::MessageRow, Vec<String>)> = Vec::new();++ for (i, msg) in current_batch.iter().enumerate() {+ let html = match &msg.body_html_sanitized {+ Some(h) => h,+ None => continue,+ };++ let sfs_urls = process::extract_sfs_urls(html);+ if sfs_urls.is_empty() {+ continue;+ }++ println!(" Message {}: found {} SFS URL(s)", msg.id, sfs_urls.len());++ all_sfs_urls.extend(sfs_urls.clone());+ messages_with_urls.push((i, msg, sfs_urls));+ }++ // Bulk lookup all SFS URLs for this batch in one query+ let mappings = process::lookup_source_urls_bulk(&db_pool, &all_sfs_urls).await?;+ if !all_sfs_urls.is_empty() {+ println!(+ " Looked up {} SFS URLs, found {} mappings",+ all_sfs_urls.len(),+ mappings.len()+ );+ }++ // Apply string replacements concurrently across messages using spawn_blocking+ let mapping_map_owned: std::collections::HashMap<String, String> = mappings+ .iter()+ .map(|m| (m.destination.clone(), m.source.clone()))+ .collect();++ // Collect owned data for the blocking task+ let replace_inputs: Vec<(uuid::Uuid, String, Vec<String>)> = messages_with_urls+ .into_iter()+ .map(|(_i, msg, sfs_urls)| (msg.id, msg.body_html_sanitized.clone().unwrap(), sfs_urls))+ .collect();++ let replace_results = tokio::task::spawn_blocking(move || {+ replace_inputs+ .into_iter()+ .filter_map(|(id, html, sfs_urls)| {+ let mut new_html = html;+ let mut urls_reversed = 0usize;+ let mut urls_not_found = 0usize;++ for sfs_url in &sfs_urls {+ if let Some(source_url) = mapping_map_owned.get(sfs_url.as_str()) {+ println!(+ " Reversing [{}]: {} -> {}",+ id,+ truncate_url(sfs_url, 80),+ truncate_url(source_url, 80)+ );+ new_html = new_html.replace(sfs_url, source_url);+ urls_reversed += 1;+ } else {+ println!(+ " WARNING [{}]: No mapping found for: {}",+ id,+ truncate_url(sfs_url, 100)+ );+ urls_not_found += 1;+ }+ }++ if urls_reversed > 0 {+ Some((id, new_html, urls_reversed, urls_not_found))+ } else {+ None+ }+ })+ .collect::<Vec<_>>()+ })+ .await+ .context("String replacement task panicked")?;++ // Bulk update all modified messages in one query+ if !replace_results.is_empty() {+ let mut update_ids: Vec<uuid::Uuid> = Vec::with_capacity(replace_results.len());+ let mut update_htmls: Vec<String> = Vec::with_capacity(replace_results.len());++ for (id, new_html, urls_reversed, urls_not_found) in &replace_results {+ update_ids.push(*id);+ update_htmls.push(new_html.clone());+ total_urls_reversed += urls_reversed;+ total_urls_not_found += urls_not_found;+ }++ let rows_affected =+ process::bulk_update_message_html(&db_pool, &update_ids, &update_htmls).await?;+ total_messages_updated += rows_affected as usize;+ println!(+ " Bulk updated {} messages ({} rows affected)",+ replace_results.len(),+ rows_affected+ );+ }++ current_offset = next_offset;++ if is_last_batch {+ break;+ }++ // Await the prefetched next batch+ current_batch = next_batch_fut.unwrap().await?;++ println!(+ " Batch done. Next offset: {}. Elapsed: {:.2?}\n",+ current_offset,+ start.elapsed()+ );+ }++ let duration = start.elapsed();+ println!("\n=== Summary ===");+ println!("Total messages scanned: {}", total_messages_scanned);+ println!("Total messages updated: {}", total_messages_updated);+ println!("Total URLs reversed: {}", total_urls_reversed);+ println!("Total URLs with no mapping: {}", total_urls_not_found);+ println!("Final offset: {}", current_offset);+ println!("Total time: {:.2?}", duration);++ Ok(())+}++/// Truncates a URL for display purposes.+fn truncate_url(url: &str, max_len: usize) -> String {+ if url.len() <= max_len {+ url.to_string()+ } else {+ format!("{}...", &url[..max_len])+ }+}