Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(entity-mutation): add domain capability contracts (#5161)

Sean Aye61fd03e5a12b
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 054538ffad..61dafa279d 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -54,6 +54,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -144,6 +145,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -221,6 +223,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -367,6 +370,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/favorites",
"crates/filter_ast",
"crates/foreign_entity",
@@ -506,6 +510,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -602,6 +607,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -685,6 +691,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -786,6 +793,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -841,6 +849,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
@@ -884,6 +893,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -954,6 +964,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -1180,6 +1191,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -1338,6 +1350,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -1421,6 +1434,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -1543,6 +1557,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/favorites",
"crates/filter_ast",
"crates/foreign_entity",
@@ -1728,6 +1743,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -1812,6 +1828,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -1887,6 +1904,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -1965,6 +1983,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -2057,6 +2076,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -2119,6 +2139,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -2185,6 +2206,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/gmail_client",
@@ -2264,6 +2286,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -2319,6 +2342,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -2469,6 +2493,35 @@
"crates/models_permissions",
"crates/workspace-hack"
],
+ "entity_mutation": [
+ "crates/agent",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
+ "crates/bot_id",
+ "crates/cowlike",
+ "crates/document_sub_type",
+ "crates/entity_access",
+ "crates/entity_mutation",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_user",
+ "crates/models_bulk_upload",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/non_empty",
+ "crates/prompt",
+ "crates/remote_env_var",
+ "crates/workspace-hack"
+ ],
"favorites": [
"crates/agent",
"crates/ai_toolset",
@@ -2578,6 +2631,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -2686,6 +2740,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/graphql_email",
@@ -2825,6 +2880,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -3043,6 +3099,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -3117,6 +3174,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -3478,6 +3536,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -3586,6 +3645,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -3814,6 +3874,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -3895,6 +3956,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -3965,6 +4027,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4216,6 +4279,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4278,6 +4342,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4341,6 +4406,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4561,6 +4627,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -4664,6 +4731,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4752,6 +4820,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4833,6 +4902,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4902,6 +4972,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -4978,6 +5049,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/fusionauth",
@@ -5096,6 +5168,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -5171,6 +5244,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
@@ -5250,6 +5324,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -5438,6 +5513,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -5514,6 +5590,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/generic_email_domains",
@@ -5597,6 +5674,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -5659,6 +5737,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
"crates/invite_email",
@@ -5771,6 +5850,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_access_management",
+ "crates/entity_mutation",
"crates/filter_ast",
"crates/foreign_entity",
"crates/frecency",
diff --git a/Cargo.lock b/Cargo.lock
index eb382b71fd..0a40761897 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2398,6 +2398,7 @@ dependencies = [
"connection",
"entity_access",
"entity_access_db_utils",
+ "entity_mutation",
"filter_ast",
"futures",
"item_filters",
@@ -2415,6 +2416,7 @@ dependencies = [
"models_permissions",
"notification",
"pgvector",
+ "rootcause",
"schemars 1.2.1",
"serde",
"serde_json",
@@ -2610,6 +2612,7 @@ dependencies = [
"contacts",
"entity_access",
"entity_access_db_utils",
+ "entity_mutation",
"filter_ast",
"frecency",
"futures",
@@ -2675,6 +2678,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "entity_mutation",
"futures",
"http-body-util",
"macro_authorization",
@@ -4450,6 +4454,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "entity_mutation",
"foreign_entity",
"futures",
"hex",
@@ -4745,6 +4750,7 @@ dependencies = [
"email_utils",
"entity_access",
"entity_access_management",
+ "entity_mutation",
"filter_ast",
"frecency",
"futures",
@@ -4763,6 +4769,7 @@ dependencies = [
"recursion",
"redis",
"reqwest 0.13.4",
+ "rootcause",
"schemars 1.2.1",
"scraper",
"serde",
@@ -5188,6 +5195,19 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "entity_mutation"
+version = "0.1.0"
+dependencies = [
+ "entity_access",
+ "macro_user_id",
+ "model-entity",
+ "models_permissions",
+ "rootcause",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "enum-as-inner"
version = "0.5.1"
@@ -11131,6 +11151,7 @@ dependencies = [
"entity_access",
"entity_access_db_utils",
"entity_access_management",
+ "entity_mutation",
"futures",
"hex",
"http-body-util",
diff --git a/Cargo.toml b/Cargo.toml
index 5e7693469c..d7e29bf881 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -17,6 +17,7 @@ members = [
"crates/cowlike",
"crates/crm",
"crates/embedding",
+ "crates/entity_mutation",
"crates/favorites",
"crates/foreign_entity",
"crates/generic_email_domains",
diff --git a/crates/call/Cargo.toml b/crates/call/Cargo.toml
index 9fb560181d..25a6ca627d 100644
--- a/crates/call/Cargo.toml
+++ b/crates/call/Cargo.toml
@@ -51,6 +51,7 @@ connection = { path = "../connection", default-features = false, features = [
entity_access = { path = "../entity_access", optional = true, default-features = false, features = [
"ports",
] }
+entity_mutation = { path = "../entity_mutation" }
entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
filter_ast = { path = "../filter_ast" }
futures = { workspace = true, optional = true }
@@ -70,6 +71,7 @@ model-error-response = { path = "../model-error-response", optional = true }
models_pagination = { path = "../models_pagination" }
models_permissions = { path = "../models_permissions" }
notification = { path = "../notification" }
+rootcause = { workspace = true }
pgvector = { workspace = true, optional = true }
schemars = { workspace = true, optional = true }
serde = { workspace = true }
diff --git a/crates/call/src/domain/entity_mutation.rs b/crates/call/src/domain/entity_mutation.rs
new file mode 100644
index 0000000000..f75f452578
--- /dev/null
+++ b/crates/call/src/domain/entity_mutation.rs
@@ -0,0 +1,175 @@
+//! Unified entity-mutation capability impls for calls.
+
+use entity_access::domain::models::{
+ AccessError, EditAccessLevel, EntityAccessReceipt, ViewAccessLevel,
+};
+use entity_mutation::{
+ DeleteEntityPermanently, EntityMutationErrorCode, RenameEntity, UpdateEntitySharePolicy,
+};
+use model_entity::Entity;
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+use super::{
+ models::{CallError, EditCallRecordRequest},
+ ports::CallService,
+ service::CallServiceImpl,
+};
+use connection::domain::ports::ConnectionService;
+use notification::domain::{ports::VoipPushSender, service::NotificationIngress};
+
+use crate::domain::ports::{
+ CallRepository, CallRtcClient, CallSearchIndexer, CallSummarizer, RecordingStorage,
+ VoiceRepository,
+};
+
+impl From<CallError> for EntityMutationErrorCode {
+ fn from(error: CallError) -> Self {
+ match error {
+ error @ CallError::NotFound(_) => Self::not_found(rootcause::report!(error)),
+ error @ (CallError::Auth | CallError::NotInCall) => {
+ Self::forbidden(rootcause::report!(error))
+ }
+ error @ CallError::InvalidRequest(_) => Self::invalid(rootcause::report!(error)),
+ error @ CallError::AlreadyInCall(_) => Self::conflict(rootcause::report!(error)),
+ error @ CallError::Internal(_) => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Map an access-domain error onto the public mutation vocabulary.
+fn access_error(error: AccessError) -> EntityMutationErrorCode {
+ match error {
+ error @ (AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_)) => {
+ EntityMutationErrorCode::forbidden(rootcause::report!(error))
+ }
+ error @ AccessError::NotFound(_) => {
+ EntityMutationErrorCode::not_found(rootcause::report!(error))
+ }
+ error @ AccessError::BadRequest(_) => {
+ EntityMutationErrorCode::invalid(rootcause::report!(error))
+ }
+ error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {
+ EntityMutationErrorCode::internal(rootcause::report!(error))
+ }
+ }
+}
+
+/// Reject the mutation while the call is still active.
+async fn require_archived_call<S: CallService>(
+ service: &S,
+ edit_receipt: &EntityAccessReceipt<EditAccessLevel>,
+ operation: &str,
+) -> Result<(), EntityMutationErrorCode> {
+ let view_receipt = edit_receipt
+ .clone()
+ .try_into_requirement::<ViewAccessLevel>()
+ .map_err(access_error)?;
+ if service.get_call_record(view_receipt).await?.is_active {
+ return Err(EntityMutationErrorCode::conflict(rootcause::report!(
+ format!("cannot {operation} an active call")
+ )));
+ }
+ Ok(())
+}
+
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr> RenameEntity
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+where
+ R: CallRepository,
+ C: CallRtcClient,
+ Cn: ConnectionService,
+ E: entity_access::domain::ports::EntityAccessService,
+ N: NotificationIngress,
+ S: RecordingStorage,
+ Sm: CallSummarizer,
+ I: CallSearchIndexer,
+ V: VoipPushSender,
+ Vr: VoiceRepository,
+ Self: CallService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn rename_entity(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ require_archived_call(self, &receipt, "rename").await?;
+ self.edit_call_record(
+ receipt,
+ EditCallRecordRequest {
+ share_permission: None,
+ share_with_team: None,
+ custom_name: Some(display_name),
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr> UpdateEntitySharePolicy
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+where
+ R: CallRepository,
+ C: CallRtcClient,
+ Cn: ConnectionService,
+ E: entity_access::domain::ports::EntityAccessService,
+ N: NotificationIngress,
+ S: RecordingStorage,
+ Sm: CallSummarizer,
+ I: CallSearchIndexer,
+ V: VoipPushSender,
+ Vr: VoiceRepository,
+ Self: CallService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn update_share_policy(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ policy: UpdateSharePermissionRequestV2,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ require_archived_call(self, &receipt, "update sharing for").await?;
+ self.edit_call_record(
+ receipt,
+ EditCallRecordRequest {
+ share_permission: Some(policy),
+ share_with_team: None,
+ custom_name: None,
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, C, Cn, E, N, S, Sm, I, V, Vr> DeleteEntityPermanently
+ for CallServiceImpl<R, C, Cn, E, N, S, Sm, I, V, Vr>
+where
+ R: CallRepository,
+ C: CallRtcClient,
+ Cn: ConnectionService,
+ E: entity_access::domain::ports::EntityAccessService,
+ N: NotificationIngress,
+ S: RecordingStorage,
+ Sm: CallSummarizer,
+ I: CallSearchIndexer,
+ V: VoipPushSender,
+ Vr: VoiceRepository,
+ Self: CallService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn delete_entity_permanently(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ require_archived_call(self, &receipt, "permanently delete").await?;
+ self.delete_call_record(receipt).await?;
+ Ok(Vec::new())
+ }
+}
diff --git a/crates/call/src/domain/mod.rs b/crates/call/src/domain/mod.rs
index f080d971b1..c2acc673d8 100644
--- a/crates/call/src/domain/mod.rs
+++ b/crates/call/src/domain/mod.rs
@@ -1,6 +1,10 @@
/// Domain models for calls.
pub mod models;
+/// Unified entity-mutation capability impls.
+#[cfg(feature = "ports")]
+pub mod entity_mutation;
+
/// Port traits for calls.
#[cfg(feature = "ports")]
pub mod ports;
diff --git a/crates/channels/Cargo.toml b/crates/channels/Cargo.toml
index eb713994bd..e2e5852952 100644
--- a/crates/channels/Cargo.toml
+++ b/crates/channels/Cargo.toml
@@ -63,6 +63,14 @@ outbound = [
"macro_user_id/sqlx",
"ports",
]
+entity_mutation = [
+ "dep:entity_access",
+ "dep:entity_mutation",
+ "dep:model-entity",
+ "dep:rootcause",
+ "entity_access/ports",
+ "ports",
+]
ports = ["dep:tokio"]
[dependencies]
@@ -71,6 +79,7 @@ attachment = { path = "../attachment", optional = true }
axum = { workspace = true, optional = true }
bot_id = { path = "../bot_id" }
channel_sender = { path = "../channel_sender" }
+entity_mutation = { path = "../entity_mutation", optional = true }
chrono = { workspace = true }
connection_gateway_client = { path = "../connection_gateway_client", optional = true }
contacts = { path = "../contacts", default-features = false, features = [
diff --git a/crates/channels/src/domain/entity_mutation.rs b/crates/channels/src/domain/entity_mutation.rs
new file mode 100644
index 0000000000..30949510d1
--- /dev/null
+++ b/crates/channels/src/domain/entity_mutation.rs
@@ -0,0 +1,90 @@
+//! Unified entity-mutation capability impls for channels.
+
+use entity_access::domain::models::{
+ AdminParticipantRole, EntityAccessReceipt, OwnerParticipantRole, RequiredPermission,
+};
+use entity_mutation::{DeleteEntityPermanently, EntityMutationErrorCode, RenameEntity};
+use model_entity::Entity;
+use uuid::Uuid;
+
+use super::{
+ models::{PatchChannelRequest, Sender},
+ ports::{ChannelMutationErr, ChannelService},
+ service::ChannelServiceImpl,
+};
+
+impl From<ChannelMutationErr> for EntityMutationErrorCode {
+ fn from(error: ChannelMutationErr) -> Self {
+ match error {
+ error @ ChannelMutationErr::BadRequest(_) => Self::invalid(rootcause::report!(error)),
+ error @ (ChannelMutationErr::Unauthorized(_) | ChannelMutationErr::Forbidden(_)) => {
+ Self::forbidden(rootcause::report!(error))
+ }
+ error @ ChannelMutationErr::NotFound(_) => Self::not_found(rootcause::report!(error)),
+ error => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Parse the channel id, rejecting non-UUID identifiers.
+fn channel_uuid(entity: &Entity<'static>) -> Result<Uuid, EntityMutationErrorCode> {
+ Uuid::parse_str(&entity.entity_id)
+ .map_err(|error| EntityMutationErrorCode::invalid(rootcause::report!(error)))
+}
+
+/// Convert the authenticated receipt holder into a channel sender.
+fn sender_from_receipt<T: RequiredPermission>(
+ receipt: &EntityAccessReceipt<T>,
+) -> Result<Sender, EntityMutationErrorCode> {
+ receipt
+ .get_authenticated_user()
+ .cloned()
+ .map(Sender::new_from_user)
+ .map_err(|error| EntityMutationErrorCode::forbidden(rootcause::report!(error)))
+}
+
+impl<R, E, P, M> RenameEntity for ChannelServiceImpl<R, E, P, M>
+where
+ Self: ChannelService,
+{
+ type Receipt = AdminParticipantRole;
+
+ async fn rename_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let channel_id = channel_uuid(&entity)?;
+ let sender = sender_from_receipt(&receipt)?;
+ self.patch_channel(
+ sender,
+ channel_id,
+ PatchChannelRequest {
+ channel_name: Some(display_name),
+ convert_to_team_channel: None,
+ auto_join_team: None,
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, E, P, M> DeleteEntityPermanently for ChannelServiceImpl<R, E, P, M>
+where
+ Self: ChannelService,
+{
+ type Receipt = OwnerParticipantRole;
+
+ async fn delete_entity_permanently(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let channel_id = channel_uuid(&entity)?;
+ let sender = sender_from_receipt(&receipt)?;
+ self.delete_channel(sender, channel_id).await?;
+ Ok(Vec::new())
+ }
+}
diff --git a/crates/channels/src/domain/mod.rs b/crates/channels/src/domain/mod.rs
index 08feb11715..c6ec8374d4 100644
--- a/crates/channels/src/domain/mod.rs
+++ b/crates/channels/src/domain/mod.rs
@@ -1,5 +1,8 @@
/// Kafka event models for the `macro.channels` topic.
pub mod broker_events;
+#[cfg(feature = "entity_mutation")]
+/// Unified entity-mutation capability impls.
+pub mod entity_mutation;
/// Domain events emitted by channel workflows.
pub mod events;
/// Legacy channel list service implementation.
diff --git a/crates/chat/Cargo.toml b/crates/chat/Cargo.toml
index 0470705f29..66b5b2fb78 100644
--- a/crates/chat/Cargo.toml
+++ b/crates/chat/Cargo.toml
@@ -33,12 +33,14 @@ entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }
entity_access_management = { path = "../entity_access_management", default-features = false, features = [
"ports",
] }
+entity_mutation = { path = "../entity_mutation" }
macro_user_id = { path = "../macro_user_id" }
model = { path = "../model" }
non_empty = { path = "../non_empty" }
model-entity = { path = "../model-entity" }
models_entity_access_management = { path = "../models_entity_access_management", default-features = false }
models_permissions = { path = "../models_permissions" }
+rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -73,7 +75,6 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
-rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tower = { workspace = true }
diff --git a/crates/chat/src/domain/ports/chat.rs b/crates/chat/src/domain/ports/chat.rs
index fae69d4b5f..c6bfdbc67d 100644
--- a/crates/chat/src/domain/ports/chat.rs
+++ b/crates/chat/src/domain/ports/chat.rs
@@ -137,6 +137,12 @@ pub trait ChatService: Send + Sync + 'static {
entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
) -> impl std::future::Future<Output = Result<GetChatResponse>> + Send;
+ /// Get chat metadata without loading messages.
+ fn get_metadata(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> impl std::future::Future<Output = Result<model::chat::Chat>> + Send;
+
/// Copy a chat and its messages, returning the new chat ID.
fn copy_chat(
&self,
diff --git a/crates/chat/src/domain/service/chat.rs b/crates/chat/src/domain/service/chat.rs
index fcf29434ea..e073440c0b 100644
--- a/crates/chat/src/domain/service/chat.rs
+++ b/crates/chat/src/domain/service/chat.rs
@@ -50,6 +50,19 @@ where
}
}
+impl<R: ChatRepo, Eam: EntityAccessManagementService> ChatServiceImpl<R, (), Eam> {
+ /// Create a chat service for hosts that only use metadata/lifecycle
+ /// operations and never execute stored tool calls.
+ pub fn new_without_tools(repo: R, entity_access_management_service: Eam) -> Self {
+ Self::new(
+ repo,
+ Arc::new(AsyncToolCollection::new()),
+ (),
+ entity_access_management_service,
+ )
+ }
+}
+
impl<R: ChatRepo, ToolSetContext, Eam: EntityAccessManagementService> ChatService
for ChatServiceImpl<R, ToolSetContext, Eam>
where
@@ -122,6 +135,16 @@ where
})
}
+ #[tracing::instrument(err, skip(self))]
+ async fn get_metadata(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<model::chat::Chat> {
+ self.repo
+ .get_metadata(&entity_access_receipt.entity().entity_id)
+ .await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn copy_chat(
&self,
diff --git a/crates/chat/src/domain/service/entity_mutation.rs b/crates/chat/src/domain/service/entity_mutation.rs
new file mode 100644
index 0000000000..6420470293
--- /dev/null
+++ b/crates/chat/src/domain/service/entity_mutation.rs
@@ -0,0 +1,237 @@
+//! Unified entity-mutation capability impls for chats.
+
+use std::collections::HashSet;
+
+use entity_access::domain::models::{
+ AccessError, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+};
+use entity_mutation::{
+ DeleteEntityPermanently, DuplicateEntity, EntityMutationErrorCode, MoveEntity, RenameEntity,
+ RestoreEntity, TrashEntity, UpdateEntitySharePolicy, capability::MoveEntityRequest,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+use crate::domain::{
+ models::{ChatErr, PatchChatArgs},
+ ports::ChatService,
+};
+
+use super::chat::ChatServiceImpl;
+
+impl From<ChatErr> for EntityMutationErrorCode {
+ fn from(error: ChatErr) -> Self {
+ match error {
+ error @ ChatErr::NotFound => Self::not_found(rootcause::report!(error)),
+ error @ ChatErr::BadRequest(_) => Self::invalid(rootcause::report!(error)),
+ ChatErr::Access(error) => access_error(error),
+ error @ ChatErr::Unknown(_) => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Map an access-domain error onto the public mutation vocabulary.
+fn access_error(error: AccessError) -> EntityMutationErrorCode {
+ match error {
+ error @ (AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_)) => {
+ EntityMutationErrorCode::forbidden(rootcause::report!(error))
+ }
+ error @ AccessError::NotFound(_) => {
+ EntityMutationErrorCode::not_found(rootcause::report!(error))
+ }
+ error @ AccessError::BadRequest(_) => {
+ EntityMutationErrorCode::invalid(rootcause::report!(error))
+ }
+ error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {
+ EntityMutationErrorCode::internal(rootcause::report!(error))
+ }
+ }
+}
+
+/// Build affected project entities from optional container ids.
+fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
+ let mut seen = HashSet::new();
+ ids.into_iter()
+ .flatten()
+ .filter(|id| !id.is_empty() && seen.insert(id.clone()))
+ .map(|id| EntityType::Project.with_entity_string(id))
+ .collect()
+}
+
+/// Resolve the chat's containing project for affected-record reporting.
+async fn chat_project_id<S: ChatService>(
+ service: &S,
+ owner_receipt: &EntityAccessReceipt<OwnerAccessLevel>,
+) -> Option<String> {
+ let view_receipt = owner_receipt
+ .clone()
+ .try_into_requirement::<ViewAccessLevel>()
+ .ok()?;
+ service.get_metadata(view_receipt).await.ok()?.project_id
+}
+
+impl<R, ToolSetContext, Eam> RenameEntity for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn rename_entity(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ self.patch(
+ receipt,
+ PatchChatArgs {
+ name: Some(display_name),
+ project_id: None,
+ share_permission: None,
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, ToolSetContext, Eam> MoveEntity for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let (receipt, project_id) = match request {
+ MoveEntityRequest::MoveToRoot { receipt, .. } => (receipt, None),
+ MoveEntityRequest::MoveToProject {
+ receipt,
+ project_id,
+ project_receipt: _,
+ ..
+ } => (receipt, Some(project_id)),
+ };
+ let old_project_id = chat_project_id(self, &receipt).await;
+ self.patch(
+ receipt,
+ PatchChatArgs {
+ name: None,
+ // The chat patch API uses an empty id to mean "root".
+ project_id: Some(project_id.clone().unwrap_or_default()),
+ share_permission: None,
+ },
+ )
+ .await?;
+ Ok(project_refs([old_project_id, project_id]))
+ }
+}
+
+impl<R, ToolSetContext, Eam> UpdateEntitySharePolicy for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn update_share_policy(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ policy: UpdateSharePermissionRequestV2,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ self.patch(
+ receipt,
+ PatchChatArgs {
+ name: None,
+ project_id: None,
+ share_permission: Some(policy),
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, ToolSetContext, Eam> TrashEntity for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn trash_entity(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project_id = chat_project_id(self, &receipt).await;
+ self.delete(receipt).await?;
+ Ok(project_refs([project_id]))
+ }
+}
+
+impl<R, ToolSetContext, Eam> RestoreEntity for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn restore_entity(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project_id = chat_project_id(self, &receipt).await;
+ self.revert_delete(receipt).await?;
+ Ok(project_refs([project_id]))
+ }
+}
+
+impl<R, ToolSetContext, Eam> DeleteEntityPermanently for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn delete_entity_permanently(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project_id = chat_project_id(self, &receipt).await;
+ self.permanently_delete(receipt).await?;
+ Ok(project_refs([project_id]))
+ }
+}
+
+impl<R, ToolSetContext, Eam> DuplicateEntity for ChatServiceImpl<R, ToolSetContext, Eam>
+where
+ ToolSetContext: Clone + Send + Sync + 'static,
+ Self: ChatService,
+{
+ type Receipt = ViewAccessLevel;
+
+ async fn duplicate_entity(
+ &self,
+ _entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ _user_id: MacroUserIdStr<'static>,
+ display_name: Option<String>,
+ ) -> Result<Entity<'static>, EntityMutationErrorCode> {
+ if display_name.is_some() {
+ return Err(EntityMutationErrorCode::invalid(rootcause::report!(
+ "chat duplication does not yet accept a custom display name".to_string()
+ )));
+ }
+ let id = self.copy_chat(receipt).await?;
+ Ok(EntityType::Chat.with_entity_string(id))
+ }
+}
diff --git a/crates/chat/src/domain/service/mod.rs b/crates/chat/src/domain/service/mod.rs
index e44b3f0c4c..99a7a0aae3 100644
--- a/crates/chat/src/domain/service/mod.rs
+++ b/crates/chat/src/domain/service/mod.rs
@@ -1,6 +1,8 @@
//! Service implementations for the chat domain.
mod chat;
+/// Unified entity-mutation capability impls.
+mod entity_mutation;
mod message;
mod model_access;
diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rs
index 375b18cceb..f1db3a960c 100644
--- a/crates/chat/src/inbound/test.rs
+++ b/crates/chat/src/inbound/test.rs
@@ -64,6 +64,13 @@ impl ChatService for MockService {
})
}
+ async fn get_metadata(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<model::chat::Chat> {
+ Err(ChatErr::NotFound)
+ }
+
async fn copy_chat(
&self,
_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -168,6 +175,13 @@ impl ChatService for ErrorService {
Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
}
+ async fn get_metadata(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<model::chat::Chat> {
+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))
+ }
+
async fn copy_chat(
&self,
_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -269,6 +283,13 @@ impl ChatService for NotFoundService {
Err(ChatErr::NotFound)
}
+ async fn get_metadata(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<model::chat::Chat> {
+ Err(ChatErr::NotFound)
+ }
+
async fn copy_chat(
&self,
_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,
diff --git a/crates/chat/src/inbound/toolset/test.rs b/crates/chat/src/inbound/toolset/test.rs
index 60ac346c9d..412e79b830 100644
--- a/crates/chat/src/inbound/toolset/test.rs
+++ b/crates/chat/src/inbound/toolset/test.rs
@@ -57,6 +57,15 @@ mod self_read_guard {
unreachable!("guard should short-circuit before calling the chat service")
}
+ async fn get_metadata(
+ &self,
+ _entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<model::chat::Chat> {
+ unreachable!("guard should short-circuit before calling the chat service")
+ }
+
async fn copy_chat(
&self,
_entity_access_receipt: EntityAccessReceipt<
@@ -275,6 +284,28 @@ mod self_read_guard {
Err(ChatErr::Unknown(anyhow::anyhow!("not used by this test")))
}
+ async fn get_metadata(
+ &self,
+ entity_access_receipt: EntityAccessReceipt<
+ entity_access::domain::models::ViewAccessLevel,
+ >,
+ ) -> Result<model::chat::Chat> {
+ #[allow(deprecated)]
+ let chat_id = entity_access_receipt.entity().entity_id.clone();
+ Ok(model::chat::Chat {
+ id: chat_id.to_string(),
+ name: "Other Chat".to_string(),
+ user_id: "macro|[email protected]".to_string(),
+ model: None,
+ project_id: None,
+ created_at: None,
+ updated_at: None,
+ token_count: None,
+ is_persistent: true,
+ deleted_at: None,
+ })
+ }
+
async fn get_chat(
&self,
entity_access_receipt: EntityAccessReceipt<
diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml
index 540760660d..932abfb1e0 100644
--- a/crates/documents/Cargo.toml
+++ b/crates/documents/Cargo.toml
@@ -83,6 +83,7 @@ connection = { path = "../connection", default-features = false, features = [
] }
document_sub_type = { path = "../document_sub_type" }
entity_access = { path = "../entity_access" }
+entity_mutation = { path = "../entity_mutation" }
entity_access_management = { path = "../entity_access_management", default-features = false, features = [
"outbound",
"ports",
@@ -106,6 +107,7 @@ model = { path = "../model" }
model-entity = { path = "../model-entity" }
models_permissions = { path = "../models_permissions" }
models_properties = { path = "../models_properties" }
+rootcause = { workspace = true }
s3_key = { path = "../s3_key" }
# Async runtime (for ports)
@@ -157,7 +159,6 @@ macro_db_migrator = { path = "../macro_db_migrator" }
macro_event_broker = { path = "../macro_event_broker" }
mockall = { workspace = true }
rdkafka = { workspace = true }
-rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal"] }
tower = { workspace = true }
diff --git a/crates/documents/src/domain.rs b/crates/documents/src/domain.rs
index 3b3bf94198..d7c033def6 100644
--- a/crates/documents/src/domain.rs
+++ b/crates/documents/src/domain.rs
@@ -2,6 +2,8 @@
pub mod branch_name;
pub mod content;
+/// Unified entity-mutation capability impls.
+pub mod entity_mutation;
pub mod events;
#[cfg(feature = "ports")]
pub mod markdown_backfill;
diff --git a/crates/documents/src/domain/entity_mutation.rs b/crates/documents/src/domain/entity_mutation.rs
new file mode 100644
index 0000000000..1a57e60f72
--- /dev/null
+++ b/crates/documents/src/domain/entity_mutation.rs
@@ -0,0 +1,253 @@
+//! Unified entity-mutation capability impls for documents.
+//!
+//! Each impl owns the mapping from the unified mutation vocabulary onto the
+//! document service's own methods, preconditions, and errors, so the
+//! composition layer routes without translating.
+
+use std::collections::HashSet;
+
+use entity_access::domain::models::{
+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,
+};
+use entity_mutation::{
+ DuplicateEntity, EntityMutationErrorCode, MoveEntity, RenameEntity, TrashEntity,
+ UpdateEntitySharePolicy, capability::MoveEntityRequest,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::DocumentBasic;
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+use connection::domain::ports::ConnectionService;
+use entity_access_management::domain::ports::EntityAccessManagementService;
+use foreign_entity::domain::ports::ForeignEntityService;
+use macro_event_broker::MacroEventBroker;
+
+use super::{
+ models::{DocumentError, EditDocumentServiceArgs},
+ ports::{DocumentRepo, DocumentService, PresignedUploadUrlPort, TaskPropertiesPort},
+ service::DocumentServiceImpl,
+};
+
+impl From<DocumentError> for EntityMutationErrorCode {
+ fn from(error: DocumentError) -> Self {
+ match error {
+ error @ (DocumentError::NotFound(_) | DocumentError::Gone) => {
+ Self::not_found(rootcause::report!(error))
+ }
+ error @ DocumentError::Unauthorized => Self::forbidden(rootcause::report!(error)),
+ error @ DocumentError::Conflict(_) => Self::conflict(rootcause::report!(error)),
+ error @ (DocumentError::BadRequest(_) | DocumentError::NameTooLong { .. }) => {
+ Self::invalid(rootcause::report!(error))
+ }
+ error => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Build affected project entities from optional container ids.
+fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
+ let mut seen = HashSet::new();
+ ids.into_iter()
+ .flatten()
+ .filter(|id| !id.is_empty() && seen.insert(id.clone()))
+ .map(|id| EntityType::Project.with_entity_string(id))
+ .collect()
+}
+
+/// Fetch a document and reject the mutation if it is trashed.
+async fn live_document<S: DocumentService>(
+ service: &S,
+ entity: &Entity<'static>,
+ action: &str,
+) -> Result<DocumentBasic, EntityMutationErrorCode> {
+ let document = service
+ .internal_get_basic_document(&entity.entity_id)
+ .await?;
+ if document.deleted_at.is_some() {
+ return Err(EntityMutationErrorCode::conflict(rootcause::report!(
+ format!("cannot {action} a deleted document")
+ )));
+ }
+ Ok(document)
+}
+
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
+ B: MacroEventBroker,
+> RenameEntity for DocumentServiceImpl<R, U, T, C, Eam, F, B>
+where
+ Self: DocumentService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn rename_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let document = live_document(self, &entity, "rename").await?;
+ self.edit_document(
+ receipt,
+ document,
+ EditDocumentServiceArgs {
+ document_name: Some(display_name),
+ project_id: None,
+ share_permission: None,
+ file_type: None,
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
+ B: MacroEventBroker,
+> MoveEntity for DocumentServiceImpl<R, U, T, C, Eam, F, B>
+where
+ Self: DocumentService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let (entity, receipt, project_id) = match request {
+ MoveEntityRequest::MoveToRoot { entity, receipt } => (entity, receipt, None),
+ MoveEntityRequest::MoveToProject {
+ entity,
+ receipt,
+ project_id,
+ project_receipt: _,
+ } => (entity, receipt, Some(project_id)),
+ };
+ let document = live_document(self, &entity, "move").await?;
+ let old_project_id = document.project_id.clone().map(|id| id.to_string());
+ self.edit_document(
+ receipt,
+ document,
+ EditDocumentServiceArgs {
+ document_name: None,
+ // The document edit API uses an empty id to mean "root".
+ project_id: Some(project_id.clone().unwrap_or_default()),
+ share_permission: None,
+ file_type: None,
+ },
+ )
+ .await?;
+ Ok(project_refs([old_project_id, project_id]))
+ }
+}
+
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
+ B: MacroEventBroker,
+> UpdateEntitySharePolicy for DocumentServiceImpl<R, U, T, C, Eam, F, B>
+where
+ Self: DocumentService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn update_share_policy(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ policy: UpdateSharePermissionRequestV2,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let document = live_document(self, &entity, "update sharing for").await?;
+ self.edit_document(
+ receipt,
+ document,
+ EditDocumentServiceArgs {
+ document_name: None,
+ project_id: None,
+ share_permission: Some(policy),
+ file_type: None,
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
+ B: MacroEventBroker,
+> TrashEntity for DocumentServiceImpl<R, U, T, C, Eam, F, B>
+where
+ Self: DocumentService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn trash_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project_id = self
+ .internal_get_basic_document(&entity.entity_id)
+ .await?
+ .project_id;
+ let affected_project_id = project_id.clone().map(|id| id.to_string());
+ self.delete_document(receipt, project_id).await?;
+ Ok(project_refs([affected_project_id]))
+ }
+}
+
+impl<
+ R: DocumentRepo,
+ U: PresignedUploadUrlPort,
+ T: TaskPropertiesPort,
+ C: ConnectionService,
+ Eam: EntityAccessManagementService,
+ F: ForeignEntityService,
+ B: MacroEventBroker,
+> DuplicateEntity for DocumentServiceImpl<R, U, T, C, Eam, F, B>
+where
+ Self: DocumentService,
+{
+ type Receipt = ViewAccessLevel;
+
+ async fn duplicate_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ user_id: MacroUserIdStr<'static>,
+ display_name: Option<String>,
+ ) -> Result<Entity<'static>, EntityMutationErrorCode> {
+ let document = self.internal_get_basic_document(&entity.entity_id).await?;
+ let display_name =
+ display_name.unwrap_or_else(|| format!("{} copy", document.document_name));
+ let response = self
+ .copy_document(receipt, document, user_id, display_name, None, None)
+ .await?;
+ Ok(
+ EntityType::Document
+ .with_entity_string(response.document_metadata.metadata.document_id),
+ )
+ }
+}
diff --git a/crates/email/Cargo.toml b/crates/email/Cargo.toml
index a616219a97..c9dda2b805 100644
--- a/crates/email/Cargo.toml
+++ b/crates/email/Cargo.toml
@@ -66,6 +66,7 @@ email_db_client = { path = "../email_db_client", optional = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = ["axum"], optional = true }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
+entity_mutation = { path = "../entity_mutation" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model-entity = { path = "../model-entity" }
@@ -74,6 +75,7 @@ model-error-response = { path = "../model-error-response", optional = true }
models_pagination = { path = "../models_pagination" }
recursion = { workspace = true }
reqwest = { workspace = true, optional = true }
+rootcause = { workspace = true }
schemars = { workspace = true, optional = true, features = ["uuid1"] }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/crates/email/src/domain/service/entity_mutation.rs b/crates/email/src/domain/service/entity_mutation.rs
new file mode 100644
index 0000000000..174cd840a7
--- /dev/null
+++ b/crates/email/src/domain/service/entity_mutation.rs
@@ -0,0 +1,54 @@
+//! Unified entity-mutation capability impls for email threads.
+
+use std::collections::HashSet;
+
+use entity_access::domain::models::EditAccessLevel;
+use entity_mutation::{EntityMutationErrorCode, MoveEntity, capability::MoveEntityRequest};
+use model_entity::{Entity, EntityType};
+
+use super::EmailServiceImpl;
+use crate::domain::{models::EmailErr, ports::EmailService};
+
+impl From<EmailErr> for EntityMutationErrorCode {
+ fn from(error: EmailErr) -> Self {
+ match error {
+ error @ EmailErr::ThreadNotFound => Self::not_found(rootcause::report!(error)),
+ error @ EmailErr::Unauthorized => Self::forbidden(rootcause::report!(error)),
+ error => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Build affected project entities from optional container ids.
+fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
+ let mut seen = HashSet::new();
+ ids.into_iter()
+ .flatten()
+ .filter(|id| !id.is_empty() && seen.insert(id.clone()))
+ .map(|id| EntityType::Project.with_entity_string(id))
+ .collect()
+}
+
+impl<T, U, E, CS, Eam, B> MoveEntity for EmailServiceImpl<T, U, E, CS, Eam, B>
+where
+ Self: EmailService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let (receipt, project_id, project_receipt) = match request {
+ MoveEntityRequest::MoveToRoot { receipt, .. } => (receipt, None, None),
+ MoveEntityRequest::MoveToProject {
+ receipt,
+ project_id,
+ project_receipt,
+ ..
+ } => (receipt, Some(project_id), Some(project_receipt)),
+ };
+ let old_project_id = self.update_thread_project(receipt, project_receipt).await?;
+ Ok(project_refs([old_project_id, project_id]))
+ }
+}
diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rs
index e73e6a7a32..db33ee1edd 100644
--- a/crates/email/src/domain/service/mod.rs
+++ b/crates/email/src/domain/service/mod.rs
@@ -5,6 +5,9 @@ mod signature;
mod thread;
mod thread_labels;
+/// Unified entity-mutation capability impls.
+mod entity_mutation;
+
use crate::domain::{
events::{EmailMacroEvent, ThreadProjectChangedMetadata},
models::{
diff --git a/crates/entity_access/src/domain/models.rs b/crates/entity_access/src/domain/models.rs
index 4f93c6f57b..68a6b3e488 100644
--- a/crates/entity_access/src/domain/models.rs
+++ b/crates/entity_access/src/domain/models.rs
@@ -307,6 +307,17 @@ pub struct EntityAccessReceipt<T: RequiredPermission> {
}
impl<T: RequiredPermission> EntityAccessReceipt<T> {
+ /// Re-tag this receipt for another permission requirement after
+ /// revalidating the already-resolved permission.
+ ///
+ /// This safely supports passing a stronger receipt to a read-only domain
+ /// method without repeating the underlying access lookup.
+ pub fn try_into_requirement<U: RequiredPermission>(
+ self,
+ ) -> Result<EntityAccessReceipt<U>, AccessError> {
+ EntityAccessReceipt::<U>::try_new(self.auth, self.entity, self.entity_permission)
+ }
+
/// Creates an access receipt for the given auth after validating the
/// provided permission against the required level `T`.
pub fn try_new(
diff --git a/crates/entity_mutation/Cargo.toml b/crates/entity_mutation/Cargo.toml
new file mode 100644
index 0000000000..345d177471
--- /dev/null
+++ b/crates/entity_mutation/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+edition = "2024"
+name = "entity_mutation"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+entity_access = { path = "../entity_access", default-features = false, features = [
+ "ports",
+] }
+macro_user_id = { path = "../macro_user_id" }
+model-entity = { path = "../model-entity" }
+models_permissions = { path = "../models_permissions" }
+rootcause = { workspace = true }
+tracing = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/entity_mutation/src/capability.rs b/crates/entity_mutation/src/capability.rs
new file mode 100644
index 0000000000..39ba030a23
--- /dev/null
+++ b/crates/entity_mutation/src/capability.rs
@@ -0,0 +1,140 @@
+//! Per-capability mutation traits implemented by each entity domain.
+//!
+//! These traits push unification down into the domain crates: each crate
+//! implements the capabilities that make sense for its entity kind and owns
+//! the mapping from the unified vocabulary onto its own service methods,
+//! preconditions, and errors. The composition layer (the DSS entity mutation
+//! service) stays a thin router: it resolves access receipts, enforces the
+//! batch contract, and dispatches each item to the owning domain's impl.
+//!
+//! Every trait declares its required access level as an associated
+//! [`RequiredPermission`] type, so each entity kind's permission requirement
+//! lives with its implementation and the router resolves receipts
+//! generically. Implementations return the additional records they affected
+//! (containers, cascade descendants); the router attributes outcomes to the
+//! requested entity.
+
+use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, RequiredPermission};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+use crate::EntityMutationErrorCode;
+
+/// Rename an entity's user-visible display name.
+pub trait RenameEntity {
+ /// Access requirement for renaming this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Rename the entity, returning any additionally affected records.
+ fn rename_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// The payload to move an entity
+pub enum MoveEntityRequest<R: RequiredPermission> {
+ /// we are moving the entity to "root" i.e. not a project
+ MoveToRoot {
+ /// the entity to move
+ entity: Entity<'static>,
+ /// the access to the entity
+ receipt: EntityAccessReceipt<R>,
+ },
+ /// we are moving the entity to a project
+ MoveToProject {
+ /// the entity to move
+ entity: Entity<'static>,
+ /// the access to the entity
+ receipt: EntityAccessReceipt<R>,
+ /// the project id
+ project_id: String,
+ /// the access to the project
+ project_receipt: EntityAccessReceipt<EditAccessLevel>,
+ },
+}
+
+/// Move an entity into a project, or to the root.
+pub trait MoveEntity {
+ /// Access requirement for moving this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Move the entity. `project_id` of `None` means the root; the router
+ /// has already validated edit access to the target project and passes
+ /// the receipt along for domains that consume it.
+ fn move_entity(
+ &self,
+ req: MoveEntityRequest<Self::Receipt>,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// Update an entity's public and channel share policy.
+pub trait UpdateEntitySharePolicy {
+ /// Access requirement for changing this entity kind's share policy.
+ type Receipt: RequiredPermission;
+
+ /// Apply the share-policy update, returning affected records.
+ fn update_share_policy(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ policy: UpdateSharePermissionRequestV2,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// Soft-delete an entity with a reversible trash lifecycle.
+pub trait TrashEntity {
+ /// Access requirement for trashing this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Trash the entity, returning affected records (containers, cascades).
+ fn trash_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// Restore a reversibly deleted entity.
+pub trait RestoreEntity {
+ /// Access requirement for restoring this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Restore the entity, returning affected records.
+ fn restore_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// Irreversibly delete an entity.
+pub trait DeleteEntityPermanently {
+ /// Access requirement for permanently deleting this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Permanently delete the entity, returning affected records.
+ fn delete_entity_permanently(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, EntityMutationErrorCode>> + Send;
+}
+
+/// Duplicate an entity.
+pub trait DuplicateEntity {
+ /// Access requirement for duplicating this entity kind.
+ type Receipt: RequiredPermission;
+
+ /// Duplicate the entity, returning the newly created entity.
+ fn duplicate_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ user_id: MacroUserIdStr<'static>,
+ display_name: Option<String>,
+ ) -> impl Future<Output = Result<Entity<'static>, EntityMutationErrorCode>> + Send;
+}
diff --git a/crates/entity_mutation/src/lib.rs b/crates/entity_mutation/src/lib.rs
new file mode 100644
index 0000000000..0ca97e93b5
--- /dev/null
+++ b/crates/entity_mutation/src/lib.rs
@@ -0,0 +1,19 @@
+//! Unified entity mutation domain contract.
+//!
+//! This crate defines the canonical mutation vocabulary used by API adapters.
+//! Concrete services preserve each entity domain's authorization and business
+//! rules while presenting one capability-oriented surface to callers.
+#![deny(missing_docs)]
+
+/// Per-capability mutation traits implemented by each entity domain.
+pub mod capability;
+mod models;
+
+pub use capability::{
+ DeleteEntityPermanently, DuplicateEntity, MoveEntity, RenameEntity, RestoreEntity, TrashEntity,
+ UpdateEntitySharePolicy,
+};
+pub use models::{
+ DuplicateEntityRequest, EntityMutationActor, EntityMutationErrorCode, MoveEntityRequest,
+ RenameEntityRequest, UpdateEntitySharePolicyRequest,
+};
diff --git a/crates/entity_mutation/src/models.rs b/crates/entity_mutation/src/models.rs
new file mode 100644
index 0000000000..bdbaaefd33
--- /dev/null
+++ b/crates/entity_mutation/src/models.rs
@@ -0,0 +1,105 @@
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+/// Authenticated actor performing an entity mutation.
+#[derive(Clone, Debug)]
+pub struct EntityMutationActor {
+ /// Stable Macro user id.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Organization id attached to the authenticated request, when present.
+ pub organization_id: Option<i64>,
+}
+
+/// Request to update an entity's display name.
+#[derive(Clone, Debug)]
+pub struct RenameEntityRequest {
+ /// Entity to rename.
+ pub entity: Entity<'static>,
+ /// New user-visible display name.
+ pub display_name: String,
+}
+
+/// Request to move an entity into or out of a project.
+#[derive(Clone, Debug)]
+pub struct MoveEntityRequest {
+ /// Entity to move.
+ pub entity: Entity<'static>,
+ /// Destination project id, or `None` to move the entity to the root.
+ pub project_id: Option<String>,
+}
+
+/// Request to duplicate an entity.
+#[derive(Clone, Debug)]
+pub struct DuplicateEntityRequest {
+ /// Source entity to duplicate.
+ pub entity: Entity<'static>,
+ /// Optional display name for the new entity.
+ pub display_name: Option<String>,
+}
+
+/// Request to update an entity's public and channel share policy.
+#[derive(Clone, Debug)]
+pub struct UpdateEntitySharePolicyRequest {
+ /// Entity whose share policy should change.
+ pub entity: Entity<'static>,
+ /// Shared permission update used by documents, projects, chats, email
+ /// threads, and calls.
+ pub policy: UpdateSharePermissionRequestV2,
+}
+
+/// Unit struct with private constructor
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Sentinel(());
+
+/// Stable machine-readable mutation failure category.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum EntityMutationErrorCode {
+ /// The operation does not apply to this entity kind.
+ UnsupportedOperation(Sentinel),
+ /// The request is syntactically valid but violates a domain constraint.
+ InvalidInput(Sentinel),
+ /// The actor is authenticated but lacks the required capability.
+ Forbidden(Sentinel),
+ /// The referenced entity does not exist.
+ NotFound(Sentinel),
+ /// The requested mutation conflicts with current entity state.
+ Conflict(Sentinel),
+ /// The mutation failed for an internal reason.
+ Internal(Sentinel),
+}
+
+impl EntityMutationErrorCode {
+ /// Log an internal failure and return the generic user-safe error.
+ ///
+ /// Callers run inside a per-item tracing span carrying the operation and
+ /// entity fields, so the log line stays attributable.
+ #[tracing::instrument(ret)]
+ pub fn internal<C, O, T>(err: rootcause::Report<C, O, T>) -> Self {
+ EntityMutationErrorCode::Internal(Sentinel(()))
+ }
+
+ /// Construct a not-found error.
+ #[tracing::instrument(ret)]
+ pub fn not_found<C, O, T>(err: rootcause::Report<C, O, T>) -> Self {
+ EntityMutationErrorCode::NotFound(Sentinel(()))
+ }
+
+ /// Construct a forbidden error.
+ #[tracing::instrument(ret)]
+ pub fn forbidden<C, O, T>(err: rootcause::Report<C, O, T>) -> Self {
+ EntityMutationErrorCode::Forbidden(Sentinel(()))
+ }
+
+ /// Construct an invalid-input error.
+ #[tracing::instrument(ret)]
+ pub fn invalid<C, O, T>(err: rootcause::Report<C, O, T>) -> Self {
+ EntityMutationErrorCode::InvalidInput(Sentinel(()))
+ }
+
+ /// Construct a state-conflict error.
+ #[tracing::instrument(ret)]
+ pub fn conflict<C, O, T>(err: rootcause::Report<C, O, T>) -> Self {
+ EntityMutationErrorCode::Conflict(Sentinel(()))
+ }
+}
diff --git a/crates/projects/Cargo.toml b/crates/projects/Cargo.toml
index f16bc46c62..d23d35017d 100644
--- a/crates/projects/Cargo.toml
+++ b/crates/projects/Cargo.toml
@@ -54,12 +54,14 @@ macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_env_var = { path = "../macro_env_var" }
macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
+entity_mutation = { path = "../entity_mutation" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
models_bulk_upload = { path = "../models_bulk_upload" }
models_permissions = { path = "../models_permissions" }
+rootcause = { workspace = true }
s3_key = { path = "../s3_key" }
# Async runtime (for ports)
@@ -98,7 +100,6 @@ macro_event_broker = { path = "../macro_event_broker" }
mockall = { workspace = true }
rdkafka = { workspace = true }
model_user = { path = "../model_user" }
-rootcause = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal"] }
tower = { workspace = true }
diff --git a/crates/projects/src/domain.rs b/crates/projects/src/domain.rs
index c811c4bb28..4ed26cf913 100644
--- a/crates/projects/src/domain.rs
+++ b/crates/projects/src/domain.rs
@@ -1,5 +1,7 @@
//! Domain models, ports, and project service definitions.
+/// Unified entity-mutation capability impls.
+pub mod entity_mutation;
pub mod events;
pub mod models;
pub mod response;
diff --git a/crates/projects/src/domain/entity_mutation.rs b/crates/projects/src/domain/entity_mutation.rs
new file mode 100644
index 0000000000..48501a3562
--- /dev/null
+++ b/crates/projects/src/domain/entity_mutation.rs
@@ -0,0 +1,292 @@
+//! Unified entity-mutation capability impls for projects.
+
+use std::collections::HashSet;
+
+use entity_access::domain::models::{
+ AccessError, EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel,
+};
+use entity_access_management::domain::ports::EntityAccessManagementService;
+use entity_mutation::{
+ DeleteEntityPermanently, EntityMutationErrorCode, MoveEntity, RenameEntity, RestoreEntity,
+ TrashEntity, UpdateEntitySharePolicy, capability::MoveEntityRequest,
+};
+use macro_event_broker::MacroEventBroker;
+use model::project::{BasicProject, request::PatchProjectRequestV2};
+use model_entity::{Entity, EntityType};
+use models_permissions::share_permission::UpdateSharePermissionRequestV2;
+
+use super::{
+ models::ProjectError,
+ ports::{
+ BulkUploadRequestPort, ProjectRepo, ProjectSearchIndexer, ProjectService,
+ ProjectUploadUrlPort, ShaCounterPort,
+ },
+ service::ProjectServiceImpl,
+};
+
+impl From<ProjectError> for EntityMutationErrorCode {
+ fn from(error: ProjectError) -> Self {
+ match error {
+ error @ ProjectError::NotFound(_) => Self::not_found(rootcause::report!(error)),
+ error @ (ProjectError::Unauthorized | ProjectError::UnauthorizedWithMessage(_)) => {
+ Self::forbidden(rootcause::report!(error))
+ }
+ error @ (ProjectError::BadRequest(_)
+ | ProjectError::NameTooLong { .. }
+ | ProjectError::RecursiveNesting) => Self::invalid(rootcause::report!(error)),
+ error @ ProjectError::CannotModifyDeleted => Self::conflict(rootcause::report!(error)),
+ error @ ProjectError::Internal(_) => Self::internal(rootcause::report!(error)),
+ }
+ }
+}
+
+/// Map an access-domain error onto the public mutation vocabulary.
+fn access_error(error: AccessError) -> EntityMutationErrorCode {
+ match error {
+ error @ (AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_)) => {
+ EntityMutationErrorCode::forbidden(rootcause::report!(error))
+ }
+ error @ AccessError::NotFound(_) => {
+ EntityMutationErrorCode::not_found(rootcause::report!(error))
+ }
+ error @ AccessError::BadRequest(_) => {
+ EntityMutationErrorCode::invalid(rootcause::report!(error))
+ }
+ error @ (AccessError::DatabaseError(_) | AccessError::Internal) => {
+ EntityMutationErrorCode::internal(rootcause::report!(error))
+ }
+ }
+}
+
+/// Build affected project entities from optional container ids.
+fn project_refs(ids: impl IntoIterator<Item = Option<String>>) -> Vec<Entity<'static>> {
+ let mut seen = HashSet::new();
+ ids.into_iter()
+ .flatten()
+ .filter(|id| !id.is_empty() && seen.insert(id.clone()))
+ .map(|id| EntityType::Project.with_entity_string(id))
+ .collect()
+}
+
+/// Fetch project metadata; access is enforced separately via receipts.
+async fn basic_project<S: ProjectService>(
+ service: &S,
+ entity: &Entity<'static>,
+) -> Result<BasicProject, EntityMutationErrorCode> {
+ Ok(service
+ .internal_get_basic_project(&entity.entity_id)
+ .await?)
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> RenameEntity for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = EditAccessLevel;
+
+ async fn rename_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ display_name: String,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project = basic_project(self, &entity).await?;
+ let parent_id = project.parent_id.clone();
+ self.edit_project(
+ receipt,
+ project,
+ PatchProjectRequestV2 {
+ name: Some(display_name),
+ project_parent_id: None,
+ share_permission: None,
+ },
+ )
+ .await?;
+ Ok(project_refs([parent_id]))
+ }
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> MoveEntity for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn move_entity(
+ &self,
+ request: MoveEntityRequest<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let (entity, receipt, project_id) = match request {
+ MoveEntityRequest::MoveToRoot { entity, receipt } => (entity, receipt, None),
+ MoveEntityRequest::MoveToProject {
+ entity,
+ receipt,
+ project_id,
+ project_receipt: _,
+ } => (entity, receipt, Some(project_id)),
+ };
+ let project = basic_project(self, &entity).await?;
+ let old_parent_id = project.parent_id.clone();
+ // Moving requires ownership at the API surface; the edit call itself
+ // consumes an edit-level receipt. Self-parenting, cycles, and
+ // deleted-state are enforced by the project domain service; an empty
+ // parent id means "root".
+ let receipt = receipt
+ .try_into_requirement::<EditAccessLevel>()
+ .map_err(access_error)?;
+ self.edit_project(
+ receipt,
+ project,
+ PatchProjectRequestV2 {
+ name: None,
+ project_parent_id: Some(project_id.clone().unwrap_or_default()),
+ share_permission: None,
+ },
+ )
+ .await?;
+ Ok(project_refs([old_parent_id, project_id]))
+ }
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> UpdateEntitySharePolicy
+ for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn update_share_policy(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ policy: UpdateSharePermissionRequestV2,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project = basic_project(self, &entity).await?;
+ let receipt = receipt
+ .try_into_requirement::<EditAccessLevel>()
+ .map_err(access_error)?;
+ self.edit_project(
+ receipt,
+ project,
+ PatchProjectRequestV2 {
+ name: None,
+ project_parent_id: None,
+ share_permission: Some(policy),
+ },
+ )
+ .await?;
+ Ok(Vec::new())
+ }
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> TrashEntity for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn trash_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project = basic_project(self, &entity).await?;
+ let actor = receipt
+ .get_authenticated_user()
+ .map_err(access_error)?
+ .to_string();
+ let deleted = self.soft_delete_project(receipt, project, actor).await?;
+ Ok(refs(EntityType::Project, deleted.project_ids)
+ .chain(refs(EntityType::Document, deleted.document_ids))
+ .chain(refs(EntityType::Chat, deleted.chat_ids))
+ .collect())
+ }
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> RestoreEntity for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn restore_entity(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project = basic_project(self, &entity).await?;
+ let parent_id = project.parent_id.clone();
+ self.revert_delete_project(receipt, project).await?;
+ Ok(project_refs([parent_id]))
+ }
+}
+
+impl<R, U, D, Sha, Eam, Idx, B> DeleteEntityPermanently
+ for ProjectServiceImpl<R, U, D, Sha, Eam, Idx, B>
+where
+ R: ProjectRepo,
+ U: ProjectUploadUrlPort,
+ D: BulkUploadRequestPort,
+ Sha: ShaCounterPort,
+ Eam: EntityAccessManagementService,
+ Idx: ProjectSearchIndexer,
+ B: MacroEventBroker,
+ Self: ProjectService,
+{
+ type Receipt = OwnerAccessLevel;
+
+ async fn delete_entity_permanently(
+ &self,
+ entity: Entity<'static>,
+ receipt: EntityAccessReceipt<Self::Receipt>,
+ ) -> Result<Vec<Entity<'static>>, EntityMutationErrorCode> {
+ let project = basic_project(self, &entity).await?;
+ let parent_id = project.parent_id.clone();
+ self.permanently_delete_project(receipt, project).await?;
+ Ok(project_refs([parent_id]))
+ }
+}
+
+/// Build entity refs of one kind from raw ids.
+fn refs(
+ entity_type: EntityType,
+ ids: impl IntoIterator<Item = String>,
+) -> impl Iterator<Item = Entity<'static>> {
+ ids.into_iter()
+ .map(move |id| entity_type.with_entity_string(id))
+}