Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
Expose paginated email messages in GraphQL (#5283)
Sean Ayea4bb25e4bef3
diff --git a/Cargo.lock b/Cargo.lockindex 5fb66cbeda..a33935b223 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6244,6 +6244,7 @@ dependencies = ["chrono","email","entity_access",+ "futures","macro_user_id","tokio","tracing",diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rsindex 13e79e38a5..a90bf8dc11 100644--- a/crates/complete_graph/src/edges.rs+++ b/crates/complete_graph/src/edges.rs@@ -2,7 +2,8 @@ use std::marker::PhantomData;use async_graphql::{Context, Object};use graphql_email::{- EmailContentKey, GraphqlSoupEmailMessage, SoupEmailContentEdgeReader, load_latest_email_message,+ EmailContentKey, GraphqlSoupEmailMessage, SoupEmailContentEdgeReader, load_email_messages,+ load_latest_email_message,};use graphql_favorite::{EntityFavoriteEdgeReader, load_entity_favorite};use graphql_notification::{@@ -142,6 +143,36 @@ where}}+/// default limit of messages if none is provided+const DEFAULT_EMAIL_MESSAGE_LIMIT: i32 = 5;+/// max possible limit of messages+const MAX_EMAIL_MESSAGE_LIMIT: i32 = 100;++/// parses the incoming optional limits into the actual range+fn parse_email_message_pagination(+ offset: Option<i32>,+ limit: Option<i32>,+) -> async_graphql::Result<(u32, u32)> {+ let offset = offset.unwrap_or(0);+ let limit = limit.unwrap_or(DEFAULT_EMAIL_MESSAGE_LIMIT);++ let offset = u32::try_from(offset)+ .map_err(|_| async_graphql::Error::new("offset must be non-negative"))?;+ if limit <= 0 {+ return Err(async_graphql::Error::new("limit must be positive"));+ }+ if limit > MAX_EMAIL_MESSAGE_LIMIT {+ return Err(async_graphql::Error::new(format!(+ "limit must not exceed {MAX_EMAIL_MESSAGE_LIMIT}"+ )));+ }++ Ok((+ offset,+ u32::try_from(limit).expect("positive GraphQL Int fits in u32"),+ ))+}+/// Email-content fields attached only to Soup email-thread entities.pub struct SoupEmailThreadEdges<ER> {/// The uuid of the email thread@@ -165,17 +196,25 @@ impl<ER> SoupEmailThreadEdges<ER>whereER: SoupEmailContentEdgeReader,{+ /// A page of messages in this thread, newest first.+ async fn messages(+ &self,+ ctx: &Context<'_>,+ offset: Option<i32>,+ limit: Option<i32>,+ ) -> async_graphql::Result<Vec<GraphqlSoupEmailMessage>> {+ let (offset, limit) = parse_email_message_pagination(offset, limit)?;+ load_email_messages::<ER>(ctx, EmailContentKey::page(self.thread_id, offset, limit)).await+ }+/// The newest non-draft content message in this thread.async fn latest_content_message(&self,ctx: &Context<'_>,) -> async_graphql::Result<Option<GraphqlSoupEmailMessage>> {- load_latest_email_message::<ER>(- ctx,- EmailContentKey {- thread_id: self.thread_id,- },- )- .await+ load_latest_email_message::<ER>(ctx, self.thread_id).await}}++#[cfg(test)]+mod test;diff --git a/crates/complete_graph/src/edges/test.rs b/crates/complete_graph/src/edges/test.rsnew file mode 100644index 0000000000..0ab45e2abc--- /dev/null+++ b/crates/complete_graph/src/edges/test.rs@@ -0,0 +1,36 @@+use super::*;++#[test]+fn email_message_pagination_uses_rest_compatible_defaults() {+ assert_eq!(parse_email_message_pagination(None, None).unwrap(), (0, 5));+}++#[test]+fn email_message_pagination_accepts_valid_values() {+ assert_eq!(+ parse_email_message_pagination(Some(7), Some(20)).unwrap(),+ (7, 20)+ );+}++#[test]+fn email_message_pagination_rejects_invalid_values() {+ assert_eq!(+ parse_email_message_pagination(Some(-1), None)+ .unwrap_err()+ .message,+ "offset must be non-negative"+ );+ assert_eq!(+ parse_email_message_pagination(None, Some(0))+ .unwrap_err()+ .message,+ "limit must be positive"+ );+ assert_eq!(+ parse_email_message_pagination(None, Some(101))+ .unwrap_err()+ .message,+ "limit must not exceed 100"+ );+}diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex dee08019c3..fd0f2c5c97 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -20,8 +20,10 @@ fn soup_response_schema_exposes_frontend_fields() {"attachments: [GraphqlSoupEmailAttachment!]!","labels: [GraphqlSoupEmailLabel!]!","properties: [GraphqlProperty!]!",+ "messages(offset: Int, limit: Int): [GraphqlSoupEmailMessage!]!","latestContentMessage: GraphqlSoupEmailMessage","type GraphqlSoupEmailMessage {",+ "isDraft: Boolean!","bodyParsed: String","bodyHtmlSanitized: String","bodyReplyless: String",diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rsindex 8960ea8875..9eaa2dc878 100644--- a/crates/email/src/domain/ports.rs+++ b/crates/email/src/domain/ports.rs@@ -354,6 +354,14 @@ pub trait EmailContentService: Send + Sync + 'static {&self,receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,) -> impl Future<Output = Result<HashMap<Uuid, ParsedMessage>, EmailErr>> + Send;++ /// Fetch one page of parsed messages for an authorized thread.+ fn get_messages_parsed(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ offset: i64,+ limit: i64,+ ) -> impl Future<Output = Result<Option<Vec<ParsedMessage>>, EmailErr>> + Send;}/// Newtype adapter that restricts a full `EmailService` to read-only preview access.@@ -693,6 +701,15 @@ impl EmailContentService for NoOpEmailService {) -> Result<HashMap<Uuid, ParsedMessage>, EmailErr> {Err(no_op_email_err())}++ async fn get_messages_parsed(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ _offset: i64,+ _limit: i64,+ ) -> Result<Option<Vec<ParsedMessage>>, EmailErr> {+ Err(no_op_email_err())+ }}/// Outcome of a first-inbox provisioning attempt.diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rsindex 70c2dd4713..9a85fa2758 100644--- a/crates/email/src/domain/service/mod.rs+++ b/crates/email/src/domain/service/mod.rs@@ -459,4 +459,15 @@ where) -> Result<HashMap<Uuid, ParsedMessage>, EmailErr> {self.get_latest_messages_parsed_impl(receipts).await}++ async fn get_messages_parsed(+ &self,+ receipt: EntityAccessReceipt<ViewAccessLevel>,+ offset: i64,+ limit: i64,+ ) -> Result<Option<Vec<ParsedMessage>>, EmailErr> {+ self.get_thread_parsed_impl(receipt, offset, limit)+ .await+ .map(|thread| thread.map(|thread| thread.messages))+ }}diff --git a/crates/graphql_email/Cargo.toml b/crates/graphql_email/Cargo.tomlindex c8c5f15f10..fba3941677 100644--- a/crates/graphql_email/Cargo.toml+++ b/crates/graphql_email/Cargo.toml@@ -9,6 +9,7 @@ async-graphql = { workspace = true, features = ["dataloader"] }chrono = { workspace = true }email = { path = "../email", default-features = false, features = ["ports"] }entity_access = { path = "../entity_access", default-features = false }+futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }tokio = { workspace = true }tracing = { workspace = true }diff --git a/crates/graphql_email/src/lib.rs b/crates/graphql_email/src/lib.rsindex 1d189b2609..de88b8be61 100644--- a/crates/graphql_email/src/lib.rs+++ b/crates/graphql_email/src/lib.rs@@ -9,4 +9,4 @@ pub use loaders::{EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader, email_content_loader,};-pub use objects::{GraphqlSoupEmailMessage, load_latest_email_message};+pub use objects::{GraphqlSoupEmailMessage, load_email_messages, load_latest_email_message};diff --git a/crates/graphql_email/src/loaders.rs b/crates/graphql_email/src/loaders.rsindex e02ad70909..c5171fee29 100644--- a/crates/graphql_email/src/loaders.rs+++ b/crates/graphql_email/src/loaders.rs@@ -1,29 +1,75 @@-use std::{collections::HashMap, sync::Arc};+use std::{+ collections::{HashMap, HashSet},+ sync::Arc,+};use async_graphql::dataloader::{DataLoader, Loader};use email::domain::{models::ParsedMessage, ports::EmailContentService};use entity_access::domain::{models::AccessError, ports::EntityAccessService};+use futures::future::join_all;use macro_user_id::user_id::MacroUserIdStr;use uuid::Uuid;pub(crate) const MAX_EMAIL_CONTENT_KEYS: usize = 20;+pub(crate) const MAX_EMAIL_CONTENT_MESSAGES: usize = 100;-/// Result of loading the newest non-draft content message for one email thread.+/// Result of loading parsed content messages for one email thread.#[derive(Debug, Clone)]pub enum EmailContentLoad {- /// The thread has a non-draft content message.- Found(Box<ParsedMessage>),- /// The thread is absent, inaccessible, or has no content messages.+ /// The thread has a parsed content-message page, which may be empty.+ Found(Vec<ParsedMessage>),+ /// The thread is absent or inaccessible.Missing,/// An internal failure occurred. Details are logged, never exposed.Failed,}-/// A request for the newest non-draft content message belonging to an email thread.+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]+enum EmailContentRequest {+ Latest,+ Page { offset: u32, limit: u32 },+}++/// A request for parsed content messages belonging to an email thread.#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]pub struct EmailContentKey {/// Email thread ID.pub thread_id: Uuid,+ request: EmailContentRequest,+}++impl EmailContentKey {+ /// Request the newest non-draft content message for a thread.+ pub fn latest(thread_id: Uuid) -> Self {+ Self {+ thread_id,+ request: EmailContentRequest::Latest,+ }+ }++ /// Request a paginated content-message page for a thread.+ pub fn page(thread_id: Uuid, offset: u32, limit: u32) -> Self {+ Self {+ thread_id,+ request: EmailContentRequest::Page { offset, limit },+ }+ }++ fn requested_message_count(self) -> usize {+ match self.request {+ EmailContentRequest::Latest => 1,+ EmailContentRequest::Page { limit, .. } => limit as usize,+ }+ }++ fn page_params(self) -> Option<(i64, i64)> {+ match self.request {+ EmailContentRequest::Latest => None,+ EmailContentRequest::Page { offset, limit } => {+ Some((i64::from(offset), i64::from(limit)))+ }+ }+ }}/// Reader used by the Soup email-content GraphQL edge.@@ -80,76 +126,129 @@ whereuser_id: &MacroUserIdStr<'static>,keys: Vec<EmailContentKey>,) -> HashMap<EmailContentKey, EmailContentLoad> {- let thread_ids = keys- .iter()- .map(|key| key.thread_id.to_string())- .collect::<Vec<_>>();- let mut receipts = self+ let thread_ids = keys.iter().map(|key| key.thread_id).collect::<HashSet<_>>();+ let thread_id_strings = thread_ids.iter().map(Uuid::to_string).collect::<Vec<_>>();+ let mut access_results = self.entity_access_service- .generate_email_thread_view_access_receipts(user_id, None, &thread_ids)+ .generate_email_thread_view_access_receipts(user_id, None, &thread_id_strings).await;- let mut loads = HashMap::with_capacity(keys.len());- let mut authorized = Vec::with_capacity(keys.len());- let mut authorized_keys = HashMap::with_capacity(keys.len());+ let mut authorized = HashMap::with_capacity(thread_ids.len());+ let mut missing = HashSet::new();+ let mut failed = HashSet::new();- for key in keys {- match receipts- .remove(&key.thread_id.to_string())+ for thread_id in thread_ids {+ match access_results+ .remove(&thread_id.to_string()).unwrap_or(Err(AccessError::Internal)){Ok(receipt) => {- authorized.push(receipt);- authorized_keys.insert(key.thread_id, key);+ authorized.insert(thread_id, receipt);}Err(AccessError::Unauthorized| AccessError::UnauthorizedWithMessage(_)| AccessError::NotFound(_),) => {- loads.insert(key, EmailContentLoad::Missing);+ missing.insert(thread_id);}Err(error) => {- tracing::error!(thread_id = %key.thread_id, error = ?error, "email content access check failed");- loads.insert(key, EmailContentLoad::Failed);+ tracing::error!(%thread_id, error = ?error, "email content access check failed");+ failed.insert(thread_id);}}}- if authorized.is_empty() {- return loads;+ let mut loads = HashMap::with_capacity(keys.len());+ let mut latest_requests = Vec::new();+ let mut page_requests = Vec::new();++ for key in keys {+ let Some(receipt) = authorized.get(&key.thread_id).cloned() else {+ let load = if missing.contains(&key.thread_id) {+ EmailContentLoad::Missing+ } else {+ debug_assert!(failed.contains(&key.thread_id));+ EmailContentLoad::Failed+ };+ loads.insert(key, load);+ continue;+ };++ match key.request {+ EmailContentRequest::Latest => latest_requests.push((key, receipt)),+ EmailContentRequest::Page { .. } => page_requests.push((key, receipt)),+ }}- match self- .email_service- .get_latest_messages_parsed(authorized)- .await- {- Ok(mut messages) => {- for (thread_id, key) in authorized_keys {- let load = messages- .remove(&thread_id)- .map_or(EmailContentLoad::Missing, |message| {- EmailContentLoad::Found(Box::new(message))- });- loads.insert(key, load);+ if !latest_requests.is_empty() {+ let receipts = latest_requests+ .iter()+ .map(|(_, receipt)| receipt.clone())+ .collect();+ match self+ .email_service+ .get_latest_messages_parsed(receipts)+ .await+ {+ Ok(mut messages) => {+ for (key, _) in latest_requests {+ let load = messages+ .remove(&key.thread_id)+ .map_or(EmailContentLoad::Missing, |message| {+ EmailContentLoad::Found(vec![message])+ });+ loads.insert(key, load);+ }+ }+ Err(error) => {+ tracing::error!(error = ?error, "bulk latest email content load failed");+ loads.extend(+ latest_requests+ .into_iter()+ .map(|(key, _)| (key, EmailContentLoad::Failed)),+ );}}- Err(error) => {- tracing::error!(error = ?error, "bulk email content load failed");- loads.extend(- authorized_keys- .into_values()- .map(|key| (key, EmailContentLoad::Failed)),- );+ }++ let page_results = join_all(page_requests.into_iter().map(|(key, receipt)| {+ let email_service = Arc::clone(&self.email_service);+ async move {+ let (offset, limit) = key+ .page_params()+ .expect("page requests always have pagination parameters");+ let result = email_service+ .get_messages_parsed(receipt, offset, limit)+ .await;+ (key, offset, limit, result)}+ }))+ .await;++ for (key, offset, limit, result) in page_results {+ let load = match result {+ Ok(Some(messages)) => EmailContentLoad::Found(messages),+ Ok(None) => EmailContentLoad::Missing,+ Err(error) => {+ tracing::error!(+ thread_id = %key.thread_id,+ offset,+ limit,+ error = ?error,+ "paginated email content load failed"+ );+ EmailContentLoad::Failed+ }+ };+ loads.insert(key, load);}loads}}-/// DataLoader for the newest non-draft content message attached to Soup email threads.+/// DataLoader for parsed content messages attached to Soup email threads.pub struct EmailContentLoader<R> {user_id: MacroUserIdStr<'static>,reader: R,@@ -159,14 +258,23 @@ pub struct EmailContentLoader<R> {#[derive(Debug)]pub struct EmailContentLoaderError {key_count: usize,+ message_count: usize,}impl std::fmt::Display for EmailContentLoaderError {fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ if self.key_count > MAX_EMAIL_CONTENT_KEYS {+ return write!(+ formatter,+ "email content edge supports at most {MAX_EMAIL_CONTENT_KEYS} requests per operation (received {})",+ self.key_count+ );+ }+write!(formatter,- "email content edge supports at most {MAX_EMAIL_CONTENT_KEYS} threads per operation (received {})",- self.key_count+ "email content edge supports at most {MAX_EMAIL_CONTENT_MESSAGES} requested messages per operation (received {})",+ self.message_count)}}@@ -191,14 +299,18 @@ where&self,keys: &[EmailContentKey],) -> Result<HashMap<EmailContentKey, Self::Value>, Self::Error> {- if keys.len() > MAX_EMAIL_CONTENT_KEYS {+ let message_count = keys.iter().map(|key| key.requested_message_count()).sum();+ if keys.len() > MAX_EMAIL_CONTENT_KEYS || message_count > MAX_EMAIL_CONTENT_MESSAGES {tracing::warn!(key_count = keys.len(),+ message_count,max_key_count = MAX_EMAIL_CONTENT_KEYS,+ max_message_count = MAX_EMAIL_CONTENT_MESSAGES,"rejecting oversized Soup email content batch");return Err(Arc::new(EmailContentLoaderError {key_count: keys.len(),+ message_count,}));}diff --git a/crates/graphql_email/src/loaders/test.rs b/crates/graphql_email/src/loaders/test.rsindex 8680ee32d5..3a0876280d 100644--- a/crates/graphql_email/src/loaders/test.rs+++ b/crates/graphql_email/src/loaders/test.rs@@ -1,6 +1,6 @@use entity_access::domain::models::TeamRole;use std::sync::{- Arc,+ Arc, Mutex,atomic::{AtomicUsize, Ordering},};@@ -149,7 +149,9 @@ impl EntityAccessService for TestAccessService {#[derive(Default)]struct RecordingContentService {- calls: AtomicUsize,+ latest_calls: AtomicUsize,+ page_calls: AtomicUsize,+ pagination: Mutex<Vec<(i64, i64)>>,}impl EmailContentService for RecordingContentService {@@ -157,15 +159,24 @@ impl EmailContentService for RecordingContentService {&self,_receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,) -> Result<HashMap<Uuid, ParsedMessage>, EmailErr> {- self.calls.fetch_add(1, Ordering::SeqCst);+ self.latest_calls.fetch_add(1, Ordering::SeqCst);Ok(HashMap::new())}++ async fn get_messages_parsed(+ &self,+ _receipt: EntityAccessReceipt<ViewAccessLevel>,+ offset: i64,+ limit: i64,+ ) -> Result<Option<Vec<ParsedMessage>>, EmailErr> {+ self.page_calls.fetch_add(1, Ordering::SeqCst);+ self.pagination.lock().unwrap().push((offset, limit));+ Ok(Some(Vec::new()))+ }}fn key(index: usize) -> EmailContentKey {- EmailContentKey {- thread_id: Uuid::from_u128(index as u128),- }+ EmailContentKey::latest(Uuid::from_u128(index as u128))}#[tokio::test]@@ -199,7 +210,23 @@ async fn rejects_oversized_batches_without_calling_the_reader() {let error = loader.load(&keys).await.unwrap_err();assert_eq!(reader.calls.load(Ordering::SeqCst), 0);- assert!(error.to_string().contains("at most 20 threads"));+ assert!(error.to_string().contains("at most 20 requests"));+}++#[tokio::test]+async fn rejects_excessive_requested_messages_without_calling_the_reader() {+ let reader = RecordingReader::default();+ let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let loader = EmailContentLoader::new(user_id, reader.clone());+ let keys = vec![+ EmailContentKey::page(Uuid::from_u128(1), 0, 51),+ EmailContentKey::page(Uuid::from_u128(2), 0, 50),+ ];++ let error = loader.load(&keys).await.unwrap_err();++ assert_eq!(reader.calls.load(Ordering::SeqCst), 0);+ assert!(error.to_string().contains("at most 100 requested messages"));}#[tokio::test]@@ -214,13 +241,34 @@ async fn authorized_keys_reach_the_email_domain() {let loaded = reader.get_email_content(&user_id, vec![requested]).await;- assert_eq!(content.calls.load(Ordering::SeqCst), 1);+ assert_eq!(content.latest_calls.load(Ordering::SeqCst), 1);assert!(matches!(loaded.get(&requested),Some(EmailContentLoad::Missing)));}+#[tokio::test]+async fn paginated_keys_forward_offset_and_limit_to_the_email_domain() {+ let content = Arc::new(RecordingContentService::default());+ let reader = EmailServiceEmailContentReader::new(+ content.clone(),+ Arc::new(TestAccessService { allow: true }),+ );+ let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let requested = EmailContentKey::page(Uuid::from_u128(1), 7, 9);++ let loaded = reader.get_email_content(&user_id, vec![requested]).await;++ assert_eq!(content.latest_calls.load(Ordering::SeqCst), 0);+ assert_eq!(content.page_calls.load(Ordering::SeqCst), 1);+ assert_eq!(*content.pagination.lock().unwrap(), vec![(7, 9)]);+ assert!(matches!(+ loaded.get(&requested),+ Some(EmailContentLoad::Found(messages)) if messages.is_empty()+ ));+}+#[tokio::test]async fn unauthorized_keys_do_not_reach_the_email_domain() {let content = Arc::new(RecordingContentService::default());@@ -233,7 +281,8 @@ async fn unauthorized_keys_do_not_reach_the_email_domain() {let loaded = reader.get_email_content(&user_id, vec![requested]).await;- assert_eq!(content.calls.load(Ordering::SeqCst), 0);+ assert_eq!(content.latest_calls.load(Ordering::SeqCst), 0);+ assert_eq!(content.page_calls.load(Ordering::SeqCst), 0);assert!(matches!(loaded.get(&requested),Some(EmailContentLoad::Missing)diff --git a/crates/graphql_email/src/objects.rs b/crates/graphql_email/src/objects.rsindex 2e61a39b2d..35bdf3ddd2 100644--- a/crates/graphql_email/src/objects.rs+++ b/crates/graphql_email/src/objects.rs@@ -61,6 +61,11 @@ impl GraphqlSoupEmailMessage {self.0.is_sent}+ /// Whether the message is a draft.+ async fn is_draft(&self) -> bool {+ self.0.is_draft+ }+/// Whether the message has attachments.async fn has_attachments(&self) -> bool {self.0.has_attachments@@ -186,22 +191,40 @@ impl GraphqlSoupEmailMessageLabel {}}-/// Load the newest non-draft content message for an email thread.-pub async fn load_latest_email_message<R>(+/// Load a paginated parsed-message page for an email thread.+pub async fn load_email_messages<R>(ctx: &Context<'_>,key: EmailContentKey,-) -> async_graphql::Result<Option<GraphqlSoupEmailMessage>>+) -> async_graphql::Result<Vec<GraphqlSoupEmailMessage>>whereR: SoupEmailContentEdgeReader,{let loader = ctx.data::<DataLoader<EmailContentLoader<R>>>()?;let value = loader.load_one(key).await?;Ok(match value {- Some(EmailContentLoad::Found(message)) => Some(GraphqlSoupEmailMessage(*message)),- Some(EmailContentLoad::Missing | EmailContentLoad::Failed) | None => None,+ Some(EmailContentLoad::Found(messages)) => {+ messages.into_iter().map(GraphqlSoupEmailMessage).collect()+ }+ Some(EmailContentLoad::Missing | EmailContentLoad::Failed) | None => Vec::new(),})}+/// Load the newest non-draft content message for an email thread.+pub async fn load_latest_email_message<R>(+ ctx: &Context<'_>,+ thread_id: uuid::Uuid,+) -> async_graphql::Result<Option<GraphqlSoupEmailMessage>>+where+ R: SoupEmailContentEdgeReader,+{+ Ok(+ load_email_messages::<R>(ctx, EmailContentKey::latest(thread_id))+ .await?+ .into_iter()+ .next(),+ )+}+#[cfg(test)]mod tests {use std::collections::HashMap;@@ -222,11 +245,16 @@ mod tests {&self,ctx: &Context<'_>,) -> async_graphql::Result<Option<GraphqlSoupEmailMessage>> {- load_latest_email_message::<ContentReader>(+ load_latest_email_message::<ContentReader>(ctx, Uuid::from_u128(2)).await+ }++ async fn messages(+ &self,+ ctx: &Context<'_>,+ ) -> async_graphql::Result<Vec<GraphqlSoupEmailMessage>> {+ load_email_messages::<ContentReader>(ctx,- EmailContentKey {- thread_id: Uuid::from_u128(2),- },+ EmailContentKey::page(Uuid::from_u128(2), 3, 2),).await}@@ -241,12 +269,7 @@ mod tests {keys: Vec<EmailContentKey>,) -> HashMap<EmailContentKey, EmailContentLoad> {keys.into_iter()- .map(|key| {- (- key,- EmailContentLoad::Found(Box::new(message(key.thread_id))),- )- })+ .map(|key| (key, EmailContentLoad::Found(vec![message(key.thread_id)]))).collect()}}@@ -281,6 +304,24 @@ mod tests {}}+ #[tokio::test]+ async fn executes_paginated_messages_with_request_scoped_loader() {+ let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();+ let schema = Schema::build(ContentQuery, EmptyMutation, EmptySubscription)+ .data(email_content_loader(user_id, ContentReader))+ .finish();++ let response = schema+ .execute("{ messages { id threadId bodyParsed } }")+ .await;++ assert!(response.errors.is_empty(), "{:?}", response.errors);+ assert_eq!(+ response.data.to_string(),+ r#"{messages: [{id: "00000000-0000-0000-0000-000000000001", threadId: "00000000-0000-0000-0000-000000000002", bodyParsed: "Hello from the edge"}]}"#+ );+ }+#[tokio::test]async fn executes_content_field_with_request_scoped_loader() {let user_id = MacroUserIdStr::try_from_email("[email protected]").unwrap();diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex b7d11789af..318126afa3 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -2562,6 +2562,10 @@ type GraphqlSoupEmailMessage {"""isSent: Boolean!"""+ Whether the message is a draft.+ """+ isDraft: Boolean!+ """Whether the message has attachments."""hasAttachments: Boolean!@@ -2784,6 +2788,10 @@ type GraphqlSoupEmailThread implements GraphqlSoupEntity {"""frecencyScore: Float"""+ A page of messages in this thread, newest first.+ """+ messages(offset: Int, limit: Int): [GraphqlSoupEmailMessage!]!+ """The newest non-draft content message in this thread."""latestContentMessage: GraphqlSoupEmailMessage