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): expose user favorites query (#6250)

Sean Aye57f83e55e80a
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index fcf6774e8d..6d3af693c3 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -43,8 +43,9 @@ pub use graphql_entity_mutation::{
RenameEntityInput, UpdateEntitySharePolicyInput,
};
pub use graphql_favorite::{
- EntityFavoriteEdgeReader, EntityFavoriteLoader, FavoriteMutationRoot, GraphqlFavorite,
- NoOpFavoriteMutationService, ReorderFavoritesInput, entity_favorite_loader,
+ EntityFavoriteEdgeReader, EntityFavoriteLoader, FavoriteMutationRoot, FavoriteQueryReader,
+ GraphqlFavorite, NoOpFavoriteMutationService, ReorderFavoritesInput, entity_favorite_loader,
+ resolve_favorites,
};
pub use graphql_notification::{
EntityNotificationsLoader, GraphqlNotificationUpdateOperation, NoOpNotificationMutationService,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 56a1ba3e8e..04dc30aec6 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -27,8 +27,8 @@ use graphql_email::{
};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{
- EntityFavoriteEdgeReader, FavoriteMutationRoot, NoOpEntityFavoriteEdgeReader,
- NoOpFavoriteMutationService,
+ EntityFavoriteEdgeReader, FavoriteMutationRoot, FavoriteQueryReader, GraphqlFavorite,
+ NoOpEntityFavoriteEdgeReader, NoOpFavoriteMutationService, resolve_favorites,
};
use graphql_notification::{
NoOpNotificationMutationService, NoOpSoupNotificationEdgeReader, NotificationMutationRoot,
@@ -135,8 +135,8 @@ where
/// 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.
+/// `FR` the favorite edge and query 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, FM, SoupEdges<NR, PR, ER, FR, AR, AcR>, C, N, EAS, E>,
@@ -319,7 +319,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -376,7 +376,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -432,7 +432,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -465,7 +465,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -488,7 +488,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -553,7 +553,7 @@ where
NR: SoupNotificationEdgeReader,
PR: EntityPropertyReader,
ER: SoupEmailContentEdgeReader,
- FR: EntityFavoriteEdgeReader,
+ FR: EntityFavoriteEdgeReader + FavoriteQueryReader,
AR: EntityPermissionEdgeReader,
AcR: ActivityReader,
{
@@ -562,6 +562,11 @@ where
async_graphql::ID(self.user_id.to_string())
}
+ /// The authenticated user's favorites in manual order.
+ async fn favorites(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlFavorite>> {
+ resolve_favorites::<FR>(ctx, &self.user_id).await
+ }
+
/// A page of the authenticated user's own activity, newest first.
/// Delegated actions performed on the user's behalf are included.
async fn activity(
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 6a7ae6c1f7..95fc1f55b6 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -1069,6 +1069,7 @@ impl TestHarness {
user_id,
self.email_content_reader.clone(),
))
+ .data(NoOpEntityFavoriteEdgeReader)
.data(self.activity_reader.clone())
.data(graphql_activity::entity_activity_loader(
self.activity_reader.clone(),
@@ -1193,6 +1194,19 @@ async fn user_id_resolves_without_touching_services() {
assert_eq!(harness.grouped_soup_calls.load(Ordering::SeqCst), 0);
}
+#[tokio::test]
+async fn favorites_are_nested_under_the_authenticated_user() {
+ let harness = harness();
+
+ let response = harness
+ .execute("{ user { favorites { entityType entityId sortOrder } } }")
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(response.data.to_string(), "{user: {favorites: []}}");
+ assert_eq!(harness.authorization_calls.load(Ordering::SeqCst), 1);
+}
+
#[tokio::test]
async fn email_catalog_fields_use_the_authenticated_user_and_remain_direct_user_fields() {
let harness = harness();
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 538233d901..06eaa8a2c5 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -15,6 +15,7 @@ fn soup_response_schema_exposes_frontend_fields() {
"threadId: ID!",
"emailLabels: [GraphqlSoupEmailLabel!]!",
"emailLinks: [GraphqlEmailLink!]!",
+ "favorites: [GraphqlFavorite!]!",
"emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread",
"type GraphqlSoupEmailThread implements GraphqlSoupEntity {",
"providerId: String",
diff --git a/crates/graphql_favorite/src/lib.rs b/crates/graphql_favorite/src/lib.rs
index 21c3b1d78a..75e2b41c79 100644
--- a/crates/graphql_favorite/src/lib.rs
+++ b/crates/graphql_favorite/src/lib.rs
@@ -1,5 +1,6 @@
//! GraphQL inbound adapter for the favorites domain: ordered favorite objects,
-//! mutations, and the DataLoader-backed current-viewer favorite edge.
+//! user-scoped queries, mutations, and the DataLoader-backed current-viewer
+//! favorite edge.
#![deny(missing_docs)]
#![deny(clippy::missing_docs_in_private_items)]
@@ -9,6 +10,8 @@ mod loaders;
mod mutations;
/// GraphQL favorite output objects.
mod objects;
+/// User-scoped favorites query adapter.
+mod queries;
pub use loaders::{
EntityFavoriteEdgeReader, EntityFavoriteLoader, NoOpEntityFavoriteEdgeReader,
@@ -16,3 +19,4 @@ pub use loaders::{
};
pub use mutations::{FavoriteMutationRoot, NoOpFavoriteMutationService, ReorderFavoritesInput};
pub use objects::GraphqlFavorite;
+pub use queries::{FavoriteQueryReader, resolve_favorites};
diff --git a/crates/graphql_favorite/src/queries.rs b/crates/graphql_favorite/src/queries.rs
new file mode 100644
index 0000000000..a195ed9377
--- /dev/null
+++ b/crates/graphql_favorite/src/queries.rs
@@ -0,0 +1,67 @@
+use std::sync::Arc;
+
+use async_graphql::Context;
+use favorites::domain::{
+ models::{Favorite, FavoritesError},
+ ports::FavoritesService,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+
+use crate::{GraphqlFavorite, NoOpEntityFavoriteEdgeReader};
+
+#[cfg(test)]
+mod test;
+
+/// Reader used by GraphQL user-scoped favorites queries.
+pub trait FavoriteQueryReader: Send + Sync + 'static {
+ /// List a user's favorites in manual order.
+ fn list_favorites<'a>(
+ &'a self,
+ user_id: &'a MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<Favorite>, FavoritesError>> + Send + 'a;
+}
+
+impl<T> FavoriteQueryReader for Arc<T>
+where
+ T: FavoritesService,
+{
+ async fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ FavoritesService::list_favorites(self.as_ref(), user_id).await
+ }
+}
+
+impl FavoriteQueryReader for NoOpEntityFavoriteEdgeReader {
+ async fn list_favorites(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ Ok(Vec::new())
+ }
+}
+
+/// Resolve the authenticated user's ordered favorites from GraphQL request data.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn resolve_favorites<R>(
+ ctx: &Context<'_>,
+ user_id: &MacroUserIdStr<'static>,
+) -> async_graphql::Result<Vec<GraphqlFavorite>>
+where
+ R: FavoriteQueryReader,
+{
+ let reader = ctx.data::<R>()?;
+ reader
+ .list_favorites(user_id)
+ .await
+ .map(|favorites| favorites.into_iter().map(GraphqlFavorite::new).collect())
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ user_id = %user_id,
+ "failed to load authenticated user's favorites"
+ );
+ async_graphql::Error::new("favorites are unavailable")
+ })
+}
diff --git a/crates/graphql_favorite/src/queries/test.rs b/crates/graphql_favorite/src/queries/test.rs
new file mode 100644
index 0000000000..42797ac12b
--- /dev/null
+++ b/crates/graphql_favorite/src/queries/test.rs
@@ -0,0 +1,107 @@
+use std::sync::{Arc, Mutex};
+
+use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema, value};
+use chrono::{TimeZone, Utc};
+use model_entity::EntityType;
+
+use super::*;
+
+const USER_ID: &str = "macro|[email protected]";
+
+#[derive(Clone, Default)]
+struct RecordingReader {
+ requested_users: Arc<Mutex<Vec<String>>>,
+ fail: bool,
+}
+
+impl FavoriteQueryReader for RecordingReader {
+ async fn list_favorites(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<Favorite>, FavoritesError> {
+ self.requested_users
+ .lock()
+ .expect("requested users lock poisoned")
+ .push(user_id.to_string());
+ if self.fail {
+ return Err(FavoritesError::BadRequest(
+ "sensitive favorites detail".to_string(),
+ ));
+ }
+
+ Ok(vec![Favorite {
+ entity_type: EntityType::Document,
+ entity_id: "document-1".to_string(),
+ sort_order: 2.5,
+ created_at: Utc.with_ymd_and_hms(2025, 1, 2, 3, 4, 5).unwrap(),
+ file_type: Some("pdf".to_string()),
+ document_sub_type: Some("task".to_string()),
+ channel_type: None,
+ channel_id: None,
+ }])
+ }
+}
+
+struct QueryRoot;
+
+#[Object]
+impl QueryRoot {
+ async fn favorites(&self, ctx: &Context<'_>) -> async_graphql::Result<Vec<GraphqlFavorite>> {
+ let user_id = MacroUserIdStr::parse_from_str(USER_ID).expect("valid user id");
+ resolve_favorites::<RecordingReader>(ctx, &user_id).await
+ }
+}
+
+fn schema(reader: RecordingReader) -> Schema<QueryRoot, EmptyMutation, EmptySubscription> {
+ Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
+ .data(reader)
+ .finish()
+}
+
+#[tokio::test]
+async fn lists_ordered_favorites_for_the_bound_user() {
+ let reader = RecordingReader::default();
+ let response = schema(reader.clone())
+ .execute(
+ "{ favorites { entityType entityId sortOrder createdAt fileType documentSubType channelType channelId } }",
+ )
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data,
+ value!({
+ "favorites": [{
+ "entityType": "DOCUMENT",
+ "entityId": "document-1",
+ "sortOrder": 2.5,
+ "createdAt": "2025-01-02T03:04:05+00:00",
+ "fileType": "pdf",
+ "documentSubType": "task",
+ "channelType": null,
+ "channelId": null,
+ }]
+ })
+ );
+ assert_eq!(
+ *reader
+ .requested_users
+ .lock()
+ .expect("requested users lock poisoned"),
+ vec![USER_ID.to_string()]
+ );
+}
+
+#[tokio::test]
+async fn returns_a_safe_error_when_favorites_cannot_be_loaded() {
+ let response = schema(RecordingReader {
+ fail: true,
+ ..Default::default()
+ })
+ .execute("{ favorites { entityId } }")
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+ assert_eq!(response.errors[0].message, "favorites are unavailable");
+ assert!(!response.errors[0].message.contains("sensitive"));
+}
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index 223dcd9928..fc82308aa9 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -160,6 +160,7 @@ fn insert_graphql_context_data(
});
data.insert(state.graphql_entity_mutation_service.clone());
data.insert(state.favorites_mutation_service.clone());
+ data.insert(state.favorites_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/static_assets/schema.graphql b/static_assets/schema.graphql
index 0119a813b9..7cfa67d9a3 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -5384,6 +5384,10 @@ type GraphqlUser {
"""
id: ID!
"""
+ The authenticated user's favorites in manual order.
+ """
+ favorites: [GraphqlFavorite!]!
+ """
A page of the authenticated user's own activity, newest first.
Delegated actions performed on the user's behalf are included.
"""