Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix: support files/folders with the same name during bulk upload (#150)

gbirmanfa03e10f5d48
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index fd7ed77798..a30dd8e0a5 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -81,16 +81,26 @@ async fn main() -> anyhow::Result<()> {
);
// Create DynamoDB client with local endpoint for local environment
+ // If DynamoEndpointUrl is not set, use AWS DynamoDB even in local mode
let dynamo_db = if matches!(config.environment, Environment::Local) {
env_var!(
struct DynamoEndpointUrl;
);
- let local_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
- .region("us-east-1")
- .endpoint_url(DynamoEndpointUrl::new()?.to_string())
- .load()
- .await;
- aws_sdk_dynamodb::Client::new(&local_config)
+ match DynamoEndpointUrl::new() {
+ Ok(endpoint_url) => {
+ tracing::info!("Using local DynamoDB endpoint: {}", endpoint_url.as_ref());
+ let local_config = aws_config::defaults(aws_config::BehaviorVersion::latest())
+ .region("us-east-1")
+ .endpoint_url(endpoint_url.to_string())
+ .load()
+ .await;
+ aws_sdk_dynamodb::Client::new(&local_config)
+ }
+ Err(_) => {
+ tracing::info!("DynamoEndpointUrl not set, using AWS DynamoDB");
+ aws_sdk_dynamodb::Client::new(&aws_config)
+ }
+ }
} else {
aws_sdk_dynamodb::Client::new(&aws_config)
};
diff --git a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
index c451c8f0d6..5098301113 100644
--- a/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
+++ b/rust/cloud-storage/macro_db_client/src/projects/upload_folder/mod.rs
@@ -301,6 +301,7 @@ mod tests {
// Create files for the root folder
let root_file1 = FolderItem {
name: "rootFile1".to_string(),
+ full_name: "rootFile1.pdf".to_string(),
file_type: Some(FileType::Pdf),
sha: "sha123".to_string(),
relative_path: "/Root Test Folder".to_string(),
@@ -308,6 +309,7 @@ mod tests {
let root_file2 = FolderItem {
name: "rootFile2".to_string(),
+ full_name: "rootFile2.docx".to_string(),
file_type: Some(FileType::Docx),
sha: "sha456".to_string(),
relative_path: "/Root Test Folder".to_string(),
@@ -316,6 +318,7 @@ mod tests {
// Create a subfolder with its own files
let subfolder1_file1 = FolderItem {
name: "subfolder1File1".to_string(),
+ full_name: "subfolder1File1.txt".to_string(),
file_type: Some(FileType::Txt),
sha: "sha789".to_string(),
relative_path: "/Root Test Folder/subfolder1".to_string(),
@@ -323,6 +326,7 @@ mod tests {
let subfolder1_file2 = FolderItem {
name: "subfolder1File2".to_string(),
+ full_name: "subfolder1File2.pdf".to_string(),
file_type: Some(FileType::Pdf),
sha: "sha101".to_string(),
relative_path: "/Root Test Folder/subfolder1".to_string(),
@@ -331,6 +335,7 @@ mod tests {
// Create a sub-subfolder with its own files
let subsubfolder_file = FolderItem {
name: "deepNestedFile".to_string(),
+ full_name: "deepNestedFile.pdf".to_string(),
file_type: Some(FileType::Pdf),
sha: "sha202".to_string(),
relative_path: "/Root Test Folder/subfolder1/nested".to_string(),
@@ -345,6 +350,7 @@ mod tests {
// Create another subfolder with its own content
let subfolder2_file = FolderItem {
name: "subfolder2File".to_string(),
+ full_name: "subfolder2File.txt".to_string(),
file_type: Some(FileType::Txt),
sha: "sha303".to_string(),
relative_path: "/Root Test Folder/subfolder2".to_string(),
@@ -689,6 +695,7 @@ mod tests {
let mut current_folder = HashMap::new();
let deepest_file = FolderItem {
name: "deepestFile".to_string(),
+ full_name: "deepestFile.pdf".to_string(),
file_type: Some(FileType::Pdf),
sha: "sha_deepest".to_string(),
relative_path: "/Deep Nested Structure/level1/level2/level3/level4/level5".to_string(),
@@ -719,6 +726,7 @@ mod tests {
let level_file = FolderItem {
name: format!("file_level{}", level),
+ full_name: format!("file_level{}.txt", level),
file_type: Some(FileType::Txt),
sha: format!("sha_level{}", level),
relative_path: current_path.clone(),
@@ -761,6 +769,7 @@ mod tests {
// Add a file at the root level
let root_file = FolderItem {
name: "root_file".to_string(),
+ full_name: "root_file.txt".to_string(),
file_type: Some(FileType::Txt),
sha: "sha_root".to_string(),
relative_path: "/Deep Nested Structure".to_string(),
@@ -878,6 +887,7 @@ mod tests {
// Create a root file
let root_file = FolderItem {
name: "root_document".to_string(),
+ full_name: "root_document.pdf".to_string(),
file_type: Some(FileType::Pdf),
sha: "sha_root_doc".to_string(),
relative_path: "/Test FileSystem Structure".to_string(),
@@ -886,6 +896,7 @@ mod tests {
// Create a subfolder with a file
let subfolder_file = FolderItem {
name: "subfolder_document".to_string(),
+ full_name: "subfolder_document.txt".to_string(),
file_type: Some(FileType::Txt),
sha: "sha_subfolder_doc".to_string(),
relative_path: "/Test FileSystem Structure/subfolder".to_string(),
@@ -1174,4 +1185,164 @@ mod tests {
Ok(())
}
+
+ #[sqlx::test]
+ async fn test_files_and_folders_with_same_name(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ // This tests the scenario where you have both a file and folder with identical names
+ // Example: "Report.pdf" (file) and "Report" (folder)
+
+ let root_folder_name = "Conflicting Names Test";
+ let upload_request_id = "conflict_test_123";
+ let user_id = "macro|[email protected]";
+ let share_permission = create_test_permission(&pool).await?;
+
+ // Create a file called "Report.pdf"
+ let report_file = FolderItem {
+ name: "Report".to_string(),
+ full_name: "Report.pdf".to_string(),
+ file_type: Some(FileType::Pdf),
+ sha: "sha_report_file".to_string(),
+ relative_path: "/Conflicting Names Test".to_string(),
+ };
+
+ // Create a folder called "Report" with a file inside
+ let report_folder_file = FolderItem {
+ name: "contents".to_string(),
+ full_name: "contents.txt".to_string(),
+ file_type: Some(FileType::Txt),
+ sha: "sha_report_folder_contents".to_string(),
+ relative_path: "/Conflicting Names Test/Report".to_string(),
+ };
+
+ // Build the folder structure
+ let mut report_folder_content = HashMap::new();
+ report_folder_content.insert(
+ "contents.txt".to_string(),
+ FileSystemNode::File(report_folder_file),
+ );
+
+ let mut root_content = HashMap::new();
+ root_content.insert("Report.pdf".to_string(), FileSystemNode::File(report_file));
+ root_content.insert(
+ "Report".to_string(),
+ FileSystemNode::Folder(report_folder_content),
+ );
+
+ let folder_tree = FileSystemNode::Folder(root_content);
+
+ // Start transaction
+ let mut transaction = pool.begin().await?;
+
+ // Upload the folder structure
+ let UploadFolderWithIdsResponse {
+ file_system,
+ project_ids,
+ documents,
+ ..
+ } = upload_folder_with_ids(
+ &mut transaction,
+ user_id,
+ &share_permission,
+ &folder_tree,
+ root_folder_name,
+ upload_request_id,
+ None,
+ )
+ .await?;
+
+ // Commit the transaction
+ transaction.commit().await?;
+
+ // Verify the structure was created correctly
+ assert_eq!(
+ project_ids.len(),
+ 2,
+ "Expected 2 projects: root folder + Report subfolder"
+ );
+ assert_eq!(
+ documents.len(),
+ 2,
+ "Expected 2 documents: Report.pdf file + contents.txt inside Report folder"
+ );
+
+ // Verify the file system structure
+ match &file_system {
+ FileSystemNodeWithIds::File { .. } => {
+ panic!("Expected root to be a folder");
+ }
+ FileSystemNodeWithIds::Folder { content, .. } => {
+ // Should have both "Report.pdf" (file) and "Report" (folder)
+ assert_eq!(content.len(), 2, "Root should have 2 items");
+
+ // Verify the file exists
+ let report_file_node = content
+ .get("Report.pdf")
+ .expect("Report.pdf file should exist");
+ match report_file_node {
+ FileSystemNodeWithIds::File { item, document_id } => {
+ assert_eq!(item.name, "Report");
+ assert_eq!(item.full_name, "Report.pdf");
+ assert_eq!(item.file_type, Some(FileType::Pdf));
+
+ // Verify document was created
+ let doc = documents
+ .iter()
+ .find(|d| &d.document_id == document_id)
+ .expect("Report.pdf document should exist in documents list");
+ assert_eq!(doc.document_name, "Report");
+ }
+ _ => panic!("Report.pdf should be a file node"),
+ }
+
+ // Verify the folder exists
+ let report_folder_node = content.get("Report").expect("Report folder should exist");
+ match report_folder_node {
+ FileSystemNodeWithIds::Folder {
+ content: folder_content,
+ project_id,
+ } => {
+ assert_eq!(folder_content.len(), 1, "Report folder should have 1 file");
+
+ // Verify the file inside the folder
+ let contents_file = folder_content
+ .get("contents.txt")
+ .expect("contents.txt should exist in Report folder");
+ match contents_file {
+ FileSystemNodeWithIds::File { item, document_id } => {
+ assert_eq!(item.name, "contents");
+ assert_eq!(item.full_name, "contents.txt");
+ assert_eq!(item.relative_path, "/Conflicting Names Test/Report");
+
+ // Verify document was created
+ let doc = documents
+ .iter()
+ .find(|d| &d.document_id == document_id)
+ .expect("contents.txt document should exist");
+ assert_eq!(doc.document_name, "contents");
+ }
+ _ => panic!("contents.txt should be a file node"),
+ }
+
+ // Verify the folder has a project_id
+ assert!(
+ project_ids.contains(project_id),
+ "Report folder project_id should be in the project list"
+ );
+ }
+ _ => panic!("Report should be a folder node"),
+ }
+ }
+ }
+
+ // Clean up
+ let mut cleanup_tx = pool.begin().await?;
+ for project_id in &project_ids {
+ let _ = sqlx::query!(r#"DELETE FROM "Project" WHERE id = $1"#, project_id)
+ .execute(&mut *cleanup_tx)
+ .await?;
+ }
+ cleanup_tx.commit().await?;
+
+ Ok(())
+ }
}
diff --git a/rust/cloud-storage/model/src/folder.rs b/rust/cloud-storage/model/src/folder.rs
index c4029294eb..4eab3b2fda 100644
--- a/rust/cloud-storage/model/src/folder.rs
+++ b/rust/cloud-storage/model/src/folder.rs
@@ -51,6 +51,8 @@ pub struct UploadFolderResponseData {
pub struct FolderItem {
/// The name of the file, without the extension
pub name: String,
+ /// The full OS name of the file for deduplication
+ pub full_name: String,
/// The file type of the file
#[serde(skip_serializing_if = "Option::is_none")]
pub file_type: Option<FileType>,
@@ -108,7 +110,7 @@ impl FileSystemNode {
.collect();
// Add the file name as the last component
- path_components.push(&item.name);
+ path_components.push(&item.full_name);
let mut current_node = &mut root;
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip
index c21ab7d5c8..2280dcde56 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_handler/bootstrap.zip differ
diff --git a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip
index 0f314a1473..db57b26ee7 100644
Binary files a/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip and b/rust/cloud-storage/target/lambda/upload_extractor_lambda_trigger/bootstrap.zip differ
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/event.json b/rust/cloud-storage/upload_extractor_lambda_handler/event.json
index 08e75747c7..b39e906617 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/event.json
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/event.json
@@ -3,7 +3,7 @@
{
"messageId": "91ccd6d4-ea77-45a7-8951-faaa492961a8",
"receiptHandle": "AQEBhmGHyLbsQ6pS7yIM+t2p1I7KNcgwwM6Eh94ADlyKNj3XBnnisbL7WZxsfp5nBzbOPU3L/BGo6c5235TKPOlAEXDow4esJxPvmMjDc7//VPJBnXmOav4a9SCW4X8Udy5/yaMiVhM/UrgI5qSlECCQKpcj4nsk3+MrIu2E/PRQ6gawxOTax26zyt2RuEVSPnZvUDLmEcRzZWCAwnnLuQTLKBWynyLm7erMJ2Xg3aFbcCR+wK49PGxaMSr5qdP4pkMj3ACNN0qbbNW/ru64ss30bQ+a8czMqpnMudtAmcrH76l5S+mMdu0ri+4zs9gXiTee8EJ7fkNCfxgUmG1YS9cFCm2e2/MerkLWqqUrq2rnjPtji06d/0xf/K+DoDQtAmhzFCU99zU8zxxU42CCLY5I1w==",
- "body": "{\"ExtractZip\":{\"upload_request_id\":\"d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc\",\"key\":\"extract/d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc\",\"user_id\":\"macro|[email protected]\",\"name\":\"Folder Name Override\"}}",
+ "body": "{\"ExtractZip\":{\"upload_request_id\":\"d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc\",\"key\":\"extract/d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc\",\"user_id\":\"macro|[email protected]\",\"name\":\"Folder Name Override\"}}",
"md5OfBody": "60cb940e6637053d88b88b36366f9130",
"md5OfMessageAttributes": "705fb11e31dc5721b24901f9eb1d3305",
"attributes": {
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/justfile b/rust/cloud-storage/upload_extractor_lambda_handler/justfile
index 8d2fc49479..b06fca326a 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/justfile
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/justfile
@@ -9,6 +9,6 @@ build:
watch:
cargo lambda watch -F local
-# invoke the lambda locally after watch-local is running
+# invoke the lambda locally after watch is running
invoke:
cargo lambda invoke {{lambda_name}} --data-file event.json
diff --git a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
index 374f2c8728..268144d85f 100644
--- a/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
+++ b/rust/cloud-storage/upload_extractor_lambda_handler/src/main.rs
@@ -207,8 +207,9 @@ async fn process_zipped_s3_object(
if cfg!(feature = "local") {
tracing::info!("using local zip file, remove local feature to download s3 object");
- // let file_path = format!("/my/path/to/file.zip");
- let file_path = "/Users/gabrielbirman/Development/macro/TestZipExtract.zip";
+ // Update this path to your zip file location
+ let file_path = std::env::var("LOCAL_ZIP_PATH").unwrap();
+ tracing::info!("Loading local zip file from: {}", file_path);
let file = File::open(file_path).await?;
let mut body = tokio::io::BufReader::new(file);
@@ -258,6 +259,7 @@ async fn process_zipped_s3_object(
.get_project_id()
.ok_or_else(|| anyhow::anyhow!("No project found for root folder"))?;
+ tracing::debug!("returned file system: {:?}", file_system);
tracing::debug!("root project id: {:?}", root_project_id);
let destination_map = upload_result.destination_map;
@@ -274,21 +276,6 @@ async fn process_zipped_s3_object(
tracing::debug!("Request status: {:?}", request_status);
return Ok((request_status, root_project_id.clone()));
-
- // match request_status {
- // UploadFolderStatus::Completed => {
- // return Ok((UploadFolderStatus::Completed, Some(root_project_id.clone())));
- // }
- // _ => {
- // dynamodb_client
- // .bulk_upload
- // .update_bulk_upload_request_status(request_id, request_status.clone(), None, None)
- // .await
- // .inspect_err(|e| tracing::error!("Failed to update bulk upload status: {:?}", e))
- // .ok();
- // return Ok((request_status, None));
- // }
- // }
}
#[tracing::instrument(skip_all, fields(request_id=request_id))]
@@ -543,6 +530,7 @@ async fn build_file_system(extract_dir: &Path) -> Result<Vec<FolderItem>, Error>
Ok(FolderItem {
name: file_name.to_string(),
+ full_name: full_name.to_string(),
file_type,
relative_path: relative_path_without_filename,
sha,
@@ -588,8 +576,8 @@ async fn main() -> Result<(), Error> {
let upload_staging_bucket =
std::env::var("UPLOAD_BUCKET_NAME").context("UPLOAD_STAGING_BUCKET must be set")?;
- let dss_auth_key = std::env::var("DSS_AUTH_KEY")
- .context("DSS_AUTH_KEY must be set")
+ let internal_api_secret_key = std::env::var("INTERNAL_API_SECRET_KEY")
+ .context("INTERNAL_API_SECRET_KEY must be set")
.unwrap();
let dss_url = std::env::var("DSS_URL").context("DSS_URL must be set")?;
let dynamo_table_name =
@@ -601,11 +589,12 @@ async fn main() -> Result<(), Error> {
let config = aws_config::from_env().region(region_provider).load().await;
let s3_client = S3Client::new(&config);
- let dss_client = DocumentStorageServiceClient::new(dss_auth_key.clone(), dss_url);
+ let dss_client = DocumentStorageServiceClient::new(internal_api_secret_key.clone(), dss_url);
let dynamodb_client = DynamodbClient::new(&config, Some(dynamo_table_name.clone()));
- let conn_gateway_client = ConnectionGatewayClient::new(dss_auth_key, connection_gateway_url);
+ let conn_gateway_client =
+ ConnectionGatewayClient::new(internal_api_secret_key, connection_gateway_url);
let shared_s3_client = Arc::new(s3_client);
let shared_dss_client = Arc::new(dss_client);
@@ -701,6 +690,7 @@ mod tests {
let extract_dir = PathBuf::from("/tmp/extract");
let item = FolderItem {
name: "document".to_string(),
+ full_name: "document.pdf".to_string(),
file_type: Some(FileType::Pdf),
relative_path: "folder/subfolder".to_string(),
sha: "abcd1234".to_string(),
@@ -718,6 +708,7 @@ mod tests {
let extract_dir = PathBuf::from("/tmp/extract");
let item = FolderItem {
name: "document".to_string(),
+ full_name: "document.tar.gz".to_string(),
file_type: Some(FileType::TarGz),
relative_path: "folder/subfolder".to_string(),
sha: "abcd1234".to_string(),
@@ -735,6 +726,7 @@ mod tests {
let extract_dir = PathBuf::from("/tmp/extract");
let item = FolderItem {
name: "config".to_string(),
+ full_name: "config".to_string(),
file_type: None,
relative_path: "settings".to_string(),
sha: "efgh5678".to_string(),
@@ -749,6 +741,7 @@ mod tests {
let extract_dir = PathBuf::from("/tmp/extract");
let item = FolderItem {
name: "test.1.5.5".to_string(),
+ full_name: "test.1.5.5.tar.gz".to_string(),
file_type: Some(FileType::TarGz),
relative_path: "settings".to_string(),
sha: "efgh5678".to_string(),
@@ -766,6 +759,7 @@ mod tests {
let extract_dir = PathBuf::from("/tmp/extract");
let item = FolderItem {
name: "root_file".to_string(),
+ full_name: "root_file.txt".to_string(),
file_type: Some(FileType::Txt),
relative_path: "".to_string(),
sha: "ijkl9012".to_string(),
diff --git a/rust/cloud-storage/upload_extractor_lambda_trigger/justfile b/rust/cloud-storage/upload_extractor_lambda_trigger/justfile
index 7e82e27780..dd63405190 100644
--- a/rust/cloud-storage/upload_extractor_lambda_trigger/justfile
+++ b/rust/cloud-storage/upload_extractor_lambda_trigger/justfile
@@ -9,6 +9,38 @@ build:
watch:
cargo lambda watch
-# invoke the lambda locally after watch-local is running
+# invoke the lambda locally after watch is running
invoke:
cargo lambda invoke {{lambda_name}} --data-file event.json
+
+# Add a bulk upload request to DynamoDB (AWS)
+add_bulk_upload_request request_id="d50676e2-0a12-4c62-bc07-4b1cb6d8e9bc" user_id="macro|[email protected]" name="Folder Name Override" parent_id="":
+ #!/usr/bin/env bash
+ set -euo pipefail
+
+ # Load DYNAMODB_TABLE from .env if it exists
+ if [ -f upload_extractor_lambda_trigger/.env ]; then
+ export $(grep -v '^#' upload_extractor_lambda_trigger/.env | grep DYNAMODB_TABLE | xargs)
+ fi
+ TABLE_NAME="${DYNAMODB_TABLE:-bulk-upload-test}"
+
+ NOW=$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")
+ KEY="extract/{{ request_id }}"
+ PK="REQUEST#{{ request_id }}"
+ SK="META"
+
+ # Build JSON item
+ ITEM='{"PK":{"S":"'$PK'"},"SK":{"S":"'$SK'"},"request_id":{"S":"{{ request_id }}"},"user_id":{"S":"{{ user_id }}"},"key":{"S":"'$KEY'"},"status":{"S":"pending"},"created_at":{"S":"'$NOW'"},"updated_at":{"S":"'$NOW'"},"entity_type":{"S":"BulkUploadZipRequest"}}'
+
+ # Add optional fields using jq if provided
+ if [ -n "{{ name }}" ]; then
+ ITEM=$(echo "$ITEM" | jq '. + {"name":{"S":"{{ name }}"}}')
+ fi
+
+ if [ -n "{{ parent_id }}" ]; then
+ ITEM=$(echo "$ITEM" | jq '. + {"parent_id":{"S":"{{ parent_id }}"}}')
+ fi
+
+ aws dynamodb put-item \
+ --table-name "$TABLE_NAME" \
+ --item "$ITEM"