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(ownership): chat register chats in the entity table (#6425)
Will Hutchinson7fd7b1dd1771
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex ab4e01bd1b..c31d8892fe 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -73,6 +73,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -178,6 +180,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -288,6 +292,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -426,6 +432,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -766,6 +774,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -969,6 +979,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -1145,6 +1157,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/favorites","crates/filter_ast","crates/foreign_entity",@@ -1600,6 +1614,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -1773,6 +1789,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -2041,6 +2059,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/favorites","crates/filter_ast","crates/foreign_entity",@@ -2310,6 +2330,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -2533,10 +2555,17 @@"crates/workspace-hack"],"delete_chat_handler": [+ "crates/bot_id",+ "crates/cowlike",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/macro_entrypoint","crates/macro_env","crates/macro_env_var",+ "crates/macro_user_id","crates/macro_uuid",+ "crates/model-entity",+ "crates/model_owner","crates/workspace-hack","services/delete_chat_handler"],@@ -2573,6 +2602,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -2685,6 +2716,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -2831,6 +2864,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/favorites","crates/filter_ast","crates/foreign_entity",@@ -3207,6 +3242,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -3576,6 +3613,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -3797,6 +3836,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -4388,6 +4429,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -4499,6 +4542,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/favorites","crates/filter_ast","crates/foreign_entity",@@ -4748,6 +4793,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -4893,6 +4940,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -5269,6 +5318,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -5341,6 +5392,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -5547,6 +5600,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -5688,6 +5743,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -6303,6 +6360,8 @@"crates/document_sub_type","crates/email_formatting","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",@@ -6969,6 +7028,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -7100,6 +7161,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -7214,6 +7277,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -7431,6 +7496,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/fusionauth",@@ -7918,6 +7985,8 @@"crates/entity_access_db_utils","crates/entity_access_management","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/foreign_entity","crates/frecency",@@ -8514,6 +8583,8 @@"crates/cowlike","crates/document_sub_type","crates/entity_access_db_utils",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/genai_telemetry","crates/harness_id","crates/harness_token",diff --git a/Cargo.lock b/Cargo.lockindex ed71bdf469..23e4b995c6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -3487,6 +3487,7 @@ dependencies = ["entity_access_db_utils","entity_access_management","entity_mutation",+ "entity_registry_db_utils","futures","http-body-util","macro_authorization",@@ -3497,6 +3498,7 @@ dependencies = ["macro_uuid","model","model-entity",+ "model_owner","models_entity_access_management","models_permissions","non_empty",@@ -4887,7 +4889,9 @@ version = "0.1.0"dependencies = ["anyhow","aws_lambda_events",+ "entity_registry_db_utils","lambda_runtime",+ "macro_db_migrator","macro_entrypoint","macro_env_var","macro_uuid",@@ -9942,12 +9946,14 @@ dependencies = ["chrono","document_sub_type","entity_access_db_utils",+ "entity_registry_db_utils","futures","macro_user_id","macro_uuid","model","model-entity","model_file_type",+ "model_owner","models_dcs","models_entity_access_management","models_opensearch",diff --git a/crates/chat/Cargo.toml b/crates/chat/Cargo.tomlindex 8d2bb34d47..63e557db0e 100644--- a/crates/chat/Cargo.toml+++ b/crates/chat/Cargo.toml@@ -20,7 +20,9 @@ inbound = []outbound = ["dep:entity_access_db_utils",+ "dep:entity_registry_db_utils","dep:macro_uuid",+ "dep:model_owner","dep:share_permission_db_utils","dep:sqlx","ports",@@ -37,6 +39,7 @@ attachment = { path = "../attachment" }chrono = { workspace = true }entity_access = { path = "../entity_access", default-features = false }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }entity_access_management = { path = "../entity_access_management", default-features = false, features = ["ports",] }@@ -47,6 +50,7 @@ macro_user_id = { path = "../macro_user_id" }model = { path = "../model" }non_empty = { path = "../non_empty" }model-entity = { path = "../model-entity" }+model_owner = { path = "../model_owner", optional = true }models_entity_access_management = { path = "../models_entity_access_management", default-features = false }models_permissions = { path = "../models_permissions" }rootcause = { workspace = true }diff --git a/crates/chat/src/outbound/postgres.rs b/crates/chat/src/outbound/postgres.rsindex 0d2e50e212..613c76a344 100644--- a/crates/chat/src/outbound/postgres.rs+++ b/crates/chat/src/outbound/postgres.rs@@ -113,9 +113,10 @@ impl ChatRepo for PgChatRepo {.await.map_err(to_chat_err)?;+ let chat_uuid = macro_uuid::string_to_uuid(&chat_id).map_err(to_chat_err)?;entity_access_db_utils::insert_entity_access_row(&mut tx,- ¯o_uuid::string_to_uuid(&chat_id).unwrap(),+ &chat_uuid,entity_access_db_utils::EntityType::Chat,user_id.as_ref(),entity_access_db_utils::EntityAccessSourceType::User,@@ -124,6 +125,17 @@ impl ChatRepo for PgChatRepo {.await.map_err(|e| ChatErr::Unknown(e.into()))?;+ entity_registry_db_utils::insert_entity(+ &mut tx,+ entity_registry_db_utils::NewEntityRecord::new(+ chat_uuid,+ entity_registry_db_utils::RegisteredEntityType::Chat,+ model_owner::Owner::User(user_id),+ ),+ )+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+tx.commit().await.map_err(|e| {tracing::error!(error=?e, "create_chat transaction error");ChatErr::Unknown(e.into())@@ -217,9 +229,10 @@ impl ChatRepo for PgChatRepo {.await.map_err(to_chat_err)?;+ let chat_uuid = macro_uuid::string_to_uuid(&chat_id).map_err(to_chat_err)?;entity_access_db_utils::insert_entity_access_row(&mut tx,- ¯o_uuid::string_to_uuid(&chat_id).unwrap(),+ &chat_uuid,entity_access_db_utils::EntityType::Chat,user_id.as_ref(),entity_access_db_utils::EntityAccessSourceType::User,@@ -232,6 +245,17 @@ impl ChatRepo for PgChatRepo {.await.map_err(to_chat_err)?;+ entity_registry_db_utils::insert_entity(+ &mut tx,+ entity_registry_db_utils::NewEntityRecord::new(+ chat_uuid,+ entity_registry_db_utils::RegisteredEntityType::Chat,+ model_owner::Owner::User(user_id),+ ),+ )+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+tx.commit().await.map_err(|e| {tracing::error!(error=?e, "copy_chat transaction error");ChatErr::Unknown(e.into())diff --git a/crates/chat/src/outbound/postgres/queries/permanently_delete_chat.rs b/crates/chat/src/outbound/postgres/queries/permanently_delete_chat.rsindex 4fe51e0a72..86d751c591 100644--- a/crates/chat/src/outbound/postgres/queries/permanently_delete_chat.rs+++ b/crates/chat/src/outbound/postgres/queries/permanently_delete_chat.rs@@ -1,9 +1,6 @@-//! Permanently delete a chat and all associated data.-use model_entity::EntityType;use sqlx::{Postgres, Transaction};-/// Hard-delete a chat: remove pins, history, permissions, access, and the chat row.#[tracing::instrument(err, skip(tx))]pub(crate) async fn permanently_delete_chat(tx: &mut Transaction<'_, Postgres>,@@ -23,7 +20,6 @@ pub(crate) async fn permanently_delete_chat(.execute(tx.as_mut()).await?;- // Delete share permission (cascades ChatPermission)sqlx::query!(r#"DELETE FROM "SharePermission"@@ -38,9 +34,10 @@ pub(crate) async fn permanently_delete_chat(.execute(tx.as_mut()).await?;+ let chat_uuid = macro_uuid::string_to_uuid(chat_id)?;sqlx::query!(r#"DELETE FROM "entity_access" WHERE "entity_id" = $1 AND "entity_type" = $2"#,- macro_uuid::string_to_uuid(chat_id).unwrap(),+ chat_uuid,EntityType::Chat.as_ref(),).execute(tx.as_mut())@@ -50,5 +47,7 @@ pub(crate) async fn permanently_delete_chat(.execute(tx.as_mut()).await?;+ entity_registry_db_utils::delete_entity(tx, chat_uuid).await?;+Ok(())}diff --git a/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs b/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rsindex 318cce0c6a..59e81551c7 100644--- a/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs+++ b/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs@@ -1,9 +1,5 @@-//! Revert a soft-deleted chat.-use anyhow::Context;-/// Clear `deleted_at`, restore the chat to user history, and detach from a-/// deleted project if necessary.#[tracing::instrument(err, skip(tx))]pub(crate) async fn revert_delete_chat(tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,@@ -24,6 +20,9 @@ pub(crate) async fn revert_delete_chat(.await.context("unable to update chat")?;+ let chat_uuid = macro_uuid::string_to_uuid(chat_id)?;+ entity_registry_db_utils::clear_deleted(tx, chat_uuid).await?;+sqlx::query!(r#"INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")diff --git a/crates/chat/src/outbound/postgres/queries/soft_delete_chat.rs b/crates/chat/src/outbound/postgres/queries/soft_delete_chat.rsindex 8fc1bfdcf4..758b2d8e79 100644--- a/crates/chat/src/outbound/postgres/queries/soft_delete_chat.rs+++ b/crates/chat/src/outbound/postgres/queries/soft_delete_chat.rs@@ -1,8 +1,6 @@-//! Soft-delete a chat.-+use chrono::Utc;use sqlx::{Postgres, Transaction};-/// Soft-delete a chat: remove pins and history, then set `deletedAt`.#[tracing::instrument(err, skip(tx))]pub(crate) async fn soft_delete_chat(tx: &mut Transaction<'_, Postgres>,@@ -29,5 +27,8 @@ pub(crate) async fn soft_delete_chat(.execute(tx.as_mut()).await?;+ let chat_uuid = macro_uuid::string_to_uuid(chat_id)?;+ entity_registry_db_utils::mark_deleted(tx, chat_uuid, Utc::now()).await?;+Ok(())}diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rsindex 804ff1fd5e..1ffb3cbe2b 100644--- a/crates/chat/src/outbound/postgres/test.rs+++ b/crates/chat/src/outbound/postgres/test.rs@@ -10,6 +10,7 @@ use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::{LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,};+use sqlx::postgres::PgRow;use sqlx::{Pool, Postgres, Row};use super::PgChatRepo;@@ -416,6 +417,197 @@ async fn create_chat_creates_user_item_access(pool: Pool<Postgres>) {);}+async fn fetch_entity_row(pool: &Pool<Postgres>, chat_id: &str) -> PgRow {+ sqlx::query(+ r#"+ SELECT+ owner_type::text AS owner_type,+ owner_id,+ entity_type,+ deleted_at+ FROM entity+ WHERE id = $1+ "#,+ )+ .bind(macro_uuid::string_to_uuid(chat_id).unwrap())+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_registers_entity_row(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Entity Chat".to_string(),+ project_id: None,+ },+ default_share_permission(),+ )+ .await+ .unwrap();++ let row = fetch_entity_row(&pool, &chat_id).await;+ assert_eq!(row.get::<String, _>("owner_type"), "user");+ assert_eq!(row.get::<String, _>("owner_id"), "macro|[email protected]");+ assert_eq!(row.get::<String, _>("entity_type"), "chat");+ assert_eq!(+ row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at"),+ None+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn delete_chat_marks_entity_deleted(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Entity Soft Delete").await;++ repo.delete(&chat_id).await.unwrap();++ let row = fetch_entity_row(&pool, &chat_id).await;+ assert!(+ row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at")+ .is_some()+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn revert_delete_clears_entity_deleted_at(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Entity Restore").await;++ repo.delete(&chat_id).await.unwrap();+ repo.revert_delete(&chat_id, None).await.unwrap();++ let row = fetch_entity_row(&pool, &chat_id).await;+ assert_eq!(+ row.get::<Option<chrono::DateTime<Utc>>, _>("deleted_at"),+ None+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn permanently_delete_chat_removes_entity_row(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Entity Perm Delete").await;++ repo.permanently_delete(&chat_id).await.unwrap();++ let count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM entity WHERE id = $1"#)+ .bind(macro_uuid::string_to_uuid(&chat_id).unwrap())+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn copy_chat_registers_entity_row_for_source_and_copy(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let source_id = repo+ .create(+ user_id.clone(),+ CreateChatArgs {+ name: "Entity Source".to_string(),+ project_id: None,+ },+ default_share_permission(),+ )+ .await+ .unwrap();++ let copied_id = repo+ .copy_chat(+ user_id,+ &source_id,+ CopyChatArgs {+ name: "Entity Copy".to_string(),+ project_id: None,+ },+ default_share_permission(),+ )+ .await+ .unwrap();++ assert_ne!(source_id, copied_id);++ let source_row = fetch_entity_row(&pool, &source_id).await;+ let copy_row = fetch_entity_row(&pool, &copied_id).await;+ assert_eq!(source_row.get::<String, _>("entity_type"), "chat");+ assert_eq!(copy_row.get::<String, _>("entity_type"), "chat");+ assert_eq!(source_row.get::<String, _>("owner_type"), "user");+ assert_eq!(copy_row.get::<String, _>("owner_type"), "user");+ assert_eq!(+ source_row.get::<String, _>("owner_id"),+ "macro|[email protected]"+ );+ assert_eq!(+ copy_row.get::<String, _>("owner_id"),+ "macro|[email protected]"+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn delete_restore_and_purge_succeed_without_entity_row(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Legacy Chat").await;+ let chat_uuid = macro_uuid::string_to_uuid(&chat_id).unwrap();++ sqlx::query(r#"DELETE FROM entity WHERE id = $1"#)+ .bind(chat_uuid)+ .execute(&pool)+ .await+ .unwrap();++ repo.delete(&chat_id).await.unwrap();+ repo.revert_delete(&chat_id, None).await.unwrap();+ repo.permanently_delete(&chat_id).await.unwrap();++ let chat_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(chat_count.0, 0);++ let entity_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM entity WHERE id = $1"#)+ .bind(chat_uuid)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(entity_count.0, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "fixtures", scripts("users"))diff --git a/crates/macro_db_client/Cargo.toml b/crates/macro_db_client/Cargo.tomlindex d17ad26f2e..207c5b7d33 100644--- a/crates/macro_db_client/Cargo.toml+++ b/crates/macro_db_client/Cargo.toml@@ -18,11 +18,13 @@ cached = { workspace = true }chrono = { workspace = true }document_sub_type = { path = "../document_sub_type" }entity_access_db_utils = { path = "../entity_access_db_utils" }+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils" }futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }model = { path = "../model" }model-entity = { path = "../model-entity" }+model_owner = { path = "../model_owner" }model_file_type = { path = "../model_file_type" }models_dcs = { path = "../models_dcs" }models_entity_access_management = { path = "../models_entity_access_management", features = [diff --git a/crates/macro_db_client/src/dcs/create_chat.rs b/crates/macro_db_client/src/dcs/create_chat.rsindex e2a7aa626d..d77f6b08ff 100644--- a/crates/macro_db_client/src/dcs/create_chat.rs+++ b/crates/macro_db_client/src/dcs/create_chat.rs@@ -7,7 +7,6 @@ use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use sqlx::{Pool, Postgres};-// this has types that should not become dependencies of macro_db_client#[tracing::instrument(skip(db))]#[expect(clippy::too_many_arguments, reason = "too annoying to fix")]pub async fn create_chat_v2(@@ -22,8 +21,6 @@ pub async fn create_chat_v2(is_persistent: bool,) -> anyhow::Result<String> {let mut transaction: sqlx::Transaction<'_, Postgres> = db.begin().await?;- // move this as a standalone query to macro_db_client/dcs/create_empty_chat- // create a row in chat tablelet chat = sqlx::query_as!(IDWithTimeStamps,r#"@@ -49,7 +46,6 @@ pub async fn create_chat_v2(}).collect::<Vec<_>>();- // create row in chat permissionscrate::share_permission::create::create_chat_permission(&mut transaction,&chat.id,@@ -57,18 +53,17 @@ pub async fn create_chat_v2().await?;- // trackingupsert_user_history(&mut transaction, user_id.copied(), &chat.id, "chat").await?;upsert_item_last_accessed(&mut transaction, &chat.id, "chat").await?;- // add attachment rowsfor attachment in attachments {append_attachment_to_chat(&mut transaction, attachment).await?;}+ let chat_uuid = macro_uuid::string_to_uuid(&chat.id)?;entity_access_db_utils::insert_entity_access_row(&mut transaction,- ¯o_uuid::string_to_uuid(&chat.id).unwrap(),+ &chat_uuid,EntityType::Chat,user_id.as_ref(),entity_access_db_utils::EntityAccessSourceType::User,@@ -76,6 +71,16 @@ pub async fn create_chat_v2().await?;+ entity_registry_db_utils::insert_entity(+ &mut transaction,+ entity_registry_db_utils::NewEntityRecord::new(+ chat_uuid,+ entity_registry_db_utils::RegisteredEntityType::Chat,+ model_owner::Owner::User(user_id),+ ),+ )+ .await?;+transaction.commit().await.map_err(|e| {tracing::error!(error=?e, "create_chat transaction error");anyhow::Error::from(e)diff --git a/crates/macro_db_client/src/dcs/create_empty_chat.rs b/crates/macro_db_client/src/dcs/create_empty_chat.rsdeleted file mode 100644index 0782841848..0000000000--- a/crates/macro_db_client/src/dcs/create_empty_chat.rs+++ /dev/null@@ -1,30 +0,0 @@-use model::IDWithTimeStamps;-use sqlx::{Postgres, Transaction};--#[tracing::instrument(skip(transaction))]-pub async fn create_empty_chat(- transaction: &mut Transaction<'_, Postgres>,- user_id: &str,- name: &str,- model: &str,- project_id: Option<&str>,- is_persistent: bool,-) -> anyhow::Result<IDWithTimeStamps> {- let chat = sqlx::query_as!(- IDWithTimeStamps,- r#"- INSERT INTO "Chat" ("userId", name, model, "projectId", "isPersistent")- VALUES ($1, $2, $3, $4, $5)- RETURNING id, "createdAt"::timestamptz as created_at, "updatedAt"::timestamptz as updated_at;- "#,- &user_id,- &name,- model,- project_id,- is_persistent- )- .fetch_one(&mut **transaction)- .await?;-- Ok(chat)-}diff --git a/crates/macro_db_client/src/dcs/mod.rs b/crates/macro_db_client/src/dcs/mod.rsindex bba389fc8a..730b906f43 100644--- a/crates/macro_db_client/src/dcs/mod.rs+++ b/crates/macro_db_client/src/dcs/mod.rs@@ -5,7 +5,6 @@pub mod append_attachment_to_chat;pub mod copy_messages;pub mod create_chat_message;-pub mod create_empty_chat;pub mod delete_chat_message;pub mod get_attachment;pub mod get_attachments_for_message;diff --git a/services/delete_chat_handler/Cargo.toml b/services/delete_chat_handler/Cargo.tomlindex 49f75561e4..49cee922dc 100644--- a/services/delete_chat_handler/Cargo.toml+++ b/services/delete_chat_handler/Cargo.toml@@ -10,9 +10,14 @@ aws_lambda_events = { workspace = true, features = ["sqs"] }lambda_runtime = { workspace = true }macro_entrypoint = { path = "../../crates/macro_entrypoint" }macro_env_var = { path = "../../crates/macro_env_var" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }macro_uuid = { path = "../../crates/macro_uuid" }sqlx = { workspace = true }tokio = { workspace = true }tracing = { workspace = true }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }+[dev-dependencies]+macro_db_migrator = { path = "../../crates/macro_db_migrator" }+tokio = { workspace = true }+diff --git a/services/delete_chat_handler/src/service/db/delete_chat.rs b/services/delete_chat_handler/src/service/db/delete_chat.rsindex 59d0b40f82..b4356644bf 100644--- a/services/delete_chat_handler/src/service/db/delete_chat.rs+++ b/services/delete_chat_handler/src/service/db/delete_chat.rs@@ -1,7 +1,6 @@pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()> {let mut transaction = db.begin().await?;- // Delete pinssqlx::query!(r#"DELETE FROM "Pin" WHERE "pinnedItemId" = $1 AND "pinnedItemType" = $2@@ -12,7 +11,6 @@ pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()>.execute(&mut *transaction).await?;- // Delete user historysqlx::query!(r#"DELETE FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = $2@@ -23,7 +21,6 @@ pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()>.execute(&mut *transaction).await?;- // Get share permission if presentlet share_permission: Option<String> = sqlx::query!(r#"SELECT "sharePermissionId" as share_permission_id@@ -36,7 +33,6 @@ pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()>.await?;if let Some(share_permission) = share_permission {- // Delete share permissionsqlx::query!(r#"DELETE FROM "SharePermission" WHERE id = $1"#,@@ -46,12 +42,13 @@ pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()>.await?;}+ let chat_uuid = macro_uuid::string_to_uuid(chat_id)?;sqlx::query!(r#"DELETE FROM "entity_access"WHERE "entity_id" = $1 AND "entity_type" = $2"#,- macro_uuid::string_to_uuid(chat_id).unwrap(),+ chat_uuid,"chat",).execute(&mut *transaction)@@ -66,7 +63,12 @@ pub async fn delete_chat(db: sqlx::PgPool, chat_id: &str) -> anyhow::Result<()>.execute(&mut *transaction).await?;+ entity_registry_db_utils::delete_entity(&mut transaction, chat_uuid).await?;+transaction.commit().await?;Ok(())}++#[cfg(test)]+mod test;diff --git a/services/delete_chat_handler/src/service/db/delete_chat/fixtures/users.sql b/services/delete_chat_handler/src/service/db/delete_chat/fixtures/users.sqlnew file mode 100644index 0000000000..830de09a64--- /dev/null+++ b/services/delete_chat_handler/src/service/db/delete_chat/fixtures/users.sql@@ -0,0 +1,8 @@+INSERT INTO public."Organization" ("id","name")+(SELECT 1, 'organization-one');++INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")+(SELECT 'a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_test');++INSERT INTO public."User" ("id","email","stripeCustomerId","macro_user_id")+(SELECT 'macro|[email protected]', '[email protected]','stripe_test','a1111111-1111-1111-1111-111111111111');diff --git a/services/delete_chat_handler/src/service/db/delete_chat/test.rs b/services/delete_chat_handler/src/service/db/delete_chat/test.rsnew file mode 100644index 0000000000..e091a14474--- /dev/null+++ b/services/delete_chat_handler/src/service/db/delete_chat/test.rs@@ -0,0 +1,52 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++use super::delete_chat;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn delete_chat_removes_entity_row(pool: Pool<Postgres>) {+ let chat_id: String = sqlx::query_scalar!(+ r#"+ INSERT INTO "Chat" ("userId", name)+ VALUES ($1, $2)+ RETURNING id+ "#,+ "macro|[email protected]",+ "Retention Chat",+ )+ .fetch_one(&pool)+ .await+ .unwrap();++ let chat_uuid = macro_uuid::string_to_uuid(&chat_id).unwrap();+ sqlx::query(+ r#"+ INSERT INTO entity (id, entity_type, owner_type, owner_id)+ VALUES ($1, 'chat', 'user', $2)+ "#,+ )+ .bind(chat_uuid)+ .bind("macro|[email protected]")+ .execute(&pool)+ .await+ .unwrap();++ delete_chat(pool.clone(), &chat_id).await.unwrap();++ let chat_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(chat_count.0, 0);++ let entity_count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM entity WHERE id = $1"#)+ .bind(chat_uuid)+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(entity_count.0, 0);+}