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
use crate::domain::{
models::{
Attachment, AttachmentDraft, AttachmentForwarded, Contact, ContactInfo, DraftDeletion,
EmailErr, EmailFilter, EmailInboxDetails, EmailThreadMailProjection, EmailThreadMetadata,
EmailThreadPreview, Label, Link, LinkLabel, MessageAttachment, MessageLabel, MessageRow,
MessageTimestamps, ParsedAddresses, PreviewCursorQuery, ResolvedDraftInput,
SettledDraftIds, SimpleMessage, SimpleMessageInfo, StagedLabelChange, ThreadRow,
UpsertEmailFilterInput, UpsertedContacts, UserProvider,
},
ports::{
DraftAttachmentRepo, EmailRepo, EmailUserRepo, LinkEmailSettings, RecipientsByMessageId,
},
};
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
use std::collections::HashMap;
use uuid::Uuid;
#[cfg(feature = "mailbox")]
mod attachment_access;
mod attachment_cleanup;
mod client_id_mapping;
mod contact;
mod db_types;
mod draft;
mod draft_attachments;
mod draft_resolution;
#[cfg(feature = "mailbox")]
mod draft_transfer;
mod dynamic;
mod email_filter;
mod followup;
mod label;
mod link;
mod mailbox_action;
mod message;
#[cfg(feature = "mailbox")]
mod message_source;
mod preview;
mod preview_views;
mod project;
mod scheduled;
mod send_attempt;
pub(super) mod sender_policy;
mod settings;
mod thread;
#[cfg(test)]
mod test;
#[derive(Clone)]
pub struct EmailPgRepo {
pool: PgPool,
}
impl EmailPgRepo {
pub fn new(pool: PgPool) -> Self {
EmailPgRepo { pool }
}
pub async fn link_by_fusionauth_email_provider(
&self,
fusionauth_user_id: &str,
email_address: &str,
provider: UserProvider,
) -> Result<Option<Link>, sqlx::Error> {
link::link_by_fusionauth_email_provider(
&self.pool,
fusionauth_user_id,
email_address,
provider,
)
.await
}
}
impl EmailUserRepo for EmailPgRepo {
async fn user_sender_filters(&self, link_id: Uuid) -> Result<Vec<EmailFilter>, EmailErr> {
email_filter::list_email_filters(&self.pool, link_id)
.await
.map_err(|error| EmailErr::RepoErr(error.into()))
}
async fn user_accessible_inboxes(
&self,
macro_id: MacroUserIdStr<'static>,
) -> Result<Vec<Link>, EmailErr> {
link::inboxes_for_macro_id(&self.pool, macro_id)
.await
.map_err(|error| EmailErr::RepoErr(error.into()))
}
async fn user_labels_for_link(&self, link_id: Uuid) -> Result<Vec<LinkLabel>, EmailErr> {
label::list_labels_by_link_id(&self.pool, link_id)
.await
.map_err(|error| EmailErr::RepoErr(error.into()))
}
async fn user_inbox_details(
&self,
macro_id: MacroUserIdStr<'static>,
) -> Result<Vec<EmailInboxDetails>, EmailErr> {
link::inbox_details_for_macro_id(&self.pool, ¯o_id)
.await
.map_err(|error| EmailErr::RepoErr(error.into()))
}
}
impl EmailRepo for EmailPgRepo {
async fn redirected_thread_id(
&self,
thread_id: Uuid,
link_ids: &[Uuid],
) -> Result<Option<Uuid>, Self::Err> {
client_id_mapping::redirected_thread_id(&self.pool, thread_id, link_ids).await
}
async fn commit_sender_policy(
&self,
actor: &MacroUserIdStr<'_>,
link: Uuid,
sender: &str,
blocked: bool,
important: Option<bool>,
) -> Result<(), Self::Err> {
sender_policy::commit(&self.pool, actor, link, sender, blocked, important).await
}
async fn commit_message_resolution(
&self,
actor: &MacroUserIdStr<'_>,
plan: crate::domain::models::mailbox_operation::MessageResolutionPlan,
) -> Result<Uuid, EmailErr> {
draft_resolution::commit(&self.pool, actor, plan).await
}
async fn message_operation_facts(
&self,
ids: &[Uuid],
) -> Result<
HashMap<Uuid, crate::domain::models::mailbox_operation::MessageOperationFacts>,
Self::Err,
> {
draft::operation_facts(&self.pool, ids).await
}
async fn thread_mailbox_operations(
&self,
link: Uuid,
thread: Uuid,
) -> Result<Vec<crate::domain::models::mailbox_action::MailboxOperation>, Self::Err> {
mailbox_action::operations(&self.pool, link, thread).await
}
async fn mailbox_action_messages(
&self,
link_id: Uuid,
thread_id: Uuid,
) -> Result<Vec<crate::domain::models::mailbox_action::MailboxActionMessage>, Self::Err> {
mailbox_action::messages(&self.pool, link_id, thread_id).await
}
async fn enqueue_mailbox_action(
&self,
link_id: Uuid,
actor: MacroUserIdStr<'_>,
action: &crate::domain::models::mailbox_action::MailboxAction,
targets: &[crate::domain::models::mailbox_action::MailboxActionTarget],
) -> Result<Uuid, Self::Err> {
mailbox_action::enqueue(&self.pool, link_id, actor, action, targets).await
}
type Err = sqlx::Error;
async fn fetch_email_settings(&self, link_id: Uuid) -> Result<LinkEmailSettings, EmailErr> {
settings::fetch_email_settings(&self.pool, link_id)
.await
.map_err(|error| EmailErr::RepoErr(error.into()))
}
async fn previews_for_view_cursor(
&self,
query: PreviewCursorQuery,
user_id: MacroUserIdStr<'static>,
) -> Result<Vec<EmailThreadPreview>, Self::Err> {
preview::previews_for_view_cursor(&self.pool, query, user_id).await
}
async fn attachments_by_thread_ids(
&self,
thread_ids: &[Uuid],
) -> Result<Vec<Attachment>, Self::Err> {
preview::attachments_by_thread_ids(&self.pool, thread_ids).await
}
async fn contacts_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Contact>, Self::Err> {
preview::contacts_by_thread_ids(&self.pool, thread_ids).await
}
async fn labels_by_thread_ids(&self, thread_ids: &[Uuid]) -> Result<Vec<Label>, Self::Err> {
preview::labels_by_thread_ids(&self.pool, thread_ids).await
}
async fn link_by_fusionauth_and_macro_id(
&self,
fusionauth_user_id: &str,
macro_id: MacroUserIdStr<'_>,
provider: UserProvider,
) -> Result<Option<Link>, Self::Err> {
link::link_by_fusionauth_and_macro_id(&self.pool, fusionauth_user_id, macro_id, provider)
.await
}
async fn owned_link_for_thread(
&self,
thread_id: Uuid,
macro_id: MacroUserIdStr<'_>,
) -> Result<Option<Link>, Self::Err> {
link::owned_link_for_thread(&self.pool, thread_id, macro_id).await
}
async fn inboxes_for_macro_id(
&self,
macro_id: MacroUserIdStr<'_>,
) -> Result<Vec<Link>, Self::Err> {
link::inboxes_for_macro_id(&self.pool, macro_id).await
}
async fn thread_by_id(&self, thread_id: Uuid) -> Result<Option<ThreadRow>, Self::Err> {
thread::thread_by_id(&self.pool, thread_id).await
}
async fn thread_metadata_by_ids(
&self,
thread_ids: &[Uuid],
) -> Result<Vec<EmailThreadMetadata>, Self::Err> {
thread::thread_metadata_by_ids(&self.pool, thread_ids).await
}
async fn thread_mail_projections_by_ids(
&self,
viewer: MacroUserIdStr<'_>,
thread_ids: &[Uuid],
) -> Result<Vec<EmailThreadMailProjection>, Self::Err> {
thread::thread_mail_projections_by_ids(&self.pool, viewer, thread_ids).await
}
async fn messages_by_thread_id_paginated(
&self,
thread_id: Uuid,
offset: i64,
limit: i64,
) -> Result<Vec<MessageRow>, Self::Err> {
thread::messages_by_thread_id_paginated(&self.pool, thread_id, offset, limit).await
}
async fn latest_content_message_rows(
&self,
thread_ids: &[Uuid],
) -> Result<Vec<MessageRow>, Self::Err> {
thread::latest_content_message_rows(&self.pool, thread_ids).await
}
async fn cross_inbox_reply_drafts(
&self,
replying_to_ids: &[Uuid],
link_ids: &[Uuid],
exclude_thread_id: Uuid,
) -> Result<Vec<MessageRow>, Self::Err> {
thread::cross_inbox_reply_drafts(&self.pool, replying_to_ids, link_ids, exclude_thread_id)
.await
}
async fn senders_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, ContactInfo>, Self::Err> {
message::senders_by_message_ids(&self.pool, message_ids).await
}
async fn recipients_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<RecipientsByMessageId, Self::Err> {
message::recipients_by_message_ids(&self.pool, message_ids).await
}
async fn labels_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<MessageLabel>>, Self::Err> {
message::labels_by_message_ids(&self.pool, message_ids).await
}
async fn calendar_invitations_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<
HashMap<Uuid, Vec<crate::domain::models::calendar_invitation::CalendarInvitation>>,
Self::Err,
> {
crate::outbound::invitation_pg::load(&self.pool, message_ids).await
}
async fn attachments_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<MessageAttachment>>, Self::Err> {
message::attachments_by_message_ids(&self.pool, message_ids).await
}
async fn message_timestamps(
&self,
message_id: Uuid,
link_id: Uuid,
) -> Result<Option<MessageTimestamps>, Self::Err> {
message::message_timestamps(&self.pool, message_id, link_id).await
}
async fn draft_attachments_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<AttachmentDraft>>, Self::Err> {
message::draft_attachments_by_message_ids(&self.pool, message_ids).await
}
async fn forwarded_attachments_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, Vec<AttachmentForwarded>>, Self::Err> {
message::forwarded_attachments_by_message_ids(&self.pool, message_ids).await
}
async fn scheduled_sends_by_message_ids(
&self,
message_ids: &[Uuid],
) -> Result<HashMap<Uuid, crate::domain::models::ScheduledSend>, Self::Err> {
message::scheduled_sends_by_message_ids(&self.pool, message_ids).await
}
async fn get_simple_message(
&self,
message_id: Uuid,
link_ids: &[Uuid],
) -> Result<Option<SimpleMessageInfo>, Self::Err> {
message::get_simple_message(&self.pool, message_id, link_ids).await
}
async fn message_id_for_client_draft_id(
&self,
client_id: Uuid,
link_ids: &[Uuid],
) -> Result<Option<Uuid>, Self::Err> {
client_id_mapping::message_id_for_client_draft_id(&self.pool, client_id, link_ids).await
}
async fn thread_id_for_client_thread_id(
&self,
client_id: Uuid,
link_ids: &[Uuid],
) -> Result<Option<Uuid>, Self::Err> {
client_id_mapping::thread_id_for_client_thread_id(&self.pool, client_id, link_ids).await
}
async fn get_draft_replying_to(
&self,
link_id: Uuid,
replying_to_id: Uuid,
) -> Result<Option<SimpleMessageInfo>, Self::Err> {
message::get_draft_replying_to(&self.pool, link_id, replying_to_id).await
}
async fn delete_draft_message(
&self,
message_id: Uuid,
thread_db_id: Uuid,
link_ids: &[Uuid],
actor: Option<&str>,
expected_generation: i32,
) -> Result<Option<DraftDeletion>, Self::Err> {
message::delete_draft_message(
&self.pool,
message_id,
thread_db_id,
link_ids,
actor,
expected_generation,
)
.await
}
async fn upsert_contacts(
&self,
link_id: Uuid,
addresses: ParsedAddresses,
) -> Result<UpsertedContacts, Self::Err> {
contact::upsert_contacts(&self.pool, link_id, addresses).await
}
async fn insert_message(
&self,
input: &ResolvedDraftInput,
contacts: &UpsertedContacts,
link_id: Uuid,
new_thread: Option<ThreadRow>,
is_draft: bool,
) -> Result<Option<SettledDraftIds>, EmailErr> {
draft::insert_message(&self.pool, input, contacts, link_id, new_thread, is_draft).await
}
async fn get_label_by_id(
&self,
label_id: Uuid,
link_id: Uuid,
) -> Result<Option<LinkLabel>, Self::Err> {
label::get_label_by_id(&self.pool, label_id, link_id).await
}
async fn get_thread_label_messages(
&self,
thread_id: Uuid,
link_id: Uuid,
) -> Result<Vec<SimpleMessage>, Self::Err> {
label::get_thread_label_messages(&self.pool, thread_id, link_id).await
}
async fn insert_message_labels_batch(
&self,
message_ids: &[Uuid],
provider_label_id: &str,
link_id: Uuid,
) -> Result<(), Self::Err> {
label::insert_message_labels_batch(&self.pool, message_ids, provider_label_id, link_id)
.await
}
async fn delete_message_labels_batch(
&self,
message_ids: &[Uuid],
provider_label_id: &str,
link_id: Uuid,
) -> Result<(), Self::Err> {
label::delete_message_labels_batch(&self.pool, message_ids, provider_label_id, link_id)
.await
}
async fn stage_thread_label_change(
&self,
thread_id: Uuid,
link_id: Uuid,
provider_label_id: &str,
add: bool,
write_id: Uuid,
) -> Result<Option<StagedLabelChange>, Self::Err> {
label::stage_thread_label_change(
&self.pool,
thread_id,
link_id,
provider_label_id,
add,
write_id,
)
.await
}
async fn revert_staged_label_change(
&self,
thread_id: Uuid,
link_id: Uuid,
provider_label_id: &str,
add: bool,
write_id: Uuid,
provider_message_ids: &[Uuid],
local_message_ids: &[Uuid],
) -> Result<(), Self::Err> {
label::revert_staged_label_change(
&self.pool,
thread_id,
link_id,
provider_label_id,
add,
write_id,
provider_message_ids,
local_message_ids,
)
.await
}
async fn update_message_read_status_batch(
&self,
message_ids: &[Uuid],
link_id: Uuid,
is_read: bool,
) -> Result<(), Self::Err> {
label::update_message_read_status_batch(&self.pool, message_ids, link_id, is_read).await
}
async fn update_thread_read_status(
&self,
thread_id: Uuid,
link_id: Uuid,
is_read: bool,
) -> Result<(), Self::Err> {
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],
link_id: Uuid,
is_starred: bool,
) -> Result<(), Self::Err> {
label::update_message_starred_status_batch(&self.pool, message_ids, link_id, is_starred)
.await
}
async fn list_labels_by_link_id(&self, link_id: Uuid) -> Result<Vec<LinkLabel>, Self::Err> {
label::list_labels_by_link_id(&self.pool, link_id).await
}
async fn delete_scheduled_messages_batch(
&self,
message_ids: &[Uuid],
link_id: Uuid,
) -> Result<Vec<Uuid>, Self::Err> {
label::delete_scheduled_messages_batch(&self.pool, message_ids, link_id).await
}
async fn update_thread_project(
&self,
thread_id: Uuid,
project_id: Option<&str>,
) -> Result<bool, Self::Err> {
thread::update_thread_project(&self.pool, thread_id, project_id).await
}
async fn get_thread_project_id(&self, thread_id: Uuid) -> Result<Option<String>, Self::Err> {
thread::get_thread_project_id(&self.pool, thread_id).await
}
async fn touch_project_updated_at(&self, project_id: &str) -> Result<(), Self::Err> {
project::touch_project_updated_at(&self.pool, project_id).await
}
async fn upsert_email_filter(
&self,
link_id: Uuid,
input: UpsertEmailFilterInput,
) -> Result<EmailFilter, Self::Err> {
// One transaction: the override and the is_signal resync it feeds
// must land together, or a resync failure leaves stale flags.
let mut tx = self.pool.begin().await?;
let filter = if let Some(address) = &input.email_address {
email_filter::upsert_email_filter_by_address(
&mut tx,
link_id,
address,
input.is_important,
)
.await?
} else if let Some(domain) = &input.email_domain {
email_filter::upsert_email_filter_by_domain(
&mut tx,
link_id,
domain,
input.is_important,
)
.await?
} else {
unreachable!(
"UpsertEmailFilterInput must have either email_address or email_domain; validated by service layer"
)
};
email_filter::resync_signal_flags_for_sender(
&mut tx,
link_id,
filter.email_address.as_deref(),
filter.email_domain.as_deref(),
)
.await?;
tx.commit().await?;
Ok(filter)
}
async fn delete_email_filter(&self, filter_id: Uuid, link_id: Uuid) -> Result<bool, Self::Err> {
let mut tx = self.pool.begin().await?;
let deleted = email_filter::delete_email_filter(&mut tx, filter_id, link_id).await?;
if let Some(target) = &deleted {
email_filter::resync_signal_flags_for_sender(
&mut tx,
link_id,
target.email_address.as_deref(),
target.email_domain.as_deref(),
)
.await?;
}
tx.commit().await?;
Ok(deleted.is_some())
}
async fn list_email_filters(&self, link_id: Uuid) -> Result<Vec<EmailFilter>, Self::Err> {
email_filter::list_email_filters(&self.pool, link_id).await
}
}
impl DraftAttachmentRepo for EmailPgRepo {
type Err = sqlx::Error;
async fn insert_draft_attachment(
&self,
link_id: Uuid,
attachment: &AttachmentDraft,
) -> Result<(), Self::Err> {
message::insert_draft_attachment(&self.pool, link_id, attachment).await
}
}