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): lazily hydrate full email message edges (#5470)

Sean Aye844928b15681
diff --git a/crates/complete_graph/src/edges.rs b/crates/complete_graph/src/edges.rs
index fe787b70e0..8c614509f8 100644
--- a/crates/complete_graph/src/edges.rs
+++ b/crates/complete_graph/src/edges.rs
@@ -2,8 +2,8 @@ use std::marker::PhantomData;
use async_graphql::{Context, Object};
use graphql_email::{
- EmailContentKey, GraphqlSoupEmailMessage, SoupEmailContentEdgeReader, load_email_messages,
- load_latest_email_message,
+ EmailContentKey, GraphqlSoupEmailMessage, SoupEmailContentEdgeReader,
+ email_message_selection_requires_full_payload, load_email_messages, load_latest_email_message,
};
use graphql_favorite::{EntityFavoriteEdgeReader, load_entity_favorite};
use graphql_notification::{
@@ -207,7 +207,12 @@ where
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
+ let key = if email_message_selection_requires_full_payload(ctx) {
+ EmailContentKey::page_full(self.thread_id, offset, limit)
+ } else {
+ EmailContentKey::page(self.thread_id, offset, limit)
+ };
+ load_email_messages::<ER>(ctx, key).await
}
/// The newest non-draft content message in this thread.
diff --git a/crates/complete_graph/src/schema/test.rs b/crates/complete_graph/src/schema/test.rs
index 10a5915295..1bdfebaf7e 100644
--- a/crates/complete_graph/src/schema/test.rs
+++ b/crates/complete_graph/src/schema/test.rs
@@ -4,10 +4,11 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use axum::http::{Request as HttpRequest, header};
use email::domain::models::{
- CreateDraftInput, CreatedDraft, EmailErr, EmailFilter, EmailSyncStatus,
- EnrichedEmailThreadPreview, GetEmailsRequest, LabelListVisibility, LabelType, Link, LinkLabel,
- MessageListVisibility, ParsedMessage, ParsedThread, Thread, UpdateThreadLabelsResult,
- UpsertEmailFilterInput, UserEmailLink, UserEmailLinkSettings, UserProvider,
+ AttachmentDraft, AttachmentForwarded, CreateDraftInput, CreatedDraft, EmailErr, EmailFilter,
+ EmailSyncStatus, EnrichedEmailThreadPreview, GetEmailsRequest, LabelListVisibility, LabelType,
+ Link, LinkLabel, Message, MessageAttachment, MessageListVisibility, ParsedMessage,
+ ParsedThread, Thread, UpdateThreadLabelsResult, UpsertEmailFilterInput, UserEmailLink,
+ UserEmailLinkSettings, UserProvider,
};
use entity_access::domain::models::{
AccessError, AccessLevel, BotAccessScope, BotId, CallChannelInfo, EditAccessLevel,
@@ -445,10 +446,12 @@ impl graphql_email::SoupEmailContentEdgeReader for RecordingEmailContentReader {
keys.into_iter()
.map(|key| {
let thread_id = key.thread_id;
- (
- key,
- graphql_email::EmailContentLoad::Found(vec![parsed_message(thread_id)]),
- )
+ let message = if key.requires_full_payload() {
+ full_message(thread_id).into()
+ } else {
+ parsed_message(thread_id).into()
+ };
+ (key, graphql_email::EmailContentLoad::Found(vec![message]))
})
.collect()
}
@@ -483,6 +486,71 @@ fn parsed_message(thread_id: Uuid) -> ParsedMessage {
}
}
+fn full_message(thread_id: Uuid) -> Message {
+ let message_id = Uuid::from_u128(100);
+ let draft_attachment_id = Uuid::from_u128(102);
+ Message {
+ db_id: message_id,
+ provider_id: Some("provider-message".to_owned()),
+ thread_db_id: thread_id,
+ provider_thread_id: Some("provider-thread".to_owned()),
+ replying_to_id: Some(Uuid::from_u128(101)),
+ global_id: Some("global-message".to_owned()),
+ link_id: Uuid::from_u128(200),
+ subject: Some("Direct thread subject".to_owned()),
+ snippet: Some("Direct thread snippet".to_owned()),
+ provider_history_id: None,
+ internal_date_ts: Some(Default::default()),
+ sent_at: Some(Default::default()),
+ size_estimate: None,
+ is_read: true,
+ is_starred: false,
+ is_sent: false,
+ is_draft: true,
+ has_attachments: true,
+ scheduled_send_time: Some(Default::default()),
+ from: None,
+ to: Vec::new(),
+ cc: Vec::new(),
+ bcc: Vec::new(),
+ labels: Vec::new(),
+ body_text: Some("Direct thread body".to_owned()),
+ body_html_sanitized: None,
+ body_macro: None,
+ body_replyless: Some("Direct thread body".to_owned()),
+ attachments: vec![MessageAttachment {
+ db_id: Uuid::from_u128(103),
+ provider_id: Some("provider-attachment".to_owned()),
+ filename: Some("provider.txt".to_owned()),
+ mime_type: Some("text/plain".to_owned()),
+ size_bytes: Some(10),
+ sfs_id: Some(Uuid::from_u128(104)),
+ content_id: Some("inline-content".to_owned()),
+ }],
+ attachments_draft: vec![AttachmentDraft {
+ id: draft_attachment_id,
+ draft_id: message_id,
+ file_name: "draft.txt".to_owned(),
+ content_type: "text/plain".to_owned(),
+ sha: "sha256".to_owned(),
+ size: 20,
+ s3_key: "draft/key".to_owned(),
+ }],
+ attachments_forwarded: vec![AttachmentForwarded {
+ attachment_id: Uuid::from_u128(105),
+ draft_id: message_id,
+ provider_attachment_id: Some("forwarded-attachment".to_owned()),
+ message_provider_id: "original-provider-message".to_owned(),
+ filename: Some("forwarded.txt".to_owned()),
+ mime_type: Some("text/plain".to_owned()),
+ size_bytes: Some(30),
+ }],
+ headers_json: None,
+ 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 {
@@ -1189,6 +1257,80 @@ async fn email_thread_returns_the_canonical_soup_type_and_forwards_message_pagin
);
}
+#[tokio::test]
+async fn email_message_full_fields_request_the_full_edge_payload() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(43);
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread(thread_id)]);
+
+ let response = harness
+ .execute(&format!(
+ r#"{{ user {{ emailThread(input: {{threadId: "{thread_id}"}}) {{ messages(offset: 2, limit: 4) {{ providerId replyingToId scheduledSendTime bodyParsed attachments {{ id providerId sfsId }} attachmentsDraft {{ id draftId fileName }} attachmentsForwarded {{ attachmentId draftId providerAttachmentId }} }} }} }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let data = response.data.into_json().unwrap();
+ let message = &data["user"]["emailThread"]["messages"][0];
+ assert_eq!(message["providerId"], "provider-message");
+ assert_eq!(message["replyingToId"], Uuid::from_u128(101).to_string());
+ assert!(message["scheduledSendTime"].as_str().is_some());
+ assert_eq!(message["bodyParsed"], "Direct thread body");
+ assert_eq!(
+ message["attachments"][0]["sfsId"],
+ Uuid::from_u128(104).to_string()
+ );
+ assert_eq!(message["attachmentsDraft"][0]["fileName"], "draft.txt");
+ assert_eq!(
+ message["attachmentsForwarded"][0]["providerAttachmentId"],
+ "forwarded-attachment"
+ );
+ assert_eq!(
+ *harness
+ .email_content_reader
+ .calls
+ .lock()
+ .expect("email content calls lock"),
+ vec![vec![graphql_email::EmailContentKey::page_full(
+ thread_id, 2, 4
+ )]]
+ );
+}
+
+#[tokio::test]
+async fn latest_email_message_full_fields_request_the_full_edge_payload() {
+ let harness = harness();
+ let thread_id = Uuid::from_u128(44);
+ harness
+ .soup_service
+ .set_raw_response(vec![soup_email_thread(thread_id)]);
+
+ let response = harness
+ .execute(&format!(
+ r#"{{ user {{ emailThread(input: {{threadId: "{thread_id}"}}) {{ latestContentMessage {{ providerId attachments {{ sfsId }} }} }} }} }}"#
+ ))
+ .await;
+
+ assert!(response.errors.is_empty(), "{:?}", response.errors);
+ let message =
+ &response.data.into_json().unwrap()["user"]["emailThread"]["latestContentMessage"];
+ assert_eq!(message["providerId"], "provider-message");
+ assert_eq!(
+ message["attachments"][0]["sfsId"],
+ Uuid::from_u128(104).to_string()
+ );
+ assert_eq!(
+ *harness
+ .email_content_reader
+ .calls
+ .lock()
+ .expect("email content calls lock"),
+ vec![vec![graphql_email::EmailContentKey::latest_full(thread_id)]]
+ );
+}
+
#[tokio::test]
async fn email_mutations_return_the_canonical_thread_for_normalized_cache_updates() {
let harness = harness();
diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rs
index 65e1fef564..1f12c6da9b 100644
--- a/crates/complete_graph/src/sdl_test.rs
+++ b/crates/complete_graph/src/sdl_test.rs
@@ -41,10 +41,19 @@ fn soup_response_schema_exposes_frontend_fields() {
"messages(offset: Int, limit: Int): [GraphqlSoupEmailMessage!]!",
"latestContentMessage: GraphqlSoupEmailMessage",
"type GraphqlSoupEmailMessage {",
+ "replyingToId: ID",
+ "scheduledSendTime: String",
"isDraft: Boolean!",
"bodyParsed: String",
"bodyHtmlSanitized: String",
"bodyReplyless: String",
+ "attachments: [GraphqlSoupEmailMessageAttachment!]!",
+ "attachmentsDraft: [GraphqlSoupEmailDraftAttachment!]!",
+ "attachmentsForwarded: [GraphqlSoupEmailForwardedAttachment!]!",
+ "type GraphqlSoupEmailMessageAttachment {",
+ "sfsId: ID",
+ "type GraphqlSoupEmailDraftAttachment {",
+ "type GraphqlSoupEmailForwardedAttachment {",
"type GraphqlSoupCall implements GraphqlSoupEntity {",
"channelName: String",
"customName: String",
diff --git a/crates/email/src/domain/models/parsed_message.rs b/crates/email/src/domain/models/parsed_message.rs
index c6ce582d67..b6b9fa0bba 100644
--- a/crates/email/src/domain/models/parsed_message.rs
+++ b/crates/email/src/domain/models/parsed_message.rs
@@ -1,7 +1,7 @@
use chrono::{DateTime, Utc};
use uuid::Uuid;
-use super::contact::ContactInfo;
+use super::{contact::ContactInfo, message::Message};
/// A lightweight label representation for parsed messages.
#[derive(Debug, Clone)]
@@ -65,6 +65,49 @@ pub struct ParsedMessage {
pub updated_at: DateTime<Utc>,
}
+impl From<&Message> for ParsedMessage {
+ fn from(message: &Message) -> Self {
+ let body_parsed = email_utils::body_parsed::compute_body_parsed(
+ message.body_html_sanitized.is_some(),
+ &message.body_replyless,
+ );
+
+ Self {
+ db_id: message.db_id,
+ link_id: message.link_id,
+ thread_db_id: message.thread_db_id,
+ subject: message.subject.clone(),
+ snippet: message.snippet.clone(),
+ from: message.from.clone(),
+ to: message.to.clone(),
+ cc: message.cc.clone(),
+ bcc: message.bcc.clone(),
+ labels: message
+ .labels
+ .iter()
+ .map(|label| ParsedLabel {
+ provider_id: label.provider_label_id.clone(),
+ name: label.name.clone().unwrap_or_default(),
+ })
+ .collect(),
+ body_parsed,
+ body_text: message.body_text.clone(),
+ body_html_sanitized: message.body_html_sanitized.clone(),
+ body_macro: message.body_macro.clone(),
+ body_replyless: message.body_replyless.clone(),
+ internal_date_ts: message.internal_date_ts,
+ sent_at: message.sent_at,
+ is_read: message.is_read,
+ is_starred: message.is_starred,
+ is_sent: message.is_sent,
+ is_draft: message.is_draft,
+ has_attachments: message.has_attachments,
+ created_at: message.created_at,
+ updated_at: message.updated_at,
+ }
+ }
+}
+
/// A thread with lightweight parsed messages.
#[derive(Debug, Clone)]
pub struct ParsedThread {
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index e8511007ba..c293ac2d4e 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -1,11 +1,11 @@
use crate::domain::models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, CreateDraftInput,
CreatedDraft, EmailErr, EmailFilter, EmailInboxDetails, EmailThreadPreview,
- EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link, LinkLabel, MessageAttachment,
- MessageLabel, MessageRow, ParsedAddresses, ParsedMessage, ParsedThread, PreviewCursorQuery,
- RecipientType, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo, Thread, ThreadRow,
- UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts, UserEmailLink,
- UserProvider,
+ EnrichedEmailThreadPreview, GetEmailsRequest, Label, Link, LinkLabel, Message,
+ MessageAttachment, MessageLabel, MessageRow, ParsedAddresses, ParsedMessage, ParsedThread,
+ PreviewCursorQuery, RecipientType, ResolvedDraftInput, SimpleMessage, SimpleMessageInfo,
+ Thread, ThreadRow, UpdateThreadLabelsResult, UpsertEmailFilterInput, UpsertedContacts,
+ UserEmailLink, UserProvider,
};
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, ViewAccessLevel};
@@ -387,6 +387,12 @@ pub trait EmailContentService: Send + Sync + 'static {
receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
) -> impl Future<Output = Result<HashMap<Uuid, ParsedMessage>, EmailErr>> + Send;
+ /// Fetch the newest non-draft fully hydrated message for each authorized thread.
+ fn get_latest_messages_full(
+ &self,
+ receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> impl Future<Output = Result<HashMap<Uuid, Message>, EmailErr>> + Send;
+
/// Fetch one page of parsed messages for an authorized thread.
fn get_messages_parsed(
&self,
@@ -394,6 +400,14 @@ pub trait EmailContentService: Send + Sync + 'static {
offset: i64,
limit: i64,
) -> impl Future<Output = Result<Option<Vec<ParsedMessage>>, EmailErr>> + Send;
+
+ /// Fetch one page of fully hydrated messages for an authorized thread.
+ fn get_messages_full(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> impl Future<Output = Result<Option<Vec<Message>>, EmailErr>> + Send;
}
/// Newtype adapter that restricts a full `EmailService` to read-only preview access.
@@ -785,6 +799,13 @@ impl EmailContentService for NoOpEmailService {
Err(no_op_email_err())
}
+ async fn get_latest_messages_full(
+ &self,
+ _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Result<HashMap<Uuid, Message>, EmailErr> {
+ Err(no_op_email_err())
+ }
+
async fn get_messages_parsed(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -793,6 +814,15 @@ impl EmailContentService for NoOpEmailService {
) -> Result<Option<Vec<ParsedMessage>>, EmailErr> {
Err(no_op_email_err())
}
+
+ async fn get_messages_full(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ _offset: i64,
+ _limit: i64,
+ ) -> Result<Option<Vec<Message>>, 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.rs
index 695d10af4d..15ba77ee66 100644
--- a/crates/email/src/domain/service/mod.rs
+++ b/crates/email/src/domain/service/mod.rs
@@ -481,6 +481,13 @@ where
self.get_latest_messages_parsed_impl(receipts).await
}
+ async fn get_latest_messages_full(
+ &self,
+ receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Result<HashMap<Uuid, crate::domain::models::Message>, EmailErr> {
+ self.get_latest_messages_full_impl(receipts).await
+ }
+
async fn get_messages_parsed(
&self,
receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -491,4 +498,15 @@ where
.await
.map(|thread| thread.map(|thread| thread.messages))
}
+
+ async fn get_messages_full(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> Result<Option<Vec<crate::domain::models::Message>>, EmailErr> {
+ self.get_thread_with_messages_impl(receipt, offset, limit)
+ .await
+ .map(|thread| thread.map(|thread| thread.messages))
+ }
}
diff --git a/crates/email/src/domain/service/thread.rs b/crates/email/src/domain/service/thread.rs
index 5279a18415..b3d1815893 100644
--- a/crates/email/src/domain/service/thread.rs
+++ b/crates/email/src/domain/service/thread.rs
@@ -20,7 +20,6 @@ use super::EmailServiceImpl;
struct ThreadFetchResult {
thread_row: ThreadRow,
message_rows: Vec<MessageRow>,
- message_ids: Vec<Uuid>,
senders: HashMap<Uuid, ContactInfo>,
recipients: RecipientsByMessageId,
labels: HashMap<Uuid, Vec<MessageLabel>>,
@@ -75,7 +74,6 @@ where
return Ok(Some(ThreadFetchResult {
thread_row,
message_rows: vec![],
- message_ids: vec![],
senders: HashMap::new(),
recipients: HashMap::new(),
labels: HashMap::new(),
@@ -128,7 +126,6 @@ where
Ok(Some(ThreadFetchResult {
thread_row,
message_rows,
- message_ids,
senders,
recipients,
labels,
@@ -136,35 +133,28 @@ where
}))
}
- #[tracing::instrument(err, skip(self, receipt))]
- pub(crate) async fn get_thread_with_messages_impl(
+ async fn hydrate_full_messages(
&self,
- receipt: EntityAccessReceipt<ViewAccessLevel>,
- offset: i64,
- limit: i64,
- ) -> Result<Option<Thread>, EmailErr> {
- let Some(ThreadFetchResult {
- thread_row,
- message_rows,
- message_ids,
- mut senders,
- mut recipients,
- mut labels,
- is_owner,
- }) = self.fetch_thread_core(&receipt, offset, limit).await?
- else {
- return Ok(None);
- };
-
+ message_rows: Vec<MessageRow>,
+ mut senders: HashMap<Uuid, ContactInfo>,
+ mut recipients: RecipientsByMessageId,
+ mut labels: HashMap<Uuid, Vec<MessageLabel>>,
+ is_owner: bool,
+ ) -> Result<Vec<Message>, EmailErr> {
+ let message_rows: Vec<MessageRow> = message_rows
+ .into_iter()
+ .filter(|row| is_owner || !row.is_draft)
+ .collect();
+ let message_ids: Vec<Uuid> = message_rows.iter().map(|row| row.db_id).collect();
let message_ids_with_attachments: Vec<Uuid> = message_rows
.iter()
- .filter(|m| m.has_attachments)
- .map(|m| m.db_id)
+ .filter(|message| message.has_attachments)
+ .map(|message| message.db_id)
.collect();
let draft_message_ids: Vec<Uuid> = message_rows
.iter()
- .filter(|m| m.provider_id.is_none())
- .map(|m| m.db_id)
+ .filter(|message| message.provider_id.is_none())
+ .map(|message| message.db_id)
.collect();
let (mut scheduled, mut attachments, mut draft_attachments, mut forwarded_attachments) = tokio::try_join!(
@@ -194,9 +184,8 @@ where
},
)?;
- let messages: Vec<Message> = message_rows
+ Ok(message_rows
.into_iter()
- .filter(|row| is_owner || !row.is_draft)
.map(|row| {
let sender = senders.remove(&row.db_id);
let recipient_list = recipients.remove(&row.db_id).unwrap_or_default();
@@ -209,7 +198,6 @@ where
forwarded_attachments.remove(&row.db_id).unwrap_or_default();
let (to, cc, bcc) = split_recipients(recipient_list);
-
let body_replyless = email_utils::body_replyless::compute_body_replyless(
row.subject.as_deref(),
row.body_html_sanitized.as_deref(),
@@ -230,7 +218,31 @@ where
body_replyless,
)
})
- .collect();
+ .collect())
+ }
+
+ #[tracing::instrument(err, skip(self, receipt))]
+ pub(crate) async fn get_thread_with_messages_impl(
+ &self,
+ receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> Result<Option<Thread>, EmailErr> {
+ let Some(ThreadFetchResult {
+ thread_row,
+ message_rows,
+ senders,
+ recipients,
+ labels,
+ is_owner,
+ }) = self.fetch_thread_core(&receipt, offset, limit).await?
+ else {
+ return Ok(None);
+ };
+
+ let messages = self
+ .hydrate_full_messages(message_rows, senders, recipients, labels, is_owner)
+ .await?;
Ok(Some(thread_from_row(thread_row, messages)))
}
@@ -245,7 +257,6 @@ where
let Some(ThreadFetchResult {
thread_row,
message_rows,
- message_ids: _,
mut senders,
mut recipients,
mut labels,
@@ -344,6 +355,53 @@ where
})
.collect())
}
+
+ /// Fetch and fully hydrate the newest non-draft content message for each
+ /// authorized thread.
+ pub(crate) async fn get_latest_messages_full_impl(
+ &self,
+ receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Result<HashMap<Uuid, Message>, EmailErr> {
+ let thread_ids = email_thread_ids_from_receipts(receipts)?;
+
+ if thread_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let rows = self
+ .email_repo
+ .latest_content_message_rows(&thread_ids)
+ .await
+ .map_err(anyhow::Error::from)?;
+ let message_ids = rows.iter().map(|row| row.db_id).collect::<Vec<_>>();
+ let (senders, recipients, labels) = tokio::try_join!(
+ async {
+ self.email_repo
+ .senders_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .recipients_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ async {
+ self.email_repo
+ .labels_by_message_ids(&message_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ },
+ )?;
+
+ Ok(self
+ .hydrate_full_messages(rows, senders, recipients, labels, true)
+ .await?
+ .into_iter()
+ .map(|message| (message.thread_db_id, message))
+ .collect())
+ }
}
fn email_thread_ids_from_receipts(
diff --git a/crates/graphql_email/src/lib.rs b/crates/graphql_email/src/lib.rs
index 95ccdd3cd4..0e4fba777d 100644
--- a/crates/graphql_email/src/lib.rs
+++ b/crates/graphql_email/src/lib.rs
@@ -9,14 +9,18 @@ mod user_objects;
mod user_query;
pub use loaders::{
- EmailContentKey, EmailContentLoad, EmailContentLoader, EmailServiceEmailContentReader,
- NoOpSoupEmailContentEdgeReader, SoupEmailContentEdgeReader, email_content_loader,
+ EmailContentKey, EmailContentLoad, EmailContentLoader, EmailContentMessage,
+ 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 objects::{
+ GraphqlSoupEmailMessage, email_message_selection_requires_full_payload, load_email_messages,
+ load_latest_email_message,
+};
pub use user_objects::{
GraphqlEmailLabel, GraphqlEmailLink, GraphqlEmailLinkSettings, GraphqlEmailProvider,
GraphqlEmailSyncStatus,
diff --git a/crates/graphql_email/src/loaders.rs b/crates/graphql_email/src/loaders.rs
index c5171fee29..4847bc1ed8 100644
--- a/crates/graphql_email/src/loaders.rs
+++ b/crates/graphql_email/src/loaders.rs
@@ -4,7 +4,10 @@ use std::{
};
use async_graphql::dataloader::{DataLoader, Loader};
-use email::domain::{models::ParsedMessage, ports::EmailContentService};
+use email::domain::{
+ models::{Message, ParsedMessage},
+ ports::EmailContentService,
+};
use entity_access::domain::{models::AccessError, ports::EntityAccessService};
use futures::future::join_all;
use macro_user_id::user_id::MacroUserIdStr;
@@ -13,11 +16,43 @@ use uuid::Uuid;
pub(crate) const MAX_EMAIL_CONTENT_KEYS: usize = 20;
pub(crate) const MAX_EMAIL_CONTENT_MESSAGES: usize = 100;
-/// Result of loading parsed content messages for one email thread.
+/// A message returned by the email-content edge.
+#[derive(Debug, Clone)]
+pub struct EmailContentMessage {
+ parsed: ParsedMessage,
+ full: Option<Message>,
+}
+
+impl EmailContentMessage {
+ pub(crate) fn parsed(&self) -> &ParsedMessage {
+ &self.parsed
+ }
+
+ pub(crate) fn full(&self) -> Option<&Message> {
+ self.full.as_ref()
+ }
+}
+
+impl From<ParsedMessage> for EmailContentMessage {
+ fn from(parsed: ParsedMessage) -> Self {
+ Self { parsed, full: None }
+ }
+}
+
+impl From<Message> for EmailContentMessage {
+ fn from(full: Message) -> Self {
+ Self {
+ parsed: ParsedMessage::from(&full),
+ full: Some(full),
+ }
+ }
+}
+
+/// Result of loading content messages for one email thread.
#[derive(Debug, Clone)]
pub enum EmailContentLoad {
- /// The thread has a parsed content-message page, which may be empty.
- Found(Vec<ParsedMessage>),
+ /// The thread has a content-message page, which may be empty.
+ Found(Vec<EmailContentMessage>),
/// The thread is absent or inaccessible.
Missing,
/// An internal failure occurred. Details are logged, never exposed.
@@ -30,12 +65,19 @@ enum EmailContentRequest {
Page { offset: u32, limit: u32 },
}
-/// A request for parsed content messages belonging to an email thread.
+#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)]
+enum EmailContentHydration {
+ Parsed,
+ Full,
+}
+
+/// A request for 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,
+ hydration: EmailContentHydration,
}
impl EmailContentKey {
@@ -44,17 +86,42 @@ impl EmailContentKey {
Self {
thread_id,
request: EmailContentRequest::Latest,
+ hydration: EmailContentHydration::Parsed,
+ }
+ }
+
+ /// Request the newest fully hydrated non-draft content message for a thread.
+ pub fn latest_full(thread_id: Uuid) -> Self {
+ Self {
+ thread_id,
+ request: EmailContentRequest::Latest,
+ hydration: EmailContentHydration::Full,
}
}
- /// Request a paginated content-message page for a thread.
+ /// Request a paginated lightweight 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 },
+ hydration: EmailContentHydration::Parsed,
}
}
+ /// Request a paginated fully hydrated content-message page for a thread.
+ pub fn page_full(thread_id: Uuid, offset: u32, limit: u32) -> Self {
+ Self {
+ thread_id,
+ request: EmailContentRequest::Page { offset, limit },
+ hydration: EmailContentHydration::Full,
+ }
+ }
+
+ /// Whether this request requires fully hydrated messages.
+ pub fn requires_full_payload(self) -> bool {
+ self.hydration == EmailContentHydration::Full
+ }
+
fn requested_message_count(self) -> usize {
match self.request {
EmailContentRequest::Latest => 1,
@@ -160,7 +227,8 @@ where
}
let mut loads = HashMap::with_capacity(keys.len());
- let mut latest_requests = Vec::new();
+ let mut latest_parsed_requests = Vec::new();
+ let mut latest_full_requests = Vec::new();
let mut page_requests = Vec::new();
for key in keys {
@@ -175,14 +243,19 @@ where
continue;
};
- match key.request {
- EmailContentRequest::Latest => latest_requests.push((key, receipt)),
- EmailContentRequest::Page { .. } => page_requests.push((key, receipt)),
+ match (key.request, key.hydration) {
+ (EmailContentRequest::Latest, EmailContentHydration::Parsed) => {
+ latest_parsed_requests.push((key, receipt));
+ }
+ (EmailContentRequest::Latest, EmailContentHydration::Full) => {
+ latest_full_requests.push((key, receipt));
+ }
+ (EmailContentRequest::Page { .. }, _) => page_requests.push((key, receipt)),
}
}
- if !latest_requests.is_empty() {
- let receipts = latest_requests
+ if !latest_parsed_requests.is_empty() {
+ let receipts = latest_parsed_requests
.iter()
.map(|(_, receipt)| receipt.clone())
.collect();
@@ -192,19 +265,46 @@ where
.await
{
Ok(mut messages) => {
- for (key, _) in latest_requests {
+ for (key, _) in latest_parsed_requests {
+ let load = messages
+ .remove(&key.thread_id)
+ .map_or(EmailContentLoad::Missing, |message| {
+ EmailContentLoad::Found(vec![message.into()])
+ });
+ loads.insert(key, load);
+ }
+ }
+ Err(error) => {
+ tracing::error!(error = ?error, "bulk latest parsed email content load failed");
+ loads.extend(
+ latest_parsed_requests
+ .into_iter()
+ .map(|(key, _)| (key, EmailContentLoad::Failed)),
+ );
+ }
+ }
+ }
+
+ if !latest_full_requests.is_empty() {
+ let receipts = latest_full_requests
+ .iter()
+ .map(|(_, receipt)| receipt.clone())
+ .collect();
+ match self.email_service.get_latest_messages_full(receipts).await {
+ Ok(mut messages) => {
+ for (key, _) in latest_full_requests {
let load = messages
.remove(&key.thread_id)
.map_or(EmailContentLoad::Missing, |message| {
- EmailContentLoad::Found(vec![message])
+ EmailContentLoad::Found(vec![message.into()])
});
loads.insert(key, load);
}
}
Err(error) => {
- tracing::error!(error = ?error, "bulk latest email content load failed");
+ tracing::error!(error = ?error, "bulk latest full email content load failed");
loads.extend(
- latest_requests
+ latest_full_requests
.into_iter()
.map(|(key, _)| (key, EmailContentLoad::Failed)),
);
@@ -218,9 +318,30 @@ where
let (offset, limit) = key
.page_params()
.expect("page requests always have pagination parameters");
- let result = email_service
- .get_messages_parsed(receipt, offset, limit)
- .await;
+ let result = match key.hydration {
+ EmailContentHydration::Parsed => email_service
+ .get_messages_parsed(receipt, offset, limit)
+ .await
+ .map(|messages| {
+ messages.map(|messages| {
+ messages
+ .into_iter()
+ .map(EmailContentMessage::from)
+ .collect()
+ })
+ }),
+ EmailContentHydration::Full => email_service
+ .get_messages_full(receipt, offset, limit)
+ .await
+ .map(|messages| {
+ messages.map(|messages| {
+ messages
+ .into_iter()
+ .map(EmailContentMessage::from)
+ .collect()
+ })
+ }),
+ };
(key, offset, limit, result)
}
}))
@@ -248,7 +369,7 @@ where
}
}
-/// DataLoader for parsed content messages attached to Soup email threads.
+/// DataLoader for adaptively hydrated content messages attached to Soup email threads.
pub struct EmailContentLoader<R> {
user_id: MacroUserIdStr<'static>,
reader: R,
diff --git a/crates/graphql_email/src/loaders/test.rs b/crates/graphql_email/src/loaders/test.rs
index 3a0876280d..cc335a177c 100644
--- a/crates/graphql_email/src/loaders/test.rs
+++ b/crates/graphql_email/src/loaders/test.rs
@@ -150,7 +150,9 @@ impl EntityAccessService for TestAccessService {
#[derive(Default)]
struct RecordingContentService {
latest_calls: AtomicUsize,
+ latest_full_calls: AtomicUsize,
page_calls: AtomicUsize,
+ page_full_calls: AtomicUsize,
pagination: Mutex<Vec<(i64, i64)>>,
}
@@ -163,6 +165,14 @@ impl EmailContentService for RecordingContentService {
Ok(HashMap::new())
}
+ async fn get_latest_messages_full(
+ &self,
+ _receipts: Vec<EntityAccessReceipt<ViewAccessLevel>>,
+ ) -> Result<HashMap<Uuid, Message>, EmailErr> {
+ self.latest_full_calls.fetch_add(1, Ordering::SeqCst);
+ Ok(HashMap::new())
+ }
+
async fn get_messages_parsed(
&self,
_receipt: EntityAccessReceipt<ViewAccessLevel>,
@@ -173,6 +183,17 @@ impl EmailContentService for RecordingContentService {
self.pagination.lock().unwrap().push((offset, limit));
Ok(Some(Vec::new()))
}
+
+ async fn get_messages_full(
+ &self,
+ _receipt: EntityAccessReceipt<ViewAccessLevel>,
+ offset: i64,
+ limit: i64,
+ ) -> Result<Option<Vec<Message>>, EmailErr> {
+ self.page_full_calls.fetch_add(1, Ordering::SeqCst);
+ self.pagination.lock().unwrap().push((offset, limit));
+ Ok(Some(Vec::new()))
+ }
}
fn key(index: usize) -> EmailContentKey {
@@ -242,6 +263,7 @@ async fn authorized_keys_reach_the_email_domain() {
let loaded = reader.get_email_content(&user_id, vec![requested]).await;
assert_eq!(content.latest_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(content.latest_full_calls.load(Ordering::SeqCst), 0);
assert!(matches!(
loaded.get(&requested),
Some(EmailContentLoad::Missing)
@@ -261,7 +283,9 @@ async fn paginated_keys_forward_offset_and_limit_to_the_email_domain() {
let loaded = reader.get_email_content(&user_id, vec![requested]).await;
assert_eq!(content.latest_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(content.latest_full_calls.load(Ordering::SeqCst), 0);
assert_eq!(content.page_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(content.page_full_calls.load(Ordering::SeqCst), 0);
assert_eq!(*content.pagination.lock().unwrap(), vec![(7, 9)]);
assert!(matches!(
loaded.get(&requested),
@@ -269,6 +293,34 @@ async fn paginated_keys_forward_offset_and_limit_to_the_email_domain() {
));
}
+#[tokio::test]
+async fn full_keys_use_only_the_full_email_domain_path() {
+ 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 latest = EmailContentKey::latest_full(Uuid::from_u128(1));
+ let page = EmailContentKey::page_full(Uuid::from_u128(2), 4, 6);
+
+ let loaded = reader.get_email_content(&user_id, vec![latest, page]).await;
+
+ assert_eq!(content.latest_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(content.latest_full_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(content.page_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(content.page_full_calls.load(Ordering::SeqCst), 1);
+ assert_eq!(*content.pagination.lock().unwrap(), vec![(4, 6)]);
+ assert!(matches!(
+ loaded.get(&latest),
+ Some(EmailContentLoad::Missing)
+ ));
+ assert!(matches!(
+ loaded.get(&page),
+ 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());
@@ -282,7 +334,9 @@ async fn unauthorized_keys_do_not_reach_the_email_domain() {
let loaded = reader.get_email_content(&user_id, vec![requested]).await;
assert_eq!(content.latest_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(content.latest_full_calls.load(Ordering::SeqCst), 0);
assert_eq!(content.page_calls.load(Ordering::SeqCst), 0);
+ assert_eq!(content.page_full_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.rs
index 35bdf3ddd2..a14a739e6a 100644
--- a/crates/graphql_email/src/objects.rs
+++ b/crates/graphql_email/src/objects.rs
@@ -1,84 +1,140 @@
-use async_graphql::{Context, ID, Object, dataloader::DataLoader};
-use email::domain::models::{ContactInfo, ParsedLabel, ParsedMessage};
+use async_graphql::{Context, ID, Object, SimpleObject, dataloader::DataLoader};
+use email::domain::models::{
+ AttachmentDraft, AttachmentForwarded, ContactInfo, Message, MessageAttachment, ParsedLabel,
+ ParsedMessage,
+};
use crate::loaders::{
- EmailContentKey, EmailContentLoad, EmailContentLoader, SoupEmailContentEdgeReader,
+ EmailContentKey, EmailContentLoad, EmailContentLoader, EmailContentMessage,
+ SoupEmailContentEdgeReader,
};
-/// A lightweight email content projection for Soup queries.
-pub struct GraphqlSoupEmailMessage(ParsedMessage);
+const FULL_MESSAGE_FIELDS: &[&str] = &[
+ "providerId",
+ "replyingToId",
+ "scheduledSendTime",
+ "attachments",
+ "attachmentsDraft",
+ "attachmentsForwarded",
+];
+
+/// Whether the selected message fields require fully hydrated email messages.
+pub fn email_message_selection_requires_full_payload(ctx: &Context<'_>) -> bool {
+ let lookahead = ctx.look_ahead();
+ FULL_MESSAGE_FIELDS
+ .iter()
+ .any(|field| lookahead.field(field).exists())
+}
+
+/// An adaptively hydrated email content projection for Soup queries.
+pub struct GraphqlSoupEmailMessage(EmailContentMessage);
+
+impl GraphqlSoupEmailMessage {
+ fn parsed(&self) -> &ParsedMessage {
+ self.0.parsed()
+ }
-/// A lightweight email content projection for Soup queries.
+ fn full(&self) -> async_graphql::Result<&Message> {
+ self.0.full().ok_or_else(|| {
+ async_graphql::Error::new("requested email message fields were not hydrated")
+ })
+ }
+}
+
+/// An adaptively hydrated email content projection for Soup queries.
#[Object]
impl GraphqlSoupEmailMessage {
/// The unique message identifier.
async fn id(&self) -> ID {
- ID(self.0.db_id.to_string())
+ ID(self.parsed().db_id.to_string())
+ }
+
+ /// The identifier assigned by the email provider.
+ async fn provider_id(&self) -> async_graphql::Result<Option<&str>> {
+ Ok(self.full()?.provider_id.as_deref())
}
/// The identifier of the containing thread.
async fn thread_id(&self) -> ID {
- ID(self.0.thread_db_id.to_string())
+ ID(self.parsed().thread_db_id.to_string())
+ }
+
+ /// The identifier of the message this message replies to.
+ async fn replying_to_id(&self) -> async_graphql::Result<Option<ID>> {
+ Ok(self
+ .full()?
+ .replying_to_id
+ .map(|value| ID(value.to_string())))
}
/// The identifier of the linked email account.
async fn link_id(&self) -> ID {
- ID(self.0.link_id.to_string())
+ ID(self.parsed().link_id.to_string())
}
/// The message subject.
async fn subject(&self) -> Option<&str> {
- self.0.subject.as_deref()
+ self.parsed().subject.as_deref()
}
/// A short preview of the message content.
async fn snippet(&self) -> Option<&str> {
- self.0.snippet.as_deref()
+ self.parsed().snippet.as_deref()
}
/// The provider's internal timestamp in RFC 3339 format.
async fn internal_date_ts(&self) -> Option<String> {
- self.0.internal_date_ts.map(|value| value.to_rfc3339())
+ self.parsed()
+ .internal_date_ts
+ .map(|value| value.to_rfc3339())
}
/// The sent timestamp in RFC 3339 format.
async fn sent_at(&self) -> Option<String> {
- self.0.sent_at.map(|value| value.to_rfc3339())
+ self.parsed().sent_at.map(|value| value.to_rfc3339())
}
/// Whether the message has been read.
async fn is_read(&self) -> bool {
- self.0.is_read
+ self.parsed().is_read
}
/// Whether the message is starred.
async fn is_starred(&self) -> bool {
- self.0.is_starred
+ self.parsed().is_starred
}
/// Whether the message was sent by the linked account.
async fn is_sent(&self) -> bool {
- self.0.is_sent
+ self.parsed().is_sent
}
/// Whether the message is a draft.
async fn is_draft(&self) -> bool {
- self.0.is_draft
+ self.parsed().is_draft
}
/// Whether the message has attachments.
async fn has_attachments(&self) -> bool {
- self.0.has_attachments
+ self.parsed().has_attachments
+ }
+
+ /// When this draft is scheduled to be sent, in RFC 3339 format.
+ async fn scheduled_send_time(&self) -> async_graphql::Result<Option<String>> {
+ Ok(self
+ .full()?
+ .scheduled_send_time
+ .map(|value| value.to_rfc3339()))
}
/// The sender of the message.
async fn from(&self) -> Option<GraphqlSoupEmailContact> {
- self.0.from.clone().map(GraphqlSoupEmailContact)
+ self.parsed().from.clone().map(GraphqlSoupEmailContact)
}
/// The primary recipients of the message.
async fn to(&self) -> Vec<GraphqlSoupEmailContact> {
- self.0
+ self.parsed()
.to
.iter()
.cloned()
@@ -88,7 +144,7 @@ impl GraphqlSoupEmailMessage {
/// The carbon-copy recipients of the message.
async fn cc(&self) -> Vec<GraphqlSoupEmailContact> {
- self.0
+ self.parsed()
.cc
.iter()
.cloned()
@@ -98,7 +154,7 @@ impl GraphqlSoupEmailMessage {
/// The blind-carbon-copy recipients of the message.
async fn bcc(&self) -> Vec<GraphqlSoupEmailContact> {
- self.0
+ self.parsed()
.bcc
.iter()
.cloned()
@@ -108,7 +164,7 @@ impl GraphqlSoupEmailMessage {
/// Labels assigned to the message.
async fn labels(&self) -> Vec<GraphqlSoupEmailMessageLabel> {
- self.0
+ self.parsed()
.labels
.iter()
.cloned()
@@ -118,37 +174,170 @@ impl GraphqlSoupEmailMessage {
/// The parsed message body.
async fn body_parsed(&self) -> Option<&str> {
- self.0.body_parsed.as_deref()
+ self.parsed().body_parsed.as_deref()
}
/// The plain-text message body.
async fn body_text(&self) -> Option<&str> {
- self.0.body_text.as_deref()
+ self.parsed().body_text.as_deref()
}
/// The sanitized HTML message body.
async fn body_html_sanitized(&self) -> Option<&str> {
- self.0.body_html_sanitized.as_deref()
+ self.parsed().body_html_sanitized.as_deref()
}
/// The message body in Macro's rich-text format.
async fn body_macro(&self) -> Option<&str> {
- self.0.body_macro.as_deref()
+ self.parsed().body_macro.as_deref()
}
/// The message body with quoted replies removed.
async fn body_replyless(&self) -> Option<&str> {
- self.0.body_replyless.as_deref()
+ self.parsed().body_replyless.as_deref()
+ }
+
+ /// Provider-hosted attachments on the message.
+ async fn attachments(&self) -> async_graphql::Result<Vec<GraphqlSoupEmailMessageAttachment>> {
+ Ok(self
+ .full()?
+ .attachments
+ .iter()
+ .map(GraphqlSoupEmailMessageAttachment::new)
+ .collect())
+ }
+
+ /// Uploaded attachments belonging to a draft message.
+ async fn attachments_draft(
+ &self,
+ ) -> async_graphql::Result<Vec<GraphqlSoupEmailDraftAttachment>> {
+ Ok(self
+ .full()?
+ .attachments_draft
+ .iter()
+ .map(GraphqlSoupEmailDraftAttachment::new)
+ .collect())
+ }
+
+ /// Forwarded provider attachments belonging to a draft message.
+ async fn attachments_forwarded(
+ &self,
+ ) -> async_graphql::Result<Vec<GraphqlSoupEmailForwardedAttachment>> {
+ Ok(self
+ .full()?
+ .attachments_forwarded
+ .iter()
+ .map(GraphqlSoupEmailForwardedAttachment::new)
+ .collect())
}
/// The creation timestamp in RFC 3339 format.
async fn created_at(&self) -> String {
- self.0.created_at.to_rfc3339()
+ self.parsed().created_at.to_rfc3339()
}
/// The last-updated timestamp in RFC 3339 format.
async fn updated_at(&self) -> String {
- self.0.updated_at.to_rfc3339()
+ self.parsed().updated_at.to_rfc3339()
+ }
+}
+
+/// A provider-hosted attachment embedded in an email message.
+#[derive(SimpleObject)]
+pub struct GraphqlSoupEmailMessageAttachment {
+ /// The attachment's canonical database identifier.
+ id: ID,
+ /// The attachment identifier assigned by the email provider.
+ provider_id: Option<String>,
+ /// The original filename.
+ filename: Option<String>,
+ /// The MIME type.
+ mime_type: Option<String>,
+ /// The attachment size in bytes.
+ size_bytes: Option<i64>,
+ /// The corresponding static-file-service identifier, when uploaded.
+ sfs_id: Option<ID>,
+ /// The content identifier used by inline attachments.
+ content_id: Option<String>,
+}
+
+impl GraphqlSoupEmailMessageAttachment {
+ fn new(value: &MessageAttachment) -> Self {
+ Self {
+ id: ID(value.db_id.to_string()),
+ provider_id: value.provider_id.clone(),
+ filename: value.filename.clone(),
+ mime_type: value.mime_type.clone(),
+ size_bytes: value.size_bytes,
+ sfs_id: value.sfs_id.map(|id| ID(id.to_string())),
+ content_id: value.content_id.clone(),
+ }
+ }
+}
+
+/// An uploaded attachment embedded in a draft email message.
+#[derive(SimpleObject)]
+pub struct GraphqlSoupEmailDraftAttachment {
+ /// The attachment's canonical identifier.
+ id: ID,
+ /// The draft message identifier.
+ draft_id: ID,
+ /// The original filename.
+ file_name: String,
+ /// The MIME type.
+ content_type: String,
+ /// The SHA-256 content digest.
+ sha: String,
+ /// The attachment size in bytes.
+ size: i32,
+ /// The storage key containing the uploaded attachment.
+ s3_key: String,
+}
+
+impl GraphqlSoupEmailDraftAttachment {
+ fn new(value: &AttachmentDraft) -> Self {
+ Self {
+ id: ID(value.id.to_string()),
+ draft_id: ID(value.draft_id.to_string()),
+ file_name: value.file_name.clone(),
+ content_type: value.content_type.clone(),
+ sha: value.sha.clone(),
+ size: value.size,
+ s3_key: value.s3_key.clone(),
+ }
+ }
+}
+
+/// A forwarded provider attachment embedded in a draft email message.
+#[derive(SimpleObject)]
+pub struct GraphqlSoupEmailForwardedAttachment {
+ /// The original attachment identifier.
+ attachment_id: ID,
+ /// The draft message identifier.
+ draft_id: ID,
+ /// The attachment identifier assigned by the email provider.
+ provider_attachment_id: Option<String>,
+ /// The provider identifier of the original message.
+ message_provider_id: String,
+ /// The original filename.
+ filename: Option<String>,
+ /// The MIME type.
+ mime_type: Option<String>,
+ /// The attachment size in bytes.
+ size_bytes: Option<i64>,
+}
+
+impl GraphqlSoupEmailForwardedAttachment {
+ fn new(value: &AttachmentForwarded) -> Self {
+ Self {
+ attachment_id: ID(value.attachment_id.to_string()),
+ draft_id: ID(value.draft_id.to_string()),
+ provider_attachment_id: value.provider_attachment_id.clone(),
+ message_provider_id: value.message_provider_id.clone(),
+ filename: value.filename.clone(),
+ mime_type: value.mime_type.clone(),
+ size_bytes: value.size_bytes,
+ }
}
}
@@ -191,7 +380,7 @@ impl GraphqlSoupEmailMessageLabel {
}
}
-/// Load a paginated parsed-message page for an email thread.
+/// Load a paginated adaptively hydrated message page for an email thread.
pub async fn load_email_messages<R>(
ctx: &Context<'_>,
key: EmailContentKey,
@@ -217,12 +406,13 @@ pub async fn load_latest_email_message<R>(
where
R: SoupEmailContentEdgeReader,
{
- Ok(
- load_email_messages::<R>(ctx, EmailContentKey::latest(thread_id))
- .await?
- .into_iter()
- .next(),
- )
+ let key = if email_message_selection_requires_full_payload(ctx) {
+ EmailContentKey::latest_full(thread_id)
+ } else {
+ EmailContentKey::latest(thread_id)
+ };
+
+ Ok(load_email_messages::<R>(ctx, key).await?.into_iter().next())
}
#[cfg(test)]
@@ -269,7 +459,12 @@ mod tests {
keys: Vec<EmailContentKey>,
) -> HashMap<EmailContentKey, EmailContentLoad> {
keys.into_iter()
- .map(|key| (key, EmailContentLoad::Found(vec![message(key.thread_id)])))
+ .map(|key| {
+ (
+ key,
+ EmailContentLoad::Found(vec![message(key.thread_id).into()]),
+ )
+ })
.collect()
}
}
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index c0bfe7a794..6af2fed80c 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -2761,6 +2761,74 @@ type GraphqlSoupEmailContact {
photoUrl: String
}
+"""
+An uploaded attachment embedded in a draft email message.
+"""
+type GraphqlSoupEmailDraftAttachment {
+ """
+ The attachment's canonical identifier.
+ """
+ id: ID!
+ """
+ The draft message identifier.
+ """
+ draftId: ID!
+ """
+ The original filename.
+ """
+ fileName: String!
+ """
+ The MIME type.
+ """
+ contentType: String!
+ """
+ The SHA-256 content digest.
+ """
+ sha: String!
+ """
+ The attachment size in bytes.
+ """
+ size: Int!
+ """
+ The storage key containing the uploaded attachment.
+ """
+ s3Key: String!
+}
+
+"""
+A forwarded provider attachment embedded in a draft email message.
+"""
+type GraphqlSoupEmailForwardedAttachment {
+ """
+ The original attachment identifier.
+ """
+ attachmentId: ID!
+ """
+ The draft message identifier.
+ """
+ draftId: ID!
+ """
+ The attachment identifier assigned by the email provider.
+ """
+ providerAttachmentId: String
+ """
+ The provider identifier of the original message.
+ """
+ messageProviderId: String!
+ """
+ The original filename.
+ """
+ filename: String
+ """
+ The MIME type.
+ """
+ mimeType: String
+ """
+ The attachment size in bytes.
+ """
+ sizeBytes: Int
+}
+
"""
Canonical normalized GraphQL email label used by both email threads and
the authenticated user's label catalog.
@@ -2801,7 +2869,7 @@ type GraphqlSoupEmailLabel {
}
"""
-A lightweight email content projection for Soup queries.
+An adaptively hydrated email content projection for Soup queries.
"""
type GraphqlSoupEmailMessage {
"""
@@ -2809,10 +2877,18 @@ type GraphqlSoupEmailMessage {
"""
id: ID!
"""
+ The identifier assigned by the email provider.
+ """
+ providerId: String
+ """
The identifier of the containing thread.
"""
threadId: ID!
"""
+ The identifier of the message this message replies to.
+ """
+ replyingToId: ID
+ """
The identifier of the linked email account.
"""
linkId: ID!
@@ -2853,6 +2929,10 @@ type GraphqlSoupEmailMessage {
"""
hasAttachments: Boolean!
"""
+ When this draft is scheduled to be sent, in RFC 3339 format.
+ """
+ scheduledSendTime: String
+ """
The sender of the message.
"""
from: GraphqlSoupEmailContact
@@ -2893,6 +2973,18 @@ type GraphqlSoupEmailMessage {
"""
bodyReplyless: String
"""
+ Provider-hosted attachments on the message.
+ """
+ attachments: [GraphqlSoupEmailMessageAttachment!]!
+ """
+ Uploaded attachments belonging to a draft message.
+ """
+ attachmentsDraft: [GraphqlSoupEmailDraftAttachment!]!
+ """
+ Forwarded provider attachments belonging to a draft message.
+ """
+ attachmentsForwarded: [GraphqlSoupEmailForwardedAttachment!]!
+ """
The creation timestamp in RFC 3339 format.
"""
createdAt: String!
@@ -2902,6 +2994,40 @@ type GraphqlSoupEmailMessage {
updatedAt: String!
}
+"""
+A provider-hosted attachment embedded in an email message.
+"""
+type GraphqlSoupEmailMessageAttachment {
+ """
+ The attachment's canonical database identifier.
+ """
+ id: ID!
+ """
+ The attachment identifier assigned by the email provider.
+ """
+ providerId: String
+ """
+ The original filename.
+ """
+ filename: String
+ """
+ The MIME type.
+ """
+ mimeType: String
+ """
+ The attachment size in bytes.
+ """
+ sizeBytes: Int
+ """
+ The corresponding static-file-service identifier, when uploaded.
+ """
+ sfsId: ID
+ """
+ The content identifier used by inline attachments.
+ """
+ contentId: String
+}
+
"""
A lightweight label embedded in an email message.
"""