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.

Expose direct email thread GraphQL query (#5288)

Sean Aye798cc1261642
diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rs
index a90bf8dc11..fe787b70e0 100644
--- a/crates/complete_graph/src/edges.rs
+++ b/crates/complete_graph/src/edges.rs
@@ -144,11 +144,14 @@ where
}
/// default limit of messages if none is provided
+/// REST-compatible default number of email messages returned per page.
const DEFAULT_EMAIL_MESSAGE_LIMIT: i32 = 5;
/// max possible limit of messages
+/// Maximum number of email messages one field may request.
const MAX_EMAIL_MESSAGE_LIMIT: i32 = 100;
/// parses the incoming optional limits into the actual range
+/// Validate email-message pagination and apply REST-compatible defaults.
fn parse_email_message_pagination(
offset: Option<i32>,
limit: Option<i32>,
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index 377081b11e..325e1e516c 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -50,7 +50,7 @@ pub use graphql_properties::{
entity_properties_loader,
};
pub use schema::{
- SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SoupQueryRoot, SoupSchema,
- SoupSubscriptionRoot, build_schema, build_schema_from_arc, build_schema_from_arcs,
+ EmailThreadInput, SchemaOnlySoupSchema, SchemaOnlyState, SharedSoupSchema, SoupQueryRoot,
+ SoupSchema, SoupSubscriptionRoot, build_schema, build_schema_from_arc, build_schema_from_arcs,
build_schema_with_service, build_schema_with_services,
};
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index 9a1b081159..4f86194d71 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -3,7 +3,7 @@ mod test;
use std::{marker::PhantomData, sync::Arc};
-use async_graphql::{Context, MergedObject, Object, Schema, Subscription};
+use async_graphql::{Context, ID, MergedObject, Object, Schema, Subscription};
use axum::extract::FromRef;
use email::{
domain::ports::{EmailService, NoOpEmailService},
@@ -15,7 +15,7 @@ use graphql_channel::{
ChannelActivityAuthorizer, ChannelActivityMutationService, ChannelMutationRoot,
NoOpChannelActivityMutationService,
};
-use graphql_common::require_authorized_user;
+use graphql_common::{parse_id, require_authorized_user};
use graphql_email::{NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{EntityFavoriteEdgeReader, NoOpEntityFavoriteEdgeReader};
@@ -29,8 +29,8 @@ use graphql_properties::{
PropertiesMutationRoot,
};
use graphql_soup::{
- GroupedSoup, GroupedSoupInput, SoupEntityEdges, SoupInput, SoupPage, SoupPatch,
- resolve_grouped_soup, resolve_soup, resolve_soup_updates,
+ GraphqlSoupEmailThread, GroupedSoup, GroupedSoupInput, SoupEntityEdges, SoupInput, SoupPage,
+ SoupPatch, resolve_grouped_soup, resolve_soup, resolve_soup_email_thread, resolve_soup_updates,
};
use macro_authorization::{
InternalAuthConfig, MacroAuthorizationService, MacroAuthorizationServiceImpl,
@@ -208,6 +208,13 @@ pub struct GraphqlUser<S, E, EAS, Auth, St, NR, PR, ER, FR, AR> {
user_id: MacroUserIdStr<'static>,
}
+/// Input for fetching one email thread by its canonical identifier.
+#[derive(async_graphql::InputObject)]
+pub struct EmailThreadInput {
+ /// The canonical email thread identifier.
+ thread_id: ID,
+}
+
/// Build a GraphQL schema for Soup suitable for SDL export or introspection.
pub fn build_schema() -> SchemaOnlySoupSchema {
build_schema_with_services(NoOpSoupService, NoOpSoupRealtimeSubscriptionService)
@@ -445,6 +452,21 @@ where
async_graphql::ID(self.user_id.to_string())
}
+ /// Fetch one accessible email thread by its canonical identifier.
+ async fn email_thread(
+ &self,
+ ctx: &Context<'_>,
+ input: EmailThreadInput,
+ ) -> async_graphql::Result<Option<GraphqlSoupEmailThread<SoupEdges<NR, PR, ER, FR, AR>>>> {
+ let thread_id = parse_id(input.thread_id, "threadId")?;
+ resolve_soup_email_thread::<SoupEdges<NR, PR, ER, FR, AR>>(
+ ctx,
+ self.user_id.clone(),
+ thread_id,
+ )
+ .await
+ }
+
/// Fetch Soup items nested into grouping bins.
async fn group_soup(
&self,
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index c35ee7a122..9c550e68c5 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -1,11 +1,12 @@
+use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use axum::http::{Request as HttpRequest, header};
use email::domain::models::{
CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EnrichedEmailThreadPreview,
- GetEmailsRequest, Link, LinkLabel, ParsedThread, Thread, UpdateThreadLabelsResult,
- UpsertEmailFilterInput,
+ GetEmailsRequest, Link, LinkLabel, ParsedMessage, ParsedThread, Thread,
+ UpdateThreadLabelsResult, UpsertEmailFilterInput,
};
use entity_access::domain::models::{
AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
@@ -24,7 +25,11 @@ use macro_user_id::{
use model_entity::EntityType as ModelEntityType;
use model_user::UserContext;
use models_pagination::{Paginated, PaginatedCursor, SimpleSortMethod};
-use models_soup::{document::SoupDocument, item::SoupItem};
+use models_soup::{
+ document::SoupDocument,
+ email_thread::{SoupContact, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreview},
+ item::SoupItem,
+};
use rootcause::Report;
use soup_realtime::domain::models::Patch;
use uuid::Uuid;
@@ -60,6 +65,7 @@ struct CountingSoupService {
raw_calls: Arc<AtomicUsize>,
raw_team_receipts: Arc<AtomicUsize>,
return_empty_raw: bool,
+ raw_response: Arc<Mutex<Option<Vec<SoupItem<()>>>>>,
frecency_calls: Arc<AtomicUsize>,
frecency_team_receipts: Arc<AtomicUsize>,
grouped_calls: Arc<AtomicUsize>,
@@ -90,6 +96,12 @@ fn test_soup_err() -> soup::domain::models::SoupErr {
soup::domain::models::SoupErr::SoupDbErr(anyhow::anyhow!("counting Soup service"))
}
+impl CountingSoupService {
+ fn set_raw_response(&self, items: Vec<SoupItem<()>>) {
+ *self.raw_response.lock().expect("raw response lock") = Some(items);
+ }
+}
+
impl SoupService for CountingSoupService {
async fn get_user_soup<T>(
&self,
@@ -104,9 +116,10 @@ impl SoupService for CountingSoupService {
if team_receipt.is_some() {
self.raw_team_receipts.fetch_add(1, Ordering::SeqCst);
}
- if self.return_empty_raw {
+ let raw_response = self.raw_response.lock().expect("raw response lock").clone();
+ if self.return_empty_raw || raw_response.is_some() {
let page: PaginatedCursor<SoupItem<()>, String, SimpleSortMethod, T> =
- Paginated::from_parts(Vec::new(), None);
+ Paginated::from_parts(raw_response.unwrap_or_default(), None);
return Ok(soup::domain::ports::SoupOutput::Left(page));
}
Err(test_soup_err())
@@ -327,6 +340,62 @@ impl EmailService for CountingEmailService {
}
}
+#[derive(Clone, Default)]
+struct RecordingEmailContentReader {
+ calls: Arc<Mutex<Vec<Vec<graphql_email::EmailContentKey>>>>,
+}
+
+impl graphql_email::SoupEmailContentEdgeReader for RecordingEmailContentReader {
+ async fn get_email_content(
+ &self,
+ _user_id: &MacroUserIdStr<'static>,
+ keys: Vec<graphql_email::EmailContentKey>,
+ ) -> HashMap<graphql_email::EmailContentKey, graphql_email::EmailContentLoad> {
+ self.calls
+ .lock()
+ .expect("email content calls lock")
+ .push(keys.clone());
+ keys.into_iter()
+ .map(|key| {
+ let thread_id = key.thread_id;
+ (
+ key,
+ graphql_email::EmailContentLoad::Found(vec![parsed_message(thread_id)]),
+ )
+ })
+ .collect()
+ }
+}
+
+fn parsed_message(thread_id: Uuid) -> ParsedMessage {
+ ParsedMessage {
+ db_id: Uuid::from_u128(100),
+ link_id: Uuid::from_u128(200),
+ thread_db_id: thread_id,
+ subject: Some("Direct thread subject".to_owned()),
+ snippet: Some("Direct thread snippet".to_owned()),
+ from: None,
+ to: Vec::new(),
+ cc: Vec::new(),
+ bcc: Vec::new(),
+ labels: Vec::new(),
+ body_parsed: Some("Direct thread body".to_owned()),
+ body_text: Some("Direct thread body".to_owned()),
+ body_html_sanitized: None,
+ body_macro: None,
+ body_replyless: Some("Direct thread body".to_owned()),
+ internal_date_ts: Some(Default::default()),
+ sent_at: Some(Default::default()),
+ is_read: true,
+ is_starred: false,
+ is_sent: false,
+ is_draft: false,
+ has_attachments: false,
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ }
+}
+
/// Entity access service whose team lookups are counted and return a team.
#[derive(Clone, Default)]
struct CountingEntityAccessService {
@@ -514,11 +583,14 @@ struct TestHarness {
NoOpNotificationMutationService,
NoOpSoupNotificationEdgeReader,
NoOpEntityPropertyReader,
- NoOpSoupEmailContentEdgeReader,
+ RecordingEmailContentReader,
graphql_favorite::NoOpEntityFavoriteEdgeReader,
graphql_permission::NoOpEntityPermissionEdgeReader,
>,
state: TestState,
+ soup_service: CountingSoupService,
+ email_service: CountingEmailService,
+ email_content_reader: RecordingEmailContentReader,
authorization_calls: Arc<AtomicUsize>,
inbox_calls: Arc<AtomicUsize>,
team_calls: Arc<AtomicUsize>,
@@ -534,6 +606,7 @@ fn harness() -> TestHarness {
let entity_access = CountingEntityAccessService::default();
let authorization = FakeAuthorizationService::default();
let soup = CountingSoupService::default();
+ let email_content_reader = RecordingEmailContentReader::default();
let authorization_calls = Arc::clone(&authorization.authorization_calls);
let inbox_calls = Arc::clone(&email.inbox_calls);
let team_calls = Arc::clone(&entity_access.team_calls);
@@ -543,12 +616,15 @@ fn harness() -> TestHarness {
let frecency_soup_team_receipts = Arc::clone(&soup.frecency_team_receipts);
let grouped_soup_calls = Arc::clone(&soup.grouped_calls);
TestHarness {
- schema: build_schema_with_service(soup),
+ schema: build_schema_with_service(soup.clone()),
state: TestState {
authorization: MacroAuthorizationState::new(Arc::new(authorization)),
- email: EmailRouterState::new(email),
+ email: EmailRouterState::new(email.clone()),
entity_access: Arc::new(entity_access),
},
+ soup_service: soup,
+ email_service: email,
+ email_content_reader,
authorization_calls,
inbox_calls,
team_calls,
@@ -591,9 +667,18 @@ impl TestHarness {
query: &str,
parts: axum::http::request::Parts,
) -> async_graphql::Response {
+ let user_id = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();
let request = async_graphql::Request::new(query)
.data(GraphqlRequestParts::new(parts))
- .data(self.state.clone());
+ .data(self.state.clone())
+ .data(graphql_soup::soup_item_loader(
+ self.soup_service.clone(),
+ Arc::new(self.email_service.clone()),
+ ))
+ .data(graphql_email::email_content_loader(
+ user_id,
+ self.email_content_reader.clone(),
+ ));
self.schema.execute(request).await
}
}
@@ -870,3 +955,118 @@ async fn expired_credentials_return_the_safe_authorization_error() {
assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);
assert_eq!(harness.team_calls.load(Ordering::SeqCst), 0);
}
+
+fn soup_email_thread(thread_id: Uuid) -> SoupItem<()> {
+ SoupItem::EmailThread(SoupEnrichedEmailThreadPreview {
+ thread: SoupEmailThreadPreview {
+ id: thread_id,
+ provider_id: Some("provider-thread".to_owned()),
+ owner_id: MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap(),
+ inbox_visible: true,
+ is_read: false,
+ is_draft: false,
+ is_important: true,
+ name: Some("Direct thread".to_owned()),
+ snippet: Some("Direct thread snippet".to_owned()),
+ sender_email: Some("[email protected]".to_owned()),
+ sender_name: Some("Sender".to_owned()),
+ sender_photo_url: None,
+ sort_ts: Default::default(),
+ created_at: Default::default(),
+ updated_at: Default::default(),
+ viewed_at: None,
+ project_id: None,
+ },
+ attachments: Vec::new(),
+ participants: vec![SoupContact {
+ id: Uuid::from_u128(300),
+ link_id: Uuid::from_u128(200),
+ name: Some("Sender".to_owned()),
+ email_address: Some("[email protected]".to_owned()),
+ sfs_photo_url: None,
+ }],
+ labels: Vec::new(),
+ extra: (),
+ })
+}
+
+#[tokio::test]
+async fn email_thread_returns_the_canonical_soup_type_and_forwards_message_pagination() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(42);
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread(thread_id)]);
+
+ let response = harness
+ .execute(&format!(
+ r#"{{ user {{ emailThread(input: {{threadId: "{thread_id}"}}) {{ __typename id linkId inboxVisible isRead messages(offset: 7, limit: 20) {{ id threadId bodyParsed }} }} }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let thread = &data["user"]["emailThread"];
+ assert_eq!(thread["__typename"], "GraphqlSoupEmailThread");
+ assert_eq!(thread["id"], thread_id.to_string());
+ assert_eq!(thread["linkId"], Uuid::from_u128(200).to_string());
+ assert_eq!(thread["inboxVisible"], true);
+ assert_eq!(thread["isRead"], false);
+ assert_eq!(thread["messages"][0]["threadId"], thread_id.to_string());
+ assert_eq!(thread["messages"][0]["bodyParsed"], "Direct thread body");
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(
+ *harness
+ .email_content_reader
+ .calls
+ .lock()
+ .expect("email content calls lock"),
+ vec![vec![graphql_email::EmailContentKey::page(thread_id, 7, 20)]]
+ );
+}
+
+#[tokio::test]
+async fn email_thread_returns_null_when_soup_cannot_load_the_thread() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(43);
+ harness.soup_service.set_raw_response(Vec::new());
+
+ let response = harness
+ .execute(&format!(
+ r#"{{ user {{ emailThread(input: {{threadId: "{thread_id}"}}) {{ id messages {{ id }} }} }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ assert!(data["user"]["emailThread"].is_null());
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 1);
+ assert!(
+ harness
+ .email_content_reader
+ .calls
+ .lock()
+ .expect("email content calls lock")
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn email_thread_rejects_an_invalid_thread_id_before_loading_soup() {
+ let harness = harness();
+
+ let response = harness
+ .execute(r#"{ user { emailThread(input: {threadId: "not-a-uuid"}) { id } } }"#)
+ .await;
+
+ assert_eq!(response.errors.len(), 1);
+ assert!(
+ response.errors[0]
+ .message
+ .starts_with("invalid threadId UUID")
+ );
+ assert_eq!(harness.raw_soup_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(harness.inbox_calls.load(Ordering::SeqCst), 0);
+}
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index fd0f2c5c97..5c89b4ea52 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -11,6 +11,9 @@ fn soup_response_schema_exposes_frontend_fields() {
"participants: [GraphqlSoupChannelParticipant!]!",
"latestMessage: GraphqlSoupChannelMessagePreview",
"latestNonThreadMessage: GraphqlSoupChannelMessagePreview",
+ "input EmailThreadInput {",
+ "threadId: ID!",
+ "emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread",
"type GraphqlSoupEmailThread implements GraphqlSoupEntity {",
"providerId: String",
"inboxVisible: Boolean!",
diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rs
index 29cea52739..d561d41120 100644
--- a/crates/graphql_soup/src/lib.rs
+++ b/crates/graphql_soup/src/lib.rs
@@ -28,4 +28,6 @@ pub use objects::{
GraphqlSoupForeignEntity, GraphqlSoupProject, GroupedSoup, SoupEntityEdges, SoupPage,
SoupPatch, SoupUpdated,
};
-pub use resolvers::{resolve_grouped_soup, resolve_soup, resolve_soup_updates};
+pub use resolvers::{
+ resolve_grouped_soup, resolve_soup, resolve_soup_email_thread, resolve_soup_updates,
+};
diff --git a/crates/graphql_soup/src/resolvers.rs b/crates/graphql_soup/src/resolvers.rs
index 4cb5c794c1..f4d2e58a4f 100644
--- a/crates/graphql_soup/src/resolvers.rs
+++ b/crates/graphql_soup/src/resolvers.rs
@@ -14,13 +14,19 @@ use entity_access::{
use futures::Stream;
use graphql_common::{extract_part, require_authorized_user};
use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
+use macro_user_id::user_id::MacroUserIdStr;
+use model_entity::EntityType;
use models_pagination::TypeEraseCursor;
use soup::domain::{models::grouping::NestedSoupGroups, ports::SoupService};
use soup_realtime::domain::ports::SoupRealtimeSubscriptionService;
use crate::{
inputs::{GroupedSoupInput, SoupInput},
- objects::{GroupedSoup, SoupEntityEdges, SoupPage, SoupPatch},
+ loaders::SoupItemDataLoader,
+ objects::{
+ GraphqlSoupEmailThread, GraphqlSoupEntity, GroupedSoup, SoupEntityEdges, SoupPage,
+ SoupPatch,
+ },
};
/// Subscribe to realtime Soup updates for the authenticated user.
@@ -77,6 +83,32 @@ where
))
}
+/// Resolve one email thread through the existing user-scoped Soup item loader.
+///
+/// A missing or inaccessible thread is represented as `None` by the loader's
+/// filtered Soup request.
+pub async fn resolve_soup_email_thread<Edges>(
+ ctx: &Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: uuid::Uuid,
+) -> async_graphql::Result<Option<GraphqlSoupEmailThread<Edges>>>
+where
+ Edges: SoupEntityEdges,
+{
+ let loader = ctx.data::<SoupItemDataLoader>()?;
+ let entity = EntityType::EmailThread.with_entity_string(thread_id.to_string());
+ let Some(item) = loader.load_one((user_id, entity)).await? else {
+ return Ok(None);
+ };
+
+ match GraphqlSoupEntity::<Edges>::new(item) {
+ GraphqlSoupEntity::EmailThread(thread) => Ok(Some(thread)),
+ _ => Err(async_graphql::Error::new(
+ "Soup returned a non-email entity for an email-thread request",
+ )),
+ }
+}
+
/// Resolve a page of Soup items for the authenticated user: runs the lazy
/// axum extractors against the request context, converts the GraphQL input
/// into a Soup request, and executes it against the Soup service.
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 318126afa3..1f817d2e20 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -94,6 +94,16 @@ input DuplicateEntityInput {
displayName: String
}
+"""
+Input for fetching one email thread by its canonical identifier.
+"""
+input EmailThreadInput {
+ """
+ The canonical email thread identifier.
+ """
+ threadId: ID!
+}
+
"""
Results for a batch mutation, preserving the input order.
"""
@@ -3132,6 +3142,10 @@ type GraphqlUser {
"""
id: ID!
"""
+ Fetch one accessible email thread by its canonical identifier.
+ """
+ emailThread(input: EmailThreadInput!): GraphqlSoupEmailThread
+ """
Fetch Soup items nested into grouping bins.
"""
groupSoup(input: GroupedSoupInput!): GroupedSoup!