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.

Seanaye/feat/email mutations (#5305)

Sean Aye55f5e81ddb41
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 225ee51b2a..1d3d2b6180 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -2790,6 +2790,7 @@
"crates/entity_mutation",
"crates/filter_ast",
"crates/frecency",
+ "crates/graphql_common",
"crates/graphql_email",
"crates/invite_email",
"crates/item_filters",
diff --git a/Cargo.lock b/Cargo.lock
index d5da8d53a8..02f61e5518 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6281,7 +6281,9 @@ dependencies = [
"email",
"entity_access",
"futures",
+ "graphql_common",
"macro_user_id",
+ "serde_json",
"tokio",
"tracing",
"uuid",
diff --git a/crates/complete_graph/src/lib.rs b/crates/complete_graph/src/lib.rs
index f99fdfa74d..ee4fd12df3 100644
--- a/crates/complete_graph/src/lib.rs
+++ b/crates/complete_graph/src/lib.rs
@@ -20,10 +20,11 @@ pub use graphql_channel::{
};
pub use graphql_common::GraphqlRequestParts;
pub use graphql_email::{
- EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,
- GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings, GraphqlEmailProvider,
- GraphqlEmailQuery, GraphqlEmailSyncStatus, NoOpSoupEmailContentEdgeReader,
- SoupEmailContentEdgeReader, email_content_loader,
+ EmailContentKey, EmailContentLoad, EmailContentLoader, EmailMutationService,
+ EmailServiceEmailContentReader, GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings,
+ GraphqlEmailMutation, GraphqlEmailProvider, GraphqlEmailQuery, GraphqlEmailSyncStatus,
+ MarkEmailThreadSeenInput, NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader,
+ UpdateEmailThreadLabelInput, email_content_loader,
};
pub use graphql_entity_mutation::{
ChannelSharePolicyInput, DuplicateEntityInput, EntityMutationPayload, EntityMutationRoot,
diff --git a/crates/complete_graph/src/schema.rs b/crates/complete_graph/src/schema.rs
index b67a2525a6..5e38b70754 100644
--- a/crates/complete_graph/src/schema.rs
+++ b/crates/complete_graph/src/schema.rs
@@ -17,7 +17,8 @@ use graphql_channel::{
};
use graphql_common::{parse_id, require_authorized_user};
use graphql_email::{
- GraphqlEmailQuery, NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader,
+ GraphqlEmailMutation, GraphqlEmailQuery, NoOpSoupEmailContentEdgeReader,
+ SoupEmailContentEdgeReader,
};
use graphql_entity_mutation::EntityMutationRoot;
use graphql_favorite::{EntityFavoriteEdgeReader, NoOpEntityFavoriteEdgeReader};
@@ -31,8 +32,9 @@ use graphql_properties::{
PropertiesMutationRoot,
};
use graphql_soup::{
- GraphqlSoupEmailThread, GroupedSoup, GroupedSoupInput, SoupEntityEdges, SoupInput, SoupPage,
- SoupPatch, resolve_grouped_soup, resolve_soup, resolve_soup_email_thread, resolve_soup_updates,
+ GraphqlSoupEmailThread, GroupedSoup, GroupedSoupInput, SoupEmailThreadMutationOutput,
+ SoupEntityEdges, SoupInput, SoupPage, SoupPatch, resolve_grouped_soup, resolve_soup,
+ resolve_soup_email_thread, resolve_soup_updates,
};
use macro_authorization::{
InternalAuthConfig, MacroAuthorizationService, MacroAuthorizationServiceImpl,
@@ -55,11 +57,13 @@ pub struct CompleteMutationRoot<
C: ChannelActivityMutationService,
N: NotificationMutationService,
A: ChannelActivityAuthorizer,
+ ES: EmailService,
>(
PropertiesMutationRoot<W>,
EntityMutationRoot<M, E>,
ChannelMutationRoot<C, A>,
NotificationMutationRoot<N>,
+ GraphqlEmailMutation<ES, SoupEmailThreadMutationOutput<E>>,
);
impl<
@@ -69,7 +73,8 @@ impl<
C: ChannelActivityMutationService,
N: NotificationMutationService,
A: ChannelActivityAuthorizer,
-> CompleteMutationRoot<W, M, E, C, N, A>
+ ES: EmailService,
+> CompleteMutationRoot<W, M, E, C, N, A, ES>
{
/// Construct the composed mutation root.
fn new() -> Self {
@@ -78,6 +83,7 @@ impl<
EntityMutationRoot::<M, E>::new(),
ChannelMutationRoot::<C, A>::new(),
NotificationMutationRoot::<N>::new(),
+ GraphqlEmailMutation::<ES, SoupEmailThreadMutationOutput<E>>::new(),
)
}
}
@@ -93,7 +99,7 @@ impl<
/// `FR` the favorite edge reader, and `AR` the access edge reader.
pub type SoupSchema<S, R, E, EAS, Auth, St, W, M, C, N, NR, PR, ER, FR, AR> = Schema<
SoupQueryRoot<S, E, EAS, Auth, St, NR, PR, ER, FR, AR>,
- CompleteMutationRoot<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS>,
+ CompleteMutationRoot<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS, E>,
SoupSubscriptionRoot<R, Auth, St, NR, PR, ER, FR, AR>,
>;
@@ -293,7 +299,7 @@ where
{
Schema::build(
SoupQueryRoot::new(service),
- CompleteMutationRoot::<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS>::new(),
+ CompleteMutationRoot::<W, M, SoupEdges<NR, PR, ER, FR, AR>, C, N, EAS, E>::new(),
SoupSubscriptionRoot::new(realtime_service),
)
.finish()
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index bf7786ff5c..10a5915295 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -224,6 +224,8 @@ struct CountingEmailService {
user_label_calls: Arc<AtomicUsize>,
user_link_calls: Arc<AtomicUsize>,
user_catalog_identities: Arc<Mutex<Vec<MacroUserIdStr<'static>>>>,
+ seen_mutation_calls: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid)>>>,
+ label_mutation_calls: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, Uuid, bool)>>>,
}
fn test_email_err() -> EmailErr {
@@ -371,6 +373,35 @@ impl EmailService for CountingEmailService {
Err(test_email_err())
}
+ async fn mark_thread_seen(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<(), EmailErr> {
+ self.seen_mutation_calls
+ .lock()
+ .expect("seen mutation calls lock")
+ .push((macro_id, thread_id));
+ Ok(())
+ }
+
+ async fn update_thread_labels_for_user(
+ &self,
+ macro_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.label_mutation_calls
+ .lock()
+ .expect("label mutation calls lock")
+ .push((macro_id, thread_id, label_id, add));
+ Ok(UpdateThreadLabelsResult {
+ successful_ids: Vec::new(),
+ failed_ids: Vec::new(),
+ })
+ }
+
async fn update_thread_project(
&self,
_thread_receipt: EntityAccessReceipt<EditAccessLevel>,
@@ -732,10 +763,22 @@ impl TestHarness {
query: &str,
parts: axum::http::request::Parts,
) -> async_graphql::Response {
+ self.schema.execute(self.request(query, parts)).await
+ }
+
+ async fn execute_authenticated_mutation(&self, mutation: &str) -> async_graphql::Response {
+ let user_id = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();
+ self.schema
+ .execute(self.request(mutation, authenticated_parts()).data(user_id))
+ .await
+ }
+
+ fn request(&self, query: &str, parts: axum::http::request::Parts) -> async_graphql::Request {
let user_id = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();
- let request = async_graphql::Request::new(query)
+ async_graphql::Request::new(query)
.data(GraphqlRequestParts::new(parts))
.data(self.state.clone())
+ .data(self.state.email.service())
.data(graphql_soup::soup_item_loader(
self.soup_service.clone(),
Arc::new(self.email_service.clone()),
@@ -743,8 +786,7 @@ impl TestHarness {
.data(graphql_email::email_content_loader(
user_id,
self.email_content_reader.clone(),
- ));
- self.schema.execute(request).await
+ ))
}
}
@@ -1074,13 +1116,17 @@ async fn expired_credentials_return_the_safe_authorization_error() {
}
fn soup_email_thread(thread_id: Uuid) -> SoupItem<()> {
+ soup_email_thread_with_read_status(thread_id, false)
+}
+
+fn soup_email_thread_with_read_status(thread_id: Uuid, is_read: bool) -> 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_read,
is_draft: false,
is_important: true,
name: Some("Direct thread".to_owned()),
@@ -1143,6 +1189,64 @@ async fn email_thread_returns_the_canonical_soup_type_and_forwards_message_pagin
);
}
+#[tokio::test]
+async fn email_mutations_return_the_canonical_thread_for_normalized_cache_updates() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(44);
+ let label_id = Uuid::from_u128(45);
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread_with_read_status(thread_id, true)]);
+
+ let seen_response = harness
+ .execute_authenticated_mutation(&format!(
+ r#"mutation {{ markEmailThreadSeen(input: {{threadId: "{thread_id}"}}) {{ __typename id isRead }} }}"#
+ ))
+ .await;
+ assert!(
+ seen_response.errors.is_empty(),
+ "{:?}",
+ seen_response.errors
+ );
+ let seen_thread = &seen_response.data.into_json().unwrap()["markEmailThreadSeen"];
+ assert_eq!(seen_thread["__typename"], "GraphqlSoupEmailThread");
+ assert_eq!(seen_thread["id"], thread_id.to_string());
+ assert_eq!(seen_thread["isRead"], true);
+
+ let label_response = harness
+ .execute_authenticated_mutation(&format!(
+ r#"mutation {{ updateEmailThreadLabel(input: {{threadId: "{thread_id}", labelId: "{label_id}", value: true}}) {{ __typename id isRead }} }}"#
+ ))
+ .await;
+ assert!(
+ label_response.errors.is_empty(),
+ "{:?}",
+ label_response.errors
+ );
+ let label_thread = &label_response.data.into_json().unwrap()["updateEmailThreadLabel"];
+ assert_eq!(label_thread["__typename"], "GraphqlSoupEmailThread");
+ assert_eq!(label_thread["id"], thread_id.to_string());
+ assert_eq!(label_thread["isRead"], true);
+
+ let expected_user = MacroUserIdStr::parse_from_str(VALID_USER_ID).unwrap();
+ assert_eq!(
+ *harness
+ .email_service
+ .seen_mutation_calls
+ .lock()
+ .expect("seen mutation calls lock"),
+ vec![(expected_user.clone(), thread_id)]
+ );
+ assert_eq!(
+ *harness
+ .email_service
+ .label_mutation_calls
+ .lock()
+ .expect("label mutation calls lock"),
+ vec![(expected_user, thread_id, label_id, true)]
+ );
+}
+
#[tokio::test]
async fn email_thread_returns_null_when_soup_cannot_load_the_thread() {
let harness = harness();
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 79f178b406..65e1fef564 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -65,6 +65,12 @@ fn soup_response_schema_exposes_frontend_fields() {
"effects: [SoupPatch!]!",
"recordChannelActivity(input: RecordChannelActivityInput!): GraphqlChannelActivity!",
"updateNotifications(input: UpdateNotificationsInput!): [GraphqlSoupNotification!]!",
+ "markEmailThreadSeen(input: MarkEmailThreadSeenInput!): GraphqlSoupEmailThread!",
+ "updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!",
+ "input MarkEmailThreadSeenInput {",
+ "input UpdateEmailThreadLabelInput {",
+ "labelId: ID!",
+ "value: Boolean!",
"enum ChannelActivityType {",
"enum NotificationUpdateOperation {",
"MARK_SEEN",
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index bf4b6c6b0e..e8511007ba 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -285,6 +285,13 @@ pub trait EmailRepo: Send + Sync + 'static {
is_read: bool,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Record that the user viewed a thread.
+ fn upsert_thread_user_history(
+ &self,
+ link_id: Uuid,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Update the starred status for a batch of messages, verified by link_id.
fn update_message_starred_status_batch(
&self,
@@ -514,6 +521,26 @@ pub trait EmailService: Send + Sync + 'static {
add: bool,
) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;
+ /// Mark a caller-accessible thread as seen and read.
+ fn mark_thread_seen(
+ &self,
+ _macro_id: MacroUserIdStr<'static>,
+ _thread_id: Uuid,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send {
+ async { Err(no_op_email_err()) }
+ }
+
+ /// Add or remove a label from a caller-accessible thread.
+ fn update_thread_labels_for_user(
+ &self,
+ _macro_id: MacroUserIdStr<'static>,
+ _thread_id: Uuid,
+ _label_id: Uuid,
+ _add: bool,
+ ) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send {
+ async { Err(no_op_email_err()) }
+ }
+
/// Update the project assignment for a thread. Returns the old project_id.
///
/// `thread_receipt` proves the caller has edit access to the thread.
diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rs
index 562240b8a9..695d10af4d 100644
--- a/crates/email/src/domain/service/mod.rs
+++ b/crates/email/src/domain/service/mod.rs
@@ -295,6 +295,25 @@ where
.await
}
+ async fn mark_thread_seen(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<(), EmailErr> {
+ self.mark_thread_seen_impl(macro_id, thread_id).await
+ }
+
+ async fn update_thread_labels_for_user(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.update_thread_labels_for_user_impl(macro_id, thread_id, label_id, add)
+ .await
+ }
+
async fn update_thread_project(
&self,
thread_receipt: EntityAccessReceipt<EditAccessLevel>,
@@ -445,13 +464,14 @@ where
}
}
-impl<T, U, E, CS, Eam> EmailContentService for EmailServiceImpl<T, U, E, CS, Eam>
+impl<T, U, E, CS, Eam, B> EmailContentService for EmailServiceImpl<T, U, E, CS, Eam, B>
where
T: EmailRepo,
U: FrecencyQueryService,
E: EmailMessageEnqueuer,
CS: CrmService,
Eam: EntityAccessManagementService,
+ B: MacroEventBroker,
anyhow::Error: From<T::Err>,
{
async fn get_latest_messages_parsed(
diff --git a/crates/email/src/domain/service/thread_labels.rs b/crates/email/src/domain/service/thread_labels.rs
index 0c486c8b5c..f423fdc2e3 100644
--- a/crates/email/src/domain/service/thread_labels.rs
+++ b/crates/email/src/domain/service/thread_labels.rs
@@ -21,6 +21,79 @@ where
anyhow::Error: From<T::Err>,
anyhow::Error: From<E::Err>,
{
+ #[tracing::instrument(err, skip(self), fields(user_id = %macro_id, %thread_id))]
+ pub(crate) async fn mark_thread_seen_impl(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<(), EmailErr> {
+ let link = self
+ .email_repo
+ .owned_link_for_thread(thread_id, macro_id.clone())
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::ThreadNotFound)?;
+
+ let messages = self
+ .email_repo
+ .get_thread_label_messages(thread_id, link.id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ if messages.is_empty() {
+ return Err(EmailErr::ThreadNotFound);
+ }
+
+ self.email_repo
+ .upsert_thread_user_history(link.id, thread_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+
+ let message_ids: Vec<Uuid> = messages.iter().map(|message| message.db_id).collect();
+ let labels_by_message = self
+ .email_repo
+ .labels_by_message_ids(&message_ids)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ let unread_label_id = labels_by_message
+ .values()
+ .flatten()
+ .find(|label| label.provider_label_id == system_labels::UNREAD)
+ .and_then(|label| label.id);
+
+ let Some(unread_label_id) = unread_label_id else {
+ // Preserve the seen endpoint's repair behavior when the UNREAD
+ // assignments are already absent but the denormalized flag is stale.
+ self.email_repo
+ .update_thread_read_status(thread_id, link.id, true)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?;
+ return Ok(());
+ };
+
+ self.update_thread_labels_impl(&link, thread_id, unread_label_id, false)
+ .await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(err, skip(self), fields(user_id = %macro_id, %thread_id, %label_id, add))]
+ pub(crate) async fn update_thread_labels_for_user_impl(
+ &self,
+ macro_id: macro_user_id::user_id::MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ add: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ let link = self
+ .email_repo
+ .owned_link_for_thread(thread_id, macro_id)
+ .await
+ .map_err(|e| EmailErr::RepoErr(anyhow::Error::from(e)))?
+ .ok_or(EmailErr::ThreadNotFound)?;
+
+ self.update_thread_labels_impl(&link, thread_id, label_id, add)
+ .await
+ }
+
#[tracing::instrument(err, skip(self, link))]
pub(crate) async fn update_thread_labels_impl(
&self,
diff --git a/crates/email/src/outbound/email_pg_repo/mod.rs b/crates/email/src/outbound/email_pg_repo/mod.rs
index f7793d8068..64a71c7759 100644
--- a/crates/email/src/outbound/email_pg_repo/mod.rs
+++ b/crates/email/src/outbound/email_pg_repo/mod.rs
@@ -323,6 +323,15 @@ impl EmailRepo for EmailPgRepo {
thread::update_thread_read_status(&self.pool, thread_id, link_id, is_read).await
}
+ async fn upsert_thread_user_history(
+ &self,
+ link_id: Uuid,
+ thread_id: Uuid,
+ ) -> Result<(), Self::Err> {
+ let mut connection = self.pool.acquire().await?;
+ thread::upsert_user_history(&mut connection, link_id, thread_id).await
+ }
+
async fn update_message_starred_status_batch(
&self,
message_ids: &[Uuid],
diff --git a/crates/graphql_email/Cargo.toml b/crates/graphql_email/Cargo.toml
index fba3941677..b410718519 100644
--- a/crates/graphql_email/Cargo.toml
+++ b/crates/graphql_email/Cargo.toml
@@ -10,8 +10,12 @@ chrono = { workspace = true }
email = { path = "../email", default-features = false, features = ["ports"] }
entity_access = { path = "../entity_access", default-features = false }
futures = { workspace = true }
+graphql_common = { path = "../graphql_common" }
macro_user_id = { path = "../macro_user_id" }
tokio = { workspace = true }
tracing = { workspace = true }
uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/crates/graphql_email/src/lib.rs b/crates/graphql_email/src/lib.rs
index 625376ce94..95ccdd3cd4 100644
--- a/crates/graphql_email/src/lib.rs
+++ b/crates/graphql_email/src/lib.rs
@@ -3,6 +3,7 @@
#![deny(missing_docs)]
mod loaders;
+mod mutation;
mod objects;
mod user_objects;
mod user_query;
@@ -11,6 +12,10 @@ pub use loaders::{
EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,
NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader, email_content_loader,
};
+pub use mutation::{
+ EmailMutationService, EmailThreadMutationLoadFuture, EmailThreadMutationOutput,
+ GraphqlEmailMutation, MarkEmailThreadSeenInput, UpdateEmailThreadLabelInput,
+};
pub use objects::{GraphqlSoupEmailMessage, load_email_messages, load_latest_email_message};
pub use user_objects::{
GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings, GraphqlEmailProvider,
diff --git a/crates/graphql_email/src/mutation.rs b/crates/graphql_email/src/mutation.rs
new file mode 100644
index 0000000000..540eb8c440
--- /dev/null
+++ b/crates/graphql_email/src/mutation.rs
@@ -0,0 +1,196 @@
+use std::{future::Future, marker::PhantomData, pin::Pin, sync::Arc};
+
+use async_graphql::{Context, ID, InputObject, Object, OutputType};
+use email::domain::{
+ models::{EmailErr, UpdateThreadLabelsResult},
+ ports::EmailService,
+};
+use graphql_common::{parse_id, require_authenticated_user};
+use macro_user_id::user_id::MacroUserIdStr;
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+/// Domain-facing capability required by email thread mutations.
+pub trait EmailMutationService: Send + Sync + 'static {
+ /// Mark an accessible email thread as seen by the authenticated user.
+ fn mark_email_thread_seen(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> impl Future<Output = Result<(), EmailErr>> + Send;
+
+ /// Add or remove one label from every message in an accessible email thread.
+ fn update_email_thread_label(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ value: bool,
+ ) -> impl Future<Output = Result<UpdateThreadLabelsResult, EmailErr>> + Send;
+}
+
+impl<S> EmailMutationService for S
+where
+ S: EmailService,
+{
+ async fn mark_email_thread_seen(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<(), EmailErr> {
+ self.mark_thread_seen(user_id, thread_id).await
+ }
+
+ async fn update_email_thread_label(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ value: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.update_thread_labels_for_user(user_id, thread_id, label_id, value)
+ .await
+ }
+}
+
+/// Boxed future that reloads an email thread after a mutation.
+pub type EmailThreadMutationLoadFuture<'ctx, T> =
+ Pin<Box<dyn Future<Output = async_graphql::Result<Option<T>>> + Send + 'ctx>>;
+
+/// Supplies the canonical email-thread GraphQL object returned after a mutation.
+///
+/// The complete schema implements this boundary with its Soup email-thread type,
+/// keeping `graphql_email` independent from the higher-level schema composition.
+pub trait EmailThreadMutationOutput: Send + Sync + 'static {
+ /// Canonical email-thread output object.
+ type Thread: OutputType + Send + Sync + 'static;
+
+ /// Reload the mutated thread for the authenticated viewer.
+ fn load_email_thread<'ctx>(
+ ctx: &'ctx Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> EmailThreadMutationLoadFuture<'ctx, Self::Thread>;
+}
+
+/// Root GraphQL adapter for email mutations.
+pub struct GraphqlEmailMutation<S, O>(PhantomData<fn() -> (S, O)>);
+
+impl<S, O> GraphqlEmailMutation<S, O> {
+ /// Construct an email mutation root.
+ pub fn new() -> Self {
+ Self(PhantomData)
+ }
+}
+
+impl<S, O> Default for GraphqlEmailMutation<S, O> {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+/// Input for marking an email thread as seen.
+#[derive(InputObject)]
+pub struct MarkEmailThreadSeenInput {
+ /// Email thread to mark as seen.
+ pub thread_id: ID,
+}
+
+/// Input for adding or removing a label from an email thread.
+#[derive(InputObject)]
+pub struct UpdateEmailThreadLabelInput {
+ /// Email thread whose label assignment will change.
+ pub thread_id: ID,
+ /// Label to add or remove.
+ pub label_id: ID,
+ /// Whether the label should be present after the mutation.
+ pub value: bool,
+}
+
+fn mutation_error(error: &EmailErr) -> async_graphql::Error {
+ let message = match error {
+ EmailErr::ThreadNotFound | EmailErr::ThreadEmpty => "email thread not found",
+ EmailErr::LabelNotFound => "email label not found",
+ EmailErr::EmptyProviderLabelId => "email label is invalid",
+ EmailErr::Unauthorized => "not authorized to update email thread",
+ _ => "email thread mutation failed",
+ };
+ async_graphql::Error::new(message)
+}
+
+async fn reload_thread<O: EmailThreadMutationOutput>(
+ ctx: &Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+) -> async_graphql::Result<O::Thread> {
+ O::load_email_thread(ctx, user_id, thread_id)
+ .await?
+ .ok_or_else(|| async_graphql::Error::new("updated email thread is unavailable"))
+}
+
+/// GraphQL email mutations.
+#[Object]
+impl<S, O> GraphqlEmailMutation<S, O>
+where
+ S: EmailMutationService,
+ O: EmailThreadMutationOutput,
+{
+ /// Mark an accessible email thread as seen and return its authoritative cache record.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn mark_email_thread_seen(
+ &self,
+ ctx: &Context<'_>,
+ input: MarkEmailThreadSeenInput,
+ ) -> async_graphql::Result<O::Thread> {
+ let user_id = require_authenticated_user(ctx)?;
+ let thread_id = parse_id(input.thread_id, "threadId")?;
+ let service = ctx.data::<Arc<S>>()?;
+
+ service
+ .mark_email_thread_seen(user_id.clone(), thread_id)
+ .await
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ user_id = %user_id,
+ %thread_id,
+ "failed to mark email thread seen"
+ );
+ mutation_error(&error)
+ })?;
+
+ reload_thread::<O>(ctx, user_id, thread_id).await
+ }
+
+ /// Add or remove one label from an accessible email thread and return its authoritative cache record.
+ #[tracing::instrument(skip_all, err(Debug))]
+ async fn update_email_thread_label(
+ &self,
+ ctx: &Context<'_>,
+ input: UpdateEmailThreadLabelInput,
+ ) -> async_graphql::Result<O::Thread> {
+ let user_id = require_authenticated_user(ctx)?;
+ let thread_id = parse_id(input.thread_id, "threadId")?;
+ let label_id = parse_id(input.label_id, "labelId")?;
+ let service = ctx.data::<Arc<S>>()?;
+
+ service
+ .update_email_thread_label(user_id.clone(), thread_id, label_id, input.value)
+ .await
+ .map_err(|error| {
+ tracing::error!(
+ error = ?error,
+ user_id = %user_id,
+ %thread_id,
+ %label_id,
+ value = input.value,
+ "failed to update email thread label"
+ );
+ mutation_error(&error)
+ })?;
+
+ reload_thread::<O>(ctx, user_id, thread_id).await
+ }
+}
diff --git a/crates/graphql_email/src/mutation/test.rs b/crates/graphql_email/src/mutation/test.rs
new file mode 100644
index 0000000000..0b93077e24
--- /dev/null
+++ b/crates/graphql_email/src/mutation/test.rs
@@ -0,0 +1,160 @@
+use std::sync::Mutex;
+
+use async_graphql::{EmptySubscription, Object, Schema, SimpleObject};
+
+use super::*;
+
+struct QueryRoot;
+
+#[Object]
+impl QueryRoot {
+ async fn health(&self) -> bool {
+ true
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+enum CapturedMutation {
+ Seen {
+ user_id: String,
+ thread_id: Uuid,
+ },
+ Label {
+ user_id: String,
+ thread_id: Uuid,
+ label_id: Uuid,
+ value: bool,
+ },
+}
+
+#[derive(Default)]
+struct CapturingEmailMutationService {
+ calls: Mutex<Vec<CapturedMutation>>,
+}
+
+impl EmailMutationService for CapturingEmailMutationService {
+ async fn mark_email_thread_seen(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Result<(), EmailErr> {
+ self.calls.lock().unwrap().push(CapturedMutation::Seen {
+ user_id: user_id.to_string(),
+ thread_id,
+ });
+ Ok(())
+ }
+
+ async fn update_email_thread_label(
+ &self,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ label_id: Uuid,
+ value: bool,
+ ) -> Result<UpdateThreadLabelsResult, EmailErr> {
+ self.calls.lock().unwrap().push(CapturedMutation::Label {
+ user_id: user_id.to_string(),
+ thread_id,
+ label_id,
+ value,
+ });
+ Ok(UpdateThreadLabelsResult {
+ successful_ids: Vec::new(),
+ failed_ids: Vec::new(),
+ })
+ }
+}
+
+struct TestEmailThreadOutput;
+
+#[derive(SimpleObject)]
+struct TestEmailThread {
+ id: ID,
+ is_read: bool,
+}
+
+impl EmailThreadMutationOutput for TestEmailThreadOutput {
+ type Thread = TestEmailThread;
+
+ fn load_email_thread<'ctx>(
+ _ctx: &'ctx Context<'_>,
+ _user_id: MacroUserIdStr<'static>,
+ thread_id: Uuid,
+ ) -> Pin<Box<dyn Future<Output = async_graphql::Result<Option<Self::Thread>>> + Send + 'ctx>>
+ {
+ Box::pin(async move {
+ Ok(Some(TestEmailThread {
+ id: ID(thread_id.to_string()),
+ is_read: true,
+ }))
+ })
+ }
+}
+
+fn schema(
+ service: Arc<CapturingEmailMutationService>,
+) -> Schema<
+ QueryRoot,
+ GraphqlEmailMutation<CapturingEmailMutationService, TestEmailThreadOutput>,
+ EmptySubscription,
+> {
+ Schema::build(
+ QueryRoot,
+ GraphqlEmailMutation::<CapturingEmailMutationService, TestEmailThreadOutput>::new(),
+ EmptySubscription,
+ )
+ .data(service)
+ .data(MacroUserIdStr::try_from_email("[email protected]").unwrap())
+ .finish()
+}
+
+#[tokio::test]
+async fn mark_seen_calls_the_email_service_and_returns_the_reloaded_thread() {
+ let service = Arc::new(CapturingEmailMutationService::default());
+ let thread_id = Uuid::new_v4();
+ let response = schema(service.clone())
+ .execute(format!(
+ r#"mutation {{ markEmailThreadSeen(input: {{ threadId: "{thread_id}" }}) {{ id isRead }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap()["markEmailThreadSeen"],
+ serde_json::json!({ "id": thread_id, "isRead": true })
+ );
+ assert_eq!(
+ *service.calls.lock().unwrap(),
+ vec![CapturedMutation::Seen {
+ user_id: "macro|[email protected]".to_string(),
+ thread_id,
+ }]
+ );
+}
+
+#[tokio::test]
+async fn update_label_calls_the_email_service_and_returns_the_reloaded_thread() {
+ let service = Arc::new(CapturingEmailMutationService::default());
+ let thread_id = Uuid::new_v4();
+ let label_id = Uuid::new_v4();
+ let response = schema(service.clone())
+ .execute(format!(
+ r#"mutation {{ updateEmailThreadLabel(input: {{ threadId: "{thread_id}", labelId: "{label_id}", value: false }}) {{ id isRead }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ assert_eq!(
+ response.data.into_json().unwrap()["updateEmailThreadLabel"],
+ serde_json::json!({ "id": thread_id, "isRead": true })
+ );
+ assert_eq!(
+ *service.calls.lock().unwrap(),
+ vec![CapturedMutation::Label {
+ user_id: "macro|[email protected]".to_string(),
+ thread_id,
+ label_id,
+ value: false,
+ }]
+ );
+}
diff --git a/crates/graphql_soup/src/lib.rs b/crates/graphql_soup/src/lib.rs
index d561d41120..8cf45425ba 100644
--- a/crates/graphql_soup/src/lib.rs
+++ b/crates/graphql_soup/src/lib.rs
@@ -29,5 +29,6 @@ pub use objects::{
SoupPatch, SoupUpdated,
};
pub use resolvers::{
- resolve_grouped_soup, resolve_soup, resolve_soup_email_thread, resolve_soup_updates,
+ SoupEmailThreadMutationOutput, 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 f4d2e58a4f..848c4fce2c 100644
--- a/crates/graphql_soup/src/resolvers.rs
+++ b/crates/graphql_soup/src/resolvers.rs
@@ -1,4 +1,4 @@
-use std::sync::Arc;
+use std::{future::Future, marker::PhantomData, pin::Pin, sync::Arc};
use async_graphql::Context;
use axum::extract::FromRef;
@@ -13,6 +13,7 @@ use entity_access::{
};
use futures::Stream;
use graphql_common::{extract_part, require_authorized_user};
+use graphql_email::EmailThreadMutationOutput;
use macro_authorization::{MacroAuthorizationService, MacroAuthorizationState};
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
@@ -109,6 +110,25 @@ where
}
}
+/// Mutation-output adapter that reloads the canonical Soup email-thread object.
+pub struct SoupEmailThreadMutationOutput<Edges>(PhantomData<fn() -> Edges>);
+
+impl<Edges> EmailThreadMutationOutput for SoupEmailThreadMutationOutput<Edges>
+where
+ Edges: SoupEntityEdges,
+{
+ type Thread = GraphqlSoupEmailThread<Edges>;
+
+ fn load_email_thread<'ctx>(
+ ctx: &'ctx Context<'_>,
+ user_id: MacroUserIdStr<'static>,
+ thread_id: uuid::Uuid,
+ ) -> Pin<Box<dyn Future<Output = async_graphql::Result<Option<Self::Thread>>> + Send + 'ctx>>
+ {
+ Box::pin(resolve_soup_email_thread::<Edges>(ctx, user_id, thread_id))
+ }
+}
+
/// 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/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.ts
index dc12ee2aea..7a40c3ee91 100644
--- a/infra/stacks/cloud-storage-service/index.ts
+++ b/infra/stacks/cloud-storage-service/index.ts
@@ -145,6 +145,10 @@ const emailScheduledQueueArn: pulumi.Output<string> = emailServiceStack
.getOutput('scheduledQueueArn')
.apply((arn) => arn as string);
+const gmailOpsQueueArn: pulumi.Output<string> = emailServiceStack
+ .getOutput('gmailOpsQueueArn')
+ .apply((arn) => arn as string);
+
const {
notificationIngressQueueArn,
notificationApnsVoipPlatformArn: snsApnsVoipPlatformArn,
@@ -261,6 +265,7 @@ const cloudStorageService = new CloudStorageService(
notificationIngressQueueArn,
contactsQueueArn,
emailScheduledQueueArn,
+ gmailOpsQueueArn,
],
vpc: coparse_api_vpc,
platform: {
diff --git a/services/document_storage_service/Cargo.toml b/services/document_storage_service/Cargo.toml
index df0f5750bb..e5c41d300f 100644
--- a/services/document_storage_service/Cargo.toml
+++ b/services/document_storage_service/Cargo.toml
@@ -185,6 +185,7 @@ soup_realtime = { path = "../../crates/soup_realtime", default-features = false,
sqlx = { workspace = true }
sqs_client = { path = "../../crates/sqs_client", default-features = false, features = [
"document",
+ "email",
"search",
] }
sqs_worker = { path = "../../crates/sqs_worker" }
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index ad5c2d8c1e..bbf5ec2ed0 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -130,9 +130,10 @@ pub(crate) type DssCrmService = crm::domain::service::CrmServiceImpl<
pub(crate) type DssEmailService = EmailServiceImpl<
EmailPgRepo,
FrecencyQueryServiceImpl<FrecencyPgStorage>,
- email::domain::ports::NoOpEnqueuer,
+ sqs_client::SQS,
DssCrmService,
EntityAccessManagementService,
+ DssEventBroker,
>;
/// CRM router state.
diff --git a/services/document_storage_service/src/api/graphql_soup.rs b/services/document_storage_service/src/api/graphql_soup.rs
index 57abac5b83..b81edf85ef 100644
--- a/services/document_storage_service/src/api/graphql_soup.rs
+++ b/services/document_storage_service/src/api/graphql_soup.rs
@@ -149,7 +149,6 @@ fn insert_graphql_context_data(
state.soup_router_state.service(),
state.soup_router_state.email_service(),
);
-
data.insert(macro_user_id.clone());
data.insert(entity_mutation::EntityMutationActor {
user_id: macro_user_id.clone(),
@@ -158,6 +157,7 @@ fn insert_graphql_context_data(
data.insert(state.graphql_entity_mutation_service.clone());
data.insert(state.channel_service.clone());
data.insert(state.graphql_notification_reader.clone());
+ data.insert(state.soup_router_state.email_service());
data.insert(state.entity_access_service.clone());
data.insert(soup_item_loader);
data.insert(complete_graph::entity_properties_loader(
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 6e38e4fbf9..4f6db9540a 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -222,9 +222,11 @@ async fn main() -> anyhow::Result<()> {
let document_delete_queue = macro_queues::DocumentDeleteQueue::new();
let contacts_queue = macro_queues::ContactsQueue::new();
let notification_queue = macro_queues::NotificationIngressQueue::new();
+ let gmail_ops_queue = macro_queues::GmailOpsQueue::new();
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(&aws_config))
.search_event_queue(&search_event_queue)
- .document_delete_queue(&document_delete_queue);
+ .document_delete_queue(&document_delete_queue)
+ .gmail_ops_queue(&gmail_ops_queue);
let webhook_event_queue = webhook::outbound::SqsWebhookQueue::new(
Arc::new(sqs_client.clone()),
macro_queues::WebhookEventQueue::new().to_string(),
@@ -322,23 +324,27 @@ async fn main() -> anyhow::Result<()> {
let email_service = EmailServiceImpl::new(
EmailPgRepo::new(db.clone()),
frecency_service.clone(),
- email::domain::ports::NoOpEnqueuer,
+ sqs_client.clone(),
crm_service.clone(),
entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
entity_access_management::outbound::PgRepository::new(db.clone()),
),
0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone());
+ let readonly_email_service = ReadonlyEmailPreviewAdapter(
+ EmailServiceImpl::new(
+ EmailPgRepo::new(readonly_db.clone()),
+ frecency_service.clone(),
+ sqs_client.clone(),
+ crm_service.clone(),
+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
+ entity_access_management::outbound::PgRepository::new(readonly_db.clone()),
+ ),
+ 0,
+ )
+ .with_macro_event_broker(macro_event_broker.clone()),
);
- let readonly_email_service = ReadonlyEmailPreviewAdapter(EmailServiceImpl::new(
- EmailPgRepo::new(readonly_db.clone()),
- frecency_service.clone(),
- email::domain::ports::NoOpEnqueuer,
- crm_service.clone(),
- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(
- entity_access_management::outbound::PgRepository::new(readonly_db.clone()),
- ),
- 0,
- ));
let system_properties_service =
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));
let ingress_queue = SqsQueue::new(
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index d8281a0e67..c0bfe7a794 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -78,6 +78,14 @@ type CompleteMutationRoot {
Update authenticated user-owned notifications and return authoritative rows.
"""
updateNotifications(input: UpdateNotificationsInput!): [GraphqlSoupNotification!]!
+ """
+ Mark an accessible email thread as seen and return its authoritative cache record.
+ """
+ markEmailThreadSeen(input: MarkEmailThreadSeenInput!): GraphqlSoupEmailThread!
+ """
+ Add or remove one label from an accessible email thread and return its authoritative cache record.
+ """
+ updateEmailThreadLabel(input: UpdateEmailThreadLabelInput!): GraphqlSoupEmailThread!
}
"""
@@ -3501,6 +3509,16 @@ A scalar that can represent any JSON value.
"""
scalar JSON
+"""
+Input for marking an email thread as seen.
+"""
+input MarkEmailThreadSeenInput {
+ """
+ Email thread to mark as seen.
+ """
+ threadId: ID!
+}
+
"""
One entity move in a batch.
"""
@@ -3691,6 +3709,24 @@ type SoupUpdated {
item: GraphqlSoupEntity
}
+"""
+Input for adding or removing a label from an email thread.
+"""
+input UpdateEmailThreadLabelInput {
+ """
+ Email thread whose label assignment will change.
+ """
+ threadId: ID!
+ """
+ Label to add or remove.
+ """
+ labelId: ID!
+ """
+ Whether the label should be present after the mutation.
+ """
+ value: Boolean!
+}
+
"""
One share-policy update in a batch.
"""