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): Binaries for cleaning up unused sfs images (#1146)
Evan Hutnik4f10d868a465
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a1658579b8..25931a0885 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -3195,6 +3195,7 @@ dependencies = ["models_permissions","models_properties","redis",+ "regex","reqwest","s3_client","schemars",@@ -8579,6 +8580,8 @@ dependencies = ["serde","serde_dynamo","serde_json",+ "strum_macros",+ "thiserror 2.0.17","tokio","tower 0.5.2","tower-http",diff --git a/rust/cloud-storage/email_service/Cargo.toml b/rust/cloud-storage/email_service/Cargo.tomlindex 1ba71598f4..6d699295ec 100644--- a/rust/cloud-storage/email_service/Cargo.toml+++ b/rust/cloud-storage/email_service/Cargo.toml@@ -29,6 +29,18 @@ path = "src/bin/backfill_sfs_attachments/backfill_sfs_attachments.rs"name = "pubsub_workers"path = "src/bin/pubsub_workers/pubsub_workers.rs"+[[bin]]+name = "find_used_sfs_ids"+path = "src/bin/find_used_sfs_ids/find_used_sfs_ids.rs"++[[bin]]+name = "find_unused_sfs_ids"+path = "src/bin/find_unused_sfs_ids/find_unused_sfs_ids.rs"++[[bin]]+name = "cleanup_unused_sfs"+path = "src/bin/cleanup_unused_sfs/cleanup_unused_sfs.rs"+[[bin]]name = "email_service_openapi"path = "src/openapi.rs"@@ -102,6 +114,7 @@ redis = { workspace = true, features = ["cluster-async","tokio-native-tls-comp",] }+regex = { workspace = true }reqwest = { workspace = true, features = ["stream"] }s3_client = { path = "../s3_client" }schemars = { workspace = true }diff --git a/rust/cloud-storage/email_service/src/bin/.gitignore b/rust/cloud-storage/email_service/src/bin/.gitignorenew file mode 100644index 0000000000..e1fb01de7d--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/.gitignore@@ -0,0 +1,2 @@+**/*.processed+**/*.txtdiff --git a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/README.md b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/README.mdnew file mode 100644index 0000000000..dfd316fca5--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/README.md@@ -0,0 +1,250 @@+# Cleanup Unused SFS Files++This binary deletes unused SFS files and their corresponding database mappings using the SFS bulk delete API. It streams UUIDs from a file, batches them, and sends bulk delete requests to efficiently remove files and their mappings from the `email_sfs_mappings` table.++## Purpose++Part of a three-step workflow to identify and clean up unused SFS files:+1. `find_used_sfs_ids` → Finds SFS UUIDs referenced in email message bodies+2. `find_unused_sfs_ids` → Compares all mappings against used UUIDs to find orphans+3. **This tool** → Deletes the unused files and mappings++## How It Works++1. Counts UUIDs in the input file (streaming, no loading into memory)+2. Streams UUIDs from the file and groups them into batches+3. For each batch (default: 50 files per batch):+ - Sends bulk delete request to SFS API (`POST /file/bulk-delete`)+ - SFS endpoint deletes files from S3 and removes its own DynamoDB metadata+ - For each successful SFS deletion, removes mapping from PostgreSQL `email_sfs_mappings` table+ - Tracks success/failure for each individual file+4. Processes batches concurrently (default: 5 concurrent requests)+5. Falls back to individual deletions if bulk request fails+6. Logs progress every 100 files+7. Provides detailed summary of deletions at the end++**Key Improvements Over Individual Deletes**:+- **50x fewer API calls**: Deletes 50 files in 1 request vs 50 requests+- **Faster execution**: Concurrent batch processing reduces total time+- **Better error handling**: Per-file results even in bulk operations+- **Automatic fallback**: Falls back to individual deletes if bulk fails++**Memory Efficient**: UUIDs are streamed from file and processed in configurable-size batches. Only the current batch is in memory.++## Environment Variables++### Required+- `DATABASE_URL`: PostgreSQL connection string for the MacroDB database+- `SFS_URL`: The URL for the Static File Service (e.g., `https://static-file-service.macro.com`)+- `INTERNAL_AUTH_KEY`: Internal auth key for SFS authentication+- `DESTINATION_URL_PREFIX`: URL prefix for reconstructing destination URLs+ - Example: `https://static-file-service.macro.com/file/`+ - Used to build full destination URL: `{prefix}{uuid}`++### Optional+- `UNUSED_UUIDS_FILE`: Path to file containing unused UUIDs (default: `unused_sfs_uuids.txt`)+ - Generated by `find_unused_sfs_ids`+- `BULK_BATCH_SIZE`: Number of files to include in each bulk delete request (default: `50`)+ - Maximum is 100 (enforced by SFS bulk delete endpoint)+ - Larger batches = fewer API calls but less granular error handling+- `BULK_CONCURRENCY`: Number of concurrent bulk delete requests (default: `5`)+ - Increase for faster deletions, decrease if overwhelming SFS or database++## Usage++### Basic Usage+```bash+cargo run --bin cleanup_unused_sfs+```++### With Custom Configuration+```bash+export DATABASE_URL="postgresql://user:pass@localhost/macrodb"+export SFS_URL="https://static-file-service-dev.macro.com"+export INTERNAL_AUTH_KEY="your-auth-key-here"+export DESTINATION_URL_PREFIX="https://static-file-service-dev.macro.com/file/"+export BULK_BATCH_SIZE="100"+export BULK_CONCURRENCY="10"+cargo run --bin cleanup_unused_sfs+```++### From Release Binary+```bash+./cleanup_unused_sfs+```++### Using .env File+Create a `.env` file in the binary's directory:+```env+SFS_URL="https://static-file-service.macro.com"+INTERNAL_AUTH_KEY="2a46d3ed0abe6d45118e0eb03f61e7bc"+DESTINATION_URL_PREFIX="https://static-file-service.macro.com/file/"+BULK_BATCH_SIZE="50"+BULK_CONCURRENCY="5"+```++Then run:+```bash+cargo run --bin cleanup_unused_sfs+```++## Input File++### `unused_sfs_uuids.txt` (required)+Must be generated first by running `find_unused_sfs_ids`. Contains one UUID per line.++Example:+```+e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b+f2a3b4c5-d6e7-4f8a-9b0c-1d2e3f4a5b6c+a3b4c5d6-e7f8-4a9b-0c1d-2e3f4a5b6c7d+```++## Deletion Behavior++For each UUID, the tool performs two operations:++### 1. Delete from SFS+- Calls SFS bulk delete API: `POST /file/bulk-delete` (batches of 50 by default)+- SFS endpoint deletes files from S3 and removes its own DynamoDB metadata+- **Success**: File was deleted from S3+- **Already Deleted** (404): File doesn't exist (counted separately, not an error)+- **Error**: Network issue, auth failure, or other error+- Falls back to individual `DELETE /file/{uuid}` calls if bulk request fails++### 2. Delete from PostgreSQL Database+- Only attempted for files that successfully deleted from SFS+- Executes: `DELETE FROM email_sfs_mappings WHERE destination = '{prefix}{uuid}'`+- **Success**: Mapping row deleted+- **Error**: Database connection issue or permission error++The database cleanup only happens after successful SFS deletion to maintain consistency.++## Safety Features++- **Dry run not available**: This tool permanently deletes files+- **No confirmation prompt**: Assumes you've verified the unused UUIDs+- **Continues on errors**: Individual failures don't stop the entire batch+- **Progress tracking**: Can be interrupted and resumed (just run again with same file)+- **Concurrent limits**: `BULK_CONCURRENCY` setting prevents overwhelming services++## Performance++- **Streaming architecture**: Reads UUIDs from file in 1000-item batches+- **Concurrent deletions**: Configured via `BULK_CONCURRENCY` (default: 5)+- **Memory usage**: Constant, regardless of total file count+- **Typical speed**: 100-500 deletions per second (depends on SFS/DB latency)++Typical performance at different bulk concurrency levels:+- BULK_CONCURRENCY 5 (default): ~250 deletions/sec, conservative+- BULK_CONCURRENCY 10: ~500 deletions/sec, recommended+- BULK_CONCURRENCY 20: ~1000 deletions/sec, aggressive (may overwhelm services)++Note: With bulk operations, each request deletes up to 50 files (BULK_BATCH_SIZE), so performance scales much better than individual deletions.++## Example Run++```+=== Cleanup Unused SFS Files ===++Loading configuration...+Configuration:+ SFS URL: https://static-file-service.macro.com+ Unused UUIDs file: unused_sfs_uuids.txt+ Destination URL prefix: https://static-file-service.macro.com/file/+ Concurrency: 20++Counting UUIDs in unused_sfs_uuids.txt...+Found 221720 UUIDs to delete in 1.2s++Connecting to the database...+Deleting 221720 files with concurrency 20...++Progress: 100/221720 processed (SFS: 87 deleted, 13 already deleted, 0 failed)+Progress: 200/221720 processed (SFS: 175 deleted, 25 already deleted, 0 failed)+Progress: 300/221720 processed (SFS: 264 deleted, 34 already deleted, 2 failed)+...+Progress: 221700/221720 processed (SFS: 194523 deleted, 27145 already deleted, 32 failed)+Progress: 221720/221720 processed (SFS: 194541 deleted, 27147 already deleted, 32 failed)++=== Summary ===+Total UUIDs processed: 221720+SFS deletions: 194541 deleted, 27147 already deleted, 32 failed+DB deletions: 221688 succeeded, 32 failed+Total time: 18m 32s+```++## Exit Behavior++- **Exit code 0**: Always, even if some deletions fail+- **Individual failures**: Logged to stderr but don't stop execution+- **Final summary**: Shows success/failure counts for review++## Next Steps++After running this tool:+1. Review the summary statistics+2. Check if any files failed to delete (investigate errors in output)+3. Optionally re-run to attempt failed deletions again+4. Archive or delete the `unused_sfs_uuids.txt` file++## Troubleshooting++### "File does not exist: unused_sfs_uuids.txt"+- Run `find_unused_sfs_ids` first to generate this file++### "No UUIDs to delete"+- The input file is empty+- Run `find_unused_sfs_ids` to generate unused UUIDs+- Or verify the file path is correct++### High SFS failure rate+- Check `SFS_URL` is correct and service is reachable+- Verify `INTERNAL_AUTH_KEY` is valid+- Check network connectivity+- Reduce `BULK_CONCURRENCY` to avoid rate limiting++### High DB failure rate+- Check `DATABASE_URL` is correct and database is reachable+- Verify user has DELETE permissions on `email_sfs_mappings` table+- Check `DESTINATION_URL_PREFIX` matches format in database+- Reduce `BULK_CONCURRENCY` to avoid connection pool exhaustion++### "Already deleted" count is high+- Normal behavior if tool has been run before on same file+- Files may have been manually deleted+- SFS may have already cleaned up some files++### Process is too slow+- Increase `BULK_CONCURRENCY` (try 10, 15, or 20)+- Check network latency to SFS+- Verify database connection pool is adequate++### Process is too fast / overwhelming services+- Decrease `BULK_CONCURRENCY` (try 2 or 1)+- Monitor SFS and database server load++### Want to test without deleting+- **Not recommended**: This tool has no dry-run mode+- Alternative: Manually test with a small file (1-10 UUIDs)+- Copy a few UUIDs to a test file and run with that file++## Safety Checklist++Before running in production:++- [ ] Verified `unused_sfs_uuids.txt` contains only truly unused files+- [ ] Checked percentage of unused files is reasonable (in `find_unused_sfs_ids` output)+- [ ] Confirmed `SFS_URL` and `DESTINATION_URL_PREFIX` match your environment+- [ ] Tested with small batch first (optional but recommended)+- [ ] Have database backup (for peace of mind)+- [ ] Set appropriate `BULK_CONCURRENCY` for your infrastructure+- [ ] Ready to monitor the deletion progress++## Recovery++If you accidentally delete files that shouldn't have been deleted:++1. **Database mappings**: Can be restored from database backup+2. **SFS files**: If you have S3 versioning enabled, files may be recoverable+3. **Prevention**: Next time, spot-check unused UUIDs before running cleanupdiff --git a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/cleanup_unused_sfs.rs b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/cleanup_unused_sfs.rsnew file mode 100644index 0000000000..3f72794d7f--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/cleanup_unused_sfs.rs@@ -0,0 +1,346 @@+//! # Cleanup Unused SFS Files Utility+//!+//! This binary deletes unused SFS files and their corresponding database mappings.+//! It reads UUIDs from a file, deletes each file from SFS, then removes the mapping+//! from the email_sfs_mappings table.+//!+//! ## Required Environment Variables:+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.+//! - `SFS_URL`: The URL for the Static File Service.+//! - `INTERNAL_AUTH_KEY`: Internal auth key for SFS authentication.+//! - `DESTINATION_URL_PREFIX`: URL prefix for reconstructing destination URLs+//! (e.g., "https://static-file-service-dev.macro.com/file/").+//!+//! ## Optional Environment Variables:+//! - `UNUSED_UUIDS_FILE`: Path to the file containing unused UUIDs (default: "unused_sfs_uuids.txt").+//! - `CONCURRENCY`: Number of concurrent delete operations (default: 10).++mod config;+mod process;++use std::path::Path;+use std::sync::Arc;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::time::Instant;++use anyhow::Context;+use futures::stream::{StreamExt as FuturesStreamExt, TryStreamExt};+use macro_entrypoint::MacroEntrypoint;+use sqlx::PgPool;+use sqlx::postgres::PgPoolOptions;++/// Statistics for tracking deletion operations.+struct DeletionStats {+ sfs_deleted: Arc<AtomicUsize>,+ sfs_already_deleted: Arc<AtomicUsize>,+ sfs_failed: Arc<AtomicUsize>,+ db_success: Arc<AtomicUsize>,+ db_failed: Arc<AtomicUsize>,+ processed: Arc<AtomicUsize>,+}++/// Context for deletion operations.+struct DeletionContext<'a> {+ uuids_file: &'a str,+ sfs_client: &'a static_file_service_client::StaticFileServiceClient,+ db_pool: &'a PgPool,+ destination_prefix: &'a str,+ bulk_batch_size: usize,+ bulk_concurrency: usize,+ stats: &'a DeletionStats,+ total: usize,+}++impl DeletionStats {+ fn new() -> Self {+ Self {+ sfs_deleted: Arc::new(AtomicUsize::new(0)),+ sfs_already_deleted: Arc::new(AtomicUsize::new(0)),+ sfs_failed: Arc::new(AtomicUsize::new(0)),+ db_success: Arc::new(AtomicUsize::new(0)),+ db_failed: Arc::new(AtomicUsize::new(0)),+ processed: Arc::new(AtomicUsize::new(0)),+ }+ }++ fn print_summary(&self, total: usize, duration: std::time::Duration) {+ println!("\n=== Summary ===");+ println!("Total UUIDs processed: {}", total);+ println!(+ "SFS deletions: {} deleted, {} already deleted, {} failed",+ self.sfs_deleted.load(Ordering::Relaxed),+ self.sfs_already_deleted.load(Ordering::Relaxed),+ self.sfs_failed.load(Ordering::Relaxed)+ );+ println!(+ "DB deletions: {} succeeded, {} failed",+ self.db_success.load(Ordering::Relaxed),+ self.db_failed.load(Ordering::Relaxed)+ );+ println!("Total time: {:.2?}", duration);+ }+}++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ println!("=== Cleanup Unused SFS Files ===\n");++ // Initialize and load configuration+ MacroEntrypoint::default().init();+ let config = load_and_print_config()?;++ // Count UUIDs to delete+ let total = count_uuids_to_delete(&config.unused_uuids_file)?;+ if total == 0 {+ println!("No UUIDs to delete. Exiting.");+ return Ok(());+ }++ // Setup database and SFS client+ let db_pool = connect_to_database(&config).await?;+ let sfs_client = create_sfs_client(&config);++ // Execute deletions+ let stats = DeletionStats::new();+ let delete_start = Instant::now();++ let ctx = DeletionContext {+ uuids_file: &config.unused_uuids_file,+ sfs_client: &sfs_client,+ db_pool: &db_pool,+ destination_prefix: &config.destination_url_prefix,+ bulk_batch_size: config.bulk_batch_size,+ bulk_concurrency: config.bulk_concurrency,+ stats: &stats,+ total,+ };++ execute_deletions(ctx).await?;++ // Print summary+ stats.print_summary(total, delete_start.elapsed());++ Ok(())+}++/// Loads and prints configuration.+fn load_and_print_config() -> anyhow::Result<config::Config> {+ println!("Loading configuration...");+ let config = config::Config::from_env().context("Failed to load configuration")?;++ println!("Configuration:");+ println!(" SFS URL: {}", config.sfs_url);+ println!(" Unused UUIDs file: {}", config.unused_uuids_file);+ println!(+ " Destination URL prefix: {}",+ config.destination_url_prefix+ );+ println!(" Bulk batch size: {}", config.bulk_batch_size);+ println!(" Bulk concurrency: {}\n", config.bulk_concurrency);++ Ok(config)+}++/// Counts UUIDs in the input file.+fn count_uuids_to_delete(file_path: &str) -> anyhow::Result<usize> {+ println!("Counting UUIDs in {}...", file_path);+ let count_start = Instant::now();+ let total = process::count_uuids_in_file(Path::new(file_path))?;+ println!(+ "Found {} UUIDs to delete in {:.2?}\n",+ total,+ count_start.elapsed()+ );+ Ok(total)+}++/// Connects to the database.+async fn connect_to_database(config: &config::Config) -> anyhow::Result<PgPool> {+ println!("Connecting to the database...");+ PgPoolOptions::new()+ .min_connections(5)+ .max_connections(config.bulk_concurrency as u32 + 5)+ .connect(&config.database_url)+ .await+ .context("Failed to connect to database")+}++/// Creates the SFS client.+fn create_sfs_client(+ config: &config::Config,+) -> static_file_service_client::StaticFileServiceClient {+ static_file_service_client::StaticFileServiceClient::new(+ config.internal_auth_key.clone(),+ config.sfs_url.clone(),+ )+}++/// Executes all deletions using bulk delete endpoint.+async fn execute_deletions(ctx: DeletionContext<'_>) -> anyhow::Result<()> {+ println!(+ "Deleting {} files with bulk batch size {} and concurrency {}...\n",+ ctx.total, ctx.bulk_batch_size, ctx.bulk_concurrency+ );++ // Collect UUIDs into batches+ let uuid_stream = process::stream_uuids_from_file(Path::new(ctx.uuids_file))?;++ // Batch the UUIDs and process them concurrently+ uuid_stream+ .try_chunks(ctx.bulk_batch_size)+ .map(|result| async {+ match result {+ Ok(uuids) if !uuids.is_empty() => {+ process_bulk_batch(+ uuids,+ ctx.sfs_client,+ ctx.db_pool,+ ctx.destination_prefix,+ ctx.stats,+ ctx.total,+ )+ .await;+ }+ Ok(_) => {} // Empty batch+ Err(e) => {+ eprintln!("Error reading UUIDs from file: {:?}", e.1);+ }+ }+ })+ .buffer_unordered(ctx.bulk_concurrency)+ .collect::<Vec<_>>()+ .await;++ Ok(())+}++/// Processes a bulk batch of UUIDs.+async fn process_bulk_batch(+ uuids: Vec<String>,+ sfs_client: &static_file_service_client::StaticFileServiceClient,+ db_pool: &PgPool,+ destination_prefix: &str,+ stats: &DeletionStats,+ total: usize,+) {+ let batch_size = uuids.len();++ // Call bulk delete endpoint+ match sfs_client.bulk_delete_files(uuids.clone()).await {+ Ok(response) => {+ // Process SFS results+ for result in &response.results {+ if result.success {+ stats.sfs_deleted.fetch_add(1, Ordering::Relaxed);+ } else if let Some(error) = &result.error {+ if error.contains("not found") || error.contains("404") {+ stats.sfs_already_deleted.fetch_add(1, Ordering::Relaxed);+ } else {+ eprintln!("Failed to delete {} from SFS: {}", result.file_id, error);+ stats.sfs_failed.fetch_add(1, Ordering::Relaxed);+ }+ } else {+ stats.sfs_failed.fetch_add(1, Ordering::Relaxed);+ }+ }++ // Delete from PostgreSQL database for files that succeeded in SFS+ // Note: The SFS bulk delete endpoint handles its own DynamoDB metadata,+ // but we need to clean up the email_sfs_mappings table in PostgreSQL+ let successful_destination_urls: Vec<String> = response+ .results+ .iter()+ .filter(|r| r.success)+ .map(|r| format!("{}{}", destination_prefix, r.file_id))+ .collect();++ if !successful_destination_urls.is_empty() {+ match process::bulk_delete_mappings_from_db(db_pool, &successful_destination_urls)+ .await+ {+ Ok(deleted_count) => {+ stats+ .db_success+ .fetch_add(deleted_count as usize, Ordering::Relaxed);+ // If some rows weren't found, count them as failures+ let expected_count = successful_destination_urls.len();+ if deleted_count < expected_count as u64 {+ let failed_count = expected_count - deleted_count as usize;+ stats.db_failed.fetch_add(failed_count, Ordering::Relaxed);+ }+ }+ Err(e) => {+ eprintln!("Failed to bulk delete mappings: {:?}", e);+ stats+ .db_failed+ .fetch_add(successful_destination_urls.len(), Ordering::Relaxed);+ }+ }+ }+ }+ Err(e) => {+ tracing::error!(error = ?e, "bulk delete request failed");+ eprintln!("Bulk delete request failed: {:?}", e);++ // Fall back to individual deletions for this batch+ for uuid in uuids {+ delete_single_file_fallback(uuid, sfs_client, db_pool, destination_prefix, stats)+ .await;+ }+ }+ }++ // Update progress+ let count = stats.processed.fetch_add(batch_size, Ordering::Relaxed) + batch_size;+ if count.is_multiple_of(100) || count >= total {+ print_progress(count, total, stats);+ }+}++/// Fallback to single file deletion if bulk delete fails.+async fn delete_single_file_fallback(+ uuid: String,+ sfs_client: &static_file_service_client::StaticFileServiceClient,+ db_pool: &PgPool,+ destination_prefix: &str,+ stats: &DeletionStats,+) {+ // Delete from SFS using the old single delete endpoint+ match process::delete_from_sfs(sfs_client, &uuid).await {+ process::SfsDeleteResult::Deleted => {+ stats.sfs_deleted.fetch_add(1, Ordering::Relaxed);+ }+ process::SfsDeleteResult::AlreadyDeleted => {+ stats.sfs_already_deleted.fetch_add(1, Ordering::Relaxed);+ }+ process::SfsDeleteResult::Error(e) => {+ eprintln!("Failed to delete {} from SFS: {:?}", uuid, e);+ stats.sfs_failed.fetch_add(1, Ordering::Relaxed);+ return; // Don't try to delete from DB if SFS failed+ }+ }++ // Delete from database+ let destination_url = format!("{}{}", destination_prefix, uuid);+ match process::delete_mapping_from_db(db_pool, &destination_url).await {+ Ok(_) => {+ stats.db_success.fetch_add(1, Ordering::Relaxed);+ }+ Err(e) => {+ eprintln!("Failed to delete mapping for {}: {:?}", uuid, e);+ stats.db_failed.fetch_add(1, Ordering::Relaxed);+ }+ }+}++/// Prints progress update.+fn print_progress(count: usize, total: usize, stats: &DeletionStats) {+ println!(+ "Progress: {}/{} processed (SFS: {} deleted, {} already deleted, {} failed)",+ count,+ total,+ stats.sfs_deleted.load(Ordering::Relaxed),+ stats.sfs_already_deleted.load(Ordering::Relaxed),+ stats.sfs_failed.load(Ordering::Relaxed)+ );+}diff --git a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rsnew file mode 100644index 0000000000..0a4ebb48bb--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/config.rs@@ -0,0 +1,50 @@+//! Configuration for the cleanup_unused_sfs binary.++use anyhow::Context;++/// Holds all configuration loaded from environment variables.+pub struct Config {+ /// Database connection URL.+ pub database_url: String,+ /// URL for the Static File Service.+ pub sfs_url: String,+ /// Internal auth key for SFS.+ pub internal_auth_key: String,+ /// Path to the file containing unused UUIDs.+ pub unused_uuids_file: String,+ /// URL prefix to reconstruct full destination URLs (e.g., "https://static-file-service-dev.macro.com/file/").+ pub destination_url_prefix: String,+ /// Number of files to include in each bulk delete request.+ pub bulk_batch_size: usize,+ /// Number of concurrent bulk delete requests.+ pub bulk_concurrency: usize,+}++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 bulk_batch_size = std::env::var("BULK_BATCH_SIZE")+ .unwrap_or_else(|_| "50".to_string())+ .parse::<usize>()+ .context("BULK_BATCH_SIZE is not a valid number")?;++ let bulk_concurrency = std::env::var("BULK_CONCURRENCY")+ .unwrap_or_else(|_| "5".to_string())+ .parse::<usize>()+ .context("BULK_CONCURRENCY is not a valid number")?;++ Ok(Self {+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,+ 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")?,+ unused_uuids_file: std::env::var("UNUSED_UUIDS_FILE")+ .unwrap_or_else(|_| "unused_sfs_uuids.txt".to_string()),+ destination_url_prefix: std::env::var("DESTINATION_URL_PREFIX")+ .context("DESTINATION_URL_PREFIX not set")?,+ bulk_batch_size,+ bulk_concurrency,+ })+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/process.rs b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/process.rsnew file mode 100644index 0000000000..9d9aa79a73--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/cleanup_unused_sfs/process.rs@@ -0,0 +1,130 @@+//! Processing logic for cleaning up unused SFS files.++use std::fs::File;+use std::io::{BufRead, BufReader};+use std::path::Path;++use anyhow::Context;+use futures::stream::{self, Stream};+use sqlx::PgPool;+use tokio::sync::mpsc;++/// Counts non-empty lines in a file without loading all into memory.+pub fn count_uuids_in_file(path: &Path) -> anyhow::Result<usize> {+ if !path.exists() {+ anyhow::bail!("File does not exist: {}", path.display());+ }++ let file =+ File::open(path).with_context(|| format!("Failed to open file: {}", path.display()))?;+ let reader = BufReader::new(file);++ let mut count = 0;+ for line in reader.lines() {+ let line = line.context("Failed to read line")?;+ if !line.trim().is_empty() {+ count += 1;+ }+ }++ Ok(count)+}++/// Creates an async stream of UUIDs from a file.+/// Returns a stream that yields UUIDs one at a time.+pub fn stream_uuids_from_file(+ path: &Path,+) -> anyhow::Result<impl Stream<Item = Result<String, anyhow::Error>>> {+ if !path.exists() {+ anyhow::bail!("File does not exist: {}", path.display());+ }++ let file =+ File::open(path).with_context(|| format!("Failed to open file: {}", path.display()))?;++ let (tx, rx) = mpsc::channel(1000);++ // Spawn a task to read the file and send UUIDs through the channel+ tokio::spawn(async move {+ let reader = BufReader::new(file);+ for line in reader.lines() {+ match line {+ Ok(line) => {+ let trimmed = line.trim();+ if !trimmed.is_empty() && tx.send(Ok(trimmed.to_string())).await.is_err() {+ // Receiver dropped, stop reading+ break;+ }+ }+ Err(e) => {+ let _ = tx.send(Err(anyhow::Error::from(e))).await;+ break;+ }+ }+ }+ });++ // Convert the receiver to a stream using futures::stream::unfold+ Ok(stream::unfold(rx, |mut rx| async move {+ rx.recv().await.map(|item| (item, rx))+ }))+}++/// Result of an SFS delete operation.+pub enum SfsDeleteResult {+ /// File was successfully deleted.+ Deleted,+ /// File was already deleted (404).+ AlreadyDeleted,+ /// An error occurred.+ Error(anyhow::Error),+}++/// Deletes a file from SFS.+pub async fn delete_from_sfs(+ sfs_client: &static_file_service_client::StaticFileServiceClient,+ uuid: &str,+) -> SfsDeleteResult {+ match sfs_client.delete_file(uuid).await {+ Ok(_status) => SfsDeleteResult::Deleted,+ Err(e) => {+ // Check if it's a 404 - the file is already gone+ let err_str = format!("{:?}", e);+ if err_str.contains("404") {+ SfsDeleteResult::AlreadyDeleted+ } else {+ SfsDeleteResult::Error(e)+ }+ }+ }+}++/// Deletes the mapping row from email_sfs_mappings by destination URL.+pub async fn delete_mapping_from_db(db: &PgPool, destination_url: &str) -> anyhow::Result<bool> {+ let result = sqlx::query("DELETE FROM public.email_sfs_mappings WHERE destination = $1")+ .bind(destination_url)+ .execute(db)+ .await+ .context("Failed to delete mapping from database")?;++ Ok(result.rows_affected() > 0)+}++/// Deletes multiple mapping rows from email_sfs_mappings by destination URLs.+/// Returns the number of rows deleted.+pub async fn bulk_delete_mappings_from_db(+ db: &PgPool,+ destination_urls: &[String],+) -> anyhow::Result<u64> {+ if destination_urls.is_empty() {+ return Ok(0);+ }++ let result = sqlx::query("DELETE FROM public.email_sfs_mappings WHERE destination = ANY($1)")+ .bind(destination_urls)+ .execute(db)+ .await+ .context("Failed to bulk delete mappings from database")?;++ Ok(result.rows_affected())+}diff --git a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/README.md b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/README.mdnew file mode 100644index 0000000000..47b5f27ddc--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/README.md@@ -0,0 +1,219 @@+# Find Unused SFS IDs++This binary compares UUIDs from the `email_sfs_mappings` table against a file of used UUIDs to identify which SFS mappings are no longer referenced in email message bodies. It streams data for memory efficiency and can handle millions of records.++## Purpose++Part of a three-step workflow to identify and clean up unused SFS files:+1. `find_used_sfs_ids` → Finds SFS UUIDs referenced in email message bodies+2. **This tool** → Compares all mappings against used UUIDs to find orphans+3. `cleanup_unused_sfs` → Deletes the unused files and mappings++## How It Works++1. Loads the used UUIDs file into a HashSet for O(1) lookups+2. Streams SFS mapping destinations from database (if not cached)+3. Extracts UUIDs from destination URLs+4. Writes mapping UUIDs to `all_sfs_mapping_uuids.txt` (cached for future runs)+5. Streams through all mapping UUIDs and compares against used set+6. Writes unused UUIDs directly to output file++**Memory Efficient**: Only the used UUIDs HashSet is kept in memory. All other operations stream data line-by-line.++## Environment Variables++### Required+- `DATABASE_URL`: PostgreSQL connection string for the MacroDB database++### Optional+- `USED_UUIDS_FILE`: Path to file containing used UUIDs (default: `used_sfs_uuids.txt`)+ - Generated by `find_used_sfs_ids`+- `ALL_MAPPINGS_FILE`: Path to store all mapping UUIDs (default: `all_sfs_mapping_uuids.txt`)+ - Cached file to avoid re-querying database+- `UNUSED_UUIDS_FILE`: Path to store unused UUIDs (default: `unused_sfs_uuids.txt`)+- `EXTRACTION_CONCURRENCY`: Concurrency for UUID extraction (default: `100`)+ - Not currently used due to streaming refactor++## Usage++### Basic Usage+```bash+cargo run --bin find_unused_sfs_ids+```++### With Custom Configuration+```bash+export DATABASE_URL="postgresql://user:pass@localhost/macrodb"+export USED_UUIDS_FILE="custom_used_uuids.txt"+export UNUSED_UUIDS_FILE="custom_unused_uuids.txt"+cargo run --bin find_unused_sfs_ids+```++### From Release Binary+```bash+./find_unused_sfs_ids+```++## Input File++### `used_sfs_uuids.txt` (required)+Must be generated first by running `find_used_sfs_ids`. Contains one UUID per line.++Example:+```+bc698c53-5a61-45f9-ac88-212e22cf8a33+d4e7f1a2-9b3c-4d2e-8f5a-1a2b3c4d5e6f+```++## Output Files++### `unused_sfs_uuids.txt` (default)+Contains one UUID per line for each SFS mapping that is NOT referenced in any email message.++Example:+```+e1f2a3b4-c5d6-4e7f-8a9b-0c1d2e3f4a5b+f2a3b4c5-d6e7-4f8a-9b0c-1d2e3f4a5b6c+```++### `all_sfs_mapping_uuids.txt` (default)+Cached list of all UUIDs from `email_sfs_mappings` table. If this file exists on subsequent runs, the database query is skipped entirely (much faster).++To force a fresh database query, delete this file.++## Caching Behavior++The tool uses aggressive caching to speed up repeated runs:++1. **First run**: Queries database for all mappings (~slow)+ - Streams mappings from `email_sfs_mappings` table+ - Writes UUIDs to `all_sfs_mapping_uuids.txt`++2. **Subsequent runs**: Uses cached file (~instant)+ - Counts lines in `all_sfs_mapping_uuids.txt` (streaming)+ - Skips database connection entirely++To refresh the cache (e.g., after new email mappings are created):+```bash+rm all_sfs_mapping_uuids.txt+cargo run --bin find_unused_sfs_ids+```++## Performance++- **Streaming architecture**: Never loads all mappings or UUIDs into memory+- **Memory usage**: Only used UUIDs HashSet in memory (~1MB per 100k UUIDs)+- **Processing speed**: ~100k-500k UUIDs per second on comparison+- **Database streaming**: Fetches mapping destinations one-by-one via SQL cursor++Typical performance:+- Loading used UUIDs: ~0.1-1s for 10k-100k UUIDs+- Streaming from database (first run): ~10-60s for 1M mappings+- Counting cached file (subsequent runs): ~1-5s for 1M mappings+- Finding unused UUIDs: ~2-10s for 1M mappings++Can handle tens of millions of records without running out of memory.++## Example Run++### First Run (No Cache)+```+=== Find Unused SFS IDs ===++Loading configuration...+Configuration:+ Used UUIDs file: used_sfs_uuids.txt+ All mappings file: all_sfs_mapping_uuids.txt+ Unused UUIDs file: unused_sfs_uuids.txt+ Extraction concurrency: 100++Loading used UUIDs from used_sfs_uuids.txt...+Loaded 12847 used UUIDs in 145ms++Connecting to the database...+Streaming mapping destinations from email_sfs_mappings to all_sfs_mapping_uuids.txt...+ Streamed 10000 UUIDs so far...+ Streamed 20000 UUIDs so far...+ ...+Streamed and wrote 234567 UUIDs in 45.2s++Streaming through all_sfs_mapping_uuids.txt to find unused UUIDs...+ Processed 100000 UUIDs, found 87234 unused so far...+ Processed 200000 UUIDs, found 187654 unused so far...+Found 221720 unused UUIDs in 3.8s++=== Summary ===+Total mappings: 234567+Total mapping UUIDs: 234567+Total used UUIDs (from file): 12847+Total unused UUIDs: 221720+Percentage unused: 94.52%++Results saved to: unused_sfs_uuids.txt+```++### Subsequent Run (With Cache)+```+=== Find Unused SFS IDs ===++Loading configuration...+Configuration:+ Used UUIDs file: used_sfs_uuids.txt+ All mappings file: all_sfs_mapping_uuids.txt+ Unused UUIDs file: unused_sfs_uuids.txt+ Extraction concurrency: 100++Loading used UUIDs from used_sfs_uuids.txt...+Loaded 12847 used UUIDs in 145ms++All mappings file already exists at all_sfs_mapping_uuids.txt, using cached data...+Counted 234567 UUIDs in file in 1.2s++Streaming through all_sfs_mapping_uuids.txt to find unused UUIDs...+ Processed 100000 UUIDs, found 87234 unused so far...+ Processed 200000 UUIDs, found 187654 unused so far...+Found 221720 unused UUIDs in 3.8s++=== Summary ===+Total mappings: 234567+Total mapping UUIDs: 234567+Total used UUIDs (from file): 12847+Total unused UUIDs: 221720+Percentage unused: 94.52%++Results saved to: unused_sfs_uuids.txt+```++## Next Steps++After running this tool:+1. Review the percentage of unused files (high percentage is normal)+2. Optionally spot-check a few unused UUIDs to verify they're safe to delete+3. Run `cleanup_unused_sfs` to delete the unused files and database mappings++## Troubleshooting++### "File does not exist: used_sfs_uuids.txt"+- Run `find_used_sfs_ids` first to generate this file++### "Failed to connect to database"+- Only occurs on first run (database is skipped if cache exists)+- Verify `DATABASE_URL` is set correctly+- Check database is running and accessible+- Ensure user has SELECT permissions on `email_sfs_mappings` table++### Out of memory+- Unusual with streaming architecture+- Check size of `used_sfs_uuids.txt` - this is the only file loaded fully into memory+- If used UUIDs file is extremely large (>10M entries), you may need more RAM++### Results look wrong (unexpected percentage)+- Verify `used_sfs_uuids.txt` was generated from the same database+- Check that `all_sfs_mapping_uuids.txt` is up-to-date (delete and re-run if unsure)+- Ensure destination URLs in database follow expected format: `{prefix}/{uuid}`++### Want to force fresh database query+```bash+rm all_sfs_mapping_uuids.txt+cargo run --bin find_unused_sfs_ids+```diff --git a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rsnew file mode 100644index 0000000000..46b625480c--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/config.rs@@ -0,0 +1,39 @@+//! Configuration for the find_unused_sfs_ids binary.++use anyhow::Context;++/// Holds all configuration loaded from environment variables.+pub struct Config {+ /// Database connection URL.+ pub database_url: String,+ /// Path to the file containing used SFS UUIDs.+ pub used_uuids_file: String,+ /// Path to the file storing all mapping UUIDs from the database.+ pub all_mappings_file: String,+ /// Path to the file storing unused SFS UUIDs.+ pub unused_uuids_file: String,+ /// Concurrency for UUID extraction from URLs.+ pub extraction_concurrency: usize,+}++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 extraction_concurrency = std::env::var("EXTRACTION_CONCURRENCY")+ .unwrap_or_else(|_| "100".to_string())+ .parse::<usize>()+ .context("EXTRACTION_CONCURRENCY is not a valid number")?;++ Ok(Self {+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,+ used_uuids_file: std::env::var("USED_UUIDS_FILE")+ .unwrap_or_else(|_| "used_sfs_uuids.txt".to_string()),+ all_mappings_file: std::env::var("ALL_MAPPINGS_FILE")+ .unwrap_or_else(|_| "all_sfs_mapping_uuids.txt".to_string()),+ unused_uuids_file: std::env::var("UNUSED_UUIDS_FILE")+ .unwrap_or_else(|_| "unused_sfs_uuids.txt".to_string()),+ extraction_concurrency,+ })+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/find_unused_sfs_ids.rs b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/find_unused_sfs_ids.rsnew file mode 100644index 0000000000..d91083f042--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/find_unused_sfs_ids.rs@@ -0,0 +1,176 @@+//! # Find Unused SFS IDs Utility+//!+//! This binary compares UUIDs from the email_sfs_mappings table against a file of used UUIDs+//! to identify which SFS mappings are no longer referenced in email message bodies.+//!+//! ## Required Environment Variables:+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.+//!+//! ## Optional Environment Variables:+//! - `USED_UUIDS_FILE`: Path to the file containing used UUIDs (default: "used_sfs_uuids.txt").+//! - `ALL_MAPPINGS_FILE`: Path to store all mapping UUIDs (default: "all_sfs_mapping_uuids.txt").+//! - `UNUSED_UUIDS_FILE`: Path to store unused UUIDs (default: "unused_sfs_uuids.txt").+//! - `EXTRACTION_CONCURRENCY`: Concurrency for UUID extraction (default: 100).++mod config;+mod process;++use std::path::Path;+use std::time::Instant;++use anyhow::Context;+use macro_entrypoint::MacroEntrypoint;+use sqlx::postgres::PgPoolOptions;++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ println!("=== Find Unused SFS IDs ===\n");++ // Initialize and load configuration+ MacroEntrypoint::default().init();+ let config = load_and_print_config()?;++ // Load used UUIDs into memory for fast lookups+ let used_uuids = load_used_uuids(&config.used_uuids_file)?;++ // Load or fetch all mapping UUIDs+ let all_mappings_path = Path::new(&config.all_mappings_file);+ let total_mappings = load_or_fetch_mappings(&config, all_mappings_path).await?;++ // Find unused UUIDs by streaming comparison+ let unused_count =+ find_and_write_unused_uuids(all_mappings_path, &used_uuids, &config.unused_uuids_file)?;++ // Print summary+ print_summary(+ total_mappings,+ used_uuids.len(),+ unused_count,+ &config.unused_uuids_file,+ );++ Ok(())+}++/// Loads and prints configuration.+fn load_and_print_config() -> anyhow::Result<config::Config> {+ println!("Loading configuration...");+ let config = config::Config::from_env().context("Failed to load configuration")?;++ println!("Configuration:");+ println!(" Used UUIDs file: {}", config.used_uuids_file);+ println!(" All mappings file: {}", config.all_mappings_file);+ println!(" Unused UUIDs file: {}", config.unused_uuids_file);+ println!(+ " Extraction concurrency: {}\n",+ config.extraction_concurrency+ );++ Ok(config)+}++/// Loads used UUIDs from file into a HashSet for O(1) lookups.+fn load_used_uuids(file_path: &str) -> anyhow::Result<std::collections::HashSet<String>> {+ println!("Loading used UUIDs from {}...", file_path);+ let load_start = Instant::now();+ let used_uuids = process::load_uuids_from_file(Path::new(file_path))?;+ println!(+ "Loaded {} used UUIDs in {:.2?}\n",+ used_uuids.len(),+ load_start.elapsed()+ );+ Ok(used_uuids)+}++/// Loads mapping UUIDs from cache or fetches from database if needed.+async fn load_or_fetch_mappings(+ config: &config::Config,+ all_mappings_path: &Path,+) -> anyhow::Result<usize> {+ if all_mappings_path.exists() {+ load_cached_mappings(all_mappings_path, &config.all_mappings_file)+ } else {+ fetch_mappings_from_database(config, all_mappings_path).await+ }+}++/// Loads mapping count from cached file.+fn load_cached_mappings(path: &Path, file_name: &str) -> anyhow::Result<usize> {+ println!(+ "All mappings file already exists at {}, using cached data...",+ file_name+ );+ let count_start = Instant::now();+ let count = process::count_lines_in_file(path)?;+ println!(+ "Counted {} UUIDs in file in {:.2?}\n",+ count,+ count_start.elapsed()+ );+ Ok(count)+}++/// Fetches mappings from database and writes to file.+async fn fetch_mappings_from_database(+ config: &config::Config,+ output_path: &Path,+) -> anyhow::Result<usize> {+ println!("Connecting to the database...");+ let db_pool = PgPoolOptions::new()+ .min_connections(1)+ .max_connections(5)+ .connect(&config.database_url)+ .await+ .context("Failed to connect to database")?;++ println!(+ "Streaming mapping destinations from email_sfs_mappings to {}...",+ config.all_mappings_file+ );+ let stream_start = Instant::now();+ let count = process::stream_mapping_uuids_to_file(&db_pool, output_path).await?;+ println!(+ "Streamed and wrote {} UUIDs in {:.2?}\n",+ count,+ stream_start.elapsed()+ );+ Ok(count)+}++/// Finds unused UUIDs by streaming comparison and writes to file.+fn find_and_write_unused_uuids(+ all_mappings_path: &Path,+ used_uuids: &std::collections::HashSet<String>,+ output_file: &str,+) -> anyhow::Result<usize> {+ println!(+ "Streaming through {} to find unused UUIDs...",+ all_mappings_path.display()+ );+ let stream_start = Instant::now();+ let unused_count =+ process::stream_find_unused_uuids(all_mappings_path, used_uuids, Path::new(output_file))?;+ println!(+ "Found {} unused UUIDs in {:.2?}\n",+ unused_count,+ stream_start.elapsed()+ );+ Ok(unused_count)+}++/// Prints the final summary.+fn print_summary(total_mappings: usize, used_count: usize, unused_count: usize, output_file: &str) {+ println!("\n=== Summary ===");+ println!("Total mappings: {}", total_mappings);+ println!("Total used UUIDs (from file): {}", used_count);+ println!("Total unused UUIDs: {}", unused_count);+ if total_mappings > 0 {+ println!(+ "Percentage unused: {:.2}%",+ (unused_count as f64 / total_mappings as f64) * 100.0+ );+ } else {+ println!("Percentage unused: N/A (no mappings)");+ }+ println!("\nResults saved to: {}", output_file);+}diff --git a/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/process.rs b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/process.rsnew file mode 100644index 0000000000..713595f16e--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_unused_sfs_ids/process.rs@@ -0,0 +1,174 @@+//! Processing logic for finding unused SFS UUIDs.++use std::collections::HashSet;+use std::fs::File;+use std::io::{BufRead, BufReader, BufWriter, Write};+use std::path::Path;++use anyhow::Context;+use futures::TryStreamExt;+use sqlx::PgPool;++/// Length of a UUID string (8-4-4-4-12 format with dashes).+const UUID_LENGTH: usize = 36;++/// Streams mapping destinations from the database, extracts UUIDs, and writes them to a file.+/// Returns the number of UUIDs written.+pub async fn stream_mapping_uuids_to_file(db: &PgPool, file_path: &Path) -> anyhow::Result<usize> {+ let file = File::create(file_path)+ .with_context(|| format!("Failed to create file: {}", file_path.display()))?;+ let mut writer = BufWriter::new(file);++ let mut stream =+ sqlx::query_scalar::<_, String>("SELECT destination FROM public.email_sfs_mappings")+ .fetch(db);++ let mut count = 0;+ while let Some(destination) = stream.try_next().await? {+ let uuid = extract_uuid_from_url(&destination);+ writeln!(writer, "{}", uuid).context("Failed to write UUID to file")?;+ count += 1;++ // Flush periodically to avoid buffering too much in memory+ if count % 10000 == 0 {+ writer.flush().context("Failed to flush buffer")?;+ println!(" Streamed {} UUIDs so far...", count);+ }+ }++ writer.flush().context("Failed to flush final buffer")?;+ Ok(count)+}++/// Extracts a UUID string from the end of a URL.+/// Assumes the last 36 characters are always the UUID.+/// Expected format: https://domain.com/file/{uuid}+pub fn extract_uuid_from_url(url: &str) -> String {+ if url.len() >= UUID_LENGTH {+ url[url.len() - UUID_LENGTH..].to_string()+ } else {+ url.to_string()+ }+}++/// Loads UUID strings from a file into a HashSet for O(1) lookups.+pub fn load_uuids_from_file(path: &Path) -> anyhow::Result<HashSet<String>> {+ if !path.exists() {+ anyhow::bail!("File does not exist: {}", path.display());+ }++ let file = File::open(path).context("Failed to open UUIDs file")?;+ let reader = BufReader::new(file);+ let mut uuids = HashSet::new();++ for line in reader.lines() {+ let line = line.context("Failed to read line")?;+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ uuids.insert(trimmed.to_string());+ }+ }++ Ok(uuids)+}++/// Counts non-empty lines in a file without loading all into memory.+pub fn count_lines_in_file(path: &Path) -> anyhow::Result<usize> {+ if !path.exists() {+ anyhow::bail!("File does not exist: {}", path.display());+ }++ let file =+ File::open(path).with_context(|| format!("Failed to open file: {}", path.display()))?;+ let reader = BufReader::new(file);++ let mut count = 0;+ for line in reader.lines() {+ let line = line.context("Failed to read line")?;+ if !line.trim().is_empty() {+ count += 1;+ }+ }++ Ok(count)+}++/// Streams through all mapping UUIDs and writes unused ones to a file.+/// Returns the count of unused UUIDs found.+pub fn stream_find_unused_uuids(+ all_mappings_file: &Path,+ used_uuids: &HashSet<String>,+ output_file: &Path,+) -> anyhow::Result<usize> {+ if !all_mappings_file.exists() {+ anyhow::bail!(+ "All mappings file does not exist: {}",+ all_mappings_file.display()+ );+ }++ let input = File::open(all_mappings_file)+ .with_context(|| format!("Failed to open file: {}", all_mappings_file.display()))?;+ let reader = BufReader::new(input);++ let output = File::create(output_file)+ .with_context(|| format!("Failed to create file: {}", output_file.display()))?;+ let mut writer = BufWriter::new(output);++ let mut count = 0;+ let mut processed = 0;++ for line in reader.lines() {+ let line = line.context("Failed to read line")?;+ let uuid = line.trim();++ if !uuid.is_empty() {+ processed += 1;++ // If this UUID is not in the used set, it's unused+ if !used_uuids.contains(uuid) {+ writeln!(writer, "{}", uuid).context("Failed to write unused UUID")?;+ count += 1;+ }++ // Progress update every 100k UUIDs+ if processed % 100000 == 0 {+ writer.flush().context("Failed to flush buffer")?;+ println!(+ " Processed {} UUIDs, found {} unused so far...",+ processed, count+ );+ }+ }+ }++ writer.flush().context("Failed to flush final buffer")?;+ Ok(count)+}++#[cfg(test)]+mod test {+ use super::*;++ #[test]+ fn test_extract_uuid_from_url_basic() {+ let url =+ "https://static-file-service-dev.macro.com/file/bc698c53-5a61-45f9-ac88-212e22cf8a33";+ let uuid = extract_uuid_from_url(url);+ assert_eq!(uuid, "bc698c53-5a61-45f9-ac88-212e22cf8a33");+ }++ #[test]+ fn test_extract_uuid_from_url_different_domain() {+ let url = "https://other-domain.com/assets/bc698c53-5a61-45f9-ac88-212e22cf8a33";+ let uuid = extract_uuid_from_url(url);+ assert_eq!(uuid, "bc698c53-5a61-45f9-ac88-212e22cf8a33");+ }++ #[test]+ fn test_extract_uuid_from_url_short_url() {+ let url = "short";+ let uuid = extract_uuid_from_url(url);+ assert_eq!(uuid, "short");+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/README.md b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/README.mdnew file mode 100644index 0000000000..3adf4645f8--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/README.md@@ -0,0 +1,155 @@+# Find Used SFS IDs++This binary scans email message HTML content to find all SFS (Static File Service) UUIDs that are referenced in message bodies. This helps identify which SFS mappings are actually in use versus those that are orphaned.++## Purpose++Part of a three-step workflow to identify and clean up unused SFS files:+1. **This tool** → Finds SFS UUIDs referenced in email message bodies+2. `find_unused_sfs_ids` → Compares all mappings against used UUIDs to find orphans+3. `cleanup_unused_sfs` → Deletes the unused files and mappings++## How It Works++1. Fetches all email message IDs from the database+2. Retrieves message HTML content in batches (streaming, memory-efficient)+3. Extracts SFS UUIDs from HTML using regex pattern matching+4. Writes unique UUIDs to output file as they're discovered+5. Supports resume functionality - if interrupted, it picks up where it left off++## Environment Variables++### Required+- `DATABASE_URL`: PostgreSQL connection string for the MacroDB database++### Optional+- `SFS_DOMAIN`: The domain to search for (default: `static-file-service.macro.com`)+- `MESSAGE_IDS_FILE`: Path to store/load message IDs (default: `message_ids.txt`)+- `USED_UUIDS_FILE`: Path to store found UUIDs (default: `used_sfs_uuids.txt`)+- `FETCH_BATCH_SIZE`: Number of messages to fetch from DB per query (default: `1000`)+- `BATCH_SIZE`: Number of messages to process before logging progress (default: `1000`)+- `PREFETCH_BATCHES`: Number of batches to prefetch while processing (default: `2`)++## Usage++### Basic Usage+```bash+cargo run --bin find_used_sfs_ids+```++### With Custom Configuration+```bash+export DATABASE_URL="postgresql://user:pass@localhost/macrodb"+export SFS_DOMAIN="static-file-service-dev.macro.com"+export USED_UUIDS_FILE="custom_used_uuids.txt"+cargo run --bin find_used_sfs_ids+```++### From Release Binary+```bash+./find_used_sfs_ids+```++## Output Files++### `used_sfs_uuids.txt` (default)+Contains one UUID per line for each SFS file referenced in email message bodies.++Example:+```+bc698c53-5a61-45f9-ac88-212e22cf8a33+d4e7f1a2-9b3c-4d2e-8f5a-1a2b3c4d5e6f+a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d+```++### `message_ids.txt` (default)+Cached list of all message IDs from the database. If this file exists, the tool will use it instead of querying the database again.++### `message_ids.processed` (automatically created)+Tracks which message IDs have been processed. Used for resume functionality.++## Resume Functionality++The tool automatically supports resuming interrupted runs:++1. On start, checks for existing `message_ids.processed` file+2. Skips messages that have already been processed+3. Appends newly found UUIDs to the existing output file+4. Progress is saved incrementally, so interruptions are safe++To force a fresh run, delete:+- `message_ids.processed`+- `used_sfs_uuids.txt` (optional, if you want to start fresh)++## Performance++- **Streaming architecture**: Fetches and processes messages in batches to avoid loading all into memory+- **Concurrent processing**: Uses tokio tasks to process multiple messages in parallel+- **Prefetching**: Database batches are fetched ahead of processing to minimize wait time+- **Incremental writes**: UUIDs are written to disk as they're found, not buffered in memory++Typical performance:+- ~1000-2000 messages per second (varies based on HTML complexity)+- Memory usage stays constant regardless of total message count+- Can process millions of messages without issue++## Example Run++```+=== Find Used SFS IDs ===++Loading configuration...+Configuration:+ SFS Domain: static-file-service.macro.com+ Message IDs file: message_ids.txt+ Used UUIDs file: used_sfs_uuids.txt+ Fetch batch size: 1000+ Progress batch size: 1000+ Prefetch batches: 2++Connecting to the database...+Fetching all message IDs from the database...+Found 145623 message IDs++Total message IDs to process: 145623++ [Batch 1/146] DB fetch: 1000 messages in 245ms+ [Batch 1/146] Processing: 1000 messages in 1.2s+Progress: 1000/145623 messages processed, 342 unique UUIDs found (342 new this run)+ [Batch 2/146] DB fetch: 1000 messages in 198ms+ [Batch 2/146] Processing: 1000 messages in 1.1s+Progress: 2000/145623 messages processed, 687 unique UUIDs found (345 new this run)+...++=== Processing Complete ===+Total messages processed: 145623+Total unique SFS UUIDs found: 12847+Results saved to: used_sfs_uuids.txt+```++## Next Steps++After running this tool:+1. Run `find_unused_sfs_ids` to compare all mappings against this list+2. Review the unused UUIDs file to verify they're safe to delete+3. Run `cleanup_unused_sfs` to delete the unused files and mappings++## Troubleshooting++### "Failed to connect to database"+- Verify `DATABASE_URL` is set correctly+- Check database is running and accessible+- Ensure user has SELECT permissions on email_messages table++### Out of memory+- Reduce `FETCH_BATCH_SIZE` (try 500 or 250)+- Reduce `PREFETCH_BATCHES` (try 1)++### Slow performance+- Increase `FETCH_BATCH_SIZE` (try 2000 or 5000)+- Ensure database has proper indexes on email_messages table+- Check database connection pool size++### Resume not working+- Check that `message_ids.processed` file has write permissions+- Verify file is in the same directory as the binarydiff --git a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rsnew file mode 100644index 0000000000..feaa087878--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/config.rs@@ -0,0 +1,55 @@+//! Configuration for the find_used_sfs_ids binary.++use anyhow::Context;++/// Holds all configuration loaded from environment variables.+pub struct Config {+ /// Database connection URL.+ pub database_url: String,+ /// The domain to search for in HTML content (e.g., "static-file-service.macro.com").+ pub sfs_domain: String,+ /// Path to the file storing message IDs.+ pub message_ids_file: String,+ /// Path to the file storing used SFS UUIDs.+ pub used_uuids_file: String,+ /// Batch size for fetching message bodies from the database.+ pub fetch_batch_size: usize,+ /// Batch size for progress logging.+ pub batch_size: usize,+ /// Number of batches to prefetch (buffer size for the fetch-process pipeline).+ pub prefetch_batches: usize,+}++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 fetch_batch_size = std::env::var("FETCH_BATCH_SIZE")+ .unwrap_or_else(|_| "1000".to_string())+ .parse::<usize>()+ .context("FETCH_BATCH_SIZE is not a valid number")?;++ let batch_size = std::env::var("BATCH_SIZE")+ .unwrap_or_else(|_| "1000".to_string())+ .parse::<usize>()+ .context("BATCH_SIZE is not a valid number")?;++ let prefetch_batches = std::env::var("PREFETCH_BATCHES")+ .unwrap_or_else(|_| "2".to_string())+ .parse::<usize>()+ .context("PREFETCH_BATCHES is not a valid number")?;++ Ok(Self {+ database_url: std::env::var("DATABASE_URL").context("DATABASE_URL not set")?,+ sfs_domain: std::env::var("SFS_DOMAIN")+ .unwrap_or_else(|_| "static-file-service.macro.com".to_string()),+ message_ids_file: std::env::var("MESSAGE_IDS_FILE")+ .unwrap_or_else(|_| "message_ids.txt".to_string()),+ used_uuids_file: std::env::var("USED_UUIDS_FILE")+ .unwrap_or_else(|_| "used_sfs_uuids.txt".to_string()),+ fetch_batch_size,+ batch_size,+ prefetch_batches,+ })+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/find_used_sfs_ids.rs b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/find_used_sfs_ids.rsnew file mode 100644index 0000000000..a254cefce6--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/find_used_sfs_ids.rs@@ -0,0 +1,382 @@+//! # Find Used SFS IDs Utility+//!+//! This binary scans email message HTML content to find all SFS (Static File Service) UUIDs+//! that are referenced in message bodies. This helps identify which SFS mappings are actually+//! in use versus those that are orphaned.+//!+//! ## Required Environment Variables:+//! - `DATABASE_URL`: The connection string for the PostgreSQL database.+//!+//! ## Optional Environment Variables:+//! - `SFS_DOMAIN`: The domain to search for (default: "static-file-service.macro.com").+//! - `MESSAGE_IDS_FILE`: Path to store/load message IDs (default: "message_ids.txt").+//! - `USED_UUIDS_FILE`: Path to store found UUIDs (default: "used_sfs_uuids.txt").+//! - `FETCH_BATCH_SIZE`: Number of messages to fetch from DB per query (default: 1000).+//! - `BATCH_SIZE`: Number of messages to process before logging progress (default: 1000).+//! - `PREFETCH_BATCHES`: Number of batches to prefetch while processing (default: 2).++mod config;+mod process;++use std::collections::HashSet;+use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::Instant;++use anyhow::Context;+use futures::future::join_all;+use macro_entrypoint::MacroEntrypoint;+use sqlx::PgPool;+use sqlx::postgres::PgPoolOptions;+use tokio::sync::mpsc;+use uuid::Uuid;++/// A fetched batch of message bodies along with their original IDs.+struct FetchedBatch {+ message_bodies: Vec<process::MessageBody>,+ fetch_duration: std::time::Duration,+}++/// Tracking state for processing progress and results.+struct ProcessingState {+ all_found_uuids: HashSet<Uuid>,+ new_uuids_this_run: HashSet<Uuid>,+ processed_count: usize,+ batches_completed: usize,+}++impl ProcessingState {+ fn new(initial_uuids: HashSet<Uuid>) -> Self {+ Self {+ all_found_uuids: initial_uuids,+ new_uuids_this_run: HashSet::new(),+ processed_count: 0,+ batches_completed: 0,+ }+ }+}++#[tokio::main]+async fn main() -> anyhow::Result<()> {+ println!("=== Find Used SFS IDs ===\n");++ // Initialize and load configuration+ MacroEntrypoint::default().init();+ let config = load_and_print_config()?;++ // Connect to database+ let db_pool = connect_to_database(&config.database_url).await?;++ // Load or fetch all message IDs+ let message_ids = process::load_or_fetch_message_ids(&db_pool, &config).await?;+ println!("Total message IDs to process: {}\n", message_ids.len());++ // Setup resume functionality and load existing progress+ let (used_uuids_path, processed_file) = setup_file_paths(&config);+ let existing_uuids = load_existing_progress(&used_uuids_path)?;+ let processed_ids = load_resume_state(&processed_file)?;++ // Filter to only unprocessed messages+ let ids_to_process = filter_unprocessed_ids(message_ids, processed_ids);+ if ids_to_process.is_empty() {+ println!("No messages to process. Exiting.");+ return Ok(());+ }++ // Process all messages and extract UUIDs+ let mut state = ProcessingState::new(existing_uuids);+ process_all_messages(+ &db_pool,+ ids_to_process,+ &config,+ &mut state,+ &used_uuids_path,+ &processed_file,+ )+ .await?;++ // Print final summary+ print_summary(&state, &config.used_uuids_file);++ Ok(())+}++/// Loads and prints configuration.+fn load_and_print_config() -> anyhow::Result<config::Config> {+ println!("Loading configuration...");+ let config = config::Config::from_env().context("Failed to load configuration")?;++ println!("Configuration:");+ println!(" SFS Domain: {}", config.sfs_domain);+ println!(" Message IDs file: {}", config.message_ids_file);+ println!(" Used UUIDs file: {}", config.used_uuids_file);+ println!(" Fetch batch size: {}", config.fetch_batch_size);+ println!(" Progress batch size: {}", config.batch_size);+ println!(" Prefetch batches: {}\n", config.prefetch_batches);++ Ok(config)+}++/// Connects to the database.+async fn connect_to_database(database_url: &str) -> anyhow::Result<PgPool> {+ println!("Connecting to the database...");+ PgPoolOptions::new()+ .min_connections(5)+ .max_connections(20)+ .connect(database_url)+ .await+ .context("Failed to connect to database")+}++/// Sets up file paths for output and resume tracking.+fn setup_file_paths(config: &config::Config) -> (PathBuf, PathBuf) {+ let used_uuids_path = PathBuf::from(&config.used_uuids_file);+ let processed_file = Path::new(&config.message_ids_file).with_extension("processed");+ (used_uuids_path, processed_file)+}++/// Loads existing UUIDs from previous runs.+fn load_existing_progress(used_uuids_path: &Path) -> anyhow::Result<HashSet<Uuid>> {+ let existing_uuids = process::load_existing_used_uuids(used_uuids_path)?;+ let initial_count = existing_uuids.len();+ if initial_count > 0 {+ println!(+ "Loaded {} existing UUIDs from {}",+ initial_count,+ used_uuids_path.display()+ );+ }+ Ok(existing_uuids)+}++/// Loads resume state (already processed message IDs).+fn load_resume_state(processed_file: &Path) -> anyhow::Result<HashSet<Uuid>> {+ let processed_ids = process::load_processed_message_ids(processed_file)?;+ let already_processed = processed_ids.len();+ if already_processed > 0 {+ println!("Resuming: {} messages already processed", already_processed);+ }+ Ok(processed_ids)+}++/// Filters out already processed messages.+fn filter_unprocessed_ids(message_ids: Vec<Uuid>, processed_ids: HashSet<Uuid>) -> Vec<Uuid> {+ let ids_to_process: Vec<_> = message_ids+ .into_iter()+ .filter(|id| !processed_ids.contains(id))+ .collect();+ println!("Messages remaining to process: {}\n", ids_to_process.len());+ ids_to_process+}++/// Processes all messages by fetching and extracting UUIDs.+async fn process_all_messages(+ db_pool: &PgPool,+ ids_to_process: Vec<Uuid>,+ config: &config::Config,+ state: &mut ProcessingState,+ used_uuids_path: &Path,+ processed_file: &Path,+) -> anyhow::Result<()> {+ let total_to_process = ids_to_process.len();++ // Create channel for the fetch-process pipeline+ let (tx, mut rx) = mpsc::channel::<FetchedBatch>(config.prefetch_batches);++ // Split IDs into batches and spawn fetcher task+ let batches = create_batches(&ids_to_process, config.fetch_batch_size);+ let total_batches = batches.len();+ let fetcher_handle = spawn_fetcher_task(db_pool.clone(), batches, tx);++ // Process batches as they arrive+ let sfs_domain = Arc::new(config.sfs_domain.clone());++ while let Some(batch) = rx.recv().await {+ process_single_batch(+ batch,+ state,+ &sfs_domain,+ total_batches,+ total_to_process,+ used_uuids_path,+ processed_file,+ )+ .await?;+ }++ // Wait for fetcher to complete+ fetcher_handle.await?;++ // Flush any remaining UUIDs+ if !state.new_uuids_this_run.is_empty() {+ process::append_uuids_to_file(&state.new_uuids_this_run, used_uuids_path)?;+ }++ Ok(())+}++/// Creates batches of message IDs for processing.+fn create_batches(ids: &[Uuid], batch_size: usize) -> Vec<Vec<Uuid>> {+ ids.chunks(batch_size).map(|chunk| chunk.to_vec()).collect()+}++/// Spawns the database fetcher task.+fn spawn_fetcher_task(+ db_pool: PgPool,+ batches: Vec<Vec<Uuid>>,+ tx: mpsc::Sender<FetchedBatch>,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(async move {+ fetch_batches(db_pool, batches, tx).await;+ })+}++/// Processes a single batch of messages.+async fn process_single_batch(+ batch: FetchedBatch,+ state: &mut ProcessingState,+ sfs_domain: &Arc<String>,+ total_batches: usize,+ total_to_process: usize,+ used_uuids_path: &Path,+ processed_file: &Path,+) -> anyhow::Result<()> {+ state.batches_completed += 1;++ println!(+ " [Batch {}/{}] DB fetch: {} messages in {:.2?}",+ state.batches_completed,+ total_batches,+ batch.message_bodies.len(),+ batch.fetch_duration+ );++ // Extract UUIDs from all messages in the batch+ let process_start = Instant::now();+ let batch_count = batch.message_bodies.len();+ let batch_processed_ids =+ extract_uuids_from_batch(batch.message_bodies, sfs_domain, state).await;++ println!(+ " [Batch {}/{}] Processing: {} messages in {:.2?}",+ state.batches_completed,+ total_batches,+ batch_count,+ process_start.elapsed()+ );++ // Mark batch as processed+ if let Err(e) = process::append_uuids_to_file(+ &batch_processed_ids.iter().cloned().collect(),+ processed_file,+ ) {+ eprintln!("Warning: Failed to mark batch as processed: {:?}", e);+ }++ state.processed_count += batch_count;++ // Log progress and flush UUIDs+ print_batch_progress(state, total_to_process);+ flush_new_uuids(&mut state.new_uuids_this_run, used_uuids_path)?;++ Ok(())+}++/// Extracts UUIDs from a batch of messages concurrently.+async fn extract_uuids_from_batch(+ messages: Vec<process::MessageBody>,+ sfs_domain: &Arc<String>,+ state: &mut ProcessingState,+) -> Vec<Uuid> {+ let extraction_futures: Vec<_> = messages+ .into_iter()+ .map(|msg| {+ let domain = Arc::clone(sfs_domain);+ tokio::task::spawn_blocking(move || {+ let found = msg+ .body_html_sanitized+ .as_ref()+ .map(|body| process::extract_sfs_uuids(body, &domain))+ .unwrap_or_default();+ (msg.id, found)+ })+ })+ .collect();++ let batch_results = join_all(extraction_futures).await;+ let mut batch_processed_ids = Vec::new();++ for result in batch_results {+ match result {+ Ok((msg_id, found_uuids)) => {+ for uuid in found_uuids {+ if !state.all_found_uuids.contains(&uuid) {+ state.all_found_uuids.insert(uuid);+ state.new_uuids_this_run.insert(uuid);+ }+ }+ batch_processed_ids.push(msg_id);+ }+ Err(e) => {+ eprintln!("Error processing message: {:?}", e);+ }+ }+ }++ batch_processed_ids+}++/// Prints progress for the current batch.+fn print_batch_progress(state: &ProcessingState, total_to_process: usize) {+ println!(+ "Progress: {}/{} messages processed, {} unique UUIDs found ({} new this run)",+ state.processed_count,+ total_to_process,+ state.all_found_uuids.len(),+ state.new_uuids_this_run.len()+ );+}++/// Flushes newly found UUIDs to file.+fn flush_new_uuids(new_uuids: &mut HashSet<Uuid>, path: &Path) -> anyhow::Result<()> {+ if !new_uuids.is_empty() {+ process::append_uuids_to_file(new_uuids, path)?;+ new_uuids.clear();+ }+ Ok(())+}++/// Prints the final summary.+fn print_summary(state: &ProcessingState, output_file: &str) {+ println!("\n=== Processing Complete ===");+ println!("Total messages processed: {}", state.processed_count);+ println!(+ "Total unique SFS UUIDs found: {}",+ state.all_found_uuids.len()+ );+ println!("Results saved to: {}", output_file);+}++/// Fetches batches from the database and sends them through the channel.+async fn fetch_batches(db_pool: PgPool, batches: Vec<Vec<Uuid>>, tx: mpsc::Sender<FetchedBatch>) {+ for batch_ids in batches {+ let fetch_start = Instant::now();+ match process::fetch_message_bodies_batch(&db_pool, &batch_ids).await {+ Ok(message_bodies) => {+ let fetch_duration = fetch_start.elapsed();+ let fetched_batch = FetchedBatch {+ message_bodies,+ fetch_duration,+ };+ if tx.send(fetched_batch).await.is_err() {+ // Receiver dropped, stop fetching+ break;+ }+ }+ Err(e) => {+ eprintln!("Error fetching batch of messages: {:?}", e);+ // Continue to next batch on error+ }+ }+ }+}diff --git a/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/process.rs b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/process.rsnew file mode 100644index 0000000000..a7ab69788b--- /dev/null+++ b/rust/cloud-storage/email_service/src/bin/find_used_sfs_ids/process.rs@@ -0,0 +1,255 @@+//! Processing logic for finding used SFS UUIDs in email messages.++use std::collections::HashSet;+use std::fs::{File, OpenOptions};+use std::io::{BufRead, BufReader, BufWriter, Write};+use std::path::Path;++use anyhow::Context;+use regex::Regex;+use sqlx::PgPool;+use uuid::Uuid;++use crate::config::Config;++/// Fetches all message IDs from the database.+pub async fn fetch_all_message_ids(db: &PgPool) -> anyhow::Result<Vec<Uuid>> {+ let rows: Vec<(Uuid,)> = sqlx::query_as("SELECT id FROM public.email_messages")+ .fetch_all(db)+ .await+ .context("Failed to fetch message IDs")?;++ Ok(rows.into_iter().map(|(id,)| id).collect())+}++/// Loads message IDs from a file, or fetches from DB and saves to file if it doesn't exist.+pub async fn load_or_fetch_message_ids(db: &PgPool, config: &Config) -> anyhow::Result<Vec<Uuid>> {+ let path = Path::new(&config.message_ids_file);++ if path.exists() {+ println!(+ "Message IDs file exists at {}, loading from file...",+ config.message_ids_file+ );+ load_message_ids_from_file(path)+ } else {+ println!(+ "Message IDs file not found, fetching from database and saving to {}...",+ config.message_ids_file+ );+ let ids = fetch_all_message_ids(db).await?;+ save_message_ids_to_file(&ids, path)?;+ Ok(ids)+ }+}++/// Loads message IDs from a file.+fn load_message_ids_from_file(path: &Path) -> anyhow::Result<Vec<Uuid>> {+ let file = File::open(path).context("Failed to open message IDs file")?;+ let reader = BufReader::new(file);+ let mut ids = Vec::new();++ for line in reader.lines() {+ let line = line.context("Failed to read line from message IDs file")?;+ let trimmed = line.trim();+ if !trimmed.is_empty() {+ let id = Uuid::parse_str(trimmed)+ .with_context(|| format!("Failed to parse UUID: {}", trimmed))?;+ ids.push(id);+ }+ }++ Ok(ids)+}++/// Saves message IDs to a file.+fn save_message_ids_to_file(ids: &[Uuid], path: &Path) -> anyhow::Result<()> {+ let file = File::create(path).context("Failed to create message IDs file")?;+ let mut writer = BufWriter::new(file);++ for id in ids {+ writeln!(writer, "{}", id).context("Failed to write message ID")?;+ }++ writer.flush().context("Failed to flush message IDs file")?;+ Ok(())+}++/// Message body result containing the message ID and its HTML body.+pub struct MessageBody {+ /// The message ID.+ pub id: Uuid,+ /// The sanitized HTML body, if present.+ pub body_html_sanitized: Option<String>,+}++/// Fetches message bodies in batch for the given message IDs.+pub async fn fetch_message_bodies_batch(+ db: &PgPool,+ message_ids: &[Uuid],+) -> anyhow::Result<Vec<MessageBody>> {+ if message_ids.is_empty() {+ return Ok(Vec::new());+ }++ // Build a query with ANY($1) to fetch multiple messages at once+ let rows: Vec<(Uuid, Option<String>)> = sqlx::query_as(+ "SELECT id, body_html_sanitized FROM public.email_messages WHERE id = ANY($1)",+ )+ .bind(message_ids)+ .fetch_all(db)+ .await+ .context("Failed to fetch message bodies")?;++ Ok(rows+ .into_iter()+ .map(|(id, body_html_sanitized)| MessageBody {+ id,+ body_html_sanitized,+ })+ .collect())+}++/// Extracts SFS UUIDs from HTML content by finding URLs matching the configured domain.+pub fn extract_sfs_uuids(html: &str, sfs_domain: &str) -> HashSet<Uuid> {+ let mut uuids = HashSet::new();++ // Build regex pattern to match URLs like https://{domain}/file/{uuid}+ // The UUID is a standard format: 8-4-4-4-12 hex characters+ let pattern = format!(+ r#"https?://{}[^\s"'<>]*?/([0-9a-fA-F]{{8}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{4}}-[0-9a-fA-F]{{12}})"#,+ regex::escape(sfs_domain)+ );++ let re = match Regex::new(&pattern) {+ Ok(r) => r,+ Err(e) => {+ eprintln!("Failed to compile regex pattern: {}", e);+ return uuids;+ }+ };++ for cap in re.captures_iter(html) {+ if let Some(uuid_match) = cap.get(1)+ && let Ok(uuid) = Uuid::parse_str(uuid_match.as_str())+ {+ uuids.insert(uuid);+ }+ }++ uuids+}++/// Loads already-processed message IDs to support resume functionality.+pub fn load_processed_message_ids(processed_file: &Path) -> anyhow::Result<HashSet<Uuid>> {+ if !processed_file.exists() {+ return Ok(HashSet::new());+ }++ let file = File::open(processed_file).context("Failed to open processed messages file")?;+ let reader = BufReader::new(file);+ let mut ids = HashSet::new();++ for line in reader.lines() {+ let line = line.context("Failed to read line from processed messages file")?;+ let trimmed = line.trim();+ if !trimmed.is_empty()+ && let Ok(id) = Uuid::parse_str(trimmed)+ {+ ids.insert(id);+ }+ }++ Ok(ids)+}++/// Appends multiple UUIDs to a file.+pub fn append_uuids_to_file(uuids: &HashSet<Uuid>, path: &Path) -> anyhow::Result<()> {+ let mut file = OpenOptions::new()+ .create(true)+ .append(true)+ .open(path)+ .context("Failed to open used UUIDs file for appending")?;++ for uuid in uuids {+ writeln!(file, "{}", uuid).context("Failed to write UUID")?;+ }++ Ok(())+}++/// Loads existing used UUIDs from file to avoid duplicates.+pub fn load_existing_used_uuids(path: &Path) -> anyhow::Result<HashSet<Uuid>> {+ if !path.exists() {+ return Ok(HashSet::new());+ }++ let file = File::open(path).context("Failed to open used UUIDs file")?;+ let reader = BufReader::new(file);+ let mut uuids = HashSet::new();++ for line in reader.lines() {+ let line = line.context("Failed to read line from used UUIDs file")?;+ let trimmed = line.trim();+ if !trimmed.is_empty()+ && let Ok(uuid) = Uuid::parse_str(trimmed)+ {+ uuids.insert(uuid);+ }+ }++ Ok(uuids)+}++#[cfg(test)]+mod test {+ use super::*;++ #[test]+ fn test_extract_sfs_uuids_basic() {+ let html = r#"<img src="https://static-file-service.macro.com/file/4e369509-666f-4d00-a321-4a7f0faa1304">"#;+ let uuids = extract_sfs_uuids(html, "static-file-service.macro.com");++ assert_eq!(uuids.len(), 1);+ assert!(uuids.contains(&Uuid::parse_str("4e369509-666f-4d00-a321-4a7f0faa1304").unwrap()));+ }++ #[test]+ fn test_extract_sfs_uuids_multiple() {+ let html = r#"+ <img src="https://static-file-service.macro.com/file/4e369509-666f-4d00-a321-4a7f0faa1304">+ <img src="https://static-file-service.macro.com/file/12345678-1234-1234-1234-123456789abc">+ "#;+ let uuids = extract_sfs_uuids(html, "static-file-service.macro.com");++ assert_eq!(uuids.len(), 2);+ assert!(uuids.contains(&Uuid::parse_str("4e369509-666f-4d00-a321-4a7f0faa1304").unwrap()));+ assert!(uuids.contains(&Uuid::parse_str("12345678-1234-1234-1234-123456789abc").unwrap()));+ }++ #[test]+ fn test_extract_sfs_uuids_no_match() {+ let html =+ r#"<img src="https://other-domain.com/file/4e369509-666f-4d00-a321-4a7f0faa1304">"#;+ let uuids = extract_sfs_uuids(html, "static-file-service.macro.com");++ assert!(uuids.is_empty());+ }++ #[test]+ fn test_extract_sfs_uuids_with_query_params() {+ let html = r#"<img src="https://static-file-service.macro.com/file/4e369509-666f-4d00-a321-4a7f0faa1304?size=thumb">"#;+ let uuids = extract_sfs_uuids(html, "static-file-service.macro.com");++ assert_eq!(uuids.len(), 1);+ assert!(uuids.contains(&Uuid::parse_str("4e369509-666f-4d00-a321-4a7f0faa1304").unwrap()));+ }++ #[test]+ fn test_extract_sfs_uuids_custom_domain() {+ let html = r#"<img src="https://custom.sfs.example.com/file/4e369509-666f-4d00-a321-4a7f0faa1304">"#;+ let uuids = extract_sfs_uuids(html, "custom.sfs.example.com");++ assert_eq!(uuids.len(), 1);+ }+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsonnew file mode 100644index 0000000000..d2b084cf10--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsonnew file mode 100644index 0000000000..6d97183829--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsonnew file mode 100644index 0000000000..9d717fa5f9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "values",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsonnew file mode 100644index 0000000000..182e0858ba--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"+}diff --git a/rust/cloud-storage/static_file_service/Cargo.toml b/rust/cloud-storage/static_file_service/Cargo.tomlindex b24347f378..bd5e75c0fc 100644--- a/rust/cloud-storage/static_file_service/Cargo.toml+++ b/rust/cloud-storage/static_file_service/Cargo.toml@@ -39,6 +39,8 @@ secretsmanager_client = { path = "../secretsmanager_client" }serde = { workspace = true }serde_dynamo = { workspace = true }serde_json = { workspace = true }+strum_macros = { workspace = true }+thiserror = { workspace = true }tokio = { workspace = true }tower = { workspace = true }tower-http = { workspace = true, features = ["limit", "timeout"] }diff --git a/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rs b/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rsnew file mode 100644index 0000000000..c47d391f3e--- /dev/null+++ b/rust/cloud-storage/static_file_service/src/api/file/bulk_delete_file.rs@@ -0,0 +1,190 @@+use crate::model::api::{BulkDeleteRequest, BulkDeleteResponse, DeleteResult};+use crate::service::dynamodb::client::DynamodbClient;+use crate::service::s3::client::S3Client;+use axum::extract::State;+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::{Extension, Json};+use macro_middleware::auth::internal_access::ValidInternalKey;+use model::response::ErrorResponse;+use model::user::UserContext;+use std::sync::Arc;+use strum_macros::AsRefStr;+use thiserror::Error;++#[derive(Debug, Error, AsRefStr)]+pub enum BulkDeleteError {+ #[error("Validation error: {0}")]+ Validation(String),++ #[error("Internal error")]+ InternalError(#[from] anyhow::Error),+}++impl IntoResponse for BulkDeleteError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ BulkDeleteError::Validation(_) => StatusCode::BAD_REQUEST,+ BulkDeleteError::InternalError(_) => StatusCode::INTERNAL_SERVER_ERROR,+ };++ (+ status_code,+ Json(ErrorResponse {+ message: self.as_ref(),+ }),+ )+ .into_response()+ }+}++/// Bulk delete files.+#[utoipa::path(+ post,+ path = "/api/file/bulk-delete",+ request_body = BulkDeleteRequest,+ responses(+ (status = 200, description = "Bulk delete results", body = BulkDeleteResponse),+ (status = 400, body = ErrorResponse),+ (status = 401, body = ErrorResponse),+ (status = 403, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+ )+]+#[tracing::instrument(skip(metadata_client, storage_client, usr, internal_key), fields(user_id = usr.user_id), err)]+pub async fn handle_bulk_delete_file(+ State(metadata_client): State<DynamodbClient>,+ State(storage_client): State<Arc<S3Client>>,+ usr: Extension<UserContext>,+ internal_key: Option<ValidInternalKey>,+ Json(req): Json<BulkDeleteRequest>,+) -> Result<Json<BulkDeleteResponse>, BulkDeleteError> {+ // Validate request+ if req.file_ids.is_empty() {+ return Err(BulkDeleteError::Validation(+ "file_ids cannot be empty".to_string(),+ ));+ }++ if req.file_ids.len() > req.max_file_ids() {+ return Err(BulkDeleteError::Validation(format!(+ "Cannot delete more than {} files at once",+ req.max_file_ids()+ )));+ }++ // Fetch metadata for all files+ let metadata_results = metadata_client+ .bulk_get_metadata(&req.file_ids)+ .await+ .map_err(|_| anyhow::anyhow!("failed to fetch metadata"))?;++ let mut results = Vec::with_capacity(req.file_ids.len());+ let mut s3_keys_to_delete = Vec::new();+ let mut file_ids_to_delete = Vec::new();++ // Process each file+ for file_id in &req.file_ids {+ match metadata_results.get(file_id) {+ Some(metadata) => {+ // Skip owner check for internal requests+ if internal_key.is_none() && metadata.owner_id != usr.user_id {+ tracing::warn!(file_id = file_id, "delete requested by non-owner");+ results.push(DeleteResult {+ file_id: file_id.clone(),+ success: false,+ error: Some("access denied".to_string()),+ });+ } else {+ // Collect for deletion+ s3_keys_to_delete.push(metadata.s3_key.clone());+ file_ids_to_delete.push(file_id.clone());+ results.push(DeleteResult {+ file_id: file_id.clone(),+ success: true,+ error: None,+ });+ }+ }+ None => {+ results.push(DeleteResult {+ file_id: file_id.clone(),+ success: false,+ error: Some("not found".to_string()),+ });+ }+ }+ }++ // Perform bulk S3 deletion+ if !s3_keys_to_delete.is_empty() {+ let s3_results = storage_client+ .bulk_hard_delete_objects(s3_keys_to_delete)+ .await;++ // Update results based on S3 deletion outcomes+ for (idx, file_id) in file_ids_to_delete.iter().enumerate() {+ if let Some(result) = results.iter_mut().find(|r| &r.file_id == file_id) {+ match &s3_results.get(idx) {+ Some(Ok(_)) => {+ // S3 deletion succeeded, keep success: true+ }+ Some(Err(e)) => {+ tracing::error!(file_id = file_id, error = ?e, "failed to delete from S3");+ result.success = false;+ result.error = Some(format!("s3 deletion failed: {}", e));+ }+ None => {+ result.success = false;+ result.error = Some("s3 deletion failed: no result".to_string());+ }+ }+ }+ }+ }++ // Perform bulk metadata deletion (only for files that passed S3 deletion)+ let successful_indices_and_ids: Vec<(usize, String)> = results+ .iter()+ .enumerate()+ .filter_map(|(idx, r)| {+ if r.success {+ Some((idx, r.file_id.clone()))+ } else {+ None+ }+ })+ .collect();++ if !successful_indices_and_ids.is_empty() {+ let file_ids_only: Vec<&str> = successful_indices_and_ids+ .iter()+ .map(|(_, id)| id.as_str())+ .collect();+ let db_results = metadata_client.bulk_delete_metadata(&file_ids_only).await;++ // Update results based on DB deletion outcomes+ for ((idx, file_id), db_result) in successful_indices_and_ids.iter().zip(db_results.iter())+ {+ if let Err(e) = db_result {+ tracing::error!(file_id = file_id, error = ?e, "failed to delete metadata");+ results[*idx].success = false;+ results[*idx].error = Some(format!("metadata deletion failed: {}", e));+ }+ }+ }++ // Calculate statistics+ let succeeded = results.iter().filter(|r| r.success).count();+ let failed = results.len() - succeeded;++ let response = BulkDeleteResponse {+ total: results.len(),+ succeeded,+ failed,+ results,+ };++ Ok(Json(response))+}diff --git a/rust/cloud-storage/static_file_service/src/api/file/mod.rs b/rust/cloud-storage/static_file_service/src/api/file/mod.rsindex 20beede732..9444d6343f 100644--- a/rust/cloud-storage/static_file_service/src/api/file/mod.rs+++ b/rust/cloud-storage/static_file_service/src/api/file/mod.rs@@ -1,10 +1,11 @@+pub mod bulk_delete_file;pub mod delete_file;pub mod get_file;pub mod metadata;pub mod put_presigned_url;use axum::Router;-use axum::routing::{delete, get, put};+use axum::routing::{delete, get, post, put};use crate::api::context::AppState;@@ -20,4 +21,8 @@ pub fn router() -> Router<AppState> {).route("/file", put(put_presigned_url::put_presigned_url)).route("/file/:file_id", delete(delete_file::handle_delete_file))+ .route(+ "/file/bulk-delete",+ post(bulk_delete_file::handle_bulk_delete_file),+ )}diff --git a/rust/cloud-storage/static_file_service/src/api/swagger.rs b/rust/cloud-storage/static_file_service/src/api/swagger.rsindex 3a419cea53..3a0613ef68 100644--- a/rust/cloud-storage/static_file_service/src/api/swagger.rs+++ b/rust/cloud-storage/static_file_service/src/api/swagger.rs@@ -1,5 +1,8 @@use crate::api::file;-use crate::model::api::*;+use crate::model::api::{+ BulkDeleteRequest, BulkDeleteResponse, DeleteResult, GetFileMetadataResponse, PutFileRequest,+ PutFileResponse,+};use utoipa::OpenApi;#[utoipa::path(@@ -28,13 +31,17 @@ fn get_file_documentation() {}file::metadata::handle_get_metadata,file::put_presigned_url::put_presigned_url,file::delete_file::handle_delete_file,+ file::bulk_delete_file::handle_bulk_delete_file,get_file_documentation),components(schemas(PutFileRequest,PutFileResponse,- GetFileMetadataResponse+ GetFileMetadataResponse,+ BulkDeleteRequest,+ BulkDeleteResponse,+ DeleteResult)),tags(diff --git a/rust/cloud-storage/static_file_service/src/model/api.rs b/rust/cloud-storage/static_file_service/src/model/api.rsindex 287b75710c..ba71765844 100644--- a/rust/cloud-storage/static_file_service/src/model/api.rs+++ b/rust/cloud-storage/static_file_service/src/model/api.rs@@ -41,3 +41,39 @@ impl From<MetadataObject> for FileMetadata {}}}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct BulkDeleteRequest {+ /// List of file IDs to delete+ pub file_ids: Vec<String>,+}++impl BulkDeleteRequest {+ /// Maximum number of files that can be deleted in a single bulk request+ /// Set to 100 as that's the Dynamo Get Item limit we use to fetch metadata+ pub fn max_file_ids(&self) -> usize {+ 100+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct DeleteResult {+ /// File ID that was attempted to delete+ pub file_id: String,+ /// Whether the deletion was successful+ pub success: bool,+ /// Error message if deletion failed+ pub error: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct BulkDeleteResponse {+ /// Total number of files attempted+ pub total: usize,+ /// Number of successful deletions+ pub succeeded: usize,+ /// Number of failed deletions+ pub failed: usize,+ /// Individual results for each file+ pub results: Vec<DeleteResult>,+}diff --git a/rust/cloud-storage/static_file_service/src/service/dynamodb/client.rs b/rust/cloud-storage/static_file_service/src/service/dynamodb/client.rsindex 1580c73184..b8797b92e4 100644--- a/rust/cloud-storage/static_file_service/src/service/dynamodb/client.rs+++ b/rust/cloud-storage/static_file_service/src/service/dynamodb/client.rs@@ -7,7 +7,9 @@ use super::put_item;use anyhow::{Context, Result, format_err};use aws_config::Region;use aws_sdk_dynamodb::Client;+use aws_sdk_dynamodb::types::AttributeValue;use serde_dynamo::{Item, from_item, to_item};+use std::collections::HashMap;#[derive(Debug, Clone)]pub struct DynamodbClient {@@ -59,4 +61,165 @@ impl DynamodbClient {pub async fn mark_uploaded(&self, id: &str) -> Result<()> {mark_uploaded::mark_uploaded(&self.client, &self.table, id).await}++ #[tracing::instrument(skip(self), fields(count = file_ids.len()), err)]+ pub async fn bulk_get_metadata(+ &self,+ file_ids: &[String],+ ) -> Result<HashMap<String, MetadataObject>> {+ if file_ids.is_empty() {+ return Ok(HashMap::new());+ }++ // DynamoDB batch_get_item has a limit of 100 items+ let chunk_size = 100;+ let mut all_results = HashMap::new();++ for chunk in file_ids.chunks(chunk_size) {+ let mut keys = Vec::new();+ for file_id in chunk {+ let mut key = HashMap::new();+ key.insert("file_id".to_string(), AttributeValue::S(file_id.clone()));+ keys.push(key);+ }++ let request_items = {+ let mut request_items = HashMap::new();+ request_items.insert(+ self.table.clone(),+ aws_sdk_dynamodb::types::KeysAndAttributes::builder()+ .set_keys(Some(keys))+ .build()+ .context("failed to build KeysAndAttributes")?,+ );+ request_items+ };++ let response = self+ .client+ .batch_get_item()+ .set_request_items(Some(request_items))+ .send()+ .await+ .context("failed to batch get items from metadata table")?;++ if let Some(responses) = response.responses()+ && let Some(items) = responses.get(&self.table)+ {+ for item in items {+ let metadata: MetadataObject =+ from_item(item.clone()).context("failed to deserialize metadata")?;+ all_results.insert(metadata.file_id.clone(), metadata);+ }+ }+ }++ Ok(all_results)+ }++ #[tracing::instrument(skip(self), fields(count = file_ids.len()))]+ pub async fn bulk_delete_metadata(&self, file_ids: &[&str]) -> Vec<Result<(), DeleteError>> {+ if file_ids.is_empty() {+ return Vec::new();+ }++ // DynamoDB batch_write_item has a limit of 25 items per request+ const BATCH_SIZE: usize = 25;+ let mut results = Vec::with_capacity(file_ids.len());++ // Initialize results as success, will mark failures later+ for _ in 0..file_ids.len() {+ results.push(Ok(()));+ }++ for (chunk_idx, chunk) in file_ids.chunks(BATCH_SIZE).enumerate() {+ let base_idx = chunk_idx * BATCH_SIZE;++ // Build delete requests+ let mut write_requests = Vec::new();+ for file_id in chunk {+ let mut key = HashMap::new();+ key.insert(+ "file_id".to_string(),+ AttributeValue::S(file_id.to_string()),+ );++ let delete_request = aws_sdk_dynamodb::types::DeleteRequest::builder()+ .set_key(Some(key))+ .build()+ .context("failed to build DeleteRequest");++ match delete_request {+ Ok(del_req) => {+ write_requests.push(+ aws_sdk_dynamodb::types::WriteRequest::builder()+ .delete_request(del_req)+ .build(),+ );+ }+ Err(e) => {+ tracing::error!(file_id = file_id, error = ?e, "failed to build delete request");+ results[base_idx + write_requests.len()] =+ Err(DeleteError::Other(e.to_string()));+ }+ }+ }++ if write_requests.is_empty() {+ continue;+ }++ let mut request_items = HashMap::new();+ request_items.insert(self.table.clone(), write_requests);++ // Execute batch write+ match self+ .client+ .batch_write_item()+ .set_request_items(Some(request_items.clone()))+ .send()+ .await+ {+ Ok(response) => {+ // Handle unprocessed items+ if let Some(unprocessed) = response.unprocessed_items()+ && let Some(unprocessed_writes) = unprocessed.get(&self.table)+ && !unprocessed_writes.is_empty()+ {+ tracing::warn!(+ count = unprocessed_writes.len(),+ "batch delete had unprocessed items, marking as errors"+ );++ // Mark unprocessed items as failures+ for write_req in unprocessed_writes {+ if let Some(del_req) = write_req.delete_request() {+ let key = del_req.key();+ if let Some(AttributeValue::S(file_id)) = key.get("file_id") {+ // Find the index of this file_id in the chunk+ if let Some(local_idx) =+ chunk.iter().position(|id| *id == file_id.as_str())+ {+ results[base_idx + local_idx] = Err(DeleteError::Other(+ "unprocessed by DynamoDB".to_string(),+ ));+ }+ }+ }+ }+ }+ }+ Err(e) => {+ tracing::error!(error = ?e, "batch delete request failed");+ // Mark all items in this chunk as failed+ for (i, _) in chunk.iter().enumerate() {+ results[base_idx + i] =+ Err(DeleteError::Other(format!("batch delete failed: {}", e)));+ }+ }+ }+ }++ results+ }}diff --git a/rust/cloud-storage/static_file_service/src/service/dynamodb/model.rs b/rust/cloud-storage/static_file_service/src/service/dynamodb/model.rsindex c4ca861566..a4b1a46609 100644--- a/rust/cloud-storage/static_file_service/src/service/dynamodb/model.rs+++ b/rust/cloud-storage/static_file_service/src/service/dynamodb/model.rs@@ -2,10 +2,22 @@ use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use serde_json::Value;+#[derive(Debug)]pub enum DeleteError {NotFound(String),Other(String),}++impl std::fmt::Display for DeleteError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ DeleteError::NotFound(msg) => write!(f, "Not found: {}", msg),+ DeleteError::Other(msg) => write!(f, "Error: {}", msg),+ }+ }+}++impl std::error::Error for DeleteError {}#[derive(Clone, Debug, Serialize, Deserialize)]/// The model stored in themetadat dynamodb tablepub struct MetadataObject {diff --git a/rust/cloud-storage/static_file_service/src/service/s3/client.rs b/rust/cloud-storage/static_file_service/src/service/s3/client.rsindex 0d10bbccab..e154c1fa9e 100644--- a/rust/cloud-storage/static_file_service/src/service/s3/client.rs+++ b/rust/cloud-storage/static_file_service/src/service/s3/client.rs@@ -62,4 +62,104 @@ impl S3Client {Ok(presigned_url.uri().to_string())}++ #[tracing::instrument(skip(self), fields(count = keys.len()))]+ pub async fn bulk_hard_delete_objects(&self, keys: Vec<String>) -> Vec<Result<()>> {+ if keys.is_empty() {+ return Vec::new();+ }++ // S3 delete_objects has a limit of 1000 keys per request+ let chunk_size = 1000;+ let mut all_results = Vec::with_capacity(keys.len());++ for chunk in keys.chunks(chunk_size) {+ let mut object_identifiers = Vec::new();+ for key in chunk {+ object_identifiers.push(+ aws_sdk_s3::types::ObjectIdentifier::builder()+ .key(key.clone())+ .build()+ .expect("failed to build ObjectIdentifier"),+ );+ }++ let delete_request = aws_sdk_s3::types::Delete::builder()+ .set_objects(Some(object_identifiers))+ .build()+ .context("failed to build Delete request");++ match delete_request {+ Ok(delete_req) => {+ match self+ .inner+ .delete_objects()+ .bucket(self.storage_bucket.clone())+ .delete(delete_req)+ .send()+ .await+ {+ Ok(output) => {+ // Build a map of error keys to their error messages+ let errors = output.errors();+ let error_map: std::collections::HashMap<&str, String> = errors+ .iter()+ .filter_map(|e| {+ e.key().map(|key| {+ let msg =+ e.message().unwrap_or("unknown error").to_string();+ (key, msg)+ })+ })+ .collect();++ // Log errors+ for error in errors {+ if let Some(key) = error.key() {+ tracing::warn!(+ key = key,+ error = ?error,+ "failed to delete object from S3"+ );+ }+ }++ // Add results in the same order as the input keys+ for key in chunk {+ if let Some(error_msg) = error_map.get(key.as_str()) {+ all_results.push(Err(anyhow::anyhow!(+ "failed to delete {}: {}",+ key,+ error_msg+ )));+ } else {+ all_results.push(Ok(()));+ }+ }+ }+ Err(e) => {+ tracing::error!(error = ?e, "failed to delete batch of objects from S3");+ // Add error for each key in this chunk+ for _ in chunk {+ all_results+ .push(Err(anyhow::anyhow!("batch delete failed: {}", e)));+ }+ }+ }+ }+ Err(e) => {+ let err_msg = e.to_string();+ tracing::error!(error = ?e, "failed to build delete request");+ for _ in chunk {+ all_results.push(Err(anyhow::anyhow!(+ "failed to build delete request: {}",+ err_msg+ )));+ }+ }+ }+ }++ all_results+ }}diff --git a/rust/cloud-storage/static_file_service_client/src/delete_file.rs b/rust/cloud-storage/static_file_service_client/src/delete_file.rsindex 6728f4bdff..e1b404202c 100644--- a/rust/cloud-storage/static_file_service_client/src/delete_file.rs+++ b/rust/cloud-storage/static_file_service_client/src/delete_file.rs@@ -1,5 +1,26 @@use super::StaticFileServiceClient;use anyhow::Result;+use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BulkDeleteRequest {+ pub file_ids: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DeleteResult {+ pub file_id: String,+ pub success: bool,+ pub error: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BulkDeleteResponse {+ pub total: usize,+ pub succeeded: usize,+ pub failed: usize,+ pub results: Vec<DeleteResult>,+}impl StaticFileServiceClient {/// delete file. propagate error upwards - some callers might see 404 as error, and some as success@@ -13,4 +34,20 @@ impl StaticFileServiceClient {Ok(response.status())}++ /// bulk delete files. returns detailed results for each file+ pub async fn bulk_delete_files(&self, file_ids: Vec<String>) -> Result<BulkDeleteResponse> {+ let request = BulkDeleteRequest { file_ids };++ let response = self+ .client+ .post(format!("{}/internal/file/bulk-delete", self.url))+ .json(&request)+ .send()+ .await?+ .error_for_status()?;++ let bulk_response = response.json::<BulkDeleteResponse>().await?;+ Ok(bulk_response)+ }}