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(graphql): move favorite mutations into favorite adapter (#6215)

Sean Ayee7fe6bca2b40
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 26b4043b83..f470b5619e 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -4294,36 +4294,116 @@
"crates/workspace-hack"
],
"graphql_favorite": [
+ "crates/activity",
"crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
+ "crates/authentication_service_client",
"crates/bot_id",
"crates/bot_token",
+ "crates/broadcast",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/chat",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
"crates/cowlike",
+ "crates/crm",
"crates/document_sub_type",
+ "crates/documents",
+ "crates/dynamodb_client",
+ "crates/email",
+ "crates/email_utils",
+ "crates/embedding",
"crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
"crates/favorites",
+ "crates/filter_ast",
+ "crates/foreign_entity",
+ "crates/frecency",
+ "crates/graphql_common",
+ "crates/graphql_email",
+ "crates/graphql_entity_mutation",
"crates/graphql_favorite",
+ "crates/graphql_permission",
+ "crates/graphql_soup",
+ "crates/graphql_soup_filter_input",
"crates/harness_id",
"crates/harness_token",
+ "crates/invite_email",
+ "crates/item_filter_index",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
"crates/macro_auth",
"crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_sha_count_client",
+ "crates/macro_sync_service_jwt",
+ "crates/macro_tower_layers",
"crates/macro_user_id",
"crates/macro_uuid",
+ "crates/mention_utils",
"crates/model",
"crates/model-entity",
"crates/model-error-response",
"crates/model_file_type",
+ "crates/model_notifications",
"crates/model_user",
+ "crates/models_ai_projection",
"crates/models_bulk_upload",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_grouping",
+ "crates/models_opensearch",
"crates/models_pagination",
"crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_search",
+ "crates/models_search_cursor",
+ "crates/models_soup",
"crates/non_empty",
+ "crates/notification",
+ "crates/opensearch_client",
+ "crates/opensearch_query_builder",
+ "crates/predicate_index",
+ "crates/projects",
"crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/readonly_pool",
+ "crates/reminders",
"crates/remote_env_var",
+ "crates/roles_and_permissions",
+ "crates/s3_key",
+ "crates/secretsmanager_client",
+ "crates/share_permission_db_utils",
+ "crates/soup",
+ "crates/soup_filter_projection",
+ "crates/soup_realtime",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/sync_service",
+ "crates/sync_service_client",
+ "crates/system_properties",
+ "crates/system_skills",
+ "crates/task_dedup",
+ "crates/unfurl",
"crates/workspace-hack"
],
"graphql_notification": [
diff --git a/Cargo.lock b/Cargo.lock
index 6e938cd2bb..56277b63d6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3742,6 +3742,7 @@ dependencies = [
"email",
"entity_access",
"entity_mutation",
+ "favorites",
"graphql_activity",
"graphql_channel",
"graphql_common",
@@ -7213,12 +7214,19 @@ name = "graphql_favorite"
version = "0.1.0"
dependencies = [
"async-graphql",
+ "chrono",
+ "entity_mutation",
"favorites",
+ "graphql_common",
+ "graphql_entity_mutation",
+ "graphql_permission",
+ "graphql_soup",
"macro_user_id",
"model-entity",
"rootcause",
"tokio",
"tracing",
+ "uuid",
"workspace-hack",
]
diff --git a/crates/complete_graph/Cargo.toml b/crates/complete_graph/Cargo.toml
index ddf28edd02..89eddc4d02 100644
--- a/crates/complete_graph/Cargo.toml
+++ b/crates/complete_graph/Cargo.toml
@@ -17,6 +17,7 @@ entity_access = { path = "../entity_access", default-features = false, features
"inbound",
] }
entity_mutation = { path = "../entity_mutation" }
+favorites = { path = "../favorites", default-features = false, features = ["ports"] }
graphql_activity = { path = "../graphql_activity" }
graphql_channel = { path = "../graphql_channel" }
graphql_common = { path = "../graphql_common" }
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index c2cdaa0945..fcf6774e8d 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -1,6 +1,6 @@
//! Composition of the domain GraphQL adapter crates (`graphql_soup`,
//! `graphql_channel`, `graphql_properties`, `graphql_notification`, `graphql_email`,
-//! `graphql_entity_mutation`) into the complete schema served by
+//! `graphql_favorite`, `graphql_entity_mutation`) into the complete schema served by
//! `document_storage_service` and exported as SDL.
#![deny(missing_docs)]
#![deny(clippy::missing_docs_in_private_items)]
@@ -43,7 +43,8 @@ pub use graphql_entity_mutation::{
RenameEntityInput, UpdateEntitySharePolicyInput,
};
pub use graphql_favorite::{
- EntityFavoriteEdgeReader, EntityFavoriteLoader, entity_favorite_loader,
+ EntityFavoriteEdgeReader, EntityFavoriteLoader, FavoriteMutationRoot, GraphqlFavorite,
+ NoOpFavoriteMutationService, ReorderFavoritesInput, entity_favorite_loader,
};
pub use graphql_notification::{
EntityNotificationsLoader, GraphqlNotificationUpdateOperation, NoOpNotificationMutationService,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 1a3413b422..56a1ba3e8e 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -11,6 +11,7 @@ use email::{
};
use entity_access::domain::ports::{EntityAccessService, NoOpEntityAccessService};
use entity_mutation::{EntityMutationService, UnavailableEntityMutationService};
+use favorites::domain::ports::FavoritesMutationService;
use graphql_activity::{
ActivityFeedInput, ActivityOverviewInput, ActivityReader, GraphqlActivityOverview,
GraphqlActivityPage, NoOpActivityReader, resolve_activity_feed, resolve_activity_overview,
@@ -25,7 +26,10 @@ use graphql_email::{
SoupEmailContentEdgeReader,
};
use graphql_entity_mutation::EntityMutationRoot;
-use graphql_favorite::{EntityFavoriteEdgeReader, NoOpEntityFavoriteEdgeReader};
+use graphql_favorite::{
+ EntityFavoriteEdgeReader, FavoriteMutationRoot, NoOpEntityFavoriteEdgeReader,
+ NoOpFavoriteMutationService,
+};
use graphql_notification::{
NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,
NotificationMutationService, NotificationSubscriptionRoot, SoupNotificationEdgeReader,
@@ -64,6 +68,7 @@ use crate::SoupEdges;
pub struct CompleteMutationRoot<
W: EntityPropertyWriter,
M: EntityMutationService,
+ F: FavoritesMutationService,
E: SoupEntityEdges,
C: ChannelActivityMutationService,
N: NotificationMutationService,
@@ -72,6 +77,7 @@ pub struct CompleteMutationRoot<
>(
PropertiesMutationRoot<W>,
EntityMutationRoot<M, E>,
+ FavoriteMutationRoot<F, E>,
ChannelMutationRoot<C, A>,
NotificationMutationRoot<N>,
GraphqlEmailMutation<ES, SoupEmailThreadMutationOutput<E>>,
@@ -80,18 +86,20 @@ pub struct CompleteMutationRoot<
impl<
W: EntityPropertyWriter,
M: EntityMutationService,
+ F: FavoritesMutationService,
E: SoupEntityEdges,
C: ChannelActivityMutationService,
N: NotificationMutationService,
A: ChannelActivityAuthorizer,
ES: EmailService,
-> CompleteMutationRoot<W, M, E, C, N, A, ES>
+> CompleteMutationRoot<W, M, F, E, C, N, A, ES>
{
/// Construct the composed mutation root.
fn new() -> Self {
Self(
PropertiesMutationRoot::<W>::new(),
EntityMutationRoot::<M, E>::new(),
+ FavoriteMutationRoot::<F, E>::new(),
ChannelMutationRoot::<C, A>::new(),
NotificationMutationRoot::<N>::new(),
GraphqlEmailMutation::<ES, SoupEmailThreadMutationOutput<E>>::new(),
@@ -124,19 +132,20 @@ where
/// `NS` the realtime notification subscription service, `E` the email service,
/// `EAS` the entity access service, `Auth` the authorization service, `St` the
/// embedding axum router state, `W` the property mutation writer, `M` the entity
-/// mutation service, `C` the channel activity mutation service, `N` the notification
-/// mutation service, `NR` the notification edge reader, `PR` the property edge
-/// reader, `ER` the email-content edge reader, `FR` the favorite edge reader,
-/// `AR` the access edge reader, and `AcR` the activity reader.
-pub type SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR> = Schema<
+/// mutation service, `FM` the favorites mutation service, `C` the channel activity
+/// mutation service, `N` the notification mutation service, `NR` the notification
+/// edge reader, `PR` the property edge reader, `ER` the email-content edge reader,
+/// `FR` the favorite edge reader, `AR` the access edge reader, and `AcR` the activity
+/// reader.
+pub type SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR> = Schema<
SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR, AcR>,
- CompleteMutationRoot<W, M, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>,
+ CompleteMutationRoot<W, M, FM, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>,
CompleteSubscriptionRoot<R, NS, Auth, St, NR, PR, ER, FR, AR, AcR>,
>;
/// GraphQL Soup schema type backed by shared query and realtime services.
-pub type SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR> =
- SoupSchema<Arc<S>, Arc<R>, Arc<NS>, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>;
+pub type SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR> =
+ SoupSchema<Arc<S>, Arc<R>, Arc<NS>, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>;
/// GraphQL Soup schema type backed by the no-op services, used only for
/// SDL export or introspection.
@@ -150,6 +159,7 @@ pub type SchemaOnlySoupSchema = SoupSchema<
SchemaOnlyState,
NoOpEntityPropertyWriter,
UnavailableEntityMutationService,
+ NoOpFavoriteMutationService,
NoOpChannelActivityMutationService,
NoOpNotificationMutationService,
NoOpSoupNotificationEdgeReader,
@@ -270,7 +280,7 @@ pub fn build_schema() -> SchemaOnlySoupSchema {
/// Build a GraphQL schema backed by a query service and no-op realtime service.
#[allow(clippy::type_complexity)]
-pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>(
+pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>(
service: S,
) -> SoupSchema<
S,
@@ -282,6 +292,7 @@ pub fn build_schema_with_service<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR
St,
W,
M,
+ FM,
C,
N,
NR,
@@ -302,6 +313,7 @@ where
MacroAuthorizationState<Auth>: FromRef<St>,
W: EntityPropertyWriter,
M: EntityMutationService,
+ FM: FavoritesMutationService,
C: ChannelActivityMutationService,
N: NotificationMutationService,
NR: SoupNotificationEdgeReader,
@@ -320,11 +332,30 @@ where
/// Build a GraphQL schema backed by query and realtime Soup services.
#[allow(clippy::type_complexity)]
-pub fn build_schema_with_services<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>(
+pub fn build_schema_with_services<
+ S,
+ R,
+ NS,
+ E,
+ EAS,
+ Auth,
+ St,
+ W,
+ M,
+ FM,
+ C,
+ N,
+ NR,
+ PR,
+ ER,
+ FR,
+ AR,
+ AcR,
+>(
service: S,
realtime_service: R,
notification_subscription_service: NS,
-) -> SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>
+) -> SoupSchema<S, R, NS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>
where
S: SoupService + Clone,
R: SoupRealtimeSubscriptionService + Clone,
@@ -339,6 +370,7 @@ where
MacroAuthorizationState<Auth>: FromRef<St>,
W: EntityPropertyWriter,
M: EntityMutationService,
+ FM: FavoritesMutationService,
C: ChannelActivityMutationService,
N: NotificationMutationService,
NR: SoupNotificationEdgeReader,
@@ -350,7 +382,7 @@ where
{
Schema::build(
SoupQueryRoot::new(service),
- CompleteMutationRoot::<W, M, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>::new(),
+ CompleteMutationRoot::<W, M, FM, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>::new(),
CompleteSubscriptionRoot(
SoupSubscriptionRoot::new(realtime_service),
NotificationSubscriptionRoot::new(notification_subscription_service),
@@ -361,7 +393,7 @@ where
/// Build a GraphQL schema backed by an `Arc`-shared query service.
#[allow(clippy::type_complexity)]
-pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>(
+pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>(
service: Arc<S>,
) -> SoupSchema<
Arc<S>,
@@ -373,6 +405,7 @@ pub fn build_schema_from_arc<S, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR
St,
W,
M,
+ FM,
C,
N,
NR,
@@ -393,6 +426,7 @@ where
MacroAuthorizationState<Auth>: FromRef<St>,
W: EntityPropertyWriter,
M: EntityMutationService,
+ FM: FavoritesMutationService,
C: ChannelActivityMutationService,
N: NotificationMutationService,
NR: SoupNotificationEdgeReader,
@@ -407,11 +441,11 @@ where
/// Build a GraphQL schema backed by `Arc`-shared query and realtime services.
#[allow(clippy::type_complexity)]
-pub fn build_schema_from_arcs<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>(
+pub fn build_schema_from_arcs<S, R, NS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>(
service: Arc<S>,
realtime_service: Arc<R>,
notification_subscription_service: Arc<NS>,
-) -> SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR, AcR>
+) -> SharedSoupSchema<S, R, NS, E, EAS, Auth, St, W, M, FM, C, N, NR, PR, ER, FR, AR, AcR>
where
S: SoupService,
R: SoupRealtimeSubscriptionService,
@@ -425,6 +459,7 @@ where
MacroAuthorizationState<Auth>: FromRef<St>,
W: EntityPropertyWriter,
M: EntityMutationService,
+ FM: FavoritesMutationService,
C: ChannelActivityMutationService,
N: NotificationMutationService,
NR: SoupNotificationEdgeReader,
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 31ff1b848e..d3f8c35c39 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -939,6 +939,7 @@ struct TestHarness {
TestState,
NoOpEntityPropertyWriter,
UnavailableEntityMutationService,
+ graphql_favorite::NoOpFavoriteMutationService,
NoOpChannelActivityMutationService,
NoOpNotificationMutationService,
NoOpSoupNotificationEdgeReader,
@@ -1100,6 +1101,7 @@ async fn soup_updates_subscribes_as_the_authenticated_user() {
SchemaOnlyState,
NoOpEntityPropertyWriter,
UnavailableEntityMutationService,
+ NoOpFavoriteMutationService,
NoOpChannelActivityMutationService,
NoOpNotificationMutationService,
NoOpSoupNotificationEdgeReader,
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 9c5a1e393d..538233d901 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -73,6 +73,14 @@ fn soup_response_schema_exposes_frontend_fields() {
"union SoupPatch = SoupUpdated | GraphqlCacheDeletion",
"type GraphqlMutationSuccess {",
"effects: [SoupPatch!]!",
+ "setEntityFavorite(entity: EntityRefInput!, favorite: Boolean!): GraphqlEntityMutationResult!",
+ "reorderFavorites(input: ReorderFavoritesInput!): [GraphqlFavorite!]!",
+ "input ReorderFavoritesInput {",
+ "favorites: [EntityRefInput!]!",
+ "type GraphqlFavorite {",
+ "entityType: GraphqlEntityType!",
+ "entityId: ID!",
+ "sortOrder: Float!",
"recordChannelActivity(input: RecordChannelActivityInput!): GraphqlChannelActivity!",
"updateNotifications(input: UpdateNotificationsInput!): [GraphqlNotification!]!",
"updateNotificationsForEntity(input: UpdateNotificationsForEntityInput!): [GraphqlNotification!]!",
diff --git a/crates/entity_mutation/src/ports.rs b/crates/entity_mutation/src/ports.rs
index 0222c9176b..b1f353c05f 100644
--- a/crates/entity_mutation/src/ports.rs
+++ b/crates/entity_mutation/src/ports.rs
@@ -65,14 +65,6 @@ pub trait EntityMutationService: Send + Sync + 'static {
actor: EntityMutationActor,
requests: Vec<DuplicateEntityRequest>,
) -> impl Future<Output = Vec<MutateEntitiesResult>> + Send;
-
- /// Add or remove an entity from the actor's favorites.
- fn set_favorite(
- &self,
- actor: EntityMutationActor,
- entity: Entity<'static>,
- favorite: bool,
- ) -> impl Future<Output = MutateEntitiesResult> + Send;
}
/// Schema-only implementation used when no mutation services are wired.
@@ -153,15 +145,4 @@ impl EntityMutationService for UnavailableEntityMutationService {
requests.into_iter().map(|request| request.entity),
)
}
-
- async fn set_favorite(
- &self,
- _actor: EntityMutationActor,
- entity: Entity<'static>,
- _favorite: bool,
- ) -> MutateEntitiesResult {
- Err(EntityMutationErrorCode::unsupported(
- report!(entity).attach("favorites"),
- ))
- }
}
diff --git a/crates/favorites/src/domain.rs b/crates/favorites/src/domain.rs
index 8623e6a1d9..6ac5fb7b67 100644
--- a/crates/favorites/src/domain.rs
+++ b/crates/favorites/src/domain.rs
@@ -2,6 +2,8 @@
pub mod models;
#[cfg(feature = "ports")]
+pub mod mutation_service;
+#[cfg(feature = "ports")]
pub mod ports;
#[cfg(feature = "ports")]
pub mod service;
diff --git a/crates/favorites/src/domain/models.rs b/crates/favorites/src/domain/models.rs
index 7df060eda3..973d275087 100644
--- a/crates/favorites/src/domain/models.rs
+++ b/crates/favorites/src/domain/models.rs
@@ -1,6 +1,7 @@
//! Domain models for favorites.
use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::{Entity, EntityType};
use serde::{Deserialize, Serialize};
@@ -56,12 +57,24 @@ pub struct FavoritesList {
pub favorites: Vec<Favorite>,
}
+/// Authenticated actor performing a favorites mutation.
+#[derive(Clone, Debug)]
+pub struct FavoritesMutationActor {
+ /// Stable Macro user id.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Organization id attached to the authenticated request, when present.
+ pub organization_id: Option<i64>,
+}
+
/// Errors returned by the favorites service.
#[derive(Debug, thiserror::Error)]
pub enum FavoritesError {
/// The favorite (or entity) could not be found in the user's collection.
#[error("favorite not found")]
NotFound,
+ /// The entity kind is not supported by the favorites mutation surface.
+ #[error("entities of type {0} cannot be favorited")]
+ UnsupportedEntityType(EntityType),
/// The request was invalid.
#[error("{0}")]
BadRequest(String),
diff --git a/crates/favorites/src/domain/mutation_service.rs b/crates/favorites/src/domain/mutation_service.rs
new file mode 100644
index 0000000000..b8824d0698
--- /dev/null
+++ b/crates/favorites/src/domain/mutation_service.rs
@@ -0,0 +1,98 @@
+//! Authorized favorites mutation use cases.
+
+#[cfg(test)]
+mod test;
+
+use std::sync::Arc;
+
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::{Entity, EntityType};
+
+use crate::domain::{
+ models::{Favorite, FavoritesError, FavoritesMutationActor},
+ ports::{FavoritesAuthorizer, FavoritesMutationService, FavoritesService},
+};
+
+/// Favorites mutation service that composes authorization with the core
+/// favorites service.
+#[derive(Debug, Clone)]
+pub struct FavoritesMutationServiceImpl<S, A> {
+ /// Core favorites use cases and persistence boundary.
+ favorites: Arc<S>,
+ /// Entity-view authorization boundary.
+ authorizer: Arc<A>,
+}
+
+impl<S, A> FavoritesMutationServiceImpl<S, A> {
+ /// Compose favorites mutations from the core service and authorizer.
+ pub fn new(favorites: Arc<S>, authorizer: Arc<A>) -> Self {
+ Self {
+ favorites,
+ authorizer,
+ }
+ }
+}
+
+impl<S, A> FavoritesMutationService for FavoritesMutationServiceImpl<S, A>
+where
+ S: FavoritesService,
+ A: FavoritesAuthorizer,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn set_favorite(
+ &self,
+ actor: FavoritesMutationActor,
+ entity: Entity<'static>,
+ favorite: bool,
+ ) -> Result<Entity<'static>, FavoritesError> {
+ validate_favoritable(entity.entity_type)?;
+
+ if favorite {
+ let receipt = self.authorizer.authorize_favorite(&actor, &entity).await?;
+ self.favorites.add_favorite(&receipt).await?;
+ } else {
+ self.favorites
+ .remove_favorite_by_entity(&actor.user_id, &entity)
+ .await?;
+ }
+
+ Ok(entity)
+ }
+
+ #[tracing::instrument(err, skip(self, ordered))]
+ async fn reorder_favorites(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ordered: Vec<Entity<'static>>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ self.favorites.reorder_favorites(&user_id, &ordered).await?;
+ self.favorites.list_favorites(&user_id).await
+ }
+}
+
+/// Validate the entity kinds supported by the favorite toggle.
+///
+/// Favorites storage is intentionally broader for trusted internal workflows,
+/// while the interactive toggle accepts only entity kinds with a supported
+/// user-facing favorite lifecycle.
+fn validate_favoritable(entity_type: EntityType) -> Result<(), FavoritesError> {
+ match entity_type {
+ EntityType::Document
+ | EntityType::Project
+ | EntityType::Chat
+ | EntityType::Channel
+ | EntityType::EmailThread
+ | EntityType::Call
+ | EntityType::ForeignEntity
+ | EntityType::CrmCompany => Ok(()),
+ EntityType::User
+ | EntityType::Team
+ | EntityType::ChannelMessage
+ | EntityType::StaticFile
+ | EntityType::CrmContact
+ | EntityType::CalendarEvent
+ | EntityType::Reminder
+ | EntityType::Skill
+ | EntityType::AgentSession => Err(FavoritesError::UnsupportedEntityType(entity_type)),
+ }
+}
diff --git a/crates/favorites/src/domain/mutation_service/test.rs b/crates/favorites/src/domain/mutation_service/test.rs
new file mode 100644
index 0000000000..4c0ce911d1
--- /dev/null
+++ b/crates/favorites/src/domain/mutation_service/test.rs
@@ -0,0 +1,268 @@
+use std::{collections::HashSet, sync::Mutex};
+
+use chrono::Utc;
+use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+
+use super::*;
+use crate::domain::ports::FavoritesAuthorizer;
+
+const USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum ServiceCall {
+ Add(EntityType, String),
+ Remove(EntityType, String),
+ Reorder(Vec<(EntityType, String)>),
+ List,
+}
+
+#[derive(Default)]
+struct FakeFavoritesService {
+ calls: Mutex<Vec<ServiceCall>>,
+}
+
+impl FakeFavoritesService {
+ fn calls(&self) -> Vec<ServiceCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl FavoritesService for FakeFavoritesService {
+ async fn add_favorite(
+ &self,
+ receipt: &EntityAccessReceipt<ViewAccessLevel>,
+ ) -> Result<Favorite, FavoritesError> {
+ let entity = receipt.entity();
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(ServiceCall::Add(
+ entity.entity_type,
+ entity.entity_id.clone(),
+ ));
+ Ok(favorite(entity.entity_type, &entity.entity_id, 0.0))
+ }
+
+ async fn add_favorite_with_established_access(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<Favorite, FavoritesError> {
+ Ok(favorite(entity.entity_type, &entity.entity_id, 0.0))
+ }
+
+ async fn list_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(ServiceCall::List);
+ Ok(vec![favorite(EntityType::Document, "document-1", 0.0)])
+ }
+
+ async fn remove_favorite_by_entity(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ entity: &Entity<'_>,
+ ) -> Result<(), FavoritesError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(ServiceCall::Remove(
+ entity.entity_type,
+ entity.entity_id.to_string(),
+ ));
+ Ok(())
+ }
+
+ async fn reorder_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ ordered: &[Entity<'_>],
+ ) -> Result<(), FavoritesError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(ServiceCall::Reorder(
+ ordered
+ .iter()
+ .map(|entity| (entity.entity_type, entity.entity_id.to_string()))
+ .collect(),
+ ));
+ Ok(())
+ }
+
+ async fn favorited_entities(
+ &self,
+ _user_id: &MacroUserIdStr<'_>,
+ _entities: &[Entity<'_>],
+ ) -> Result<HashSet<Entity<'static>>, FavoritesError> {
+ Ok(HashSet::new())
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct AuthorizerCall {
+ user_id: String,
+ organization_id: Option<i64>,
+ entity_type: EntityType,
+ entity_id: String,
+}
+
+#[derive(Default)]
+struct FakeAuthorizer {
+ calls: Mutex<Vec<AuthorizerCall>>,
+}
+
+impl FakeAuthorizer {
+ fn calls(&self) -> Vec<AuthorizerCall> {
+ self.calls.lock().expect("calls lock poisoned").clone()
+ }
+}
+
+impl FavoritesAuthorizer for FakeAuthorizer {
+ async fn authorize_favorite(
+ &self,
+ actor: &FavoritesMutationActor,
+ entity: &Entity<'static>,
+ ) -> Result<EntityAccessReceipt<ViewAccessLevel>, FavoritesError> {
+ self.calls
+ .lock()
+ .expect("calls lock poisoned")
+ .push(AuthorizerCall {
+ user_id: actor.user_id.to_string(),
+ organization_id: actor.organization_id,
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.to_string(),
+ });
+ Ok(
+ EntityAccessReceipt::<ViewAccessLevel>::dangerously_assert_authenticated_user(
+ actor.user_id.clone(),
+ &entity.entity_id,
+ entity.entity_type,
+ ),
+ )
+ }
+}
+
+fn actor() -> FavoritesMutationActor {
+ FavoritesMutationActor {
+ user_id: MacroUserIdStr::parse_from_str(USER_ID).expect("valid user id"),
+ organization_id: Some(42),
+ }
+}
+
+fn favorite(entity_type: EntityType, entity_id: &str, sort_order: f64) -> Favorite {
+ Favorite {
+ entity_type,
+ entity_id: entity_id.to_string(),
+ sort_order,
+ created_at: Utc::now(),
+ file_type: None,
+ document_sub_type: None,
+ channel_type: None,
+ channel_id: None,
+ }
+}
+
+#[tokio::test]
+async fn favorite_authorizes_then_delegates_to_core_service() {
+ let favorites = Arc::new(FakeFavoritesService::default());
+ let authorizer = Arc::new(FakeAuthorizer::default());
+ let service = FavoritesMutationServiceImpl::new(favorites.clone(), authorizer.clone());
+ let entity = EntityType::Document.with_entity_string("document-1".to_string());
+
+ let updated = service
+ .set_favorite(actor(), entity.clone(), true)
+ .await
+ .expect("favorite should succeed");
+
+ assert_eq!(updated, entity);
+ assert_eq!(
+ authorizer.calls(),
+ vec![AuthorizerCall {
+ user_id: USER_ID.to_string(),
+ organization_id: Some(42),
+ entity_type: EntityType::Document,
+ entity_id: "document-1".to_string(),
+ }]
+ );
+ assert_eq!(
+ favorites.calls(),
+ vec![ServiceCall::Add(
+ EntityType::Document,
+ "document-1".to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn unfavorite_delegates_without_requiring_current_entity_access() {
+ let favorites = Arc::new(FakeFavoritesService::default());
+ let authorizer = Arc::new(FakeAuthorizer::default());
+ let service = FavoritesMutationServiceImpl::new(favorites.clone(), authorizer.clone());
+ let entity = EntityType::Document.with_entity_string("document-1".to_string());
+
+ let updated = service
+ .set_favorite(actor(), entity.clone(), false)
+ .await
+ .expect("unfavorite should succeed");
+
+ assert_eq!(updated, entity);
+ assert!(authorizer.calls().is_empty());
+ assert_eq!(
+ favorites.calls(),
+ vec![ServiceCall::Remove(
+ EntityType::Document,
+ "document-1".to_string()
+ )]
+ );
+}
+
+#[tokio::test]
+async fn unsupported_toggle_is_rejected_before_authorization_or_persistence() {
+ let favorites = Arc::new(FakeFavoritesService::default());
+ let authorizer = Arc::new(FakeAuthorizer::default());
+ let service = FavoritesMutationServiceImpl::new(favorites.clone(), authorizer.clone());
+
+ let error = service
+ .set_favorite(
+ actor(),
+ EntityType::User.with_entity_string("user-1".to_string()),
+ true,
+ )
+ .await
+ .expect_err("users are not favoritable");
+
+ assert!(matches!(
+ error,
+ FavoritesError::UnsupportedEntityType(EntityType::User)
+ ));
+ assert!(authorizer.calls().is_empty());
+ assert!(favorites.calls().is_empty());
+}
+
+#[tokio::test]
+async fn reorder_delegates_and_returns_the_authoritative_collection() {
+ let favorites = Arc::new(FakeFavoritesService::default());
+ let service =
+ FavoritesMutationServiceImpl::new(favorites.clone(), Arc::new(FakeAuthorizer::default()));
+ let ordered = vec![EntityType::Document.with_entity_string("document-1".to_string())];
+
+ let result = service
+ .reorder_favorites(actor().user_id, ordered)
+ .await
+ .expect("reorder should succeed");
+
+ assert_eq!(result.len(), 1);
+ assert_eq!(result[0].entity_id, "document-1");
+ assert_eq!(
+ favorites.calls(),
+ vec![
+ ServiceCall::Reorder(vec![(EntityType::Document, "document-1".to_string())]),
+ ServiceCall::List,
+ ]
+ );
+}
diff --git a/crates/favorites/src/domain/ports.rs b/crates/favorites/src/domain/ports.rs
index a6358403bd..cf6aa26092 100644
--- a/crates/favorites/src/domain/ports.rs
+++ b/crates/favorites/src/domain/ports.rs
@@ -2,11 +2,14 @@
use std::collections::HashSet;
-use entity_access::domain::models::{EntityAccessReceipt, ViewAccessLevel};
+use entity_access::domain::{
+ models::{AccessError, EntityAccessReceipt, ViewAccessLevel},
+ ports::EntityAccessService,
+};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
-use crate::domain::models::{Favorite, FavoritesError};
+use crate::domain::models::{Favorite, FavoritesError, FavoritesMutationActor};
/// Outbound persistence port for favorites.
pub trait FavoritesRepo: Send + Sync + 'static {
@@ -62,6 +65,63 @@ pub trait FavoritesRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<HashSet<Entity<'static>>, Self::Err>> + Send;
}
+/// Authorization port used by favorites mutation use cases.
+pub trait FavoritesAuthorizer: Send + Sync + 'static {
+ /// Verify that the actor can view the entity being added to favorites.
+ fn authorize_favorite(
+ &self,
+ actor: &FavoritesMutationActor,
+ entity: &Entity<'static>,
+ ) -> impl Future<Output = Result<EntityAccessReceipt<ViewAccessLevel>, FavoritesError>> + Send;
+}
+
+impl<A> FavoritesAuthorizer for A
+where
+ A: EntityAccessService,
+{
+ async fn authorize_favorite(
+ &self,
+ actor: &FavoritesMutationActor,
+ entity: &Entity<'static>,
+ ) -> Result<EntityAccessReceipt<ViewAccessLevel>, FavoritesError> {
+ self.generate_entity_access_receipt::<ViewAccessLevel>(
+ &actor.user_id,
+ actor.organization_id,
+ &entity.entity_id,
+ entity.entity_type,
+ )
+ .await
+ .map_err(|error| match error {
+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {
+ FavoritesError::Unauthorized
+ }
+ AccessError::NotFound(_) => FavoritesError::NotFound,
+ AccessError::BadRequest(message) => FavoritesError::BadRequest(message.to_string()),
+ error @ (AccessError::Unavailable(_) | AccessError::Internal(_)) => {
+ FavoritesError::Internal(anyhow::Error::new(error))
+ }
+ })
+ }
+}
+
+/// Inbound service port for favorite and ordering mutations.
+pub trait FavoritesMutationService: Send + Sync + 'static {
+ /// Set whether an entity belongs to the actor's favorites collection.
+ fn set_favorite(
+ &self,
+ actor: FavoritesMutationActor,
+ entity: Entity<'static>,
+ favorite: bool,
+ ) -> impl Future<Output = Result<Entity<'static>, FavoritesError>> + Send;
+
+ /// Persist a complete manual order and return the authoritative collection.
+ fn reorder_favorites(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ordered: Vec<Entity<'static>>,
+ ) -> impl Future<Output = Result<Vec<Favorite>, FavoritesError>> + Send;
+}
+
/// Inbound service port: the favorites API used by drivers (HTTP, soup enrichment).
pub trait FavoritesService: Send + Sync + 'static {
/// Add an entity to the user's favorites (idempotent).
diff --git a/crates/favorites/src/inbound/axum_router.rs b/crates/favorites/src/inbound/axum_router.rs
index 4c90d4ba87..b978b3fdc3 100644
--- a/crates/favorites/src/inbound/axum_router.rs
+++ b/crates/favorites/src/inbound/axum_router.rs
@@ -285,7 +285,9 @@ impl IntoResponse for FavoritesError {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
FavoritesError::NotFound => StatusCode::NOT_FOUND,
- FavoritesError::BadRequest(_) => StatusCode::BAD_REQUEST,
+ FavoritesError::UnsupportedEntityType(_) | FavoritesError::BadRequest(_) => {
+ StatusCode::BAD_REQUEST
+ }
FavoritesError::Unauthorized => StatusCode::FORBIDDEN,
FavoritesError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
diff --git a/crates/graphql_entity_mutation/src/mutations.rs b/crates/graphql_entity_mutation/src/mutations.rs
index 77588fddf5..69858c8501 100644
--- a/crates/graphql_entity_mutation/src/mutations.rs
+++ b/crates/graphql_entity_mutation/src/mutations.rs
@@ -411,6 +411,19 @@ pub enum GraphqlEntityMutationResult<E: SoupEntityEdges> {
}
impl<E: SoupEntityEdges> GraphqlEntityMutationResult<E> {
+ /// Construct a successful result that refreshes one entity's Soup record.
+ pub fn from_updated_entity(entity: Entity<'static>) -> Self {
+ Self::Success(GraphqlMutationSuccess {
+ effects: vec![EntityMutationEffect::updated(entity)],
+ edges: PhantomData,
+ })
+ }
+
+ /// Construct a failed result from a domain-classified error.
+ pub fn from_error_code(error: EntityMutationErrorCode) -> Self {
+ Self::Error(GraphqlMutationError(error))
+ }
+
/// Convert a borrowed domain mutation outcome into its GraphQL union variant.
fn new(x: Result<&EntityMutationSuccess, &EntityMutationErrorCode>) -> Self {
match x {
@@ -421,17 +434,6 @@ impl<E: SoupEntityEdges> GraphqlEntityMutationResult<E> {
Err(error) => Self::Error(GraphqlMutationError(*error)),
}
}
-
- /// Convert an owned domain mutation outcome into its GraphQL union variant.
- fn new_owned(x: MutateEntitiesResult) -> Self {
- match x {
- Ok(result) => Self::Success(GraphqlMutationSuccess {
- effects: result.effects,
- edges: PhantomData,
- }),
- Err(error) => Self::Error(GraphqlMutationError(error)),
- }
- }
}
/// Batch mutation payload. Results preserve input order and allow partial
@@ -635,18 +637,4 @@ impl<S: EntityMutationService, E: SoupEntityEdges> EntityMutationRoot<S, E> {
.await,
))
}
-
- /// Add or remove an entity from the actor's favorites.
- async fn set_entity_favorite(
- &self,
- ctx: &Context<'_>,
- entity: EntityRefInput,
- favorite: bool,
- ) -> async_graphql::Result<GraphqlEntityMutationResult<E>> {
- let res = mutation_service::<S>(ctx)?
- .set_favorite(mutation_actor(ctx)?, entity.into_model(), favorite)
- .await;
-
- Ok(GraphqlEntityMutationResult::new_owned(res))
- }
}
diff --git a/crates/graphql_favorite/Cargo.toml b/crates/graphql_favorite/Cargo.toml
index 7712b0617d..0b370b4d95 100644
--- a/crates/graphql_favorite/Cargo.toml
+++ b/crates/graphql_favorite/Cargo.toml
@@ -6,12 +6,21 @@ publish = false
[dependencies]
async-graphql = { workspace = true, features = ["dataloader"] }
+entity_mutation = { path = "../entity_mutation" }
favorites = { path = "../favorites", default-features = false, features = [
"ports",
] }
+graphql_common = { path = "../graphql_common" }
+graphql_entity_mutation = { path = "../graphql_entity_mutation" }
+graphql_soup = { path = "../graphql_soup" }
macro_user_id = { path = "../macro_user_id" }
model-entity = { path = "../model-entity" }
rootcause = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+chrono = { workspace = true }
+graphql_permission = { path = "../graphql_permission" }
+uuid = { workspace = true }
diff --git a/crates/graphql_favorite/src/lib.rs b/crates/graphql_favorite/src/lib.rs
index 5e5a1d5da8..21c3b1d78a 100644
--- a/crates/graphql_favorite/src/lib.rs
+++ b/crates/graphql_favorite/src/lib.rs
@@ -1,12 +1,18 @@
-//! GraphQL inbound adapter for the favorites domain: the DataLoader-backed
-//! current-viewer favorite edge attached to Soup entities.
+//! GraphQL inbound adapter for the favorites domain: ordered favorite objects,
+//! mutations, and the DataLoader-backed current-viewer favorite edge.
#![deny(missing_docs)]
#![deny(clippy::missing_docs_in_private_items)]
/// Lazy favorite-state edge loading.
-mod favorite;
+mod loaders;
+/// GraphQL favorite mutation adapter.
+mod mutations;
+/// GraphQL favorite output objects.
+mod objects;
-pub use favorite::{
+pub use loaders::{
EntityFavoriteEdgeReader, EntityFavoriteLoader, NoOpEntityFavoriteEdgeReader,
entity_favorite_loader, load_entity_favorite,
};
+pub use mutations::{FavoriteMutationRoot, NoOpFavoriteMutationService, ReorderFavoritesInput};
+pub use objects::GraphqlFavorite;
diff --git a/crates/graphql_favorite/src/favorite.rs b/crates/graphql_favorite/src/loaders.rs
similarity index 100%
rename from crates/graphql_favorite/src/favorite.rs
rename to crates/graphql_favorite/src/loaders.rs
diff --git a/crates/graphql_favorite/src/favorite/test.rs b/crates/graphql_favorite/src/loaders/test.rs
similarity index 100%
rename from crates/graphql_favorite/src/favorite/test.rs
rename to crates/graphql_favorite/src/loaders/test.rs
diff --git a/crates/graphql_favorite/src/mutations.rs b/crates/graphql_favorite/src/mutations.rs
new file mode 100644
index 0000000000..938bc8cfdf
--- /dev/null
+++ b/crates/graphql_favorite/src/mutations.rs
@@ -0,0 +1,155 @@
+use std::{marker::PhantomData, sync::Arc};
+
+use async_graphql::{Context, InputObject, Object};
+use entity_mutation::EntityMutationErrorCode;
+use favorites::domain::{
+ models::{Favorite, FavoritesError, FavoritesMutationActor},
+ ports::FavoritesMutationService,
+};
+use graphql_common::require_authenticated_user;
+use graphql_entity_mutation::{EntityRefInput, GraphqlEntityMutationResult};
+use graphql_soup::SoupEntityEdges;
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::Entity;
+
+use crate::objects::GraphqlFavorite;
+
+#[cfg(test)]
+mod test;
+
+/// Root GraphQL adapter for favorites mutations.
+pub struct FavoriteMutationRoot<S, E>(PhantomData<fn() -> (S, E)>);
+
+impl<S, E> FavoriteMutationRoot<S, E> {
+ /// Construct a favorites mutation root.
+ pub fn new() -> Self {
+ Self(PhantomData)
+ }
+}
+
+impl<S, E> Default for FavoriteMutationRoot<S, E> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Schema-only favorites mutation service.
+#[derive(Clone, Copy, Debug, Default)]
+pub struct NoOpFavoriteMutationService;
+
+impl FavoritesMutationService for NoOpFavoriteMutationService {
+ async fn set_favorite(
+ &self,
+ _actor: FavoritesMutationActor,
+ _entity: Entity<'static>,
+ _favorite: bool,
+ ) -> Result<Entity<'static>, FavoritesError> {
+ Err(FavoritesError::BadRequest(
+ "favorite mutations are not configured".to_string(),
+ ))
+ }
+
+ async fn reorder_favorites(
+ &self,
+ _user_id: MacroUserIdStr<'static>,
+ _ordered: Vec<Entity<'static>>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ Err(FavoritesError::BadRequest(
+ "favorite mutations are not configured".to_string(),
+ ))
+ }
+}
+
+/// Input for persisting the authenticated user's complete favorites order.
+#[derive(InputObject)]
+pub struct ReorderFavoritesInput {
+ /// Favorited entities in the desired order.
+ pub favorites: Vec<EntityRefInput>,
+}
+
+/// Map a favorites failure into the existing entity-mutation result vocabulary.
+fn mutation_error_code(error: FavoritesError) -> EntityMutationErrorCode {
+ match error {
+ error @ FavoritesError::UnsupportedEntityType(_) => {
+ EntityMutationErrorCode::unsupported(rootcause::report!(error))
+ }
+ error @ FavoritesError::NotFound => {
+ EntityMutationErrorCode::not_found(rootcause::report!(error))
+ }
+ error @ FavoritesError::BadRequest(_) => {
+ EntityMutationErrorCode::invalid(rootcause::report!(error))
+ }
+ error @ FavoritesError::Unauthorized => {
+ EntityMutationErrorCode::forbidden(rootcause::report!(error))
+ }
+ error @ FavoritesError::Internal(_) => {
+ EntityMutationErrorCode::internal(rootcause::report!(error))
+ }
+ }
+}
+
+/// Convert an aggregate favorites failure into a user-safe GraphQL error.
+fn reorder_error(error: FavoritesError) -> async_graphql::Error {
+ let message = match &error {
+ FavoritesError::NotFound => "favorite not found".to_string(),
+ FavoritesError::UnsupportedEntityType(_) | FavoritesError::BadRequest(_) => {
+ error.to_string()
+ }
+ FavoritesError::Unauthorized => "not authorized to update favorites".to_string(),
+ FavoritesError::Internal(_) => {
+ tracing::error!(error = ?error, "failed to reorder favorites");
+ "favorites mutation failed".to_string()
+ }
+ };
+ async_graphql::Error::new(message)
+}
+
+/// GraphQL favorites mutations.
+#[Object]
+impl<S, E> FavoriteMutationRoot<S, E>
+where
+ S: FavoritesMutationService,
+ E: SoupEntityEdges,
+{
+ /// Add or remove an entity from the actor's favorites.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn set_entity_favorite(
+ &self,
+ ctx: &Context<'_>,
+ entity: EntityRefInput,
+ favorite: bool,
+ ) -> async_graphql::Result<GraphqlEntityMutationResult<E>> {
+ let actor = ctx.data::<FavoritesMutationActor>()?.clone();
+ let service = ctx.data::<Arc<S>>()?;
+ let result = service
+ .set_favorite(actor, entity.into_model(), favorite)
+ .await;
+
+ Ok(match result {
+ Ok(entity) => GraphqlEntityMutationResult::from_updated_entity(entity),
+ Err(error) => GraphqlEntityMutationResult::from_error_code(mutation_error_code(error)),
+ })
+ }
+
+ /// Persist the authenticated user's complete favorites order and return the authoritative list.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn reorder_favorites(
+ &self,
+ ctx: &Context<'_>,
+ input: ReorderFavoritesInput,
+ ) -> async_graphql::Result<Vec<GraphqlFavorite>> {
+ let user_id = require_authenticated_user(ctx)?;
+ let ordered = input
+ .favorites
+ .into_iter()
+ .map(EntityRefInput::into_model)
+ .collect();
+ let service = ctx.data::<Arc<S>>()?;
+ let favorites = service
+ .reorder_favorites(user_id, ordered)
+ .await
+ .map_err(reorder_error)?;
+
+ Ok(favorites.into_iter().map(GraphqlFavorite::new).collect())
+ }
+}
diff --git a/crates/graphql_favorite/src/mutations/test.rs b/crates/graphql_favorite/src/mutations/test.rs
new file mode 100644
index 0000000000..e523c0b6fe
--- /dev/null
+++ b/crates/graphql_favorite/src/mutations/test.rs
@@ -0,0 +1,279 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{Context, EmptySubscription, Object, Schema, SimpleObject, value};
+use entity_mutation::EntityMutationActor;
+use favorites::domain::models::FavoritesMutationActor;
+use graphql_soup::SoupEntityEdges;
+use model_entity::EntityType;
+use uuid::Uuid;
+
+use super::*;
+
+/// Minimal query root for the isolated mutation schema.
+struct QueryRoot;
+
+#[Object]
+impl QueryRoot {
+ async fn health(&self) -> bool {
+ true
+ }
+}
+
+/// Minimal composed edge object needed by the shared mutation result.
+#[derive(Clone, SimpleObject)]
+struct TestSoupEdges {
+ available: bool,
+}
+
+/// Minimal email edge object needed by the Soup edge trait.
+#[derive(Clone, SimpleObject)]
+struct TestEmailEdges {
+ available: bool,
+}
+
+impl SoupEntityEdges for TestSoupEdges {
+ type Property = String;
+ type Notification = String;
+ type ActivityEvent = String;
+ type EmailThreadEdges = TestEmailEdges;
+
+ fn from_entity(_entity: Entity<'static>) -> Self {
+ Self { available: true }
+ }
+
+ fn email_thread_edges(_email_thread_id: Uuid) -> Self::EmailThreadEdges {
+ TestEmailEdges { available: true }
+ }
+
+ async fn resolve_properties(
+ &self,
+ _ctx: &Context<'_>,
+ ) -> async_graphql::Result<Vec<Self::Property>> {
+ Ok(Vec::new())
+ }
+
+ async fn resolve_notifications(
+ &self,
+ _ctx: &Context<'_>,
+ ) -> async_graphql::Result<Vec<Self::Notification>> {
+ Ok(Vec::new())
+ }
+
+ async fn resolve_is_favorited(&self, _ctx: &Context<'_>) -> async_graphql::Result<bool> {
+ Ok(true)
+ }
+
+ async fn resolve_viewer_permission(
+ &self,
+ _ctx: &Context<'_>,
+ ) -> async_graphql::Result<Option<graphql_permission::GraphqlEntityPermission>> {
+ Ok(None)
+ }
+
+ async fn resolve_activity(
+ &self,
+ _ctx: &Context<'_>,
+ _limit: Option<i32>,
+ ) -> async_graphql::Result<Vec<Self::ActivityEvent>> {
+ Ok(Vec::new())
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct SetCall {
+ actor_user_id: String,
+ organization_id: Option<i64>,
+ entity_type: EntityType,
+ entity_id: String,
+ favorite: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+struct ReorderCall {
+ user_id: String,
+ entities: Vec<(EntityType, String)>,
+}
+
+#[derive(Default)]
+struct CapturingService {
+ set_call: Mutex<Option<SetCall>>,
+ reorder_call: Mutex<Option<ReorderCall>>,
+}
+
+impl FavoritesMutationService for CapturingService {
+ async fn set_favorite(
+ &self,
+ actor: FavoritesMutationActor,
+ entity: Entity<'static>,
+ favorite: bool,
+ ) -> Result<Entity<'static>, FavoritesError> {
+ *self.set_call.lock().expect("set call lock poisoned") = Some(SetCall {
+ actor_user_id: actor.user_id.to_string(),
+ organization_id: actor.organization_id,
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.to_string(),
+ favorite,
+ });
+ Ok(entity)
+ }
+
+ async fn reorder_favorites(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ ordered: Vec<Entity<'static>>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ *self
+ .reorder_call
+ .lock()
+ .expect("reorder call lock poisoned") = Some(ReorderCall {
+ user_id: user_id.to_string(),
+ entities: ordered
+ .iter()
+ .map(|entity| (entity.entity_type, entity.entity_id.to_string()))
+ .collect(),
+ });
+ Ok(ordered
+ .into_iter()
+ .enumerate()
+ .map(|(index, entity)| Favorite {
+ entity_type: entity.entity_type,
+ entity_id: entity.entity_id.into_owned(),
+ sort_order: index as f64,
+ created_at: chrono::Utc::now(),
+ file_type: None,
+ document_sub_type: None,
+ channel_type: None,
+ channel_id: None,
+ })
+ .collect())
+ }
+}
+
+fn user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").expect("valid user id")
+}
+
+fn schema(
+ service: Arc<CapturingService>,
+) -> Schema<QueryRoot, FavoriteMutationRoot<CapturingService, TestSoupEdges>, EmptySubscription> {
+ let user_id = user_id();
+ Schema::build(
+ QueryRoot,
+ FavoriteMutationRoot::<CapturingService, TestSoupEdges>::new(),
+ EmptySubscription,
+ )
+ .data(service)
+ .data(user_id.clone())
+ .data(FavoritesMutationActor {
+ user_id: user_id.clone(),
+ organization_id: Some(42),
+ })
+ .data(EntityMutationActor {
+ user_id,
+ organization_id: Some(42),
+ })
+ .finish()
+}
+
+#[tokio::test]
+async fn set_entity_favorite_preserves_the_toggle_and_delegates_to_favorites() {
+ let service = Arc::new(CapturingService::default());
+ let response = schema(service.clone())
+ .execute(
+ r#"
+ mutation {
+ setEntityFavorite(
+ entity: { type: DOCUMENT, id: "document-1" }
+ favorite: true
+ ) {
+ __typename
+ ... on GraphqlMutationSuccess {
+ effects { __typename }
+ }
+ }
+ }
+ "#,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data,
+ value!({
+ "setEntityFavorite": {
+ "__typename": "GraphqlMutationSuccess",
+ "effects": [{ "__typename": "SoupUpdated" }],
+ }
+ })
+ );
+ assert_eq!(
+ service
+ .set_call
+ .lock()
+ .expect("set call lock poisoned")
+ .clone(),
+ Some(SetCall {
+ actor_user_id: "macro|[email protected]".to_string(),
+ organization_id: Some(42),
+ entity_type: EntityType::Document,
+ entity_id: "document-1".to_string(),
+ favorite: true,
+ })
+ );
+}
+
+#[tokio::test]
+async fn reorder_favorites_delegates_and_returns_authoritative_order() {
+ let service = Arc::new(CapturingService::default());
+ let response = schema(service.clone())
+ .execute(
+ r#"
+ mutation {
+ reorderFavorites(input: {
+ favorites: [
+ { type: PROJECT, id: "project-1" }
+ { type: DOCUMENT, id: "document-1" }
+ ]
+ }) {
+ entityType
+ entityId
+ sortOrder
+ }
+ }
+ "#,
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data,
+ value!({
+ "reorderFavorites": [
+ {
+ "entityType": "PROJECT",
+ "entityId": "project-1",
+ "sortOrder": 0.0,
+ },
+ {
+ "entityType": "DOCUMENT",
+ "entityId": "document-1",
+ "sortOrder": 1.0,
+ },
+ ]
+ })
+ );
+ assert_eq!(
+ service
+ .reorder_call
+ .lock()
+ .expect("reorder call lock poisoned")
+ .clone(),
+ Some(ReorderCall {
+ user_id: "macro|[email protected]".to_string(),
+ entities: vec![
+ (EntityType::Project, "project-1".to_string()),
+ (EntityType::Document, "document-1".to_string()),
+ ],
+ })
+ );
+}
diff --git a/crates/graphql_favorite/src/objects.rs b/crates/graphql_favorite/src/objects.rs
new file mode 100644
index 0000000000..ab22a432ee
--- /dev/null
+++ b/crates/graphql_favorite/src/objects.rs
@@ -0,0 +1,57 @@
+use async_graphql::{ID, Object};
+use favorites::domain::models::Favorite;
+use graphql_common::GraphqlEntityType;
+
+/// An entity in the authenticated user's ordered favorites collection.
+pub struct GraphqlFavorite(Favorite);
+
+impl GraphqlFavorite {
+ /// Construct a GraphQL favorite from its domain model.
+ pub fn new(favorite: Favorite) -> Self {
+ Self(favorite)
+ }
+}
+
+/// GraphQL fields for an ordered favorite.
+#[Object]
+impl GraphqlFavorite {
+ /// Canonical type of the favorited entity.
+ async fn entity_type(&self) -> GraphqlEntityType {
+ GraphqlEntityType::new(self.0.entity_type)
+ }
+
+ /// Canonical identifier of the favorited entity.
+ async fn entity_id(&self) -> ID {
+ ID(self.0.entity_id.clone())
+ }
+
+ /// Manual ordering value; lower values sort first.
+ async fn sort_order(&self) -> f64 {
+ self.0.sort_order
+ }
+
+ /// Time at which the entity was first favorited, in RFC 3339 format.
+ async fn created_at(&self) -> String {
+ self.0.created_at.to_rfc3339()
+ }
+
+ /// File type of a favorited document, when applicable.
+ async fn file_type(&self) -> Option<&str> {
+ self.0.file_type.as_deref()
+ }
+
+ /// Document subtype of a favorited document, when applicable.
+ async fn document_sub_type(&self) -> Option<&str> {
+ self.0.document_sub_type.as_deref()
+ }
+
+ /// Channel type of a favorited channel, when applicable.
+ async fn channel_type(&self) -> Option<&str> {
+ self.0.channel_type.as_deref()
+ }
+
+ /// Owning channel id of a favorited channel message, when applicable.
+ async fn channel_id(&self) -> Option<ID> {
+ self.0.channel_id.clone().map(ID)
+ }
+}
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index 1a75f3f76a..4db188d127 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -53,7 +53,8 @@ use email::{
};
use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};
use favorites::{
- domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,
+ domain::{mutation_service::FavoritesMutationServiceImpl, service::FavoritesServiceImpl},
+ inbound::axum_router::FavoritesRouterState,
outbound::pg_favorites_repo::PgFavoritesRepo,
};
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
@@ -192,6 +193,7 @@ pub(crate) type DssGraphqlSoupSchema = complete_graph::SharedSoupSchema<
ApiContext,
complete_graph::PropertiesEntityPropertyWriter<PropertiesService, EntityAccessService>,
DssEntityMutationService,
+ FavoritesMutationServiceType,
DssChannelService,
ai_tools::ToolNotificationService,
Arc<ai_tools::ToolNotificationService>,
@@ -434,13 +436,16 @@ pub(crate) type DssEntityMutationService =
DssEmailService,
ProjectService,
EntityAccessService,
- FavoritesServiceType,
crate::outbound::entity_mutation::DssEntityLifecycleAdapter<DssEventBroker>,
>;
/// Type alias for the favorites service.
pub(crate) type FavoritesServiceType = FavoritesServiceImpl<PgFavoritesRepo>;
+/// Authorized favorites mutation service wired into GraphQL.
+pub(crate) type FavoritesMutationServiceType =
+ FavoritesMutationServiceImpl<FavoritesServiceType, EntityAccessService>;
+
/// Type alias for the favorites router state.
pub(crate) type DssFavoritesState =
FavoritesRouterState<FavoritesServiceType, EntityAccessService, AuthorizationService>;
@@ -525,6 +530,7 @@ pub(crate) struct ApiContext {
pub graphql_entity_mutation_service: Arc<DssEntityMutationService>,
pub favorites_state: DssFavoritesState,
pub favorites_service: Arc<FavoritesServiceType>,
+ pub favorites_mutation_service: Arc<FavoritesMutationServiceType>,
pub user_api_key_state: DssUserApiKeyState,
pub reminders_state: DssRemindersState,
pub collab_surface_state: DssCollabSurfaceState,
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index b9a34f5ce4..223dcd9928 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -154,7 +154,12 @@ fn insert_graphql_context_data(
user_id: macro_user_id.clone(),
organization_id,
});
+ data.insert(favorites::domain::models::FavoritesMutationActor {
+ user_id: macro_user_id.clone(),
+ organization_id,
+ });
data.insert(state.graphql_entity_mutation_service.clone());
+ data.insert(state.favorites_mutation_service.clone());
data.insert(state.channel_service.clone());
data.insert(state.graphql_notification_reader.clone());
data.insert(state.soup_router_state.email_service());
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 328be81f0b..27c16781d3 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -74,7 +74,8 @@ use email::{
};
use embedding::embedding_provider::openai::TextEmbedding3Small;
use favorites::{
- domain::service::FavoritesServiceImpl, inbound::axum_router::FavoritesRouterState,
+ domain::{mutation_service::FavoritesMutationServiceImpl, service::FavoritesServiceImpl},
+ inbound::axum_router::FavoritesRouterState,
outbound::pg_favorites_repo::PgFavoritesRepo,
};
use foreign_entity::{
@@ -1222,6 +1223,10 @@ async fn run() -> anyhow::Result<()> {
});
let favorites_service = Arc::new(FavoritesServiceImpl::new(PgFavoritesRepo::new(db.clone())));
+ let favorites_mutation_service = Arc::new(FavoritesMutationServiceImpl::new(
+ favorites_service.clone(),
+ entity_access_service.clone(),
+ ));
let user_api_key_service = Arc::new(UserApiKeyServiceImpl::new(PgUserApiKeysRepo::new(
db.clone(),
)));
@@ -1303,7 +1308,6 @@ async fn run() -> anyhow::Result<()> {
Arc::new(email_service.clone()),
project_service.clone(),
entity_access_service.clone(),
- favorites_service.clone(),
Arc::new(outbound::entity_mutation::DssEntityLifecycleAdapter::new(
db.clone(),
redis_sha_client.clone(),
@@ -1329,6 +1333,7 @@ async fn run() -> anyhow::Result<()> {
authorization_state.clone(),
),
favorites_service,
+ favorites_mutation_service,
user_api_key_state: UserApiKeyRouterState::new(
user_api_key_service,
authorization_state.clone(),
diff --git a/services/document_storage_service/src/service/entity_mutation.rs b/services/document_storage_service/src/service/entity_mutation.rs
index 0421f7f92e..0e23279f3d 100644
--- a/services/document_storage_service/src/service/entity_mutation.rs
+++ b/services/document_storage_service/src/service/entity_mutation.rs
@@ -25,9 +25,7 @@ use chat::domain::ports::ChatService;
use documents_hex::domain::ports::DocumentService;
use email::domain::ports::EmailService;
use entity_access::domain::{
- models::{
- AccessError, EditAccessLevel, EntityAccessReceipt, RequiredPermission, ViewAccessLevel,
- },
+ models::{AccessError, EditAccessLevel, EntityAccessReceipt, RequiredPermission},
ports::EntityAccessService,
};
use entity_mutation::{
@@ -37,7 +35,6 @@ use entity_mutation::{
RestoreEntity, TrashEntity, UpdateEntitySharePolicy, UpdateEntitySharePolicyRequest,
capability::MoveEntityRequest as CapabilityMoveEntityRequest,
};
-use favorites::domain::{models::FavoritesError, ports::FavoritesService};
use futures::{StreamExt, stream};
use model_entity::{Entity, EntityType};
use models_permissions::share_permission::UpdateSharePermissionRequestV2;
@@ -119,24 +116,6 @@ fn target_project_failure(error: AccessError) -> EntityMutationErrorCode {
access_failure(error)
}
-/// Map a favorites-domain failure onto the public vocabulary.
-fn favorites_failure(error: FavoritesError) -> EntityMutationErrorCode {
- match error {
- error @ FavoritesError::NotFound => {
- EntityMutationErrorCode::not_found(rootcause::report!(error))
- }
- error @ FavoritesError::BadRequest(_) => {
- EntityMutationErrorCode::invalid(rootcause::report!(error))
- }
- error @ FavoritesError::Unauthorized => {
- EntityMutationErrorCode::forbidden(rootcause::report!(error))
- }
- error @ FavoritesError::Internal(_) => {
- EntityMutationErrorCode::internal(rootcause::report!(error))
- }
- }
-}
-
/// Map a lifecycle-port failure onto the public vocabulary.
fn lifecycle_failure(error: LifecycleError) -> EntityMutationErrorCode {
match error {
@@ -164,35 +143,6 @@ fn success(effects: Vec<EntityMutationEffect>) -> EntityMutationResult {
Ok(EntityMutationSuccess { effects })
}
-/// Entity kinds whose favorite mutation can return a Soup update effect.
-///
-/// The REST favorites domain remains broader; this capability surface accepts
-/// only entities representable by the GraphQL Soup contract. Exhaustiveness
-/// makes each new [`EntityType`] an explicit decision.
-fn favoritable(entity_type: EntityType) -> bool {
- match entity_type {
- EntityType::Document
- | EntityType::Project
- | EntityType::Chat
- | EntityType::Channel
- | EntityType::EmailThread
- | EntityType::Call
- | EntityType::ForeignEntity
- | EntityType::CrmCompany => true,
- EntityType::User
- | EntityType::Team
- | EntityType::ChannelMessage
- | EntityType::StaticFile
- | EntityType::CrmContact
- | EntityType::CalendarEvent
- // Reminders are managed through the reminders API, not favorites.
- | EntityType::Reminder
- | EntityType::Skill
- // Agent sessions are not entity-mutation targets.
- | EntityType::AgentSession => false,
- }
-}
-
async fn collect_ordered<F>(futures: impl IntoIterator<Item = F>) -> Vec<EntityMutationResult>
where
F: Future<Output = EntityMutationResult>,
@@ -205,7 +155,7 @@ where
/// Unified entity mutation router wired from the domain services.
#[derive(Clone)]
-pub struct DssEntityMutationService<D, H, C, K, E, P, A, F, L> {
+pub struct DssEntityMutationService<D, H, C, K, E, P, A, L> {
documents: Arc<D>,
chats: Arc<H>,
channels: Arc<C>,
@@ -213,11 +163,10 @@ pub struct DssEntityMutationService<D, H, C, K, E, P, A, F, L> {
email: Arc<E>,
projects: Arc<P>,
access: Arc<A>,
- favorites: Arc<F>,
lifecycle: Arc<L>,
}
-impl<D, H, C, K, E, P, A, F, L> DssEntityMutationService<D, H, C, K, E, P, A, F, L> {
+impl<D, H, C, K, E, P, A, L> DssEntityMutationService<D, H, C, K, E, P, A, L> {
/// Compose the unified mutation router from domain services.
#[expect(
clippy::too_many_arguments,
@@ -231,7 +180,6 @@ impl<D, H, C, K, E, P, A, F, L> DssEntityMutationService<D, H, C, K, E, P, A, F,
email: Arc<E>,
projects: Arc<P>,
access: Arc<A>,
- favorites: Arc<F>,
lifecycle: Arc<L>,
) -> Self {
Self {
@@ -242,13 +190,12 @@ impl<D, H, C, K, E, P, A, F, L> DssEntityMutationService<D, H, C, K, E, P, A, F,
email,
projects,
access,
- favorites,
lifecycle,
}
}
}
-impl<D, H, C, K, E, P, A, F, L> DssEntityMutationService<D, H, C, K, E, P, A, F, L>
+impl<D, H, C, K, E, P, A, L> DssEntityMutationService<D, H, C, K, E, P, A, L>
where
D: DocumentService
+ RenameEntity
@@ -275,7 +222,6 @@ where
+ RestoreEntity
+ DeleteEntityPermanently,
A: EntityAccessService,
- F: FavoritesService,
L: EntityLifecycleService,
{
/// Resolve the access receipt a capability impl requires.
@@ -754,33 +700,10 @@ where
};
result.and_then(success)
}
-
- async fn set_favorite_one(
- &self,
- actor: &EntityMutationActor,
- entity: &Entity<'static>,
- favorite: bool,
- ) -> Result<(), EntityMutationErrorCode> {
- if favorite {
- // The view receipt both proves visibility and carries the actor
- // and entity for the favorites domain.
- let receipt = self.receipt::<ViewAccessLevel>(actor, entity).await?;
- self.favorites
- .add_favorite(&receipt)
- .await
- .map_err(favorites_failure)?;
- } else {
- self.favorites
- .remove_favorite_by_entity(&actor.user_id, entity)
- .await
- .map_err(favorites_failure)?;
- }
- Ok(())
- }
}
-impl<D, H, C, K, E, P, A, F, L> EntityMutationService
- for DssEntityMutationService<D, H, C, K, E, P, A, F, L>
+impl<D, H, C, K, E, P, A, L> EntityMutationService
+ for DssEntityMutationService<D, H, C, K, E, P, A, L>
where
D: DocumentService
+ RenameEntity
@@ -807,7 +730,6 @@ where
+ RestoreEntity
+ DeleteEntityPermanently,
A: EntityAccessService,
- F: FavoritesService,
L: EntityLifecycleService,
{
async fn rename_entities(
@@ -897,20 +819,4 @@ where
)
.await
}
-
- #[tracing::instrument(skip_all, fields(entity_type = %entity.entity_type, entity_id = %entity.entity_id))]
- async fn set_favorite(
- &self,
- actor: EntityMutationActor,
- entity: Entity<'static>,
- favorite: bool,
- ) -> EntityMutationResult {
- if !favoritable(entity.entity_type) {
- return unsupported(entity, "favorites");
- }
- match self.set_favorite_one(&actor, &entity, favorite).await {
- Ok(()) => success(vec![EntityMutationEffect::updated(entity)]),
- Err(error) => Err(error),
- }
- }
}
diff --git a/services/document_storage_service/src/service/entity_mutation/test.rs b/services/document_storage_service/src/service/entity_mutation/test.rs
index b7d3f44721..a812fa5e4c 100644
--- a/services/document_storage_service/src/service/entity_mutation/test.rs
+++ b/services/document_storage_service/src/service/entity_mutation/test.rs
@@ -40,34 +40,3 @@ fn target_project_failures_map_to_stable_error_codes() {
entity_mutation::EntityMutationErrorCode::NotFound(_)
));
}
-
-#[test]
-fn favoritable_kinds_are_an_explicit_allowlist() {
- for entity_type in [
- EntityType::User,
- EntityType::Team,
- EntityType::ChannelMessage,
- EntityType::StaticFile,
- EntityType::CrmContact,
- ] {
- assert!(
- !favoritable(entity_type),
- "{entity_type} must not be favoritable"
- );
- }
- for entity_type in [
- EntityType::Document,
- EntityType::Project,
- EntityType::Chat,
- EntityType::Channel,
- EntityType::EmailThread,
- EntityType::Call,
- EntityType::ForeignEntity,
- EntityType::CrmCompany,
- ] {
- assert!(
- favoritable(entity_type),
- "{entity_type} must be favoritable"
- );
- }
-}
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index f286b54385..aad9e989f9 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -100,6 +100,10 @@ type CompleteMutationRoot {
"""
setEntityFavorite(entity: EntityRefInput!, favorite: Boolean!): GraphqlEntityMutationResult!
"""
+ Persist the authenticated user's complete favorites order and return the authoritative list.
+ """
+ reorderFavorites(input: ReorderFavoritesInput!): [GraphqlFavorite!]!
+ """
Record a view or interaction in the authenticated user's channel activity.
"""
recordChannelActivity(input: RecordChannelActivityInput!): GraphqlChannelActivity!
@@ -2048,6 +2052,44 @@ enum GraphqlEntityType {
AGENT_SESSION
}
+"""
+GraphQL fields for an ordered favorite.
+"""
+type GraphqlFavorite {
+ """
+ Canonical type of the favorited entity.
+ """
+ entityType: GraphqlEntityType!
+ """
+ Canonical identifier of the favorited entity.
+ """
+ entityId: ID!
+ """
+ Manual ordering value; lower values sort first.
+ """
+ sortOrder: Float!
+ """
+ Time at which the entity was first favorited, in RFC 3339 format.
+ """
+ createdAt: String!
+ """
+ File type of a favorited document, when applicable.
+ """
+ fileType: String
+ """
+ Document subtype of a favorited document, when applicable.
+ """
+ documentSubType: String
+ """
+ Channel type of a favorited channel, when applicable.
+ """
+ channelType: String
+ """
+ Owning channel id of a favorited channel message, when applicable.
+ """
+ channelId: ID
+}
+
"""
The two operands of a recursive `PropertiesFilterExpr` binary expression.
"""
@@ -5520,6 +5562,16 @@ input RenameEntityInput {
displayName: String!
}
+"""
+Input for persisting the authenticated user's complete favorites order.
+"""
+input ReorderFavoritesInput {
+ """
+ Favorited entities in the desired order.
+ """
+ favorites: [EntityRefInput!]!
+}
+
"""
Input for assigning or updating an entity property.
"""