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.

17.0 KB
Raw Blame
use crate::{
    Result, delegate_methods,
    search::{
        builder::{SearchQueryBuilder, SearchQueryConfig},
        properties::build_tag_filter,
        utils::should_wildcard_field_query_builder,
    },
};

use models_opensearch::OpenSearchEntityType;
use opensearch_query_builder::{
    BoolQuery, BoolQueryBuilder, QueryType, SimpleQueryStringQuery, WildcardQuery,
};

pub(crate) struct EmailSearchConfig;

impl SearchQueryConfig for EmailSearchConfig {
    const USER_ID_KEY: Option<&'static str> = Some("user_id");
    const TITLE_KEY: &'static str = "subject";
    const ENTITY_INDEX: OpenSearchEntityType = OpenSearchEntityType::Emails;
}

/// Email-address fields matched explicitly, never as a character prefix.
/// The raw keyword-indexed addresses plus their `.parts` sub-fields, which
/// the `email_parts` analyzer splits into positioned segment tokens
/// (`[email protected]` indexes `jane`, `doe`, `mail`, `foo`, `com`).
/// A bare word matches only a whole segment, so `ali` won't match
/// `[email protected]` and `immipart` won't match `immipartner.com`.
/// Dotted terms like `foo.com` are quoted into phrases and match any
/// in-order adjacent run of segments.
const EMAIL_KEYWORD_FIELDS: &[&str] = &[
    "sender",
    "reply_to",
    "recipients",
    "cc",
    "bcc",
    "sender.parts",
    "reply_to.parts",
    "recipients.parts",
    "cc.parts",
    "bcc.parts",
];

/// Domain Macro's own notification/digest emails are sent from. Those are
/// never signal, mirroring the Postgres `is_signal` heuristic. Kept in sync
/// with `email_utils::MACRO_NOTIFICATION_SENDER_DOMAIN`, which is not imported
/// so this crate stays free of the email HTML tooling that crate pulls in.
const MACRO_NOTIFICATION_SENDER_DOMAIN: &str = "notification.macro.com";

/// Matches messages whose `sender` is any address at
/// [`MACRO_NOTIFICATION_SENDER_DOMAIN`].
fn macro_notification_sender_query<'a>() -> QueryType<'a> {
    QueryType::WildCard(WildcardQuery::new(
        "sender",
        format!("*@{MACRO_NOTIFICATION_SENDER_DOMAIN}"),
        true,
        None,
    ))
}

/// Text-analyzed fields. Matched as a prefix so `scri` matches `script`.
const EMAIL_TEXT_FIELDS: &[&str] = &[
    "subject",
    "content",
    "sender_name",
    "recipient_names",
    "cc_names",
    "bcc_names",
];

/// Builds the simple_query_string over the email-address fields.
/// Single-word terms become `(term | term@*)` — an exact segment-token match
/// on the `.parts` sub-fields OR an exact-local-part match on the raw
/// address. The `term@*` pattern is redundant with `.parts` once the index
/// carries the sub-fields but keeps the query compatible with an index that
/// predates them. This deliberately does NOT use a trailing `*` on the bare
/// term, so partial segments don't leak across addresses (e.g. `ali` won't
/// match `[email protected]` via this group).
/// Terms containing `@`, `.`, or spaces (quoted phrases from
/// `split_search_terms`) are wrapped in quotes to force phrase matching. On
/// the `.parts` sub-fields the `email_parts` analyzer splits such terms into
/// segment tokens, so the phrase requires an in-order adjacent run —
/// `mail.foo.com`, `foo.com`, and full addresses all match `[email protected]`,
/// but reordered or gapped segments don't. Without the quotes,
/// `default_operator: "AND"` would match each segment independently anywhere
/// in the field.
/// The email pattern is lowercased because email addresses are case-insensitive.
/// Terms are ANDed together with `+`.
fn build_keyword_query_string(terms: &[String]) -> String {
    terms
        .iter()
        .map(|term| {
            if term.contains('@') || term.contains('.') || term.contains(' ') {
                format!("\"{}\"", term)
            } else {
                format!("({} | {}@*)", term, term.to_lowercase())
            }
        })
        .collect::<Vec<_>>()
        .join(" + ")
}

/// Minimum prefix length before we emit a `term*` wildcard. Shorter prefixes
/// expand to too many unique tokens in the index and risk blowing past
/// `max_clause_count`. Under this threshold we fall back to exact token match.
const MIN_PREFIX_LEN: usize = 3;

/// Builds the simple_query_string over the text-analyzed fields.
/// Single-word terms become `term*` so a prefix like `scri` matches the
/// token `script` in subject/content/display-name fields. Terms shorter than
/// `MIN_PREFIX_LEN` fall back to a grouped exact-token match to keep term
/// expansion bounded. In `exact` match mode the prefix wildcard is dropped so
/// every single-word term is an exact-token match. Multi-word terms (quoted
/// phrases from `split_search_terms`) and `@`-containing terms are wrapped in
/// quotes to
/// force phrase matching — otherwise `default_operator: "AND"` would turn
/// `(reply test)` into `reply AND test` and match each token independently
/// anywhere in the field instead of as an adjacent phrase.
fn build_text_query_string(terms: &[String], match_type: &str) -> String {
    let exact = match_type == "exact";
    terms
        .iter()
        .map(|term| {
            if term.contains('@') || term.contains(' ') {
                format!("\"{}\"", term)
            } else if exact || term.chars().count() < MIN_PREFIX_LEN {
                format!("({})", term)
            } else {
                format!("{}*", term)
            }
        })
        .collect::<Vec<_>>()
        .join(" + ")
}

pub(crate) struct EmailQueryBuilder {
    inner: SearchQueryBuilder<EmailSearchConfig>,
    /// link ids to query over
    link_ids: Vec<String>,
    /// The sender of the email message
    sender: Vec<String>,
    /// The cc of the email message
    cc: Vec<String>,
    /// The bcc of the email message
    bcc: Vec<String>,
    /// The recipients of the email message
    recipients: Vec<String>,
    /// Labels to include (emails must have at least one)
    include_labels: Vec<String>,
    /// Labels to exclude (emails must not have any)
    exclude_labels: Vec<String>,
    /// Filter by importance. All filters (importance, include_labels, exclude_labels) are
    /// ANDed together. Contradictory combinations (e.g. importance=true with
    /// include_labels=["CATEGORY_PROMOTIONS"]) will return no results.
    importance: Option<bool>,
    /// When true, only search the subject field (for name-only search mode)
    subject_only: bool,
    /// Tag option ids the thread must carry (definition-agnostic)
    tag_option_ids: Vec<String>,
    /// Whether the thread must carry every tag option id instead of any
    match_all_tags: bool,
}

impl EmailQueryBuilder {
    pub fn new(terms: Vec<String>) -> Self {
        Self {
            inner: SearchQueryBuilder::new(terms),
            link_ids: Vec::new(),
            sender: Vec::new(),
            cc: Vec::new(),
            bcc: Vec::new(),
            recipients: Vec::new(),
            include_labels: Vec::new(),
            exclude_labels: Vec::new(),
            importance: None,
            subject_only: false,
            tag_option_ids: Vec::new(),
            match_all_tags: false,
        }
    }

    // Copy function signature from SearchQueryBuilder
    delegate_methods! {
        fn match_type(match_type: &str) -> Self;
        fn page(page: u32) -> Self;
        fn page_size(page_size: u32) -> Self;
        fn user_id(user_id: &str) -> Self;
        fn user_ids(user_ids: Vec<String>) -> Self;
        fn collapse(collapse: bool) -> Self;
        fn ids(ids: Vec<String>) -> Self;
        fn ids_only(ids_only: bool) -> Self;
    }

    pub fn link_ids(mut self, link_ids: Vec<String>) -> Self {
        self.link_ids = link_ids;
        self
    }

    pub fn sender(mut self, sender: Vec<String>) -> Self {
        self.sender = sender;
        self
    }

    pub fn cc(mut self, cc: Vec<String>) -> Self {
        self.cc = cc;
        self
    }

    pub fn bcc(mut self, bcc: Vec<String>) -> Self {
        self.bcc = bcc;
        self
    }

    pub fn recipients(mut self, recipients: Vec<String>) -> Self {
        self.recipients = recipients;
        self
    }

    pub fn include_labels(mut self, include_labels: Vec<String>) -> Self {
        self.include_labels = include_labels;
        self
    }

    pub fn exclude_labels(mut self, exclude_labels: Vec<String>) -> Self {
        self.exclude_labels = exclude_labels;
        self
    }

    pub fn importance(mut self, importance: Option<bool>) -> Self {
        self.importance = importance;
        self
    }

    pub fn subject_only(mut self, subject_only: bool) -> Self {
        self.subject_only = subject_only;
        self
    }

    pub fn tag_option_ids(mut self, tag_option_ids: Vec<String>) -> Self {
        self.tag_option_ids = tag_option_ids;
        self
    }

    pub fn match_all_tags(mut self, match_all_tags: bool) -> Self {
        self.match_all_tags = match_all_tags;
        self
    }

    pub fn build_bool_query<'a>(&'a self) -> Result<BoolQueryBuilder<'a>> {
        let mut content_bool_query = self.inner.build_content_bool_query()?;

        // In subject_only mode (name search), replace with a match on TITLE_KEY (subject).
        // Otherwise replace with simple_query_string across all email fields.
        if self.subject_only {
            let title_query = self.inner.build_title_term_query()?;
            let mut inner = BoolQueryBuilder::new();
            inner.minimum_should_match(1);
            inner.should(title_query);
            content_bool_query.set_must(inner.build().into());
        } else {
            let keyword_sqs = SimpleQueryStringQuery::new(
                build_keyword_query_string(&self.inner.terms),
                EMAIL_KEYWORD_FIELDS.iter().copied(),
            )
            .default_operator("AND");

            let text_sqs = SimpleQueryStringQuery::new(
                build_text_query_string(&self.inner.terms, &self.inner.match_type),
                EMAIL_TEXT_FIELDS.iter().copied(),
            )
            .default_operator("AND");

            let mut combined = BoolQueryBuilder::new();
            combined.minimum_should_match(1);
            combined.should(keyword_sqs.into());
            combined.should(text_sqs.into());
            content_bool_query.set_must(combined.build().into());
        }

        // CUSTOM ATTRIBUTES SECTION
        // If link_ids are provided, add them to the query
        if !self.link_ids.is_empty() {
            content_bool_query.filter(QueryType::terms("link_id", self.link_ids.clone()));
        }

        if !self.sender.is_empty() {
            // Create new query for senders
            let senders_query = should_wildcard_field_query_builder("sender", &self.sender);
            content_bool_query.filter(senders_query);
        }

        if !self.cc.is_empty() {
            let ccs_query = should_wildcard_field_query_builder("cc", &self.cc);
            content_bool_query.filter(ccs_query);
        }

        if !self.bcc.is_empty() {
            // Create new query for bccs
            let bccs_query = should_wildcard_field_query_builder("bcc", &self.bcc);
            content_bool_query.filter(bccs_query);
        }

        if !self.recipients.is_empty() {
            let recipients_query =
                should_wildcard_field_query_builder("recipients", &self.recipients);
            content_bool_query.filter(recipients_query);
        }

        if !self.include_labels.is_empty() {
            content_bool_query.filter(QueryType::terms("labels", self.include_labels.clone()));
        }

        // Tag filter: nested clause(s) matching the option ids in
        // `properties.values`. Thread-level properties are denormalized onto
        // every message doc, so filtering per doc filters the thread.
        if let Some(nested) = build_tag_filter(&self.tag_option_ids, self.match_all_tags) {
            content_bool_query.filter(nested);
        }

        for label in &self.exclude_labels {
            content_bool_query.must_not(QueryType::term("labels", label.clone()));
        }

        // Importance filter. Source of truth for the label logic is in
        // email/src/outbound/email_pg_repo/dynamic.rs (EmailLiteral::Importance).
        // Macro's own notification emails are always noise on top of that.
        match self.importance {
            Some(true) => {
                // Exclude emails that have depriority labels UNLESS they also have a priority label.
                let importance_exclude = BoolQuery::new()
                    .filter(QueryType::terms(
                        "labels",
                        [
                            "CATEGORY_UPDATES",
                            "CATEGORY_PROMOTIONS",
                            "CATEGORY_SOCIAL",
                            "CATEGORY_FORUMS",
                        ],
                    ))
                    .must_not(QueryType::terms(
                        "labels",
                        ["CATEGORY_PERSONAL", "SENT", "DRAFT"],
                    ));
                content_bool_query.must_not(QueryType::Bool(importance_exclude));
                content_bool_query.must_not(macro_notification_sender_query());
            }
            Some(false) => {
                // Only show deprioritized emails: must have a depriority label
                // AND must not have a priority label, or come from Macro's
                // own notification sender.
                let depriority_filter = BoolQuery::new()
                    .filter(QueryType::terms(
                        "labels",
                        [
                            "CATEGORY_UPDATES",
                            "CATEGORY_PROMOTIONS",
                            "CATEGORY_SOCIAL",
                            "CATEGORY_FORUMS",
                        ],
                    ))
                    .must_not(QueryType::terms(
                        "labels",
                        ["CATEGORY_PERSONAL", "SENT", "DRAFT"],
                    ));
                let noise_filter = BoolQuery::new()
                    .should(QueryType::Bool(depriority_filter))
                    .should(macro_notification_sender_query())
                    .minimum_should_match(1);
                content_bool_query.filter(QueryType::Bool(noise_filter));
            }
            None => {}
        }
        // END CUSTOM ATTRIBUTES SECTION

        Ok(content_bool_query)
    }
}

#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct EmailIndex {
    /// The id of the email thread
    pub entity_id: uuid::Uuid,
    /// The id of the email message
    pub message_id: uuid::Uuid,
    /// The sender of the email message
    pub sender: String,
    /// The display name of the sender
    #[serde(default)]
    pub sender_name: Option<String>,
    /// The reply-to address of the email message
    #[serde(default)]
    pub reply_to: Option<String>,
    /// The recipients of the email message
    pub recipients: Vec<String>,
    /// The display names of the recipients
    #[serde(default)]
    pub recipient_names: Vec<String>,
    /// The cc of the email message
    pub cc: Vec<String>,
    /// The display names of the cc contacts
    #[serde(default)]
    pub cc_names: Vec<String>,
    /// The bcc of the email message
    pub bcc: Vec<String>,
    /// The display names of the bcc contacts
    #[serde(default)]
    pub bcc_names: Vec<String>,
    /// The labels of the email message
    pub labels: Vec<String>,
    /// The link id of the email message
    pub link_id: String,
    /// The user id of the email message
    pub user_id: String,
    /// The subject of the email message
    pub subject: Option<String>,
    /// The sent at time of the email message, in milliseconds
    #[serde(default)]
    pub sent_at_millis: Option<i64>,
}

pub struct EmailSearchArgs {
    pub terms: Vec<String>,
    pub user_id: String,
    pub user_ids: Vec<String>,
    pub thread_ids: Vec<String>,
    pub link_ids: Vec<String>,
    pub sender: Vec<String>,
    pub cc: Vec<String>,
    pub bcc: Vec<String>,
    pub recipients: Vec<String>,
    pub include_labels: Vec<String>,
    pub exclude_labels: Vec<String>,
    pub importance: Option<bool>,
    pub page: u32,
    pub page_size: u32,
    pub match_type: String,
    pub collapse: bool,
    pub ids_only: bool,
    pub subject_only: bool,
    pub tag_option_ids: Vec<String>,
    pub match_all_tags: bool,
}

impl From<EmailSearchArgs> for EmailQueryBuilder {
    fn from(args: EmailSearchArgs) -> Self {
        EmailQueryBuilder::new(args.terms)
            .match_type(&args.match_type)
            .page_size(args.page_size)
            .page(args.page)
            .user_id(&args.user_id)
            .user_ids(args.user_ids)
            .ids(args.thread_ids)
            .link_ids(args.link_ids)
            .sender(args.sender)
            .cc(args.cc)
            .bcc(args.bcc)
            .recipients(args.recipients)
            .include_labels(args.include_labels)
            .exclude_labels(args.exclude_labels)
            .importance(args.importance)
            .collapse(args.collapse)
            .ids_only(args.ids_only)
            .subject_only(args.subject_only)
            .tag_option_ids(args.tag_option_ids)
            .match_all_tags(args.match_all_tags)
    }
}

#[cfg(test)]
mod test;